diff --git a/guides/HKSV3Protocol.md b/guides/HKSV3Protocol.md index 4df8cff51..7223ec4a2 100644 --- a/guides/HKSV3Protocol.md +++ b/guides/HKSV3Protocol.md @@ -304,7 +304,7 @@ The second way has a catch, and it cost me a few days: **the timestamps have to 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. +**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. A recording's lead-up is the one exception: no view opens from it, and a view waits for the first live keyframe instead. #### When A Packet Is Lost @@ -636,6 +636,9 @@ That time is **not required** to be the moment the video was taken. A recording - A hub that timed out asked once more, 5 seconds after its close, while Motion Detected was still raised. After a second timeout it didn't ask again, and where motion had already cleared it didn't ask a second time at all. - A recording that starts late carries no video from before the motion. The hub judged it as usual, and its clip showed in the Home app's timeline and played. +**In HAP-NodeJS** a camera that can't keep its stream open states the recording mode `'onDemand'`. The library asks for its stream at the hub's open, and the recording +opens at the stream's first decodable keyframe. It carries the lead-up the plugin's stream brings, and nothing from before the open where the stream brings none. + 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 @@ -715,7 +718,7 @@ Each of these is answered 201. - 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. -**In HAP-NodeJS** a clip's media playlist states one target duration, in its opening form and its closing form: the longest segment the camera's recording can cut, which is its prebuffer plus ten seconds, 15 at the default. +**In HAP-NodeJS** a clip's media playlist states one target duration, in its opening form and its closing form: the longest segment the camera's recording can cut, which is its prebuffer plus ten seconds: 15 at the default prebuffer, and 10 for a camera that records on demand. The playlists are in appendix A. diff --git a/guides/UpgradingCameraPlugins.md b/guides/UpgradingCameraPlugins.md index df34a3ee0..f8acbd009 100644 --- a/guides/UpgradingCameraPlugins.md +++ b/guides/UpgradingCameraPlugins.md @@ -20,7 +20,7 @@ Moving a camera to the modern form means writing less code, not more. The librar - **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. +- **Recording.** No recording delegate, no prebuffer of your own, no fragments to cut. The library keeps the recent video, or for a camera that can't keep its stream open starts the stream when a hub asks, 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. @@ -85,16 +85,16 @@ Two things decide whether a camera can take 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. | +| 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 `sensorUUID` and `tierId` naming the tier recorded, `mode`, `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 @@ -112,7 +112,7 @@ const camera = new hap.CameraController({ 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: 4500, frameRate: 30, height: 2160, id: 1, quality: hap.CameraVideoQuality.HIGH, 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 }, ], @@ -125,8 +125,8 @@ const camera = new hap.CameraController({ - **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. +- **The recorded tier** is the one `recording` names by its `sensorUUID` and `tierId`. Leave them out and 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. A camera that records with a prebuffer keeps its recorded tier running whenever recording is allowed, marked or not, and a camera that records on demand runs it from a hub's open. - **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. @@ -148,7 +148,7 @@ This is the form every set of named constants takes from 2.4 on. A constant obje ### 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. +`tierDemandStarted` is called when a tier gains its first consumer, and the stream's `reason` says who asked: `'view'` when a viewer did, `'recording'` when a hub's recording did on a camera that records on demand, and `'keepRunning'` when nobody did and the library keeps the stream running. 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 = { @@ -163,7 +163,7 @@ const delegate: MultiTierStreamingDelegate = { ``` - **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. -- **State when your pictures were taken, if your source knows.** A `prft` box in front of a fragment states the wall clock of that fragment, and a recording is stamped from it. A stream that states its times carries one in front of every fragment. Without them the library stamps each picture with the moment it arrived, which is right for a live source. From ffmpeg that's `-write_prft wallclock`. Don't use `-write_prft pts`: it states the stream's own times as a date in 1970, and every recording is dated there. The library takes a stated time as it stands. Keeping that clock true is yours. +- **State when your pictures were taken, if your source knows.** A `prft` box in front of a fragment states the wall clock of that fragment, and a recording is stamped from it. A stream that states its times carries one in front of every fragment. Without them the library stamps each picture with the moment it arrived, which is right for a live source. From ffmpeg that's `-write_prft wallclock`. Don't use `-write_prft pts`: it states the stream's own times as a date in 1970, and every recording is dated there. The library dates a recording by a stated time as it stands. Keeping that clock true is yours. The library reads a stated time against its own clock for one thing only: to tell an on-demand recording's lead-up from live video, as [Recording](#recording) explains. A stream stated behind the computer's clock holds its live video back from the viewers of an on-demand recording's start for up to 10 seconds, and then until its next keyframe. - **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. @@ -253,19 +253,30 @@ if (device.hasSpeaker) { ### 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. +`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, and for a size no picture has. It tells you of each one through the `snapshot-refused` event, with its `cause` and the request's `reason`. 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. +The request carries `keyframe` when a running tier has one that isn't a recording's lead-up: 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. -- **Each recording is dated by when its video was taken**: the time your stream states, or each picture's arrival. Its clip stands there in the Home app's timeline, lead-up included, however long the upload takes. -- **`shouldRecord(start)`** lets you decline a recording. It's asked once, and must answer `true` or `false` on the spot. +In the modern form you build no recording and no clip. The library holds the recorded tier, hands a hub what it asks for, and uploads the clip when the hub says to keep it. `mode` says how the recorded tier's stream is supplied. + +- **`mode: 'prebuffered'`**, the default, keeps the recorded tier running while the user allows recording and holds its recent video, and each recording reaches back before the event. +- **`prebuffer`** is how far back each prebuffered recording reaches, in milliseconds: 5000 by default, from 1 to 30000. +- **`mode: 'onDemand'`** is for a camera that can't keep its stream open, such as a battery or a cloud camera. The library asks for the recorded tier's stream when a hub opens a recording, and keeps it while a recording is open or motion is detected. Each recording opens at the stream's first decodable keyframe and carries the lead-up your stream brings, if it brings any. A tier that's already running, for a viewer or under `keepRunning`, serves the recording at once. This mode takes no `prebuffer`. +- **A camera that keeps its own recent video can hand it over as lead-up.** Write lead-up only when `stream.reason` reads `'recording'`. State when each + fragment's pictures were taken in its `prft` box, which ffmpeg's `-write_prft wallclock` doesn't do for older video, because it states the moment each + fragment is written. Every fragment of the lead-up states its time, and a sound in a fragment that states no time is kept from viewers until the first + live picture if it's handed over within 10 seconds of the stream's first bytes. A recording takes no sound from a fragment before the one that brings + the stream's first keyframe, nor any sound timed before that keyframe. Write the lead-up and the live video as one stream whose decode + times rise from one into the other with no step past a second. Hand the whole lead-up over within 10 seconds of the stream's first bytes. A recording + that opens on a tier that's already running takes no lead-up. Lead-up written at any other start is shown to that start's viewers. +- **A camera that records on demand has about 11 seconds from a hub's open to its first picture**, as [HomeKit Cameras in iOS 27](HKSV3Protocol.md) explains. A start that can't bring its first picture in that time should fail rather than stay pending, because the library asks for the stream again a second after a failed start, and holds a start that hasn't settled for 30 seconds without asking for anything new. The library gives up a recording still waiting for its first keyframe 30 seconds after the hub's request, and a hub gives up sooner. +- **Each recording is dated by when its video was taken**: the time your stream states, or each picture's arrival. Its clip stands there in the Home app's timeline with its lead-up, a prebuffered camera's prebuffer or the lead-up an on-demand stream brings, however long the upload takes. +- **`shouldRecord(start)`** lets you decline a recording. It's asked once, and must answer `true` or `false` on the spot. On demand it's asked before the stream starts, and a declined recording wakes no camera. - **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. +- **`recording-started` and `recording-ended`** tell you of each recording. `recording-ended` carries how it ended and, where a hub closed it, the hub's reason. +- **A hub's close with the reason TIMEOUT** also raises a `recording-timed-out` problem of its own. ### Motion @@ -278,14 +289,14 @@ In the modern form you build no recording and no clip. While the user allows rec `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. +- **`'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 holds, the recorded tier while it's held 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. +- **Events** on the controller: `operating-mode-change`, `streaming-enabled-change`, `recording-started`, `recording-ended`, `live-view-started`, `live-view-ended` and `snapshot-refused`, 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. +- **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. A `stream-failed`, `recording-declined` or `recording-timed-out` problem also carries a `cause` you can branch on once you've narrowed it by `kind`, while the `sentence` stays words for a person to read. 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. diff --git a/src/accessories/ModernCamera_example.ts b/src/accessories/ModernCamera_example.ts index 2f32145bd..b3c7cd21c 100644 --- a/src/accessories/ModernCamera_example.ts +++ b/src/accessories/ModernCamera_example.ts @@ -8,7 +8,7 @@ * 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`. + * recording on demand and `strict`. */ import type { CameraSnapshotRequest, TierStream } from '../index.js' diff --git a/src/lib/Accessory.ts b/src/lib/Accessory.ts index 8d3058b54..f56c2b4da 100644 --- a/src/lib/Accessory.ts +++ b/src/lib/Accessory.ts @@ -88,7 +88,12 @@ 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 { + CHARACTERISTIC_TIMEOUT_AFTER_WARNING, + CHARACTERISTIC_TIMEOUT_WARNING, + extractHAPStatusFromError, + formatOutgoingCharacteristicValue, +} from './util/request-util.js' import * as uuid from './util/uuid.js' import { toShortForm } from './util/uuid.js' @@ -441,9 +446,9 @@ function loggableValue(characteristic: Characteristic, value: unknown): unknown */ export class Accessory extends EventEmitter { // Timeout in milliseconds until a characteristic warning is issued - private static readonly TIMEOUT_WARNING = 3000 + private static readonly TIMEOUT_WARNING = CHARACTERISTIC_TIMEOUT_WARNING // Timeout in milliseconds after `TIMEOUT_WARNING` until the operation on the characteristic is considered timed out. - private static readonly TIMEOUT_AFTER_WARNING = 6000 + private static readonly TIMEOUT_AFTER_WARNING = CHARACTERISTIC_TIMEOUT_AFTER_WARNING // NOTICE: when adding/changing properties, remember to possibly adjust the serialize/deserialize functions aid: Nullable = null // assigned by us in assignIDs() or by a Bridge @@ -1909,7 +1914,7 @@ export class Accessory extends EventEmitter { let timeout: NodeJS.Timeout | undefined = setTimeout(() => { warnMissing(true) - // after a total of 10s we no longer wait for a request to appear and just return status code timeout + // after a total of TIMEOUT_WARNING plus TIMEOUT_AFTER_WARNING we no longer wait for a request to appear and just return status code timeout timeout = setTimeout(() => { timeout = undefined diff --git a/src/lib/Advertiser.spec.ts b/src/lib/Advertiser.spec.ts index fbc4f5ff0..962cdd4e2 100644 --- a/src/lib/Advertiser.spec.ts +++ b/src/lib/Advertiser.spec.ts @@ -109,6 +109,28 @@ describe('CiaoAdvertiser destroy', () => { expect(destroyService).toHaveBeenCalledTimes(1) expect(shutdown).toHaveBeenCalledTimes(1) }) + + it('should release the shared responder when the destroy of its service rejects, and reject its own destroy with that failure', async () => { + const advertiser = new CiaoAdvertiser(accessoryInfo('AA:BB:CC:DD:EE:04', 'Destroy Test Four')) + const service = (advertiser as any).advertisedService + const failure = new Error('The service could not send its goodbye.') + const destroyService = vi.spyOn(service, 'destroy').mockRejectedValue(failure) + const shutdown = vi.spyOn((advertiser as any).responder, 'shutdown') + + try { + await expect(advertiser.destroy()).rejects.toBe(failure) + + expect(shutdown).toHaveBeenCalledTimes(1) + + await expect(advertiser.destroy()).rejects.toBe(failure) + + expect(destroyService).toHaveBeenCalledTimes(1) + expect(shutdown).toHaveBeenCalledTimes(1) + } finally { + destroyService.mockRestore() + await service.destroy() + } + }) }) describe('BonjourHAPAdvertiser', () => { diff --git a/src/lib/Advertiser.ts b/src/lib/Advertiser.ts index b24058113..e945c8885 100644 --- a/src/lib/Advertiser.ts +++ b/src/lib/Advertiser.ts @@ -167,9 +167,13 @@ export class CiaoAdvertiser extends EventEmitter implements Advertiser { private async destroyService(): Promise { // The responder is shared with every other advertiser created with the same options, and its shutdown() // only does something for the last one of them. So the service must send its goodbye on its own first. - await this.advertisedService.destroy() - await this.responder.shutdown() - this.removeAllListeners() + // A goodbye that fails still releases this advertiser's hold on the responder, and the failure still rejects the destroy. + try { + await this.advertisedService.destroy() + } finally { + await this.responder.shutdown() + this.removeAllListeners() + } } static createTxt(accessoryInfo: AccessoryInfo, setupHash: string): ServiceTxt { diff --git a/src/lib/Characteristic.spec.ts b/src/lib/Characteristic.spec.ts index d18724120..6badcef81 100644 --- a/src/lib/Characteristic.spec.ts +++ b/src/lib/Characteristic.spec.ts @@ -3227,6 +3227,44 @@ describe('transient characteristics', () => { await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') }) + // An unpaired writer is one a server in insecure mode lets through: alive until its close, and never authenticated. + it.each([ + { + before: (): void => undefined, + held: ['AQEB', '', 1], + writer: 'that is alive', + }, + { + before: (writer: HAPConnection): void => { + writer.emit(HAPConnectionEvent.CLOSED) + }, + held: ['', '', 0], + writer: 'that closed before its write', + }, + ])('holds a write\'s answer for an unpaired writer $writer as for a paired one, for its read alone and until its close', async ({ before, held }) => { + const characteristic = createTransientCharacteristic() + const unpaired = buildEmitterConnection('IPv6', { paired: false }) + const other = buildEmitterConnection() + characteristic.onSet(() => 'AQEB') + + before(unpaired) + await expect(characteristic.handleSetRequest('AQEC', unpaired)).resolves.toBe('AQEB') + + const kept = [ + await characteristic.handleGetRequest(unpaired), + await characteristic.handleGetRequest(other), + unpaired.listenerCount(HAPConnectionEvent.CLOSED), + ] + + unpaired.emit(HAPConnectionEvent.CLOSED) + + expect([ + kept, + await characteristic.handleGetRequest(unpaired), + unpaired.listenerCount(HAPConnectionEvent.CLOSED), + ]).toEqual([held, '', 0]) + }) + 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() diff --git a/src/lib/Characteristic.ts b/src/lib/Characteristic.ts index 7e1250506..a10c2f4a2 100644 --- a/src/lib/Characteristic.ts +++ b/src/lib/Characteristic.ts @@ -2991,9 +2991,9 @@ export class Characteristic extends EventEmitter { 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()) { + // A connection that is not alive 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.isAlive()) { this.releaseTransientAnswers(connection) return } diff --git a/src/lib/camera/MultiTierStreamManagement.spec.ts b/src/lib/camera/MultiTierStreamManagement.spec.ts index 8623fc78a..0a60a53a6 100644 --- a/src/lib/camera/MultiTierStreamManagement.spec.ts +++ b/src/lib/camera/MultiTierStreamManagement.spec.ts @@ -83,7 +83,8 @@ import { Accessory, AccessoryEventTypes, Categories, MDNSAdvertiser } from '../A import { Bridge } from '../Bridge.js' import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' import { CameraController, CameraControllerEvents } from '../controller/index.js' -import { HAPStatus } from '../HAPServer.js' +import { HDSProtocolError, HDSProtocolSpecificErrorReason } from '../datastream/index.js' +import { HAPHTTPCode, HAPStatus } from '../HAPServer.js' import { AccessoryInfo, PermissionTypes } from '../model/AccessoryInfo.js' import { Service, ServiceEventTypes } from '../Service.js' import { awaitEventOnce } from '../util/promise-utils.js' @@ -649,6 +650,18 @@ describe('multiTierStreamManagement', () => { await expect(readSetupEndpoints(service)).resolves.toBe('AgEC') }) + // An unpaired connection is one a server in insecure mode lets through: alive, and never authenticated. + it('serves a write from an unpaired connection that is alive, its read on that connection answering the write', async () => { + const { service } = harness() + const from = await endpoint() + const sessionIdentifier = crypto.randomUUID() + + expect(await prepare(service, buildEmitterConnection('IPv6', { paired: false }), from, sessionIdentifier)).toMatchObject({ + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier, + }) + }) + 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() @@ -2449,7 +2462,7 @@ describe('multiTierStreamManagement', () => { // 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()) + const raised = table.hold(soundTier, scriptedHolder(), 'recording') writeTierFrame(streamOf(delegate, 1), 'audio', { data: Buffer.alloc(60, 1), @@ -2479,7 +2492,7 @@ describe('multiTierStreamManagement', () => { const from = await endpoint() const connection = buildEmitterConnection() const answer = await streaming(service, connection, from, 2) - const other = table.hold(table.videoTiers.get(1)!, scriptedHolder()) + const other = table.hold(table.videoTiers.get(1)!, scriptedHolder(), 'recording') writeTierFrame(streamOf(delegate, 1), 'audio', { data: Buffer.alloc(60, 1), @@ -2514,7 +2527,7 @@ describe('multiTierStreamManagement', () => { 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()) + const other = table.hold(soundTier, scriptedHolder(), 'recording') await settle() streamOf(delegate, 1).fail('The sound encoder crashed.') @@ -2530,7 +2543,7 @@ describe('multiTierStreamManagement', () => { 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()) + const later = table.hold(soundTier, scriptedHolder(), 'recording') await settle() @@ -3439,7 +3452,7 @@ describe('multiTierStreamManagement', () => { // 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()) + table.hold(table.videoTiers.get(1)!, scriptedHolder(), 'recording') await settle() const stream = streamOf(delegate) @@ -5685,6 +5698,66 @@ describe('multiTierStreamManagement', () => { expect(plain.subarray(plain.length - unit.length).equals(unit)).toBe(true) expect(await command({ sessionIdentifier, command: RTPStreamingCommand.END })).toEqual({ sessionIdentifier, status: RTPStreamingStatus.SUCCESS }) }) + + /* A controller in insecure mode writes on a plain connection with the pincode in its Authorization header, as the insecure rows of the HAP server's + * suite send it: the server lets the write through, and the connection is alive and never authenticated. A successful write answers No Content, every + * status 0, and a successful read answers OK with no status, which is 0. + */ + it('serves a Setup Endpoints write and its read back on a plain connection to an accessory published in insecure mode, the pincode in its ' + + 'Authorization header', async () => { + const { 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, + }, true) + const [port] = await listening + + const client = new HAPHTTPClient('127.0.0.1', port) + await client.connect() + clients.push(client) + + const from = await endpoint() + const sessionIdentifier = crypto.randomUUID() + const aid = accessory.aid! + const iid = service.getCharacteristic(Characteristic.SetupEndpoints).iid! + const authorized = { + headers: { + authorization: accessoryInfo.pincode, + }, + } + const request = Buffer.from(JSON.stringify({ + characteristics: [ + { + aid, + iid, + value: setupRequest(from, sessionIdentifier), + }, + ], + })) + const written = await client.writeHTTPRequest('PUT', '/characteristics', request, authorized) + const read = await client.writeHTTPRequest('GET', `/characteristics?id=${aid}.${iid}`, undefined, authorized) + const { characteristics } = JSON.parse(read.body.toString()) as { characteristics: { status?: HAPStatus, value: string }[] } + + expect([ + written.statusCode, + read.statusCode, + characteristics.map(({ status = HAPStatus.SUCCESS }) => status), + decodeSetupEndpointsResponse(characteristics[0].value), + ]).toMatchObject([ + HAPHTTPCode.NO_CONTENT, + HAPHTTPCode.OK, + [HAPStatus.SUCCESS], + { + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier, + }, + ]) + }) }) describe('camera controller wiring', () => { @@ -6456,18 +6529,13 @@ describe('multiTierStreamManagement', () => { 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. + /* What every row reads once the camera has left service: each of its tiers ended, its recording cancelled, 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. The recording has sent its initialization segment alone, under the four-second target: a camera that leaves service by its accessory's + * path closes it to the hub as cancelled, and one whose source is stated away sends its segment in progress as it stands and then the end marker. + */ const ENDED = { alerts: [], - recording: [ - ['cancelled'], - { - data: Buffer.alloc(1), - isLast: true, - }, - ], registrations: [1, 1], session: RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, signal: true, @@ -6479,6 +6547,19 @@ describe('multiTierStreamManagement', () => { ], } + // How the recording ends, as its outcomes and what its packets end with: the close the recorder threw, naming its reason, or the last packet. + const CLOSED = [ + ['cancelled'], + HDSProtocolSpecificErrorReason.CANCELLED, + ] + const MARKED = [ + ['cancelled'], + { + data: Buffer.alloc(1), + isLast: true, + }, + ] + // The accessories a row publishes or bridges, destroyed after it. No server, record or context outlives its row. const accessories: Accessory[] = [] @@ -6501,6 +6582,8 @@ describe('multiTierStreamManagement', () => { readonly alerts: CameraProblem[] readonly answer: Prepared readonly base: number + // The reason of the close the recording's iterable threw as it ended, absent for one that ended without. + readonly closed: () => HDSProtocolSpecificErrorReason | undefined readonly connection: HAPConnection readonly delegate: ScriptedTierDelegate readonly ends: CameraRecordingEnd[] @@ -6571,12 +6654,12 @@ describe('multiTierStreamManagement', () => { } // 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. + // pending, and its first sensor's tier 1 recorded in the prebuffered mode at a prebuffer of 1 millisecond. 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 }, + recording: { prebuffer: 1 }, streaming: { delegate }, videoSensors: [ { @@ -6605,6 +6688,7 @@ describe('multiTierStreamManagement', () => { const { problems: alerts } = problemsOf(accessory.UUID) const ends: CameraRecordingEnd[] = [] const packets: RecordingPacket[] = [] + let thrown: unknown camera.on(CameraControllerEvents.RECORDING_ENDED, end => ends.push(end)) recordingManagement.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) @@ -6612,17 +6696,22 @@ describe('multiTierStreamManagement', () => { const path = await enter(accessory, camera) const recorded = streamOf(delegate, RECORDED_TIER) + // The buffer is ready once its second frame stands its prebuffer past the keyframe it opens on. recorded.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) - frames(recorded, 0, 1) + frames(recorded, 0, 2) const recording = recordingManagement.delegate.handleRecordingStreamRequest(1) void (async () => { - for await (const packet of recording) { - packets.push(packet) + try { + for await (const packet of recording) { + packets.push(packet) + } + } catch (error) { + thrown = error } })() - frames(recorded, 1, 45) + frames(recorded, 2, 45) const services = accessory.services.filter(service => service.UUID === Service.CameraMultiTierRTPStreamManagement.UUID) const from = await endpoint() @@ -6635,6 +6724,9 @@ describe('multiTierStreamManagement', () => { alerts, answer, base, + closed: () => (thrown instanceof HDSProtocolError) + ? thrown.reason + : undefined, connection, delegate, ends, @@ -6654,7 +6746,7 @@ describe('multiTierStreamManagement', () => { } // 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> { + async function endedBy(served: Serving): Promise> { await settle() await until(() => udpSockets() === served.base) await settle() @@ -6663,7 +6755,7 @@ describe('multiTierStreamManagement', () => { alerts: served.alerts, recording: [ served.ends.map(({ outcome }) => outcome), - served.packets.at(-1), + served.closed() ?? 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), @@ -6675,16 +6767,16 @@ describe('multiTierStreamManagement', () => { } 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], + ['its accessory is unpublished and published again', alone, CLOSED], + ['its accessory is taken off its published bridge and put back', bridged, CLOSED], + ['its source is stated away and then available', stated, MARKED], ] 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) => { + + '%s, and raises each tier it holds afresh with no alert once back', async (_path, enter, recording) => { const served = await serving(enter) await served.path.leave() - expect(await endedBy(served)).toEqual(ENDED) + expect(await endedBy(served)).toEqual({ ...ENDED, recording }) const before = streamsOf(served.delegate).length @@ -6713,7 +6805,7 @@ describe('multiTierStreamManagement', () => { await served.accessory.destroy() - expect(await endedBy(served)).toEqual(ENDED) + expect(await endedBy(served)).toEqual({ ...ENDED, recording: CLOSED }) served.pending.resolve() }) diff --git a/src/lib/camera/RTPStreamManagement.spec.ts b/src/lib/camera/RTPStreamManagement.spec.ts index 222e981a1..4e7246765 100644 --- a/src/lib/camera/RTPStreamManagement.spec.ts +++ b/src/lib/camera/RTPStreamManagement.spec.ts @@ -1,8 +1,8 @@ import type { MockInstance } from 'vitest' -import type { CameraControllerOptions, PrepareStreamCallback } from '../controller/index.js' +import type { CameraControllerOptions, PrepareStreamCallback, StreamRequestCallback } from '../controller/index.js' import type { HAPConnection } from '../util/eventedhttp.js' -import type { CameraStreamingOptions, PrepareStreamRequest, PrepareStreamResponse } from './RTPStreamManagement.js' +import type { CameraStreamingOptions, PrepareStreamRequest, PrepareStreamResponse, StreamingRequest } from './RTPStreamManagement.js' import { Buffer } from 'node:buffer' import { format } from 'node:util' @@ -12,6 +12,7 @@ import tweetnacl from 'tweetnacl' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { + buildEmitterConnection, buildMockConnection, buildSetupEndpointsTlv, createCameraControllerOptions, @@ -25,12 +26,13 @@ import { } 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 { settle } from '../../test-utils/settle.js' +import { Accessory, AccessoryEventTypes, Categories, CharacteristicWarningType, MDNSAdvertiser } from '../Accessory.js' import { AudioStreamingCodecType, AudioStreamingSamplerate, } from '../camera/index.js' -import { Characteristic } from '../Characteristic.js' +import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' import { CameraController } from '../controller/index.js' import { HAPStatus } from '../HAPServer.js' import { AccessoryInfo, PermissionTypes } from '../model/AccessoryInfo.js' @@ -131,7 +133,60 @@ function buildClosableConnection() { function startTlv(sessionId: string, command = 0x01): string { // only session control matters for END; START with garbage parameters fails synchronously, so we use END/START via delegate - return tlv.encode(0x01, tlv.encode(0x01, uuid.write(sessionId), 0x02, command)).toString('base64') + return selectedConfiguration(sessionId, command) +} + +// The session the rows below set up, which buildSetupEndpointsTlv names where a row names none. +const SESSION = '11111111-1111-1111-1111-111111111111' + +// The commands of a Selected RTP Stream Configuration write's session control. +const END_SESSION = 0x00 +const START_SESSION = 0x01 +const RECONFIGURE_SESSION = 0x04 + +// A TLV entry whose declared length runs past the bytes it holds, which no decode reads. +const CUT_SHORT = Buffer.from([0x01, 0x05, 0x00]) + +/* The selected video and audio parameters of a start, and the selected video parameters of a reconfigure. The video is H.264: its codec type, its codec + * parameters (profile, level and packetization mode), its attributes (width, height and frame rate) and its RTP parameters (payload type, SSRC, maximum + * bitrate and RTCP interval). The audio is Opus: its codec type, its codec parameters (channels, bitrate mode, sample rate and packet time), its RTP + * parameters (payload type, SSRC, maximum bitrate, RTCP interval and comfort noise payload type) and its comfort noise flag. + */ +const VIDEO_ATTRIBUTES = tlv.encode(0x01, tlv.writeUInt16(1280), 0x02, tlv.writeUInt16(720), 0x03, 30) +const START_VIDEO_PARAMETERS = tlv.encode( + 0x01, 0x00, + 0x02, tlv.encode(0x01, 0x00, 0x02, 0x00, 0x03, 0x00), + 0x03, VIDEO_ATTRIBUTES, + 0x04, tlv.encode(0x01, 99, 0x02, tlv.writeUInt32(1), 0x03, tlv.writeUInt16(300), 0x04, tlv.writeFloat32LE(0.5)), +) +const START_AUDIO_PARAMETERS = tlv.encode( + 0x01, 0x03, + 0x02, tlv.encode(0x01, 1, 0x02, 0x00, 0x03, 0x01, 0x04, 20), + 0x03, tlv.encode(0x01, 110, 0x02, tlv.writeUInt32(2), 0x03, tlv.writeUInt16(24), 0x04, tlv.writeFloat32LE(0.5), 0x06, 13), + 0x04, 0x00, +) +const RECONFIGURE_VIDEO_PARAMETERS = tlv.encode( + 0x03, VIDEO_ATTRIBUTES, + 0x04, tlv.encode(0x03, tlv.writeUInt16(300), 0x04, tlv.writeFloat32LE(0.5)), +) + +// A Selected RTP Stream Configuration value: its session control, naming the session and the command, then each parameters entry by its type. +function selectedConfiguration(sessionId: string, command: number, parameters: Record = {}): string { + return Buffer.concat([ + tlv.encode(0x01, tlv.encode(0x01, uuid.write(sessionId), 0x02, command)), + ...Object.entries(parameters).map(([type, value]) => tlv.encode(Number(type), value)), + ]).toString('base64') +} + +// Records each stream request the delegate hears as its type and session, answering it at once. +function recordStreamRequests(): string[] { + const requests: string[] = [] + vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(((request: StreamingRequest, callback: StreamRequestCallback) => { + requests.push(`${request.type}:${request.sessionID}`) + callback() + }) as () => void) + + return requests } describe('RTPStreamManagement', () => { @@ -193,11 +248,10 @@ describe('RTPStreamManagement', () => { const rtp = controller.streamManagements[0] as RTPStreamManagement const callback = vi.fn(); - // empty video/audio config — every indexed buffer access (e.g. - // `videoParameters[VideoCodecParametersTypes.PROFILE_ID][0]`) would - // throw without the try/catch from 34056583. + // Empty video and audio parameters decode to empty records, and every indexed buffer access (e.g. + // `videoParameters[VideoCodecParametersTypes.PROFILE_ID][0]`) would throw outside the parse's try. - (rtp as any)._handleStartStream({}, {}, callback) + (rtp as any)._handleStartStream(Buffer.alloc(0), Buffer.alloc(0), callback) expect(callback).toHaveBeenCalledTimes(1) expect(callback.mock.calls[0][0]).toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) @@ -207,15 +261,12 @@ describe('RTPStreamManagement', () => { const rtp = controller.streamManagements[0] as RTPStreamManagement const callback = vi.fn() - // SelectedVideoParametersTypes.CODEC_TYPE = 0x01 — provide that but - // omit CODEC_PARAMETERS / ATTRIBUTES / RTP_PARAMETERS so the inner - // `tlv.decode(undefined)` would have crashed without the guard. - const videoConfig = { - 0x01: Buffer.from([0x00]), - } + // SelectedVideoParametersTypes.CODEC_TYPE = 0x01 is given, and CODEC_PARAMETERS, ATTRIBUTES and RTP_PARAMETERS are left out, which means the + // inner `tlv.decode(undefined)` would throw outside the parse's try. + const videoParameters = tlv.encode(0x01, 0x00) expect(() => { - (rtp as any)._handleStartStream(videoConfig, {}, callback) + (rtp as any)._handleStartStream(videoParameters, Buffer.alloc(0), callback) }).not.toThrow() expect(callback).toHaveBeenCalledTimes(1) @@ -461,15 +512,20 @@ describe('RTPStreamManagement', () => { vi.spyOn(RTPProxy.prototype, 'incomingRTPPort').mockReturnValue(10000) vi.spyOn(RTPProxy.prototype, 'incomingRTCPPort').mockReturnValue(10001) const prepareStream = vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(() => undefined) + const handleStreamRequest = vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined) const rtp = controller.streamManagements[0] as RTPStreamManagement const first = vi.fn() const second = vi.fn() + const firstConnection = buildClosableConnection() // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), first, buildMockConnection()) - // @ts-expect-error: private method access - rtp.handleSessionClosed() // e.g. the connection closed + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), first, firstConnection) + firstConnection.close() // the HAP connection closes while the sockets are bound, and the delegate hears STOP + expect(handleStreamRequest).toHaveBeenCalledExactlyOnceWith({ + sessionID: '11111111-1111-1111-1111-111111111111', + type: StreamRequestTypes.STOP, + }, expect.any(Function)) // @ts-expect-error: private method access rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, '22222222-2222-2222-2222-222222222222'), second, buildMockConnection()) @@ -485,6 +541,7 @@ describe('RTPStreamManagement', () => { audio: { proxy_rtp: 10000, proxy_rtcp: 10001 }, }) expect(second).not.toHaveBeenCalled() // still waits for the delegate + expect(handleStreamRequest).toHaveBeenCalledTimes(1) }) }) @@ -618,6 +675,7 @@ describe('RTPStreamManagement', () => { [ 'an error', (callback: PrepareStreamCallback) => callback(new Error('camera offline')), + 1, ], [ 'a response', @@ -635,19 +693,21 @@ describe('RTPStreamManagement', () => { srtp_salt: Buffer.alloc(14), }, }), + 2, ], - ])('should ignore %s for a session which ended while it was prepared', async (_name, answer) => { + ])('should ignore %s for a session which ended while it was prepared', async (_name, answer, stops) => { const rtp = controller.streamManagements[0] as RTPStreamManagement const prepareCallbacks: PrepareStreamCallback[] = [] const prepareStream = (_request: unknown, callback: PrepareStreamCallback) => { prepareCallbacks.push(callback) } vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(prepareStream as () => void) + const handleStreamRequest = vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined) 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 connectionA = buildClosableConnection() const connectionB = buildMockConnection() const callbackA = vi.fn() const callbackB = vi.fn() @@ -655,8 +715,8 @@ describe('RTPStreamManagement', () => { // 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 + connectionA.close() // the HAP connection closes while the delegate is still preparing, and the delegate hears STOP + expect(handleStreamRequest).toHaveBeenCalledExactlyOnceWith({ sessionID: sessionA, type: StreamRequestTypes.STOP }, expect.any(Function)) characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionB), connectionB).then(() => callbackB(), callbackB) await vi.waitFor(() => expect(prepareCallbacks).toHaveLength(2)) const answersBefore = await answers([connectionA, connectionB]) @@ -664,6 +724,10 @@ describe('RTPStreamManagement', () => { answer(prepareCallbacks[0]) // the late answer for the first session await vi.waitFor(() => expect(callbackA).toHaveBeenCalledExactlyOnceWith(HAPStatus.SERVICE_COMMUNICATION_FAILURE)) + await settle() + // A late success leaves the delegate streaming for the ended session, which it is told to stop once more. A late error hears nothing more. + expect(handleStreamRequest.mock.calls.map(call => (call as unknown[])[0])) + .toEqual(Array.from({ length: stops }, () => ({ sessionID: sessionA, type: StreamRequestTypes.STOP }))) expect(callbackB).not.toHaveBeenCalled() expect(rtp.sessionIdentifier).toEqual(sessionB) expect(rtp.streamStatus).toBe(1) // StreamingStatus.IN_USE @@ -1156,4 +1220,589 @@ describe('RTPStreamManagement', () => { } }) }) + + describe('the cut of a prepare the delegate has not answered', () => { + let controller: CameraController + let rtp: RTPStreamManagement + let requests: string[] + + // Builds the camera whose first stream the row drives, under the streaming options the row names. + function build(options: CameraStreamingOptions = mockStreamingOptions): void { + controller = new CameraController(buildControllerOptions(options)) + controller.constructServices() + controller.configureServices() + rtp = controller.streamManagements[0] + } + + beforeEach(() => { + vi.useFakeTimers() + build() + requests = recordStreamRequests() + }) + + afterEach(() => { + vi.restoreAllMocks() + controller.handleFactoryReset() + vi.useRealTimers() + }) + + // Collects each prepare callback the delegate is handed, answering none. + function holdPreparations(): PrepareStreamCallback[] { + const callbacks: PrepareStreamCallback[] = [] + vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(((_request: unknown, callback: PrepareStreamCallback) => { + callbacks.push(callback) + }) as () => void) + + return callbacks + } + + it('should end a session whose prepare never answers once the write has timed out, leaving the write unanswered and nothing standing', async () => { + holdPreparations() + const connection = buildEmitterConnection() + const listeners = connection.listenerCount('closed') + const allowance = connection.getMaxListeners() + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), callback, connection) + await vi.advanceTimersByTimeAsync(8999) + + expect(callback).not.toHaveBeenCalled() + expect(requests).toEqual([]) + expect(rtp.streamStatus).toBe(1) // StreamingStatus.IN_USE + + await vi.advanceTimersByTimeAsync(1) + + expect(callback).not.toHaveBeenCalled() + expect(requests).toEqual([`stop:${SESSION}`]) + expect(rtp.streamStatus).toBe(0) // StreamingStatus.AVAILABLE + expect(connection.listenerCount('closed')).toBe(listeners) + expect(connection.getMaxListeners()).toBe(allowance) + expect(vi.getTimerCount()).toBe(0) + }) + + it('should clear the cut of a prepare answered with success after the call, and stop nothing', async () => { + vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(((request: unknown, callback: PrepareStreamCallback) => { + setTimeout(prepareOk, 1000, request, callback) + }) as () => void) + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), callback, buildMockConnection()) + await vi.advanceTimersByTimeAsync(1000) + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback.mock.calls[0][0]).toBeUndefined() + expect(vi.getTimerCount()).toBe(0) + + await vi.advanceTimersByTimeAsync(8000) + + expect(requests).toEqual([]) + expect(rtp.sessionIdentifier).toBe(SESSION) + }) + + it('should clear the cut of a prepare answered with success inside the call, and stop nothing', async () => { + vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(prepareOk as () => void) + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), callback, buildMockConnection()) + await vi.advanceTimersByTimeAsync(0) + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback.mock.calls[0][0]).toBeUndefined() + expect(vi.getTimerCount()).toBe(0) + + await vi.advanceTimersByTimeAsync(9000) + + expect(requests).toEqual([]) + expect(rtp.sessionIdentifier).toBe(SESSION) + }) + + it.each([ + [ + 'the close of its HAP connection', + (_rtp: RTPStreamManagement, connection: ReturnType) => connection.close(), + ], + [ + 'END_SESSION', + // @ts-expect-error: private method access + (management: RTPStreamManagement) => management._handleSelectedStreamConfigurationWrite(startTlv(SESSION, END_SESSION), vi.fn()), + ], + [ + 'a force-stop', + (management: RTPStreamManagement) => management.forceStop(), + ], + [ + 'a factory reset', + (management: RTPStreamManagement) => management.handleFactoryReset(), + ], + [ + 'its destroy', + (management: RTPStreamManagement) => management.destroy(), + ], + ])('should clear the cut of a pending prepare whose session ends at %s, which stops it once', async (_name, end) => { + holdPreparations() + const connection = buildClosableConnection() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), vi.fn(), connection) + await vi.advanceTimersByTimeAsync(1000) + end(rtp, connection) + + expect(requests).toEqual([`stop:${SESSION}`]) + expect(vi.getTimerCount()).toBe(0) + + await vi.advanceTimersByTimeAsync(8000) + + expect(requests).toEqual([`stop:${SESSION}`]) + }) + + it('should leave the cut of the next session armed when the ended session\'s prepare answers late', async () => { + const callbacks = holdPreparations() + const sessionB = '22222222-2222-2222-2222-222222222222' + const connectionA = buildClosableConnection() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), vi.fn(), connectionA) + await vi.advanceTimersByTimeAsync(1000) + connectionA.close() + await vi.advanceTimersByTimeAsync(1000) + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionB), vi.fn(), buildClosableConnection()) + await vi.advanceTimersByTimeAsync(1000) + prepareOk(undefined, callbacks[0]) + await vi.advanceTimersByTimeAsync(7999) + + // The first session heard its STOP at the close and a second one after its late success, and the second session has heard nothing. + expect(requests).toEqual([`stop:${SESSION}`, `stop:${SESSION}`]) + + await vi.advanceTimersByTimeAsync(1) + + expect(requests).toEqual([`stop:${SESSION}`, `stop:${SESSION}`, `stop:${sessionB}`]) + }) + + it('should arm no cut for a session that ended while its proxy sockets were bound, also when the next session started', async () => { + controller.handleFactoryReset() + build({ ...mockStreamingOptions, proxy: true }) + const bound: (() => void)[] = [] + vi.spyOn(RTPProxy.prototype, 'setup').mockImplementation(() => new Promise(resolve => bound.push(resolve))) + vi.spyOn(RTPProxy.prototype, 'incomingRTPPort').mockReturnValue(10000) + vi.spyOn(RTPProxy.prototype, 'incomingRTCPPort').mockReturnValue(10001) + const prepareStream = vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(() => undefined) + const sessionB = '22222222-2222-2222-2222-222222222222' + const connectionA = buildClosableConnection() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), vi.fn(), connectionA) + connectionA.close() + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionB), vi.fn(), buildClosableConnection()) + // The sockets of the ended session are ready last. + for (const resolve of bound.reverse()) { + resolve() + } + await vi.advanceTimersByTimeAsync(0) + + expect(prepareStream).toHaveBeenCalledTimes(1) + expect((prepareStream.mock.calls[0] as unknown[])[0]).toMatchObject({ sessionID: sessionB }) + + rtp.forceStop() + + expect(requests).toEqual([`stop:${SESSION}`, `stop:${sessionB}`]) + expect(vi.getTimerCount()).toBe(0) + }) + + it('should keep the cut of a pending session when a setup finds the stream busy', async () => { + holdPreparations() + const busy = vi.fn() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), vi.fn(), buildClosableConnection()) + await vi.advanceTimersByTimeAsync(1000) + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, '22222222-2222-2222-2222-222222222222'), busy, buildClosableConnection()) + + expect(decodeSetupEndpointsResponse(busy.mock.calls[0][1] as string)).toMatchObject({ status: SetupEndpointsStatus.BUSY }) + + await vi.advanceTimersByTimeAsync(8000) + + expect(requests).toEqual([`stop:${SESSION}`]) + }) + + it('should answer a prepare that succeeds after the cut with a communication failure, and tell the delegate STOP once its callback returned', async () => { + const callbacks = holdPreparations() + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), callback, buildMockConnection()) + await vi.advanceTimersByTimeAsync(9000) + + expect(requests).toEqual([`stop:${SESSION}`]) + expect(() => prepareOk(undefined, callbacks[0])).not.toThrow() + expect(callback).toHaveBeenCalledExactlyOnceWith(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(requests).toEqual([`stop:${SESSION}`]) + + await Promise.resolve() + + expect(requests).toEqual([`stop:${SESSION}`, `stop:${SESSION}`]) + }) + }) + + describe('a prepare the delegate never answers, written through the accessory', () => { + it('should leave the write to the accessory, which answers it as timed out with its warning, and end the session once it has', async () => { + vi.useFakeTimers() + const accessory = new Accessory('Cam', uuid.generate('a prepare the delegate never answers')) + const controller = new CameraController(buildControllerOptions(mockStreamingOptions)) + accessory.configureController(controller) + accessory._identifierCache = new IdentifierCache('AA:BB:CC:DD:EE:FF') + accessory._assignIDs(accessory._identifierCache) + const rtp = controller.streamManagements[0] + const setup = rtp.getService().getCharacteristic(Characteristic.SetupEndpoints) + vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(() => undefined) + const requests = recordStreamRequests() + const warnings: CharacteristicWarningType[] = [] + accessory.on(AccessoryEventTypes.CHARACTERISTIC_WARNING, warning => warnings.push(warning.type)) + const callback = vi.fn() + + try { + // @ts-expect-error: private method access + accessory.handleSetCharacteristics(buildMockConnection(), { + characteristics: [ + { + aid: 1, + iid: setup.iid!, + value: buildSetupEndpointsTlv(), + }, + ], + }, callback) + await vi.advanceTimersByTimeAsync(8999) + + expect(callback).not.toHaveBeenCalled() + expect(requests).toEqual([]) + expect(rtp.streamStatus).toBe(1) // StreamingStatus.IN_USE + + await vi.advanceTimersByTimeAsync(1) + + expect(callback).toHaveBeenCalledExactlyOnceWith(undefined, { + characteristics: [ + { aid: 1, iid: setup.iid, status: HAPStatus.OPERATION_TIMED_OUT }, + ], + }) + expect(warnings.filter(type => type === CharacteristicWarningType.TIMEOUT_WRITE)).toHaveLength(1) + expect(requests).toEqual([`stop:${SESSION}`]) + expect(rtp.streamStatus).toBe(0) // StreamingStatus.AVAILABLE + } finally { + vi.restoreAllMocks() + controller.handleFactoryReset() + vi.useRealTimers() + } + }) + }) + + describe('a delegate that fails a stream preparation', () => { + const FAILURE = new Error('The camera is offline.') + + let controller: CameraController + let rtp: RTPStreamManagement + let requests: string[] + let error: MockInstance + let lines: string[] + let namespaces: string + + beforeEach(() => { + vi.useFakeTimers() + controller = new CameraController(buildControllerOptions(mockStreamingOptions)) + controller.constructServices() + controller.configureServices() + rtp = controller.streamManagements[0] + requests = recordStreamRequests() + error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + namespaces = createDebug.disable() + createDebug.enable('HAP-NodeJS:Camera:RTPStreamManagement') + lines = [] + vi.spyOn(createDebug, 'log').mockImplementation((...args: unknown[]) => { + lines.push(format(...args)) + }) + }) + + afterEach(() => { + vi.restoreAllMocks() + createDebug.enable(namespaces) + controller.handleFactoryReset() + vi.useRealTimers() + }) + + it.each([ + [ + 'throws', + (): void => { + throw FAILURE + }, + ], + [ + 'returns a promise that rejects', + async (): Promise => { + throw FAILURE + }, + ], + ])('should answer the write with the failure of a delegate that %s before it answers, freeing the stream with no STOP', async (_name, prepareStream) => { + vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(prepareStream as () => void) + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), callback, buildMockConnection()) + await vi.advanceTimersByTimeAsync(0) + + expect(callback).toHaveBeenCalledExactlyOnceWith(FAILURE) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to prepare a stream: Error: The camera is offline.'), + ], + ]) + expect(lines.filter(line => line.includes('RTP proxy setup failed'))).toEqual([]) + expect(rtp.streamStatus).toBe(0) // StreamingStatus.AVAILABLE + expect(rtp.sessionIdentifier).toBeUndefined() + expect(requests).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + }) + + it.each([ + [ + 'throws', + (request: unknown, callback: PrepareStreamCallback): void => { + prepareOk(request, callback) + throw FAILURE + }, + ], + [ + 'returns a promise that rejects', + async (request: unknown, callback: PrepareStreamCallback): Promise => { + prepareOk(request, callback) + throw FAILURE + }, + ], + ])('should keep the answer and the session of a delegate that answers with success and then %s, logging the failure', async (_name, prepareStream) => { + vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(prepareStream as () => void) + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), callback, buildMockConnection()) + await vi.advanceTimersByTimeAsync(0) + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback.mock.calls[0][0]).toBeUndefined() + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to prepare a stream: Error: The camera is offline.'), + ], + ]) + expect(rtp.sessionIdentifier).toBe(SESSION) + expect(rtp.streamStatus).toBe(1) // StreamingStatus.IN_USE + expect(requests).toEqual([]) + expect(vi.getTimerCount()).toBe(0) + }) + + it('should answer the write once and leave the next session standing when a prepare rejects after its HAP connection closed and the next session ' + + 'started', async () => { + const rejections: ((error: Error) => void)[] = [] + vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation((() => new Promise((_resolve, reject) => { + rejections.push(reject) + })) as () => void) + const sessionB = '22222222-2222-2222-2222-222222222222' + const connectionA = buildClosableConnection() + const callbackA = vi.fn() + + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), callbackA, connectionA) + await vi.advanceTimersByTimeAsync(1000) + connectionA.close() + // @ts-expect-error: private method access + rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionB), vi.fn(), buildClosableConnection()) + await vi.advanceTimersByTimeAsync(1000) + rejections[0](FAILURE) + await vi.advanceTimersByTimeAsync(0) + + expect(callbackA).toHaveBeenCalledTimes(1) + expect(requests).toEqual([`stop:${SESSION}`]) + expect(rtp.sessionIdentifier).toBe(sessionB) + expect(rtp.streamStatus).toBe(1) + }) + }) + + describe('a delegate that fails a stream request', () => { + let controller: CameraController + let rtp: RTPStreamManagement + let error: MockInstance + + beforeEach(() => { + controller = new CameraController(buildControllerOptions(mockStreamingOptions)) + controller.constructServices() + controller.configureServices() + rtp = controller.streamManagements[0] + rtp.sessionIdentifier = SESSION // a stream is running + error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + }) + + afterEach(() => { + vi.restoreAllMocks() + controller.handleFactoryReset() + }) + + // Scripts the delegate's handleStreamRequest by request type, recording each type it hears: a STOP is answered at once, and every other request runs + // the row's own handler. + function script(handle: (callback: StreamRequestCallback) => unknown): string[] { + const requests: string[] = [] + vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(((request: StreamingRequest, callback: StreamRequestCallback) => { + requests.push(request.type) + + return request.type === StreamRequestTypes.STOP + ? callback() + : handle(callback) + }) as () => void) + + return requests + } + + const throwing = (): void => { + throw new Error('The camera could not stream.') + } + const rejecting = async (): Promise => { + throw new Error('The camera could not stream.') + } + + it.each([ + ['throws', throwing], + ['returns a promise that rejects before it calls back', rejecting], + ])('should answer a start whose delegate %s with a communication failure, and stop the session', async (_name, handle) => { + const requests = script(handle) + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp._handleSelectedStreamConfigurationWrite(selectedConfiguration(SESSION, START_SESSION, { + 0x02: START_VIDEO_PARAMETERS, + 0x03: START_AUDIO_PARAMETERS, + }), callback) + await settle() + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback.mock.calls[0][0]).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to handle a start stream request: Error: The camera could not stream.'), + ], + ]) + expect(requests).toEqual(['start', 'stop']) + expect(rtp.sessionIdentifier).toBeUndefined() + }) + + it('should keep the answer of a delegate that answers a start and then throws, logging the failure', async () => { + const requests = script((callback) => { + callback() + throwing() + }) + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp._handleSelectedStreamConfigurationWrite(selectedConfiguration(SESSION, START_SESSION, { + 0x02: START_VIDEO_PARAMETERS, + 0x03: START_AUDIO_PARAMETERS, + }), callback) + await settle() + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback.mock.calls[0][0]).toBeUndefined() + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to handle a start stream request: Error: The camera could not stream.'), + ], + ]) + expect(requests).toEqual(['start']) + expect(rtp.sessionIdentifier).toBe(SESSION) + }) + + it('should throw at a delegate that calls a start\'s callback a second time, the write answered once', async () => { + const callbacks: StreamRequestCallback[] = [] + const requests = script((callback) => { + callbacks.push(callback) + }) + const callback = vi.fn() + + // @ts-expect-error: private method access + rtp._handleSelectedStreamConfigurationWrite(selectedConfiguration(SESSION, START_SESSION, { + 0x02: START_VIDEO_PARAMETERS, + 0x03: START_AUDIO_PARAMETERS, + }), callback) + await settle() + callbacks[0]() + + expect(() => callbacks[0]()).toThrow('This callback function has already been called by someone else; it can only be called one time.') + expect(callback).toHaveBeenCalledTimes(1) + expect(callback.mock.calls[0][0]).toBeUndefined() + expect(error.mock.calls).toEqual([]) + expect(requests).toEqual(['start']) + expect(rtp.sessionIdentifier).toBe(SESSION) + }) + + it.each([ + ['throws', throwing], + ['returns a promise that rejects before it calls back', rejecting], + ])('should answer a reconfigure whose delegate %s with a communication failure and no characteristic warning, and stop the session', async (_name, handle) => { + const requests = script(handle) + const characteristic = rtp.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration) + const warnings = vi.fn() + characteristic.on(CharacteristicEventTypes.CHARACTERISTIC_WARNING, warnings) + + await expect(characteristic.handleSetRequest(selectedConfiguration(SESSION, RECONFIGURE_SESSION, { 0x02: RECONFIGURE_VIDEO_PARAMETERS }))) + .rejects + .toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await settle() + + expect(warnings).not.toHaveBeenCalled() + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to handle a reconfigure stream request: Error: The camera could not stream.'), + ], + ]) + expect(requests).toEqual(['reconfigure', 'stop']) + expect(rtp.sessionIdentifier).toBeUndefined() + }) + + it.each([ + [ + 'a value whose TLV is cut short', + CUT_SHORT.toString('base64'), + [], + ], + [ + 'a reconfigure whose parameters are cut short', + selectedConfiguration(SESSION, RECONFIGURE_SESSION, { 0x02: CUT_SHORT }), + ['stop'], + ], + [ + 'a start whose selected video parameters are missing', + selectedConfiguration(SESSION, START_SESSION, { 0x03: START_AUDIO_PARAMETERS }), + ['stop'], + ], + [ + 'a start whose selected video parameters are cut short', + selectedConfiguration(SESSION, START_SESSION, { + 0x02: CUT_SHORT, + 0x03: START_AUDIO_PARAMETERS, + }), + ['stop'], + ], + ])('should answer %s as an invalid request with no characteristic warning', async (_name, value, stops) => { + const requests = script(throwing) + const characteristic = rtp.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration) + const warnings = vi.fn() + characteristic.on(CharacteristicEventTypes.CHARACTERISTIC_WARNING, warnings) + + await expect(characteristic.handleSetRequest(value)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + + expect(warnings).not.toHaveBeenCalled() + expect(requests).toEqual(stops) + expect(error.mock.calls).toEqual([]) + }) + }) }) diff --git a/src/lib/camera/RTPStreamManagement.ts b/src/lib/camera/RTPStreamManagement.ts index e239cc479..3656ffeb9 100644 --- a/src/lib/camera/RTPStreamManagement.ts +++ b/src/lib/camera/RTPStreamManagement.ts @@ -22,7 +22,8 @@ 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 { callDelegate, logDelegateFailure } from '../util/promise-utils.js' +import { CHARACTERISTIC_TIMEOUT_AFTER_WARNING, CHARACTERISTIC_TIMEOUT_WARNING } from '../util/request-util.js' import * as tlv from '../util/tlv.js' import * as uuid from '../util/uuid.js' import { @@ -528,6 +529,9 @@ export class RTPStreamManagement { private activeConnection?: HAPConnection private readonly activeConnectionClosedListener: (callback?: CharacteristicSetCallback) => void sessionIdentifier?: StreamSessionIdentifier = undefined + // The cut of the current session's prepare, which a session's end clears through here. A prepare's own answer clears its cut through the handle its setup + // holds instead, which is why the late answer of an ended session leaves the cut of the session after it armed. + private prepareCut?: ReturnType /** * @private */ @@ -746,6 +750,10 @@ export class RTPStreamManagement { } private handleSessionClosed(): void { // called when the streaming was ended or aborted and needs to be cleaned up + // Every end of a session reaches here, and the cut goes first, ahead of the characteristic updates whose change listeners are a plugin's own. + clearTimeout(this.prepareCut) + this.prepareCut = undefined + this.resetSelectedStreamConfiguration() // 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() @@ -787,12 +795,22 @@ export class RTPStreamManagement { return } - const data = Buffer.from(value as string, 'base64') - const objects = tlv.decode(data) + // A value that does not decode is the hub's invalid request, answered as one rather than thrown to the characteristic. Each command's parameters are + // decoded inside its own handler's try, which answers through the stream's callback and ends the session a malformed command names. + let objects: Record + let sessionIdentifier: StreamSessionIdentifier + let requestType: SessionControlCommand + try { + objects = tlv.decode(Buffer.from(value as string, 'base64')) - const sessionControl = tlv.decode(objects[SelectedRTPStreamConfigurationTypes.SESSION_CONTROL]) - const sessionIdentifier = uuid.unparse(sessionControl[SessionControlTypes.SESSION_IDENTIFIER]) - const requestType: SessionControlCommand = sessionControl[SessionControlTypes.COMMAND][0] + const sessionControl = tlv.decode(objects[SelectedRTPStreamConfigurationTypes.SESSION_CONTROL]) + sessionIdentifier = uuid.unparse(sessionControl[SessionControlTypes.SESSION_IDENTIFIER]) + requestType = sessionControl[SessionControlTypes.COMMAND][0] + } catch (error) { + debug('Failed to parse the selected stream configuration: %s', errorMessage(error)) + callback(HAPStatus.INVALID_VALUE_IN_REQUEST) + return + } if (sessionIdentifier !== this.sessionIdentifier) { debug(`Received unknown session Identifier with request to ${SessionControlCommand[requestType]}`) @@ -805,36 +823,30 @@ export class RTPStreamManagement { // intercept the callback chain to check if an error occurred. const streamCallback: CharacteristicSetCallback = (error, writeResponse) => { callback(error, writeResponse) // does not support writeResponse, but who knows what comes in the future. - // a late answer for a session which already ended must leave the session which came after it alone + // A late answer for a session which already ended must leave the session which came after it alone. An END_SESSION's session was closed before its + // stop was forwarded, which is why a failed start or reconfigure of the current session is the only failure that reaches the stop below. if (error && this.sessionIdentifier === sessionIdentifier) { - if (requestType !== SessionControlCommand.END_SESSION) { - // The session is given up, but the delegate may still be streaming for it (it does after a failed - // reconfigure). The controller's END_SESSION won't reach it anymore, so it is told to stop here. - try { - this._handleStopStream() - } catch (stopError) { - debug('Failed to stop the stream after a failed request: %s', errorMessage(stopError)) - } - } else { - this.handleSessionClosed() + // The session is given up, but the delegate may still be streaming for it (it does after a failed + // reconfigure). The controller's END_SESSION won't reach it anymore, so it is told to stop here. + try { + this._handleStopStream() + } catch (stopError) { + debug('Failed to stop the stream after a failed request: %s', errorMessage(stopError)) } } } switch (requestType) { - case SessionControlCommand.START_SESSION: { - const selectedVideoParameters = tlv.decode(objects[SelectedRTPStreamConfigurationTypes.SELECTED_VIDEO_PARAMETERS]) - const selectedAudioParameters = tlv.decode(objects[SelectedRTPStreamConfigurationTypes.SELECTED_AUDIO_PARAMETERS]) - - this._handleStartStream(selectedVideoParameters, selectedAudioParameters, streamCallback) + case SessionControlCommand.START_SESSION: + this._handleStartStream( + objects[SelectedRTPStreamConfigurationTypes.SELECTED_VIDEO_PARAMETERS], + objects[SelectedRTPStreamConfigurationTypes.SELECTED_AUDIO_PARAMETERS], + streamCallback, + ) break - } - case SessionControlCommand.RECONFIGURE_SESSION: { - const reconfiguredVideoParameters = tlv.decode(objects[SelectedRTPStreamConfigurationTypes.SELECTED_VIDEO_PARAMETERS]) - - this.handleReconfigureStream(reconfiguredVideoParameters, streamCallback) + case SessionControlCommand.RECONFIGURE_SESSION: + this.handleReconfigureStream(objects[SelectedRTPStreamConfigurationTypes.SELECTED_VIDEO_PARAMETERS], streamCallback) break - } case SessionControlCommand.END_SESSION: this._handleStopStream(streamCallback) break @@ -846,24 +858,21 @@ export class RTPStreamManagement { } } - private _handleStartStream( - videoConfiguration: Record, - audioConfiguration: Record, - callback: CharacteristicSetCallback, - ): void { + // The parameters are decoded and parsed inside the try, and the request is forwarded after it, which leaves a delegate's failure to the forward's own answer. + private _handleStartStream(videoParameters: Buffer, audioParameters: Buffer, callback: CharacteristicSetCallback): void { + let request: StartStreamRequest try { - this._handleStartStreamInner(videoConfiguration, audioConfiguration, callback) + request = this._handleStartStreamInner(tlv.decode(videoParameters), tlv.decode(audioParameters)) } catch (error) { debug('Failed to parse stream start request: %s', errorMessage(error)) callback(HAPStatus.INVALID_VALUE_IN_REQUEST) + return } + + this.forwardStreamRequest(request, callback) } - private _handleStartStreamInner( - videoConfiguration: Record, - audioConfiguration: Record, - callback: CharacteristicSetCallback, - ): void { + private _handleStartStreamInner(videoConfiguration: Record, audioConfiguration: Record): StartStreamRequest { // selected video configuration // noinspection JSUnusedLocalSymbols const videoCodec = videoConfiguration[SelectedVideoParametersTypes.CODEC_TYPE] // always 0x00 for h264 @@ -1007,17 +1016,29 @@ export class RTPStreamManagement { comfortNoiseEnabled: comfortNoise, } - const request: StartStreamRequest = { + return { sessionID: this.sessionIdentifier!, type: StreamRequestTypes.START, video: videoInfo, audio: audioInfo, } + } + + // As a start's: the parameters are decoded and parsed inside the try, and the request is forwarded after it. + private handleReconfigureStream(videoParameters: Buffer, callback: CharacteristicSetCallback): void { + let request: ReconfigureStreamRequest + try { + request = this.parseReconfigureStream(tlv.decode(videoParameters)) + } catch (error) { + debug('Failed to parse stream reconfigure request: %s', errorMessage(error)) + callback(HAPStatus.INVALID_VALUE_IN_REQUEST) + return + } this.forwardStreamRequest(request, callback) } - private handleReconfigureStream(videoConfiguration: Record, callback: CharacteristicSetCallback): void { + private parseReconfigureStream(videoConfiguration: Record): ReconfigureStreamRequest { // selected video configuration const videoAttributesTLV = videoConfiguration[SelectedVideoParametersTypes.ATTRIBUTES] const videoRTPParametersTLV = videoConfiguration[SelectedVideoParametersTypes.RTP_PARAMETERS] @@ -1043,13 +1064,11 @@ export class RTPStreamManagement { rtcp_interval: videoRTCPInterval, } - const request: ReconfigureStreamRequest = { + return { sessionID: this.sessionIdentifier!, type: StreamRequestTypes.RECONFIGURE, video: reconfiguredVideoInfo, } - - this.forwardStreamRequest(request, callback) } private _handleStopStream(callback?: CharacteristicSetCallback): void { @@ -1063,15 +1082,31 @@ export class RTPStreamManagement { 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. + /* A stream request that answers a write answers it once, through a local answer, whichever comes first of the delegate's callback and its failure. A + * throw, or the rejection of a promise the delegate returns before it calls back, is logged and answers the write with a communication failure, and the + * write's handler then ends a failed start or reconfigure with a STOP. A failure after the delegate's answer is logged alone, and the answer stands. The + * delegate's callback keeps its own once, which throws at a second call as the write's callback does. A stop at a closed connection or a teardown + * answers no write, and callDelegate logs its failure alone. + */ 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 { + if (!callback) { callDelegate(() => this.delegate.handleStreamRequest(request, () => undefined), failure) + return } + + let answered = false + const answer = (error?: Error | HAPStatus): void => { + if (!answered) { + answered = true + callback(error) + } + } + + callDelegate(() => this.delegate.handleStreamRequest(request, once((error?: Error) => answer(error))), failure, (failed, error) => { + logDelegateFailure(failed, error) + answer(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + }) } private handleSetupEndpoints(value: CharacteristicValue, callback: CharacteristicSetCallback, connection: HAPConnection): void { @@ -1199,14 +1234,43 @@ export class RTPStreamManagement { prepareRequest.audio.proxy_rtcp = audioProxy.incomingRTCPPort() } - // 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) => { + // The write is answered once, through this local answer alone, whichever comes first of the delegate's callback and its failure. The write's own + // callback throws at a second call, which would land in the delegate's callback. + let answered = false + const answer: CharacteristicSetCallback = (...answerArguments) => { + if (!answered) { + answered = true + callback(...answerArguments) + } + } + + /* The cut ends a session whose delegate has not answered its prepare once Accessory has answered the hub's write as timed out: it closes the session + * and tells the delegate STOP. It never answers the write, which Accessory's own timer answers with its timeout warning, and it fires only while the + * write is unanswered and its session current. Each of its clears removes a cut whose check would read false: the prepare's answer and failure clear + * it through this handle, and a session's end through the stream's field. + */ + const cut = setTimeout(() => { + if (!answered && (this.sessionIdentifier === sessionIdentifier)) { + debug('The delegate did not prepare the stream of session %s before the write timed out, and the session ends.', sessionIdentifier) + this._handleStopStream() + } + }, CHARACTERISTIC_TIMEOUT_WARNING + CHARACTERISTIC_TIMEOUT_AFTER_WARNING).unref() + this.prepareCut = cut + + const prepared = (error?: Error, response?: PrepareStreamResponse): void => { + clearTimeout(cut) + 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. + // The session ended while the delegate was preparing it (the connection closed, or the cut ended it), and another one may have started since. + // This answer must not touch that one. A success leaves the delegate streaming for the ended session, which it is told to stop once this + // callback has returned. debug('Ignoring the PrepareStream response for session %s which is not the current session anymore', sessionIdentifier) - callback(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + answer(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + + if (!error && response) { + queueMicrotask(() => this.forwardStreamRequest({ sessionID: sessionIdentifier, type: StreamRequestTypes.STOP })) + } + return } @@ -1215,21 +1279,41 @@ export class RTPStreamManagement { 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) + answer(error ?? HAPStatus.SERVICE_COMMUNICATION_FAILURE) } else { try { - this.generateSetupEndpointResponse(connection, sessionIdentifier, prepareRequest, response, callback) + this.generateSetupEndpointResponse(connection, sessionIdentifier, prepareRequest, response, answer) } 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() - callback(error instanceof Error + answer(error instanceof Error ? error : new Error(String(error))) } } - })), 'CameraStreamingDelegate failed to prepare a stream') + } + + // A throw from the delegate, or the rejection of a promise it returns before it calls back, fails the prepare at once: the session closes with no + // STOP and the write is answered with the failure. A failure after the delegate's answer is logged alone, and the session stays as the answer left it. + callDelegate(() => this.delegate.prepareStream(prepareRequest, once(prepared)), 'CameraStreamingDelegate failed to prepare a stream', (failure, error) => { + logDelegateFailure(failure, error) + + if (answered) { + return + } + + clearTimeout(cut) + + if (this.sessionIdentifier === sessionIdentifier) { + this.handleSessionClosed() + } + + answer(error instanceof Error + ? error + : new Error(String(error))) + }) }).catch((error: Error | undefined) => { debug(`RTP proxy setup failed: ${errorMessage(error)}`) diff --git a/src/lib/camera/RecordingManagement.spec.ts b/src/lib/camera/RecordingManagement.spec.ts index 2214a9d9a..7bddef18b 100644 --- a/src/lib/camera/RecordingManagement.spec.ts +++ b/src/lib/camera/RecordingManagement.spec.ts @@ -1,6 +1,6 @@ import type { Mock, MockInstance } from 'vitest' -import type { CameraControllerServiceMap, CameraRecordingDelegate, CameraStreamingDelegate } from '../controller/index.js' +import type { CameraControllerServiceMap, CameraRecordingDelegate, CameraRecordingEnd, 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' @@ -583,7 +583,11 @@ describe('RecordingManagement', () => { const answers: RecordingAdmission[] = [ { admitted: false, reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED }, { admitted: false, reason: HDSProtocolSpecificErrorReason.BUSY }, - { admitted: true, serve }, + { + admitted: true, + hubClosed: vi.fn(), + serve, + }, ] const admit = vi.fn<(streamId: number) => RecordingAdmission>(() => answers.shift()!) const delegate = recordingDelegate(async function* () { @@ -654,6 +658,45 @@ describe('RecordingManagement', () => { acknowledge(plainClient) }) + it('hands a hub\'s close of a stream its capabilities\' admit served to the admission\'s route with the reason the hub named, and not to the ' + + 'delegate\'s closeRecordingStream, while the stream\'s connection\'s close still reaches the delegate', async () => { + const { reporter } = problemsOf() + const hubClosed = vi.fn<(reason: HDSProtocolSpecificErrorReason | undefined) => void>() + const serve = vi.fn(async function* (signal?: AbortSignal): AsyncGenerator { + await aborted(signal!) + }) + const delegate = recordingDelegate(async function* () { + yield packet(100, true) + }) + const management = new RecordingManagement(undefined, delegate, new Set([EventTriggerOption.MOTION]), undefined, undefined, { + admit: () => ({ admitted: true, hubClosed, serve }), + feed: new ServedRecordings({ reporter, sensorUUID: FIRST_VIDEO_SENSOR.uuid }), + reporter, + }) + + management.recordingManagementService.getCharacteristic(Characteristic.Active).value = Characteristic.Active.ACTIVE + + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client, 1) + await settle() + hubClose(client, 1, HDSProtocolSpecificErrorReason.TIMEOUT) + await settle() + + expect(hubClosed.mock.calls).toEqual([ + [HDSProtocolSpecificErrorReason.TIMEOUT], + ]) + expect(delegate.closeRecordingStream).not.toHaveBeenCalled() + + open(client, 2) + await settle() + client.closeSocket() + await settle() + + expect(hubClosed).toHaveBeenCalledOnce() + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(2, undefined) + }) + it('saves no recording state', () => { expect(slim().serialize()).toBeUndefined() }) @@ -2094,9 +2137,10 @@ describe('RecordingManagement', () => { /* 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. + * gives, and it records from its camera buffer on demand, its recorded tier marked keepRunning and holding a keyframe, which its recorder serves a + * recording from at once. 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 @@ -2113,7 +2157,11 @@ describe('RecordingManagement', () => { handleSnapshotRequest: vi.fn((_request, callback) => callback(undefined, picture)), }) const snapshot = vi.fn(async () => picture) - const buffered = bufferCamera({ prebuffer: 0 }) + const buffered = bufferCamera({ mode: 'onDemand' }) + const [recordedSensor] = buffered.options.cameraCapabilities.videoSensors + + recordedSensor.tiers = recordedSensor.tiers.map(tier => ({ ...tier, keepRunning: tier.id === 1 })) + const camera = new CameraController(capabilities ? { ...buffered.options, @@ -2589,23 +2637,32 @@ describe('RecordingManagement', () => { } }) - // 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. + // 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. The ack reaches the + // recorder's acknowledgeStream, and the hub's close the admission's route, which tells the recording's end the reason the hub named. it.each([ { - called: 'acknowledgeStream' as const, hub: (client: DataStreamClient): void => acknowledge(client), kind: 'ack', - with: [1], + reached: { + acknowledgeStream: [ + [1], + ], + closeRecordingStream: [], + }, + reason: undefined, }, { - called: 'closeRecordingStream' as const, hub: (client: DataStreamClient): void => hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL), kind: 'close', - with: [1, HDSProtocolSpecificErrorReason.NORMAL], + reached: { acknowledgeStream: [], closeRecordingStream: [] }, + reason: 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() + ])('refuses as busy a snapshot open naming the running recording\'s stream, whose $kind still reaches the recording', async ({ hub, reached, reason }) => { + const { camera, management, recording, snapshot } = snapshotCamera() const client = await DataStreamClient.connect(management.dataStreamManagement) + const ends: CameraRecordingEnd[] = [] + + camera.on('recording-ended', end => ends.push(end)) open(client) await settle() @@ -2620,7 +2677,17 @@ describe('RecordingManagement', () => { hub(client) await settle() - expect(recording[called]).toHaveBeenCalledExactlyOnceWith(...args) + expect({ + acknowledgeStream: recording.acknowledgeStream.mock.calls, + closeRecordingStream: recording.closeRecordingStream.mock.calls, + }).toEqual(reached) + expect(ends.map(({ outcome, reason: named, streamId }) => ({ outcome, reason: named, streamId }))).toEqual([ + { + outcome: 'ended', + reason, + streamId: 1, + }, + ]) expect(recordingStreamOf(management)).toBeUndefined() }) diff --git a/src/lib/camera/RecordingManagement.ts b/src/lib/camera/RecordingManagement.ts index e250e70c8..702ac2de6 100644 --- a/src/lib/camera/RecordingManagement.ts +++ b/src/lib/camera/RecordingManagement.ts @@ -393,8 +393,9 @@ export interface RecordingManagementServices { 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. + * the open's answer with its reason, and an admission's serving function serves the stream in place of the delegate's request, its route of the hub's + * close taking the hub's own close of the stream in place of the delegate's closeRecordingStream. Without it, an open passing those checks is answered + * success and the stream asks the delegate. */ readonly admit?: (streamId: number) => RecordingAdmission /** @@ -407,12 +408,14 @@ interface RecordingManagementCapabilities { 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. + * where the gate lets it through, 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, and the one route by which the management tells the camera of a size it refuses, with the + * request's reason, before it answers the open. 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 + readonly sizeRefused: (reason: ResourceRequestReason | undefined) => void } } @@ -534,7 +537,8 @@ export class RecordingManagement { // 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. + // The recorder's decision a camera with the capabilities block asks before it answers a recording open, which carries the stream's serving function and + // its route of the hub's close. 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 @@ -849,7 +853,7 @@ export class RecordingManagement { const route = this.routeOf(connection) // eslint-disable-next-line ts/no-use-before-define - const stream = new CameraRecordingStream(connection, this.delegate, id, streamId, this.producerReferenceTime, this.report, this.feed, admission?.serve) + const stream = new CameraRecordingStream(connection, this.delegate, id, streamId, this.producerReferenceTime, this.report, this.feed, admission) // 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. @@ -867,7 +871,9 @@ export class RecordingManagement { * 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. + * whole number. The gate's refusals and the size's are each told as the camera's `snapshot-refused` event before the open is answered, the gate telling + * its own and the size's going through the capability's route, while a held stream ID is a clash of the data stream's own and tells none. Otherwise a + * snapshot stream joins the route, answers the open and sends the picture its fetch brings. */ private handleSnapshotOpen( connection: DataStreamConnection, @@ -925,6 +931,7 @@ export class RecordingManagement { sentence: `[HDS ${connection.remoteAddress}] Rejecting DATA_SEND OPEN of snapshot stream ${streamId} as it names no valid picture size.`, streamId, })) + snapshot.sizeRefused(reason) connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { status: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, }) @@ -1513,8 +1520,9 @@ class CameraRecordingStream extends EventEmitter { // Where the guarded call of the delegate at the stream's close reports its failure, its management's. private readonly report: DelegateFailureReport - // The serving function of the recorder's admission on a camera with the capabilities block, which the stream calls in place of the delegate's request. - private readonly serve?: Extract['serve'] + // The recorder's admission on a camera with the capabilities block: its serving function, which the stream calls in place of the delegate's request, and + // its route of the hub's close, which takes the hub's own close in place of the delegate's closeRecordingStream. + private readonly admission?: Extract constructor( connection: DataStreamConnection, @@ -1524,7 +1532,7 @@ class CameraRecordingStream extends EventEmitter { producerReferenceTime: boolean, report: DelegateFailureReport, feed?: ServedRecordings, - serve?: Extract['serve'], + admission?: Extract, ) { super() this.connection = connection @@ -1532,7 +1540,7 @@ class CameraRecordingStream extends EventEmitter { this.hdsRequestId = requestId this.streamId = streamId this.report = report - this.serve = serve + this.admission = admission if (producerReferenceTime) { this.writer = new ProducerReferenceTimeWriter() @@ -1583,15 +1591,15 @@ class CameraRecordingStream extends EventEmitter { this.loop = new AbortController() this.stack.defer(() => this.loop?.abort()) - const recording = holdRecording(this.serve - ? this.serve(this.loop.signal) + const recording = holdRecording(this.admission + ? this.admission.serve(this.loop.signal) : this.delegate.handleRecordingStreamRequest(this.streamId, this.loop.signal)) this.iterator = recording.iterator // The wall clock each packet's first picture is stamped at, which the writer anchors the recording at: on the serve path the time the recorder's own // packet says its first picture was taken, and the moment a delegate's packet is written, whatever members a plugin's own object carries. - const clockOf: (packet: RecorderPacket) => number = this.serve === undefined + const clockOf: (packet: RecorderPacket) => number = this.admission === undefined ? () => Date.now() : packet => packet.wallClock ?? Date.now() @@ -1745,7 +1753,13 @@ class CameraRecordingStream extends EventEmitter { ? HDSProtocolSpecificErrorReason[reason] : reason) - this.handleClosed(() => this.delegate.closeRecordingStream(this.streamId, reason)) + // On the serve path the hub's own close takes the admission's route, which tells the recording's end the reason the hub named, while the library's own + // closes and the connection's reach the delegate's closeRecordingStream as on every other path. + const { admission } = this + + this.handleClosed(admission === undefined + ? () => this.delegate.closeRecordingStream(this.streamId, reason) + : () => admission.hubClosed(reason)) } // The close of the stream's connection, which its route hands each stream it holds. diff --git a/src/lib/camera/StreamingOptions.spec.ts b/src/lib/camera/StreamingOptions.spec.ts index 3f9c67e8a..ac1b6ece8 100644 --- a/src/lib/camera/StreamingOptions.spec.ts +++ b/src/lib/camera/StreamingOptions.spec.ts @@ -1,4 +1,4 @@ -import type { CameraCapabilitiesOptions, CameraControllerOptions } from '../controller/index.js' +import type { CameraBufferRecordingOptions, CameraCapabilitiesOptions, CameraControllerOptions } from '../controller/index.js' import type { CameraVideoSensor, CameraVideoTier, MultiTierStreamingOptions } from './StreamingOptions.js' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -51,28 +51,22 @@ function sourced(sensor: CameraVideoSensor, source: CameraVideoSensor['audio'][' } } -// A sensor marked recorded on the tier of the identifier given. -function recordedOn(sensor: CameraVideoSensor, tierId: number): CameraVideoSensor { - return { - ...sensor, - tiers: sensor.tiers.map(tier => ({ ...tier, recorded: tier.id === tierId })), - } -} - // The second sensor advertising its tiers smallest first, its identifiers reversed: its best tier is its last, tier 3. const SMALLEST_FIRST: CameraVideoSensor = { ...SENSOR_B, tiers: SENSOR_B.tiers.map(tier => ({ ...tier, id: 4 - tier.id })).reverse(), } -/* The cases of a sensor's sound, each named short enough to print whole in a title: the sensors a camera states, the one whose tier set a row reads, by its - * index, the source and the sound tier the options boundary settles on that set, and the tiers whose settled entry reads that their stream must carry the - * sensor's sound. A lesser tier is one that is not its sensor's best. The case of a sensor that is not the recorded sensor marks the first sensor recorded - * on its tier 2, which means the second sensor's best tier is neither its first nor the one whose identifier the recorded tier carries. +/* The cases of a sensor's sound, each named short enough to print whole in a title: the sensors a camera states, the recording option naming its recorded + * tier, if any, the one whose tier set a row reads, by its index, the source and the sound tier the options boundary settles on that set, and the tiers + * whose settled entry reads that their stream must carry the sensor's sound. A lesser tier is one that is not its sensor's best. The case of a sensor that + * is not the recorded sensor records the first sensor's tier 2, which means the second sensor's best tier is neither its first nor the one whose + * identifier the recorded tier carries. */ const SOUND_CASES: { readonly name: string readonly sensors: CameraVideoSensor[] + readonly recording?: CameraBufferRecordingOptions readonly read: number readonly audioSource: 'shared' | 'tier' readonly soundTierId: number @@ -98,7 +92,7 @@ const SOUND_CASES: { }, { audioSource: 'shared', - name: 'is shared and recorded, none marked', + name: 'is shared and recorded by default', read: 0, sensors: [ sourced(SENSOR_A, 'shared'), @@ -108,10 +102,11 @@ const SOUND_CASES: { }, { audioSource: 'shared', - name: 'is shared and marked on a lesser tier', + name: 'is shared and recorded on a lesser tier', read: 0, + recording: { tierId: 2 }, sensors: [ - recordedOn(sourced(SENSOR_A, 'shared'), 2), + sourced(SENSOR_A, 'shared'), ], soundTierId: 2, sounding: [2], @@ -120,8 +115,9 @@ const SOUND_CASES: { audioSource: 'shared', name: 'is shared and not the recorded sensor', read: 1, + recording: { sensorUUID: SENSOR_A.uuid, tierId: 2 }, sensors: [ - recordedOn(SENSOR_A, 2), + SENSOR_A, sourced(SMALLEST_FIRST, 'shared'), ], soundTierId: 3, @@ -129,10 +125,11 @@ const SOUND_CASES: { }, { audioSource: 'tier', - name: 'states \'tier\', marked on a lesser tier', + name: 'states \'tier\', recorded on a lesser tier', read: 0, + recording: { tierId: 2 }, sensors: [ - recordedOn(sourced(SENSOR_A, 'tier'), 2), + sourced(SENSOR_A, 'tier'), ], soundTierId: 1, sounding: [1, 2, 3], @@ -425,11 +422,6 @@ describe('multi-tier streaming options', () => { it('refuses each entry the boundary cannot state with a TypeError naming its member, warning nothing, a UUID that is no UUID ahead of every other', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) const a = 'a1b2c3d4-0000-4000-8000-000000000001' - const b = 'b0000002-0000-4000-8000-000000000002' - const recordedFirst = (sensor: CameraVideoSensor): CameraVideoSensor => ({ - ...sensor, - tiers: sensor.tiers.map(tier => ({ ...tier, recorded: tier.id === 1 })), - }) const unencodable = tiersWith(tiers => tiers.map(tier => ({ ...tier, frameRate: 300 }))) const cases: [CameraVideoSensor[], string][] = [ [ @@ -453,13 +445,6 @@ describe('multi-tier streaming options', () => { ], `The video sensor "${a}" has two tiers with the id 1.`, ], - [ - [ - recordedFirst(SENSOR_A), - recordedFirst(SENSOR_B), - ], - `The tier 1 of the video sensor "${b}" is marked recorded beside the tier 1 of the video sensor "${a}", but a camera records one tier.`, - ], [ [ tiersWith(tiers => tiers.map(tier => ({ ...tier, peakBitrate: tier.bitrate - 100 }))), @@ -478,12 +463,6 @@ describe('multi-tier streaming options', () => { ], `The keepRunning of the tier 1 of the video sensor "${a}" is not a boolean.`, ], - [ - [ - tiersWith(tiers => tiers.map(tier => ({ ...tier, recorded: 1 as unknown as boolean }))), - ], - `The recorded of the tier 1 of the video sensor "${a}" is not a boolean.`, - ], [ [ { ...SENSOR_A, audio: undefined as unknown as CameraVideoSensor['audio'] }, @@ -553,14 +532,36 @@ describe('multi-tier streaming options', () => { expect(warn).not.toHaveBeenCalled() }) - it.each(SOUND_CASES)('settles on its tier set the source and the sound tier of a sensor that $name', ({ audioSource, read, sensors, soundTierId }) => { - const { tierSets } = validateVideoSensors(sensors, idleStreaming(), false) + it('reads nothing of a recorded member a JavaScript plugin gives its tiers, two marked true and one marked 1, and records the default tier', () => { + // An untyped caller can still write the member on its tiers, none of them the first sensor's best. + const marked = (sensor: CameraVideoSensor, marks: Record): CameraVideoSensor => ({ + ...sensor, + tiers: sensor.tiers.map(tier => (tier.id in marks) + ? { ...tier, recorded: marks[tier.id] } as CameraVideoTier + : tier), + }) + const sensors = [ + marked(SENSOR_A, { 2: true, 3: true }), + marked(SENSOR_B, { 1: 1 }), + ] + + expect(() => new CameraController(withCapabilities(sensors))).not.toThrow() + expect(validateVideoSensors(sensors, idleStreaming(), false).recorded).toEqual({ sensorUUID: SENSOR_A.uuid, tierId: 1 }) + }) + + it.each(SOUND_CASES)('settles on its tier set the source and the sound tier of a sensor that $name', ({ audioSource, read, recording, sensors, soundTierId }) => { + const { tierSets } = validateVideoSensors(sensors, idleStreaming(), false, recording) expect({ audioSource: tierSets[read].audioSource, soundTierId: tierSets[read].soundTierId }).toEqual({ audioSource, soundTierId }) }) - it.each(SOUND_CASES)('freezes on each settled entry of a sensor that $name whether its stream must carry the sensor\'s sound', ({ read, sensors, sounding }) => { - const { tiers } = validateVideoSensors(sensors, idleStreaming(), false).tierSets[read] + it.each(SOUND_CASES)('freezes on each settled entry of a sensor that $name whether its stream must carry the sensor\'s sound', ({ + read, + recording, + sensors, + sounding, + }) => { + const { tiers } = validateVideoSensors(sensors, idleStreaming(), false, recording).tierSets[read] const entries = Array.from(tiers.values(), entry => ({ frozen: Object.isFrozen(entry), sound: entry.sound, @@ -678,19 +679,24 @@ describe('multi-tier streaming options', () => { + 'and writes no minimum', () => { const lines = captureDebug('HAP-NodeJS:Camera:Controller') const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const construct = (strict: boolean) => (): CameraController => new CameraController(capabilitiesCameraOptions({ - recording: { prebuffer: -1 }, + const construct = (strict: boolean, prebuffer: number | null = -1) => (): CameraController => new CameraController(capabilitiesCameraOptions({ + // An untyped caller alone can state a prebuffer of null. + recording: { prebuffer: prebuffer as number }, streaming: idleStreaming(), strict, videoSensors: [ tiersWith(tiers => tiers.slice(0, 2)), ], })) - const refusal = new TypeError('The prebuffer of the camera capabilities block\'s recording option, -1, is not a whole number of milliseconds from 0 to ' + const refusal = new TypeError('The prebuffer of the camera capabilities block\'s recording option, -1, is not a whole number of milliseconds from 1 to ' + '30000.') + const nullRefusal = new TypeError('The prebuffer of the camera capabilities block\'s recording option, null, is not a whole number of milliseconds from 1 ' + + 'to 30000.') expect(construct(false)).toThrow(refusal) expect(construct(true)).toThrow(refusal) + expect(construct(false, null)).toThrow(nullRefusal) + expect(construct(true, null)).toThrow(nullRefusal) expect(lines).toEqual([]) expect(warn).not.toHaveBeenCalled() }) diff --git a/src/lib/camera/StreamingOptions.ts b/src/lib/camera/StreamingOptions.ts index 57028e30d..891fd710d 100644 --- a/src/lib/camera/StreamingOptions.ts +++ b/src/lib/camera/StreamingOptions.ts @@ -1,5 +1,6 @@ import type { Buffer } from 'node:buffer' +import type { CameraBufferRecordingOptions } from '../controller/index.js' import type { CameraSensorIntent, CameraVideoStreamCapabilities, SensorConfiguration, SensorDimensions } from './capabilities/cameraSensors.js' import type { SupportedAudioStreamTiersPayload, SupportedVideoStreamTiersPayload, VideoStreamTier } from './capabilities/streamTiers.js' import type { MotionZones } from './MotionZonesManagement.js' @@ -121,6 +122,16 @@ export interface ResourceScope { defer(release: () => unknown): void } +/** + * Why the library asked for a tier's stream, which the stream's {@link TierStream.reason} carries: `'view'` where a live view at home or from away asked; + * `'recording'` where a hub's recording asked, which only a camera that records on demand states; and `'keepRunning'` where nobody asked and the library + * keeps the stream running, for a tier the plugin marked {@link CameraVideoTier.keepRunning} or for the recorded tier of a camera that records with a + * prebuffer. + * + * @group Camera + */ +export type TierDemandReason = 'keepRunning' | 'recording' | 'view' + /** * The handle a plugin writes one video tier's stream through, valid from the tier's `tierDemandStarted` to the demand's end, where the library releases * what was registered on it, as {@link ResourceScope} sets out, after which a write is ignored. The stream carries its tier, the video tier its encoding is @@ -136,27 +147,35 @@ export interface ResourceScope { * A stream states when its pictures were taken with a `prft` box in front of a `moof`: the box's NTP time stands at its media time, a presentation time * on the track it names, and states the wall clock of that fragment's pictures and sound, which a recording of the tier is stamped from. A box states * the clock of the fragment it stands in front of and of no other: a stream that states its times carries one in front of every fragment, and a - * fragment with none in front of it, as every fragment of a stream that carries none, is stamped from the moment each picture arrived. The library takes - * a stated time as it stands, with no check against its own clock: keeping the stream's clock true is the plugin's. A box the library cannot read states - * nothing and fails nothing. From ffmpeg, `-write_prft wallclock` writes the box in front of every fragment from the computer's clock, and - * `-write_prft pts` states the stream's own times as a date in 1970, which dates every recording there. + * fragment with none in front of it, as every fragment of a stream that carries none, is stamped from the moment each picture arrived. The library dates + * a recording by a stated time as it stands, and keeping the stream's clock true is the plugin's. It reads a stated time against its own clock for one + * purpose alone, to tell an on-demand recording's lead-up from live video: on a stream whose {@link TierStream.reason} reads `'recording'`, video and + * sound stated before the start and handed over within 10 seconds of the stream's first sample are lead-up, and so is every sound in a fragment that + * states no time handed over within those 10 seconds, until the stream's first video that is no lead-up, which means a stream's sound that states no + * time, written ahead of its first picture, is kept from the viewers of an on-demand recording's start. A stream stated behind the computer's clock + * therefore holds its live video back from those viewers for up to the same 10 seconds, and then until the stream's next keyframe, and a plugin hands its + * whole lead-up over within 10 seconds of its stream's first bytes. A box the library cannot read states nothing and fails nothing. From ffmpeg, + * `-write_prft wallclock` writes the box in front of every fragment from the computer's clock, and `-write_prft pts` states the stream's own times as a + * date in 1970, which dates every recording there. * * The library reads the stream as it arrives, with nothing decoded, and makes every RTP packet an RTP session is sent: it times the picture and the sound * on one run of times, every tier of a video sensor on the sensor's one clock, puts the initialization segment's parameter sets in each picture keyframe * it sends that holds fewer than each of HEVC's video, sequence and picture parameter sets, after its access unit delimiter or at its front, sends one - * that holds each of them as its sample's octets, and cuts each sample into the tier's packets and numbers them. A run opens at its first sample, picture - * or sound, from that sample's decode time, and places each sample at its presentation time's distance from that decode time, picture and sound each at - * its own rate, and the distance between them is the stream's own; a sound timed before that decode time is dropped and counted. A run ends at a - * discontinuity, at an initialization segment and at a sample timed more than a second ahead of where the one before it of its track and the time since - * that one arrived put it, with no discontinuity marked, and the next sample opens a later run for picture and sound alike. A viewer at home takes its - * sound from the tier it started where that tier's `sound` reads true, and otherwise from the sensor's sound tier, which it joins for its sound alone, - * and a viewer from away takes its sound from the sensor's sound tier, as {@link CameraAudioTier.source} sets out. + * that holds each of them as its sample's octets, and cuts each sample into the tier's packets and numbers them. A run opens at the first sample the pacer + * sends, picture or sound, which a recording's lead-up never is, from that sample's decode time, and places each sample at its presentation time's + * distance from that decode time, picture and sound each at its own rate, and the distance between them is the stream's own; a sound timed before that + * decode time is dropped and counted. A run ends at a discontinuity, at an initialization segment and at a sample timed more than a second ahead of where + * the one before it of its track and the time since that one arrived put it, with no discontinuity marked, and the next sample opens a later run for + * picture and sound alike. A viewer at home takes its sound from the tier it started where that tier's `sound` reads true, and otherwise from the + * sensor's sound tier, which it joins for its sound alone, and a viewer from away takes its sound from the sensor's sound tier, as + * {@link CameraAudioTier.source} sets out. * - * The tier has one pacer for every viewer, at home and from away. The library keeps each sample in the tier's camera buffer as it arrives, and the pacer - * releases it at the moment it falls due on one schedule, read from the stream's own times and the moments its fragments arrived, as `write` sets out: to - * every viewer joined then, or to none, a picture to no viewer of the live pictures still waiting for a keyframe, as the paragraph below sets out. A - * fragment is paced from its last byte: the stream's fragment length sets the delay a viewer sees and how many frames the library holds while it paces - * them alike, and a plugin that wants a short delay writes short fragments, a frame's length the shortest. + * The tier has one pacer for every viewer, at home and from away. The library keeps each sample in the tier's camera buffer as it arrives, a recording's + * lead-up among them, which it keeps for the recording and sends to no viewer, and the pacer releases every other sample at the moment it falls due on one + * schedule, read from the stream's own times and the moments its fragments arrived, as `write` sets out: to every viewer joined then, or to none, a + * picture to no viewer of the live pictures still waiting for a keyframe, as the paragraph below sets out. A fragment is paced from its last byte: the + * stream's fragment length sets the delay a viewer sees and how many frames the library holds while it paces them alike, and a plugin that wants a short + * delay writes short fragments, a frame's length the shortest. * * A view opens from the camera buffer. A viewer that joins a tier whose buffer keeps a picture keyframe the pacer has released is handed the pictures * from the latest such keyframe on, on timestamps that begin past every timestamp the tier has sent and run at many times the stream's speed, lower for a @@ -192,27 +211,36 @@ export interface ResourceScope { export interface TierStream extends ResourceScope { /** * The video tier the stream is for, its sensor's entry as the camera settled it and froze: its peak at its default where the entry gives none, its - * `keepRunning` and `recorded` marks as booleans, `recorded` true on the tier the camera records, its sensor's UUID in lowercase, and `sound`, true on a - * tier whose stream must carry the sensor's sound: every tier where the sensor's audio states its {@link CameraAudioTier.source} `'tier'` or states none, - * and the sound's tier alone where it states `'shared'`, which is how a plugin reads at a start whether to encode Opus for the stream. Every demand of one tier - * carries the same object. + * `keepRunning` mark as a boolean, `recorded`, true on the tier the camera records, the one the camera capabilities block's `recording` option names or + * by default the first sensor's best tier, its sensor's UUID in lowercase, and `sound`, true on a tier whose stream must carry the sensor's sound: every + * tier where the sensor's audio states its {@link CameraAudioTier.source} `'tier'` or states none, and the sound's tier alone where it states `'shared'`, + * which is how a plugin reads at a start whether to encode Opus for the stream. Every demand of one tier carries the same object. */ - readonly tier: Readonly> & { readonly sensorUUID: string, readonly sound: boolean } + readonly tier: Readonly> & { readonly recorded: boolean, readonly sensorUUID: string, readonly sound: boolean } + /** + * Why the tier's demand was raised, read once as it was raised and left as it is while other joiners come and go: a stream a view raised reads + * `'view'` whoever joins its tier later. A camera that records with a prebuffer has its recorded tier's stream read `'keepRunning'` at every start, and + * a camera that records on demand has it read `'recording'` at each start the library makes while it holds the tier for recording, whether or not the + * plugin also marked the tier `keepRunning`. A plugin writes a recording's lead-up, video and sound from before the start that its source kept, only on a stream + * that reads `'recording'`, as {@link TierStream} sets out: lead-up written on any other stream is live video to its viewers. + */ + readonly reason: TierDemandReason /** * Writes the stream's next bytes, which may end anywhere in a box. The library keeps each sample in the tier's camera buffer as the write completes its * octets and those of every sample the stream places before it, and the tier's one pacer sends it to every consumer of the tier later, a picture to none * still waiting for a keyframe, in a turn of its own and never inside this call: a fragment once its last byte is written, its first picture held to the * lateness the stream's recent fragments arrived at, by at most 200 milliseconds, and each later sample at its decode time's distance from that picture. - * A plugin writes each fragment as it has it and the library sends every viewer one steady schedule. A chunk belongs to the library once written: the - * plugin never changes or reuses it, since the library may keep a view of it. A sample whose octets the library cannot send, a picture whose lengths do - * not tile it or a sound of no octets, is dropped and counted and reaches no consumer. A sound too long for one packet is dropped and counted as it is - * cut for the sessions at home alone, and still reaches every other consumer. A picture keyframe whose sample and initialization segment lack HEVC's - * video, sequence or picture parameter set between them is sent as it stands, with one `stream-fault` problem for such a keyframe. Bytes the library - * cannot read, a sample whose decode time does not rise past the one before it in its track since the stream's last initialization segment or - * discontinuity, a stream whose initialization segment holds no video track, and a silence, no picture within the bounds - * {@link MultiTierStreamingDelegate.tierDemandStarted} sets out whatever sound is written, fail the tier with a `stream-failed` problem saying what was - * wrong, as {@link TierStream.fail} does, after which nothing more of the stream is sent and every chunk is ignored. A version 0 `tfdt`'s 32-bit decode - * time that wraps to zero past its last value is no step back: the stream's decode times carry on past the wrap. + * A recording's lead-up is kept for the recording and sent to no viewer. A plugin writes each fragment as it has it and the library sends every viewer + * one steady schedule. A chunk belongs to the library once written: the plugin never changes or reuses it, since the library may keep a view of it. A + * sample whose octets the library cannot send, a picture whose lengths do not tile it or a sound of no octets, is dropped and counted and reaches no + * consumer. A sound too long for one packet is dropped and counted as it is cut for the sessions at home alone, and still reaches every other + * consumer. A picture keyframe whose sample and initialization segment lack HEVC's video, sequence or picture parameter set between them is sent as it + * stands, with one `stream-fault` problem for such a keyframe. Bytes the library cannot read, a sample whose decode time does not rise past the one + * before it in its track since the stream's last initialization segment or discontinuity, a stream whose initialization segment holds no video track, + * and a silence, no picture within the bounds {@link MultiTierStreamingDelegate.tierDemandStarted} sets out whatever sound is written, fail the tier + * with a `stream-failed` problem saying what was wrong, as {@link TierStream.fail} does, after which nothing more of the stream is sent and every chunk + * is ignored. A version 0 `tfdt`'s 32-bit decode time that wraps to zero past its last value is no step back: the stream's decode times carry on past + * the wrap. * @param chunk - The bytes. */ write(chunk: Buffer): void @@ -301,11 +329,13 @@ export interface TalkbackSink { * * A tier's joiners are the viewers at home and from away, which the tier's one pacer sends the stream to, and the library itself, which holds a tier * with no viewer while the camera is in service, its accessory published and its source not stated away: the recorded tier while the user's switch - * allows recording, and each tier marked {@link CameraVideoTier.keepRunning} while the user's switch allows streaming. An opening needs the tier's stream - * already running, its frames since its latest keyframe kept in its camera buffer: a view starts at once on a tier the library holds, while the first - * viewer of any other tier waits for that tier's stream to start and bring its first keyframe. A plugin marks a tier `keepRunning` when its views - * should start at once, at the cost of that tier's encoding running while nobody watches, and leaves unmarked a tier whose encoding costs too much to run - * unwatched. + * allows recording in the prebuffered mode, and from a hub's recording open while a recording is open or motion is detected in the on-demand mode, and + * each tier marked {@link CameraVideoTier.keepRunning} while the user's switch allows streaming. A stream's {@link TierStream.reason} names which of them + * raised its demand. An opening needs the tier's stream already running, its frames since its latest keyframe kept in its camera buffer: a view starts + * at once on a tier the library holds, but where that tier holds a recording's lead-up and no live keyframe yet, the view waits for the first live + * keyframe, while the first viewer of any other tier waits for that tier's stream to start and bring its first keyframe. A plugin marks a tier + * `keepRunning` when its views should start at once, at the cost of that tier's encoding running while nobody watches, and leaves unmarked a tier whose + * encoding costs too much to run unwatched. * * Each tier's encoding is expected to stay within the bitrates the tier advertises. A heavier stream is accepted and never refused, at the cost * {@link TierStream} sets out for the views on it. @@ -314,14 +344,15 @@ export interface TalkbackSink { */ export interface MultiTierStreamingDelegate { /** - * Called when a video tier gains its first joiner, its demand carrying the tier's picture and the sound that comes in its stream. A consumer joins a tier - * in one step: one of the picture that finds a keyframe the tier's pacer has released in the tier's camera buffer is handed the pictures from the latest - * such keyframe on and then each picture the pacer releases, and any other is sent each sample the pacer releases from its join on, a picture from the - * next keyframe, as {@link TierStream} sets out. A stream written inside the call reaches every consumer joined by the time it is released, the one - * whose join raised the demand among them, an RTP session whose Start raised it too. A rejection of the promise refuses the demand: each join waiting on - * it is refused, an RTP session's Start as busy, the stream ignores every write and what the start registered on it is released. A start not settled - * within 30 seconds of its call, whoever joined the tier since, is withdrawn: its signal is aborted and every join waiting on it is refused, an RTP - * session's Start as busy, as at a rejection. + * Called when a video tier gains its first joiner, which the stream's {@link TierStream.reason} names, its demand carrying the tier's picture and the + * sound that comes in its stream. A consumer joins a tier in one step: one of the picture that finds a keyframe the tier's pacer has released in the + * tier's camera buffer is handed the pictures from the latest such keyframe on and then each picture the pacer releases, and any other is sent each + * sample the pacer releases from its join on, a picture from the next keyframe, as {@link TierStream} sets out. A stream written inside the call reaches + * every consumer joined by the time it is released, the one whose join raised the demand among them, an RTP session whose Start raised it too, but for + * a recording's lead-up, which the recording alone reads. A rejection of the promise refuses the demand: each join waiting on it is refused, an RTP + * session's Start as busy, the stream ignores every write and what the start registered on it is released. A start not settled within 30 seconds of + * its call, whoever joined the tier since, is withdrawn: its signal is aborted and every join waiting on it is refused, an RTP session's Start as busy, + * as at a rejection. * * A started stream is held to its silence bounds, whoever joined the tier: its first picture within 30 seconds of the start's settling, a picture written * inside the call counting, and each later picture within 10 seconds of the one before. Sound counts for neither. A stream that misses a bound fails @@ -484,16 +515,12 @@ export interface CameraVideoTier { peakBitrate?: number /** * Whether the library holds the tier while the user's switch allows streaming and the camera is in service, its accessory published and its source - * not stated away, raising its demand through `tierDemandStarted` with no viewer and asking for it again after a failure, as it holds the recorded tier - * while the user's switch allows recording and the camera is in service. A tier left unmarked is raised only on demand. `false` by default. + * not stated away, raising its demand through `tierDemandStarted` with no viewer, its stream's {@link TierStream.reason} reading `'keepRunning'` unless + * a recording on demand holds the tier too, and asking for it again after a failure, as it holds the recorded tier in the prebuffered mode while the + * user's switch allows recording and the camera is in service. A recorded tier marked in the on-demand mode serves a hub's recording at once from its + * latest keyframe. A tier left unmarked is raised only on demand. `false` by default. */ keepRunning?: boolean - /** - * Whether the camera records the tier from its camera buffer, for one tier of the camera at most: by default the first sensor's best tier, the one with - * the most pixels, the higher bitrate deciding between two of one size. `false` by default. The camera controller's constructor throws a `TypeError` for - * a second tier marked. - */ - recorded?: boolean } /** @@ -619,9 +646,9 @@ export interface SensorStreamTiers { */ soundTierId: number /** - * Each video tier's entry by its identifier, settled and frozen: its peak at its default where none is given, `keepRunning` and `recorded` as booleans, - * `recorded` true on the tier the camera records whether marked or by default, the sensor's UUID in lowercase, and `sound`, true on a tier whose stream - * must carry the sensor's sound, every tier under `'tier'` and the sound's tier alone under `'shared'`. + * Each video tier's entry by its identifier, settled and frozen: its peak at its default where none is given, `keepRunning` as a boolean, `recorded` + * true on the tier the camera records, the one the block's recording option names or by default the first sensor's best tier, the sensor's UUID in + * lowercase, and `sound`, true on a tier whose stream must carry the sensor's sound, every tier under `'tier'` and the sound's tier alone under `'shared'`. */ tiers: ReadonlyMap /** @@ -716,7 +743,8 @@ export interface CameraSnapshotRequest { */ readonly sensorUUID: string /** - * The newest keyframe of that sensor's best running tier, as the camera controller's `latestKeyframe` answers it, where the library holds one. + * The newest keyframe of that sensor's best running tier, as the camera controller's `latestKeyframe` answers it, where the library holds one: none + * from a tier for as long as its newest keyframe is a recording's lead-up, which lasts past the lead-up's end until the tier's first live keyframe. */ readonly keyframe?: CameraKeyframe } @@ -762,7 +790,8 @@ export interface ValidatedVideoSensors { */ readonly motionZones: ReadonlyMap> /** - * The recorded sensor, by its UUID in lowercase, and its recorded tier: the tier marked recorded, or the first sensor's best tier. + * The recorded sensor, by its UUID in lowercase, and its recorded tier: the sensor and tier the block's recording option names, the first sensor where + * it names none and that sensor's best tier where it names no tier. */ readonly recorded: { readonly sensorUUID: string, readonly tierId: number } /** @@ -834,9 +863,8 @@ function defaultPeak(tier: CameraVideoTier): number { /* The refusals of one sensor's entry the stream tier codec cannot make for itself, each a TypeError naming its member: tiers missing or empty, audio or its * bitrate missing, an audio source that is neither 'shared' nor 'tier', dimensions that are no object, a motionZones that is no function, an intent that is - * no sensor intent, a tier that is no object, named by its index, two tiers sharing an identifier, a quality that is no video quality, a keepRunning or a - * recorded that is no boolean and a peak below its bitrate. The sensor's UUID was refused already where it is no UUID, and each sentence names it in - * lowercase. + * no sensor intent, a tier that is no object, named by its index, two tiers sharing an identifier, a quality that is no video quality, a keepRunning + * that is no boolean and a peak below its bitrate. The sensor's UUID was refused already where it is no UUID, and each sentence names it in lowercase. */ function refuseSensor(sensor: CameraVideoSensor): void { const sensorUUID = sensor.uuid.toLowerCase() @@ -887,10 +915,8 @@ function refuseSensor(sensor: CameraVideoSensor): void { throw new TypeError(`The quality of the tier ${tier.id} of the video sensor "${sensorUUID}", ${String(tier.quality)}, is not a video quality.`) } - for (const mark of ['keepRunning', 'recorded'] as const) { - if ((tier[mark] !== undefined) && (typeof tier[mark] !== 'boolean')) { - throw new TypeError(`The ${mark} of the tier ${tier.id} of the video sensor "${sensorUUID}" is not a boolean.`) - } + if ((tier.keepRunning !== undefined) && (typeof tier.keepRunning !== 'boolean')) { + throw new TypeError(`The keepRunning of the tier ${tier.id} of the video sensor "${sensorUUID}" is not a boolean.`) } if ((tier.peakBitrate !== undefined) && (tier.peakBitrate < tier.bitrate)) { @@ -926,8 +952,8 @@ export function validateSensorUUIDs(sensorUUIDs: readonly string[]): void { /** * The best of a sensor's video tiers as they are advertised: the one with the most pixels, the higher target bitrate deciding between two of one size, and * the earlier advertised between two alike in size and bitrate. It is the sensor's sound tier, which a view from away takes its sound from, unless the - * sensor's audio states its source `'shared'` and the sensor holds the camera's recorded tier, and a camera records the first sensor's unless its plugin - * marks a tier recorded. + * sensor's audio states its source `'shared'` and the sensor holds the camera's recorded tier, and a camera records the first sensor's unless the camera + * capabilities block's `recording` option names another tier. * @param tiers - The sensor's video tiers, in the order they are advertised. * @returns The best tier, or `undefined` for a sensor that offers none. */ @@ -959,10 +985,16 @@ export function bestStreamTier(tiers: Iterable): VideoStreamTie * @param streaming - The block's multi-tier streaming, whose session bound is defaulted and validated here. * @param strict - Whether the camera was given strict, which each tier set carries, which means a running stream past twice its tier's peak raises a `stream-fault` * problem under it. Under it, the camera controller throws a specification minimum rather than writing a debug event. + * @param recording - The block's recording option, which names the recorded sensor and tier, absent where the block gives none. * @returns The configurations, the tier sets, the zones functions, the recorded tier, the session bound and the sentence of each minimum the * configuration falls below, each sensor in the plugin's order. */ -export function validateVideoSensors(sensors: readonly CameraVideoSensor[], streaming: MultiTierStreamingOptions, strict: boolean): ValidatedVideoSensors { +export function validateVideoSensors( + sensors: readonly CameraVideoSensor[], + streaming: MultiTierStreamingOptions, + strict: boolean, + recording?: CameraBufferRecordingOptions, +): ValidatedVideoSensors { // The block's shape is refused before any entry is read, since an untyped caller can give any value. A refusal names the member rather than a property // read that fails on it. if (!Array.isArray(sensors as unknown)) { @@ -1042,17 +1074,40 @@ export function validateVideoSensors(sensors: readonly CameraVideoSensor[], stre } }) - // One tier of the camera at most is marked recorded, and with none the first sensor's best tier is. - const marked = built.flatMap(({ sensor, sensorUUID }) => sensor.tiers.filter(tier => tier.recorded === true).map(tier => ({ sensorUUID, tierId: tier.id }))) + /* The recorded tier is the one the block's recording option names: its sensor, the first where it names none and read in lowercase as every sensor's + * UUID is, and that sensor's tier, its best where it names none. An untyped caller can give any value, which is why the option's shape is refused before + * a member is read, and a sensor named by anything but a string is refused as one the block does not list. + */ + if ((recording !== undefined) && ((typeof recording !== 'object') || (recording === null))) { + throw new TypeError('The recording option of the camera capabilities block is not an object.') + } + + const { sensorUUID: namedSensor, tierId: namedTier } = recording ?? {} + const recordedSensor = (namedSensor === undefined) + ? built[0] + : built.find(({ sensorUUID }) => (typeof namedSensor === 'string') && (sensorUUID === namedSensor.toLowerCase())) - if (marked.length > 1) { - const [first, second] = marked + if (recordedSensor === undefined) { + const shown = (typeof namedSensor === 'string') + ? namedSensor.toLowerCase() + : String(namedSensor) - throw new TypeError(`The tier ${second.tierId} of the video sensor "${second.sensorUUID}" is marked recorded beside the tier ${first.tierId} of the ` - + `video sensor "${first.sensorUUID}", but a camera records one tier.`) + throw new TypeError(`The recording option of the camera capabilities block names the video sensor "${shown}", which the block does not list.`) } - const recorded = marked[0] ?? { sensorUUID: built[0].sensorUUID, tierId: bestStreamTier(built[0].videoStreamTiers.tiers)!.identifier } + if ((namedTier !== undefined) && !recordedSensor.sensor.tiers.some(tier => tier.id === namedTier)) { + const shown = (typeof namedTier === 'number') + ? String(namedTier) + : `"${String(namedTier)}"` + + throw new TypeError(`The recording option of the camera capabilities block names the tier ${shown} of the video sensor "${recordedSensor.sensorUUID}", ` + + 'which that sensor does not list.') + } + + const recorded = { + sensorUUID: recordedSensor.sensorUUID, + tierId: namedTier ?? bestStreamTier(recordedSensor.videoStreamTiers.tiers)!.identifier, + } const configurations: SensorConfiguration[] = [] const tierSets: SensorStreamTiers[] = [] const motionZones = new Map>() diff --git a/src/lib/camera/TierPacer.spec.ts b/src/lib/camera/TierPacer.spec.ts index f7c35f80c..7d8a87b71 100644 --- a/src/lib/camera/TierPacer.spec.ts +++ b/src/lib/camera/TierPacer.spec.ts @@ -1,11 +1,11 @@ import type { Mock, MockInstance } from 'vitest' -import type { ScriptedTierDelegate } from '../../test-utils/cameraFixtures.js' +import type { FrameOptions, ScriptedTierDelegate } from '../../test-utils/cameraFixtures.js' import type { Deferred } from '../../test-utils/settle.js' import type { CameraReporter } from './diagnostics/CameraReporter.js' import type { CameraProblem } from './diagnostics/problems.js' import type { Mp4StreamSample } from './mp4/Mp4StreamReader.js' -import type { CameraKeyframe, MultiTierStreamingDelegate, SensorStreamTiers, StreamTierMedium, TierStream } from './StreamingOptions.js' +import type { CameraKeyframe, MultiTierStreamingDelegate, SensorStreamTiers, StreamTierMedium, TierDemandReason, TierStream } from './StreamingOptions.js' import type { KeyframeAnswer, PacketConsumer, StartAnswer, Tier, TierDemand, TierHold, TierHolder } from './TierTable.js' import { Buffer } from 'node:buffer' @@ -17,6 +17,7 @@ import { disposedOf, endsOf, FIRST_VIDEO_SENSOR, + frames, openingStamp, pendingStart, scriptedTierDelegate, @@ -36,6 +37,7 @@ import { } from '../../test-utils/mp4Fixtures.js' import { detachedReporter, problemsOf } from '../../test-utils/reporterFixtures.js' import { deferred, fakeTimeoutSignals, settle } from '../../test-utils/settle.js' +import { ntpTime } from '../util/ntp.js' import { TierBuffer } from './buffer/CameraBuffer.js' import { Mp4StreamReader } from './mp4/Mp4StreamReader.js' import { ClockRun } from './rtp/RTPClock.js' @@ -763,7 +765,7 @@ describe('tierPacer', () => { const silence = 1 // A picture let go as it falls due while the library alone holds the tier, and a keyframe that falls due after a viewer joins, its first picture. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ pictures: [100 / 3], @@ -797,7 +799,7 @@ describe('tierPacer', () => { // Pictures a third of a second long on their own time: the first two, neither a keyframe, arrive while the library alone holds the tier, which is why a viewer // joining at 500 ms joins the live releases. The third, a keyframe, arrives after the join. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ pictures: [1000 / 3], @@ -831,7 +833,7 @@ describe('tierPacer', () => { // A second-long picture on its own time and a picture 100 ms late while the library alone holds the tier, neither a keyframe, then a viewer, and a // keyframe on its own time, held to the late one's target less 0.9 s of fall. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ pictures: [1000], @@ -861,7 +863,7 @@ describe('tierPacer', () => { // Pictures that are no keyframe, each with its sound, fall due while the library alone holds the tier, and a keyframe with its sound arrives after a // viewer of the picture and the sound joins. The sound, which waits for no keyframe, reads what the join let go as the picture does. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ pictures: [100 / 3], @@ -970,7 +972,7 @@ describe('tierPacer', () => { it('sends a viewer nothing after its hold\'s release, and leaves no timer after the demand\'s end', async () => { const { at, delegate, stream, table, tier, view } = rig() - const library = table.hold(tier, scriptedHolder()) + const library = table.hold(tier, scriptedHolder(), 'recording') const { hold, releases } = view() stream().write(tierStreamInitialization()) @@ -1146,7 +1148,7 @@ describe('tierPacer', () => { // While the library alone holds the tier, its first picture falls due as it arrives and opens the run, and the keyframe arrives behind pictures // the pacer still holds when the viewers join. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ pictures: [100 / 3, 100 / 3, 100 / 3, 100 / 3], @@ -1215,7 +1217,7 @@ describe('tierPacer', () => { // While the library alone holds the tier, a run of pictures that are no keyframe, the second still held when the viewers join, and the next keyframe // after the join. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ pictures: [100 / 3, 100 / 3], @@ -1269,7 +1271,7 @@ describe('tierPacer', () => { // A keyframe and the pictures after it fall due while the library alone holds the tier. The viewers open from that keyframe, and more pictures // follow live once their openings are level. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ keyframe: true, @@ -1296,7 +1298,7 @@ describe('tierPacer', () => { // While the library alone holds the tier, pictures that are no keyframe arrive. The viewer joins and waits, and its request comes in the turn the keyframe // arrives, which falls due on its arrival: the answer opens it from that keyframe before the keyframe's own live release. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ pictures: [100 / 3, 100 / 3], @@ -1430,7 +1432,7 @@ describe('tierPacer', () => { + 'from that stream: no view of its sensor and no recording of the tier has sound.', tierId: 1, }) - const first = table.hold(soundTier, scriptedHolder()) + const first = table.hold(soundTier, scriptedHolder(), 'recording') await settle() streamsOf(delegate, 1)[0].write(silent) @@ -1439,7 +1441,7 @@ describe('tierPacer', () => { expect(problems).toEqual([fault]) first.release() - table.hold(soundTier, scriptedHolder()) + table.hold(soundTier, scriptedHolder(), 'recording') await settle() streamsOf(delegate, 1)[1].write(silent) @@ -1454,7 +1456,7 @@ describe('tierPacer', () => { const delegate = scriptedTierDelegate() const table = new TierTable(delegate, tiers, options => new TierBuffer(options), reporter) - table.hold(table.videoTiers.get(tierId)!, scriptedHolder()) + table.hold(table.videoTiers.get(tierId)!, scriptedHolder(), 'recording') await settle() streamsOf(delegate, tierId)[0].write(tierStreamInitialization({ sound: false })) await settle() @@ -1473,7 +1475,7 @@ describe('tierPacer', () => { if (held === 'a viewer') { view() } else { - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') } stream().write(tierStreamInitialization()) @@ -1590,7 +1592,7 @@ describe('tierPacer', () => { async () => { const { at, stream, table, tier, view } = rig() - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) for (let index = 0; index < 10; index++) { @@ -1633,7 +1635,7 @@ describe('tierPacer', () => { it('opens a viewer of a tier with a prebuffer from its latest keyframe released, not from the head the prebuffer holds', async () => { const { at, stream, table, tier, view } = rig() - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') tier.buffer.span = 5000 stream().write(tierStreamInitialization()) @@ -1666,7 +1668,7 @@ describe('tierPacer', () => { it('hands each of two viewers opening in one turn every picture of its opening once, and each release after it once', async () => { const { at, stream, table, tier, view } = rig() - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ keyframe: true, @@ -2222,7 +2224,7 @@ describe('tierPacer', () => { const pictures = placements(table, tier) const sounds = placements(table, tier, 'audio') - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) for (let index = 0; index < 10; index++) { @@ -2381,7 +2383,7 @@ describe('tierPacer', () => { const zero = performance.now() opens.mockClear() - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') stream().write(tierStreamInitialization()) stream().write(fragment({ keyframe: true, @@ -2540,7 +2542,7 @@ describe('tierPacer', () => { } }) - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') const hold = table.joinFrames(tier, 'video', scriptedHolder(), { take }) @@ -2642,7 +2644,7 @@ describe('tierPacer', () => { } else { // The library holds the tier, whose stream has started and written a picture that is no keyframe, let go as it falls due before the viewer // joins, and the viewer, joined to the live releases, makes its request before the stream's next keyframe. - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') await settle() stream().write(tierStreamInitialization()) stream().write(fragment({ @@ -2684,7 +2686,7 @@ describe('tierPacer', () => { // takes, which takes it off with its hold left unreleased, and a viewer whose hold is released. const { at, stream, table, tier, view } = rig() const live = view() - const alone = table.hold(tier, scriptedHolder()) + const alone = table.hold(tier, scriptedHolder(), 'recording') const thrown = table.joinFrames(tier, 'video', scriptedHolder(), { take: () => { throw new Error('The viewer\'s stream failed.') @@ -3155,7 +3157,7 @@ describe('tierPacer', () => { order.push('older') }) written.defer(() => { - const held = table.hold(tier, scriptedHolder()) + const held = table.hold(tier, scriptedHolder(), 'recording') inside.push([held.waiting, held.started, delegate.tierDemandStarted.mock.calls.length]) order.push('newer') @@ -3612,6 +3614,14 @@ describe('tierPacer', () => { // The problems a row's table raised, each by its kind and its sentence. const told = (problems: readonly CameraProblem[]): string[][] => problems.map(({ kind, sentence }) => [kind, sentence]) + // The problems a row's table raised, each by its kind and the cause a stream-failed problem names. + const caused = (problems: readonly CameraProblem[]): (string | undefined)[][] => problems.map(problem => [ + problem.kind, + (problem.kind === 'stream-failed') + ? problem.cause + : undefined, + ]) + it.each([ { written: 'after its start settled' }, { written: 'while its start is pending' }, @@ -3981,6 +3991,59 @@ describe('tierPacer', () => { 1, ]) }) + + it.each([ + { cause: 'plugin' }, + { cause: 'refused' }, + { cause: 'silent-start' }, + { cause: 'silent-gap' }, + { cause: 'silent-reconnect' }, + ] as const)('names the cause $cause on the one stream-failed problem of a demand a viewer alone holds', async ({ cause }) => { + const { problems, reporter } = problemsOf() + const { at, stream, table, view } = rig(scriptedTierDelegate(), TIERS, reporter) + + view() + await settle() + + switch (cause) { + case 'plugin': { + stream().fail('a synthetic failure') + break + } + + case 'refused': { + // A box whose size is under its header's, which the stream reader refuses. + stream().write(tierStreamInitialization()) + stream().write(Buffer.from('0000000466726565', 'hex')) + break + } + + case 'silent-start': { + await at(30000) + break + } + + default: { + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + + if (cause === 'silent-reconnect') { + table.sourceRecovering() + } + + await at((cause === 'silent-gap') + ? 10000 + : 30000) + } + } + + expect(caused(problems)).toEqual([ + ['stream-failed', cause], + ]) + }) }) describe('the opening\'s speed', () => { @@ -4322,7 +4385,7 @@ describe('tierPacer', () => { const { at, delegate, table } = rig() const best = table.videoTiers.get(1)! - table.hold(table.videoTiers.get(2)!, scriptedHolder()) + table.hold(table.videoTiers.get(2)!, scriptedHolder(), 'recording') await at(0) const lesser = startStream(streamsOf(delegate, 2)[0], 120) @@ -4332,7 +4395,7 @@ describe('tierPacer', () => { expect(best.demand).toBeUndefined() expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(1) - table.hold(best, scriptedHolder()) + table.hold(best, scriptedHolder(), 'recording') await at(0) const bestKeyframe = startStream(streamsOf(delegate, 1)[0], 140) @@ -4349,7 +4412,7 @@ describe('tierPacer', () => { expect(table.latestKeyframe()).toBeUndefined() expect(delegate.tierDemandStarted).not.toHaveBeenCalled() - const holds = [1, 2].map(tierId => table.hold(table.videoTiers.get(tierId)!, scriptedHolder())) + const holds = [1, 2].map(tierId => table.hold(table.videoTiers.get(tierId)!, scriptedHolder(), 'recording')) await at(0) @@ -4406,7 +4469,7 @@ describe('tierPacer', () => { + 'age by the steady clock', async () => { const { at, stream, table, tier } = rig() - table.hold(tier, scriptedHolder()) + table.hold(tier, scriptedHolder(), 'recording') await at(0) startStream(stream(), 100) @@ -4439,7 +4502,7 @@ describe('tierPacer', () => { const { at, delegate, table } = rig() // The fixture's third tier runs at 15 frames a second, an interval of 6000 ticks of the picture's 90 kHz track. - table.hold(table.videoTiers.get(3)!, scriptedHolder()) + table.hold(table.videoTiers.get(3)!, scriptedHolder(), 'recording') await at(0) const stream = streamsOf(delegate, 3)[0] @@ -4484,7 +4547,7 @@ describe('tierPacer', () => { const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) const lines = captureDebug('HAP-NodeJS:*') const { at, delegate, table } = rig() - const [, lesserHold] = [1, 2].map(tierId => table.hold(table.videoTiers.get(tierId)!, scriptedHolder())) + const [, lesserHold] = [1, 2].map(tierId => table.hold(table.videoTiers.get(tierId)!, scriptedHolder(), 'recording')) await at(0) @@ -4537,7 +4600,7 @@ describe('tierPacer', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) const { at, delegate, table } = rig() - table.hold(table.videoTiers.get(1)!, scriptedHolder()) + table.hold(table.videoTiers.get(1)!, scriptedHolder(), 'recording') await at(0) const stream = streamsOf(delegate, 1)[0] @@ -4563,6 +4626,549 @@ describe('tierPacer', () => { }) }) + describe('the reason a demand states', () => { + it('states view for a demand a packet join or a frame join raises and the reason a hold states for one it raises, and leaves a running demand\'s ' + + 'reason as it stands at a later join of any kind', async () => { + const { at, delegate, table } = rig() + const tier = (tierId: number): Tier => table.videoTiers.get(tierId)! + // Each start's tier and the reason its stream reads, in the order of the starts. + const reasons = (): string[] => streamsOf(delegate).map(({ reason, tier: { id } }) => `${id} ${reason}`) + + table.join(tier(1), scriptedHolder(), buildEmitterConnection(), ['video'], () => sessionHalf(10).consumer) + table.joinFrames(tier(2), 'audio', scriptedHolder(), { + take: () => undefined, + }) + + const recording = table.hold(tier(3), scriptedHolder(), 'recording') + + await at(0) + + const raised = reasons() + + table.hold(tier(1), scriptedHolder(), 'keepRunning') + table.joinFrames(tier(2), 'video', scriptedHolder(), { + take: () => undefined, + }) + + const viewed = table.joinFrames(tier(3), 'video', scriptedHolder(), { + take: () => undefined, + }) + + await at(0) + + const joined = reasons() + + recording.release() + viewed.release() + await at(0) + table.hold(tier(3), scriptedHolder(), 'keepRunning') + await at(0) + + expect([ + raised, + joined, + reasons(), + ]).toEqual([ + ['1 view', '2 view', '3 recording'], + ['1 view', '2 view', '3 recording'], + [ + '1 view', + '2 view', + '3 recording', + '3 keepRunning', + ], + ]) + }) + }) + + describe('a recording\'s lead-up', () => { + // The moment every row starts at, a fixed synthetic date, which a demand raised at the row's start reads as its start's moment. + const START = Date.parse('2026-11-12T00:00:00.000Z') + + // The length of a frame at 30 frames a second, in milliseconds. + const FRAME = 100 / 3 + + // One frame a consumer was handed: the steady clock's own moment of its release, its time in milliseconds and its timestamp. + interface Handed { + readonly at: number + readonly time: number + readonly timestamp: number + } + + interface LeadUpRig { + readonly table: TierTable + readonly tier: Tier + readonly stream: () => TierStream + // Moves the mock clock to a moment of the row's own timeline, in milliseconds from its start, each timer due by then running at its own moment. + readonly at: (moment: number) => Promise + // Joins a frame consumer of a medium, the picture unless the row names the sound, which keeps each frame it is handed. + readonly view: (medium?: StreamTierMedium) => { readonly handed: Handed[], readonly hold: TierHold } + } + + // How live writes a stream's frames: the moment of the row's timeline its first frame is written at, and a call made at each frame's moment before + // that frame is written. + interface LiveOptions extends FrameOptions { + readonly during?: (index: number) => void + readonly first?: number + } + + /* A table of the fixture's tiers built as rig builds one, on mock timers that fake the wall clock too and stand at START, its tier 1 raised for the + * reason given before anything is written: by a hold that states it for recording and keepRunning, and by the row's first view for view. + */ + function leadUpRig(raised: TierDemandReason = 'recording'): LeadUpRig { + vi.useFakeTimers({ + now: START, + toFake: [ + 'setTimeout', + 'clearTimeout', + 'performance', + 'Date', + ], + }) + + const delegate = scriptedTierDelegate() + const table = new TierTable(delegate, TIERS, options => new TierBuffer(options), detachedReporter()) + const tier = table.videoTiers.get(1)! + const zero = performance.now() + + if (raised !== 'view') { + table.hold(tier, scriptedHolder(), raised) + } + + return { + at: async (moment) => { + await vi.advanceTimersByTimeAsync(zero + moment - performance.now()) + }, + stream: () => delegate.tierDemandStarted.mock.calls.at(-1)![0], + table, + tier, + view: (medium = 'video') => { + const handed: Handed[] = [] + const hold = table.joinFrames(tier, medium, scriptedHolder(), { + take: (frame, timestamp) => { + handed.push({ + at: performance.now(), + time: Math.round(frame.time / 1000), + timestamp, + }) + }, + }) + + return { handed, hold } + }, + } + } + + // The NTP time a stream states for its picture's decode time zero where the frame of the index given, a multiple of three, is stated the offset given + // after the row's start. + function clockFor(index: number, offset = 0): bigint { + return ntpTime(START + offset - index * 1000 / 30) + } + + // Writes a stream's initialization segment and then the frames from one index up to another at once, as a camera hands over the video it kept. + function leadUp(r: LeadUpRig, from: number, to: number, options: FrameOptions = {}): void { + r.stream().write(tierStreamInitialization()) + frames(r.stream(), from, to, { inBand: true, ...options }) + } + + // Writes the frames from one index up to another each at its own moment, a frame's length after the one before from the first's, and lets half a + // second pass after the last, which releases every frame written. + async function live(r: LeadUpRig, from: number, to: number, { during, first = 0, ...options }: LiveOptions = {}): Promise { + for (let index = from; index < to; index++) { + await r.at(first + (index - from) * FRAME) + during?.(index) + frames(r.stream(), index, index + 1, { inBand: true, ...options }) + } + + await r.at(first + (to - from) * FRAME + 500) + } + + // A fragment of sound alone behind no producer reference time box, which states no time: the sounds the frames fixture times inside the frame of the + // index given. + function soundAlone(index: number): Buffer { + const first = Math.ceil(index * 5 / 3) + + return fragment({ + soundAt: first * 20, + sounds: Math.ceil((index + 1) * 5 / 3) - first, + }) + } + + it('sends a viewer joined before a recording\'s lead-up none of it, its first picture the first live keyframe', async () => { + const r = leadUpRig() + const { handed } = r.view() + + leadUp(r, 0, 90, { + clock: clockFor(90), + }) + await live(r, 90, 120, { + clock: clockFor(90), + }) + + expect(handed[0].time).toBe(3000) + }) + + it('opens the run at the first live picture after a recording\'s lead-up, placing it at the sensor\'s clock as it is released', async () => { + const r = leadUpRig() + const { handed } = r.view() + + leadUp(r, 0, 90, { + clock: clockFor(90), + }) + await live(r, 90, 120, { + clock: clockFor(90), + }) + + // The first live picture, frame 90, is read by its time whatever the viewer was handed ahead of it. + const first = handed.find(({ time }) => time === 3000)! + + expect(first.timestamp).toBe(r.tier.context.clock.timestamp('video', first.at)) + }) + + it('opens a viewer joining after a recording\'s lead-up and before the first live keyframe from no keyframe of the lead-up, its first picture that ' + + 'live keyframe', async () => { + const r = leadUpRig() + let handed: Handed[] = [] + + leadUp(r, 0, 75, { + clock: clockFor(75), + }) + await live(r, 75, 120, { + clock: clockFor(75), + during: (index) => { + if (index === 84) { + handed = r.view().handed + } + }, + }) + + expect(handed[0].time).toBe(3000) + }) + + it('opens a viewer joining after the first live keyframe that follows a recording\'s lead-up from that keyframe, its pictures standing on the ' + + 'sensor\'s clock', async () => { + const r = leadUpRig() + let handed: Handed[] = [] + + leadUp(r, 0, 90, { + clock: clockFor(90), + }) + await live(r, 90, 135, { + clock: clockFor(90), + during: (index) => { + if (index === 105) { + handed = r.view().handed + } + }, + }) + + const last = handed.at(-1)! + + expect(handed[0].time).toBe(3000) + expect(Math.abs(last.timestamp - r.tier.context.clock.timestamp('video', last.at))).toBeLessThan(250 * PICTURE_TICKS) + }) + + it('answers a viewer\'s keyframe request with no keyframe kept while the tier holds a recording\'s lead-up alone', async () => { + const r = leadUpRig() + const { hold } = r.view() + + leadUp(r, 0, 90, { + clock: clockFor(90), + }) + await r.at(300) + + expect(hold.answerKeyframeRequest()).toBe('no keyframe kept') + }) + + it('answers no newest keyframe for a snapshot while the tier holds a recording\'s lead-up alone', async () => { + const r = leadUpRig() + + leadUp(r, 0, 90, { + clock: clockFor(90), + }) + await r.at(300) + + expect(r.table.latestKeyframe()).toBeUndefined() + }) + + it('sends a session at home no packet of a recording\'s lead-up and counts none', async () => { + const r = leadUpRig() + + session(r.table, r.tier, 1000) + leadUp(r, 0, 90, { + clock: clockFor(90), + }) + await r.at(300) + + expect(r.stream().statistics().packets).toBe(0) + }) + + it('reads a first keyframe stated at the start\'s moment as live, its viewer sent the stream from it', async () => { + const r = leadUpRig() + const { handed } = r.view() + + r.stream().write(tierStreamInitialization()) + await live(r, 0, 45, { + clock: clockFor(0), + }) + + expect(handed[0].time).toBe(0) + }) + + it('reads a first keyframe stated a millisecond before the start\'s moment as lead-up, its viewer\'s first picture the next keyframe', async () => { + const r = leadUpRig() + const { handed } = r.view() + + r.stream().write(tierStreamInitialization()) + await live(r, 0, 45, { + clock: clockFor(0, -1), + }) + + expect(handed[0].time).toBe(1000) + }) + + it('latches a stream live at its first picture that states no time, sending every picture it later states as taken before the start', async () => { + const r = leadUpRig() + const { handed } = r.view() + + r.stream().write(tierStreamInitialization()) + await live(r, 0, 30) + await live(r, 30, 60, { + clock: clockFor(0, -10000), + first: 30 * FRAME + 500, + }) + + expect(handed).toHaveLength(60) + }) + + it('sends a sound stated after the start ahead of the first live picture, and no sound of the lead-up stated before it', async () => { + const r = leadUpRig() + const { handed } = r.view('audio') + // Every sound from frame 89's fragment on stands 40 ms later, which states that fragment's sound 20 ms after the start. + const retimeSound = (index: number, decodeTime: number): number => (index >= 89) + ? decodeTime + 40 * SOUND_TICKS + : decodeTime + + leadUp(r, 0, 90, { + clock: clockFor(90), + retimeSound, + }) + await live(r, 90, 120, { + clock: clockFor(90), + retimeSound, + }) + + expect(handed[0].time).toBe(3020) + }) + + it('reads a recording\'s lead-up across a discontinuity up to the first live video', async () => { + const r = leadUpRig() + const { handed } = r.view() + + leadUp(r, 0, 45, { + clock: clockFor(0, -10000), + }) + r.stream().discontinuity() + frames(r.stream(), 0, 45, { + clock: clockFor(45), + inBand: true, + }) + await live(r, 45, 90, { + clock: clockFor(45), + }) + + expect(handed[0].time).toBe(2000) + }) + + it('places the first live keyframe after a recording\'s lead-up and a gap of more than a second at the sensor\'s clock as it is released', async () => { + const r = leadUpRig() + const { handed } = r.view() + + leadUp(r, 0, 90, { + clock: clockFor(150), + }) + await live(r, 150, 180, { + clock: clockFor(150), + }) + + const [first] = handed + + expect([first.time, first.timestamp]).toEqual([ + 5000, + r.tier.context.clock.timestamp('video', first.at), + ]) + }) + + it('reads a stream stated far behind the computer\'s clock as lead-up for the window from its first sample, its viewer\'s first picture the keyframe ' + + 'after the window', async () => { + const r = leadUpRig() + const { handed } = r.view() + const clock = ntpTime(START - 5 * 60 * 1000) + + leadUp(r, 0, 1, { clock }) + await live(r, 1, 360, { clock, first: FRAME + 10 }) + + expect(handed[0].time).toBe(10000) + }) + + it.each(['view', 'keepRunning'] as const)('reads no lead-up on a demand raised for %s, its viewer sent the stream from its first keyframe', async ( + raised, + ) => { + const r = leadUpRig(raised) + const { handed } = r.view() + + leadUp(r, 0, 90, { + clock: clockFor(90), + }) + await live(r, 90, 120, { + clock: clockFor(90), + }) + + expect(handed[0].time).toBe(0) + }) + + it('counts the window from the stream\'s first sample, a stream whose first bytes come 12 seconds after its start bringing its lead-up then', async () => { + const r = leadUpRig() + const { handed } = r.view() + + await r.at(12000) + leadUp(r, 0, 90, { + clock: clockFor(90), + }) + await live(r, 450, 480, { + clock: clockFor(90), + first: 12000, + }) + + expect(handed[0].time).toBe(15000) + }) + + it('takes a sound that states no time for lead-up once the lead-up has begun, the run opening at the first live picture', async () => { + const r = leadUpRig() + const pictures = r.view().handed + const sounds = r.view('audio').handed + + r.stream().write(tierStreamInitialization()) + + for (let index = 0; index < 90; index++) { + frames(r.stream(), index, index + 1, { + clock: clockFor(90), + inBand: true, + sound: false, + }) + r.stream().write(soundAlone(index)) + } + + await live(r, 90, 120, { + clock: clockFor(90), + }) + + const [first] = pictures + + expect({ + ahead: first.timestamp - r.tier.context.clock.timestamp('video', first.at), + firstPicture: first.time, + firstSound: sounds[0].time, + soundsBefore: sounds.filter(({ time }) => time < 3000).length, + }).toEqual({ + ahead: 0, + firstPicture: 3000, + firstSound: 3000, + soundsBefore: 0, + }) + }) + + it('takes a sound that states no time for lead-up ahead of the first picture of a stream that states nothing, and sends every sound after that ' + + 'picture', async () => { + const r = leadUpRig() + const pictures = r.view().handed + const sounds = r.view('audio').handed + + r.stream().write(tierStreamInitialization()) + + for (let index = 0; index < 30; index++) { + await r.at(index * FRAME) + r.stream().write(soundAlone(index)) + frames(r.stream(), index, index + 1, { inBand: true, sound: false }) + } + + await r.at(30 * FRAME + 500) + + // The sound written ahead of frame 0 is timed at 0 and 20 ms, and the sound written ahead of frame 1 opens at 40 ms, every later sound following + // 20 ms apart up to the last frame's at 980 ms. + expect({ + firstPicture: pictures[0].time, + sounds: sounds.map(({ time }) => time), + }).toEqual({ + firstPicture: 0, + sounds: Array.from({ length: 48 }, (_, index) => 40 + index * 20), + }) + }) + + it('takes a sound that states no time written ahead of the lead-up\'s first picture for lead-up, the run opening at the first live picture', async () => { + const r = leadUpRig() + const pictures = r.view().handed + const sounds = r.view('audio').handed + + r.stream().write(tierStreamInitialization()) + + for (let index = 0; index < 90; index++) { + r.stream().write(soundAlone(index)) + frames(r.stream(), index, index + 1, { + clock: clockFor(90), + inBand: true, + sound: false, + }) + } + + await live(r, 90, 120, { + clock: clockFor(90), + }) + + const [first] = pictures + + expect({ + ahead: first.timestamp - r.tier.context.clock.timestamp('video', first.at), + firstPicture: first.time, + firstSound: sounds[0].time, + soundsBefore: sounds.filter(({ time }) => time < 3000).length, + }).toEqual({ + ahead: 0, + firstPicture: 3000, + firstSound: 3000, + soundsBefore: 0, + }) + }) + + it('sends a sound that states no time arriving the window\'s length or more after the stream\'s first sample, ahead of any picture', async () => { + const r = leadUpRig() + const sounds = r.view('audio').handed + let picturesFrom = 0 + + r.stream().write(tierStreamInitialization()) + + // A fragment of one sound every 20 ms for 12 seconds, each timed at the moment it is written from the row's start, which means a sound's time is + // the moment it arrived. + for (let index = 0; index < 600; index++) { + await r.at(index * 20) + r.stream().write(fragment({ soundAt: index * 20, sounds: 1 })) + } + + // The frames whose times follow the last sound's, each written with its sound at its own moment from 12 seconds on. + await live(r, 360, 390, { + during: (index) => { + if (index === 360) { + picturesFrom = performance.now() + } + }, + first: 12000, + }) + + expect(sounds.map(({ time }) => time)).toEqual(Array.from({ length: 150 }, (_, index) => 10000 + index * 20)) + expect(sounds[0].at).toBeLessThan(picturesFrom) + }) + }) + describe('its problems', () => { // The failure a session's packet consumer throws as it is sent a picture. const SEND_FAILURE = new Error('The session\'s socket failed.') diff --git a/src/lib/camera/TierPacer.ts b/src/lib/camera/TierPacer.ts index e8d99c50b..2792e2d01 100644 --- a/src/lib/camera/TierPacer.ts +++ b/src/lib/camera/TierPacer.ts @@ -96,7 +96,8 @@ function joinFloor(window: Arrival[], at: number, lateness: number): number { * One tier demand's pacer, which sends the tier's samples to every viewer at once on one schedule, read from the stream's own times and its arrivals. * * It hears the tier's buffer through a place that holds no keyframe, which is why it holds no head and no trim displaces it: it is told each sample the buffer - * takes, kept or passed over, each fragment's end and each run's end. It keeps the samples it was told and has not released by reference, never by copy: + * takes, kept or passed over, each fragment's end and each run's end, and keeps none of a recording's lead-up, which no viewer is sent and which opens no + * run. It keeps the samples it was told and has not released by reference, never by copy: * a run's end, which empties the buffer inside the plugin's call, loses none of them. It releases each to its demand on its one timer, in a turn of * its own and never inside a plugin's call of the stream. A sample is released once its due moment passes, sent where a consumer is joined and let go * where none is. @@ -166,8 +167,10 @@ export class TierPacer implements BufferPlace { return this.halted } + // A recording's lead-up is no viewer's, which is why the pacer keeps none of it: it is never scheduled, released, placed, counted or sent, and it moves + // none of the rule's state. taken(sample: BufferedSample): void { - if (!this.halted) { + if (!this.halted && (sample.leadUp !== true)) { this.arriving.push(sample) } } diff --git a/src/lib/camera/TierTable.ts b/src/lib/camera/TierTable.ts index 42c4eed76..05eba5fb7 100644 --- a/src/lib/camera/TierTable.ts +++ b/src/lib/camera/TierTable.ts @@ -1,13 +1,16 @@ import type { HAPConnection } from '../util/eventedhttp.js' import type { BufferedSample, TierBuffer, TierBufferOptions } from './buffer/CameraBuffer.js' +import type { TierKeeperReason } from './buffer/TierKeeper.js' import type { AudioStreamTier, VideoStreamTier } from './capabilities/streamTiers.js' import type { CameraReporter } from './diagnostics/CameraReporter.js' +import type { CameraProblem } from './diagnostics/problems.js' import type { Mp4StreamSample, Mp4StreamTracks, Mp4StreamVideoTrack } from './mp4/Mp4StreamReader.js' import type { CameraKeyframe, MultiTierStreamingDelegate, SensorStreamTiers, StreamTierMedium, + TierDemandReason, TierFrame, TierStream, TierStreamStatistics, @@ -64,16 +67,30 @@ export const RECOVERING_GAP_TIME = 30 * 1000 // The most time from a start's settling to its demand's first picture. const FIRST_SAMPLE_BOUND = 30 * 1000 -// What a demand's silence clock counts, its time and the silence the stream-failed problem of its end names: the first-sample bound from the start's -// settling to the first picture, the long-gap time from each picture, and the recovering gap time from a reconnect's statement to the next picture. +/* How long from a recording demand's first sample its stream may hand over video and sound as the recording's lead-up, the figure the + * library gives a keyframe's reach past a buffer's span and a stream's longest gap. It bounds what a stream whose clock runs behind the computer's costs: + * such a stream holds its live video back from the viewers of an on-demand recording's start for no longer than this, and then until its next keyframe. + * It bounds nothing about when a plugin begins to write. + */ +const LEAD_UP_WINDOW = 10 * 1000 + +// What a demand's silence clock counts, its time and the cause and silence the stream-failed problem of its end names: the first-sample bound from the +// start's settling to the first picture, the long-gap time from each picture, and the recovering gap time from a reconnect's statement to the next picture. const SILENCE_CLOCKS = { - first: { silence: `no picture within ${FIRST_SAMPLE_BOUND / 1000} seconds of its start's settling`, time: FIRST_SAMPLE_BOUND }, - gap: { silence: `no picture for ${LONG_GAP_TIME / 1000} seconds`, time: LONG_GAP_TIME }, - recovering: { silence: `no picture within ${RECOVERING_GAP_TIME / 1000} seconds of its source being stated reconnecting`, time: RECOVERING_GAP_TIME }, + first: { cause: 'silent-start', silence: `no picture within ${FIRST_SAMPLE_BOUND / 1000} seconds of its start's settling`, time: FIRST_SAMPLE_BOUND }, + gap: { cause: 'silent-gap', silence: `no picture for ${LONG_GAP_TIME / 1000} seconds`, time: LONG_GAP_TIME }, + recovering: { + cause: 'silent-reconnect', + silence: `no picture within ${RECOVERING_GAP_TIME / 1000} seconds of its source being stated reconnecting`, + time: RECOVERING_GAP_TIME, + }, } as const type SilenceClock = keyof typeof SILENCE_CLOCKS +// The cause a stream-failed problem names, as its arm of the problem states it. +type StreamFailedCause = Extract['cause'] + /* The movie of each keyframe a lookup answered, kept against the buffer's own sample. A keyframe's movie is written once and handed again while that * keyframe is the newest, and nothing has to forget it: a kept movie goes when the buffer lets its sample go, as the buffer's span passes the sample, as * the buffer empties, at a reset and at a removal. @@ -807,12 +824,18 @@ export class DemandHalf { * its stream with a reader of its own, which it calls only from the plugin's own calls of the stream, and those calls only fill the tier's buffer, each * initialization segment's tracks, each sample its format check lets through with the moment it arrived, and each fragment's end, and tell the buffer * and its pacer of a mark. The demand's pacer hears the buffer through a place of its own, from the demand's making until it leaves its tier, and releases - * each sample in a turn of its own to the half of its medium, its picture or its sound, each half timing its samples on the demand's one run of the - * sensor's clock and sending them to the consumers joined for its medium, the sound only while the camera's Microphone is unmuted. The run ends where the - * pacer releases past a run's end: a mark, which the demand tells the pacer of as the plugin makes it and the buffer reads at the stream's next sample, or - * an initialization segment or a jump the buffer reads, which means one restart ends the run once in every order its samples arrive in. From its failure on the - * demand ignores what the plugin writes: it feeds the buffer nothing more and its pacer releases nothing, and the buffer empties as the demand leaves - * its tier. + * each sample but a recording's lead-up in a turn of its own to the half of its medium, its picture or its sound, each half timing its samples on the + * demand's one run of the sensor's clock and sending them to the consumers joined for its medium, the sound only while the camera's Microphone is + * unmuted. The run ends where the pacer releases past a run's end: a mark, which the demand tells the pacer of as the plugin makes it and the buffer reads + * at the stream's next sample, or an initialization segment or a jump the buffer reads, which means one restart ends the run once in every order its + * samples arrive in. From its failure on the demand ignores what the plugin writes: it feeds the buffer nothing more and its pacer releases nothing, and + * the buffer empties as the demand leaves its tier. + * + * A demand raised for an on-demand recording, whose reason is `'recording'`, tells that recording's lead-up from its live video at each sample it hands + * its buffer, until its first video that is no lead-up latches it live, and marks each sample of the lead-up as it hands it over. The recorder reads the + * lead-up, and every viewer reads the stream behind a gate that passes it over: the pacer keeps none of it, which means it is never sent and the run + * opens at the live video, and the buffer's keyframe lookup answers none where its latest keyframe is lead-up, which means no opening, keyframe answer + * or snapshot reads it. A demand of any other reason is live from its making and classifies nothing. * * The demand reads every picture its stream hands over, whoever holds it, which is why it holds the stream to its silence bounds with one clock of its own: * a started stream's first picture is due within the first-sample bound of the start's settling, one written inside the start counting, and each later @@ -833,6 +856,9 @@ export class TierDemand implements TierStream { readonly pacer: TierPacer // The tier's settled entry, the one object every demand of the tier carries. readonly tier: TierStream['tier'] + // Why the demand was raised, which its stream carries: 'view' for a demand a view's join raised, and the reason the keeper states for one its hold + // raised. A later join leaves it as it stands. + readonly reason: TierDemandReason // The camera's reporter, the table's, which the demand and its halves report through, and what each of their problems concerns: the tier's sensor and // the tier. readonly reporter: CameraReporter @@ -865,12 +891,21 @@ export class TierDemand implements TierStream { private toldNoSound = false // The silence clock and what it counts, none before the start settles or the first picture, and none once the demand has failed or left its tier. private silence?: { readonly clock: SilenceClock, readonly timer: ReturnType } + /* What the lead-up rule reads, the demand's alone: the wall clock as its start was called, the steady clock's moment it handed its buffer its first + * sample, and whether it is live, which a demand of any reason but 'recording' is from its making and a recording's demand becomes at its first video + * that is no lead-up. A discontinuity, an initialization segment and a jump leave each as it stands. + */ + private startMoment = 0 + private firstArrival?: number + private live: boolean - constructor(tier: Tier) { + constructor(tier: Tier, reason: TierDemandReason) { const { context: { reporter, sensorUUID }, tierId } = tier this.videoTier = tier this.tier = tier.entry + this.reason = reason + this.live = reason !== 'recording' this.reporter = reporter this.fields = { sensorUUID, tierId } this.scope = new HandleScope(END_FAILURE, reporter, this.fields) @@ -895,7 +930,7 @@ export class TierDemand implements TierStream { // that track's can fail the tier. this.reader = new Mp4StreamReader({ fail: (reason) => { - this.failWith('The library refused', reason) + this.failWith('refused', 'The library refused', reason) }, fragmentEnd: () => { this.endFragment() @@ -953,16 +988,18 @@ export class TierDemand implements TierStream { } /* Calls the delegate's tierDemandStarted with the demand as its stream and the signal of the start's own controller, once the joins that raised the - * demand are in place. Every field a write reads is set before the call, the raiser's route and its consumers among them: a stream the plugin writes - * inside the call reaches the raiser timed and counted once the pacer releases it, and a stream failed inside it ends the raiser. The start is pending - * from the call until its settling. The signal is aborted only by an end in that span, and a rejection that follows the abort is not reported. The - * start's one bound is counted from this call, whoever waits on the demand, and no join restarts it. + * demand are in place. Every field a write reads is set before the call, the raiser's route and its consumers among them, and so is the start's moment, + * the wall clock a recording's lead-up is read against: a stream the plugin writes inside the call reaches the raiser timed and counted once the pacer + * releases it, which it never does for a recording's lead-up, and a stream failed inside it ends the raiser. The start is pending from the call until its + * settling. The signal is aborted only by an end in that span, and a rejection that follows the abort is not reported. The start's one bound is counted + * from this call, whoever waits on the demand, and no join restarts it. */ start(): void { const { context: { delegate } } = this.videoTier const pendingStart = new AbortController() this.pendingStart = pendingStart + this.startMoment = Date.now() const pending = (async () => delegate.tierDemandStarted(this, pendingStart.signal))() @@ -1016,7 +1053,7 @@ export class TierDemand implements TierStream { // The plugin's failure of the stream, from which on the demand releases nothing, its pacer letting go what waits unsent, and ignores every chunk the // plugin writes, as it does once it has ended. fail(reason: string): void { - this.failWith('The plugin failed', reason) + this.failWith('plugin', 'The plugin failed', reason) } // A join's hold keeps the demand, and takes one whose joins all released while its start was pending back to starting. @@ -1261,11 +1298,11 @@ export class TierDemand implements TierStream { } } - // Hands a sample its format check lets through to the tier's buffer, with the moment of the steady clock it arrived and any wall clock its stream - // states for it, which tells every place in the buffer of it, the pacer's among them: no packet of it is sent before the buffer has it. A picture then - // moves the silence clock on, unless the take itself ended or failed the demand: a place reading the sample can run a plugin's code, as a recording's - // place does where a trim ends its recording and a plugin's recording-ended listener states the source away, and a demand failed or ended counts no - // silence. + // Hands a sample its format check lets through to the tier's buffer, with the moment of the steady clock it arrived, any wall clock its stream states + // for it and, on a recording's demand not yet live, whether it is lead-up, read from that same moment, which tells every place in the buffer of it, the + // pacer's among them: no packet of it is sent before the buffer has it. A picture then moves the silence clock on, lead-up among them, unless the take + // itself ended or failed the demand: a place reading the sample can run a plugin's code, as a recording's place does where a trim ends its recording and a + // plugin's recording-ended listener states the source away, and a demand failed or ended counts no silence. private take(sample: Mp4StreamSample): void { if (!this.feeds) { return @@ -1277,13 +1314,40 @@ export class TierDemand implements TierStream { return } - this.videoTier.buffer.take(sample, performance.now()) + const arrival = performance.now() + + this.videoTier.buffer.take(sample, arrival, !this.live && this.leadUp(sample, arrival)) if ((medium === 'video') && this.feeds) { this.pictured() } } + /* Whether a sample of a recording's demand not yet live is that recording's lead-up, read once as the demand hands it over: a sample its stream states + * as taken before the start's moment, or a sound that states no time, arriving within the lead-up window of the first sample the demand handed its + * buffer. A picture that states no time is never lead-up, and the first video that is no lead-up latches the demand live, which means a demand's + * lead-up video comes ahead of all its live video, a sound that states no time is lead-up inside the window up to that latch whether or not lead-up + * video came before it, and no sample after the latch is read. + */ + private leadUp(sample: Mp4StreamSample, arrival: number): boolean { + this.firstArrival ??= arrival + + const { track: { medium }, wallClock } = sample + const before = (wallClock === undefined) + ? medium === 'audio' + : wallClock < this.startMoment + + if (before && ((arrival - this.firstArrival) < LEAD_UP_WINDOW)) { + return true + } + + if (medium === 'video') { + this.live = true + } + + return false + } + /* A picture the tier's buffer took, read once every place in the buffer has read it, the keeper's among them: the tier's silence is over, and the * silence clock counts the long-gap time from this picture, a running gap clock moved on and any other made again at that time, since a refresh keeps a * timer's own duration. The keeper's clocks move on at the same picture ahead of the demand's, which is why at a deadline they share the keeper tells an @@ -1321,10 +1385,11 @@ export class TierDemand implements TierStream { private silenced(clock: SilenceClock): void { const { videoTier } = this const told = videoTier.toldSilence + const { cause, silence } = SILENCE_CLOCKS[clock] this.silence = undefined videoTier.toldSilence = true - this.failWith('The library ended', SILENCE_CLOCKS[clock].silence, told) + this.failWith(cause, 'The library ended', silence, told) } private endFragment(): void { @@ -1333,18 +1398,19 @@ export class TierDemand implements TierStream { } } - // A failed stream raises one stream-failed problem with the failure's own sentence, and one whose failure its tier has told of already raises none. - private failWith(who: string, reason: string, told = false): void { + // A failed stream raises one stream-failed problem naming its cause, with the failure's own sentence, and one whose failure its tier has told of + // already raises none. + private failWith(cause: StreamFailedCause, who: string, reason: string, told = false): void { this.failHolds(told ? undefined - : `${who} the stream of ${this.tierName} (${reason}), and every session on the tier ends.`) + : { cause, sentence: `${who} the stream of ${this.tierName} (${reason}), and every session on the tier ends.` }) } /* A failed tier calls the route of every join's holder, one waiting on the tier's start among them, which ends it, and the demand ends as the last of * them releases. A hold's answer reads a failed demand as refused, which means a join waiting on it, and one made later, is answered as refused. A failed * demand releases nothing and counts no silence: its pacer and its silence clock stop before any route is called. */ - private failHolds(warning: string | undefined): void { + private failHolds(failure: { readonly cause: StreamFailedCause, readonly sentence: string } | undefined): void { if (this.failed || this.state === 'ended') { return } @@ -1354,12 +1420,13 @@ export class TierDemand implements TierStream { this.pacer.halt() this.settle() - if (warning !== undefined) { + if (failure !== undefined) { this.reporter.problem({ ...this.fields, + cause: failure.cause, kind: 'stream-failed', level: 'warning', - sentence: warning, + sentence: failure.sentence, }) } @@ -1608,10 +1675,10 @@ export class TierHold { * One video sensor's tier model, which the camera controller builds for each sensor and hands that sensor's stream management: the sensor's stream tiers * in the order they are advertised, each video tier's buffer and its demand from its first join to its last, the sensor's one RTP clock every tier's * picture and sound are timed on, and the delegate's demand calls. A viewer's keyframe request goes to the hold its consumer joined with, whose demand - * answers it from the tier's buffer. A demand reads each sample its stream is written and keeps it in its tier's buffer, and its pacer releases it in a - * turn of its own, when the demand times it and cuts it into the packets its joined consumers send. A holder joins a tier in one step, through the join - * of its consumers' kind, naming the medium each packet or frame consumer takes, and the library's own hold joins with no consumer. Only a join that - * raises a tier's demand runs plugin code, the delegate's tierDemandStarted, and a join into a running demand runs none. + * answers it from the tier's buffer. A demand reads each sample its stream is written and keeps it in its tier's buffer, and its pacer releases each but + * a recording's lead-up in a turn of its own, when the demand times it and cuts it into the packets its joined consumers send. A holder joins a tier in + * one step, through the join of its consumers' kind, naming the medium each packet or frame consumer takes, and the library's own hold joins with no + * consumer. Only a join that raises a tier's demand runs plugin code, the delegate's tierDemandStarted, and a join into a running demand runs none. */ export class TierTable { /** @@ -1723,7 +1790,7 @@ export class TierTable { media: readonly StreamTierMedium[], joining: (medium: StreamTierMedium, packetSize: number) => PacketConsumer, ): TierHold { - return this.joinDemand(tier, holder, (demand) => { + return this.joinDemand(tier, holder, 'view', (demand) => { const packetSize = demand.cutFor(connection) return media.map(medium => ({ @@ -1749,7 +1816,7 @@ export class TierTable { * @returns The join's hold. */ joinFrames(tier: Tier, medium: StreamTierMedium, holder: TierHolder, consumer: FrameConsumer): TierHold { - return this.joinDemand(tier, holder, () => [ + return this.joinDemand(tier, holder, 'view', () => [ { kind: 'frames', medium, @@ -1764,10 +1831,12 @@ export class TierTable { * counts among the stream's consumers, and calls the delegate for a demand it raised only after, a join into a running demand calling it for nothing. * @param tier - The tier. * @param holder - The holder, whose route a failed tier calls. + * @param reason - Why the library holds the tier, which the stream of a demand the hold raises states. A hold onto a running demand leaves that + * demand's reason as it stands. * @returns The join's hold. */ - hold(tier: Tier, holder: TierHolder): TierHold { - return this.joinDemand(tier, holder, () => [ + hold(tier: Tier, holder: TierHolder, reason: TierKeeperReason): TierHold { + return this.joinDemand(tier, holder, reason, () => [ { kind: 'hold', }, @@ -1781,8 +1850,8 @@ export class TierTable { * The newest and not the latest released, because a snapshot is held to no viewer's place in the stream, and the newer picture is the fresher one. * Nothing is raised for the lookup, and no tierDemandStarted runs for it. A tier whose newest keyframe lacks any of HEVC's video, sequence and picture * parameter sets, in the keyframe and in its stream's description alike, answers none, as a tier that keeps no keyframe, and is passed over for the next - * tier that serves. - * @returns The keyframe, or `undefined` where no tier of the sensor serves with a newest keyframe a decoder can read. + * tier that serves, and so is a tier whose newest keyframe is a recording's lead-up, which no snapshot shows. + * @returns The keyframe, or `undefined` where no tier of the sensor serves with a newest keyframe a decoder can read that is no recording's lead-up. */ latestKeyframe(): CameraKeyframe | undefined { // Each serving tier's newest keyframe a decoder can read, by the stream tier it was advertised from, which bestStreamTier reads. @@ -1867,10 +1936,11 @@ export class TierTable { } // A join's one step: its hold puts the holder's route in place, its consumers join the demand, and only then is the delegate called for a demand the join - // raised, which is why every field a write reads is set before the plugin's code runs. - private joinDemand(tier: Tier, holder: TierHolder, joining: (demand: TierDemand) => readonly TierJoin[]): TierHold { + // raised, which is why every field a write reads is set before the plugin's code runs. A demand the join raises carries the join's reason, 'view' for a + // view's join and the keeper's own for its hold, and a join onto a running demand leaves that demand's reason as it stands. + private joinDemand(tier: Tier, holder: TierHolder, reason: TierDemandReason, joining: (demand: TierDemand) => readonly TierJoin[]): TierHold { const raised = !tier.demand - const demand = tier.demand ?? (tier.demand = new TierDemand(tier)) + const demand = tier.demand ?? (tier.demand = new TierDemand(tier, reason)) const joins = joining(demand) const hold = new TierHold(demand, holder, joins) diff --git a/src/lib/camera/WebRTCStreamManagement.spec.ts b/src/lib/camera/WebRTCStreamManagement.spec.ts index 350234269..1065c75a5 100644 --- a/src/lib/camera/WebRTCStreamManagement.spec.ts +++ b/src/lib/camera/WebRTCStreamManagement.spec.ts @@ -610,6 +610,15 @@ describe('webRTCStreamManagement', () => { sdpAnswer: SDP_ANSWER, }) }) + + // An unpaired connection is one a server in insecure mode lets through: alive, and never authenticated. The row reads no further than the first check. + it('passes a solicit from an unpaired connection that is alive through its first check, the engine asked for an offer', async () => { + const { engine, service } = harness() + + await solicit(service, buildEmitterConnection('IPv6', { paired: false })) + + expect(engine.createOffer).toHaveBeenCalledTimes(1) + }) }) describe('session commands', () => { @@ -2405,6 +2414,7 @@ describe('webRTCStreamManagement', () => { OPERATING_MODE_CHANGED: 'operating-mode-change', RECORDING_ENDED: 'recording-ended', RECORDING_STARTED: 'recording-started', + SNAPSHOT_REFUSED: 'snapshot-refused', SPEAKER_PROPERTIES_CHANGED: 'speaker-change', STREAMING_ENABLED_CHANGED: 'streaming-enabled-change', }) diff --git a/src/lib/camera/buffer/CameraBuffer.spec.ts b/src/lib/camera/buffer/CameraBuffer.spec.ts index 7ff404a99..d8d260109 100644 --- a/src/lib/camera/buffer/CameraBuffer.spec.ts +++ b/src/lib/camera/buffer/CameraBuffer.spec.ts @@ -911,4 +911,112 @@ describe('cameraBuffer', () => { ]) }) }) + + describe('a recording\'s lead-up', () => { + // The NTP time of 2026-11-12T00:00:00.000Z, an NTP time the producer reference time writer's vectors hold, which a row's stream states. + const STATED = 0xEE9F800000000000n + + /* A buffer at a span of ten seconds fed through a reader of the row's own, built as rig builds one, whose sample callback hands the buffer the mark + * the row gives with each chunk it writes, each chunk arriving at the moment given. + */ + function marking(): { readonly buffer: TierBuffer, readonly write: (chunk: Buffer, moment: number, leadUp: boolean) => void } { + const buffer = new TierBuffer({ + reporter: detachedReporter(), + sensorUUID: SENSOR_UUID, + tierId: 1, + }) + let arrival = 0 + let marked = false + const reader = new Mp4StreamReader({ + fail: (reason) => { + throw new Error(reason) + }, + fragmentEnd: () => buffer.endFragment(), + sample: sample => buffer.take(sample, arrival, marked), + tracks: tracks => buffer.describe(tracks), + }) + + buffer.span = 10000 + reader.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + + return { + buffer, + write: (chunk, moment, leadUp) => { + arrival = moment + marked = leadUp + reader.write(chunk) + }, + } + } + + // A fragment of one picture at a time in seconds, a keyframe or not, behind a producer reference time box stating STATED at its decode time where + // the row asks. + function pictureAt(seconds: number, { keyframe = false, stated = false }: { keyframe?: boolean, stated?: boolean } = {}): Buffer { + const fragment = tierStreamFragment({ + picture: [ + tierPicture({ keyframe }), + ], + pictureTime: BigInt(seconds * PICTURE_RATE), + }) + + return stated + ? Buffer.concat([ + prft({ + mediaTime: BigInt(seconds * PICTURE_RATE), + ntpTime: STATED, + trackId: TIER_STREAM_PICTURE, + }), + fragment, + ]) + : fragment + } + + it('marks a sample handed over as lead-up with leadUp true, keeping the wall clock its stream states for it, and leaves the member off every other ' + + 'sample', () => { + const { buffer, write } = marking() + + write(pictureAt(0, { keyframe: true, stated: true }), 0, true) + write(tierStreamFragment({ + sound: [ + soundSample(Buffer.alloc(40, 0x5A)), + ], + soundTime: BigInt(0.5 * SOUND_RATE), + }), 500, true) + write(pictureAt(1, { stated: true }), 1000, false) + write(pictureAt(1.5), 1500, false) + + expect(buffer.samples.map(sample => [ + sample.track.medium, + Object.hasOwn(sample, 'leadUp') + ? sample.leadUp + : 'absent', + Object.hasOwn(sample, 'wallClock'), + ])).toEqual([ + ['video', true, true], + ['audio', true, false], + ['video', 'absent', true], + ['video', 'absent', false], + ]) + }) + + it('answers no keyframe before a place whose latest keyframe is a recording\'s lead-up, and the live keyframe once one stands', () => { + const { buffer, write } = marking() + + write(pictureAt(0, { keyframe: true }), 0, true) + write(pictureAt(1), 1000, true) + write(pictureAt(2, { keyframe: true }), 2000, true) + + const during = buffer.keyframeBefore(Number.POSITIVE_INFINITY) + + write(pictureAt(3, { keyframe: true }), 3000, false) + + const live = buffer.keyframeBefore(Number.POSITIVE_INFINITY) + + expect([ + during, + live?.time, + buffer.keyframeBefore(live!.order), + ]).toEqual([undefined, 3000000, undefined]) + }) + }) }) diff --git a/src/lib/camera/buffer/CameraBuffer.ts b/src/lib/camera/buffer/CameraBuffer.ts index a12bf8113..3c0c20db9 100644 --- a/src/lib/camera/buffer/CameraBuffer.ts +++ b/src/lib/camera/buffer/CameraBuffer.ts @@ -68,6 +68,12 @@ export interface BufferedSample { * handed the sample one. */ readonly wallClock?: number + /** + * Whether the sample is a recording's lead-up, video or sound its stream states as taken before an on-demand recording's start, or a sound that states + * no time handed over on such a stream ahead of its first live picture, whether or not any lead-up video comes with it, which the recorder reads and no + * viewer is sent: present, as `true`, only on such a sample. + */ + readonly leadUp?: true /** * The sample's decode time in whole microseconds, which the buffer compares its tracks on. */ @@ -184,6 +190,9 @@ interface TrackRun { * * The buffer offers one walk from a keyframe on, which a recording's segments read and a view's opening reads. A view's opening holds no place: it reads * the walk from its keyframe while the buffer keeps that keyframe, and once the buffer lets it go reads the buffer's keyframes again. + * + * A sample its tier's demand hands over as a recording's lead-up is kept with that mark, and the buffer treats it as any other sample in every rule + * above. The recorder reads it, while its keyframe lookup answers no keyframe that is lead-up, which means no view opens on one. */ export class TierBuffer { /** @@ -308,9 +317,10 @@ export class TierBuffer { * ends it on a track it holds a run of, a sample that brings a mark and a leap ending it once. The mark is spent at this sample whatever it ends. * @param sample - The sample, whose octets the buffer keeps as they are. * @param moment - The moment the sample arrived, in milliseconds of the steady clock. + * @param leadUp - Whether the sample is a recording's lead-up, as the tier's demand reads it, which the kept sample is marked with. */ - take(sample: Mp4StreamSample, moment: number): void { - const kept = keptOf(sample, moment, this.fragmentCount, this.sampleCount++) + take(sample: Mp4StreamSample, moment: number, leadUp = false): void { + const kept = keptOf(sample, moment, this.fragmentCount, this.sampleCount++, leadUp) const { medium } = sample.track const run = this.runs[medium] const restarted = this.marked && this.holdsRun @@ -408,12 +418,18 @@ export class TierBuffer { } /** - * The latest keyframe the buffer keeps that the stream delivered before a place in its delivery order. + * The latest keyframe the buffer keeps that the stream delivered before a place in its delivery order, and none where that keyframe is a recording's + * lead-up: a demand's lead-up video comes ahead of all its live video, which means no live keyframe stands before the place then. Every view's opening, + * every answer to a viewer's keyframe request and every snapshot reads its keyframe here. * @param before - The place, a sample's order, which the keyframe stands before. - * @returns The keyframe, or `undefined` when the buffer keeps none before that place. + * @returns The keyframe, or `undefined` when the buffer keeps none before that place or the latest it keeps there is a recording's lead-up. */ keyframeBefore(before: number): BufferedSample | undefined { - return this.keyframes.findLast(keyframe => keyframe.order < before) + const keyframe = this.keyframes.findLast(kept => kept.order < before) + + return (keyframe?.leadUp === true) + ? undefined + : keyframe } /** @@ -722,12 +738,47 @@ export function takenAt(sample: BufferedSample): number { } // A sample as the buffer keeps it: its own octets and times, with its decode time in microseconds, the moment it arrived, the fragment it arrived in, its -// place in the delivery order and the wall clock its stream states for it, where it states one. Each shape is a literal of its own, which builds a kept -// sample once and leaves out a wall clock its stream does not state rather than holding it undefined. -function keptOf(sample: Mp4StreamSample, moment: number, fragment: number, order: number): KeptSample { +// place in the delivery order, the wall clock its stream states for it, where it states one, and the mark of a recording's lead-up, where its demand marks +// it. Each shape is a literal of its own, which builds a kept sample once and leaves out a wall clock its stream does not state and a mark the sample does +// not carry rather than holding them undefined. A marked sample with no wall clock is a sound that states no time, which a recording's demand marks inside +// its lead-up window up to its first video that is no lead-up, whether or not lead-up video came before it. +function keptOf(sample: Mp4StreamSample, moment: number, fragment: number, order: number, leadUp: boolean): KeptSample { const { compositionOffset, data, decodeTime, duration, sync, track, wallClock } = sample const time = Number(decodeTime * MICROSECONDS / BigInt(track.timescale)) + if (leadUp) { + return wallClock === undefined + ? { + arrival: moment, + compositionOffset, + data, + decodeTime, + duration, + fragment, + leadUp, + order, + settled: false, + sync, + time, + track, + } + : { + arrival: moment, + compositionOffset, + data, + decodeTime, + duration, + fragment, + leadUp, + order, + settled: false, + sync, + time, + track, + wallClock, + } + } + return wallClock === undefined ? { arrival: moment, diff --git a/src/lib/camera/buffer/TierKeeper.spec.ts b/src/lib/camera/buffer/TierKeeper.spec.ts index 831b04a98..2cffb4ffc 100644 --- a/src/lib/camera/buffer/TierKeeper.spec.ts +++ b/src/lib/camera/buffer/TierKeeper.spec.ts @@ -481,7 +481,7 @@ describe('tierKeeper', () => { ] const readings: number[][] = [] - keeper.raise('kept-running') + keeper.raise('keepRunning') await settle() readings.push(reading()) keeper.raise('recording') @@ -490,7 +490,7 @@ describe('tierKeeper', () => { keeper.release('recording') readings.push(reading()) keeper.raise('recording') - keeper.release('kept-running') + keeper.release('keepRunning') readings.push(reading()) keeper.release('recording') await settle() @@ -498,7 +498,7 @@ describe('tierKeeper', () => { keeper.raise('recording') await settle() keeper.close() - keeper.raise('kept-running') + keeper.raise('keepRunning') readings.push(reading()) keeper.release('recording') await settle() @@ -614,6 +614,78 @@ describe('tierKeeper', () => { }) }) + describe('the reason its join states', () => { + // A keeper of no prebuffer, the on-demand mode's, states recording while the recording reason stands, and one of a prebuffer states keepRunning. + const KEEPERS = [ + { prebuffer: 0, recording: 'recording' }, + { prebuffer: 2000, recording: 'keepRunning' }, + ] as const + + // The reason each start of the keeper's tier read, in the order of the starts. + function reasons(delegate: ScriptedTierDelegate): string[] { + return streamsOf(delegate).map(({ reason }) => reason) + } + + // A keeper of the prebuffer given on the fake clock, whose tier's failed streams warn on no console. + function fakedKeeper(prebuffer: number): Rig { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + return rig(prebuffer) + } + + it.each(KEEPERS)('states keepRunning on a keeper of a prebuffer of $prebuffer raised for keepRunning, and a raise for the recording reason onto ' + + 'that running hold starts nothing', async ({ prebuffer }) => { + const { delegate, keeper } = fakedKeeper(prebuffer) + + keeper.raise('keepRunning') + await settle() + keeper.raise('recording') + await settle() + + expect(reasons(delegate)).toEqual(['keepRunning']) + }) + + it.each(KEEPERS)('states $recording on a keeper of a prebuffer of $prebuffer raised for the recording reason alone', async ({ prebuffer, recording }) => { + const { delegate, keeper } = fakedKeeper(prebuffer) + + keeper.raise('recording') + await settle() + + expect(reasons(delegate)).toEqual([recording]) + }) + + it.each(KEEPERS)('states $recording on a keeper of a prebuffer of $prebuffer at its join after a failure while both reasons stand', async ({ + prebuffer, + recording, + }) => { + const { delegate, keeper } = fakedKeeper(prebuffer) + + keeper.raise('keepRunning') + keeper.raise('recording') + await settle() + streamOf(delegate).fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + expect(reasons(delegate)).toEqual(['keepRunning', recording]) + }) + + it.each(KEEPERS)('states $recording on a keeper of a prebuffer of $prebuffer at the join of a raiseNow for the recording reason that clears an ' + + 'armed ask while keepRunning stands', async ({ prebuffer, recording }) => { + const { delegate, keeper } = fakedKeeper(prebuffer) + + keeper.raise('keepRunning') + await settle() + streamOf(delegate).fail('The camera went away.') + await vi.advanceTimersByTimeAsync(10) + keeper.raiseNow('recording') + + expect(reasons(delegate)).toEqual(['keepRunning', recording]) + }) + }) + describe('a release while the tier\'s start is pending', () => { it('leaves the keeper doing nothing more after a release, a reset and a removal, the start settling afterwards and the reset\'s own withdrawal among ' + 'them', async () => { @@ -751,7 +823,7 @@ describe('tierKeeper', () => { pendingStart(delegate) - const other = table.hold(table.videoTiers.get(1)!, scriptedHolder()) + const other = table.hold(table.videoTiers.get(1)!, scriptedHolder(), 'recording') await vi.advanceTimersByTimeAsync(10000) other.release() @@ -1974,5 +2046,289 @@ describe('tierKeeper', () => { }, ) }) + + describe('an open\'s ask', () => { + // The moment of each start the delegate was handed, on the faked clock, which a row's script records as each start is called. + let started: number[] = [] + + // The moments of the starts a row's script recorded, each from the moment given. + function startsFrom(from: number): number[] { + return started.map(moment => moment - from) + } + + // Refuses every start of the delegate at once, each recorded at its moment. + function refusing(delegate: ScriptedTierDelegate): void { + started = [] + delegate.tierDemandStarted.mockImplementation(async () => { + started.push(performance.now()) + throw new Error('The camera is busy.') + }) + } + + // Whether the keeper has armed an ask. + function asking(keeper: TierKeeper): boolean { + // @ts-expect-error: private access + return keeper.askTimer !== undefined + } + + it('joins at once as raise does on a keeper not raised, its span set, and starts nothing on a closed keeper whose ask is armed, that ask joining at ' + + 'its own time', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const fresh = rig(2000) + + fresh.keeper.raiseNow('recording') + + expect([ + fresh.delegate.tierDemandStarted.mock.calls.length, + fresh.buffer().span, + ]).toEqual([1, 2000]) + + const closed = rig() + + closed.delegate.tierDemandStarted.mockRejectedValueOnce(new Error('The camera is busy.')) + closed.keeper.raise('recording') + await vi.advanceTimersByTimeAsync(0) + closed.keeper.close() + closed.keeper.raiseNow('recording') + + const calls = [closed.delegate.tierDemandStarted.mock.calls.length] + + await vi.advanceTimersByTimeAsync(999) + calls.push(closed.delegate.tierDemandStarted.mock.calls.length) + await vi.advanceTimersByTimeAsync(1) + calls.push(closed.delegate.tierDemandStarted.mock.calls.length) + + expect(calls).toEqual([1, 1, 2]) + }) + + it.each([ + { reason: 'recording' as const }, + { reason: 'keepRunning' as const }, + ])('asks in its own turn on a keeper raised for $reason whose ask is armed after a refused start, and none at the old ask\'s moment, the next ' + + 'start after a refusal of that one a second on and one tier-failed standing across the call', async ({ reason }) => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { alerts, delegate, keeper } = rig() + const from = performance.now() + + refusing(delegate) + keeper.raise(reason) + await vi.advanceTimersByTimeAsync(500) + keeper.raiseNow('recording') + + const inTurn = startsFrom(from) + + await vi.advanceTimersByTimeAsync(2500) + + expect([ + inTurn, + startsFrom(from), + kinds(alerts), + ]).toEqual([ + [0, 500], + [0, 500, 1500], + ['tier-failed'], + ]) + }) + + it.each([ + { + hold: 'a start pending', + raised: async ({ delegate, keeper }: Rig): Promise => { + pendingStart(delegate) + keeper.raise('keepRunning') + await settle() + }, + }, + { + hold: 'a stream running', + raised: async ({ delegate, keeper }: Rig): Promise => { + keeper.raise('keepRunning') + await settle() + streamOf(delegate).write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + streamOf(delegate).write(fragmentAt(0, true)) + }, + }, + { + hold: 'the wait on a failed demand another holder keeps', + raised: async ({ delegate, keeper, table }: Rig): Promise => { + keeper.raise('keepRunning') + await settle() + streamOf(delegate).write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + streamOf(delegate).write(fragmentAt(0, true)) + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + streamOf(delegate).fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + }, + }, + ])('leaves a hold that stands as it stands on a keeper with $hold, calling no tierDemandStarted, joining no second hold and setting the span', + async ({ raised }) => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const kept = rig(2000) + + await raised(kept) + + const before = kept.delegate.tierDemandStarted.mock.calls.length + const consumers = streamOf(kept.delegate).statistics().consumers + + kept.keeper.raiseNow('recording') + await settle() + + expect([ + kept.delegate.tierDemandStarted.mock.calls.length - before, + streamOf(kept.delegate).statistics().consumers - consumers, + kept.buffer().span, + ]).toEqual([0, 0, 2000]) + }) + + // The open's own turn cannot show a second hold over the wait on a failed demand, which forms only once that demand leaves the tier: the row reads + // on until the other holder's release ends it. + it('leaves the wait on a failed demand another holder keeps as it stands, starting nothing in its turn, and joins one hold once that demand leaves ' + + 'the tier', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { delegate, keeper, table } = rig(2000) + + keeper.raise('keepRunning') + await settle() + streamOf(delegate).write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + streamOf(delegate).write(fragmentAt(0, true)) + + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + + streamOf(delegate).fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + const before = delegate.tierDemandStarted.mock.calls.length + + keeper.raiseNow('recording') + await settle() + + const inTurn = delegate.tierDemandStarted.mock.calls.length - before + + view.release() + await settle() + await vi.advanceTimersByTimeAsync(0) + await settle() + + expect([ + inTurn, + delegate.tierDemandStarted.mock.calls.length - before, + streamOf(delegate).statistics().consumers, + ]).toEqual([0, 1, 1]) + }) + + it('starts nothing on a keeper whose wait has doubled past the first and whose latest ask\'s start pends, and asks a second after that start\'s ' + + 'refusal', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { delegate, keeper } = rig() + const from = performance.now() + + refusing(delegate) + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(1000) + + // The third start, at 3 seconds after refusals at 0 and 1, pends until the row refuses it. + const pending = deferred() + + delegate.tierDemandStarted.mockImplementationOnce(async () => { + started.push(performance.now()) + await pending.promise + }) + await vi.advanceTimersByTimeAsync(2500) + keeper.raiseNow('recording') + + const inTurn = startsFrom(from) + + await vi.advanceTimersByTimeAsync(500) + pending.reject(new Error('The camera is busy.')) + await vi.advanceTimersByTimeAsync(2000) + + expect([ + inTurn, + startsFrom(from), + ]).toEqual([ + [0, 1000, 3000], + [0, 1000, 3000, 5000], + ]) + }) + + it('leaves the ask a fresh join lost in its own turn armed, the stream failed inside its start, the next start a second on and the one after a ' + + 'refusal of that one two seconds on', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { delegate, keeper } = rig() + const from = performance.now() + + refusing(delegate) + delegate.tierDemandStarted.mockImplementationOnce((stream) => { + started.push(performance.now()) + stream.fail('The camera went away.') + + return Promise.resolve() + }) + keeper.raiseNow('recording') + + const inTurn = [ + startsFrom(from), + asking(keeper), + ] + + await vi.advanceTimersByTimeAsync(4000) + + expect([ + inTurn, + startsFrom(from), + ]).toEqual([ + [ + [0], + true, + ], + [0, 1000, 3000], + ]) + }) + + it('joins one hold at once on a keeper whose ask is armed and none at a second call while that join\'s start pends, its demand ending once the ' + + 'start settles and the reason is released', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { delegate, keeper } = rig() + + delegate.tierDemandStarted.mockRejectedValueOnce(new Error('The camera is busy.')) + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(0) + + const pending = pendingStart(delegate) + + keeper.raiseNow('recording') + keeper.raiseNow('recording') + + const stream = streamOf(delegate) + const joined = [delegate.tierDemandStarted.mock.calls.length, stream.statistics().consumers] + + pending.resolve() + await settle() + keeper.release('recording') + await settle() + + expect([ + joined, + endsOf(delegate), + ]).toEqual([ + [2, 1], + 1, + ]) + }) + }) }) }) diff --git a/src/lib/camera/buffer/TierKeeper.ts b/src/lib/camera/buffer/TierKeeper.ts index cc7af470e..6589dc143 100644 --- a/src/lib/camera/buffer/TierKeeper.ts +++ b/src/lib/camera/buffer/TierKeeper.ts @@ -1,5 +1,6 @@ import type { CameraReporter } from '../diagnostics/CameraReporter.js' import type { CameraProblemKind } from '../diagnostics/problems.js' +import type { TierDemandReason } from '../StreamingOptions.js' import type { Tier, TierHold, TierHolder, TierTable } from '../TierTable.js' import type { BufferedSample, BufferPlace, TierBuffer } from './CameraBuffer.js' @@ -14,10 +15,11 @@ const FIRST_WAIT = 1000 const LONGEST_WAIT = 30 * 1000 /** - * Why the library holds a tier: it is the recorded tier and the user's switch allows recording, or it is marked `keepRunning` and the user's switch - * allows streaming, each while the camera is in service, its accessory published and its source not stated away. + * Why the library holds a tier, in the words a tier's stream states its demand's reason in: `'recording'`, the recorded tier, held while the user's switch + * allows recording in the prebuffered mode and while a recording is open or motion is detected in the on-demand mode, or `'keepRunning'`, a tier marked + * `keepRunning` while the user's switch allows streaming, each while the camera is in service, its accessory published and its source not stated away. */ -export type TierKeeperReason = 'kept-running' | 'recording' +export type TierKeeperReason = Exclude /** * What a keeper holds and how it reaches it: the callback that tells an open recording of a gap, the prebuffer the tier's buffer spans while the keeper @@ -31,7 +33,8 @@ export interface TierKeeperOptions { */ readonly gap?: () => void /** - * How far back the tier's buffer reaches while the keeper holds the tier for its recording, in milliseconds. + * How far back the tier's buffer reaches while the keeper holds the tier for its recording, in milliseconds. A prebuffer of 0, the on-demand mode's, is + * also what has the keeper's join state `'recording'` for the demand it raises while the recording reason stands. */ readonly prebuffer: number /** @@ -128,10 +131,12 @@ class KeptHold implements BufferPlace, TierHolder { /** * The library's own hold of one video tier, the one keeper of its tier, kept for as long as any of its reasons stands: raised for its first reason, it * joins the tier through the table with no consumer, with a holder that carries no connection, which raises the tier's demand and calls - * `tierDemandStarted` when the tier has none, and reads its clocks from a place of its own in the tier's buffer, which holds no keyframe; released from - * its last, it leaves the demand, which ends with its last join as any demand does, and every clock it runs stops. The tier's buffer spans the prebuffer - * while the recording reason stands and nothing otherwise, the head moving at once as the span falls, whatever other reason holds the tier. A closed - * keeper takes no reason, and once the reasons that stood are released it holds nothing, whatever is raised after. + * `tierDemandStarted` when the tier has none, stating the reason that demand's stream reads from the reasons standing at that join, `'recording'` while the + * recording reason stands on a keeper of no prebuffer and `'keepRunning'` otherwise, and reads its clocks from a place of its own in the tier's buffer, + * which holds no keyframe; released from its last, it leaves the demand, which ends with its last join as any demand does, and every clock it runs + * stops. The tier's buffer spans the prebuffer while the recording reason stands and nothing otherwise, the head moving at once as the span falls, + * whatever other reason holds the tier. A closed keeper takes no reason, and once the reasons that stood are released it holds nothing, whatever is + * raised after. * * A start still pending is waited on as the engine's joins wait, with no bound of the keeper's own: the start's own bound, `DELEGATE_CALL_TIMEOUT` counted * once from its call whoever joined it, withdraws a start that never settles, the hold among the joins it refuses, and a join onto a demand whose start is @@ -152,7 +157,8 @@ class KeptHold implements BufferPlace, TierHolder { * * An outage ends at the tier's next picture and raises at most one `tier-stalled` and one `tier-failed`, and one `tier-resumed` as it ends: a camera * that stays down is told of once however many asks it takes, as its demands tell its silence once. Each ask is a fresh join after a wait that doubles - * from a second to its longest and stays there, and the waits start over once the tier hands over a keyframe. An ask that finds the tier's demand failed + * from a second to its longest and stays there, and the waits start over once the tier hands over a keyframe and at each {@link TierKeeper.raiseNow}, + * the entry a recording's open makes, which clears an ask the keeper has armed and joins at once. An ask that finds the tier's demand failed * while other holders keep it releases its join, waits for that demand to leave the tier, its registrations released first and not awaited, and joins * again, with no problem and no wait doubled. A release ends an outage with no problem, cancels every timer, and arms no ask, a wait for a failed * demand's end among them. @@ -211,6 +217,36 @@ export class TierKeeper implements Disposable { this.join() } + /** + * Adds a reason to hold the tier as {@link raise} does, and asks for the tier now where the keeper waits to ask again: a recording's open, which must + * not wait on a retry the hub's own wait outlasts. A closed keeper does nothing. In every state the waits start over at the first, which gives every + * open the same retries. Where the keeper is raised with its ask armed, the ask's timer is cleared and the keeper joins at once, and in every other state + * the call is {@link raise}: a keeper not raised joins, and a hold that stands, its start pending, its stream running or its wait on a failed demand + * other holders keep, is left as it stands. + * @param reason - The reason added. + */ + raiseNow(reason: TierKeeperReason): void { + if (this.closed) { + return + } + + /* The armed ask is read and the wait set back before the reason is added: a fresh raise whose join is lost in its own turn, a stream failed inside + * the start or a failed demand no other holder keeps, arms an ask of its own and doubles the wait before raise returns, and that ask is left to its + * timer. The armed ask's timer is cleared and never left to fire, since its callback joins, which would set a second hold over the first, and the + * field is set back with it, since a later open reads the field and a cleared timer's callback never runs to unset it. + */ + const armed = (this.target !== undefined) && (this.askTimer !== undefined) + + this.wait = FIRST_WAIT + this.raise(reason) + + if (armed) { + clearTimeout(this.askTimer) + this.askTimer = undefined + this.join() + } + } + /** * Removes a reason to hold the tier, and releases the hold once no reason stands, doing nothing while it is not raised: every clock and a pending ask * stop, an open outage ends with no problem, the span of the tier's buffer falls to nothing at once, and the hold's join leaves the tier's demand, whose end @@ -273,6 +309,15 @@ export class TierKeeper implements Disposable { : 0 } + // The reason the keeper's join states for a demand it raises, read from what the span reads, the recording reason and the prebuffer: 'recording' while + // the recording reason stands on a keeper of no prebuffer, the on-demand mode's, and 'keepRunning' otherwise, a prebuffered recording's hold among them, + // since its stream runs whether or not a hub records. + private get demandReason(): TierKeeperReason { + return (this.reasons.has('recording') && (this.options.prebuffer === 0)) + ? 'recording' + : 'keepRunning' + } + // Releases the hold, and does nothing while it is not raised. private releaseHold(): void { if (this.target === undefined) { @@ -319,7 +364,7 @@ export class TierKeeper implements Disposable { this.held = held tier.buffer.takePlace(held) - const hold = held.hold = table.hold(tier, held) + const hold = held.hold = table.hold(tier, held, this.demandReason) if (held.dropped) { hold.release() diff --git a/src/lib/camera/diagnostics/debugChannels.ts b/src/lib/camera/diagnostics/debugChannels.ts index 52e63f0c8..e1a321285 100644 --- a/src/lib/camera/diagnostics/debugChannels.ts +++ b/src/lib/camera/diagnostics/debugChannels.ts @@ -35,9 +35,10 @@ export type DebugName = typeof DEBUG_NAMES[number] * yet, its kind, its sentence, and the values its sentence names under the names its call site holds them by. `accessoryUUID`, `kind` and `sentence` are * promised on every event, and every field of these events is promised too: `recording-ended` on `HAP-NodeJS:Camera:BufferRecorder` carries `dropped`, * `outcome`, `seconds`, `segments`, `sensorUUID`, `streamId` and `tierId`, its `seconds` the length of the video in the segments it counts, the prebuffer - * among them, and `clip-finalized` on `HAP-NodeJS:Camera:CMAFRecording` carries `clipID`, `seconds` and `segments`, its `seconds` the durations its media - * playlist states for the segments it uploaded, summed. A sentence's wording is never a promise, and every other event's kind and details may change in - * any release. + * among them where the camera keeps one, and `reason`, the reason a hub named as it closed the recording, present only where a hub's close ended it, + * and `clip-finalized` on `HAP-NodeJS:Camera:CMAFRecording` carries `clipID`, `seconds` and `segments`, its `seconds` the durations its media playlist + * states for the segments it uploaded, summed. A sentence's wording is never a promise, and every other event's kind and details may change in any + * release. */ export interface CameraDebugEvent { readonly accessoryUUID?: string diff --git a/src/lib/camera/diagnostics/problems.spec.ts b/src/lib/camera/diagnostics/problems.spec.ts index 109cb844c..a5b437da6 100644 --- a/src/lib/camera/diagnostics/problems.spec.ts +++ b/src/lib/camera/diagnostics/problems.spec.ts @@ -178,3 +178,59 @@ describe('onCameraProblem', () => { ]) }) }) + +describe('the cause a problem carries', () => { + // The members every tier problem the rows type shares beside its kind and its cause. + const TIER = { + level: 'warning', + sensorUUID: SENSOR, + sentence: 'The synthetic tier has a problem.', + tierId: 1, + } as const + + // A problem's cause, read once its kind narrows it to an arm that states one. + function causeOf(problem: CameraProblemReport): string | undefined { + switch (problem.kind) { + case 'recording-declined': + case 'recording-timed-out': + case 'stream-failed': + return problem.cause + + default: + return undefined + } + } + + it('types a cause of its own kind on each kind that states one, absent alone on recording-timed-out, and refuses another kind\'s cause, a missing ' + + 'one and one on a kind that states none', () => { + const accepted: CameraProblemReport[] = [ + { ...TIER, cause: 'silent-gap', kind: 'stream-failed' }, + { ...TIER, cause: 'undecodable-keyframe', kind: 'recording-declined' }, + { ...TIER, cause: 'no-segment', kind: 'recording-timed-out' }, + { ...TIER, kind: 'recording-timed-out' }, + ] + const refused: CameraProblemReport[] = [ + // @ts-expect-error: a stream-failed problem names a stream's cause, never a declined recording's. + { ...TIER, cause: 'undecodable-keyframe', kind: 'stream-failed' }, + // @ts-expect-error: a stream-failed problem always names its cause. + { ...TIER, kind: 'stream-failed' }, + // @ts-expect-error: a recording-timed-out problem names what the recording had not sent, never a stream's cause. + { ...TIER, cause: 'silent-gap', kind: 'recording-timed-out' }, + // @ts-expect-error: a tier-stalled problem names no cause. + { ...TIER, cause: 'silent-gap', kind: 'tier-stalled' }, + ] + + expect(accepted.map(causeOf)).toEqual([ + 'silent-gap', + 'undecodable-keyframe', + 'no-segment', + undefined, + ]) + expect(refused.map(({ kind }) => kind)).toEqual([ + 'stream-failed', + 'stream-failed', + 'recording-timed-out', + 'tier-stalled', + ]) + }) +}) diff --git a/src/lib/camera/diagnostics/problems.ts b/src/lib/camera/diagnostics/problems.ts index ae98ad79a..ae62ba42a 100644 --- a/src/lib/camera/diagnostics/problems.ts +++ b/src/lib/camera/diagnostics/problems.ts @@ -33,7 +33,71 @@ export type CameraProblem = { /** * A problem of one video tier of a video sensor. */ - readonly kind: 'buffer-trimmed' | 'recording-declined' | 'segment-over-cap' | 'stream-failed' | 'stream-fault' | 'tier-failed' | 'tier-resumed' | 'tier-stalled' + readonly kind: 'buffer-trimmed' | 'segment-over-cap' | 'stream-fault' | 'tier-failed' | 'tier-resumed' | 'tier-stalled' + /** + * The video sensor the problem concerns, in lowercase. + */ + readonly sensorUUID: string + /** + * The video tier the problem concerns. + */ + readonly tierId: number +} | { + /** + * A video tier's stream failed, and every session on the tier ends. + */ + readonly kind: 'stream-failed' + /** + * Why the stream failed: + * + * - `plugin`: the plugin called the stream's `fail`. + * - `refused`: the library refused the stream's bytes. + * - `silent-start`: the stream handed over no first picture within 30 seconds of its start's settling. + * - `silent-gap`: the stream handed over no picture for 10 seconds. + * - `silent-reconnect`: the stream handed over no picture within 30 seconds of its source being stated reconnecting. + */ + readonly cause: 'plugin' | 'refused' | 'silent-gap' | 'silent-reconnect' | 'silent-start' + /** + * The video sensor the problem concerns, in lowercase. + */ + readonly sensorUUID: string + /** + * The video tier the problem concerns. + */ + readonly tierId: number +} | { + /** + * A hub's recording declined by a camera that records with a prebuffer, its camera buffer not being ready to serve it. + */ + readonly kind: 'recording-declined' + /** + * Why the camera buffer was not ready: + * + * - `buffer-filling`: the camera buffer does not yet hold the prebuffer. + * - `undecodable-keyframe`: the stream carries a keyframe without its parameter sets. + */ + readonly cause: 'buffer-filling' | 'undecodable-keyframe' + /** + * The video sensor the problem concerns, in lowercase. + */ + readonly sensorUUID: string + /** + * The video tier the problem concerns. + */ + readonly tierId: number +} | { + /** + * A hub's close of a recording with the reason TIMEOUT. + */ + readonly kind: 'recording-timed-out' + /** + * What the recording had not sent as the hub gave up, absent where a media segment had left, the library then not knowing why the hub gave up: + * + * - `no-picture`: the recording still waited, its stream having handed over no picture since the hub's open. + * - `no-keyframe`: the recording still waited, its stream having handed over pictures and no keyframe a decoder can read. + * - `no-segment`: the recording opened at a keyframe and had sent no media segment. + */ + readonly cause?: 'no-keyframe' | 'no-picture' | 'no-segment' /** * The video sensor the problem concerns, in lowercase. */ @@ -127,12 +191,18 @@ export type CameraProblem = { * - `segment-over-cap`: the stretch from one keyframe to the next alone reached the cap on an uploaded segment, and the segment left as it stood. * - `store-full`: the camera's served recordings passed their ceiling of 100 MB and released their oldest bytes, whoever needed them, naming the recorded * sensor. - * - `recording-declined`: a hub's recording was declined, the camera buffer not being ready to serve it. + * - `recording-declined`: a hub's recording was declined by a camera that records with a prebuffer, the camera buffer not being ready to serve it, its + * `cause` naming why: `buffer-filling` while the buffer does not yet hold the prebuffer, or `undecodable-keyframe` for a stream that carries a keyframe + * without its parameter sets. + * - `recording-timed-out`: a hub closed a recording with the reason TIMEOUT, which a hub gives when no segment of the recording reached it in time, its + * `cause` naming what the recording had not sent: `no-picture` for one still waiting whose stream handed over no picture, `no-keyframe` for one still + * waiting whose stream handed over no keyframe a decoder can read, or `no-segment` for one that opened and sent no media segment, and absent once a + * media segment had left. * - `plugin-failure`: a function of the plugin's threw, rejected, did not settle within its bound, or answered a value the library cannot use. * - `stream-failed`: a tier's stream failed, by the plugin's own `fail`, by the library refusing its bytes or by a silence, whoever holds the tier, and * every session on the tier ends. A silence is a stream that hands over no first picture within 30 seconds of its start's settling, or no picture for 10 seconds * after one or for 30 seconds from its source being stated reconnecting, sound counting for nothing, and it is told once until the tier hands over a - * picture again. + * picture again. Its `cause` names the failure: `plugin`, `refused`, or the silence, `silent-start`, `silent-gap` or `silent-reconnect`. * - `stream-fault`: a tier's stream carries a fault the library sends on as it stands: a keyframe without its parameter sets, under `strict` a rate past * twice the tier's peak, or no Opus track in the stream of the sound tier of a sensor whose audio states its source `'shared'`. * - `view-failed`: a view from away ended on a failure, or never started: no answer accepted, a lost connection, a failed DTLS transport, no connection diff --git a/src/lib/camera/index.ts b/src/lib/camera/index.ts index 6396be9ae..f31d43549 100644 --- a/src/lib/camera/index.ts +++ b/src/lib/camera/index.ts @@ -17,6 +17,7 @@ export type { ResourceScope, TalkbackSink, Talker, + TierDemandReason, TierStream, TierStreamStatistics, } from './StreamingOptions.js' diff --git a/src/lib/camera/recording/BufferRecorder.spec.ts b/src/lib/camera/recording/BufferRecorder.spec.ts index 71520259a..4cddd9f62 100644 --- a/src/lib/camera/recording/BufferRecorder.spec.ts +++ b/src/lib/camera/recording/BufferRecorder.spec.ts @@ -8,7 +8,7 @@ import type { Mp4Sample } from '../mp4/mp4Boxes.js' import type { RecordingPacket } from '../RecordingManagement.js' import type { CameraAudioTier, TierStream } from '../StreamingOptions.js' import type { TierTable } from '../TierTable.js' -import type { BufferRecorder } from './BufferRecorder.js' +import type { BufferRecorder, RecorderPacket, RecordingAdmission } from './BufferRecorder.js' import { Buffer } from 'node:buffer' @@ -16,11 +16,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { bufferCamera, + disposedOf, endsOf, FIRST_VIDEO_SENSOR, FRAME_TICKS, frames, handPublishedContext, + pendingStart, SOUND_TICKS, streamsOf, UNREAD_SOUND, @@ -38,9 +40,9 @@ import { tierStreamInitialization, } from '../../../test-utils/mp4Fixtures.js' import { problemsOf } from '../../../test-utils/reporterFixtures.js' -import { settle } from '../../../test-utils/settle.js' +import { fakeTimeoutSignals, settle } from '../../../test-utils/settle.js' import { Characteristic } from '../../Characteristic.js' -import { CameraController } from '../../controller/index.js' +import { CameraController, DoorbellController } from '../../controller/index.js' import { HDSProtocolError, HDSProtocolSpecificErrorReason, HDSStatus, Protocols, Topics } from '../../datastream/index.js' import { Service } from '../../Service.js' import * as uuid from '../../util/uuid.js' @@ -70,6 +72,9 @@ interface Rig { interface Reading { readonly packets: RecordingPacket[] done: boolean + // What the recording's iterable threw as it ended, absent for one that ended without: the close naming a reason of an end the recorder made before + // any media segment went. + thrown?: unknown } // One segment as the box readers read it back: each track's samples with their decode times. @@ -90,21 +95,32 @@ afterEach(() => { vi.useRealTimers() }) -// The fixture's two-sensor camera with the camera capabilities block, recording its first video sensor's best tier from its camera buffer with the -// prebuffer and the shouldRecord given, that sensor's audio stating the source given or none, its streaming delegate a script, configured, handed a -// published context of an accessory of its own, whose problems it reads, and its recording allowed unless the row says otherwise. -function rig({ allowed = true, audio = true, prebuffer = 0, shouldRecord, source }: { +/* The fixture's two-sensor camera with the camera capabilities block, recording its first video sensor's best tier from its camera buffer with the + * shouldRecord given, that sensor's audio stating the source given or none, its streaming delegate a script, configured, handed a published context of an + * accessory of its own, whose problems it reads, and its recording allowed unless the row says otherwise. Given a prebuffer, it records in the + * prebuffered mode at that prebuffer, its recorded tier held while recording is allowed. Given none, it records on demand, its recorded tier marked + * keepRunning unless the row stops it: a running tier whose buffer spans nothing, held while streaming is allowed, which serves each recording at once + * from its latest keyframe with no lead-up. + */ +function rig({ allowed = true, audio = true, kept = true, prebuffer, shouldRecord, source }: { allowed?: boolean audio?: boolean + kept?: boolean prebuffer?: number shouldRecord?: CameraBufferRecordingOptions['shouldRecord'] source?: CameraAudioTier['source'] } = {}): Rig { - const { delegate, options, stream } = bufferCamera({ prebuffer, shouldRecord }) + const { delegate, options, stream } = bufferCamera((prebuffer === undefined) + ? { mode: 'onDemand', shouldRecord } + : { prebuffer, shouldRecord }) const [recordedSensor] = options.cameraCapabilities.videoSensors recordedSensor.audio = { ...recordedSensor.audio, source } + if ((prebuffer === undefined) && kept) { + recordedSensor.tiers = recordedSensor.tiers.map(tier => ({ ...tier, keepRunning: tier.id === 1 })) + } + const camera = new CameraController(options) const accessoryUUID = uuid.generate(`buffer recorder spec camera ${cameras.length}`) const { problems: alerts } = problemsOf(accessoryUUID) @@ -155,9 +171,10 @@ function initialize(stream: TierStream, options: { parameterSets?: readonly Buff stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS, ...options })) } -// A rig as the options given make it, whose recorded tier's buffer is ready, its stream started and a second and a half of its frames written. +// A rig as the options given make it, by default in the prebuffered mode at a prebuffer of a second, whose recorded tier's buffer is ready, its stream +// started and a second and a half of its frames written. function ready(options: Parameters[0] = {}): Rig { - const made = rig(options) + const made = rig({ prebuffer: 1000, ...options }) initialize(made.stream()) frames(made.stream(), 0, 45) @@ -202,13 +219,17 @@ function resized(width: number, height: number): Buffer { return data } -// Reads a recording's packets as they come, in the background, until it ends. +// Reads a recording's packets as they come, in the background, until it ends, keeping what its iterable throws as it ends. function read(recording: AsyncIterable): Reading { const reading: Reading = { done: false, packets: [] } void (async () => { - for await (const packet of recording) { - reading.packets.push(packet) + try { + for await (const packet of recording) { + reading.packets.push(packet) + } + } catch (error) { + reading.thrown = error } reading.done = true @@ -232,6 +253,13 @@ function segmentsOf(reading: Reading): ReadSegment[] { return reading.packets.slice(1).filter(({ data }) => data.length > 1).map(({ data }) => segmentOf(data)) } +// The reason of the close a recording's iterable threw as it ended, absent for one that ended without. +function closeOf({ thrown }: Reading): HDSProtocolSpecificErrorReason | undefined { + return (thrown instanceof HDSProtocolError) + ? thrown.reason + : undefined +} + // The end marker: one zero octet marked last. const MARKER: RecordingPacket = { data: Buffer.alloc(1), @@ -255,6 +283,13 @@ function thrownBy(call: () => unknown): unknown { return undefined } +// The cause each recording-timed-out problem of a rig's camera names, read once its kind narrows it, in the order raised. +function timedOut({ alerts }: Rig): (string | undefined)[] { + return alerts.flatMap(problem => (problem.kind === 'recording-timed-out') + ? [problem.cause] + : []) +} + describe('bufferRecorder', () => { describe('an open', () => { it('refuses as busy an open on an empty buffer, a part-filled one and a tier that carries its parameter sets nowhere, each with one alert, the last ' @@ -266,7 +301,7 @@ describe('bufferRecorder', () => { frames(filling.stream(), 0, 45) const partFilled = filling.recorder.admit(2) - const bare = rig() + const bare = rig({ prebuffer: 1000 }) initialize(bare.stream(), { parameterSets: [] }) frames(bare.stream(), 0, 45) @@ -293,24 +328,28 @@ describe('bufferRecorder', () => { expect([ ...filling.alerts, ...bare.alerts, - ].map(({ kind, sentence, tierId }: Partial>) => ({ kind, sentence, tierId }))).toEqual([ + ].map(({ cause, kind, sentence, tierId }: Partial>) => ({ cause, kind, sentence, tierId }))).toEqual([ { + cause: 'buffer-filling', kind: 'recording-declined', sentence: `The library declined a hub's recording of ${tierName}, because its camera buffer does not yet hold the prebuffer of 2000 milliseconds.`, tierId: 1, }, { + cause: 'buffer-filling', kind: 'recording-declined', sentence: `The library declined a hub's recording of ${tierName}, because its camera buffer does not yet hold the prebuffer of 2000 milliseconds.`, tierId: 1, }, { + cause: undefined, kind: 'stream-fault', sentence: `The stream of ${tierName} 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.', tierId: 1, }, { + cause: 'undecodable-keyframe', kind: 'recording-declined', sentence: `The library declined a hub's recording of ${tierName}, because its stream carries a keyframe without its video, sequence and picture ` + 'parameter sets, in its sample or its initialization segment.', @@ -360,7 +399,7 @@ describe('bufferRecorder', () => { it('refuses as busy an open on a tier whose description holds the sequence and picture parameter sets alone and whose keyframes carry none, with one ' + 'alert naming a keyframe without its parameter sets, after its tier\'s stream fault', async () => { - const partial = rig() + const partial = rig({ prebuffer: 1000 }) const [, ...described] = TIER_STREAM_PARAMETER_SETS initialize(partial.stream(), { parameterSets: described }) @@ -390,7 +429,7 @@ describe('bufferRecorder', () => { it('refuses as busy an open of a camera out of service, raising no alert and telling of no recording, though its buffer filled while it was in ' + 'service', async () => { - const out = rig() + const out = rig({ prebuffer: 1000 }) initialize(out.stream()) frames(out.stream(), 0, 45) @@ -657,6 +696,7 @@ describe('bufferRecorder', () => { expect(admission).toEqual({ admitted: true, + hubClosed: expect.any(Function), serve: expect.any(Function), }) @@ -677,7 +717,7 @@ describe('bufferRecorder', () => { it('publishes one debug event naming its stream and its cause for each open it refuses, out of service, on a buffer not ready, answered false and ' + 'stopped during its shouldRecord, and none for an open it admits', async () => { const events = captureDebugEvents('HAP-NodeJS:Camera:BufferRecorder') - const away = rig() + const away = rig({ prebuffer: 1000 }) const filling = rig({ prebuffer: 2000 }) const declining = asking(() => false) const { asked: stopped } = askedThrough(leaving => leaving.camera.updateSourceState('away')) @@ -877,14 +917,15 @@ describe('bufferRecorder', () => { }) describe('its segments', () => { - it('cuts at the first keyframe 4 seconds from each opening, the segments held whole leaving at the open and each later one at the end of the fragment ' - + 'holding its closing keyframe, with the sound timed inside it that arrives after that keyframe', async () => { + it('cuts at the first keyframe 4 seconds from each opening, the segments held whole leaving at the open and each later one, on a stream whose sound ' + + 'is a frame behind, held at the end of the fragment holding its closing keyframe and sent at the end of the next, with the sound timed inside it ' + + 'that arrives after that keyframe', async () => { const opened = rig({ prebuffer: 5000 }) const { recorder } = opened const stream = opened.stream() initialize(stream) - frames(stream, 0, 166, { lag: true }) + frames(stream, 0, 166, { lag: 1 }) const reading = read(recorder.handleRecordingStreamRequest(1)) @@ -892,12 +933,18 @@ describe('bufferRecorder', () => { expect(segmentsOf(reading).length).toBe(1) - frames(stream, 166, 240, { lag: true }) + frames(stream, 166, 240, { lag: 1 }) + await settle() + + expect(segmentsOf(reading).length).toBe(1) + + // The fragment of the keyframe of 8 seconds carries the sound of the frame before it, and the next fragment the sound timed at that keyframe. + frames(stream, 240, 241, { lag: 1 }) await settle() expect(segmentsOf(reading).length).toBe(1) - frames(stream, 240, 241, { lag: true }) + frames(stream, 241, 242, { lag: 1 }) await settle() const segments = segmentsOf(reading) @@ -1260,11 +1307,12 @@ describe('bufferRecorder', () => { it('joins each segment\'s sound to the next segment\'s at zero ticks, every sound at its stream\'s own time against its picture, over streams whose sound ' + 'is in step or a fragment behind, falls on the keyframes or straddles each that closes a segment, and states half or twice its step at each ' - + 'fragment\'s last', async () => { + + 'fragment\'s last, a segment whose sound is a fragment behind held at the end of the fragment holding its closing keyframe and sent at the end of ' + + 'the next', async () => { // Half a sound later than the frames' own times, a sound straddles each keyframe, every one standing on a whole second. const straddle = (_index: number, time: number): number => time + SOUND_TICKS / 2 - for (const lag of [false, true]) { + for (const lag of [0, 1]) { for (const retimeSound of [undefined, straddle]) { for (const stated of [ (step: number) => step / 2, @@ -1284,16 +1332,23 @@ describe('bufferRecorder', () => { const reading = read(opened.recorder.handleRecordingStreamRequest(1)) - // Segments each closed at the keyframe 4 seconds after its opening one, the last at 20 seconds. + // Segments each closed at the keyframe 4 seconds after its opening one, the last at 20 seconds, still held at the end of that keyframe's + // fragment where the sound is a fragment behind. frames(stream, 1, 601, options) await settle() + const held = segmentsOf(reading).length + + frames(stream, 601, 602, options) + await settle() + const segments = segmentsOf(reading) // The stream's own sounds, each 20 ms on from the one before, those timed before 20 seconds, and its pictures before then. const first = retimeSound?.(0, 0) ?? 0 const sounds = Array.from({ length: 1000 }, (_, index) => BigInt(first + index * SOUND_TICKS)) const pictures = Array.from({ length: 600 }, (_, index) => BigInt(index * FRAME_TICKS)) + expect(held).toBe(5 - lag) expect(segments).toHaveLength(5) expect(segments.flatMap(({ audio }) => audio.map(({ decodeTime }) => decodeTime))).toEqual(sounds) expect(segments.flatMap(({ audio }) => audio.map(({ duration }) => duration))).toEqual(sounds.map(() => SOUND_TICKS)) @@ -1303,6 +1358,257 @@ describe('bufferRecorder', () => { } }) + it('holds each segment cut at the target, on a stream whose sound is timed three frames behind, until the end of the first fragment that brings a sound ' + + 'timed at or after its closing keyframe, and sends it there with every sound timed inside it, its sound joined to the next segment\'s at zero ' + + 'ticks', async () => { + const opened = rig() + const stream = opened.stream() + const options: FrameOptions = { lag: 3 } + + initialize(stream) + frames(stream, 0, 1, options) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // The fragment of the keyframe of 4 seconds and the two after it carry the sound timed before that keyframe, and the third the sound timed at it. + frames(stream, 1, 123, options) + await settle() + + expect(segmentsOf(reading).length).toBe(0) + + frames(stream, 123, 124, options) + await settle() + + expect(segmentsOf(reading).length).toBe(1) + + frames(stream, 124, 243, options) + await settle() + + expect(segmentsOf(reading).length).toBe(1) + + frames(stream, 243, 244, options) + await settle() + + const segments = segmentsOf(reading) + // The stream's own sounds, each 20 ms on from the one before, those timed before 8 seconds. + const sounds = Array.from({ length: 400 }, (_, index) => BigInt(index * SOUND_TICKS)) + + expect(segments.map(({ audio, video }) => { + const last = audio.at(-1)! + + return { + pictures: video.length, + soundEnd: last.decodeTime + BigInt(last.duration!), + soundTime: audio[0].decodeTime, + } + })).toEqual([ + { + pictures: 120, + soundEnd: 4n * 48000n, + soundTime: 0n, + }, + { + pictures: 120, + soundEnd: 8n * 48000n, + soundTime: 4n * 48000n, + }, + ]) + expect(segments.flatMap(({ audio }) => audio.map(({ decodeTime }) => decodeTime))).toEqual(sounds) + }) + + it('holds a stretch that alone reaches the cap, on a stream whose sound is timed three frames behind, until the end of the first fragment that brings a ' + + 'sound timed at or after its closing keyframe, and sends it there with every sound timed inside it and its one alert, its sound joined to the next ' + + 'segment\'s at zero ticks', async () => { + const opened = rig() + const stream = opened.stream() + const options: FrameOptions = { + gop: 90, + lag: 3, + octets: 120000, + } + + initialize(stream) + frames(stream, 0, 1, options) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // The fragment of the keyframe of 3 seconds and the two after it carry the sound timed before that keyframe, and the third the sound timed at it. + frames(stream, 1, 93, options) + await settle() + + expect(segmentsOf(reading).length).toBe(0) + expect(opened.alerts).toEqual([]) + + frames(stream, 93, 94, options) + await settle() + + expect(segmentsOf(reading).length).toBe(1) + expect(opened.alerts.map(({ kind }) => kind)).toEqual(['segment-over-cap']) + + frames(stream, 94, 184, options) + await settle() + + const segments = segmentsOf(reading) + // The stream's own sounds, each 20 ms on from the one before, those timed before 6 seconds. + const sounds = Array.from({ length: 300 }, (_, index) => BigInt(index * SOUND_TICKS)) + + expect(segments.map(({ audio, video }) => { + const last = audio.at(-1)! + + return { + pictures: video.length, + soundEnd: last.decodeTime + BigInt(last.duration!), + soundTime: audio[0].decodeTime, + } + })).toEqual([ + { + pictures: 90, + soundEnd: 3n * 48000n, + soundTime: 0n, + }, + { + pictures: 90, + soundEnd: 6n * 48000n, + soundTime: 3n * 48000n, + }, + ]) + expect(segments.flatMap(({ audio }) => audio.map(({ decodeTime }) => decodeTime))).toEqual(sounds) + }) + + it('holds a segment the cap closes at its last keyframe, on a stream whose sound is timed three frames behind, until the end of the first fragment that ' + + 'brings a sound timed at or after that keyframe, whatever later keyframe the cut was found at, and sends it there with every sound timed inside ' + + 'it', async () => { + const opened = rig() + const stream = opened.stream() + // A keyframe every other frame, and pictures of a size that takes the segment to the cap long before the target. + const options: FrameOptions = { + gop: 2, + lag: 3, + octets: 300000, + } + + initialize(stream) + frames(stream, 0, 1, options) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // The cap closes the segment at the keyframe of frame 32, found once the keyframe of frame 34 would take it to the cap, and the sound timed at frame + // 32 arrives with the fragment of frame 35. + frames(stream, 1, 35, options) + await settle() + + expect(segmentsOf(reading)).toEqual([]) + + frames(stream, 35, 36, options) + await settle() + + // The sounds whose 20 ms start falls inside the frames before 32. + expect(segmentsOf(reading).map(({ audio, video }) => [video.length, audio.length])).toEqual([ + [32, 54], + ]) + expect(opened.alerts).toEqual([]) + }) + + it('sends a segment whose sound stops ahead of its closing keyframe at the end of the fragment whose picture stands half a second past that keyframe, ' + + 'holding it at the end of the fragment a frame before, with the sound that arrived', async () => { + const opened = rig() + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 1) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // The sound stops at the frame of 110, ahead of the keyframe of 4 seconds, and the picture of frame 135 stands half a second past that keyframe. + frames(stream, 1, 110) + frames(stream, 110, 135, { sound: false }) + await settle() + + expect(segmentsOf(reading).length).toBe(0) + + frames(stream, 135, 136, { sound: false }) + await settle() + + // The sounds whose 20 ms start falls inside the frames before 110. + expect(segmentsOf(reading).map(({ audio, video }) => [video.length, audio.length])).toEqual([ + [120, 184], + ]) + }) + + it.each([ + [ + 'whose Recording Audio Active reads off at the open', + { audio: false }, + {}, + ], + [ + 'on a stream that describes no sound', + {}, + { sound: false }, + ], + ] as const)('sends each segment of a recording %s at the end of the fragment holding its closing keyframe, on a stream whose sound is timed three ' + + 'frames behind', async (_recording, made, described) => { + const opened = rig(made) + const stream = opened.stream() + const options: FrameOptions = { lag: 3 } + + initialize(stream, described) + frames(stream, 0, 1, options) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + frames(stream, 1, 120, options) + await settle() + + expect(segmentsOf(reading).length).toBe(0) + + frames(stream, 120, 121, options) + await settle() + + expect(segmentsOf(reading).length).toBe(1) + + frames(stream, 121, 240, options) + await settle() + + expect(segmentsOf(reading).length).toBe(1) + + frames(stream, 240, 241, options) + await settle() + + expect(segmentsOf(reading).map(({ audio, video }) => [video.length, audio.length])).toEqual([ + [120, 0], + [120, 0], + ]) + }) + + it('closes a segment held for its sound as it stands at a discontinuity, its pictures and the keyframe that closed it in the one segment the run\'s end ' + + 'sends, with every sound that has arrived', async () => { + const opened = rig() + const stream = opened.stream() + const options: FrameOptions = { lag: 1 } + + initialize(stream) + frames(stream, 0, 1, options) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // The fragment of the keyframe of 4 seconds carries the sound of the frame before it, which leaves the segment held at that fragment's end. + frames(stream, 1, 121, options) + await settle() + + expect(segmentsOf(reading)).toEqual([]) + + // The buffer reads a mark at the stream's next sample, which means the next run's keyframe ends the run. + stream.discontinuity() + frames(stream, 0, 1, options) + await settle() + + expect(segmentsOf(reading).map(({ audio, video }) => [video.length, audio.length])).toEqual([ + [121, 200], + ]) + expect(opened.ends).toEqual([]) + }) + it.each([ [ 'a discontinuity', @@ -1594,9 +1900,12 @@ describe('bufferRecorder', () => { return durationsOf(segment).reduce((total, duration) => total + duration, 0) } - // A rig of the prebuffer given recording no sound, its buffer ready on two seconds of frames and its recording opened from their keyframe. + // A rig of the prebuffer given recording no sound, its buffer ready on two seconds of frames and its recording opened from their keyframe. A buffer of + // no prebuffer is the on-demand mode's, its recorded tier kept running. function opened(prebuffer: number, options: FrameOptions): Rig & { reading: Reading } { - const made = rig({ audio: false, prebuffer }) + const made = rig((prebuffer === 0) + ? { audio: false } + : { audio: false, prebuffer }) initialize(made.stream()) frames(made.stream(), 0, 61, options) @@ -1627,6 +1936,86 @@ describe('bufferRecorder', () => { expect(past.ends.map(({ outcome }) => outcome)).toEqual(['failed']) }) + it('sends a stretch between keyframes that spans the reach of an on-demand recording\'s buffer, its sound a frame behind, at the end of the fragment ' + + 'holding its closing keyframe, where the picture after it would carry a place still held into the trim, and goes on with no trim', async () => { + // The frames the buffer's reach of 10 seconds holds. + const reach = 10 * 30 + const options: FrameOptions = { + gop: reach, + lag: 1, + } + const recording = rig() + + initialize(recording.stream()) + frames(recording.stream(), 0, 61, options) + + const reading = read(recording.recorder.handleRecordingStreamRequest(1)) + + // The keyframe that closes the stretch stands at the reach exactly, which the buffer keeps, and its fragment brings no sound timed at it. + frames(recording.stream(), 61, reach + 1, options) + await settle() + + expect(segmentsOf(reading).map(spanOf)).toEqual([reach * FRAME_TICKS]) + + // The pictures after that keyframe stand past the reach from the stretch's opening keyframe. + frames(recording.stream(), reach + 1, reach + 3, options) + await settle() + + expect(recording.ends).toEqual([]) + expect(recording.alerts).toEqual([]) + }) + + it('sends a segment held for its sound before the pictures of a fragment seconds long carry its place into the trim, on a stream cut off its keyframes ' + + 'whose sound is timed three frames behind, with the sound that has arrived, and goes on', async () => { + const recording = rig() + const stream = recording.stream() + // One fragment of the frames from one index up to another, a keyframe every 90 frames, carrying the sound timed three frames behind its own. + const fragment = (from: number, to: number): void => { + const first = Math.max(Math.ceil((from - 3) * 5 / 3), 0) + const last = Math.max(Math.ceil((to - 3) * 5 / 3), 0) + + stream.write(tierStreamFragment({ + picture: Array.from({ length: to - from }, (_, index) => tierPicture({ keyframe: (from + index) % 90 === 0 })), + pictureTime: BigInt(from * FRAME_TICKS), + sound: Array.from({ length: last - first }, () => soundSample(UNREAD_SOUND)), + soundTime: BigInt(first * SOUND_TICKS), + })) + } + + initialize(stream) + frames(stream, 0, 1, { + gop: 90, + lag: 3, + }) + + const reading = read(recording.recorder.handleRecordingStreamRequest(1)) + + // The keyframe of 6 seconds closes the first segment as the last picture of its fragment, which brings no sound timed at it. + fragment(1, 61) + fragment(61, 181) + await settle() + + expect(segmentsOf(reading)).toEqual([]) + + // The next fragment's pictures run past 10 seconds from the opening keyframe, the buffer's reach, before the fragment ends and brings its sound. + fragment(181, 302) + await settle() + + expect(segmentsOf(reading).map(({ audio, video }) => [video.length, audio.length])).toEqual([ + [180, 297], + ]) + expect([recording.ends, recording.alerts]).toEqual([[], []]) + + fragment(302, 422) + await settle() + + expect(segmentsOf(reading).map(({ audio, video }) => [video.length, audio.length])).toEqual([ + [180, 297], + [180, 300], + ]) + expect([recording.ends, recording.alerts]).toEqual([[], []]) + }) + it.each([ [ 'a restart', @@ -1737,20 +2126,55 @@ describe('bufferRecorder', () => { }) describe('its end', () => { - // A ready recording of one whole segment, its segment in progress opening at the keyframe of 4 seconds and holding later keyframes: its place holds - // the buffer past its span. - async function recording(options: FrameOptions = {}): Promise { - const opened = rig() + // A recording's rig with the admission that served it, whose route takes the hub's own close, and the reading of its packets. + type Opened = Rig & { admission: Extract, reading: Reading } + + /* A ready recording of one whole segment, its segment in progress opening at the keyframe of 4 seconds and holding later keyframes: its place holds + * the buffer past its span. Given a prebuffer, the camera records in the prebuffered mode at that prebuffer, its recorded tier held while recording + * is allowed, and its buffer is ready once its second frame stands a prebuffer of 1 millisecond past the keyframe it opens on. + */ + async function recording(options: FrameOptions = {}, prebuffer?: number): Promise { + const opened = rig({ prebuffer }) initialize(opened.stream()) - frames(opened.stream(), 0, 1, options) + frames(opened.stream(), 0, 2, options) - const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + const admission = opened.recorder.admit(1) as Extract + const reading = read(admission.serve()) + + frames(opened.stream(), 2, 200, options) + await settle() + + return { ...opened, admission, reading } + } + + // A prebuffered recording a hub opened over its data stream connection, which has sent its first segment, and the hub's client. + async function hubRecording(): Promise { + const opened = rig({ prebuffer: 2000 }) + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 61) - frames(opened.stream(), 1, 200, options) + const client = await DataStreamClient.connect(opened.camera.recordingManagement!.dataStreamManagement) + + openRecording(client, 1) + await settle() + frames(stream, 61, 200) await settle() - return { ...opened, reading } + return { ...opened, client } + } + + // The problems a row's camera raised, each as its kind, level, sentence and tier name it. + function alertsOf({ alerts }: Rig): Partial>[] { + return alerts.map(({ kind, level, sentence, sensorUUID, tierId }: Partial>) => ({ + kind, + level, + sensorUUID, + sentence, + tierId, + })) } // The times in seconds of the keyframes the buffer holds. @@ -1762,29 +2186,34 @@ describe('bufferRecorder', () => { [ 'the hub\'s acknowledgement', 'ended', - ({ recorder }: Rig) => recorder.acknowledgeStream(1), + undefined, + ({ recorder }: Opened) => recorder.acknowledgeStream(1), ], [ 'the hub\'s normal close', 'ended', - ({ recorder }: Rig) => recorder.closeRecordingStream(1, HDSProtocolSpecificErrorReason.NORMAL), + HDSProtocolSpecificErrorReason.NORMAL, + ({ admission }: Opened) => admission.hubClosed(HDSProtocolSpecificErrorReason.NORMAL), ], [ 'the hub\'s close as not allowed', 'cancelled', - ({ recorder }: Rig) => recorder.closeRecordingStream(1, HDSProtocolSpecificErrorReason.NOT_ALLOWED), + HDSProtocolSpecificErrorReason.NOT_ALLOWED, + ({ admission }: Opened) => admission.hubClosed(HDSProtocolSpecificErrorReason.NOT_ALLOWED), ], [ 'the hub\'s close for another reason', 'failed', - ({ recorder }: Rig) => recorder.closeRecordingStream(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE), + HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, + ({ admission }: Opened) => admission.hubClosed(HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE), ], [ 'its connection\'s close', 'failed', - ({ recorder }: Rig) => recorder.closeRecordingStream(1, undefined), + undefined, + ({ recorder }: Opened) => recorder.closeRecordingStream(1, undefined), ], - ] as const)('ends once at %s, %s, its place given up so the buffer falls back to its span', async (_route, outcome, end) => { + ] as const)('ends once at %s, %s, its place given up so the buffer falls back to its span', async (_route, outcome, reason, end) => { const opened = await recording() expect(keyframeTimes(opened.buffer())).toEqual([4, 5, 6]) @@ -1796,6 +2225,7 @@ describe('bufferRecorder', () => { expect(opened.ends).toEqual([ { outcome, + reason, segments: 1, sensorUUID: SENSOR_UUID, streamId: 1, @@ -1807,19 +2237,176 @@ describe('bufferRecorder', () => { expect(opened.reading.packets.at(-1)!.isLast).toBe(false) }) - it.each([ - [ - 'recording no longer allowed', - 'cancelled', - ({ allow }: Rig) => allow(false), - ], - [ - 'the accessory\'s unpublish', - 'cancelled', - ({ accessoryUUID, camera }: Rig) => camera.handleAccessoryContext({ - accessoryInformation: new Service.AccessoryInformation('Camera') as AccessoryInformation, - accessoryUUID, - published: false, + it('ends once at a hub\'s close with the reason TIMEOUT, as failed, carrying the reason on its end and its debug event and raising one ' + + 'recording-timed-out warning', async () => { + const events = captureDebugEvents('HAP-NodeJS:Camera:BufferRecorder') + const opened = await hubRecording() + + opened.client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason: HDSProtocolSpecificErrorReason.TIMEOUT, streamId: 1 }) + await settle() + + expect(opened.ends).toEqual([ + { + outcome: 'failed', + reason: HDSProtocolSpecificErrorReason.TIMEOUT, + segments: 1, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(events.filter(({ kind }) => kind === 'recording-ended').map(({ outcome, reason }) => ({ outcome, reason }))).toEqual([ + { + outcome: 'failed', + reason: HDSProtocolSpecificErrorReason.TIMEOUT, + }, + ]) + expect(alertsOf(opened)).toEqual([ + { + kind: 'recording-timed-out', + level: 'warning', + sensorUUID: SENSOR_UUID, + sentence: `A hub closed the recording of stream 1 of the video tier 1 of the video sensor "${SENSOR_UUID}" with the reason TIMEOUT after 1 segment.`, + tierId: 1, + }, + ]) + // A recording that sent a media segment names no cause, the key absent rather than undefined. + expect(opened.alerts[0]).not.toHaveProperty('cause') + }) + + it('names no-segment on the recording-timed-out warning of a prebuffered recording a hub closes with the reason TIMEOUT before a media segment ' + + 'leaves', async () => { + const opened = rig({ prebuffer: 2000 }) + + initialize(opened.stream()) + frames(opened.stream(), 0, 61) + + const client = await DataStreamClient.connect(opened.camera.recordingManagement!.dataStreamManagement) + + openRecording(client, 1) + await settle() + client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason: HDSProtocolSpecificErrorReason.TIMEOUT, streamId: 1 }) + await settle() + + expect([ + opened.ends.map(({ outcome, segments }) => [outcome, segments]), + timedOut(opened), + ]).toEqual([ + [ + ['failed', 0], + ], + ['no-segment'], + ]) + }) + + it.each([ + { name: 'NORMAL', outcome: 'ended', reason: HDSProtocolSpecificErrorReason.NORMAL }, + { name: 'NOT_ALLOWED', outcome: 'cancelled', reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED }, + { name: 'UNEXPECTED_FAILURE', outcome: 'failed', reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE }, + ] as const)('ends once at a hub\'s close with the reason $name, as $outcome, carrying the reason and raising no problem', async ({ outcome, reason }) => { + const opened = await hubRecording() + + opened.client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason, streamId: 1 }) + await settle() + + expect(opened.ends).toEqual([ + { + outcome, + reason, + segments: 1, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(alertsOf(opened)).toEqual([]) + }) + + it.each([ + { + end: ({ client }: Rig & { client: DataStreamClient }) => client.closeSocket(), + outcome: 'failed', + segments: 1, + why: 'its connection\'s close', + }, + { + end: ({ camera }: Rig) => camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive) + .updateValue(Characteristic.HomeKitCameraActive.OFF), + outcome: 'cancelled', + segments: 1, + why: 'HomeKit Camera Active turning off', + }, + { + end: ({ allow }: Rig) => allow(false), + outcome: 'cancelled', + segments: 1, + why: 'recording turned off', + }, + { + end: ({ camera }: Rig) => camera.updateSourceState('away'), + outcome: 'cancelled', + segments: 2, + why: 'the camera\'s source stated away', + }, + { + end: ({ camera }: Rig) => camera.handleFactoryReset(), + outcome: 'cancelled', + segments: 1, + why: 'a factory reset', + }, + ] as const)('ends once at $why, $outcome, carrying no reason and raising no problem', async ({ end, outcome, segments }) => { + const opened = await hubRecording() + + end(opened) + await settle() + + expect(opened.ends).toStrictEqual([ + { + outcome, + segments, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(alertsOf(opened)).toEqual([]) + }) + + it('raises no recording-timed-out and tells no second end at a hub\'s close with the reason TIMEOUT of a recording a long gap ended with the end ' + + 'marker', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const opened = await recording() + + vi.advanceTimersByTime(10000) + opened.admission.hubClosed(HDSProtocolSpecificErrorReason.TIMEOUT) + await settle() + + expect(opened.ends.map(({ outcome, reason }) => ({ outcome, reason }))).toEqual([ + { + outcome: 'gap', + reason: undefined, + }, + ]) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + expect(alertsOf(opened).filter(({ kind }) => kind === 'recording-timed-out')).toEqual([]) + }) + + it.each([ + [ + 'recording no longer allowed', + 'cancelled', + ({ allow }: Rig) => allow(false), + ], + [ + 'the accessory\'s unpublish', + 'cancelled', + ({ accessoryUUID, camera }: Rig) => camera.handleAccessoryContext({ + accessoryInformation: new Service.AccessoryInformation('Camera') as AccessoryInformation, + accessoryUUID, + published: false, username: undefined, }), ], @@ -1834,7 +2421,8 @@ describe('bufferRecorder', () => { ({ camera }: Rig) => camera.handleControllerRemoved(), ], ] as const)('ends once at %s, %s, with the end marker after its last whole segment, the hold released and the buffer emptied', async (_route, outcome, end) => { - const opened = await recording() + // The prebuffered mode's hold, which each of these stops releases. + const opened = await recording({}, 1) // The tier's buffer as the recording found it, which the camera's tier tables do not reach once it is removed. const buffer = opened.buffer()! @@ -2183,7 +2771,7 @@ describe('bufferRecorder', () => { }) it('sends a segment whose closing keyframe arrived before an open only once that keyframe\'s fragment ends, with the sound the fragment carries after ' - + 'its keyframe', async () => { + + 'its keyframe, holding it at that end for the sound timed at its keyframe, a fragment behind, and sending it at the end of the next', async () => { const opened = rig({ prebuffer: 4000 }) const stream = opened.stream() // The fragment of the keyframe 4 seconds in, which closes the first segment, carrying the sound of the frame before it, as a fragment behind. @@ -2202,7 +2790,7 @@ describe('bufferRecorder', () => { const split = mdat.payload + tierPicture({ keyframe: true }).data.length initialize(stream) - frames(stream, 0, 120, { lag: true }) + frames(stream, 0, 120, { lag: 1 }) stream.write(closing.subarray(0, split)) const reading = read(opened.recorder.handleRecordingStreamRequest(1)) @@ -2214,6 +2802,11 @@ describe('bufferRecorder', () => { stream.write(closing.subarray(split)) await settle() + expect(segmentsOf(reading)).toEqual([]) + + frames(stream, 121, 122, { lag: 1 }) + await settle() + expect(segmentsOf(reading).map(({ audio, video }) => ({ lastSound: audio.at(-1)!.decodeTime, pictures: video.length, @@ -2261,7 +2854,8 @@ describe('bufferRecorder', () => { expect(opened.reading.packets.at(-1)).toEqual(MARKER) }) - it('ends once at a ceiling\'s trim past its place, as failed, with the end marker', async () => { + it('ends once at a ceiling\'s trim past its place, as failed, before any media segment, closed with the reason UNEXPECTED_FAILURE and no end ' + + 'marker', async () => { const opened = rig() initialize(opened.stream()) @@ -2283,7 +2877,8 @@ describe('bufferRecorder', () => { }, ]) expect(opened.alerts.map(({ kind }) => kind)).toEqual(['buffer-trimmed']) - expect(reading.packets.at(-1)).toEqual(MARKER) + expect(reading.packets.map(({ isLast }) => isLast)).toEqual([false]) + expect(closeOf(reading)).toBe(HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE) }) it('counts no silence on a demand a recording-ended listener ended inside the trim that ended its recording, the tier\'s next silence still told', async () => { @@ -2314,4 +2909,1491 @@ describe('bufferRecorder', () => { ]) }) }) + + describe('the prebuffered mode beside the on-demand one', () => { + it('leaves the demand standing at a recording\'s end with motion not raised while recording is allowed', async () => { + const opened = rig({ prebuffer: 1 }) + + initialize(opened.stream()) + frames(opened.stream(), 0, 2) + read(opened.recorder.handleRecordingStreamRequest(1)) + opened.recorder.acknowledgeStream(1) + await settle() + + expect([ + opened.ends.map(({ outcome }) => outcome), + streamsOf(opened.delegate).length, + endsOf(opened.delegate), + ]).toEqual([ + ['ended'], + 1, + 0, + ]) + }) + + it('leaves the demand standing at motion\'s fall with no recording open', async () => { + const opened = rig({ prebuffer: 1 }) + + opened.camera.updateMotionDetected(true) + opened.camera.updateMotionDetected(false) + await settle() + + expect([ + streamsOf(opened.delegate).length, + endsOf(opened.delegate), + ]).toEqual([1, 0]) + }) + + it.each([ + { mode: 'the prebuffered mode', prebuffer: 1 }, + { mode: 'the on-demand mode on a tier marked keepRunning', prebuffer: undefined }, + ])('carries a recording that has opened across its stream\'s failure in $mode, telling of no end, and resumes it at the next keyframe the keeper\'s ' + + 'next ask brings', async ({ prebuffer }) => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const opened = rig({ prebuffer }) + + initialize(opened.stream()) + frames(opened.stream(), 0, 2) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + frames(opened.stream(), 2, 160) + await settle() + + const before = segmentsOf(reading).length + + opened.stream().fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + initialize(opened.stream()) + frames(opened.stream(), 0, 160) + await settle() + + expect([ + before, + opened.ends, + streamsOf(opened.delegate).length, + segmentsOf(reading).length > before + 1, + ]).toEqual([1, [], 2, true]) + }) + + /* A recording at a prebuffer of a second that has sent its initialization segment and no media segment, the second and a half of frames the ready + * buffer holds closing no segment at the four-second target. The hub's client opened it, and reads what the camera sent. + */ + async function initialized(): Promise { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const opened = ready({ prebuffer: 1000 }) + const client = await DataStreamClient.connect(opened.camera.recordingManagement!.dataStreamManagement) + + openRecording(client, 1) + await settle() + + return { ...opened, client } + } + + it.each([ + { + closing: 'recording turned off', + end: (opened: Rig): void => opened.allow(false), + failure: [], + outcome: 'cancelled', + reason: HDSProtocolSpecificErrorReason.CANCELLED, + }, + { + closing: 'a long gap whose close of the segment in progress throws', + end: (opened: Rig): void => { + vi.spyOn(opened.buffer()!, 'walk').mockImplementation(() => { + throw new Error('The walk failed.') + }) + vi.advanceTimersByTime(10000) + }, + failure: ['library-failure'], + outcome: 'gap', + reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, + }, + { + closing: 'a throw from its own call as a place', + end: (opened: Rig): void => { + vi.spyOn(opened.buffer()!, 'walk').mockImplementation(() => { + throw new Error('The walk failed.') + }) + frames(opened.stream(), 45, 46) + }, + failure: ['library-failure'], + outcome: 'failed', + reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, + }, + ])('closes to the hub with a reason, and no end marker, a prebuffered recording that has sent no media segment at $closing', async ({ + end, + failure, + outcome, + reason, + }) => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const opened = await initialized() + + end(opened) + await settle() + + expect([ + opened.ends.map(ended => [ended.outcome, ended.segments]), + opened.alerts.map(({ kind }) => kind).filter(kind => kind === 'library-failure'), + opened.client.events(Protocols.DATA_SEND, Topics.DATA).map(({ endOfStream }) => endOfStream), + opened.client.events(Protocols.DATA_SEND, Topics.CLOSE).map(({ reason: named }) => named), + ]).toEqual([ + [ + [outcome, 0], + ], + failure, + [false], + [reason], + ]) + }) + + it('sends the segment in progress as it stands and then the end marker at a plain long gap after the initialization segment alone, as a gap of one ' + + 'segment', async () => { + const opened = await initialized() + + vi.advanceTimersByTime(10000) + await settle() + + expect([ + opened.ends.map(ended => [ended.outcome, ended.segments]), + opened.client.events(Protocols.DATA_SEND, Topics.DATA).map(({ endOfStream }) => endOfStream), + opened.client.events(Protocols.DATA_SEND, Topics.CLOSE), + ]).toEqual([ + [ + ['gap', 1], + ], + [false, false, true], + [], + ]) + }) + }) + + describe('on demand', () => { + // The NTP time of 2026-11-12T00:00:00.000Z, which a stream states for its picture's decode time zero, and that moment as a wall clock. + const CLOCK = 0xEE9F800000000000n + const MOMENT = Date.parse('2026-11-12T00:00:00.000Z') + + /* An on-demand camera whose recorded tier no reason holds until a hub's open, unless the row marks it kept running, Motion Detected raised where the + * row says, the clock faked, and a hub's client connected to its recording management. The start's bound is routed through the faked clock unless + * the row leaves it unbounded, on the runtime's own timer, which the faked clock neither runs nor counts: a row that reads the faked clock's count of + * timers does. + */ + async function demanding({ bounded = true, kept = false, motion = false, shouldRecord }: { + bounded?: boolean + kept?: boolean + motion?: boolean + shouldRecord?: CameraBufferRecordingOptions['shouldRecord'] + } = {}): Promise { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + if (bounded) { + fakeTimeoutSignals() + } + + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const made = rig({ kept, shouldRecord }) + + if (motion) { + made.camera.updateMotionDetected(true) + } + + const client = await DataStreamClient.connect(made.camera.recordingManagement!.dataStreamManagement) + + return { ...made, client } + } + + // A hub's close of the recording stream given, with the reason given. + function hubClose(client: DataStreamClient, streamId: number, reason: HDSProtocolSpecificErrorReason): void { + client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason, streamId }) + } + + // The data events the hub received of a stream, and the reasons of the closes it received. + function dataOf(client: DataStreamClient, streamId = 1): Record[] { + return client.events(Protocols.DATA_SEND, Topics.DATA).filter(event => event.streamId === streamId) + } + + function closesOf(client: DataStreamClient): HDSProtocolSpecificErrorReason[] { + return client.events(Protocols.DATA_SEND, Topics.CLOSE).map(({ reason }) => reason as HDSProtocolSpecificErrorReason) + } + + // The recording management's stream, absent once none stands. + function recordingStreamOf({ camera }: Rig): unknown { + // @ts-expect-error: private access + return camera.recordingManagement?.recordingStream + } + + // Writes a stream's initialization segment and a keyframe a decoder can read. + function picture(stream: TierStream): void { + initialize(stream) + frames(stream, 0, 1) + } + + // The moments of the delegate's starts from the moment given, each start refused at once and recorded at its moment. + function refusing(delegate: ScriptedTierDelegate): () => number[] { + const from = performance.now() + const moments: number[] = [] + + delegate.tierDemandStarted.mockImplementation(async () => { + moments.push(performance.now() - from) + throw new Error('The camera is busy.') + }) + + return () => moments + } + + /* The faked clock's count of timers a millisecond before a waiting recording's failsafe would fall, 30 seconds after the open made at the moment given, + * and the ends told once that moment has passed: an end that left the failsafe standing leaves it among those timers. + */ + async function atFailsafe({ ends }: Rig, open: number): Promise { + await vi.advanceTimersByTimeAsync(open + 29999 - performance.now()) + + const pending = vi.getTimerCount() + + await vi.advanceTimersByTimeAsync(1) + + return [pending, ends.length] + } + + it('answers a hub\'s open with success and sends nothing, telling recording-started at once and then calling tierDemandStarted once for the recorded ' + + 'tier, and refuses as busy an open shouldRecord declines and one out of service, starting nothing', async () => { + const answers = [true, false] + const opened = await demanding({ + shouldRecord: () => answers.shift()!, + }) + const told: string[] = [] + const start = opened.delegate.tierDemandStarted.getMockImplementation()! + + opened.camera.on('recording-started', () => told.push('started')) + opened.delegate.tierDemandStarted.mockImplementation(async (stream, signal) => { + told.push(`started ${stream.tier.sensorUUID} ${stream.tier.id}`) + await start(stream, signal) + }) + await settle() + + const unopened = streamsOf(opened.delegate).length + const admitted = openRecording(opened.client, 1) + + await settle() + + const answered = opened.client.answerTo(admitted)?.header.status + const sent = dataOf(opened.client).length + + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + const declined = openRecording(opened.client, 2) + + await settle() + opened.camera.updateSourceState('away') + + const away = openRecording(opened.client, 3) + + await settle() + + expect([ + unopened, + answered, + sent, + told, + opened.client.answerTo(declined)?.message, + opened.client.answerTo(away)?.message, + streamsOf(opened.delegate).length, + ]).toEqual([ + 0, + HDSStatus.SUCCESS, + 0, + ['started', `started ${SENSOR_UUID} 1`], + { status: HDSProtocolSpecificErrorReason.BUSY }, + { status: HDSProtocolSpecificErrorReason.BUSY }, + 1, + ]) + }) + + it('opens a waiting recording at the first decodable keyframe, its stream\'s initialization segment ending nothing and a keyframe a decoder cannot ' + + 'read passed over, its first segment leaving at the keyframe four seconds on and stamped when its opening keyframe was taken', async () => { + const opened = rig({ kept: false }) + const admission = opened.recorder.admit(1) as Extract + const reading = read(admission.serve()) + const stream = opened.stream() + + // The stream's description holds no parameter sets, its first keyframe carries none, and its keyframe of a second carries them in band. + initialize(stream, { parameterSets: [] }) + frames(stream, 0, 30, { clock: CLOCK }) + await settle() + + const passed = reading.packets.length + + frames(stream, 30, 150, { clock: CLOCK, inBand: true }) + await settle() + + const before = reading.packets.length + + frames(stream, 150, 151, { clock: CLOCK, inBand: true }) + await settle() + + const [initialization, first] = reading.packets as RecorderPacket[] + const moov = walkBoxes(initialization.data).boxes.find(({ type }) => type === 'moov')! + const [video] = readTrackBoxes(initialization.data, moov) + + expect([ + passed, + before, + reading.packets.length, + opened.ends, + readTrackBoxParameterSets(initialization.data, video, { lengthSize: 4, limit: 16384 })?.units, + first.wallClock, + ]).toEqual([ + 0, + 1, + 2, + [], + TIER_STREAM_PARAMETER_SETS, + MOMENT + 1000, + ]) + }) + + it.each([ + { + held: 'under keepRunning', + made: (): Rig => rig(), + }, + { + held: 'by a viewer', + made: (): Rig => { + const opened = rig({ kept: false }) + // @ts-expect-error: private access + const table = opened.recorder.options.tierTable(SENSOR_UUID) as TierTable + + table.joinFrames(table.videoTiers.get(1)!, 'video', { + tierFailed: () => undefined, + }, { + take: () => undefined, + }) + + return opened + }, + }, + ])('serves an open at once from the latest keyframe of a tier held $held, with no second tierDemandStarted', async ({ made }) => { + const opened = made() + + initialize(opened.stream()) + frames(opened.stream(), 0, 45, { clock: CLOCK }) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + await settle() + + const atOnce = reading.packets.length + + frames(opened.stream(), 45, 151, { clock: CLOCK }) + await settle() + + expect([ + atOnce, + (reading.packets[1] as RecorderPacket).wallClock, + streamsOf(opened.delegate).length, + ]).toEqual([1, MOMENT + 1000, 1]) + }) + + // A stream's one clock across its starts, stated three seconds behind the first start's moment: each start's stream hands over at once the video + // its camera kept, which that clock states before the start, and then its live video in real time. + const BEHIND = CLOCK - (3n << 32n) + + // Writes the frames from one index up to another in real time, the clock moving a frame's length before each. + function inRealTime(stream: TierStream, from: number, to: number): void { + for (let index = from; index < to; index++) { + vi.advanceTimersByTime(100 / 3) + frames(stream, index, index + 1, { clock: BEHIND, inBand: true }) + } + } + + it('opens a waiting recording at the first decodable keyframe of the lead-up its stream brings, dated when that keyframe was taken, and ends nothing', + async () => { + vi.useFakeTimers({ + now: MOMENT, + toFake: [ + 'setTimeout', + 'clearTimeout', + 'performance', + 'Date', + ], + }) + + const opened = rig({ kept: false }) + const admission = opened.recorder.admit(1) as Extract + const reading = read(admission.serve()) + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 90, { clock: BEHIND, inBand: true }) + inRealTime(stream, 90, 240) + await settle() + + const [, first] = reading.packets as RecorderPacket[] + + expect([first.wallClock, opened.ends]).toEqual([MOMENT - 3000, []]) + }) + + it('carries an opened recording across its stream\'s failure from the first keyframe the restart brings, its lead-up\'s, repeating the video the ' + + 'restart hands over again and leaving out none', async () => { + vi.useFakeTimers({ + now: MOMENT, + toFake: [ + 'setTimeout', + 'clearTimeout', + 'performance', + 'Date', + ], + }) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const opened = rig({ kept: false }) + const admission = opened.recorder.admit(1) as Extract + const reading = read(admission.serve()) + + initialize(opened.stream()) + frames(opened.stream(), 0, 90, { clock: BEHIND, inBand: true }) + inRealTime(opened.stream(), 90, 240) + await settle() + opened.stream().fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + // The keeper's ask a second after the failure raises the restart, whose stream hands over at once the video its camera kept since frame 195. + const restart = opened.stream() + + initialize(restart) + frames(restart, 195, 285, { clock: BEHIND, inBand: true }) + inRealTime(restart, 285, 435) + await settle() + + const clocks = (reading.packets as RecorderPacket[]).slice(1).filter(({ data }) => data.length > 1).map(({ wallClock }) => wallClock! - MOMENT) + const pictures = segmentsOf(reading).map(({ video }) => video.length) + // A segment that starts after the one ahead of it ends, read from that segment's wall clock and its pictures at 30 a second, leaves a hole in the + // clip. The third segment opens on the restart's first keyframe, which the camera took a second before the second segment's end. + const holes = clocks.slice(1).filter((stated, index) => stated > clocks[index] + pictures[index] * 100 / 3) + + expect([ + restart.reason, + clocks.slice(0, 3), + holes, + opened.ends, + ]).toEqual([ + 'recording', + [-3000, 1000, 4000], + [], + [], + ]) + }) + + // The reason each start of the recorded tier read, in the order of the starts. + function reasonsOf({ delegate }: Rig): string[] { + return streamsOf(delegate, 1).filter(({ tier }) => tier.sensorUUID === SENSOR_UUID).map(({ reason }) => reason) + } + + it('states recording for the recorded tier at the start a hub\'s open makes and at its join after a failure while the recording is open', async () => { + const opened = await demanding() + + openRecording(opened.client, 1) + await settle() + opened.stream().fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + expect([ + reasonsOf(opened), + opened.ends, + ]).toEqual([ + ['recording', 'recording'], + [], + ]) + }) + + it('states recording for the recorded tier at its join after a failure once the recording has ended while Motion Detected stays raised', async () => { + const opened = await demanding({ motion: true }) + + openRecording(opened.client, 1) + await settle() + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + const ended = opened.ends.map(({ outcome }) => outcome) + + opened.stream().fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + expect([ + ended, + reasonsOf(opened), + ]).toEqual([ + ['ended'], + ['recording', 'recording'], + ]) + }) + + it('states keepRunning for a recorded tier marked keepRunning at the start its context makes, a hub\'s open starting nothing, and recording at its ' + + 'join after a failure while the recording is open', async () => { + const opened = await demanding({ kept: true }) + + await settle() + openRecording(opened.client, 1) + await settle() + + const atOpen = reasonsOf(opened) + + opened.stream().fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + expect([ + atOpen, + reasonsOf(opened), + ]).toEqual([ + ['keepRunning'], + ['keepRunning', 'recording'], + ]) + }) + + it('ends a waiting recording at a hub\'s normal close as ended with no segment and nothing sent, and with motion not raised ends the demand, leaving ' + + 'no failsafe standing', async () => { + const opened = await demanding({ bounded: false }) + const events = captureDebugEvents('HAP-NodeJS:Camera:BufferRecorder') + const open = performance.now() + + openRecording(opened.client, 1) + await settle() + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + expect([ + opened.ends, + dataOf(opened.client), + events.filter(({ kind }) => kind === 'recording-ended').map(({ dropped, seconds }) => ({ dropped, seconds })), + endsOf(opened.delegate), + ]).toEqual([ + [ + { + outcome: 'ended', + reason: HDSProtocolSpecificErrorReason.NORMAL, + segments: 0, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ], + [], + [ + { + dropped: 0, + seconds: 0, + }, + ], + 1, + ]) + expect(await atFailsafe(opened, open)).toEqual([0, 1]) + }) + + it.each([ + { cleared: false, ended: 0, motion: 'raised' }, + { cleared: true, ended: 1, motion: 'cleared before the close' }, + ])('ends a waiting recording at a hub\'s TIMEOUT close 16.5 seconds on as failed with one warning, motion $motion, and serves the hub\'s second open ' + + 'at once from the stream\'s latest keyframe where motion kept it', async ({ cleared, ended }) => { + const opened = await demanding({ motion: true }) + const events = captureDebugEvents('HAP-NodeJS:Camera:BufferRecorder') + + openRecording(opened.client, 1) + await settle() + await vi.advanceTimersByTimeAsync(16500) + + if (cleared) { + opened.camera.updateMotionDetected(false) + } + + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.TIMEOUT) + await settle() + + expect([ + opened.starts.length, + opened.ends.map(({ outcome, reason, segments }) => [outcome, reason, segments]), + timedOut(opened), + events.filter(({ kind }) => kind === 'recording-ended').map(({ dropped, seconds }) => [dropped, seconds]), + endsOf(opened.delegate), + ]).toEqual([ + 1, + [ + ['failed', HDSProtocolSpecificErrorReason.TIMEOUT, 0], + ], + ['no-picture'], + [ + [0, 0], + ], + ended, + ]) + + if (cleared) { + return + } + + await vi.advanceTimersByTimeAsync(5000) + picture(opened.stream()) + openRecording(opened.client, 2) + await settle() + + expect([ + dataOf(opened.client, 2).length, + streamsOf(opened.delegate).length, + ]).toEqual([1, 1]) + }) + + it('names no-keyframe on the recording-timed-out warning of a waiting recording whose stream brings pictures and no decodable keyframe until a ' + + 'hub\'s TIMEOUT close 16.5 seconds on', async () => { + const opened = await demanding() + + openRecording(opened.client, 1) + await settle() + + const stream = opened.stream() + + // Half a second of frames at each half second of the clock through 16 seconds, its keyframes and its description holding no parameter sets. + initialize(stream, { parameterSets: [] }) + frames(stream, 0, 15) + + for (let index = 15; index < 495; index += 15) { + await vi.advanceTimersByTimeAsync(500) + frames(stream, index, index + 15) + } + + await vi.advanceTimersByTimeAsync(500) + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.TIMEOUT) + await settle() + + expect([ + opened.ends.map(({ outcome, reason, segments }) => [outcome, reason, segments]), + timedOut(opened), + ]).toEqual([ + [ + ['failed', HDSProtocolSpecificErrorReason.TIMEOUT, 0], + ], + ['no-keyframe'], + ]) + }) + + it('ends a waiting recording at its connection\'s close as failed with no reason, and ends the demand, leaving no failsafe standing', async () => { + const opened = await demanding({ bounded: false }) + const open = performance.now() + + openRecording(opened.client, 1) + await settle() + opened.client.closeSocket() + await settle() + + expect([ + opened.ends, + endsOf(opened.delegate), + ]).toStrictEqual([ + [ + { + outcome: 'failed', + segments: 0, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ], + 1, + ]) + expect(await atFailsafe(opened, open)).toEqual([0, 1]) + }) + + it.each([ + { + closes: [HDSProtocolSpecificErrorReason.CANCELLED], + stop: ({ allow }: Rig): void => allow(false), + stopping: 'Recording Active off', + }, + { + closes: [HDSProtocolSpecificErrorReason.CANCELLED], + stop: ({ services }: Rig): void => { + services['cameraCapabilities:cameraCapabilities']!.getCharacteristic(Characteristic.ManuallyDisabled).updateValue(1) + }, + stopping: 'Manually Disabled', + }, + { + closes: [HDSProtocolSpecificErrorReason.NOT_ALLOWED], + stop: ({ camera }: Rig): void => { + camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive) + .updateValue(Characteristic.HomeKitCameraActive.OFF) + }, + stopping: 'HomeKit Camera Active off', + }, + { + closes: [HDSProtocolSpecificErrorReason.CANCELLED], + stop: ({ camera }: Rig): void => camera.updateSourceState('away'), + stopping: 'the source stated away', + }, + { + closes: [HDSProtocolSpecificErrorReason.CANCELLED], + stop: ({ accessoryUUID, camera }: Rig): void => camera.handleAccessoryContext({ + accessoryInformation: new Service.AccessoryInformation('Camera') as AccessoryInformation, + accessoryUUID, + published: false, + username: undefined, + }), + stopping: 'the unpublish', + }, + { + closes: [HDSProtocolSpecificErrorReason.CANCELLED], + stop: ({ camera }: Rig): void => camera.handleFactoryReset(), + stopping: 'a factory reset', + }, + { + closes: [], + stop: ({ camera }: Rig): void => camera.handleControllerRemoved(), + stopping: 'the removal', + }, + ])('ends a waiting recording at $stopping as cancelled once, the demand ended and no recording stream left, the hub sent no data, leaving no ' + + 'failsafe standing', async ({ + closes, + stop, + }) => { + const opened = await demanding({ bounded: false }) + const management = opened.camera.recordingManagement! + const open = performance.now() + + openRecording(opened.client, 1) + await settle() + stop(opened) + await settle() + + expect([ + opened.ends.map(({ outcome }) => outcome), + endsOf(opened.delegate), + // @ts-expect-error: private access + management.recordingStream, + dataOf(opened.client), + closesOf(opened.client), + ]).toEqual([ + ['cancelled'], + 1, + undefined, + [], + closes, + ]) + expect(await atFailsafe(opened, open)).toEqual([0, 1]) + }) + + it('closes an opened recording that has sent its initialization segment and no media segment as cancelled at Recording Active off, sending no end ' + + 'marker', async () => { + const opened = await demanding() + + openRecording(opened.client, 1) + await settle() + picture(opened.stream()) + await settle() + opened.allow(false) + await settle() + + expect([ + opened.ends.map(({ outcome, segments }) => [outcome, segments]), + dataOf(opened.client).map(({ endOfStream, packets: [{ metadata }] }) => [metadata.dataType, endOfStream]), + closesOf(opened.client), + recordingStreamOf(opened), + ]).toEqual([ + [ + ['cancelled', 0], + ], + [ + ['mediaInitialization', false], + ], + [HDSProtocolSpecificErrorReason.CANCELLED], + undefined, + ]) + }) + + describe('its failsafe', () => { + // The end of a waiting recording the failsafe ends, which carries no reason. + const FAILED = { + outcome: 'failed', + segments: 0, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + } + + it('keeps a waiting recording through a refused first start, the keeper\'s ask after its first wait serving it from the next start\'s stream', + async () => { + const opened = await demanding() + + opened.delegate.tierDemandStarted.mockRejectedValueOnce(new Error('The camera is busy.')) + openRecording(opened.client, 1) + await settle() + + const refused = [opened.ends.length, streamsOf(opened.delegate).length] + + await vi.advanceTimersByTimeAsync(1000) + picture(opened.stream()) + await settle() + + expect([ + refused, + streamsOf(opened.delegate).length, + dataOf(opened.client).map(({ packets: [{ metadata }] }) => metadata.dataType), + opened.ends, + ]).toEqual([ + [0, 1], + 2, + ['mediaInitialization'], + [], + ]) + }) + + it.each([ + { + asked: [ + 0, + 1000, + 3000, + 7000, + 15000, + 31000, + 61000, + ], + motion: true, + }, + { + asked: [0, 1000, 3000, 7000, 15000], + motion: false, + }, + ])('ends a waiting recording whose starts keep refusing 30 seconds after its open, still waiting at 29.999 seconds, as failed with no reason and ' + + 'closed with UNEXPECTED_FAILURE, motion raised $motion', async ({ asked, motion }) => { + const opened = await demanding({ motion }) + const moments = refusing(opened.delegate) + + openRecording(opened.client, 1) + await settle() + await vi.advanceTimersByTimeAsync(29999) + + const waiting = [opened.ends.length, moments().length] + + await vi.advanceTimersByTimeAsync(1) + + const ended = opened.ends.map(end => ({ ...end })) + + await vi.advanceTimersByTimeAsync(31000) + + expect([ + waiting, + ended, + closesOf(opened.client), + opened.alerts.filter(({ kind }) => kind === 'plugin-failure').length, + opened.alerts.filter(({ kind }) => kind === 'tier-failed').length, + moments(), + ]).toStrictEqual([ + [0, 5], + [FAILED], + [HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + asked.length, + 1, + asked, + ]) + }) + + // The start's cut falls at the failsafe's moment too, and either may run first: the row reads the end and the close alone, which both orders give. + it('ends a waiting recording whose start never settles 30 seconds after its open, still waiting at 29.999 seconds, closed with UNEXPECTED_FAILURE', + async () => { + const opened = await demanding() + + pendingStart(opened.delegate) + openRecording(opened.client, 1) + await settle() + await vi.advanceTimersByTimeAsync(29999) + + const waiting = opened.ends.length + + await vi.advanceTimersByTimeAsync(1) + + expect([ + waiting, + opened.ends, + closesOf(opened.client), + ]).toStrictEqual([ + 0, + [FAILED], + [HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + ]) + }) + + it('ends a waiting recording whose start settled 5 seconds after its open and brought no picture 30 seconds after its open, before that stream\'s ' + + 'first-sample failure, still waiting at 29.999 seconds', async () => { + const opened = await demanding() + const pending = pendingStart(opened.delegate) + + openRecording(opened.client, 1) + await settle() + await vi.advanceTimersByTimeAsync(5000) + pending.resolve() + await vi.advanceTimersByTimeAsync(24999) + + const waiting = opened.ends.length + + await vi.advanceTimersByTimeAsync(1) + + expect([ + waiting, + opened.ends, + closesOf(opened.client), + ]).toStrictEqual([ + 0, + [FAILED], + [HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + ]) + }) + + it('ends a waiting recording whose stream brings pictures and no decodable keyframe 30 seconds after its open, those pictures moving its clocks on, ' + + 'still waiting at 29.999 seconds', async () => { + const opened = await demanding() + + openRecording(opened.client, 1) + await settle() + + const stream = opened.stream() + + // Half a second of frames at each half second of the clock through 29.5 seconds, its keyframes and its description holding no parameter sets. + initialize(stream, { parameterSets: [] }) + frames(stream, 0, 15) + + for (let index = 15; index < 900; index += 15) { + await vi.advanceTimersByTimeAsync(500) + frames(stream, index, index + 15) + } + + await vi.advanceTimersByTimeAsync(499) + + const waiting = opened.ends.length + + await vi.advanceTimersByTimeAsync(1) + + expect([ + waiting, + opened.ends, + closesOf(opened.client), + ]).toStrictEqual([ + 0, + [FAILED], + [HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + ]) + }) + + it('ends a waiting recording whose open joins a failed demand another holder keeps 30 seconds after its open, calling no tierDemandStarted, still ' + + 'waiting at 29.999 seconds', async () => { + const opened = await demanding() + // @ts-expect-error: private access + const table = opened.recorder.options.tierTable(SENSOR_UUID) as TierTable + + // A hold of the tier table's joins the tier a second before the open, its start settling at once, and keeps the demand once its stream fails: + // that second keeps the hold's own start bound and first-sample bound off the failsafe's moment. + table.hold(table.videoTiers.get(1)!, { + tierFailed: () => undefined, + }, 'recording') + opened.stream().fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + openRecording(opened.client, 1) + await settle() + + const joined = streamsOf(opened.delegate).length + + await vi.advanceTimersByTimeAsync(29999) + + const waiting = opened.ends.length + + await vi.advanceTimersByTimeAsync(1) + + expect([ + joined, + waiting, + opened.ends, + closesOf(opened.client), + ]).toStrictEqual([ + 1, + 0, + [FAILED], + [HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + ]) + }) + + // Each arm writes what it writes of the stream before the open and after it, and the row then writes half a second of frames at each half second of + // the clock until 31 seconds after the open: one recording opens at its first decodable keyframe, its stream started a second after the open, and one + // opens inside its serve on a tier kept running, a second of its stream written before the open. + it.each([ + { + after: async (opened: Rig): Promise => { + await vi.advanceTimersByTimeAsync(1000) + initialize(opened.stream()) + }, + before: async (): Promise => undefined, + kept: false, + opening: 'opens at its first decodable keyframe', + }, + { + after: async (): Promise => undefined, + before: async (opened: Rig, write: () => Promise): Promise => { + initialize(opened.stream()) + await write() + await write() + }, + kept: true, + opening: 'opens in its serve on a kept tier', + }, + ])('leaves no failsafe standing on a recording that $opening, which tells no end and receives no close through 31 seconds from the open as its ' + + 'media segments leave', async ({ after, before, kept }) => { + const opened = await demanding({ kept }) + let next = 0 + // Half a second of frames, and then half a second of the clock. + const write = async (): Promise => { + frames(opened.stream(), next, next + 15) + next += 15 + await vi.advanceTimersByTimeAsync(500) + } + + await before(opened, write) + + const open = performance.now() + + openRecording(opened.client, 1) + await settle() + await after(opened) + + while (performance.now() - open < 31000) { + await write() + } + + expect([ + opened.ends, + closesOf(opened.client), + dataOf(opened.client).some(({ packets: [{ metadata }] }) => metadata.dataType === 'mediaFragment'), + ]).toEqual([ + [], + [], + true, + ]) + }) + + it('keeps a second open waiting through the cut of a start the first open made, which falls 8.5 seconds into its wait, and serves it from the ' + + 'keeper\'s next ask', async () => { + const opened = await demanding({ motion: true }) + + pendingStart(opened.delegate) + openRecording(opened.client, 1) + await settle() + await vi.advanceTimersByTimeAsync(16500) + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.TIMEOUT) + await vi.advanceTimersByTimeAsync(5000) + openRecording(opened.client, 2) + await settle() + + const joined = streamsOf(opened.delegate).length + + await vi.advanceTimersByTimeAsync(9000) + + const cut = opened.ends.length + + await vi.advanceTimersByTimeAsync(500) + picture(opened.stream()) + await settle() + + expect([ + joined, + cut, + streamsOf(opened.delegate).length, + opened.ends.map(({ outcome, streamId }) => [outcome, streamId]), + dataOf(opened.client, 2).length, + ]).toEqual([ + 1, + 1, + 2, + [ + ['failed', 1], + ], + 1, + ]) + }) + + // Each arm makes its failure before the open, and answers how the row settles a start the arm left pending, within the keeper's first wait. + it.each([ + { + failure: 'a stream failed inside tierDemandStarted', + made: (opened: Rig): (() => void) => { + opened.delegate.tierDemandStarted.mockImplementationOnce(async (stream) => { + stream.fail('The camera went away.') + }) + + return () => undefined + }, + }, + { + failure: 'a demand found failed at the join', + made: (opened: Rig): (() => void) => { + // @ts-expect-error: private access + const table = opened.recorder.options.tierTable(SENSOR_UUID) as TierTable + const pending = pendingStart(opened.delegate) + const hold = table.hold(table.videoTiers.get(1)!, { + tierFailed: () => undefined, + }, 'recording') + + opened.stream().fail('The camera went away.') + hold.release() + + return () => pending.resolve() + }, + }, + ])('keeps a waiting recording through $failure, telling of its start and of no end, the keeper\'s ask after its first wait serving it', async ({ + made, + }) => { + const opened = await demanding() + const settleStart = made(opened) + + openRecording(opened.client, 1) + await settle() + + const waiting = [opened.starts.length, opened.ends.length] + + await vi.advanceTimersByTimeAsync(500) + settleStart() + await vi.advanceTimersByTimeAsync(500) + picture(opened.stream()) + await settle() + + expect([ + waiting, + dataOf(opened.client).length, + opened.ends, + ]).toEqual([ + [1, 0], + 1, + [], + ]) + }) + + it('asks in the serving of a second open while the keeper waits to ask again after refused starts, and again a second on, one tier-failed standing ' + + 'across both opens', async () => { + const opened = await demanding({ motion: true }) + const moments = refusing(opened.delegate) + + openRecording(opened.client, 1) + await settle() + await vi.advanceTimersByTimeAsync(16500) + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.TIMEOUT) + await vi.advanceTimersByTimeAsync(5000) + + const before = moments().length + + openRecording(opened.client, 2) + await settle() + + const inServing = moments().slice(before) + + await vi.advanceTimersByTimeAsync(1000) + + expect([ + inServing, + moments().slice(before), + opened.alerts.filter(({ kind }) => kind === 'tier-failed').length, + ]).toEqual([ + [21500], + [21500, 22500], + 1, + ]) + }) + + /* Each arm writes its last frames at a moment from the open, the keeper's gap falling 10 seconds after them, and reads the recording a millisecond + * before one moment and again at a later one: a gap 12.5 seconds after the open, read before it and a second past it as the keeper asks again, + * still waiting, and a gap 28.5 seconds after the open, whose ask a second later raises a second demand, read still waiting before the failsafe's + * moment and ended by the failsafe past it. + */ + it.each([ + { + after: 13500, + before: 12500, + closes: [], + ends: [], + last: 88, + started: 2, + waiting: [0, 1], + written: 2.5, + }, + { + after: 31000, + before: 30000, + closes: [HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + ends: [ + ['failed', 0], + ], + last: 570, + started: 2, + waiting: [0, 2], + written: 18.5, + }, + ])('takes no long gap of a waiting recording whose stream brings no decodable keyframe, its last pictures written $written seconds after the open, ' + + 'read a millisecond before $before ms and at $after ms', async ({ + after, + before, + closes, + ends, + last, + started, + waiting, + }) => { + const opened = await demanding() + + openRecording(opened.client, 1) + await settle() + + const from = performance.now() + const stream = opened.stream() + + // Half a second of frames at a time, the clock moving half a second after each, its keyframes and its description holding no parameter sets. + initialize(stream, { parameterSets: [] }) + + for (let index = 0; index < last; index += 15) { + frames(stream, index, Math.min(index + 15, last)) + await vi.advanceTimersByTimeAsync(500) + } + + await vi.advanceTimersByTimeAsync(from + before - 1 - performance.now()) + + const early = [opened.ends.length, streamsOf(opened.delegate).length] + + await vi.advanceTimersByTimeAsync(after - before + 1) + + expect([ + early, + opened.ends.map(({ outcome, segments }) => [outcome, segments]), + closesOf(opened.client), + streamsOf(opened.delegate).length, + ]).toEqual([ + waiting, + ends, + closes, + started, + ]) + }) + }) + + it('raises no demand at motion with no open, keeps the demand at a recording\'s end and through motion\'s fall during a recording, and ends it at ' + + 'motion\'s fall with none open and at Motion Enabled turning off', async () => { + const opened = await demanding() + const readings: number[][] = [] + const note = (): void => { + readings.push([ + streamsOf(opened.delegate).length, + endsOf(opened.delegate), + ]) + } + + opened.camera.updateMotionDetected(true) + await settle() + note() + openRecording(opened.client, 1) + await settle() + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + note() + opened.camera.updateMotionDetected(false) + await settle() + note() + opened.camera.updateMotionDetected(true) + openRecording(opened.client, 2) + await settle() + opened.camera.updateMotionDetected(false) + await settle() + note() + opened.camera.updateMotionDetected(true) + hubClose(opened.client, 2, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + note() + opened.camera.motionService!.getCharacteristic(Characteristic.MotionEnabled).updateValue(false) + await settle() + note() + + expect(readings).toEqual([ + [0, 0], + [1, 0], + [1, 1], + [2, 1], + [2, 1], + [2, 2], + ]) + }) + + it('keeps the demand for an open a hub writes beside its close of the recording before, with no settle between them, starting the stream once and ' + + 'telling two recordings started and one ended', async () => { + const opened = await demanding() + + openRecording(opened.client, 1) + await settle() + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.NORMAL) + openRecording(opened.client, 2) + await settle() + + expect([ + streamsOf(opened.delegate).length, + endsOf(opened.delegate), + opened.starts.length, + opened.ends.length, + ]).toEqual([1, 0, 2, 1]) + }) + + it('ends the demand motion keeps at recording turned off, and raises nothing at recording turned on again until the next open', async () => { + const opened = await demanding({ motion: true }) + + openRecording(opened.client, 1) + await settle() + hubClose(opened.client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + const kept = endsOf(opened.delegate) + + opened.allow(false) + await settle() + + const off = endsOf(opened.delegate) + + opened.allow(true) + await settle() + + const on = streamsOf(opened.delegate).length + + openRecording(opened.client, 2) + await settle() + + expect([ + kept, + off, + on, + streamsOf(opened.delegate).length, + ]).toEqual([0, 1, 1, 2]) + }) + + it.each([ + { + stop: ({ allow }: Rig): void => allow(false), + stopping: 'turns Recording Active off', + }, + { + stop: ({ camera }: Rig): void => camera.updateSourceState('away'), + stopping: 'states the source away', + }, + ])('raises no demand for a recording whose recording-started listener $stopping, motion raised, and tells it ended as cancelled once', async ({ stop }) => { + const opened = await demanding({ motion: true }) + + opened.camera.on('recording-started', () => stop(opened)) + openRecording(opened.client, 1) + await settle() + + expect([ + streamsOf(opened.delegate).length, + opened.ends.map(({ outcome }) => outcome), + ]).toEqual([ + 0, + ['cancelled'], + ]) + }) + + it('ends an opened recording whose description changes as failed, releasing its demand in a later turn than the write that carried the new ' + + 'initialization segment', async () => { + const opened = await demanding() + + openRecording(opened.client, 1) + await settle() + + const stream = opened.stream() + + picture(stream) + await settle() + stream.write(resized(1280, 720)) + + const inWrite = disposedOf(opened.delegate, stream) + + await settle() + + expect([ + opened.ends.map(({ outcome }) => outcome), + inWrite, + disposedOf(opened.delegate, stream), + ]).toEqual([ + ['failed'], + 0, + 1, + ]) + }) + + it('refuses as busy a second open while one waits, and admits an open made at once after the failsafe closed the waiting recording', async () => { + const opened = await demanding() + + pendingStart(opened.delegate) + openRecording(opened.client, 1) + await settle() + + const busy = openRecording(opened.client, 2) + + await settle() + await vi.advanceTimersByTimeAsync(30000) + await settle() + + const admitted = openRecording(opened.client, 3) + + await settle() + + expect([ + opened.client.answerTo(busy)?.message, + opened.ends.map(({ outcome, streamId }) => [outcome, streamId]), + opened.client.answerTo(admitted)?.header.status, + ]).toEqual([ + { status: HDSProtocolSpecificErrorReason.BUSY }, + [ + ['failed', 1], + ], + HDSStatus.SUCCESS, + ]) + }) + + it('raises the demand at an open of a doorbell with the block and no motion sensor, and ends it at the hub\'s normal close', async () => { + const { delegate, options } = bufferCamera({ mode: 'onDemand' }) + const camera = new DoorbellController({ + ...options, + sensors: { occupancy: true }, + }) + + cameras.push(camera) + camera.constructServices() + camera.configureServices() + handPublishedContext(camera) + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + + const client = await DataStreamClient.connect(camera.recordingManagement!.dataStreamManagement) + + openRecording(client, 1) + await settle() + + const opened = streamsOf(delegate).length + + hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + expect([ + opened, + endsOf(delegate), + ]).toEqual([1, 1]) + }) + }) }) diff --git a/src/lib/camera/recording/BufferRecorder.ts b/src/lib/camera/recording/BufferRecorder.ts index 887149ce4..a26e6054c 100644 --- a/src/lib/camera/recording/BufferRecorder.ts +++ b/src/lib/camera/recording/BufferRecorder.ts @@ -8,6 +8,7 @@ import type { import type { BufferedSample, BufferPlace, BufferWalk, TierBuffer } from '../buffer/CameraBuffer.js' import type { TierKeeper } from '../buffer/TierKeeper.js' import type { CameraReporter } from '../diagnostics/CameraReporter.js' +import type { CameraProblem } from '../diagnostics/problems.js' import type { Mp4StreamAudioTrack, Mp4StreamTrack, Mp4StreamTracks, Mp4StreamVideoTrack } from '../mp4/Mp4StreamReader.js' import type { SegmentSample } from '../mp4/mp4Writer.js' import type { OperatingModePolicy } from '../OperatingModePolicy.js' @@ -24,6 +25,7 @@ import { debugChannel } from '../diagnostics/debugChannels.js' import { readSampleEntryBoxes } from '../mp4/mp4Boxes.js' import { segmentLength, writeKeyframeInitializationSegment, writeSegment } from '../mp4/mp4Writer.js' import { decodable } from '../rtp/FrameCutter.js' +import { DELEGATE_CALL_TIMEOUT } from '../session/settleWithin.js' import { OPUS_TICKS_PER_MILLISECOND, readOpusVoice } from '../webrtc/voice/opusVoice.js' const BUFFER_RECORDER_DEBUG = debugChannel('HAP-NodeJS:Camera:BufferRecorder') @@ -38,6 +40,11 @@ const LONGEST_PREBUFFER = 30 * 1000 const SEGMENT_TARGET = 4 * 1000000 const SEGMENT_CAP = 10000000 +// How far the stream's picture runs past a segment's closing keyframe before the segment stops waiting for its sound, in microseconds of the stream's +// times: half a second, which waits out a sound that arrives frames behind its picture. A segment leaves only at a fragment's end, which means one whose +// sound has stopped leaves at the first fragment's end at or past this. +const SOUND_WAIT = 1000000 / 2 + // The codec box of each medium's sample entry, which a description is compared by. const CODEC_BOXES = { audio: 'dOps', video: 'hvcC' } as const @@ -45,18 +52,45 @@ const CODEC_BOXES = { audio: 'dOps', video: 'hvcC' } as const const OPUS_RATE = OPUS_TICKS_PER_MILLISECOND * 1000 /** - * Validates a camera's recording from its camera buffer and settles the prebuffer it leaves out at its default, beside the recorded sensor and tier the - * options boundary settled and the plugin's shouldRecord. + * Validates a camera's recording from its camera buffer and settles its mode and prebuffer, the prebuffered mode where the option names none, its prebuffer + * at its default where it gives none and the on-demand mode's at 0, beside the recorded sensor and tier the options boundary settled and the plugin's + * shouldRecord. * @param options - The block's recording option, absent when the block gives none. * @param recorded - The recorded sensor in lowercase and its recorded tier, as the options boundary settled them. - * @returns The recorded sensor in lowercase, the recorded tier, the prebuffer and the shouldRecord the option gives, if any. - * @throws TypeError for a prebuffer that is not a whole number from 0 to 30000, and for a shouldRecord that is not a function. + * @returns The mode, the prebuffer, the recorded sensor in lowercase, the recorded tier and the shouldRecord the option gives, if any. + * @throws TypeError for a mode that is neither `'prebuffered'` nor `'onDemand'`, a prebuffer beside the mode `'onDemand'`, a prebuffer of 0, one that is + * not a whole number from 1 to 30000, and for a shouldRecord that is not a function. */ export function validateBufferRecordingOptions(options: CameraBufferRecordingOptions = {}, recorded: ValidatedVideoSensors['recorded']): BufferRecording { - const { prebuffer = DEFAULT_PREBUFFER, shouldRecord } = options + // An untyped caller can give any member beside any mode, which is why the option is read as one shape: a prebuffer beside the mode 'onDemand' cannot be + // typed, and is refused here as every optional member reads, by whether it is given at all. + const { mode = 'prebuffered', prebuffer, shouldRecord }: { + readonly mode?: unknown + readonly prebuffer?: number + readonly shouldRecord?: (start: CameraRecordingStart) => boolean + } = options + + if ((mode !== 'prebuffered') && (mode !== 'onDemand')) { + throw new TypeError(`The mode of the camera capabilities block's recording option, ${String(mode)}, is neither 'prebuffered' nor 'onDemand'.`) + } + + if ((mode === 'onDemand') && (prebuffer !== undefined)) { + throw new TypeError('The recording option of the camera capabilities block states a prebuffer beside the mode \'onDemand\', which keeps none.') + } - if (!Number.isInteger(prebuffer) || (prebuffer < 0) || (prebuffer > LONGEST_PREBUFFER)) { - throw new TypeError(`The prebuffer of the camera capabilities block's recording option, ${String(prebuffer)}, is not a whole number of milliseconds from 0 ` + if (prebuffer === 0) { + throw new TypeError('The prebuffer of the camera capabilities block\'s recording option is 0, but a prebuffered recording reaches back at least 1 ' + + 'millisecond: a camera that keeps no prebuffer states the mode \'onDemand\'.') + } + + const settled = (mode === 'onDemand') + ? 0 + : (prebuffer === undefined) + ? DEFAULT_PREBUFFER + : prebuffer + + if ((mode === 'prebuffered') && (!Number.isInteger(settled) || (settled < 1) || (settled > LONGEST_PREBUFFER))) { + throw new TypeError(`The prebuffer of the camera capabilities block's recording option, ${String(prebuffer)}, is not a whole number of milliseconds from 1 ` + `to ${LONGEST_PREBUFFER}.`) } @@ -65,7 +99,8 @@ export function validateBufferRecordingOptions(options: CameraBufferRecordingOpt } return { - prebuffer, + mode, + prebuffer: settled, sensorUUID: recorded.sensorUUID, shouldRecord, tierId: recorded.tierId, @@ -74,9 +109,9 @@ export function validateBufferRecordingOptions(options: CameraBufferRecordingOpt /** * What a camera's recorder is made with, at the camera controller, its composition root: the callbacks of its recording events, the keeper that holds - * the recorded tier, the policy whose recording state and in-service fact drive the keeper's recording reason, the recorded tier and its prebuffer, the - * camera's reporter, the plugin's shouldRecord, and the lookup the sensor's tier table, which holds the recorded tier's buffer, is reached through, since - * the tables are built after the recorder. + * the recorded tier, the mode, the reader of Motion Detected, the policy whose recording state and in-service fact drive the keeper's recording reason, + * the recorded tier and its prebuffer, the camera's reporter, the plugin's shouldRecord, and the lookup the sensor's tier table, which holds the recorded + * tier's buffer, is reached through, since the tables are built after the recorder. */ export interface BufferRecorderOptions { /** @@ -87,13 +122,23 @@ export interface BufferRecorderOptions { * The keeper of the recorded tier, the tier's one keeper whatever other reason holds it. */ readonly keeper: TierKeeper + /** + * How the recorded tier's stream is supplied: in the prebuffered mode the keeper holds the tier while the user's switch allows recording and the camera + * is in service, and in the on-demand mode a hub's open raises the hold, which stands while a recording is open or Motion Detected reads raised. + */ + readonly mode: NonNullable + /** + * Reads whether Motion Detected reads raised, not raised on a camera without the library's motion sensor, which the on-demand mode's hold reads as a + * recording ends. + */ + readonly motion: () => boolean /** * The camera's operating-mode policy, whose recording state and in-service fact the keeper's recording reason follows, and whose in-service fact and * Recording Audio Active an open reads. */ readonly policy: OperatingModePolicy /** - * How far back each recording reaches, in milliseconds. + * How far back each recording reaches, in milliseconds, 0 in the on-demand mode. */ readonly prebuffer: number /** @@ -106,9 +151,9 @@ export interface BufferRecorderOptions { readonly sensorUUID: string /** * The plugin's answer to whether a hub's recording opens, asked with the start the recorder would tell of before the open is answered, once the camera - * is in service and the recorded tier's buffer is ready. A recording whose call stopped the recorder, the camera leaving service even for a moment, - * recording turned off, the camera switched off or manually disabled, or the camera reset or removed, is refused whatever the answer. Absent, every - * such recording opens. + * is in service and, in the prebuffered mode, the recorded tier's buffer is ready. A recording whose call stopped the recorder, the camera leaving + * service even for a moment, recording turned off, the camera switched off or manually disabled, or the camera reset or removed, is refused whatever + * the answer. Absent, every such recording opens. */ readonly shouldRecord?: (start: CameraRecordingStart) => boolean /** @@ -126,10 +171,10 @@ export interface BufferRecorderOptions { } /** - * A camera's recording from its camera buffer as its constructor settles it: the recorded sensor in lowercase, the recorded tier, the prebuffer and the - * plugin's shouldRecord. + * A camera's recording from its camera buffer as its constructor settles it: the mode, the prebuffer, 0 in the on-demand mode, the recorded sensor in + * lowercase, the recorded tier and the plugin's shouldRecord. */ -export type BufferRecording = Pick +export type BufferRecording = Pick /** * A packet the recorder yields: a recording packet, and for a media segment the wall clock its first picture was taken at, which the recording's @@ -145,26 +190,32 @@ export interface RecorderPacket extends RecordingPacket { /** * The recorder's answer to a hub's recording open, decided once before the recording management answers the open: a refusal, carrying the reason the * open's answer names, or an admission, carrying the function that serves the recording from what the decision read, called once the open is answered - * with the stream's signal, which a close aborts. + * with the stream's signal, which a close aborts, and the route of the hub's own close of that stream, which hands the recorder the reason the hub named. */ export type RecordingAdmission = { readonly admitted: false readonly reason: HDSProtocolSpecificErrorReason } | { readonly admitted: true + readonly hubClosed: (reason: HDSProtocolSpecificErrorReason | undefined) => void readonly serve: (signal?: AbortSignal) => AsyncIterable } // The one refusal the recorder gives, as busy, whatever it declined the open for. const REFUSED: RecordingAdmission = { admitted: false, reason: HDSProtocolSpecificErrorReason.BUSY } -// What an admission read, which the admitted recording opens on: the recorded tier's buffer, its picture's description, the keyframe at its head and the -// start the recording events carry. +// The cause a recording-declined problem names and the one a recording-timed-out problem names, as their arms of the problem state them. +type DeclinedCause = Extract['cause'] +type TimedOutCause = Extract['cause'] + +/* What an admission read, which the admitted recording opens on: the recorded tier's buffer and the start the recording events carry, and in the + * prebuffered mode the keyframe at the buffer's head with its picture's description. The on-demand mode reads neither: its recording reads the buffer as + * it is served, opening at once on a ready buffer and otherwise at the stream's first decodable keyframe. + */ interface AdmittedRecording { - readonly head: BufferedSample + readonly opening?: { readonly head: BufferedSample, readonly video: Mp4StreamVideoTrack } readonly start: CameraRecordingStart readonly tier: TierBuffer - readonly video: Mp4StreamVideoTrack } // What an open recording reaches in its recorder: the problem of a segment that reached the cap, and its own end. @@ -185,7 +236,8 @@ interface Segment { readonly end?: bigint } -// The end of a recording the recorder ends itself: one zero octet marked last, which a hub reads as the end of the stream. +// The end of a recording the recorder ends itself once it has sent a media segment: one zero octet marked last, which ends the stream after the segments +// a hub took. function endMarker(): RecordingPacket { return { data: Buffer.alloc(1), @@ -237,18 +289,36 @@ function matches(carried: Mp4StreamTrack, track: Mp4StreamTrack | undefined): bo : (right !== undefined) && left.equals(right) } +// What a recording opened on, set once at its opening: its picture's description, its sound, absent for a recording without sound, and the longest a +// segment closed as it stands spans, in the picture's ticks rounded down: the camera buffer's longest reach at the recording's prebuffer. +interface OpenedTracks { + readonly audio?: Mp4StreamAudioTrack + readonly longest: bigint + readonly video: Mp4StreamVideoTrack +} + /* One recording the recorder serves, from a hub's open to its end, and its place in the recorded tier's buffer, held at the keyframe its segment in * progress opens on. * + * A recording opens at a keyframe its initialization segment is written from: at the buffer's head as it is served, or in the on-demand mode on a buffer + * not yet ready, at the first keyframe the buffer opens on while it is ready, a keyframe whose units and description hold HEVC's parameter sets. Until + * then it waits: its place holds no keyframe, a new description is its first and ends nothing, a keyframe a decoder cannot read is passed over, and its + * length reads 0. A recording its serve leaves waiting holds the failsafe, one timer that ends it as failed `DELEGATE_CALL_TIMEOUT` after the hub's open + * whatever its stream does, cleared at its opening and at its finish, which every end of a recording passes through. + * * It cuts each segment at a keyframe, from the place on: at the first keyframe at or past the segment target from the opening one, or earlier at the last * keyframe once the segment would reach the cap, and a stretch between two keyframes that alone reaches the cap at the keyframe that closes it, with one - * `segment-over-cap` problem. A segment leaves once the fragment holding its closing keyframe has ended, which is why the sound that fragment brings after the - * keyframe goes with it. Each segment's sound is the sound timed from its opening keyframe up to its closing one. Sound timed inside a segment - * already sent is dropped. The picture's decode times start at zero and run on by each sample's duration, across a discontinuity and a short gap alike, - * which reads as the duration of the picture before it, and each segment's sound is placed against its opening keyframe on the stream's own times. An - * unsettled sound lasts as long as its own packet says: the next segment's first sound stands where it ends whatever the stream stated for it, and a - * run's lone sound whose length nothing tells, with no sound sent before it, is not written. Each track's decode times on the recording rise as the - * stream's own do, which the stream reader holds within a run, and across a run's end. + * `segment-over-cap` problem. A segment leaves once the fragment holding its closing keyframe has ended and its sound is whole, at the open where the buffer holds it + * so already and at a fragment's end after that: every sound timed inside it has arrived, or the newest picture stands `SOUND_WAIT` past its closing keyframe or + * within `SOUND_WAIT` of the recording's longest reach, and a recording without sound waits for none. The sound a later fragment brings for a segment goes with it, + * and a stream whose sound has stopped holds its segment back no further than the bound. The reach is read at each picture as well as at a fragment's end, + * which keeps a held place out of the buffer's trim whatever a fragment's length. An end that drops the segment in progress drops a held segment with it, + * and one that closes the segment in progress as it stands closes a held segment with what follows it. Each segment's sound is the sound timed from its opening + * keyframe up to its closing one. Sound timed inside a segment already sent is dropped. The picture's decode times start at zero and run on by each sample's duration, + * across a discontinuity and a short gap alike, which reads as the duration of the picture before it, and each segment's sound is placed against its + * opening keyframe on the stream's own times. An unsettled sound lasts as long as its own packet says: the next segment's first sound stands where it ends + * whatever the stream stated for it, and a run's lone sound whose length nothing tells, with no sound sent before it, is not written. Each track's decode + * times on the recording rise as the stream's own do, which the stream reader holds within a run, and across a run's end. * * The end of a run closes the segment in progress as it stands, and so does an end the stream caused before the recording ends: the camera's source * stated away, a long gap or a new description that does not match. The segment's sound ends at the least decode time the next run's first sound can take @@ -257,9 +327,12 @@ function matches(carried: Mp4StreamTrack, track: Mp4StreamTrack | undefined): bo * segment cut at a keyframe keeps within already, the buffer dropping a keyframe its newest picture reaches back past: its newest picture's stand-in is * cut to the time that reach leaves it, and a newest picture it leaves none is left out and counted as dropped. A segment under the reach is written as * it stands. A segment whose pictures span no time, a run's lone picture of no length before any picture's length is known, is not sent, and the next - * run's first picture takes the decode time it would have held. After a run's end the recording carries on from the next keyframe the buffer keeps. Its - * packets wait in a queue its iterable reads, the initialization segment first, each segment's packet carrying the wall clock its first picture was - * taken at. + * run's first picture takes the decode time it would have held. After a run's end the recording carries on from the next keyframe the buffer keeps, the + * lead-up a restart brings included, which means a clip can repeat video the restart hands over again and loses none, the repeat standing in the clip's + * time like any other video. Its packets wait in a queue its iterable reads, the initialization segment first, each segment's packet carrying the wall + * clock its first picture was taken at. An end the recorder makes itself ends its iterable with the end marker once a media segment has gone, and before + * any, the recording waiting or opened on its initialization segment alone, with a throw naming the close's reason, which the recording stream turns into + * a close to the hub. */ class OpenRecording implements BufferPlace { keyframe?: BufferedSample @@ -267,13 +340,17 @@ class OpenRecording implements BufferPlace { // The media segments sent, which the recording's end reports. segments = 0 private readonly buffer: TierBuffer - private readonly video: Mp4StreamVideoTrack - // The sound the recording carries, absent for a recording without sound. - private readonly audio?: Mp4StreamAudioTrack + // Whether the recording carries the stream's sound, as Recording Audio Active read at the hub's open. + private readonly sound: boolean + private readonly prebuffer: number + // What the recording opened on, absent while it waits. + private opened?: OpenedTracks private readonly routes: RecordingRoutes private readonly queue: RecorderPacket[] = [] - // How the recording ended, and whether its iterable ends with the end marker. - private finished?: { readonly marked: boolean } + // How the recording's iterable ends once its queue is read: with the end marker, with a throw of the close's reason, or with nothing more. + private finished?: { readonly close?: HDSProtocolSpecificErrorReason, readonly marked: boolean } + // The failsafe's timer, which ends a recording still waiting for its first keyframe, absent where the recording's serve armed none. + private failsafe?: ReturnType // Resolves the wait of the recording's iterable for its next packet. private wake?: () => void // The decode time the stream's own times give the next picture the recording sends, in the picture's timescale, from zero at the recording's first. @@ -285,28 +362,47 @@ class OpenRecording implements BufferPlace { // The stream's time in microseconds the last segment sent closed at, before which sound arriving later is dropped, and the samples the recording dropped. private sentUpTo?: number private droppedSamples = 0 - // The longest a segment closed as it stands spans, in the picture's ticks rounded down: the camera buffer's longest reach at the recording's prebuffer. - private readonly longest: bigint + // Whether the recording's stream has handed it a picture since it took its place at the hub's open, which a hub's TIMEOUT close reads. + private pictured = false - // Opens the recording at the keyframe the buffer opens on, its initialization segment queued first and written from that keyframe, which carries the - // parameter sets of a stream whose header holds none, as the buffer's readiness found in its head. - constructor(buffer: TierBuffer, video: Mp4StreamVideoTrack, head: BufferedSample, { audio, prebuffer, routes, streamId }: { - readonly audio?: Mp4StreamAudioTrack + // Makes a recording that waits until it opens, its place not yet taken. + constructor(buffer: TierBuffer, { prebuffer, routes, sound, streamId }: { readonly prebuffer: number readonly routes: RecordingRoutes + readonly sound: boolean readonly streamId: number }) { this.buffer = buffer - this.video = video - this.audio = audio + this.prebuffer = prebuffer this.routes = routes + this.sound = sound this.streamId = streamId - this.longest = BigInt(longestReach(prebuffer)) * BigInt(video.timescale) / 1000n + } + + /* Opens the recording at a keyframe the buffer opens on, its initialization segment queued first and written from that keyframe, which carries the + * parameter sets of a stream whose header holds none, as the buffer's readiness found in its head. The recording carries the stream's sound where + * Recording Audio Active read on at the open and the stream describes a sound track. + */ + open(head: BufferedSample, video: Mp4StreamVideoTrack): void { + // The one place a waiting recording stops waiting, which is why the failsafe is cleared here: its fire carries no check of its own, and a timer left + // standing would end a recording that has opened. + clearTimeout(this.failsafe) + + const audio = this.sound + ? this.buffer.tracks?.audio + : undefined + + this.opened = { + audio, + longest: BigInt(longestReach(this.prebuffer)) * BigInt(video.timescale) / 1000n, + video, + } this.keyframe = head this.queue.push({ data: writeKeyframeInitializationSegment({ audio, keyframe: head.data, video }), isLast: false, }) + this.wake?.() } // Sends the segments the buffer already holds whole, once the recording has begun. @@ -314,28 +410,79 @@ class OpenRecording implements BufferPlace { this.cut() } + /* Arms the failsafe of a recording its serve leaves waiting, on one unreferenced timer: the start the open asked for is cut at the same delegate bound + * from its call, imported and never copied, and a recording still waiting then has its fire take the recording's own route to the recorder's one end, + * closed to the hub with a reason, since no media segment has left. + */ + armFailsafe(): void { + this.failsafe = setTimeout(() => this.routes.end('failed'), DELEGATE_CALL_TIMEOUT).unref() + } + + // Whether the recording still waits for the keyframe it opens on. + get waiting(): boolean { + return this.opened === undefined + } + + /* What a hub's TIMEOUT close had not received of the recording: no media segment from one that opened, no keyframe a decoder can read from one still + * waiting whose stream handed it a picture, and no picture from one still waiting whose stream handed it none. A recording that sent a media segment + * names nothing, since the library cannot tell why the hub gave up. + */ + get timeoutCause(): TimedOutCause { + if (this.segments > 0) { + return undefined + } + + if (!this.waiting) { + return 'no-segment' + } + + return this.pictured + ? 'no-keyframe' + : 'no-picture' + } + // The samples the recording dropped, which its end reports. get dropped(): number { return this.droppedSamples } // The length in seconds of the media segments the recording counts, which its end reports: the durations of their pictures summed over the picture's - // timescale, media time and never the wall time the recording stayed open. + // timescale, media time and never the wall time the recording stayed open, 0 for a recording that never opened. get seconds(): number { - return Number(this.pictureTime) / this.video.timescale + return (this.opened === undefined) + ? 0 + : Number(this.pictureTime) / this.opened.video.timescale } - // A recording waiting for a keyframe takes its place at the first the buffer keeps, and sound timed inside a segment already sent is counted as dropped. + /* A recording holding no keyframe takes its place at the first the buffer keeps: a waiting recording opens there where the buffer is ready, a keyframe + * a decoder cannot read passed over, its lead-up's first where the stream brings one, and an opened one carries on there after a run's end, the + * lead-up a restart brings included. A clip can therefore repeat video the restart hands over again, and it loses none: the repeat stands in the clip's + * time like any other video. Sound timed inside a segment already sent is counted as dropped. + */ taken(sample: BufferedSample): void { if (sample.track.medium === 'video') { + this.pictured = true + if ((this.keyframe === undefined) && (sample === this.buffer.head)) { - this.keyframe = sample + const video = this.buffer.tracks?.video + + if (this.opened !== undefined) { + this.keyframe = sample + } else if (this.buffer.ready && (video !== undefined)) { + this.open(sample, video) + } + } + + // A place this picture brings within `SOUND_WAIT` of the reach sends what it can at this picture, with no wait for the fragment's end: the pictures + // still to come in a fragment seconds long would otherwise carry a segment held for its sound into the buffer's trim, which ends the recording. + if ((this.keyframe !== undefined) && this.pressed(this.keyframe, sample)) { + this.cut() } return } - if ((this.audio !== undefined) && (this.sentUpTo !== undefined) && (sample.time < this.sentUpTo)) { + if ((this.opened?.audio !== undefined) && (this.sentUpTo !== undefined) && (sample.time < this.sentUpTo)) { this.droppedSamples++ } } @@ -345,10 +492,17 @@ class OpenRecording implements BufferPlace { } /* A new description of a track the recording carries that does not match ends the recording, since it would need a second initialization segment, - * after the segment in progress closed as it stands, written under the description the recording opened on while the buffer still holds its run. + * after the segment in progress closed as it stands, written under the description the recording opened on while the buffer still holds its run. A + * waiting recording takes a new description as its first, and it ends nothing. */ describing(tracks: Mp4StreamTracks): void { - if (!matches(this.video, tracks.video) || ((this.audio !== undefined) && !matches(this.audio, tracks.audio))) { + const { opened } = this + + if (opened === undefined) { + return + } + + if (!matches(opened.video, tracks.video) || ((opened.audio !== undefined) && !matches(opened.audio, tracks.audio))) { this.closeAsItStands() this.routes.end('failed') } @@ -399,10 +553,24 @@ class OpenRecording implements BufferPlace { this.routes.end('failed') } - // Ends the recording's packets, after the whole segments already queued and, for an end the recorder makes itself, with the end marker, and gives up its - // place in the buffer, which falls back to its span at once. - finish(marked: boolean): void { - this.finished = { marked } + /* Ends the recording's packets after the whole segments already queued, and gives up its place in the buffer, which falls back to its span at once. An + * end the recorder makes itself is read from what the hub has received once the end's own closing has run: after a media segment its packets end with + * the end marker, and before any with a close naming CANCELLED for an end cancelled and UNEXPECTED_FAILURE for any other, since a hub leaves a stream + * open that brings the end marker alone, and the close frees it at once. + */ + finish(outcome: CameraRecordingOutcome, marked: boolean): void { + const sent = this.segments > 0 + + this.finished = { + close: marked && !sent + ? (outcome === 'cancelled') + ? HDSProtocolSpecificErrorReason.CANCELLED + : HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE + : undefined, + marked: marked && sent, + } + // Every end of a recording passes here, which is why this one clear leaves no end with the failsafe standing. + clearTimeout(this.failsafe) this.keyframe = undefined this.buffer.givePlaceUp(this) this.wake?.() @@ -413,6 +581,7 @@ class OpenRecording implements BufferPlace { * stream's signal aborts. A close never waits on the next segment. * @param signal - The stream's signal, which a close aborts. * @yields Each packet. + * @throws HDSProtocolError naming the close's reason, once the queue is read, for an end the recorder made before any media segment went. */ async* packets(signal?: AbortSignal): AsyncGenerator { signal?.addEventListener('abort', () => this.wake?.(), { once: true }) @@ -430,7 +599,13 @@ class OpenRecording implements BufferPlace { } if (this.finished !== undefined) { - if (this.finished.marked) { + const { close, marked } = this.finished + + if (close !== undefined) { + throw new HDSProtocolError(close) + } + + if (marked) { yield endMarker() } @@ -444,6 +619,12 @@ class OpenRecording implements BufferPlace { } } + // What the recording opened on, which every step that cuts, closes or sends a segment reads: those steps start from the keyframe the place holds, and a + // place holds one only once its recording has opened. + private get tracks(): OpenedTracks { + return this.opened! + } + // Sends each segment the buffer holds whole from the place on. private cut(): void { for (let segment = this.closing(); segment !== undefined; segment = this.closing()) { @@ -453,7 +634,11 @@ class OpenRecording implements BufferPlace { /* The segment the place opens that can leave now, if one can: closed at the first keyframe at or past the target, or at the last keyframe before the * segment would reach the cap, or, for a stretch that alone reaches the cap, at the keyframe that closes it. A segment whose closing keyframe arrived in a - * fragment that has not ended waits for that fragment's end. + * fragment that has not ended waits for that fragment's end, and then for its sound: it leaves at the first fragment's end that finds every sound timed + * inside it arrived, or the newest picture standing `SOUND_WAIT` past its closing keyframe, which bounds the wait of a stream whose sound has stopped, + * or within `SOUND_WAIT` of the recording's longest reach, which `taken` reads at each picture too. The call keeps no state and arms no timer, reading + * the buffer's walk again each time, which is why a held segment whose late sound takes it to the cap is cut by the cap's own rule at the next call. An + * end that drops the segment in progress drops a held segment with it, and one that closes it as it stands closes a held segment with what follows it. */ private closing(): Segment | undefined { const open = this.keyframe @@ -507,14 +692,20 @@ class OpenRecording implements BufferPlace { private stretch(open: BufferedSample): BufferWalk { const walked = this.buffer.walk(open) - return (this.audio === undefined) + return (this.tracks.audio === undefined) ? { pictures: walked.pictures, sounds: [] } : walked } - // The segment of the pictures before a closing keyframe, each at the duration the buffer settled, and the sound timed before it. - private segment(pictures: readonly BufferedSample[], sounds: readonly BufferedSample[], close: number, overCap: boolean): Segment { + // The segment of the pictures before a closing keyframe, each at the duration the buffer settled, and the sound timed before it, once that sound is + // whole, and none while the segment waits for it. Every cut at a keyframe returns through here, which is why one check serves each of them. + private segment(pictures: readonly BufferedSample[], sounds: readonly BufferedSample[], close: number, overCap: boolean): Segment | undefined { const next = pictures[close] + + if (!this.soundWhole(pictures, sounds, next)) { + return undefined + } + const cut = pictures.slice(0, close) return { @@ -526,6 +717,34 @@ class OpenRecording implements BufferPlace { } } + /* Whether the sound timed inside a segment cut at a keyframe is whole, read from the walk of its place, the segment's opening keyframe first: the + * recording carries no sound, or the walk's newest sound is timed at or after the segment's closing keyframe, which means every sound timed before it has + * arrived, a run's sound times rising in the order they arrive, or the walk's newest picture stands `SOUND_WAIT` or more past that keyframe, or within + * `SOUND_WAIT` of the recording's longest reach from the opening keyframe. The bound sends the segment of a stream whose sound has stopped, or runs + * further behind, with the sound that has arrived. The reach's clause keeps a held place out of the buffer's trim, which would end the recording: + * `taken` reads it at each picture as well, which means a held segment leaves before pictures less than `SOUND_WAIT` apart can carry its place past + * the reach, whatever a fragment's length. + */ + private soundWhole(pictures: readonly BufferedSample[], sounds: readonly BufferedSample[], close: BufferedSample): boolean { + if (this.tracks.audio === undefined) { + return true + } + + const [open] = pictures + const newest = pictures.at(-1)! + const heard = sounds.at(-1) + + return ((heard !== undefined) && (heard.time >= close.time)) + || (newest.time - close.time >= SOUND_WAIT) + || this.pressed(open, newest) + } + + // Whether a picture stands within `SOUND_WAIT` of the recording's longest reach from a place's keyframe, the buffer's own trim limit at the + // recording's prebuffer: a place held past it would be lost to the trim before pictures less than `SOUND_WAIT` apart brought the next reading. + private pressed(open: BufferedSample, newest: BufferedSample): boolean { + return newest.time - open.time >= longestReach(this.prebuffer) * 1000 - SOUND_WAIT + } + /* The pictures a segment closed as it stands carries and the duration it writes for each, which its span sums: each picture from its opening keyframe * at the duration the recording writes for it but the newest, whose stand-in is cut to the time the longest reach leaves it past the pictures before * it, and which is left out where the reach leaves it none. Every picture before the newest starts within the reach as the buffer compares times, since @@ -534,7 +753,7 @@ class OpenRecording implements BufferPlace { private standing(walked: readonly BufferedSample[]): Pick { const durations = this.pictureDurations(walked) const newest = durations.pop() - const left = this.longest - durations.reduce((total, duration) => total + BigInt(duration), 0n) + const left = this.tracks.longest - durations.reduce((total, duration) => total + BigInt(duration), 0n) if ((newest !== undefined) && (left > 0n)) { durations.push(Math.min(newest, Number(left))) @@ -566,17 +785,17 @@ class OpenRecording implements BufferPlace { * none to end, and reads it on the picture's own timescale. */ private soundEnd(open: BufferedSample, pictureEnd: bigint): bigint { - const { timescale } = this.audio ?? this.video + const { timescale } = this.tracks.audio ?? this.tracks.video - return pictureEnd * BigInt(timescale) / BigInt(this.video.timescale) - this.soundOffset(open) + return pictureEnd * BigInt(timescale) / BigInt(this.tracks.video.timescale) - this.soundOffset(open) } // How far a segment's sound stands on the recording from its stream's own decode times, on the sound's timescale: the recording's picture time at the // segment's opening keyframe less that keyframe's own decode time, divided toward zero. private soundOffset(open: BufferedSample): bigint { - const { timescale } = this.audio ?? this.video + const { timescale } = this.tracks.audio ?? this.tracks.video - return (this.pictureTime - open.decodeTime) * BigInt(timescale) / BigInt(this.video.timescale) + return (this.pictureTime - open.decodeTime) * BigInt(timescale) / BigInt(this.tracks.video.timescale) } /* The duration a segment writes for a sound: the one the buffer settled, the distance to its track's next decode time, or for an unsettled sound, its @@ -658,7 +877,7 @@ class OpenRecording implements BufferPlace { this.queue.push({ data: writeSegment({ - audio: (this.audio !== undefined) && (timed.length > 0) + audio: (this.tracks.audio !== undefined) && (timed.length > 0) ? { decodeTime: timed[0].sound.decodeTime + offset, samples: audio, @@ -686,26 +905,39 @@ class OpenRecording implements BufferPlace { /** * The recorder of a camera that records from its camera buffer: the recording delegate its recording management serves a hub's recording through, and the - * driver of the recording reason of the recorded tier's keeper, which holds the tier while the user's switch allows recording and the camera is in - * service, its accessory published and its source not stated away. + * driver of the recording reason of the recorded tier's keeper, which holds the tier, in the prebuffered mode while the user's switch allows recording and + * the camera is in service, its accessory published and its source not stated away, and in the on-demand mode from a hub's open while a recording is + * open or Motion Detected reads raised. * - * The recording reason follows the policy's `recordingInService`, recording allowed and the camera in service: read once as {@link configure} - * subscribes it and raised when it reads true, raised at each move to true and released at each move to false, at a reset and at a removal. Neither the - * recording state nor a configuration reaches the recorder through the delegate's calls, which do nothing. + * In the prebuffered mode the recording reason follows the policy's `recordingInService`, recording allowed and the camera in service: read once as + * {@link configure} subscribes it and raised when it reads true, raised at each move to true and released at each move to false, at a reset and at a + * removal. In the on-demand mode the open the recorder serves raises it, asking for the stream at once where the keeper waits to ask again, and the + * recorder releases it where no recording is open and Motion Detected does not read raised: in a later turn after a recording's end, and at Motion + * Detected's fall. A move of `recordingInService` to false, a reset and a removal release it in every mode. Neither the recording state nor a + * configuration reaches the recorder through the delegate's calls, which do nothing. * * The recorder decides a hub's open once, through {@link admit}, before the recording management answers it, and each open it declines is refused in that - * answer as busy: no stream opens and no recording event is told. An open on a camera out of service is refused with no problem, and one on a buffer - * that is not ready with one `recording-declined` problem. An open on a ready buffer asks the plugin's shouldRecord, where it gives one, with the start - * `recording-started` would carry, and one it declines is refused with no problem, as is one whose call stopped the recorder whatever it answered: the - * camera left service, even for a moment, recording was turned off, the camera was switched off or manually disabled, or the camera was reset or - * removed. An open it admits begins a recording once it is answered, told of through `recording-started` with that same start, which yields an - * initialization segment of the picture and, unless Recording Audio Active reads off at the open, the sound, and then segments, those the buffer holds - * whole at once and each later one as the fragment holding its closing keyframe ends. A recording ends once, after its last whole segment, its - * `recording-ended` emitted as the end is decided: at the hub's acknowledgement or close, and at an end the recorder makes itself, which yields the end - * marker, at recording no longer allowed or the camera going out of service, a reset or a removal, a long gap, a change of a carried track's - * description, a ceiling's trim past its place, and a throw from its own reading of the buffer, which takes its place off. An end the stream caused, the - * camera's source stated away while recording is still allowed and the accessory published, a long gap or a change of a carried track's description, - * comes after the segment in progress closed as it stands, as a run's end closes it, and every other end the recorder makes drops that segment. + * answer as busy: no stream opens and no recording event is told. An open on a camera out of service is refused with no problem, and in the prebuffered + * mode one on a buffer that is not ready with one `recording-declined` problem. An open the recorder would serve asks the plugin's shouldRecord, where it + * gives one, with the start `recording-started` would carry, and one it declines is refused with no problem, as is one whose call stopped the recorder + * whatever it answered: the camera left service, even for a moment, recording was turned off, the camera was switched off or manually disabled, or the + * camera was reset or removed. An open it admits begins a recording once it is answered, told of through `recording-started` with that same start, + * which yields an initialization segment of the picture and, unless Recording Audio Active reads off at the open, the sound, and then segments, those the + * buffer holds whole at once and each later one at the end of a fragment, once the fragment holding its closing keyframe has ended and the sound timed + * inside the segment has arrived, or its newest picture stands `SOUND_WAIT` past that keyframe, the bound on how long a stream whose sound has stopped + * holds a segment back, or within `SOUND_WAIT` of the buffer's longest reach, read at each picture too, which keeps a held segment's place out of the + * buffer's trim whatever a fragment's length. In the on-demand mode a recording on a buffer that is not ready waits through every failure of its stream + * for the stream's first decodable keyframe, its lead-up's where the stream brings one, and opens on it, and the failsafe ends a recording still waiting + * `DELEGATE_CALL_TIMEOUT` after the hub's open, whatever its stream does. + * + * A recording ends once, after its last whole segment, its `recording-ended` emitted as the end is decided: at the hub's acknowledgement or close, a close + * telling the reason the hub named and a close with the reason TIMEOUT raising one `recording-timed-out` problem, and at an end the recorder makes itself, + * at recording no longer allowed or the camera going out of service, a reset or a removal, a long gap, a change of a carried track's description, a + * ceiling's trim past its place, a throw from its own reading of the buffer, which takes its place off, and the failsafe's end of a recording still + * waiting. An end the recorder makes itself yields the end marker after a media segment, and before any, in every mode, a close naming a reason. An end + * the stream caused, the camera's source stated away while recording is still allowed and the accessory published, a long gap or a change of a carried + * track's description, comes after the segment in progress closed as it stands, as a run's end closes it, a segment held for its sound with what + * follows it, and every other end, a hub's among them, drops that segment, a held one with it. */ export class BufferRecorder implements CameraRecordingDelegate, Disposable { private readonly options: BufferRecorderOptions @@ -735,19 +967,22 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { } /** - * Subscribes the policy's `recordingInService`, which raises the keeper's recording reason at each move to true, and at each move to false stops the - * recorder and then releases the reason, and raises it now when the user's switch allows recording and the camera is in service already. A move to - * false while `recordingPublished` still reads true, recording allowed and the accessory published, is the camera's source stated away: the stop - * serves the segment in progress before the recording's end, and every other move drops it. The reason is released only where the camera still reads - * out of service once the stop returns, since a listener of the recording's end may state the source available again or turn recording on inside its - * call, which raises the reason while the stop runs. + * Subscribes the policy's `recordingInService`, which at each move to false stops the recorder and then releases the keeper's recording reason, and in + * the prebuffered mode raises the reason at each move to true and now when the user's switch allows recording and the camera is in service already. The + * on-demand mode raises nothing here, its hold raised by a hub's open alone. A move to false while `recordingPublished` still reads true, recording + * allowed and the accessory published, is the camera's source stated away: the stop serves the segment in progress before the recording's end, and + * every other move drops it. The reason is released only where the camera still reads out of service once the stop returns, since a listener of the + * recording's end may state the source available again or turn recording on inside its call, which raises the reason while the stop runs. */ configure(): void { - const { keeper, policy } = this.options + const { keeper, mode, policy } = this.options + const prebuffered = mode === 'prebuffered' policy.subscribeDerivation('recordingInService', (allowed) => { if (allowed) { - keeper.raise('recording') + if (prebuffered) { + keeper.raise('recording') + } } else { this.stop(policy.recordingPublished()) @@ -757,7 +992,7 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { } }) - if (policy.recordingInService()) { + if (prebuffered && policy.recordingInService()) { keeper.raise('recording') } } @@ -774,13 +1009,14 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { /** * Decides a hub's recording open, which the recording management asks before it answers the open: refused as busy while the camera is out of service, - * while the buffer is not ready, or where the plugin's shouldRecord answers false or its call stopped the recorder, and otherwise admitted with the - * function that serves the recording from what the decision read. The decision is made once and the recorder holds nothing until it is served. + * in the prebuffered mode while the buffer is not ready, or where the plugin's shouldRecord answers false or its call stopped the recorder, and + * otherwise admitted with the function that serves the recording from what the decision read and the route of the hub's own close of the stream. The + * decision is made once and the recorder holds nothing until it is served, which means in the on-demand mode that a declined open starts no stream. * @param streamId - The hub's recording stream. - * @returns The refusal, or the admission and its serving function. + * @returns The refusal, or the admission, its serving function and its route of the hub's close. */ admit(streamId: number): RecordingAdmission { - const { policy, reporter, sensorUUID, tierId, tierTable } = this.options + const { mode, policy, reporter, sensorUUID, tierId, tierTable } = this.options // A camera out of service holds no tier, which is why its refusal comes first and raises no problem, the plugin having done nothing wrong. if (!policy.inService()) { @@ -788,20 +1024,35 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { } const tier = tierTable(sensorUUID)?.videoTiers.get(tierId)?.buffer - const video = tier?.tracks?.video - const head = tier?.head + let opening: AdmittedRecording['opening'] + + // In the prebuffered mode a ready buffer holds a picture's description and a keyframe at its head, which the recording opens on. The on-demand mode + // reads no readiness, since its recording waits for its stream. + if (mode === 'prebuffered') { + const video = tier?.tracks?.video + const head = tier?.head + + if ((tier?.ready !== true) || (video === undefined) || (head === undefined)) { + const cause = this.declinedCause(tier) + + reporter.problem({ + cause, + kind: 'recording-declined', + level: 'warning', + sensorUUID, + sentence: this.declinedSentence(cause), + tierId, + }) + + return this.refused(streamId, 'the camera buffer is not ready') + } - // A ready buffer holds a picture's description and a keyframe at its head. - if ((tier?.ready !== true) || (video === undefined) || (head === undefined)) { - reporter.problem({ - kind: 'recording-declined', - level: 'warning', - sensorUUID, - sentence: this.declinedSentence(tier), - tierId, - }) + opening = { head, video } + } - return this.refused(streamId, 'the camera buffer is not ready') + // The sensor's tier table stands from the camera's configuration on, which is why a camera in service finds the recorded tier's buffer. + if (tier === undefined) { + return this.refused(streamId, 'the camera holds no buffer of its recorded tier') } // The plugin is asked only once the library would record, with the start the recording-started event then carries, and its decline raises no problem, @@ -818,7 +1069,8 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { return { admitted: true, - serve: signal => this.serve({ head, start, tier, video }, signal), + hubClosed: reason => this.closed(streamId, outcomeOf(reason), reason), + serve: signal => this.serve({ opening, start, tier }, signal), } } @@ -840,14 +1092,16 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { return admission.serve(signal) } - // Serves an admitted recording: it opens at the keyframe the admission read at the buffer's head, takes its place on the tier, is told of and begins. - private serve({ head, start, tier, video }: AdmittedRecording, signal?: AbortSignal): AsyncIterable { - const { policy, prebuffer, reporter, sensorUUID, started, tierId } = this.options + /* Serves an admitted recording. In the prebuffered mode it opens at the keyframe the admission read at the buffer's head, takes its place on the tier, + * is told of and begins. In the on-demand mode it opens at once at the head of a ready buffer, its stream running for a viewer or under keepRunning, and + * otherwise waits; it takes its place and is told of, and only where it is still the open one once the event returns does it raise the keeper's + * recording reason, asking for the stream at once, begin, and arm its failsafe where it still waits. A listener of the event runs in the same turn and + * may stop the recorder, turning recording off or stating the source away, which would otherwise leave the tier held out of service. + */ + private serve({ opening, start, tier }: AdmittedRecording, signal?: AbortSignal): AsyncIterable { + const { keeper, policy, prebuffer, reporter, sensorUUID, started, tierId } = this.options const { streamId } = start - const recording: OpenRecording = new OpenRecording(tier, video, head, { - audio: policy.recordingAudioActive - ? tier.tracks?.audio - : undefined, + const recording: OpenRecording = new OpenRecording(tier, { prebuffer, routes: { capped: () => { @@ -864,13 +1118,40 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { this.end(recording, outcome, true) }, }, + sound: policy.recordingAudioActive, streamId, }) + if (opening !== undefined) { + recording.open(opening.head, opening.video) + this.recording = recording + tier.takePlace(recording) + started(start) + recording.begin() + + return recording.packets(signal) + } + + const { head } = tier + const video = tier.tracks?.video + + if (tier.ready && (head !== undefined) && (video !== undefined)) { + recording.open(head, video) + } + this.recording = recording tier.takePlace(recording) started(start) - recording.begin() + + if (this.recording === recording) { + keeper.raiseNow('recording') + recording.begin() + + // Plugin code runs inside the raise and may open the recording on a keyframe it writes inside its start, or end it, and either arms nothing. + if ((this.recording === recording) && recording.waiting) { + recording.armFailsafe() + } + } return recording.packets(signal) } @@ -884,7 +1165,9 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { } /** - * Ends the recording the hub or its connection closed, by the close's reason, and does nothing for one already ended. + * Ends the recording a close names, by the close's reason, and does nothing for one already ended. The library's own closes and the connection's reach + * the recorder here, and the end they make carries no reason, while a hub's own close of an admitted stream takes the admission's route, whose end + * carries the reason the hub named. * @param streamId - The hub's recording stream. * @param reason - The close's reason, absent for the connection's close. */ @@ -893,14 +1176,32 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { } /** - * Ends an open recording at the long gap, after its segment in progress closed as it stands, which the keeper tells of once the long-gap time passes - * since the last picture it read from the tier's buffer, while the buffer still holds the run. That order rests on the keeper reading each picture + * Ends a recording that has opened at the long gap, after its segment in progress closed as it stands, which the keeper tells of once the long-gap time + * passes since the last picture it read from the tier's buffer, while the buffer still holds the run. That order rests on the keeper reading each picture * first, inside the buffer's take and before the tier's demand moves its own clock on, and on a reconnect telling each keeper before each tier table: - * at the deadline the keeper's clock and the demand's share, the gap is told before the demand's end empties the buffer. + * at the deadline the keeper's clock and the demand's share, the gap is told before the demand's end empties the buffer. A recording that still waits + * is left waiting, since it has sent no video a gap could describe, and its failsafe ends it at its own time. */ lapsed(): void { + const { recording } = this + + if ((recording === undefined) || recording.waiting) { + return + } + this.closeSegment() - this.end(this.recording, 'gap', true) + this.end(recording, 'gap', true) + } + + /** + * Takes each edge of Motion Detected, which the camera's one listener hands the recorder: in the on-demand mode its fall releases the keeper's + * recording reason where no recording is open. + * @param detected - Whether Motion Detected now reads raised. + */ + motionChanged(detected: boolean): void { + if ((this.options.mode === 'onDemand') && !detected && (this.recording === undefined)) { + this.options.keeper.release('recording') + } } /** @@ -950,28 +1251,36 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { `The recording of ${this.tierName} failed to close its segment in progress and ends without that segment`, { sensorUUID, tierId }) } - private closed(streamId: number, outcome: CameraRecordingOutcome): void { + // Ends the open recording a close names, with the reason a hub's own close named, and does nothing for a stream that names no open recording. + private closed(streamId: number, outcome: CameraRecordingOutcome, reason?: HDSProtocolSpecificErrorReason): void { const { recording } = this if (recording?.streamId === streamId) { - this.end(recording, outcome, false) + this.end(recording, outcome, false, reason) } } - // Ends a recording once, while it is the open one: its packets finish, its place is given up in the same turn, and its end is told as it is decided. - private end(recording: OpenRecording | undefined, outcome: CameraRecordingOutcome, marked: boolean): void { + /* Ends a recording once, while it is the open one: its packets finish, its place is given up in the same turn, and its end is told as it is decided. The + * reason a hub's own close named is carried on the debug event and the event alike, and every other end carries no reason. A hub's close with the reason + * TIMEOUT raises one recording-timed-out problem before the end is told, and a close of a recording already ended raises none, since it ends nothing. + */ + private end(recording: OpenRecording | undefined, outcome: CameraRecordingOutcome, marked: boolean, reason?: HDSProtocolSpecificErrorReason): void { if ((recording === undefined) || (recording !== this.recording)) { return } const { ended, reporter, sensorUUID, tierId } = this.options const { dropped, seconds, segments, streamId } = recording + const named = (reason === undefined) + ? {} + : { reason } this.recording = undefined - recording.finish(marked) + recording.finish(outcome, marked) reporter.debug(BUFFER_RECORDER_DEBUG, 'recording-ended', () => ({ dropped, outcome, + ...named, seconds, segments, sensorUUID, @@ -980,13 +1289,43 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { streamId, tierId, })) + + if (reason === HDSProtocolSpecificErrorReason.TIMEOUT) { + const cause = recording.timeoutCause + const caused = (cause === undefined) + ? {} + : { cause } + + reporter.problem({ + ...caused, + kind: 'recording-timed-out', + level: 'warning', + sensorUUID, + sentence: `A hub closed the recording of stream ${streamId} of ${this.tierName} with the reason TIMEOUT after ${counted(segments, 'segment')}.`, + tierId, + }) + } + ended({ outcome, + ...named, segments, sensorUUID, streamId, tierId, }) + + /* In the on-demand mode the end releases the recording reason in a later turn, where no recording is open and Motion Detected does not read raised + * then, as the keeper releases a failed join. The later turn keeps the release out of the buffer's own step: a recording whose description changes + * ends inside the plugin's write, and a release there would end the demand and release the plugin's registrations inside that write. + */ + if (this.options.mode === 'onDemand') { + queueMicrotask(() => { + if ((this.recording === undefined) && !this.options.motion()) { + this.options.keeper.release('recording') + } + }) + } } // Answers an open the recorder refuses, after one debug event naming the cause it read, since a refused open makes no stream and writes none of a @@ -1044,12 +1383,19 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { return true } - // Why an open is declined: a stream whose head keyframe a decoder cannot read, named in the words of the demand's own stream-fault problem, or a buffer - // still filling. - private declinedSentence(tier: TierBuffer | undefined): string { + // Why an open is declined: a stream whose head keyframe a decoder cannot read, or a buffer still filling. + private declinedCause(tier: TierBuffer | undefined): DeclinedCause { const video = tier?.tracks?.video const head = tier?.head - const why = (video !== undefined) && (head !== undefined) && !decodable(head.data, video.parameterSets) + + return (video !== undefined) && (head !== undefined) && !decodable(head.data, video.parameterSets) + ? 'undecodable-keyframe' + : 'buffer-filling' + } + + // The sentence of a declined open, read from its cause: a keyframe a decoder cannot read is named in the words of the demand's own stream-fault problem. + private declinedSentence(cause: DeclinedCause): string { + const why = (cause === 'undecodable-keyframe') ? 'its stream carries a keyframe without its video, sequence and picture parameter sets, in its sample or its initialization segment' : `its camera buffer does not yet hold the prebuffer of ${counted(this.options.prebuffer, 'millisecond')}` diff --git a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts index 3d03da432..34161ab7d 100644 --- a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts +++ b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts @@ -3206,10 +3206,20 @@ describe('cMAFRecordingManagement', () => { } } - // A camera with the capabilities block over the fixtures' video sensors that records from its camera buffer with the prebuffer given, none by default, - // and the stream its recorded tier's demand handed out, which a row writes as fragmented MP4. - function wiredCamera(prebuffer = 0): { camera: CameraController, tier: () => TierStream } { - const { options, stream } = bufferCamera({ prebuffer }) + /* A camera with the capabilities block over the fixtures' video sensors that records from its camera buffer, in the prebuffered mode at the prebuffer + * given, and with none given in the on-demand mode, its recorded tier marked keepRunning: a running tier whose buffer spans nothing. Beside it, the + * stream its recorded tier's demand handed out, which a row writes as fragmented MP4. + */ + function wiredCamera(prebuffer?: number): { camera: CameraController, tier: () => TierStream } { + const { options, stream } = bufferCamera((prebuffer === undefined) + ? { mode: 'onDemand' } + : { prebuffer }) + const [recordedSensor] = options.cameraCapabilities.videoSensors + + if (prebuffer === undefined) { + recordedSensor.tiers = recordedSensor.tiers.map(tier => ({ ...tier, keepRunning: tier.id === 1 })) + } + const camera = new CameraController(options) cameras.push(camera) @@ -3381,7 +3391,8 @@ describe('cMAFRecordingManagement', () => { it('makes its management with the longest segment the camera\'s recording can cut as each clip\'s target duration, the camera buffer\'s longest reach ' + 'at its prebuffer in whole seconds rounded up', () => { - expect([0, 2400, 5000, 30000].map((prebuffer) => { + // The on-demand mode's settled prebuffer of 0 first. + expect([undefined, 2400, 5000, 30000].map((prebuffer) => { const { camera } = wiredCamera(prebuffer) camera.constructServices() diff --git a/src/lib/camera/session/ConnectionSessions.spec.ts b/src/lib/camera/session/ConnectionSessions.spec.ts index 022882e3f..a6384ccf4 100644 --- a/src/lib/camera/session/ConnectionSessions.spec.ts +++ b/src/lib/camera/session/ConnectionSessions.spec.ts @@ -176,7 +176,7 @@ describe('connectionSessions', () => { expect(second.listenerCount('closed')).toBe(0) }) - it('serves an authenticated connection until the table is marked destroyed, and never a connection that is not authenticated', () => { + it('serves a connection that is alive until the table is marked destroyed, and never a connection that closed', () => { const { sessions } = table() const connection = buildEmitterConnection() const closed = buildEmitterConnection() @@ -191,25 +191,33 @@ describe('connectionSessions', () => { expect(sessions.serves(connection)).toBe(false) }) - it('answers a session to its opener alone, and to nobody once its opener is not authenticated or the table is marked destroyed', () => { + // An unpaired opener is one a server in insecure mode lets through: alive, and never authenticated. + it.each([ + { kind: 'a paired', paired: true }, + { kind: 'an unpaired', paired: false }, + ])('serves $kind opener that is alive and answers it its session alone, and serves nobody and answers nobody once its opener is not alive or the ' + + 'table is marked destroyed', ({ paired }) => { const { sessions } = table() - const opener = buildEmitterConnection() + const opener = buildEmitterConnection('IPv6', { paired }) const other = buildEmitterConnection() const a = session('a', opener) sessions.add(a) + expect(sessions.serves(opener)).toBe(true) expect(sessions.liveSession('a', opener)).toBe(a) expect(sessions.liveSession('a', other)).toBeUndefined() expect(sessions.liveSession('b', opener)).toBeUndefined() - const authenticated = vi.spyOn(opener, 'isAuthenticated').mockReturnValue(false) + const alive = vi.spyOn(opener, 'isAlive').mockReturnValue(false) + expect(sessions.serves(opener)).toBe(false) expect(sessions.liveSession('a', opener)).toBeUndefined() - authenticated.mockRestore() + alive.mockRestore() sessions.markDestroyed() + expect(sessions.serves(opener)).toBe(false) expect(sessions.liveSession('a', opener)).toBeUndefined() expect(sessions.get('a')).toBe(a) }) diff --git a/src/lib/camera/session/ConnectionSessions.ts b/src/lib/camera/session/ConnectionSessions.ts index a7b888fc6..5f7a5c9eb 100644 --- a/src/lib/camera/session/ConnectionSessions.ts +++ b/src/lib/camera/session/ConnectionSessions.ts @@ -151,12 +151,13 @@ export class ConnectionSessions { /** * Whether a write's handler serves it. A write waits in the service's queue, which is why its handler serves it only while the service stands and the writer's - * connection has not closed meanwhile, and a write it does not serve calls no delegate and registers nothing. + * connection has not closed meanwhile, and a write it does not serve calls no delegate and registers nothing. Recording stays out of an unpaired + * connection's reach, since the data stream's keys come from a paired session. * @param connection - The writer's connection. - * @returns Whether the service is not destroyed and the connection is authenticated. + * @returns Whether the service is not destroyed and the connection is alive. */ serves(connection: HAPConnection): boolean { - return !this.destroyed && connection.isAuthenticated() + return !this.destroyed && connection.isAlive() } /** diff --git a/src/lib/camera/webrtc/WebRTCEngine.spec.ts b/src/lib/camera/webrtc/WebRTCEngine.spec.ts index 981a0aa2c..dcc8d97ba 100644 --- a/src/lib/camera/webrtc/WebRTCEngine.spec.ts +++ b/src/lib/camera/webrtc/WebRTCEngine.spec.ts @@ -405,8 +405,8 @@ function streamOf(delegate: ScriptedDelegate, tierId: number): TierStream { return call[0] } -// The fixture's sensor with its audio shared and the tier of the identifier given marked recorded, its tier set built by the options boundary, which -// chooses its sound tier. +// The fixture's sensor with its audio shared, recorded on the tier of the identifier given through the recording option, its tier set built by the +// options boundary, which chooses its sound tier. function sharedTiers(recordedTierId: number): SensorStreamTiers { const sensor: CameraVideoSensor = { audio: { bitrate: 32, source: 'shared' }, @@ -418,7 +418,6 @@ function sharedTiers(recordedTierId: number): SensorStreamTiers { height, id: identifier, quality, - recorded: identifier === recordedTierId, width, })), uuid: SENSOR_UUID, @@ -430,7 +429,7 @@ function sharedTiers(recordedTierId: number): SensorStreamTiers { }, } - return validateVideoSensors([sensor], streaming, false).tierSets[0] + return validateVideoSensors([sensor], streaming, false, { tierId: recordedTierId }).tierSets[0] } // Each frame the picture stream of a video tier was handed, in the order handed: its time in milliseconds and the timestamp it was handed at, whole, read @@ -1531,7 +1530,7 @@ describe('webRTCEngine', () => { await end(offerRequest) }) - it('takes a view\'s sound from the sound tier of a shared sensor marked recorded on a tier that is not its best, and none from the best tier\'s Opus, ' + it('takes a view\'s sound from the sound tier of a shared sensor recorded on a tier that is not its best, and none from the best tier\'s Opus, ' + 'which the best tier\'s stream reads as none', async () => { const tiers = sharedTiers(2) const { delegate, end, offer, offerRequest, peer, sent, ssrcs, table } = await sending({ tiers }) @@ -1977,7 +1976,7 @@ describe('webRTCEngine', () => { // The library holds tier 2, whose stream releases a keyframe and a picture before the session connects. The session's picture stream of tier 2 // joins with an opening from that keyframe. Each frame written falls due as it arrives. - table.hold(table.videoTiers.get(2)!, rowHolder()) + table.hold(table.videoTiers.get(2)!, rowHolder(), 'recording') await vi.advanceTimersByTimeAsync(0) const stream = streamOf(delegate, 2) @@ -2162,7 +2161,7 @@ describe('webRTCEngine', () => { toFake: ['setTimeout', 'clearTimeout', 'performance'], }) fakeTimeoutSignals() - table.hold(table.videoTiers.get(2)!, rowHolder()) + table.hold(table.videoTiers.get(2)!, rowHolder(), 'recording') await vi.advanceTimersByTimeAsync(0) const stream = streamOf(delegate, 2) @@ -2310,7 +2309,7 @@ describe('webRTCEngine', () => { fakeTimeoutSignals() // The library holds tier 3, whose start never settles, and leaves it at 10 seconds. The session's join at 20 seconds takes the demand back. - const held = table.hold(table.videoTiers.get(3)!, rowHolder()) + const held = table.hold(table.videoTiers.get(3)!, rowHolder(), 'recording') await vi.advanceTimersByTimeAsync(10000) held.release() diff --git a/src/lib/controller/CameraController.characterization.spec.ts b/src/lib/controller/CameraController.characterization.spec.ts index 0987683b1..51a06890b 100644 --- a/src/lib/controller/CameraController.characterization.spec.ts +++ b/src/lib/controller/CameraController.characterization.spec.ts @@ -1790,7 +1790,7 @@ describe('camera controller characterization', () => { expect(error.mock.calls).toEqual([]) }) - it('logs a delegate that rejects at a stream preparation', async () => { + it('answers and logs a delegate that rejects at a stream preparation', async () => { const delegate = new MockDelegate() delegate.prepareStream = rejectsWith('The delegate failed to prepare the stream.') const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) @@ -1807,17 +1807,22 @@ describe('camera controller characterization', () => { expect.stringContaining('CameraStreamingDelegate failed to prepare a stream: Error: The delegate failed to prepare the stream.'), ], ]) - expect(callback).not.toHaveBeenCalled() + expect(callback).toHaveBeenCalledTimes(1) + expect(callback.mock.calls[0][0]).toEqual(new Error('The delegate failed to prepare the stream.')) + // The stream is free again, its status 0 being StreamingStatus.AVAILABLE. + expect(stream.streamStatus).toBe(0) }) - it('logs a delegate that rejects at a stream request that ends a session', async () => { + it('answers and logs a delegate that rejects at a stream request that ends a session', async () => { const delegate = new MockDelegate() delegate.handleStreamRequest = rejectsWith('The delegate failed to stop the stream.') const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) const stream = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)).streamManagements[0] stream.sessionIdentifier = SESSION_ID - void stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleSetRequest(END_SESSION) + await expect(stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleSetRequest(END_SESSION)) + .rejects + .toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) await settle() expect(unhandled).toEqual([]) @@ -1840,7 +1845,11 @@ describe('camera controller characterization', () => { await settle() expect(unhandled).toEqual([]) - expect(error.mock.calls).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to handle a stop stream request: Error: Unsupported!'), + ], + ]) expect(stream.sessionIdentifier).toBeUndefined() }) diff --git a/src/lib/controller/CameraController.spec.ts b/src/lib/controller/CameraController.spec.ts index c648f1e7d..ee192f897 100644 --- a/src/lib/controller/CameraController.spec.ts +++ b/src/lib/controller/CameraController.spec.ts @@ -4,12 +4,19 @@ import type { SerializedAccessory } from '../Accessory.js' import type { CameraReporter } from '../camera/diagnostics/CameraReporter.js' import type { CameraProblem } from '../camera/diagnostics/problems.js' import type { OperatingModeChange, OperatingModePolicy, StreamingEnabledChange } from '../camera/OperatingModePolicy.js' +import type { BufferRecorder, RecordingAdmission } from '../camera/recording/BufferRecorder.js' import type { ServedRecording, ServedRecordings } from '../camera/recording/ServedRecording.js' import type { MultiTierStreamingDelegate, TalkbackSink, TierStream } from '../camera/StreamingOptions.js' import type { CharacteristicChange, CharacteristicProps } from '../Characteristic.js' import type { RecordingProvisioningEntry } from '../model/RecordingProvisioning.js' import type { HAPConnection } from '../util/eventedhttp.js' -import type { CameraControllerOptions, CameraControllerServiceMap, CameraControllerState } from './index.js' +import type { + CameraBufferRecordingOptions, + CameraControllerOptions, + CameraControllerServiceMap, + CameraControllerState, + CameraSnapshotRefusal, +} from './index.js' import { Buffer } from 'node:buffer' import { generateKeyPairSync } from 'node:crypto' @@ -850,6 +857,26 @@ describe('CameraController', () => { ).rejects.toEqual(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) } }) + + it('should answer each snapshot the legacy gate refuses as it does with no listener, and tell a listener of the snapshot-refused event nothing', async () => { + const listener = vi.fn() + controller.on(CameraControllerEvents.SNAPSHOT_REFUSED, listener) + controller.recordingManagement!.operatingModeService.setCharacteristic(Characteristic.EventSnapshotsActive, false) + + await expect(controller.handleSnapshotRequest(100, 100, 'SomeAccessory', undefined)).rejects.toEqual(HAPStatus.INSUFFICIENT_PRIVILEGES) + await expect(controller.handleSnapshotRequest(100, 100, 'SomeAccessory', ResourceRequestReason.EVENT)).rejects.toEqual(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + + controller.recordingManagement!.operatingModeService.setCharacteristic(Characteristic.HomeKitCameraActive, false) + + await expect(controller.handleSnapshotRequest(100, 100, 'SomeAccessory', ResourceRequestReason.PERIODIC)).rejects.toEqual(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + + for (const management of controller.streamManagements) { + management.service.setCharacteristic(Characteristic.Active, false) + } + + await expect(controller.handleSnapshotRequest(100, 100, 'SomeAccessory', ResourceRequestReason.PERIODIC)).rejects.toEqual(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(listener).not.toHaveBeenCalled() + }) }) describe('serialization', () => { @@ -1771,8 +1798,8 @@ describe('CameraController', () => { } } - it('throws a TypeError naming the rule for a top-level recording option beside the block, with the block\'s own and without it, and a prebuffer ' - + 'that is not a whole number from 0 to 30000', () => { + it('throws a TypeError naming the rule for a top-level recording option beside the block, with the block\'s own and without it, a prebuffer of 0 ' + + 'and a prebuffer that is not a whole number from 1 to 30000', () => { const block = bufferCamera().options.cameraCapabilities const { recording } = createCameraControllerOptions() @@ -1785,9 +1812,14 @@ describe('CameraController', () => { })).toThrow(new TypeError('A camera with the camera capabilities block records from its camera buffer and takes no top-level recording option.')) } + expect(() => new CameraController(bufferCamera({ prebuffer: 0 }).options)).toThrow(new TypeError( + 'The prebuffer of the camera capabilities block\'s recording option is 0, but a prebuffered recording reaches back at least 1 millisecond: a camera ' + + 'that keeps no prebuffer states the mode \'onDemand\'.', + )) + for (const prebuffer of [-1, 1.5, 30001]) { expect(() => new CameraController(bufferCamera({ prebuffer }).options)).toThrow(new TypeError( - `The prebuffer of the camera capabilities block's recording option, ${prebuffer}, is not a whole number of milliseconds from 0 to 30000.`, + `The prebuffer of the camera capabilities block's recording option, ${prebuffer}, is not a whole number of milliseconds from 1 to 30000.`, )) } }) @@ -1838,45 +1870,187 @@ describe('CameraController', () => { expect(() => camera(bufferCamera().options)).not.toThrow() // @ts-expect-error: private access - expect(reordered.bufferRecording).toEqual({ prebuffer: 5000, sensorUUID: SENSOR_UUID, tierId: 1 }) + expect(reordered.bufferRecording).toEqual({ + mode: 'prebuffered', + prebuffer: 5000, + sensorUUID: SENSOR_UUID, + tierId: 1, + }) }) - it('records the tier its entry marks recorded, the second sensor\'s tier 2, holding that tier while recording is allowed', async () => { - const options = bufferCamera({ prebuffer: 0 }).options - const { delegate } = options.cameraCapabilities.streaming - const marked = camera({ + it('records the sensor and tier its recording option names, the second sensor named in uppercase and its tier 2, holding that tier while recording ' + + 'is allowed and settling recorded on that tier\'s entry alone', async () => { + const { delegate, options } = bufferCamera({ + sensorUUID: SECOND_VIDEO_SENSOR.uuid.toUpperCase(), + tierId: 2, + }) + const named = camera(options) + const second = SECOND_VIDEO_SENSOR.uuid.toLowerCase() + + named.constructServices() + named.configureServices() + handPublishedContext(named) + named.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + await settle() + + // @ts-expect-error: private access + expect(named.bufferRecording).toEqual({ + mode: 'prebuffered', + prebuffer: 5000, + sensorUUID: second, + tierId: 2, + }) + expect(streamsOf(delegate).map(({ tier }) => [tier.sensorUUID, tier.id])).toEqual([ + [ + second, + 2, + ], + ]) + // @ts-expect-error: private access + const settled: TierStream['tier'][] = named.sensorStreamTiers().flatMap(({ tiers }) => Array.from(tiers.values())) + + expect(settled.filter(({ recorded }) => recorded).map(({ id, sensorUUID }) => [sensorUUID, id])).toEqual([ + [ + second, + 2, + ], + ]) + }) + + it('records the first sensor\'s tier its option names by tierId alone, and the best tier of the sensor it names by sensorUUID alone, that sensor\'s ' + + 'tiers stated smallest first', () => { + const { options } = bufferCamera({ sensorUUID: SECOND_VIDEO_SENSOR.uuid }) + const block = options.cameraCapabilities + const reordered = camera({ ...options, cameraCapabilities: { - ...options.cameraCapabilities, - videoSensors: options.cameraCapabilities.videoSensors.map((sensor, index) => index === 1 + ...block, + videoSensors: block.videoSensors.map((sensor, index) => index === 1 ? { ...sensor, - tiers: sensor.tiers.map(tier => ({ ...tier, recorded: tier.id === 2 })), + tiers: [...sensor.tiers].reverse(), } : sensor), }, }) - marked.constructServices() - marked.configureServices() - handPublishedContext(marked) - marked.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) - await settle() - // @ts-expect-error: private access - expect(marked.bufferRecording).toEqual({ - prebuffer: 0, + expect(camera(bufferCamera({ tierId: 3 }).options).bufferRecording).toEqual({ + mode: 'prebuffered', + prebuffer: 5000, + sensorUUID: SENSOR_UUID, + tierId: 3, + }) + // @ts-expect-error: private access + expect(reordered.bufferRecording).toEqual({ + mode: 'prebuffered', + prebuffer: 5000, sensorUUID: SECOND_VIDEO_SENSOR.uuid.toLowerCase(), - tierId: 2, + tierId: 1, }) - expect(streamsOf(delegate).map(({ tier }) => [tier.sensorUUID, tier.id])).toEqual([ + }) + + it('throws a TypeError naming the rule for a recording option that is not an object, a sensor the block does not list and a tier that sensor does ' + + 'not list', () => { + const refusals: [unknown, string][] = [ + [null, 'The recording option of the camera capabilities block is not an object.'], + [5000, 'The recording option of the camera capabilities block is not an object.'], [ - SECOND_VIDEO_SENSOR.uuid.toLowerCase(), - 2, + { sensorUUID: 'E3000003-0000-4000-8000-000000000003' }, + 'The recording option of the camera capabilities block names the video sensor "e3000003-0000-4000-8000-000000000003", which the block does not list.', ], - ]) + [ + { sensorUUID: 7 }, + 'The recording option of the camera capabilities block names the video sensor "7", which the block does not list.', + ], + [ + { tierId: 9 }, + `The recording option of the camera capabilities block names the tier 9 of the video sensor "${SENSOR_UUID}", which that sensor does not list.`, + ], + [ + { sensorUUID: SECOND_VIDEO_SENSOR.uuid, tierId: '1' }, + `The recording option of the camera capabilities block names the tier "1" of the video sensor "${SECOND_VIDEO_SENSOR.uuid.toLowerCase()}", ` + + 'which that sensor does not list.', + ], + ] + + for (const [recording, sentence] of refusals) { + expect(() => new CameraController(bufferCamera(recording as CameraBufferRecordingOptions).options)).toThrow(new TypeError(sentence)) + } + }) + + it('throws a TypeError naming the rule for a mode that is neither value, a prebuffer beside the mode onDemand and a prebuffer of 0, constructs a camera ' + + 'in either mode, and settles the on-demand mode at a prebuffer of 0', () => { + const prebuffered = new TypeError('The prebuffer of the camera capabilities block\'s recording option is 0, but a prebuffered recording reaches back ' + + 'at least 1 millisecond: a camera that keeps no prebuffer states the mode \'onDemand\'.') + const beside = new TypeError('The recording option of the camera capabilities block states a prebuffer beside the mode \'onDemand\', which keeps ' + + 'none.') + + expect(() => camera(bufferCamera({ + // @ts-expect-error The types refuse a mode that is neither value, which an untyped caller can still give. + mode: 'later', + }).options)).toThrow(new TypeError('The mode of the camera capabilities block\'s recording option, later, is neither \'prebuffered\' nor ' + + '\'onDemand\'.')) + expect(() => camera(bufferCamera({ + mode: 'onDemand', + // @ts-expect-error The types refuse a prebuffer beside the mode 'onDemand', which an untyped caller can still give. + prebuffer: 5000, + }).options)).toThrow(beside) + expect(() => camera(bufferCamera({ + mode: 'onDemand', + // @ts-expect-error The types refuse a prebuffer beside the mode 'onDemand', which is refused before a prebuffer of 0 is read. + prebuffer: 0, + }).options)).toThrow(beside) + expect(() => camera(bufferCamera({ mode: 'prebuffered', prebuffer: 0 }).options)).toThrow(prebuffered) + expect(() => camera(bufferCamera({ mode: 'prebuffered', prebuffer: 30001 }).options)).toThrow(new TypeError('The prebuffer of the camera ' + + 'capabilities block\'s recording option, 30001, is not a whole number of milliseconds from 1 to 30000.')) + expect(() => camera(bufferCamera({ mode: 'prebuffered', prebuffer: 5000 }).options)).not.toThrow() + expect(() => camera(bufferCamera({ prebuffer: 5000 }).options)).not.toThrow() + expect(() => camera(bufferCamera({ + mode: 'onDemand', + // @ts-expect-error The types refuse a prebuffer beside the mode 'onDemand', even undefined, which an untyped caller reads as none given. + prebuffer: undefined, + }).options)).not.toThrow() + // @ts-expect-error: private access + expect(camera(bufferCamera({ mode: 'onDemand' }).options).bufferRecording).toEqual({ + mode: 'onDemand', + prebuffer: 0, + sensorUUID: SENSOR_UUID, + tierId: 1, + }) }) + it('hands the snapshot function no keyframe of an on-demand camera before any open, and the keyframe of its recording\'s stream while it runs', + async () => { + const { delegate, options } = bufferCamera({ mode: 'onDemand' }) + const made = camera(options) + const snapshot = vi.mocked(options.cameraCapabilities.snapshot) + + made.constructServices() + made.configureServices() + handPublishedContext(made) + made.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + await made.handleSnapshotRequest(360, 640, 'Camera') + + const admission = (made.recordingManagement!.delegate as BufferRecorder).admit(1) as Extract + + void admission.serve() + await settle() + + const stream = streamsOf(delegate)[0] + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(tierStreamFragment({ + picture: [ + tierPicture({ keyframe: true }), + ], + pictureTime: 0n, + })) + await made.handleSnapshotRequest(360, 640, 'Camera') + + expect(snapshot.mock.calls.map(([request]) => request.keyframe !== undefined)).toEqual([false, true]) + }) + it('reaches nothing a configure advertises, holds or calls from a change to the plugin\'s entries after construction', async () => { const zones = motionZonesFunction() const later = motionZonesFunction() @@ -2060,7 +2234,7 @@ describe('CameraController', () => { it('raises no kept tier and no recorded tier while its accessory is not published, recording and streaming on, leaving each multi-tier status active ' + 'on, and raises each once its accessory is published', async () => { - const { delegate, options } = bufferCamera({ prebuffer: 0 }) + const { delegate, options } = bufferCamera({ prebuffer: 1 }) const made = camera({ ...options, cameraCapabilities: { @@ -2203,10 +2377,10 @@ describe('CameraController', () => { }) describe('its source\'s state', () => { - // The two-sensor camera with its first sensor's tier 2 marked keepRunning, recording its first sensor's tier 1 with no prebuffer, and an accessory - // for it, which the row configures it on, its delegate's starts read by their tiers. + // The two-sensor camera with its first sensor's tier 2 marked keepRunning, recording its first sensor's tier 1 at a prebuffer of 1 millisecond, and + // an accessory for it, which the row configures it on, its delegate's starts read by their tiers. function keptCamera(): { accessory: Accessory, made: CameraController, starts: () => number[] } { - const { delegate, options } = bufferCamera({ prebuffer: 0 }) + const { delegate, options } = bufferCamera({ prebuffer: 1 }) const made = camera({ ...options, cameraCapabilities: { @@ -2438,7 +2612,7 @@ describe('CameraController', () => { it('raises no kept tier after a start that states its source away, that tier\'s stream ending with no alert and no warning, and raises each kept ' + 'tier once its source is stated available', async () => { - const { delegate, options } = bufferCamera({ prebuffer: 0 }) + const { delegate, options } = bufferCamera({ prebuffer: 1 }) const made = camera({ ...options, cameraCapabilities: { @@ -2841,11 +3015,83 @@ describe('CameraController', () => { expect([held, ends().length, withdraw.mock.calls.length]).toEqual([2, 2, 2]) expect(release.mock.calls.map(([reason], index) => [reason, release.mock.invocationCallOrder[index] < firstWithdrawal])).toEqual([ ['recording', true], - ['kept-running', true], - ['kept-running', true], - ['kept-running', true], + ['keepRunning', true], + ['keepRunning', true], + ['keepRunning', true], ]) }) + + /* The camera recording the first sensor's tier 1 in the prebuffered mode, at the prebuffer the option gives, that tier marked keepRunning where the + * row says, on the fake clock, constructed, configured and handed a published context, recording allowed before that context where the row says: the + * reason each start of the recorded tier read, in the order of the starts, the latest start's stream, and the write that allows recording. + */ + function recordedTier(recording: CameraBufferRecordingOptions, { allowFirst = false, marked = false }: { allowFirst?: boolean, marked?: boolean }): { + readonly allow: () => void + readonly camera: CameraController + readonly reasons: () => string[] + readonly stream: () => TierStream + } { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + onTestFinished(() => { + vi.useRealTimers() + }) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { delegate, options } = bufferCamera(recording) + const [recordedSensor] = options.cameraCapabilities.videoSensors + + recordedSensor.tiers = recordedSensor.tiers.map(tier => ({ ...tier, keepRunning: marked && (tier.id === 1) })) + + const made = camera(options) + const starts = (): TierStream[] => streamsOf(delegate, 1).filter(({ tier }) => tier.sensorUUID === SENSOR_UUID) + const allow = (): void => { + made.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + } + + made.constructServices() + made.configureServices() + + if (allowFirst) { + allow() + } + + handPublishedContext(made) + + return { + allow, + camera: made, + reasons: () => starts().map(({ reason }) => reason), + stream: () => starts().at(-1)!, + } + } + + it('states keepRunning for a prebuffered camera\'s recorded tier marked keepRunning at the start its context makes, at its join after a failure and ' + + 'at its join after a factory reset', async () => { + const held = recordedTier({ prebuffer: 2000 }, { allowFirst: true, marked: true }) + + await vi.advanceTimersByTimeAsync(0) + held.stream().fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + held.camera.handleFactoryReset() + await vi.advanceTimersByTimeAsync(0) + + expect(held.reasons()).toEqual(['keepRunning', 'keepRunning', 'keepRunning']) + }) + + it('states keepRunning for a prebuffered camera\'s recorded tier left unmarked at the start allowing recording makes and at its join after a failure', + async () => { + const held = recordedTier({}, {}) + + await vi.advanceTimersByTimeAsync(0) + held.allow() + await vi.advanceTimersByTimeAsync(0) + held.stream().fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + expect(held.reasons()).toEqual(['keepRunning', 'keepRunning']) + }) }) it('warns once of a stream past twice its tier\'s peak for a camera given strict, writing no debug line', async () => { @@ -3778,6 +4024,204 @@ describe('CameraController', () => { expect(signal.aborted).toBe(false) }) + + // A data stream open of a snapshot under each stream ID from 2, its metadata given, and the reason and status each answer carries once the opens settle. + async function opensAnswered(client: DataStreamClient, metadata: readonly Record[]): Promise<{ reason?: number, status?: number }[]> { + const ids = metadata.map((entry, index) => client.request(Protocols.DATA_SEND, Topics.OPEN, { + metadata: entry, + reason: 'snapshot', + streamId: index + 2, + target: 'controller', + type: 'ipcamera.snapshot', + })) + + await settle() + + return ids.map(id => client.answerTo(id)).map(written => ({ reason: written?.message.status, status: written?.header.status })) + } + + it.each([ + { + cause: 'not-allowed', + open: HDSProtocolSpecificErrorReason.NOT_ALLOWED, + status: HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE, + }, + { + cause: 'switched-off', + open: HDSProtocolSpecificErrorReason.NOT_ALLOWED, + status: HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE, + }, + { + cause: 'out-of-service', + open: HDSProtocolSpecificErrorReason.BUSY, + status: HAPStatus.SERVICE_COMMUNICATION_FAILURE, + }, + { + cause: 'size-refused', + open: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, + status: HAPStatus.INVALID_VALUE_IN_REQUEST, + }, + ] as const)('tells one snapshot-refused event of the cause $cause, with the request\'s reason where it names one, for each resource request and ' + + 'data stream open it refuses, answering each as it does with no listener and calling no snapshot function', async ({ cause, open, status }) => { + const { camera: made, map, snapshot } = snapshotting() + const refusals: CameraSnapshotRefusal[] = [] + const width = (cause === 'size-refused') + ? 0 + : 640 + + made.on(CameraControllerEvents.SNAPSHOT_REFUSED, refusal => refusals.push(refusal)) + + // Each arm makes its ground, the size's being the width of 0 its requests and opens name. + switch (cause) { + case 'not-allowed': { + map['cameraCapabilities:globalOperatingMode']!.updateCharacteristic(Characteristic.StreamingEnabled, false) + break + } + + case 'switched-off': { + made.recordingManagement!.operatingModeService.setCharacteristic(Characteristic.EventSnapshotsActive, false) + break + } + + case 'out-of-service': { + made.updateSourceState('away') + break + } + } + + for (const reason of [ResourceRequestReason.EVENT, undefined]) { + await expect(made.handleSnapshotRequest(360, width, 'Front Door', reason)).rejects.toBe(status) + } + + const client = await DataStreamClient.connect(made.recordingManagement!.dataStreamManagement) + + expect(await opensAnswered(client, [ + { imageHeight: 360, imageWidth: width, reason: ResourceRequestReason.EVENT }, + { imageHeight: 360, imageWidth: width }, + ])).toEqual([ + { reason: open, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + { reason: open, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + ]) + expect(snapshot).not.toHaveBeenCalled() + expect(refusals).toStrictEqual([ + { cause, reason: ResourceRequestReason.EVENT }, + { cause }, + { cause, reason: ResourceRequestReason.EVENT }, + { cause }, + ]) + }) + + it('tells no snapshot-refused event for a snapshot the gates let through, whether its function rejects, throws, answers or never settles, over a ' + + 'resource request and the data stream alike', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { camera: made, snapshot } = snapshotting() + const refusals: CameraSnapshotRefusal[] = [] + const settled: unknown[] = [] + + made.on(CameraControllerEvents.SNAPSHOT_REFUSED, refusal => refusals.push(refusal)) + snapshot.mockRejectedValueOnce(new Error('The camera has no picture.')) + snapshot.mockImplementationOnce(() => { + throw new Error('The camera is unreachable.') + }) + + for (const answer of [HAPStatus.SERVICE_COMMUNICATION_FAILURE, HAPStatus.SERVICE_COMMUNICATION_FAILURE]) { + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(answer) + } + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).resolves.toBe(MOCK_IMAGE) + + // Over the data stream, an open whose function rejects and one whose function answers. + const client = await DataStreamClient.connect(made.recordingManagement!.dataStreamManagement) + + snapshot.mockRejectedValueOnce(new Error('The camera has no picture.')) + + const opened = await opensAnswered(client, [ + { imageHeight: 360, imageWidth: 640, reason: ResourceRequestReason.EVENT }, + { imageHeight: 360, imageWidth: 640, reason: ResourceRequestReason.EVENT }, + ]) + + await settle() + + const closes = client.events(Protocols.DATA_SEND, Topics.CLOSE).map(({ reason, streamId }) => [streamId, reason]) + const sent = client.events(Protocols.DATA_SEND, Topics.DATA).map(({ streamId }) => streamId) + + // A function that never settles fails its resource request at its bound of 25 seconds. + snapshot.mockImplementationOnce(async () => await deferred().promise) + outcomes(made.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT), settled) + await vi.advanceTimersByTimeAsync(25000) + + expect([ + opened, + closes, + sent, + settled, + refusals, + ]).toEqual([ + [ + { reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }, + { reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }, + ], + [ + [2, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + ], + [3], + [HAPStatus.OPERATION_TIMED_OUT], + [], + ]) + expect(snapshot).toHaveBeenCalledTimes(6) + }) + + it('calls every listener of the snapshot-refused event in turn through the guard, a throw and a rejection each a plugin-failure problem of the ' + + 'camera\'s, and answers each refusal as it does with no listener', async () => { + const { problems } = problemsOf(NUMBERED_ACCESSORY_UUID) + const { camera: made, map, snapshot } = snapshotting() + const heard: string[] = [] + + made.on(CameraControllerEvents.SNAPSHOT_REFUSED, () => { + throw new Error('The listener failed.') + }) + made.on(CameraControllerEvents.SNAPSHOT_REFUSED, async () => { + throw new Error('The listener rejected.') + }) + made.on(CameraControllerEvents.SNAPSHOT_REFUSED, ({ cause }: CameraSnapshotRefusal) => heard.push(cause)) + map['cameraCapabilities:globalOperatingMode']!.updateCharacteristic(Characteristic.StreamingEnabled, false) + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + + const client = await DataStreamClient.connect(made.recordingManagement!.dataStreamManagement) + const opened = await opensAnswered(client, [ + { imageHeight: 360, imageWidth: 640, reason: ResourceRequestReason.EVENT }, + ]) + + await settle() + + expect([ + opened, + heard, + problems.map(({ kind, sentence }) => [ + kind, + sentence.startsWith('A listener of the camera controller\'s snapshot-refused event failed'), + ]), + snapshot.mock.calls.length, + ]).toEqual([ + [ + { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + ], + ['not-allowed', 'not-allowed'], + [ + ['plugin-failure', true], + ['plugin-failure', true], + ['plugin-failure', true], + ['plugin-failure', true], + ], + 0, + ]) + }) }) describe('its mutes', () => { diff --git a/src/lib/controller/CameraController.ts b/src/lib/controller/CameraController.ts index b7fba4411..09f91ec1d 100644 --- a/src/lib/controller/CameraController.ts +++ b/src/lib/controller/CameraController.ts @@ -223,9 +223,12 @@ function deserializeSlices(managements: ReadonlyMap(managements: ReadonlyMap boolean -} +} & ({ + /** + * The prebuffered mode, the default: the library keeps the recorded tier running while the user's switch allows recording and the camera is in + * service, and each recording reaches back the prebuffer. The camera controller's constructor throws a `TypeError` for a mode that is neither value. + */ + mode?: 'prebuffered' + /** + * How far back each recording reaches before a hub asks for it, in milliseconds, 5000 by default, in the prebuffered mode alone. A hub's recording is + * declined until the camera buffer holds this much of the tier. The camera controller's constructor throws a `TypeError` for a prebuffer of 0, naming + * the on-demand mode as the one for a camera that keeps no prebuffer, and for a value that is not a whole number from 1 to 30000. + */ + prebuffer?: number +} | { + /** + * The on-demand mode, for a camera that cannot keep its stream open: the library starts the recorded tier's stream at a hub's recording open and keeps + * it while a recording is open or Motion Detected reads raised, and each recording opens at the stream's first decodable keyframe, the first of its + * lead-up where the stream brings one, and carries that lead-up, the stream already running serving it at once. A camera has about 11 seconds from a + * hub's open to its first picture before the hub closes the recording with the reason TIMEOUT. The camera controller's constructor throws a `TypeError` + * for a `prebuffer` beside it, which the mode keeps none of. + */ + mode: 'onDemand' +}) /** * The options of a camera controller, in the form the camera capabilities block decides: a camera with the block takes @@ -409,14 +439,15 @@ export interface CameraControllerLegacyOptions { * none arrives. Every other line of its own is a debug event on the channel named exactly as its debug name, `HAP-NodeJS:Camera:Tier` among them, which * every camera shares: each event carries `accessoryUUID`, absent while the camera holds no accessory, `kind` and `sentence` by promise, and every field of * these events is promised too: `recording-ended` on `HAP-NodeJS:Camera:BufferRecorder` carries `dropped`, `outcome`, `seconds`, `segments`, `sensorUUID`, - * `streamId` and `tierId`, its `seconds` the length of the video in the segments it counts, the prebuffer among them, and `clip-finalized` on + * `streamId` and `tierId`, its `seconds` the length of the video in the segments it counts, the prebuffer among them where the camera keeps one, and + * `reason`, the reason a hub named as it closed the recording, present only where a hub's close ended it, and `clip-finalized` on * `HAP-NodeJS:Camera:CMAFRecording` carries `clipID`, `seconds` and `segments`, its `seconds` the durations its media playlist states for the segments it - * uploaded, summed. A sentence's wording is never a promise, and every other event's kind and details are free to change in any release. The library prints - * each event's sentence under the debug name it is published on, where the DEBUG setting named that name as the library loaded. A subscriber on such a - * channel is called inside the library's own work as each event is published, as {@link cameraProblemsChannel} states of a camera's problems channel: it - * must not call back into the camera, and a throw from it is an uncaught exception, which ends a Homebridge bridge. The recording management's lines that - * every camera writes, a recording stream's and those under `HAP-NodeJS:HKSV` among them, reach the console and the debug package as a camera without the - * block writes them. + * uploaded, summed. A sentence's wording is never a promise, and every other event's kind and details are free to change in any release. The library + * prints each event's sentence under the debug name it is published on, where the DEBUG setting named that name as the library loaded. A subscriber on + * such a channel is called inside the library's own work as each event is published, as {@link cameraProblemsChannel} states of a camera's problems + * channel: it must not call back into the camera, and a throw from it is an uncaught exception, which ends a Homebridge bridge. The recording + * management's lines that every camera writes, a recording stream's and those under `HAP-NodeJS:HKSV` among them, reach the console and the debug + * package as a camera without the block writes them. * * @group Camera */ @@ -457,8 +488,8 @@ export interface CameraCapabilitiesOptions { * is empty, an entry that is not an object, naming its index in this list, a sensor UUID that is not a UUID or that two sensors share, either naming * the sensor's index in this list, a sensor whose `tiers` is missing or empty, a sensor without `audio` or without `audio.bitrate`, a sensor without * `dimensions`, a `motionZones` that is not a function, a tier that is not an object, naming its index in `tiers`, two tiers of one sensor sharing an - * `id`, a `keepRunning` or a `recorded` that is not a boolean, a `peakBitrate` below its `bitrate`, more than one tier of the camera marked `recorded`, - * tiers the stream tier codec cannot encode and a configuration Camera Capabilities cannot encode. + * `id`, a `keepRunning` that is not a boolean, a `peakBitrate` below its `bitrate`, tiers the stream tier codec cannot encode and a configuration Camera + * Capabilities cannot encode. * * @example * A camera of one sensor, whose best tier runs while the user's switch allows streaming and the camera is in service, its accessory published and its @@ -475,7 +506,7 @@ export interface CameraCapabilitiesOptions { * intent: hap.CameraSensorIntent.MAIN, * motionZones: async (zones, reason, signal): Promise => detector.setZones(zones, { signal }), * tiers: [ - * { bitrate: 4500, frameRate: 30, height: 2160, id: 1, keepRunning: true, quality: hap.CameraVideoQuality.HIGH, recorded: true, width: 3840 }, + * { bitrate: 4500, frameRate: 30, height: 2160, id: 1, keepRunning: true, quality: hap.CameraVideoQuality.HIGH, 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 }, * ], @@ -562,14 +593,15 @@ export interface CameraCapabilitiesOptions { */ strict?: boolean /** - * The camera's recording from its camera buffer, in which the library builds every recording and the plugin builds no clip. While the user's switch - * allows recording and the camera is in service, its accessory published and its source not stated away, the library holds the recorded tier itself, - * through the multi-tier streaming delegate's `tierDemandStarted`, keeps its recent samples, and builds and serves each recording a hub asks for from - * them, its picture and, while Recording Audio Active is on, its sound. A recording asked for while the camera is out of service, or before the camera - * buffer holds the prebuffer, is declined, and so is one its `shouldRecord` answers false or whose call stopped the recorder, each decided once before - * the hub's open is answered and refused in that answer as busy. The controller tells of each recording through the `recording-started` and + * The camera's recording from its camera buffer, in which the library builds every recording and the plugin builds no clip. The library holds the + * recorded tier itself, through the multi-tier streaming delegate's `tierDemandStarted`, keeps its recent samples, and builds and serves each recording + * a hub asks for from them, its picture and, while Recording Audio Active is on, its sound: in the prebuffered mode while the user's switch allows + * recording and the camera is in service, its accessory published and its source not stated away, and in the on-demand mode from a hub's recording open + * while a recording is open or Motion Detected reads raised. A recording asked for while the camera is out of service, or in the prebuffered mode before + * the camera buffer holds the prebuffer, is declined, and so is one its `shouldRecord` answers false or whose call stopped the recorder, each decided + * once before the hub's open is answered and refused in that answer as busy. The controller tells of each recording through the `recording-started` and * `recording-ended` events, and raises the problems of the held tier and its buffer on the camera's channel. The camera controller's constructor throws - * a `TypeError` for a member its own documentation names. + * a `TypeError` for a `recording` that is not an object and for a member its own documentation names. */ recording?: CameraBufferRecordingOptions } @@ -607,7 +639,27 @@ export interface CameraStreamingDelegate { */ handleSnapshotRequest(request: SnapshotRequest, callback: SnapshotRequestCallback): void + /** + * This method is called when a HomeKit controller asks the camera to prepare a stream. The handler answers through the callback with its stream's + * ports, SSRCs and keys, or with an error. + * + * HAP-NodeJS waits for the callback until the controller's write has timed out, 9 seconds after the write, and then ends the session and calls + * {@link handleStreamRequest} with a STOP for it. A callback after that is still accepted, and a success is followed by a STOP for its session. A + * handler that throws, or an async handler whose returned promise rejects before it calls back, fails its prepare at once. + * + * @param request - Request containing the controller's addresses, ports and keys. + * @param callback - Callback supplied with the prepared stream, or with an error. + */ prepareStream(request: PrepareStreamRequest, callback: PrepareStreamCallback): void + /** + * This method is called when a HomeKit controller starts, reconfigures or ends a prepared stream, and with a STOP whenever HAP-NodeJS ends a session. + * + * A handler that throws, or an async handler whose returned promise rejects before it calls back, fails its request at once. At a start or a + * reconfigure, HAP-NodeJS then ends the session with a STOP. + * + * @param request - The start, reconfigure or stop request. + * @param callback - Callback answering the request, with an error where it failed. + */ handleStreamRequest(request: StreamingRequest, callback: StreamRequestCallback): void } @@ -632,14 +684,16 @@ export interface CameraStreamingDelegate { * The library records from its camera buffer, and your plugin builds no clip. Your plugin hands each video tier one fragmented MP4 stream of HEVC, * with Opus in every tier's stream, or in the sound's tier's alone where the sensor's audio states its `source` `'shared'`, through the `TierStream` * its multi-tier streaming delegate's `tierDemandStarted` is given. - * While the user's switch allows recording and the camera is in service, its accessory published and its source not stated away, the library holds - * the recorded tier itself and keeps its recent samples. It builds every recording a hub asks for from them: the picture, and the sound while - * Recording Audio Active is on. - * The recorded tier is the one its sensor's entry marks `recorded`, or with none marked the first sensor's tier with the most pixels, and the - * block's own `recording` option sets the `prebuffer`, 5000 milliseconds by default and 30000 at most. {@link CameraBufferRecordingOptions} states - * the formats Apple's guide requires of the recorded tier's stream, its bitrates and the cap on a segment. - * A recording a hub asks for while the camera is out of service, or before the camera buffer holds the prebuffer, is declined, and so is one the - * option's `shouldRecord` answers false or whose call stopped the recorder, each refused in the answer to the hub's open as busy. + * The library holds the recorded tier itself and keeps its recent samples, in the prebuffered mode while the user's switch allows recording and the + * camera is in service, its accessory published and its source not stated away, and in the on-demand mode from a hub's recording open. It builds + * every recording a hub asks for from them: the picture, and the sound while Recording Audio Active is on. + * The recorded tier is the one the block's own `recording` option names by its `sensorUUID` and `tierId`, by default the first sensor's tier with + * the most pixels, and that option states the `mode`, `'prebuffered'` by default, and in that mode the `prebuffer`, 5000 milliseconds by default and + * 30000 at most. {@link CameraBufferRecordingOptions} states the formats Apple's guide requires of the recorded tier's stream, its bitrates and the + * cap on a segment. + * A recording a hub asks for while the camera is out of service, or in the prebuffered mode before the camera buffer holds the prebuffer, is + * declined, and so is one the option's `shouldRecord` answers false or whose call stopped the recorder, each refused in the answer to the hub's open + * as busy. * A clip a hub uploads from a recording finishes with what that recording served when the camera's source is stated away. * The controller tells your plugin of each recording through its `recording-started` and `recording-ended` events, and raises the problems of the * held tier, its buffer and the recordings it serves on the camera's channel, which `onCameraProblem` subscribes to. @@ -890,8 +944,9 @@ export enum CameraControllerEvents { STREAMING_ENABLED_CHANGED = 'streaming-enabled-change', /** * Emitted with a {@link CameraRecordingStart} as a camera that records from its camera buffer begins to serve a hub's recording, and never for a - * recording it declines. Each listener is called in turn and the library waits on none: a throw or a rejection is a `plugin-failure` problem on the - * camera's channel and the next listener is still called. + * recording it declines: in the on-demand mode at the hub's open, before any segment and before the recorded tier's stream is asked for. Each listener + * is called in turn and the library waits on none: a throw or a rejection is a `plugin-failure` problem on the camera's channel and the next listener + * is still called. */ RECORDING_STARTED = 'recording-started', /** @@ -913,6 +968,14 @@ export enum CameraControllerEvents { * is a `plugin-failure` problem on the camera's channel and the next listener is still called. */ LIVE_VIEW_ENDED = 'live-view-ended', + /** + * Emitted once with a {@link CameraSnapshotRefusal} for each snapshot a hub asks of a camera with the camera capabilities block that the library refuses + * before its snapshot function is called, over the data stream and a resource request alike: while streaming is not allowed, while the user switched off + * the kind of snapshot the request's reason names, while the camera is out of service, and for a width or a height that is not a positive whole number. + * It is never emitted for a snapshot the library lets through, whatever the snapshot function then does. Each listener is called in turn and the library + * waits on none: a throw or a rejection is a `plugin-failure` problem on the camera's channel and the next listener is still called. + */ + SNAPSHOT_REFUSED = 'snapshot-refused', } /** @@ -946,9 +1009,10 @@ export interface CameraRecordingStart { * - `gap`: the recorded tier handed over no picture for the long-gap time of 10 seconds, or of 30 seconds from its source being stated reconnecting, * the recording ending after its segment in progress. * - `failed`: a track the recording carries changed its codec description, the recording ending after its segment in progress, a ceiling of the camera - * buffer trimmed past the segment in progress, the recording ending after its last whole segment, the recorder failed as it read the camera buffer, or - * the hub closed the recording for any other reason or its connection closed. A close of the segment in progress that fails at a changed description - * still ends the recording `failed`, without that segment, its failure raised as a `library-failure` problem. + * buffer trimmed past the segment in progress, the recording ending after its last whole segment, the recorder failed as it read the camera buffer, + * the hub closed the recording for any other reason, which {@link CameraRecordingEnd.reason} names, or its connection closed, or in the on-demand mode + * the recording still waited for its first keyframe 30 seconds after the hub's open. A close of the segment in progress that fails at a changed + * description still ends the recording `failed`, without that segment, its failure raised as a `library-failure` problem. * * @group Camera */ @@ -964,6 +1028,11 @@ export interface CameraRecordingEnd extends CameraRecordingStart { * How the recording ended. */ readonly outcome: CameraRecordingOutcome + /** + * The reason the hub named as it closed the recording, absent where its connection closed or the library ended it. A hub's close with the reason + * TIMEOUT also raises a `recording-timed-out` problem on the camera's channel. + */ + readonly reason?: HDSProtocolSpecificErrorReason /** * The media segments the recording sent, its initialization segment not counted. */ @@ -1002,6 +1071,27 @@ export type CameraLiveView = { readonly where: 'away' }) +/** + * A snapshot the library refused before the snapshot function was called, as the `snapshot-refused` event tells of it. + * + * @group Camera + */ +export interface CameraSnapshotRefusal { + /** + * Why the library refused the snapshot: + * + * - `not-allowed`: streaming is not allowed. + * - `switched-off`: the user switched off the kind of snapshot the request's reason names. + * - `out-of-service`: the camera is out of service. + * - `size-refused`: the request names a width or a height that is not a positive whole number. + */ + readonly cause: 'not-allowed' | 'out-of-service' | 'size-refused' | 'switched-off' + /** + * The reason the hub gave for the snapshot, as the snapshot function would have been handed it, absent where the hub gave none. + */ + readonly reason?: ResourceRequestReason +} + export declare interface CameraController { on(event: 'microphone-change', listener: (muted: boolean, volume: number) => void): this on(event: 'speaker-change', listener: (muted: boolean, volume: number) => void): this @@ -1011,6 +1101,7 @@ export declare interface CameraController { on(event: 'recording-ended', listener: (end: CameraRecordingEnd) => void): this on(event: 'live-view-started', listener: (view: CameraLiveView) => void): this on(event: 'live-view-ended', listener: (view: CameraLiveView) => void): this + on(event: 'snapshot-refused', listener: (refusal: CameraSnapshotRefusal) => void): this emit(event: 'microphone-change', muted: boolean, volume: number): boolean emit(event: 'speaker-change', muted: boolean, volume: number): boolean @@ -1020,6 +1111,7 @@ export declare interface CameraController { emit(event: 'recording-ended', end: CameraRecordingEnd): boolean emit(event: 'live-view-started', view: CameraLiveView): boolean emit(event: 'live-view-ended', view: CameraLiveView): boolean + emit(event: 'snapshot-refused', refusal: CameraSnapshotRefusal): boolean } /** @@ -1052,8 +1144,8 @@ export class CameraController extends EventEmitter implements SerializableContro /** * The recording of a camera with the camera capabilities block, from its camera buffer, kept for the controller's life as the recording options are: - * the recorded sensor in lowercase, the recorded tier, the prebuffer and the plugin's shouldRecord, each validated and settled when the controller is - * constructed. + * the mode, the prebuffer, 0 in the on-demand mode, the recorded sensor in lowercase, the recorded tier and the plugin's shouldRecord, each validated + * and settled when the controller is constructed. */ private readonly bufferRecording?: BufferRecording @@ -1062,10 +1154,17 @@ export class CameraController extends EventEmitter implements SerializableContro */ private bufferRecorder?: BufferRecorder + /** + * The Motion Detected the camera's one motion listener was added to at the configure, which the recorder reads in the on-demand mode as a recording + * ends: absent on a camera without the library's motion sensor, a doorbell with the block and none among them, which reads as no motion. + */ + private recordedMotion?: Characteristic + /** * The keepers of a camera that records from its camera buffer, made with each configuration's recording management, one for each video tier the - * library holds itself: every keeper, and those of the tiers marked `keepRunning`, which the controller raises while the user's switch allows streaming - * and the camera is in service, its accessory published and its source not stated away. + * library holds itself: every keeper, the recorded tier's among them, whose recording reason the recorder drives in every mode, and those of the + * tiers marked `keepRunning`, which the controller raises while the user's switch allows streaming and the camera is in service, its accessory + * published and its source not stated away. */ private keepers: { readonly every: readonly TierKeeper[], readonly listed: readonly TierKeeper[] } = { every: [], listed: [] } @@ -1251,7 +1350,7 @@ export class CameraController extends EventEmitter implements SerializableContro const capabilities = options.cameraCapabilities if (capabilities) { const strict = capabilities.strict ?? false - const sensors = validateVideoSensors(capabilities.videoSensors, capabilities.streaming, strict) + const sensors = validateVideoSensors(capabilities.videoSensors, capabilities.streaming, strict, capabilities.recording) if (typeof capabilities.snapshot !== 'function') { throw new TypeError('The camera capabilities block has no snapshot function, which answers every snapshot a hub asks for.') @@ -1424,11 +1523,12 @@ export class CameraController extends EventEmitter implements SerializableContro * width, height and age, for a snapshot a plugin takes on its own. Nothing is started for it: a tier that is not running keeps no keyframe, and a plugin * that wants a keyframe at every call marks a tier `keepRunning`. The movie's bytes are the library's, handed again while that keyframe is the newest. * A plugin reads them and never changes them. A tier whose newest keyframe lacks any of HEVC's video, sequence and picture parameter sets, in the - * keyframe and in its stream's description alike, answers none, and the next tier that runs answers in its place. + * keyframe and in its stream's description alike, answers none, and so does a tier whose newest keyframe is a recording's lead-up, and the next tier + * that runs answers in its place. * * @param sensorUUID - The video sensor's UUID, in any case, or none for the camera's first sensor. * @returns The keyframe, or `undefined` for a camera without the block, a sensor the camera does not have, a camera not configured and a sensor none of - * whose tiers runs with a newest keyframe a decoder can read. + * whose tiers runs with a newest keyframe a decoder can read that is no recording's lead-up. */ public latestKeyframe(sensorUUID?: string): CameraKeyframe | undefined { const sensor = sensorUUID?.toLowerCase() ?? this.sensorRegistry?.sensorUUIDs[0] @@ -1494,7 +1594,8 @@ export class CameraController extends EventEmitter implements SerializableContro * `cancelled`, an event of the recording stream and not of the clip, while the user's switches, an unpublish, a reset and a removal end every clip. The * source's state moves no motion or occupancy sensor's Status Active, which follows HomeKit Camera Active alone. A plugin shows a camera it cannot * reach in its own way. Stated available, the camera is in service again while its accessory is published, and each tier the library holds is raised at - * once. Stated recovering while away, the source is back. + * once: each tier marked keepRunning, and the recorded tier in the prebuffered mode, which the on-demand mode raises at a hub's next open. Stated + * recovering while away, the source is back. * * Stated recovering while not away, the source is reconnecting and its streams fall silent meanwhile: every tier whose stream is running is held through * the reconnect for up to 30 seconds, whoever holds it, a tier the library holds raising no `tier-stalled` problem, its views and an open recording @@ -2094,20 +2195,23 @@ export class CameraController extends EventEmitter implements SerializableContro const attribution = new MotionAttribution(motionService, sensorRegistry.sensorUUIDs, this.reporter!) this.motionAttribution = attribution - /* One listener takes each edge of Motion Detected, a report's and a direct write's alike, and hands it to every consumer of motion, the attribution - * and the HKSV3 recording management's event queue. No consumer listens on its own. The listener skips a write that leaves the value as it stands and is registered - * ahead of the service's own listener: the attribution writes its list before the service forwards the motion change. The ownership - * stack releases it at a removal. + /* One listener takes each edge of Motion Detected, a report's and a direct write's alike, and hands it to every consumer of motion, the attribution, + * the HKSV3 recording management's event queue and the recorder, whose on-demand hold also reads the value this characteristic holds. No consumer + * listens on its own. The listener skips a write that leaves the value as it stands and is registered ahead of the service's own listener: the + * attribution writes its list before the service forwards the motion change. The ownership stack releases it at a removal. */ const motionDetected = motionService.getCharacteristic(Characteristic.MotionDetected) const recordingManagement = this.cmafRecordingManagement + const recorder = this.bufferRecorder const motionChanged = ({ newValue, oldValue }: CharacteristicChange): void => { if (!!newValue !== !!oldValue) { attribution.motionChanged(!!newValue) recordingManagement?.motionChanged(!!newValue) + recorder?.motionChanged(!!newValue) } } + this.recordedMotion = motionDetected motionDetected.prependListener(CharacteristicEventTypes.CHANGE, motionChanged) this.ownership.defer(() => motionDetected.removeListener(CharacteristicEventTypes.CHANGE, motionChanged)) @@ -2155,17 +2259,18 @@ export class CameraController extends EventEmitter implements SerializableContro }, management.serviceKey) } - /* A camera that records from its camera buffer holds the recorded tier while the user's switch allows recording and the camera is in service, its - * accessory published and its source not stated away, and each tier marked keepRunning while the user's switch allows streaming and the camera is in - * service, from this configure on, the tier tables standing. The plugin's tierDemandStarted runs here for each tier a reason holds already, and - * otherwise once the camera is in service. + /* A camera that records from its camera buffer holds the recorded tier, in the prebuffered mode while the user's switch allows recording and the + * camera is in service, its accessory published and its source not stated away, and in the on-demand mode from a hub's open, and each tier marked + * keepRunning while the user's switch allows streaming and the camera is in service, from this configure on, the tier tables standing. The plugin's + * tierDemandStarted runs here for each tier a reason holds already, and otherwise once the camera is in service or, for the on-demand mode's recorded + * tier, at a hub's open. */ this.bufferRecorder?.configure() this.operatingMode.subscribeDerivation('streamingInService', () => this.keepRunning()) this.keepRunning() } - /* Raises or releases the kept-running reason of each listed tier's keeper, as streaming is allowed and the camera is in service or not: at a configure, + /* Raises or releases the keepRunning reason of each listed tier's keeper, as streaming is allowed and the camera is in service or not: at a configure, * at each move of the policy's streamingInService through the subscription on this configuration's policy, which handleControllerRemoved disposes, and * once a reset has run. A keeper's raise calls the plugin's tierDemandStarted in the same turn, and a release calls what a start registered, which means the * plugin can change whether the camera is in service inside such a call: a start that states its source away has the policy tell every subscriber, @@ -2175,9 +2280,9 @@ export class CameraController extends EventEmitter implements SerializableContro private keepRunning(): void { for (const keeper of this.keepers.listed) { if (this.operatingMode.streamingInService()) { - keeper.raise('kept-running') + keeper.raise('keepRunning') } else { - keeper.release('kept-running') + keeper.release('keepRunning') } } } @@ -2220,9 +2325,10 @@ export class CameraController extends EventEmitter implements SerializableContro /* The recording management reads the event triggers from the recording and sensor options the controller keeps. On a camera with the capabilities block * it takes the configuration's feed, which turns on the producer reference time box its recordings carry and serves those recordings to the HKSV3 * recording management's clips, and the recorder's decision it asks before it answers a recording open, and it answers the snapshots a hub asks over - * the data stream through this controller's snapshot gate, whose cause of a refusal it maps to its own reason, and its fetch. The feed goes on the - * ownership stack before that management: a removal drops the management first. The feed's `store-full` problem names the sensor the camera buffer - * records and goes through this configuration's reporter, as each failed call of that management's delegate does. + * the data stream through this controller's snapshot gate, whose cause of a refusal it maps to its own reason, its fetch, and the route that tells + * this controller's `snapshot-refused` event of a size the management refuses. The feed goes on the ownership stack before that management: a removal + * drops the management first. The feed's `store-full` problem names the sensor the camera buffer records and goes through this configuration's + * reporter, as each failed call of that management's delegate does. */ private createRecordingManagement( delegate: CameraRecordingDelegate, @@ -2242,6 +2348,7 @@ export class CameraController extends EventEmitter implements SerializableContro snapshot: { refusal: (reason: ResourceRequestReason | undefined): SnapshotRefusal | undefined => this.snapshotGate(this.reporter!.name, reason), fetch: async (request: SnapshotFetch): Promise => await this.fetchSnapshot(request), + sizeRefused: (reason: ResourceRequestReason | undefined): void => this.snapshotRefused('size-refused', reason), }, } const management = new RecordingManagement(options, delegate, this.retrieveEventTriggerOptions(), services, this.operatingMode, capabilities) @@ -2253,11 +2360,13 @@ export class CameraController extends EventEmitter implements SerializableContro /* A camera with the camera capabilities block records from its camera buffer: its recording management takes the recorder as its delegate, whose * decision on each open it asks before it answers the open, and no legacy options. The keepers and the recorder are this configuration's, the keepers * and the recorder going on the ownership stack after the management: a removal drops them first. A video tier the library holds has one keeper, - * whatever reasons stand: the recorded tier, whose recording reason the recorder drives, and each tier marked keepRunning, whose kept-running reason the - * controller drives, a marked recorded tier taking the recorded tier's keeper, which means it raises one demand and one set of problems and spans the prebuffer - * while its recording reason stands. Each keeper and the recorder reach a tier's buffer through the sensor's tier table, by a lookup, since the tables - * are built after the recording reconciler, and the recorded tier's keeper alone tells this configuration's recorder of a long gap. Every problem goes - * through this configuration's reporter and every recording event through the guarded dispatch. + * whatever reasons stand: the recorded tier, whose recording reason the recorder drives in every mode, and each tier marked keepRunning, whose + * keepRunning reason the controller drives, a recorded tier marked keepRunning taking the recorded tier's keeper, which means it raises one demand and + * one set of problems and spans the prebuffer while its recording reason stands, nothing in the on-demand mode, whose settled prebuffer is 0. Each + * keeper and the recorder reach a tier's buffer through the sensor's tier table, by a lookup, since the tables are built after the recording + * reconciler, and the recorded tier's keeper alone tells this configuration's recorder of a long gap, and the recorder reads the Motion Detected the + * configure's one listener was added to. Every problem goes through this configuration's reporter and every recording event through the guarded + * dispatch. */ private createBufferRecordingManagement(recording: BufferRecording, services?: RecordingManagementServices): RecordingManagement { const reporter = this.reporter! @@ -2292,6 +2401,7 @@ export class CameraController extends EventEmitter implements SerializableContro ...recording, ended: end => dispatchEvent(this, CameraControllerEvents.RECORDING_ENDED, this.reporter, end), keeper, + motion: () => !!this.recordedMotion?.value, policy: this.operatingMode, reporter, started: start => dispatchEvent(this, CameraControllerEvents.RECORDING_STARTED, this.reporter, start), @@ -2568,6 +2678,7 @@ export class CameraController extends EventEmitter implements SerializableContro this.bufferRecorder = undefined this.keepers = { every: [], listed: [] } this.motionAttribution = undefined + this.recordedMotion = undefined this.microphoneService = undefined this.speakerService = undefined @@ -2642,10 +2753,10 @@ export class CameraController extends EventEmitter implements SerializableContro /* A cause of whether the camera is in service has changed, the camera in service before it as given. The policy recomputes every derivation, which as * the camera leaves service releases the keepers, ends the recording, ends the clips where recording stops being allowed or the accessory is * unpublished, and ends every session, in that order, a source stated away leaving each clip to finish, and as it returns raises each tier the library - * holds. Where the camera left service, every start still pending on any of its tables is then withdrawn with a debug event and no - * problem, since the plugin did nothing wrong: its signal aborts and what it registered is released at once. The sessions' ends began in the - * recompute's turn, which is why a view from away whose join waits on such a start finds its session ending and writes no refusal. A user's switch-off ends the - * sessions through the same derivations and withdraws nothing. + * holds, the recorded tier in the prebuffered mode alone, which the on-demand mode raises at a hub's next open. Where the camera left service, every + * start still pending on any of its tables is then withdrawn with a debug event and no problem, since the plugin did nothing wrong: its signal aborts + * and what it registered is released at once. The sessions' ends began in the recompute's turn, which is why a view from away whose join waits on such + * a start finds its session ending and writes no refusal. A user's switch-off ends the sessions through the same derivations and withdraws nothing. */ private serviceChanged(inService: boolean): void { this.operatingMode.serviceChanged() @@ -2663,12 +2774,12 @@ export class CameraController extends EventEmitter implements SerializableContro * @private */ handleFactoryReset(): void { - // The recorder ends an open recording as cancelled and releases its keeper's recording reason, and every keeper's kept-running reason is released, all - // first: the sessions' reset below withdraws no demand a keeper still waits on. + // The recorder ends an open recording, a waiting one among them, as cancelled and releases its keeper's recording reason in every mode, and every + // keeper's keepRunning reason is released, all first: the sessions' reset below withdraws no demand a keeper still waits on. this.bufferRecorder?.reset() for (const keeper of this.keepers.every) { - keeper.release('kept-running') + keeper.release('keepRunning') } for (const management of this.streamManagements) { @@ -2699,9 +2810,10 @@ export class CameraController extends EventEmitter implements SerializableContro this.operatingMode.reset() } - /* The reset tells the policy's listeners only of a value it moved. The kept-running reason is read again here, and a listed tier is held again while + /* The reset tells the policy's listeners only of a value it moved. The keepRunning reason is read again here, and a listed tier is held again while * the user's switch allows streaming and the camera is in service, its accessory published and its source not stated away, as at a configure. The - * recorded tier stays released, recording's default being off, and a keeper a removal closed raises nothing. + * recorded tier stays released, recording's default being off in the prebuffered mode and the on-demand mode raising it at a hub's open alone, and a + * keeper a removal closed raises nothing. */ this.keepRunning() @@ -2865,7 +2977,7 @@ export class CameraController extends EventEmitter implements SerializableContro } const refusal = this.snapshot - ? this.pictureSizeGate(height, width, accessoryName) + ? this.pictureSizeGate(height, width, accessoryName, reason) : this.legacySnapshotGate(accessoryName, reason) if (refusal !== undefined) { @@ -2884,7 +2996,7 @@ export class CameraController extends EventEmitter implements SerializableContro /* The one gate a snapshot over the data stream passes on a camera with the capabilities block, and the first gate a resource request's snapshot passes * there. It answers the cause of its refusal, which each path maps to a status of its own: not allowed while streaming is not allowed and then while the * user switched off the kind the request's reason names, the user's switches read first, and then out of service while the camera is out of service. - * The snapshot function is never called for a camera out of service. + * Each refusal is told as the `snapshot-refused` event before the gate answers it. The snapshot function is never called for a camera out of service. */ private snapshotGate(accessoryName?: string, reason?: ResourceRequestReason): SnapshotRefusal | undefined { if (!this.operatingMode.streamingAllowed()) { @@ -2892,6 +3004,7 @@ export class CameraController extends EventEmitter implements SerializableContro accessoryName, sentence: `[${accessoryName}] Rejecting snapshot as streaming is not allowed.`, })) + this.snapshotRefused('not-allowed', reason) return 'not allowed' } @@ -2903,6 +3016,7 @@ export class CameraController extends EventEmitter implements SerializableContro sentence: `[${accessoryName}] Rejecting snapshot as ${switchedOff} snapshots are switched off.`, switchedOff, })) + this.snapshotRefused('switched-off', reason) return 'not allowed' } @@ -2911,12 +3025,22 @@ export class CameraController extends EventEmitter implements SerializableContro accessoryName, sentence: `[${accessoryName}] Rejecting snapshot as the camera is out of service.`, })) + this.snapshotRefused('out-of-service', reason) return 'out of service' } return undefined } + // Tells the snapshot-refused event of a snapshot a gate refused before the snapshot function was called, with the request's reason where it names one. + private snapshotRefused(cause: CameraSnapshotRefusal['cause'], reason: ResourceRequestReason | undefined): void { + const named = (reason === undefined) + ? {} + : { reason } + + dispatchEvent(this, CameraControllerEvents.SNAPSHOT_REFUSED, this.reporter, { cause, ...named }) + } + /* The kind of snapshot the user switched off that a request's reason asks for, read as the legacy gate reads the switches: an event snapshot while Event * Snapshots Active is off, a periodic one while Periodic Snapshots Active is off, and one naming no reason while either is off. A reason that names * neither kind reads as none, as the data stream reads its request's reason. A request answers alike over a resource request and the data stream. @@ -2933,14 +3057,15 @@ export class CameraController extends EventEmitter implements SerializableContro return undefined } - // The size a resource request's snapshot names on a camera with the capabilities block, checked as the data stream's open checks it. The snapshot - // function is handed only a size a picture can have. - private pictureSizeGate(height: number, width: number, accessoryName?: string): HAPStatus | undefined { + // The size a resource request's snapshot names on a camera with the capabilities block, checked as the data stream's open checks it, a refusal told as + // the `snapshot-refused` event with the request's reason. The snapshot function is handed only a size a picture can have. + private pictureSizeGate(height: number, width: number, accessoryName?: string, reason?: ResourceRequestReason): HAPStatus | undefined { if (!isPictureSize(width, height)) { this.reporter!.debug(CONTROLLER_DEBUG, 'snapshot-size-refused', () => ({ accessoryName, sentence: `[${accessoryName}] Rejecting snapshot as it names no valid picture size.`, })) + this.snapshotRefused('size-refused', reason) return HAPStatus.INVALID_VALUE_IN_REQUEST } diff --git a/src/lib/controller/eventDispatch.ts b/src/lib/controller/eventDispatch.ts index 7d5e31e2a..f3c909b3d 100644 --- a/src/lib/controller/eventDispatch.ts +++ b/src/lib/controller/eventDispatch.ts @@ -2,13 +2,13 @@ import type { EventEmitter } from 'node:events' import type { CameraReporter } from '../camera/diagnostics/CameraReporter.js' -import { callDelegate } from '../util/promise-utils.js' +import { callListeners } from '../util/promise-utils.js' /** * Dispatches one of a camera controller's guarded events: nothing is awaited, and each listener is called in turn, in the order it was added, through the guard, which * means a throw or the rejection of a promise it returns is the listener's failure and the next listener is still called. A camera with the camera * capabilities block hands its reporter, through which each failure is the plugin's on the camera's channel, and a camera without the block hands none: - * `callDelegate` logs it. A listener added with `once` is heard once, since its wrapper takes it off before it runs. The library's own work never waits on + * `callListeners` logs it. A listener added with `once` is heard once, since its wrapper takes it off before it runs. The library's own work never waits on * a plugin's listener, and a listener's failure stops nothing. * @param emitter - The controller. * @param event - The event's name. @@ -16,14 +16,5 @@ import { callDelegate } from '../util/promise-utils.js' * @param args - The event's arguments. */ export function dispatchEvent(emitter: EventEmitter, event: string, reporter: CameraReporter | undefined, ...args: readonly unknown[]): void { - for (const listener of emitter.rawListeners(event)) { - const call = (): unknown => Reflect.apply(listener, emitter, args) - const failure = `A listener of the camera controller's ${event} event failed` - - if (reporter) { - reporter.guard('plugin-failure', call, failure) - } else { - callDelegate(call, failure) - } - } + callListeners(emitter, event, args, `A listener of the camera controller's ${event} event failed`, reporter?.sink('plugin-failure')) } diff --git a/src/lib/datastream/DataStreamManagement.spec.ts b/src/lib/datastream/DataStreamManagement.spec.ts index 0aa7737cc..e6df4a8d0 100644 --- a/src/lib/datastream/DataStreamManagement.spec.ts +++ b/src/lib/datastream/DataStreamManagement.spec.ts @@ -59,6 +59,22 @@ describe('DataStreamManagement', () => { await expect(setupCharacteristic(management).handleSetRequest(value, verifiedConnection())).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) }) + it('refuses a write whose TLV is cut short as an invalid value, with no characteristic warning and no session prepared', async () => { + const management = new DataStreamManagement() + const characteristic = setupCharacteristic(management) + const warning = vi.fn() + + characteristic.on(CharacteristicEventTypes.CHARACTERISTIC_WARNING, warning) + + // A type and a declared length, and no value after them. + await expect(characteristic.handleSetRequest(Buffer.from([0x01, 0x05, 0x00]).toString('base64'), verifiedConnection())) + .rejects + .toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(warning).not.toHaveBeenCalled() + // @ts-expect-error: private access + expect(management.dataStreamServer.preparedSessions).toHaveLength(0) + }) + it('refuses a write that comes from no HAP connection as an invalid value', async () => { const management = new DataStreamManagement() diff --git a/src/lib/datastream/DataStreamManagement.ts b/src/lib/datastream/DataStreamManagement.ts index 91bb8eef6..9813a3011 100644 --- a/src/lib/datastream/DataStreamManagement.ts +++ b/src/lib/datastream/DataStreamManagement.ts @@ -4,8 +4,12 @@ import type { DataStreamTransportManagement } from '../definitions/index.js' import type { HAPConnection } from '../util/eventedhttp.js' import type { DataStreamConnection, + DataStreamServerEvent, GlobalEventHandler, - GlobalRequestHandler, Protocols, Topics } from './DataStreamServer.js' + GlobalRequestHandler, + Protocols, + Topics, +} from './DataStreamServer.js' import { Buffer } from 'node:buffer' @@ -15,11 +19,9 @@ import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' import { HAPStatus } from '../HAPServer.js' import { Service } from '../Service.js' import { DisposableStack } from '../util/disposableStack.js' +import { errorMessage } from '../util/errors.js' import * as tlv from '../util/tlv.js' -import { - DataStreamServer, - DataStreamServerEvent, -} from './DataStreamServer.js' +import { DataStreamServer } from './DataStreamServer.js' const debug = createDebug('HAP-NodeJS:DataStream:Management') @@ -160,12 +162,7 @@ export class DataStreamManagement { * @param listener - the event handler */ onServerEvent(event: DataStreamServerEvent, listener: (connection: DataStreamConnection) => void): this { - // the server declares one overload per event, which a union of both events matches only once it is narrowed - if (event === DataStreamServerEvent.CONNECTION_OPENED) { - this.dataStreamServer.on(event, listener) - } else { - this.dataStreamServer.on(event, listener) - } + this.dataStreamServer.on(event, listener) return this } @@ -175,10 +172,17 @@ export class DataStreamManagement { return } - const data = Buffer.from(value, 'base64') - const objects = tlv.decode(data) + // A value whose TLV does not decode, like a value missing an entry (answered below), is a malformed write answered as an invalid request, not a throw + // which is logged as a bug of the plugin. + let objects: Record + try { + objects = tlv.decode(Buffer.from(value, 'base64')) + } catch (error) { + debug('Received a setup write whose TLV does not decode: %s', errorMessage(error)) + callback(HAPStatus.INVALID_VALUE_IN_REQUEST) + return + } - // a missing entry is a malformed write (answered below), not a TypeError which is logged as a bug of the plugin const sessionCommandType = objects[SetupDataStreamSessionTypes.SESSION_COMMAND_TYPE]?.[0] const transportType = objects[SetupDataStreamSessionTypes.TRANSPORT_TYPE]?.[0] const controllerKeySalt = objects[SetupDataStreamSessionTypes.CONTROLLER_KEY_SALT] diff --git a/src/lib/datastream/DataStreamServer.spec.ts b/src/lib/datastream/DataStreamServer.spec.ts index 01310488e..92f9ef1d2 100644 --- a/src/lib/datastream/DataStreamServer.spec.ts +++ b/src/lib/datastream/DataStreamServer.spec.ts @@ -23,7 +23,16 @@ import { } from '../../test-utils/dataStreamClient.js' import { HAPConnectionEvent } from '../util/eventedhttp.js' import { DataStreamManagement } from './DataStreamManagement.js' -import { DataStreamServer, DataStreamServerEvent, HDSConnectionError, HDSConnectionErrorType, HDSStatus, Protocols, Topics } from './DataStreamServer.js' +import { + DataStreamServer, + DataStreamServerEvent, + HDSConnectionError, + HDSConnectionErrorType, + HDSProtocolSpecificErrorReason, + HDSStatus, + Protocols, + Topics, +} from './DataStreamServer.js' interface TestSession { server: DataStreamServer @@ -67,15 +76,6 @@ function identifiedSession(): TestSession { } describe('DataStreamServer', () => { - function hapConnection(): HAPConnection { - return { - sessionID: 'test-session', - encryption: { - sharedSecret: crypto.randomBytes(32), - }, - } as unknown as HAPConnection - } - beforeEach(() => { vi.useFakeTimers() }) @@ -92,8 +92,8 @@ describe('DataStreamServer', () => { const server = new DataStreamServer() const first = vi.fn() const second = vi.fn() - server.prepareSession(hapConnection(), crypto.randomBytes(32), first) - server.prepareSession(hapConnection(), crypto.randomBytes(32), second) + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), first) + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), second) const tcpServer = (server as any).tcpServer const error = new Error('listen EMFILE: too many open files') @@ -116,7 +116,7 @@ describe('DataStreamServer', () => { try { const server = new DataStreamServer() const session = await new Promise((resolve, reject) => { - server.prepareSession(hapConnection(), crypto.randomBytes(32), (error, prepared) => error + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), (error, prepared) => error ? reject(error) : resolve(prepared)) }) @@ -142,7 +142,7 @@ describe('DataStreamServer', () => { server.destroy() expect((server as any).state).toBe(4) // destroyed, although there is no tcp server which could report that it closed - server.prepareSession(hapConnection(), crypto.randomBytes(32), callback) + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), callback) expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The data stream server was destroyed.')) expect((server as any).tcpServer).toBeUndefined() @@ -174,8 +174,8 @@ describe('DataStreamServer', () => { const server = new DataStreamServer() const first = vi.fn() const second = vi.fn() - server.prepareSession(hapConnection(), crypto.randomBytes(32), first) - server.prepareSession(hapConnection(), crypto.randomBytes(32), second) + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), first) + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), second) const tcpServer = (server as any).tcpServer expect((server as any).state).toBe(1) // binding const closed = new Promise(resolve => tcpServer.once('close', resolve)) @@ -196,24 +196,33 @@ describe('DataStreamServer', () => { it('should answer a prepare still waiting on a closing server once with the destroyed error', async () => { const server = new DataStreamServer() - const callback = vi.fn() - server.prepareSession(hapConnection(), crypto.randomBytes(32), callback) + const first = vi.fn() + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), first) const tcpServer = (server as any).tcpServer const closed = new Promise(resolve => tcpServer.once('close', resolve)) - // The server binds (state 1) with the prepare waiting for its port. The prepared session's connect timer runs out before the server listens, and the - // server begins to close (state 3) with the prepare still unanswered. + // The server binds (state 1) with the first prepare waiting for its port. That session's connect timer runs out before the server listens, which + // answers it, and the server begins to close (state 3). expect((server as any).state).toBe(1) vi.advanceTimersByTime(10000) expect((server as any).state).toBe(3) + expect(first).toHaveBeenCalledExactlyOnceWith(new Error('The data stream session timed out before its controller connected.')) + + // A prepare made while the server closes waits for the next server, and the destroy answers it once at the destroy itself, before the closing + // server's close, and the server reads destroyed (state 4). + const callback = vi.fn() + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), callback) expect(callback).not.toHaveBeenCalled() - // The destroy answers the waiting prepare once, and the server reads destroyed (state 4). server.destroy() - await closed - expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The data stream server was destroyed.')) expect((server as any).state).toBe(4) + + // Nothing starts once the closing server closed. + await closed + vi.advanceTimersByTime(10) + expect((server as any).tcpServer).toBeUndefined() + expect(callback).toHaveBeenCalledTimes(1) }) }) @@ -228,7 +237,7 @@ describe('DataStreamServer', () => { ]) expect(() => socket.emit('data', junk)).not.toThrow() - expect(socket.end).toHaveBeenCalled() + expect(socket.destroy).toHaveBeenCalled() }) it('should accept a hello request from an identified connection', () => { @@ -371,31 +380,39 @@ describe('DataStreamServer', () => { const frame = encryptedFrame(session, messagePayload({ protocol: 'test', event: 'event' }, { data })) const chunkSize = 64 + // Every byte joined or copied into another buffer counts, whether through Buffer.concat or a buffer's own copy. let copiedBytes = 0 const realConcat = Buffer.concat + const realCopy = Buffer.prototype.copy const concatSpy = vi.spyOn(Buffer, 'concat').mockImplementation((list, totalLength) => { copiedBytes += list.reduce((sum, entry) => sum + entry.length, 0) return realConcat.call(Buffer, list, totalLength) }) + const copySpy = vi.spyOn(Buffer.prototype, 'copy').mockImplementation(function (this: Buffer, ...args: unknown[]) { + const copied = Reflect.apply(realCopy, this, args) as number + copiedBytes += copied + return copied + }) try { for (let offset = 0; offset < frame.length; offset += chunkSize) { session.socket.emit('data', frame.subarray(offset, offset + chunkSize)) } } finally { concatSpy.mockRestore() + copySpy.mockRestore() } expect(events).toHaveLength(1) expect(events[0].data.equals(data)).toBe(true) - // More than a thousand chunks: joining what is there on every chunk copies about 500 times the frame. - // The frame is joined once now. The rest of the allowance is for the copies of the decryption. + // More than a thousand chunks: growing the held bytes to each chunk's exact size, or joining them, copies about 500 times the frame. Grown by + // doubling, every byte is copied a few times at most, and the rest of the allowance is for the copies of the decryption. expect(copiedBytes).toBeLessThan(4 * frame.length) }) }) describe('closing', () => { it('should destroy a closed socket which the remote never closes', () => { - const { socket, connection } = setupSession() + const { socket, connection } = identifiedSession() connection.close() expect(socket.end).toHaveBeenCalledTimes(1) @@ -406,7 +423,7 @@ describe('DataStreamServer', () => { }) it('should not destroy a socket which the remote closed in time', () => { - const { socket, connection } = setupSession() + const { socket, connection } = identifiedSession() connection.close() socket.emit('close') @@ -414,6 +431,17 @@ describe('DataStreamServer', () => { vi.advanceTimersByTime(5000) expect(socket.destroy).not.toHaveBeenCalled() }) + + it('should leave the server\'s connections alone when a connection it does not hold closes', () => { + const { server, connection } = identifiedSession() + const stranger = setupSession().connection + + // @ts-expect-error: private method access + server.connectionClosed(stranger) + + // @ts-expect-error: private property access + expect(server.connections).toEqual([connection]) + }) }) describe('hello', () => { @@ -421,10 +449,10 @@ describe('DataStreamServer', () => { const { socket } = setupSession() vi.advanceTimersByTime(9999) - expect(socket.end).not.toHaveBeenCalled() + expect(socket.destroy).not.toHaveBeenCalled() vi.advanceTimersByTime(1) - expect(socket.end).toHaveBeenCalledTimes(1) + expect(socket.destroy).toHaveBeenCalledTimes(1) }) it('should stop the hello timer of a connection whose socket closed before its hello, which then writes and ends nothing', () => { @@ -456,24 +484,15 @@ describe('DataStreamServer', () => { vi.restoreAllMocks() }) - function hapConnection(): HAPConnection { - return Object.assign(new EventEmitter(), { - encryption: { - sharedSecret: crypto.randomBytes(32), - }, - sessionID: crypto.randomUUID(), - }) as unknown as HAPConnection - } - - function prepare(server: DataStreamServer): Mock { + function prepare(server: DataStreamServer, hapConnection: HAPConnection = verifiedConnection()): Mock { const callback = vi.fn() - server.prepareSession(hapConnection(), crypto.randomBytes(32), callback) + server.prepareSession(hapConnection, crypto.randomBytes(32), callback) return callback } // Prepares a session on a TCP server that binds, opens the server's one connection on it and identifies that connection by its hello. - function listeningSession(server: DataStreamServer): TestSession { - const callback = prepare(server) + function listeningSession(server: DataStreamServer, hapConnection: HAPConnection = verifiedConnection()): TestSession { + const callback = prepare(server, hapConnection) const tcpServer = tcpServers.at(-1)! tcpServer.emit('listening') @@ -574,7 +593,7 @@ describe('DataStreamServer', () => { const created = tcpServers.length const callback = vi.fn() - expect(() => server.prepareSession(hapConnection(), crypto.randomBytes(32), callback)).not.toThrow() + expect(() => server.prepareSession(verifiedConnection(), crypto.randomBytes(32), callback)).not.toThrow() expect(callback).toHaveBeenCalledExactlyOnceWith(expect.any(Error)) expect(server.preparedSessions).toHaveLength(0) expect(vi.getTimerCount()).toBe(0) @@ -629,6 +648,319 @@ describe('DataStreamServer', () => { tcpServers[1].emit('listening') expect(callback).toHaveBeenCalledExactlyOnceWith(undefined, expect.objectContaining({ port: FAKE_SERVER_PORT + 1 })) }) + + it('should answer a prepare whose TCP server never listens once with the timed-out error, and serve the next prepare on the next TCP server alone', () => { + const server = new DataStreamServer() + const callback = prepare(server) + + vi.advanceTimersByTime(9999) + expect(callback).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The data stream session timed out before its controller connected.')) + expect((server as any).pendingBinds).toHaveLength(0) + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + + tcpServers[0].emit('close') + const next = prepare(server) + tcpServers[1].emit('listening') + + expect(next).toHaveBeenCalledExactlyOnceWith(undefined, expect.objectContaining({ port: FAKE_SERVER_PORT })) + expect(callback).toHaveBeenCalledTimes(1) + }) + + it('should answer a prepare made while the TCP server closes once with the timed-out error, and start no TCP server once the old one closed', () => { + const server = new DataStreamServer() + const first = listeningSession(server) + + first.socket.emit('close') + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + + const callback = prepare(server) + vi.advanceTimersByTime(10000) + expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The data stream session timed out before its controller connected.')) + + tcpServers[0].emit('close') + vi.advanceTimersByTime(10) + + expect(tcpServers).toHaveLength(1) + expect(vi.getTimerCount()).toBe(0) + expect(callback).toHaveBeenCalledTimes(1) + }) + + it('should answer a prepare waiting for the restart and one made before it with the port of the one TCP server the later prepare started', () => { + const server = new DataStreamServer() + const first = listeningSession(server) + + first.socket.emit('close') + const waiting = prepare(server) + tcpServers[0].emit('close') + + // The first server's close arms the restart, and a prepare before the restart comes due starts a server at once, which the restart then leaves alone. + vi.advanceTimersByTime(5) + const later = prepare(server) + expect(tcpServers).toHaveLength(2) + + vi.advanceTimersByTime(5) + expect(tcpServers).toHaveLength(2) + + tcpServers[1].address.mockReturnValue({ address: '0.0.0.0', family: 'IPv4', port: FAKE_SERVER_PORT + 1 }) + tcpServers[1].emit('listening') + expect(waiting).toHaveBeenCalledExactlyOnceWith(undefined, expect.objectContaining({ port: FAKE_SERVER_PORT + 1 })) + expect(later).toHaveBeenCalledExactlyOnceWith(undefined, expect.objectContaining({ port: FAKE_SERVER_PORT + 1 })) + }) + + it('should refuse a prepare made from inside the destroyed answer of a waiting prepare at once, with the destroyed error', () => { + const server = new DataStreamServer() + const again = vi.fn() + + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), () => { + server.prepareSession(verifiedConnection(), crypto.randomBytes(32), again) + }) + server.destroy() + + expect(again).toHaveBeenCalledExactlyOnceWith(new Error('The data stream server was destroyed.')) + expect(server.preparedSessions).toHaveLength(0) + expect((server as any).pendingBinds).toHaveLength(0) + expect(vi.getTimerCount()).toBe(0) + }) + + it('should answer a prepare still waiting for the port once with the HAP-closed error when its HAP connection closes, and close the binding TCP server', () => { + const server = new DataStreamServer() + const hapConnection = verifiedConnection() + const listeners = hapConnection.listenerCount(HAPConnectionEvent.CLOSED) + const maxListeners = hapConnection.getMaxListeners() + const callback = prepare(server, hapConnection) + + expect(hapConnection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(listeners + 1) + expect(hapConnection.getMaxListeners()).toBe(maxListeners + 1) + + hapConnection.emit(HAPConnectionEvent.CLOSED) + + expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The HAP connection of the data stream session closed before its controller connected.')) + expect(server.preparedSessions).toHaveLength(0) + expect(vi.getTimerCount()).toBe(0) + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + }) + + it('should drop a session answered with its port when its HAP connection closes, answering it nothing more, and close the TCP server', () => { + const server = new DataStreamServer() + const hapConnection = verifiedConnection() + const callback = prepare(server, hapConnection) + + tcpServers[0].emit('listening') + expect(callback).toHaveBeenCalledExactlyOnceWith(undefined, expect.objectContaining({ port: FAKE_SERVER_PORT })) + + hapConnection.emit(HAPConnectionEvent.CLOSED) + + expect(callback).toHaveBeenCalledTimes(1) + expect(server.preparedSessions).toHaveLength(0) + expect(vi.getTimerCount()).toBe(0) + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + }) + + it('should destroy an unidentified connection at once when the last prepared session\'s HAP connection closes, and close the TCP server after its socket', () => { + const server = new DataStreamServer() + const hapConnection = verifiedConnection() + prepare(server, hapConnection) + tcpServers[0].emit('listening') + const socket = new FakeSocket() + tcpServers[0].emit('connection', socket) + + hapConnection.emit(HAPConnectionEvent.CLOSED) + + expect(socket.destroy).toHaveBeenCalledTimes(1) + expect(socket.end).not.toHaveBeenCalled() + expect(tcpServers[0].close).not.toHaveBeenCalled() + + socket.emit('close') + + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + expect(vi.getTimerCount()).toBe(0) + }) + + it('should leave an unidentified connection standing when a HAP connection closes while another session is prepared', () => { + const server = new DataStreamServer() + const hapConnection = verifiedConnection() + prepare(server, hapConnection) + prepare(server) + tcpServers[0].emit('listening') + const socket = new FakeSocket() + tcpServers[0].emit('connection', socket) + + hapConnection.emit(HAPConnectionEvent.CLOSED) + + expect(server.preparedSessions).toHaveLength(1) + expect(socket.destroy).not.toHaveBeenCalled() + expect(socket.end).not.toHaveBeenCalled() + }) + + it('should destroy a connection accepted while no session is prepared at once, which leaves the list at its socket\'s close', () => { + const server = new DataStreamServer() + const identified = listeningSession(server) + expect(server.preparedSessions).toHaveLength(0) + + const socket = new FakeSocket() + tcpServers[0].emit('connection', socket) + + expect(socket.destroy).toHaveBeenCalledTimes(1) + expect(socket.end).not.toHaveBeenCalled() + + socket.emit('close') + + expect((server as any).connections).toEqual([identified.connection]) + expect(identified.socket.end).not.toHaveBeenCalled() + expect(tcpServers[0].close).not.toHaveBeenCalled() + }) + + it('should answer a prepare made while the TCP server closes once with the HAP-closed error when its HAP connection closes, and start no TCP server', () => { + const server = new DataStreamServer() + const first = listeningSession(server) + first.socket.emit('close') + const hapConnection = verifiedConnection() + const callback = prepare(server, hapConnection) + + hapConnection.emit(HAPConnectionEvent.CLOSED) + expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The HAP connection of the data stream session closed before its controller connected.')) + + tcpServers[0].emit('close') + vi.advanceTimersByTime(10) + + expect(tcpServers).toHaveLength(1) + expect(vi.getTimerCount()).toBe(0) + expect(callback).toHaveBeenCalledTimes(1) + }) + + it('should answer a prepare waiting for the restart once with the HAP-closed error when its HAP connection closes within the 10 ms, and start no TCP server', () => { + const server = new DataStreamServer() + const first = listeningSession(server) + first.socket.emit('close') + const hapConnection = verifiedConnection() + const callback = prepare(server, hapConnection) + + tcpServers[0].emit('close') + vi.advanceTimersByTime(5) + hapConnection.emit(HAPConnectionEvent.CLOSED) + expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The HAP connection of the data stream session closed before its controller connected.')) + + vi.advanceTimersByTime(5) + + expect(tcpServers).toHaveLength(1) + expect(vi.getTimerCount()).toBe(0) + expect(callback).toHaveBeenCalledTimes(1) + }) + + it.each([ + [ + 'its timeout', + (server: DataStreamServer, hapConnection: HAPConnection): void => { + prepare(server, hapConnection) + vi.advanceTimersByTime(10000) + }, + ], + [ + 'its HAP connection\'s close', + (server: DataStreamServer, hapConnection: HAPConnection): void => { + prepare(server, hapConnection) + hapConnection.emit(HAPConnectionEvent.CLOSED) + }, + ], + [ + 'a failed listen', + (server: DataStreamServer, hapConnection: HAPConnection): void => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + prepare(server, hapConnection) + tcpServers[0].emit('error', new Error('listen EADDRINUSE: address already in use')) + }, + ], + [ + 'a destroy', + (server: DataStreamServer, hapConnection: HAPConnection): void => { + prepare(server, hapConnection) + tcpServers[0].emit('listening') + server.destroy() + }, + ], + [ + 'a prepare on a server already destroyed', + (server: DataStreamServer, hapConnection: HAPConnection): void => { + server.destroy() + prepare(server, hapConnection) + }, + ], + ])('should return the HAP connection\'s close listeners and listener allowance to their values before the prepare when %s drops the session', (_, drop) => { + const server = new DataStreamServer() + const hapConnection = verifiedConnection() + const listeners = hapConnection.listenerCount(HAPConnectionEvent.CLOSED) + const maxListeners = hapConnection.getMaxListeners() + + drop(server, hapConnection) + + expect(server.preparedSessions).toHaveLength(0) + expect(hapConnection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(listeners) + expect(hapConnection.getMaxListeners()).toBe(maxListeners) + }) + + it('should list a connection and call every later listener when a connection-opened listener throws, logging the failure once', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const server = new DataStreamServer() + const later = vi.fn() + + server.on(DataStreamServerEvent.CONNECTION_OPENED, () => { + throw new Error('The listener failed.') + }) + server.on(DataStreamServerEvent.CONNECTION_OPENED, later) + prepare(server) + tcpServers[0].emit('listening') + + expect(() => tcpServers[0].emit('connection', new FakeSocket())).not.toThrow() + expect((server as any).connections).toHaveLength(1) + expect(later).toHaveBeenCalledExactlyOnceWith((server as any).connections[0]) + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A listener of the data stream server\'s connection-opened event failed: Error: The listener failed.', + ]) + }) + + it('should call every later listener, close the TCP server and release the connection when a connection-closed listener throws', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const server = new DataStreamServer() + const hapConnection = verifiedConnection() + const listeners = hapConnection.listenerCount(HAPConnectionEvent.CLOSED) + const { connection, socket } = listeningSession(server, hapConnection) + const later = vi.fn() + + server.on(DataStreamServerEvent.CONNECTION_CLOSED, () => { + throw new Error('The listener failed.') + }) + server.on(DataStreamServerEvent.CONNECTION_CLOSED, later) + + expect(() => socket.emit('close')).not.toThrow() + expect(later).toHaveBeenCalledExactlyOnceWith(connection) + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + expect((connection as any).stack.disposed).toBe(true) + expect(hapConnection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(listeners) + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A listener of the data stream server\'s connection-closed event failed: Error: The listener failed.', + ]) + }) + + it('should hand the HAP connection from the identified session to its connection, which returns its close listeners and allowance once its socket closes', () => { + const server = new DataStreamServer() + const hapConnection = verifiedConnection() + const listeners = hapConnection.listenerCount(HAPConnectionEvent.CLOSED) + const maxListeners = hapConnection.getMaxListeners() + const { socket } = listeningSession(server, hapConnection) + + // The identification dropped the session, whose listener went with it, and the identified connection holds one of its own. + expect(server.preparedSessions).toHaveLength(0) + expect(hapConnection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(listeners + 1) + expect(hapConnection.getMaxListeners()).toBe(maxListeners + 1) + + socket.emit('close') + + expect(hapConnection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(listeners) + expect(hapConnection.getMaxListeners()).toBe(maxListeners) + }) }) describe('messages after a close', () => { @@ -802,7 +1134,14 @@ describe('DataStreamServer', () => { expect(eventHandler).not.toHaveBeenCalled() expect(requestHandler).not.toHaveBeenCalled() - expect(session.socket.write).toHaveBeenCalledTimes(1) // only the hello response + // the hello response and the request's answer: the request still carries an id, so it is answered with a payload error, and the event is not + expect(session.socket.write).toHaveBeenCalledTimes(2) + expect(sentFrame(session, 1).header).toEqual({ + protocol: 'test', + response: 'topic', + id: 2, + status: HDSStatus.PAYLOAD_ERROR, + }) expect(session.socket.end).not.toHaveBeenCalled() // the connection still works @@ -812,28 +1151,73 @@ describe('DataStreamServer', () => { expect(requestHandler).toHaveBeenCalledExactlyOnceWith(3, { value: 2 }) }) + it('should answer a request whose body does not decode with a payload error, and drop an event whose body does not decode', () => { + const { session, eventHandler, requestHandler } = sessionWithHandlers() + // An empty dictionary is written as its one tag byte, and a zero tag in its place does not decode. + const undecodable = (header: Record): Buffer => Buffer.concat([ + messagePayload(header).subarray(0, -1), + Buffer.from([0x00]), + ]) + + session.socket.emit('data', encryptedFrame(session, undecodable({ protocol: 'test', event: 'topic' }))) + session.socket.emit('data', encryptedFrame(session, undecodable({ protocol: 'test', request: 'topic', id: 2 }))) + + expect(eventHandler).not.toHaveBeenCalled() + expect(requestHandler).not.toHaveBeenCalled() + expect(session.socket.write).toHaveBeenCalledTimes(2) // the hello response and the request's answer + expect(sentFrame(session, 1).header).toEqual({ + protocol: 'test', + response: 'topic', + id: 2, + status: HDSStatus.PAYLOAD_ERROR, + }) + expect(session.socket.end).not.toHaveBeenCalled() + }) + + it('should close a connection whose first frame names the hello with a body that is not a dictionary, answering nothing', () => { + const session = setupSession() + + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'control', request: 'hello', id: 1 }, 5))) + + expect(session.socket.end).toHaveBeenCalledTimes(1) + expect(session.socket.write).not.toHaveBeenCalled() + }) + it.each([ [ 'a protocol which is not a string', { protocol: 5, event: 'topic' }, + [], ], [ 'an event name which is not a string', { protocol: 'test', event: 5 }, + [], ], [ 'a request name which is not a string', { protocol: 'test', request: 5, id: 2 }, + // The request still carries an id, so it is answered with a header error that echoes its header as it came. + [ + { + protocol: 'test', + response: 5, + id: 2, + status: HDSStatus.HEADER_ERROR, + }, + ], ], [ 'a request id which is not a number', { protocol: 'test', request: 'topic', id: 'two' }, + [], ], [ 'a request without an id', { protocol: 'test', request: 'topic' }, + [], ], - ])('should drop a message with %s', (_, header) => { + ])('should drop a message with %s', (_, header, answers) => { const { session, eventHandler, requestHandler } = sessionWithHandlers() const globalHandler = vi.fn() session.connection.on('handle-message-globally', globalHandler) @@ -843,8 +1227,9 @@ describe('DataStreamServer', () => { expect(eventHandler).not.toHaveBeenCalled() expect(requestHandler).not.toHaveBeenCalled() expect(globalHandler).not.toHaveBeenCalled() - expect(session.socket.write).toHaveBeenCalledTimes(1) // only the hello response expect(session.socket.end).not.toHaveBeenCalled() + // every write after the hello response is an answer to the dropped message + expect(session.socket.write.mock.calls.slice(1).map((_call, index) => sentFrame(session, index + 1).header)).toEqual(answers) }) it('should keep waiting when a response has a status which is not a number', () => { @@ -908,6 +1293,17 @@ describe('DataStreamServer', () => { }) }) + it('should call a global request handler of the protocol toString for a request of that protocol, writing nothing beyond the hello\'s answer', () => { + const session = identifiedSession() + const handler = vi.fn() + + session.server.onRequestMessage('toString', 'hello', handler) + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'toString', request: 'hello', id: 7 }))) + + expect(handler).toHaveBeenCalledExactlyOnceWith(session.connection, 7, {}) + expect(session.socket.write).toHaveBeenCalledTimes(1) // only the hello response + }) + it('should not answer an unhandled event or a request without an id', () => { const session = identifiedSession() @@ -989,8 +1385,71 @@ describe('DataStreamServer', () => { }) }) + describe('listeners of a connection\'s own events', () => { + it('should call every later closed listener and release the connection when a listener of its closed event throws', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { connection, socket } = identifiedSession() + const later = vi.fn() + + connection.on('closed', () => { + throw new Error('The listener failed.') + }) + connection.on('closed', later) + + expect(() => socket.emit('close')).not.toThrow() + expect(later).toHaveBeenCalledOnce() + expect((connection as any).stack.disposed).toBe(true) + expect(connection.listenerCount('closed')).toBe(0) + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A listener of the data stream connection\'s closed event failed: Error: The listener failed.', + ]) + }) + + it('should answer a request no handler takes once, and a hello, when a listener of the connection\'s handle-message-globally or identification event throws', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const session = identifiedSession() + + // The server's own listener, added when the connection was accepted, answers the request before the throwing listener runs. + session.connection.on('handle-message-globally', () => { + throw new Error('The listener failed.') + }) + + const request = encryptedFrame(session, messagePayload({ protocol: 'unknownProtocol', request: 'unknownTopic', id: 7 })) + + expect(() => session.socket.emit('data', request)).not.toThrow() + expect(session.socket.write).toHaveBeenCalledTimes(2) + expect(sentFrame(session, 1).header).toEqual({ + protocol: 'unknownProtocol', + response: 'unknownTopic', + id: 7, + status: HDSStatus.MISSING_PROTOCOL, + }) + expect((session.connection as any).unansweredRequests.has(7)).toBe(false) + + // A fresh connection whose identification listener throws after the server's own identified it. + const fresh = setupSession() + fresh.connection.on('identification', () => { + throw new Error('The listener failed.') + }) + + expect(() => fresh.socket.emit('data', encryptedFrame(fresh, messagePayload({ protocol: 'control', request: 'hello', id: 1 })))).not.toThrow() + expect(fresh.socket.write).toHaveBeenCalledTimes(1) + expect(sentFrame(fresh, 0).header).toEqual({ + protocol: 'control', + response: 'hello', + id: 1, + status: HDSStatus.SUCCESS, + }) + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A listener of the data stream connection\'s handle-message-globally event failed: Error: The listener failed.', + 'A listener of the data stream connection\'s identification event failed: Error: The listener failed.', + ]) + }) + }) + describe('dispatch', () => { - it('should leave a request unanswered when its global handler throws', () => { + it('should answer a request once with an unexpected failure when its global handler throws', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) const session = identifiedSession() session.server.onRequestMessage('test', 'fail', () => { @@ -998,8 +1457,78 @@ describe('DataStreamServer', () => { }) session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'test', request: 'fail', id: 7 }))) - // The one write is the hello response. - expect(session.socket.write).toHaveBeenCalledTimes(1) + expect(session.socket.write).toHaveBeenCalledTimes(2) // the hello response and the answer + expect(sentFrame(session, 1)).toEqual({ + header: { + protocol: 'test', + response: 'fail', + id: 7, + status: HDSStatus.PROTOCOL_SPECIFIC_ERROR, + }, + message: { status: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE }, + }) + expect(error).toHaveBeenCalledOnce() + }) + + it('should answer a request once with an unexpected failure when its connection-level handler throws', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const session = identifiedSession() + + session.connection.addProtocolHandler('test', { + requestHandler: { + fail: () => { + throw new Error('The handler failed.') + }, + }, + }) + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'test', request: 'fail', id: 7 }))) + + expect(session.socket.write).toHaveBeenCalledTimes(2) // the hello response and the answer + expect(sentFrame(session, 1)).toEqual({ + header: { + protocol: 'test', + response: 'fail', + id: 7, + status: HDSStatus.PROTOCOL_SPECIFIC_ERROR, + }, + message: { status: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE }, + }) + expect(error).toHaveBeenCalledOnce() + }) + + it('should answer a request once, with its handler\'s own answer, when a global or a connection-level handler answers and then throws', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const session = identifiedSession() + + session.server.onRequestMessage('test', 'global', (connection, id) => { + connection.sendResponse('test', 'global', id) + throw new Error('The handler failed after it answered.') + }) + session.connection.addProtocolHandler('local', { + requestHandler: { + own: (id) => { + session.connection.sendResponse('local', 'own', id) + throw new Error('The handler failed after it answered.') + }, + }, + }) + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'test', request: 'global', id: 7 }))) + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'local', request: 'own', id: 8 }))) + + expect(session.socket.write).toHaveBeenCalledTimes(3) // the hello response and each handler's own answer + expect(sentFrame(session, 1).header).toEqual({ + protocol: 'test', + response: 'global', + id: 7, + status: HDSStatus.SUCCESS, + }) + expect(sentFrame(session, 2).header).toEqual({ + protocol: 'local', + response: 'own', + id: 8, + status: HDSStatus.SUCCESS, + }) + expect(error).toHaveBeenCalledTimes(2) }) it('should keep the first protocol handler when a second is added for its protocol', () => { @@ -1023,6 +1552,28 @@ describe('DataStreamServer', () => { expect(second.eventHandler.tick).not.toHaveBeenCalled() }) + it.each(['toString', '__proto__'])('should register a protocol handler for the protocol %s, send it the protocol\'s events and remove it', (protocol) => { + const session = identifiedSession() + const handler = { + eventHandler: { + tick: vi.fn(), + }, + } + const globalTick = vi.fn() + + session.server.onEventMessage(protocol, 'tick', globalTick) + + expect(session.connection.addProtocolHandler(protocol, handler)).toBe(true) + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol, event: 'tick' }, { value: 1 }))) + expect(handler.eventHandler.tick).toHaveBeenCalledExactlyOnceWith({ value: 1 }) + expect(globalTick).not.toHaveBeenCalled() + + session.connection.removeProtocolHandler(protocol, handler) + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol, event: 'tick' }, { value: 2 }))) + expect(handler.eventHandler.tick).toHaveBeenCalledTimes(1) + expect(globalTick).toHaveBeenCalledExactlyOnceWith(session.connection, { value: 2 }) + }) + it('should send a protocol\'s messages to its connection handler alone, refusing a request it cannot take, and to the global handlers once removed', async () => { const management = new DataStreamManagement() const handler = { @@ -1071,5 +1622,75 @@ describe('DataStreamServer', () => { client.closeSocket() expect(closed).toHaveBeenCalledExactlyOnceWith(client.connection) }) + + it('should call the next global handler of a request when the first throws, and log that throw and a global event handler\'s rejection', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const session = identifiedSession() + const second = vi.fn() + + session.server.onRequestMessage('test', 'fail', () => { + throw new Error('The handler failed.') + }) + session.server.onRequestMessage('test', 'fail', second) + session.server.onEventMessage('test', 'tick', async () => { + throw new Error('The handler rejected.') + }) + + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'test', request: 'fail', id: 7 }))) + expect(second).toHaveBeenCalledExactlyOnceWith(session.connection, 7, {}) + + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'test', event: 'tick' }))) + await Promise.resolve() + await Promise.resolve() + + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A handler of the data stream\'s test fail request failed: Error: The handler failed.', + 'A handler of the data stream\'s test tick event failed: Error: The handler rejected.', + ]) + }) + + it('should log the rejection of a connection-level event handler and of a response handler', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const session = identifiedSession() + + session.connection.addProtocolHandler('test', { + eventHandler: { + tick: async () => { + throw new Error('The event handler rejected.') + }, + }, + }) + session.connection.sendRequest('test', 'ping', {}, async () => { + throw new Error('The response handler rejected.') + }) + const { header } = sentFrame(session, 1) + + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'test', event: 'tick' }))) + session.socket.emit('data', encryptedFrame(session, messagePayload({ + protocol: 'test', + response: 'ping', + id: header.id, + status: HDSStatus.SUCCESS, + }))) + await Promise.resolve() + await Promise.resolve() + + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A handler of the data stream\'s test tick event failed: Error: The event handler rejected.', + 'A response handler of a data stream request failed: Error: The response handler rejected.', + ]) + }) + + it('should not call a global handler of the protocol p-e-q and the event r for the event q-e-r of the protocol p', () => { + const session = identifiedSession() + const handler = vi.fn() + + session.server.onEventMessage('p-e-q', 'r', handler) + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'p', event: 'q-e-r' }))) + expect(handler).not.toHaveBeenCalled() + + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'p-e-q', event: 'r' }))) + expect(handler).toHaveBeenCalledExactlyOnceWith(session.connection, {}) + }) }) }) diff --git a/src/lib/datastream/DataStreamServer.ts b/src/lib/datastream/DataStreamServer.ts index c8cdeb129..db04b986d 100644 --- a/src/lib/datastream/DataStreamServer.ts +++ b/src/lib/datastream/DataStreamServer.ts @@ -12,9 +12,10 @@ import net from 'node:net' import createDebug from 'debug' import { DisposableStack } from '../util/disposableStack.js' -import { errorMessage, errorStack } from '../util/errors.js' +import { errorMessage } from '../util/errors.js' import { HAPConnectionEvent } from '../util/eventedhttp.js' import * as hapCrypto from '../util/hapCrypto.js' +import { callDelegate, callListeners } from '../util/promise-utils.js' import { DataStreamParser, DataStreamReader, DataStreamWriter, Int64 } from './DataStreamParser.js' const debug = createDebug('HAP-NodeJS:DataStream:Server') @@ -22,6 +23,13 @@ const debug = createDebug('HAP-NodeJS:DataStream:Server') // A destroyed server answers every prepare it still holds, and every later one, with this message. const SERVER_DESTROYED_MESSAGE = 'The data stream server was destroyed.' +// A prepare still waiting for the TCP server's port is answered with the message of the drop that ended its session. +const SESSION_TIMED_OUT_MESSAGE = 'The data stream session timed out before its controller connected.' +const SESSION_CONNECTION_CLOSED_MESSAGE = 'The HAP connection of the data stream session closed before its controller connected.' + +// The sentence a response handler's failure is logged under, at its response, its request's timeout and its socket's close alike. +const RESPONSE_HANDLER_FAILURE = 'A response handler of a data stream request failed' + /** * @group HomeKit Data Streams (HDS) */ @@ -220,6 +228,24 @@ export interface DataStreamMessage { message: HDSMessage } +/** + * A request dropped for its shape whose header still names a request and a numeric id, which the controller waits on an answer to: its status says what + * failed, a field of the header or the body alone, and its protocol and request are what the header holds, of whatever type. + */ +interface DroppedRequest { + dropped: HDSStatus.HEADER_ERROR | HDSStatus.PAYLOAD_ERROR + id: number + protocol: unknown + request: unknown +} + +/** + * Tells a dropped request from a message a handler can read. + */ +function isDroppedRequest(message: DataStreamMessage | DroppedRequest): message is DroppedRequest { + return 'dropped' in message +} + /** * Reads the fields of the header of a message. * @@ -269,6 +295,19 @@ function parseHeader(header: HDSMessage): Omit | u return undefined } +/** + * The key of the global handlers of one kind, protocol and topic on the server's internal emitter. A JSON array, which distinct triples never share: a + * key joined with a separator would let a protocol or a topic that holds the separator meet another pair's handlers. + */ +function globalHandlerKey(kind: 'event' | 'request', protocol: string, topic: string): string { + return JSON.stringify([kind, protocol, topic]) +} + +// The sentence the failure of a handler of a controller's event or request is logged under, a global handler's and a connection's own alike. +function handlerFailure(kind: 'event' | 'request', message: DataStreamMessage): string { + return `A handler of the data stream's ${message.protocol} ${message.topic} ${kind} failed` +} + /** * @group HomeKit Data Streams (HDS) */ @@ -287,6 +326,7 @@ export enum DataStreamServerEvent { export declare interface DataStreamServer { on(event: 'connection-opened', listener: (connection: DataStreamConnection) => void): this on(event: 'connection-closed', listener: (connection: DataStreamConnection) => void): this + on(event: DataStreamServerEvent, listener: (connection: DataStreamConnection) => void): this emit(event: 'connection-opened', connection: DataStreamConnection): boolean emit(event: 'connection-closed', connection: DataStreamConnection): boolean @@ -307,11 +347,14 @@ export class DataStreamServer extends EventEmitter { private tcpServer?: net.Server private tcpPort?: number /** - * The prepared sessions which wait for the TCP server to start listening. + * The prepared sessions which wait for a TCP server to start listening: the one that binds, or the one that starts once the closing one closed. */ private readonly pendingBinds: { preparedSession: PreparedDataStreamSession, callback: (error?: Error) => void }[] = [] preparedSessions: PreparedDataStreamSession[] = [] + // What each prepared session releases at its drop: its HAP connection's close listener with the listener allowance made for it. The stacks are held here + // rather than on the session, which is an exported shape a plugin's callback receives. + private readonly preparedSessionStacks = new Map() private readonly connections: DataStreamConnection[] = [] private readonly internalEventEmitter: EventEmitter = new EventEmitter() // used for message event and message request handlers @@ -330,7 +373,7 @@ export class DataStreamServer extends EventEmitter { * @param handler - function to be called for every occurring event */ public onEventMessage(protocol: string | Protocols, event: string | Topics, handler: GlobalEventHandler): this { - this.internalEventEmitter.on(`${protocol}-e-${event}`, handler) + this.internalEventEmitter.on(globalHandlerKey('event', protocol, event), handler) return this } @@ -342,7 +385,7 @@ export class DataStreamServer extends EventEmitter { * @param handler - registered event handler */ public removeEventHandler(protocol: string | Protocols, event: string | Topics, handler: GlobalEventHandler): this { - this.internalEventEmitter.removeListener(`${protocol}-e-${event}`, handler) + this.internalEventEmitter.removeListener(globalHandlerKey('event', protocol, event), handler) return this } @@ -356,7 +399,7 @@ export class DataStreamServer extends EventEmitter { * @param handler - function to be called for every occurring request */ public onRequestMessage(protocol: string | Protocols, request: string | Topics, handler: GlobalRequestHandler): this { - this.internalEventEmitter.on(`${protocol}-r-${request}`, handler) + this.internalEventEmitter.on(globalHandlerKey('request', protocol, request), handler) return this } @@ -368,7 +411,7 @@ export class DataStreamServer extends EventEmitter { * @param handler - registered request handler */ public removeRequestHandler(protocol: string | Protocols, request: string | Topics, handler: GlobalRequestHandler): this { - this.internalEventEmitter.removeListener(`${protocol}-r-${request}`, handler) + this.internalEventEmitter.removeListener(globalHandlerKey('request', protocol, request), handler) return this } @@ -401,6 +444,23 @@ export class DataStreamServer extends EventEmitter { } this.preparedSessions.push(preparedSession) + // The HAP connection's close drops the session, which is how an unpublish, closing every HAP connection, drops every prepared session. Its listener and + // the allowance made for it are released from the session's stack at the drop. + const stack = new DisposableStack() + const hapConnectionClosed = (): void => { + debug('The HAP connection of a prepared HDS session closed before its controller connected (%s)', connection.sessionID) + this.dropPreparedSession(preparedSession, new Error(SESSION_CONNECTION_CLOSED_MESSAGE)) + this.checkCloseable() + } + + connection.setMaxListeners(connection.getMaxListeners() + 1) + connection.on(HAPConnectionEvent.CLOSED, hapConnectionClosed) + stack.defer(() => { + connection.removeListener(HAPConnectionEvent.CLOSED, hapConnectionClosed) + connection.setMaxListeners(connection.getMaxListeners() - 1) + }) + this.preparedSessionStacks.set(preparedSession, stack) + this.checkTCPServerEstablished(preparedSession, (error) => { if (error) { callback(error) @@ -412,36 +472,46 @@ export class DataStreamServer extends EventEmitter { private timeoutPreparedSession(preparedSession: PreparedDataStreamSession) { debug('Prepared HDS session timed out since no connection was opened for 10 seconds (%s)', preparedSession.connection.sessionID) - this.dropPreparedSession(preparedSession) + this.dropPreparedSession(preparedSession, new Error(SESSION_TIMED_OUT_MESSAGE)) this.checkCloseable() } - // Forgets a prepared session and stops its connect timer: it neither identifies a later connection nor times out into checkCloseable. - private dropPreparedSession(preparedSession: PreparedDataStreamSession): void { + /* Forgets a prepared session, stops its connect timer and releases its HAP connection's close listener: it neither identifies a later connection nor + * times out into checkCloseable. Every end of a session takes this one path. A session that ends before its controller connected hands the error its + * prepare is answered with, which reaches the prepare only while it still waits for a TCP server's port...one the listening server already answered is + * answered nothing more. An identified session hands none, since a controller connects only to a listening server, whose `listening` answered every + * waiting prepare, and so does a prepare a destroyed server refuses before it waits. + */ + private dropPreparedSession(preparedSession: PreparedDataStreamSession, error?: Error): void { clearTimeout(preparedSession.connectTimeout) preparedSession.connectTimeout = undefined + // A session the server did not prepare itself holds no stack, and its drop releases nothing. + this.preparedSessionStacks.get(preparedSession)?.dispose() + this.preparedSessionStacks.delete(preparedSession) + const index = this.preparedSessions.indexOf(preparedSession) if (index >= 0) { this.preparedSessions.splice(index, 1) + + if (this.preparedSessions.length === 0) { + this.closeUnidentifiedConnections() + } + } + + const waiting = this.pendingBinds.findIndex(pendingBind => pendingBind.preparedSession === preparedSession) + if (error && waiting >= 0) { + const [{ callback }] = this.pendingBinds.splice(waiting, 1) + callback(error) } } private checkTCPServerEstablished(preparedSession: PreparedDataStreamSession, callback: (error?: Error) => void) { switch (this.state) { case ServerState.UNINITIALIZED: - debug('Starting up TCP server.') - this.tcpServer = net.createServer() - - this.tcpServer.once('listening', this.listening.bind(this)) - this.tcpServer.on('connection', this.onConnection.bind(this)) - this.tcpServer.on('close', this.closed.bind(this)) - this.tcpServer.on('error', this.onServerError.bind(this, this.tcpServer)) - this.pendingBinds.push({ preparedSession, callback }) - this.tcpServer.listen() - this.state = ServerState.BINDING + this.startTCPServer() break case ServerState.BINDING: debug('TCP server already running. Waiting for it to bind.') @@ -453,8 +523,10 @@ export class DataStreamServer extends EventEmitter { callback() break case ServerState.CLOSING: - debug('TCP socket is currently closing. Trying again when server is fully closed and opening a new one then.') - this.tcpServer!.once('close', () => setTimeout(() => this.checkTCPServerEstablished(preparedSession, callback), 10)) + // The prepare waits on the list a binding server answers: the closing server's close restarts a server for it, and a drop of its session in the + // meantime takes it off the list, which leaves no server to start. + debug('TCP socket is currently closing. Waiting for it to close and starting a new one then.') + this.pendingBinds.push({ preparedSession, callback }) break case ServerState.DESTROYED: debug('Refusing to prepare a data stream session on a destroyed server (%s)', preparedSession.connection.sessionID) @@ -464,6 +536,20 @@ export class DataStreamServer extends EventEmitter { } } + // Starts a TCP server for the prepares waiting on the list. + private startTCPServer(): void { + debug('Starting up TCP server.') + this.tcpServer = net.createServer() + + this.tcpServer.once('listening', this.listening.bind(this)) + this.tcpServer.on('connection', this.onConnection.bind(this)) + this.tcpServer.on('close', this.closed.bind(this)) + this.tcpServer.on('error', this.onServerError.bind(this, this.tcpServer)) + + this.tcpServer.listen() + this.state = ServerState.BINDING + } + private listening() { this.state = ServerState.LISTENING @@ -507,9 +593,8 @@ export class DataStreamServer extends EventEmitter { * Answers everybody who waits for the TCP server to start listening with the given error, each of them once. */ private failPendingBinds(error: Error) { - for (const { preparedSession, callback } of this.pendingBinds.splice(0)) { - this.dropPreparedSession(preparedSession) - callback(error) + for (const { preparedSession } of [...this.pendingBinds]) { + this.dropPreparedSession(preparedSession, error) } } @@ -524,7 +609,23 @@ export class DataStreamServer extends EventEmitter { this.connections.push(connection) - this.emit(DataStreamServerEvent.CONNECTION_OPENED, connection) + // The connection is listed before any listener runs, and a listener's failure stops nothing. + this.emitGuarded(DataStreamServerEvent.CONNECTION_OPENED, connection) + + // A controller learns the port and the accessory's key salt only from a Setup Data Stream Transport write's answer, which prepares a session first. + // A connection that arrives while no session is prepared can never be identified, and it is closed at once rather than at its hello timer. + if (this.preparedSessions.length === 0) { + connection.close() + } + } + + // Closes every connection still unidentified once no session is left to identify it, which handleSessionIdentification matches against alone. + private closeUnidentifiedConnections(): void { + for (const connection of [...this.connections]) { + if (connection.isUnidentified()) { + connection.close() + } + } } private handleSessionIdentification(connection: DataStreamConnection, firstFrame: HDSFrame, callback: IdentificationCallback) { @@ -557,41 +658,48 @@ export class DataStreamServer extends EventEmitter { private handleMessageGlobally(connection: DataStreamConnection, message: DataStreamMessage) { assert.notStrictEqual(message.type, MessageType.RESPONSE) // responses can't physically get here - let separator = '' - const args = [] - if (message.type === MessageType.EVENT) { - separator = '-e-' - } else if (message.type === MessageType.REQUEST) { - separator = '-r-' - args.push(message.id) - } - args.push(message.message) - - let hadListeners - try { - hadListeners = this.internalEventEmitter.emit(message.protocol + separator + message.topic, connection, ...args) - } catch (error) { - hadListeners = true - debug('[%s] Error occurred while dispatching handler for HDS message: %o', connection.remoteAddress, message) - debug(errorStack(error) ?? errorMessage(error)) - } + const kind = message.type === MessageType.REQUEST + ? 'request' + : 'event' + const key = globalHandlerKey(kind, message.protocol, message.topic) - if (!hadListeners) { + if (this.internalEventEmitter.listenerCount(key) === 0) { debug('[%s] WARNING no handler was found for message: %o', connection.remoteAddress, message) connection.respondToUnhandledRequest(message) + return + } + + // A handler's throw stops no later handler of its topic, and the rejection of a promise it returns is reported rather than left unhandled. + const args = kind === 'request' + ? [connection, message.id, message.message] + : [connection, message.message] + + // A request whose handler threw before any handler answered it is answered with a failure, which the connection sends only while it stands unanswered. + if (callListeners(this.internalEventEmitter, key, args, handlerFailure(kind, message))) { + connection.respondToFailedRequest(message) } } private connectionClosed(connection: DataStreamConnection) { debug('[%s] DataStream connection closed', connection.remoteAddress) - this.connections.splice(this.connections.indexOf(connection), 1) - this.emit(DataStreamServerEvent.CONNECTION_CLOSED, connection) + const index = this.connections.indexOf(connection) + if (index >= 0) { + this.connections.splice(index, 1) + } + + // Whatever a listener does, the server still checks whether it can close and releases its own listeners once destroyed. + this.emitGuarded(DataStreamServerEvent.CONNECTION_CLOSED, connection) this.checkCloseable() this.releaseListenersOnceDestroyed() } + // Calls each listener of one of the server's events through the delegate guard, which reports a listener's throw or rejection and stops nothing. + private emitGuarded(event: DataStreamServerEvent, connection: DataStreamConnection): void { + callListeners(this, event, [connection], `A listener of the data stream server's ${event} event failed`) + } + // A destroyed server drops its own listeners once it holds no connection: at the destroy itself when it holds none, and otherwise after its last // connection's CONNECTION_CLOSED, which is why a listener registered before the destroy still hears the close of every connection the destroy ends. private releaseListenersOnceDestroyed(): void { @@ -616,7 +724,7 @@ export class DataStreamServer extends EventEmitter { */ public destroy(): void { if (this.tcpServer && this.state < ServerState.CLOSING) { - // Only a running TCP server is closed. The closing state holds while the waiting prepares are answered below, and the destroyed state follows. + // Only a running TCP server is closed, and the closing state holds while its connections close. this.state = ServerState.CLOSING this.tcpServer.close() for (const connection of this.connections) { @@ -624,14 +732,16 @@ export class DataStreamServer extends EventEmitter { } } - // A prepare still waiting for the TCP server's port is answered here whatever state the destroy finds, since a destroyed server never listens again. + // The server reads destroyed before it answers any prepare: a prepare made from inside an answer is refused at once, where a closing server would + // leave it on a list no server answers once the destroy is done. A prepare still waiting for the TCP server's port is answered here whatever state the + // destroy finds, since a destroyed server never listens again. + this.state = ServerState.DESTROYED this.failPendingBinds(new Error(SERVER_DESTROYED_MESSAGE)) for (const preparedSession of [...this.preparedSessions]) { this.dropPreparedSession(preparedSession) } - this.state = ServerState.DESTROYED this.internalEventEmitter.removeAllListeners() this.releaseListenersOnceDestroyed() } @@ -640,8 +750,22 @@ export class DataStreamServer extends EventEmitter { this.tcpServer = undefined this.tcpPort = undefined - if (this.state !== ServerState.DESTROYED) { - this.state = ServerState.UNINITIALIZED + if (this.state === ServerState.DESTROYED) { + return + } + + this.state = ServerState.UNINITIALIZED + + // A prepare made while the server closed waits on the list, and a new server starts for it once the restart below comes due. Until then a drop of its + // session leaves the list empty, and a prepare made meanwhile starts a server at once, which answers every waiting prepare, so the restart starts one + // only where the list still holds a prepare and no server was started since. Nothing clears it: a destroy in the meantime leaves it a destroyed server + // and an empty list. + if (this.pendingBinds.length > 0) { + setTimeout(() => { + if (this.state === ServerState.UNINITIALIZED && this.pendingBinds.length > 0) { + this.startTCPServer() + } + }, 10) } } } @@ -741,15 +865,21 @@ export class DataStreamConnection extends EventEmitter { private incompleteFrameLength = 0 private incompleteFrameNeeded = 0 // the total length the bytes need before there is something new to decode - // What the connection releases once its socket closes: the HAP connection's close listener with the listener allowance made for it, and the socket's - // end timer. Each release is deferred as its resource is taken. + // What the connection releases once its socket closes: the hello timer, the HAP connection's close listener with the listener allowance made for it, and + // the socket's end timer. Each release is deferred as its resource is taken. private readonly stack = new DisposableStack() - private protocolHandlers: Record = {} // used to store protocolHandlers identified by their protocol name + // The protocol handlers by their protocol's name. A map holds a protocol of any name as an entry of its own, where a plain record would find what every + // object inherits under a name like "toString" and would set its own prototype under "__proto__". + private readonly protocolHandlers = new Map() private responseHandlers: Record = {} // used to store responseHandlers indexed by their respective requestId private responseTimers: Record = {} // used to store response timeouts indexed by their respective requestId + // The ids of the controller's requests whose dispatch is running and which no response has answered yet: a handler that throws leaves its request + // answered with a failure only while its id stands here, so a handler that answered and then threw is answered once. + private readonly unansweredRequests = new Set() + private helloTimer?: NodeJS.Timeout constructor(socket: Socket) { @@ -775,6 +905,7 @@ export class DataStreamConnection extends EventEmitter { debug('[%s] Hello message did not arrive in time. Killing the connection', this.remoteAddress) this.close() }, 10000) + this.stack.defer(() => clearTimeout(this.helloTimer)) this.socket.on('data', this.onSocketData.bind(this)) this.socket.on('error', this.onSocketError.bind(this)) @@ -808,11 +939,11 @@ export class DataStreamConnection extends EventEmitter { * @param protocolHandler - object to be registered as protocol handler */ addProtocolHandler(protocol: string | Protocols, protocolHandler: DataStreamProtocolHandler): boolean { - if (this.protocolHandlers[protocol] !== undefined) { + if (this.protocolHandlers.has(protocol)) { return false } - this.protocolHandlers[protocol] = protocolHandler + this.protocolHandlers.set(protocol, protocolHandler) return true } @@ -823,10 +954,8 @@ export class DataStreamConnection extends EventEmitter { * @param protocolHandler - object which will be unregistered */ removeProtocolHandler(protocol: string | Protocols, protocolHandler: DataStreamProtocolHandler): void { - const current = this.protocolHandlers[protocol] - - if (current === protocolHandler) { - delete this.protocolHandlers[protocol] + if (this.protocolHandlers.get(protocol) === protocolHandler) { + this.protocolHandlers.delete(protocol) } } @@ -852,7 +981,8 @@ export class DataStreamConnection extends EventEmitter { * Sends a new request message to the connected client. * * Throws an {@link HDSConnectionError} when the connection is closing or closed, is not identified yet, or the message is - * too large. The callback is not called for such a request. + * too large, and the encoder's plain error for a message holding `undefined` inside a list. The callback is not called for + * such a request. * * @param protocol - name of the protocol * @param request - name of the request (also referred to as topic. See {@link Topics} for some known ones) @@ -884,12 +1014,7 @@ export class DataStreamConnection extends EventEmitter { delete this.responseTimers[requestId] // handlers should be able to clean up their stuff. Thrown inside a timer, an error would end the process - try { - handler(new Error('timeout'), undefined, {}) - } catch (error) { - debug('[%s] Error occurred while dispatching the timeout of request %d to its response handler', this.remoteAddress, requestId) - debug(errorStack(error) ?? errorMessage(error)) - } + callDelegate(() => handler(new Error('timeout'), undefined, {}), RESPONSE_HANDLER_FAILURE) }, 10000) // 10s timer const header: HDSMessage = {} @@ -932,6 +1057,8 @@ export class DataStreamConnection extends EventEmitter { header.status = new Int64(status) this.sendHDSFrame(header, message) + // The request is answered once its response is written: a response that could not be written leaves a handler's later throw to answer it. + this.unansweredRequests.delete(id) } private onSocketData(data: Buffer) { @@ -948,7 +1075,7 @@ export class DataStreamConnection extends EventEmitter { if (this.state === ConnectionState.UNIDENTIFIED) { // at the beginning we are only interested in trying to decrypt the first frame in order to test decryption keys const firstFrame = frames[frameIndex++] - this.emit(DataStreamConnectionEvent.IDENTIFICATION, firstFrame, (identifiedSession?: PreparedDataStreamSession) => { + this.emitGuarded(DataStreamConnectionEvent.IDENTIFICATION, firstFrame, (identifiedSession?: PreparedDataStreamSession) => { if (identifiedSession) { // hooray, we found our connection this.connection = identifiedSession.connection @@ -988,12 +1115,14 @@ export class DataStreamConnection extends EventEmitter { } } - const messages: DataStreamMessage[] = this.decodePayloads(frames) // decode contents of payload + const messages = this.decodePayloads(frames) // decode contents of payload if (this.state === ConnectionState.EXPECTING_HELLO) { const firstMessage = messages[0] - if (!firstMessage || firstMessage.protocol !== Protocols.CONTROL || firstMessage.type !== MessageType.REQUEST || firstMessage.topic !== Topics.HELLO) { + // A dropped request never counts as the hello, whatever its header names. + if (!firstMessage || isDroppedRequest(firstMessage) || firstMessage.protocol !== Protocols.CONTROL || firstMessage.type !== MessageType.REQUEST + || firstMessage.topic !== Topics.HELLO) { // first message is not the expected hello request debug('[%s] First message received was not the expected hello message. Instead got: %o', this.remoteAddress, firstMessage) this.close() @@ -1006,7 +1135,9 @@ export class DataStreamConnection extends EventEmitter { return // a handler of an earlier message in this chunk closed the connection: the rest is not for anybody anymore } - if (message.type === MessageType.RESPONSE) { + if (isDroppedRequest(message)) { + this.respondWithStatus(message.protocol, message.request, message.id, message.dropped) + } else if (message.type === MessageType.RESPONSE) { // protocol and topic are currently not tested here; just assumed they are correct; // probably they are as the requestId is unique per connection no matter what protocol is used const responseHandler = this.responseHandlers[message.id!] @@ -1023,22 +1154,15 @@ export class DataStreamConnection extends EventEmitter { return } - try { - responseHandler(undefined, message.status, message.message) - } catch (error) { - debug('[%s] Error occurred while dispatching response handler for HDS message: %o', this.remoteAddress, message) - debug(errorStack(error) ?? errorMessage(error)) - } + callDelegate(() => responseHandler(undefined, message.status, message.message), RESPONSE_HANDLER_FAILURE) delete this.responseHandlers[message.id!] } else { - // Object.hasOwn(): the protocol and the topic are picked by the controller, and a name like "toString" - // or "constructor" must not find what every object inherits - const handler = Object.hasOwn(this.protocolHandlers, message.protocol) - ? this.protocolHandlers[message.protocol] - : undefined + // Object.hasOwn() below: a handler's topic records are a plugin's own objects, and a topic the controller picks, like "toString" or + // "constructor", must not find what every object inherits + const handler = this.protocolHandlers.get(message.protocol) if (handler === undefined) { // send message to the server to check if there are some global handlers for it - this.emit(DataStreamConnectionEvent.HANDLE_MESSAGE_GLOBALLY, message) + this.dispatchMessage(message, () => this.emitGuarded(DataStreamConnectionEvent.HANDLE_MESSAGE_GLOBALLY, message)) return } @@ -1050,12 +1174,7 @@ export class DataStreamConnection extends EventEmitter { return } - try { - eventHandler(message.message) - } catch (error) { - debug('[%s] Error occurred while dispatching event handler for HDS message: %o', this.remoteAddress, message) - debug(errorStack(error) ?? errorMessage(error)) - } + callDelegate(() => eventHandler(message.message), handlerFailure('event', message)) } else if (message.type === MessageType.REQUEST) { let requestHandler: RequestHandler // eslint-disable-next-line no-cond-assign @@ -1065,12 +1184,7 @@ export class DataStreamConnection extends EventEmitter { return } - try { - requestHandler(message.id!, message.message) - } catch (error) { - debug('[%s] Error occurred while dispatching request handler for HDS message: %o', this.remoteAddress, message) - debug(errorStack(error) ?? errorMessage(error)) - } + this.dispatchMessage(message, () => callDelegate(() => requestHandler(message.id!, message.message), handlerFailure('request', message))) } else { debug('[%s] Encountered unknown message type with id %d', this.remoteAddress, message.type) } @@ -1160,14 +1274,59 @@ export class DataStreamConnection extends EventEmitter { * @private */ respondToUnhandledRequest(message: DataStreamMessage): void { - if (message.type !== MessageType.REQUEST || typeof message.id !== 'number' || this.isConsideredClosed()) { + if (message.type === MessageType.REQUEST && typeof message.id === 'number') { + this.respondWithStatus(message.protocol, message.topic, message.id, HDSStatus.MISSING_PROTOCOL) + } + } + + /** + * Answers a request whose handler threw before it answered with the protocol-specific status of an unexpected failure, which keeps the controller from + * waiting for a response that never comes. A request its handler answered is answered nothing more. + * + * @private + */ + respondToFailedRequest(message: DataStreamMessage): void { + if (message.type === MessageType.REQUEST && typeof message.id === 'number' && this.unansweredRequests.has(message.id)) { + this.respondWithStatus(message.protocol, message.topic, message.id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { + status: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, + }) + } + } + + /* Answers a request with a status of the connection's own while the connection is open, and a send that fails is logged rather than thrown into the + * dispatch. A dropped request's protocol and request are echoed as the controller sent them, whatever their type, which the encoder writes as it writes + * any value. + */ + private respondWithStatus(protocol: unknown, request: unknown, id: number, status: HDSStatus, message: HDSMessage = {}): void { + if (this.isConsideredClosed()) { return } try { - this.sendResponse(message.protocol, message.topic, message.id, HDSStatus.MISSING_PROTOCOL) + this.sendResponse(protocol as string, request as string, id, status, message) } catch (error) { - debug('[%s] Failed to answer the unhandled request: %s', this.remoteAddress, errorMessage(error)) + debug('[%s] Failed to answer the request %d with the status %d: %s', this.remoteAddress, id, status, errorMessage(error)) + } + } + + /* Runs the dispatch of a controller's message to a handler, marking a request's id unanswered while it runs, and answers a request whose handler threw + * synchronously before it answered. The mark goes once the dispatch returns, whatever it does. + */ + private dispatchMessage(message: DataStreamMessage, dispatch: () => boolean): void { + const request = message.type === MessageType.REQUEST && typeof message.id === 'number' + + if (request) { + this.unansweredRequests.add(message.id!) + } + + try { + if (dispatch()) { + this.respondToFailedRequest(message) + } + } finally { + if (request) { + this.unansweredRequests.delete(message.id!) + } } } @@ -1189,8 +1348,8 @@ export class DataStreamConnection extends EventEmitter { } } - private decodePayloads(frames: HDSFrame[]) { - const messages: DataStreamMessage[] = [] + private decodePayloads(frames: HDSFrame[]): (DataStreamMessage | DroppedRequest)[] { + const messages: (DataStreamMessage | DroppedRequest)[] = [] frames.forEach((frame) => { const payload = frame.plaintextPayload @@ -1222,12 +1381,14 @@ export class DataStreamConnection extends EventEmitter { return } + // A body that does not decode drops its message as one that decodes to something other than a dictionary does, once the header is read. + let bodyDecoded = true try { messageDictionary = DataStreamParser.decode(messagePayload) messagePayload.finished() } catch (error) { debug('[%s] Failed to decode message payload: %s (header: %o)', this.remoteAddress, errorMessage(error), headerDictionary) - return + bodyDecoded = false } if (!isHDSMessage(headerDictionary)) { @@ -1236,15 +1397,32 @@ export class DataStreamConnection extends EventEmitter { } // the payload is sent by the controller, so nothing is known about its shape before it is checked. - // a message which is not of the expected shape is dropped, so that no handler is called with something it cannot read + // a message which is not of the expected shape is dropped, so that no handler is called with something it cannot read. + // A dropped request whose header still names a request and a numeric id is kept in its place, to be answered with what failed. const header = parseHeader(headerDictionary) if (!header) { debug('[%s] Encountered unknown payload header format: %o (message: %o)', this.remoteAddress, headerDictionary, messageDictionary) + if (headerDictionary.request !== undefined && typeof headerDictionary.id === 'number') { + messages.push({ + dropped: HDSStatus.HEADER_ERROR, + id: headerDictionary.id, + protocol: headerDictionary.protocol, + request: headerDictionary.request, + }) + } return } - if (!isHDSMessage(messageDictionary)) { + if (!bodyDecoded || !isHDSMessage(messageDictionary)) { debug('[%s] Encountered message which is not a dictionary: %o (header: %o)', this.remoteAddress, messageDictionary, headerDictionary) + if (header.type === MessageType.REQUEST) { + messages.push({ + dropped: HDSStatus.PAYLOAD_ERROR, + id: header.id!, + protocol: header.protocol, + request: header.topic, + }) + } return } @@ -1310,7 +1488,16 @@ export class DataStreamConnection extends EventEmitter { return // connection is already closing/closed } + const unidentified = this.state === ConnectionState.UNIDENTIFIED this.state = ConnectionState.CLOSING + + // The half-close lets an encrypted session end cleanly, which an unidentified connection never began, so its socket is destroyed at once and nothing + // waits on its remote. + if (unidentified) { + this.socket.destroy() + return + } + this.socket.end() // a remote which never closes its side would otherwise keep the half-closed socket (and this connection) around forever @@ -1327,6 +1514,15 @@ export class DataStreamConnection extends EventEmitter { return this.state >= ConnectionState.CLOSING } + /** + * Whether the connection still waits for the first frame that identifies its prepared session. + * + * @private + */ + isUnidentified(): boolean { + return this.state === ConnectionState.UNIDENTIFIED + } + private onHAPSessionClosed() { // If the hap connection is closed it is probably also a good idea to close the data stream connection debug('[%s] HAP connection disconnected. Also closing DataStream connection now.', this.remoteAddress) @@ -1342,11 +1538,6 @@ export class DataStreamConnection extends EventEmitter { // this instance is now considered completely dead this.state = ConnectionState.CLOSED - if (this.helloTimer) { - clearTimeout(this.helloTimer) - this.helloTimer = undefined - } - // no response will arrive anymore: answer the waiting requests now instead of when their timeout runs out const pendingHandlers = Object.values(this.responseHandlers) for (const timer of Object.values(this.responseTimers)) { @@ -1355,15 +1546,22 @@ export class DataStreamConnection extends EventEmitter { this.responseHandlers = {} this.responseTimers = {} for (const handler of pendingHandlers) { - try { - handler(new HDSConnectionError('The connection was closed', HDSConnectionErrorType.CLOSED_SOCKET), undefined, {}) - } catch (error) { - debug('[%s] Response handler failed for a request which was cancelled as the connection closed: %s', this.remoteAddress, error) - } + callDelegate(() => handler(new HDSConnectionError('The connection was closed', HDSConnectionErrorType.CLOSED_SOCKET), undefined, {}), + RESPONSE_HANDLER_FAILURE) } - this.emit(DataStreamConnectionEvent.CLOSED) - this.stack.dispose() - this.removeAllListeners() + // Every listener hears the close whatever an earlier one does, and the connection's releases run whatever the guard itself meets. + try { + this.emitGuarded(DataStreamConnectionEvent.CLOSED) + } finally { + this.stack.dispose() + this.removeAllListeners() + } + } + + // Calls each listener of one of the connection's own events through the delegate guard, which reports a listener's throw or rejection and stops nothing, + // and answers whether one threw synchronously. + private emitGuarded(event: DataStreamConnectionEvent, ...args: unknown[]): boolean { + return callListeners(this, event, args, `A listener of the data stream connection's ${event} event failed`) } } diff --git a/src/lib/util/eventedhttp.spec.ts b/src/lib/util/eventedhttp.spec.ts index 2af06cedc..8d67e49ee 100644 --- a/src/lib/util/eventedhttp.spec.ts +++ b/src/lib/util/eventedhttp.spec.ts @@ -10,7 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { HAPHTTPClient } from '../../test-utils/HAPHTTPClient.js' import { HAPHTTPCode } from '../HAPServer.js' -import { EventedHTTPServer, EventedHTTPServerEvent, HAPConnection, HAPConnectionEvent } from './eventedhttp.js' +import { EventedHTTPServer, EventedHTTPServerEvent, HAPConnection, HAPConnectionEvent, HAPConnectionState } from './eventedhttp.js' import { awaitEventOnce, PromiseTimeout } from './promise-utils.js' describe('eventedhttp', () => { @@ -651,4 +651,20 @@ describe('HAPConnection', () => { expect(HAPConnection.prototype.disableEventNotificationsForAccessory.call(connection, 2)).toEqual([9, 10]) expect([...registeredEvents]).toEqual(['12.9', '1.9']) }) + + it.each([ + { alive: true, authenticated: false, state: 'CONNECTING' as const }, + { alive: true, authenticated: false, state: 'FULLY_SET_UP' as const }, + { alive: true, authenticated: true, state: 'AUTHENTICATED' as const }, + { alive: false, authenticated: false, state: 'TO_BE_TEARED_DOWN' as const }, + { alive: false, authenticated: false, state: 'CLOSING' as const }, + { alive: false, authenticated: false, state: 'CLOSED' as const }, + ])('isAlive answers $alive and isAuthenticated $authenticated for a connection in the state $state', ({ alive, authenticated, state }) => { + const connection = { state: HAPConnectionState[state] } as unknown as HAPConnection + + expect([ + HAPConnection.prototype.isAlive.call(connection), + HAPConnection.prototype.isAuthenticated.call(connection), + ]).toEqual([alive, authenticated]) + }) }) diff --git a/src/lib/util/eventedhttp.ts b/src/lib/util/eventedhttp.ts index 083466564..9d45c4b9c 100644 --- a/src/lib/util/eventedhttp.ts +++ b/src/lib/util/eventedhttp.ts @@ -585,6 +585,15 @@ export class HAPConnection extends EventEmitter { return this.state === HAPConnectionState.AUTHENTICATED } + /** + * Whether the connection is alive: connecting, set up or authenticated, and not yet to be torn down, closing or closed. It decides no access, which + * the server's own checks decide: a connection a server in insecure mode lets through is alive and never authenticated. + * @returns Whether the connection is alive. + */ + public isAlive(): boolean { + return this.state <= HAPConnectionState.AUTHENTICATED + } + public close(): void { if (this.state >= HAPConnectionState.CLOSING) { return // already closed/closing diff --git a/src/lib/util/promise-utils.spec.ts b/src/lib/util/promise-utils.spec.ts index e9e9a924e..bdcec5524 100644 --- a/src/lib/util/promise-utils.spec.ts +++ b/src/lib/util/promise-utils.spec.ts @@ -1,9 +1,10 @@ +import { EventEmitter } from 'node:events' import { inspect } from 'node:util' import { afterEach, describe, expect, it, vi } from 'vitest' import { deferred, settle } from '../../test-utils/settle.js' -import { callDelegate, logDelegateRejection, renderThrown } from './promise-utils.js' +import { callDelegate, callListeners, logDelegateRejection, renderThrown } from './promise-utils.js' // The sentence a call site names for its delegate's failure, which every line the logger writes for that call opens with. const FAILURE = 'ExampleDelegate failed to apply a change' @@ -130,6 +131,58 @@ describe('callDelegate', () => { }) }) +describe('callListeners', () => { + it('calls every listener in turn and answers true for a synchronous throw and false for a rejection or none, as callDelegate answers', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const heard: string[] = [] + const throwing = new EventEmitter() + const rejecting = new EventEmitter() + + throwing.on('change', (value: number) => heard.push(`first ${value}`)) + throwing.on('change', () => { + heard.push('throwing') + throw new Error('The listener failed.') + }) + throwing.once('change', (value: number) => heard.push(`once ${value}`)) + rejecting.on('change', async () => { + throw new Error('The listener rejected.') + }) + + expect([ + callListeners(throwing, 'change', [1], FAILURE), + callListeners(throwing, 'change', [2], FAILURE), + callListeners(rejecting, 'change', [], FAILURE), + callListeners(new EventEmitter(), 'change', [], FAILURE), + ]).toEqual([true, true, false, false]) + expect(heard).toEqual([ + 'first 1', + 'throwing', + 'once 1', + 'first 2', + 'throwing', + ]) + + expect([ + callDelegate(() => { + throw new Error('The change could not be applied.') + }, FAILURE), + callDelegate(async () => { + throw new Error('The change was refused.') + }, FAILURE), + callDelegate(() => undefined, FAILURE), + ]).toEqual([true, false, false]) + await settle() + + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + `${FAILURE}: Error: The listener failed.`, + `${FAILURE}: Error: The listener failed.`, + `${FAILURE}: Error: The change could not be applied.`, + `${FAILURE}: Error: The listener rejected.`, + `${FAILURE}: Error: The change was refused.`, + ]) + }) +}) + describe('logDelegateRejection', () => { it('reports a rejection through the report it is handed, in place of the console line, and none that settles while its signal reads aborted', async () => { const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) diff --git a/src/lib/util/promise-utils.ts b/src/lib/util/promise-utils.ts index 906e2c0d7..eae7abb59 100644 --- a/src/lib/util/promise-utils.ts +++ b/src/lib/util/promise-utils.ts @@ -116,12 +116,41 @@ export function logDelegateRejection(result: unknown, failure: string, signal?: * failure stays the delegate's where nothing above the call answers for it. Each is reported through `report`, which logs it where the call site hands * none. * + * @returns Whether the call threw synchronously, for a call site that answers for that failure besides reporting it. A rejection, which settles later, + * answers false. * @group Utils */ -export function callDelegate(call: () => unknown, failure: string, report: DelegateFailureReport = logDelegateFailure): void { +export function callDelegate(call: () => unknown, failure: string, report: DelegateFailureReport = logDelegateFailure): boolean { try { logDelegateRejection(call(), failure, undefined, report) + return false } catch (error) { report(failure, error) + return true } } + +/** + * Calls each listener of an emitter's event in turn, in the order it was added, through {@link callDelegate}: nothing is awaited, a listener's throw or + * the rejection of a promise it returns is reported under the sentence its call site names, and the next listener is still called. A listener added with + * `once` is heard once, since its wrapper takes it off before it runs. Each failure is reported through `report`, which logs it where the call site hands + * none. + * + * @returns Whether a listener threw synchronously. + * @group Utils + */ +export function callListeners( + emitter: EventEmitter, + event: string, + args: readonly unknown[], + failure: string, + report: DelegateFailureReport = logDelegateFailure, +): boolean { + let threw = false + + for (const listener of emitter.rawListeners(event)) { + threw = callDelegate(() => Reflect.apply(listener, emitter, args), failure, report) || threw + } + + return threw +} diff --git a/src/lib/util/request-util.ts b/src/lib/util/request-util.ts index 645e2de6c..9aad9c475 100644 --- a/src/lib/util/request-util.ts +++ b/src/lib/util/request-util.ts @@ -4,6 +4,18 @@ import type { CharacteristicProps } from '../Characteristic.js' import { Formats } from '../Characteristic.js' import { HAPStatus, IsKnownHAPStatusError } from '../HAPServer.js' +/** + * The time a characteristic's handler may take before it is reported as slow, in milliseconds. + * @private + */ +export const CHARACTERISTIC_TIMEOUT_WARNING = 3000 + +/** + * The time after {@link CHARACTERISTIC_TIMEOUT_WARNING} at which a request whose handler is still running is answered as timed out, in milliseconds. + * @private + */ +export const CHARACTERISTIC_TIMEOUT_AFTER_WARNING = 6000 + /** * Prepares the characteristic value to be sent to the HomeKit controller. * This includes changing booleans to 0 or 1 (for lower bandwidth) and converting diff --git a/src/test-utils/cameraFixtures.ts b/src/test-utils/cameraFixtures.ts index bb700aa91..50decea70 100644 --- a/src/test-utils/cameraFixtures.ts +++ b/src/test-utils/cameraFixtures.ts @@ -113,8 +113,9 @@ export interface FrameOptions { // Each picture's octets, and each keyframe's when it differs. octets?: number keyframeOctets?: number - // Whether each fragment carries the sound timed inside the frame before its own: the sound of a keyframe's frame arrives after the keyframe. - lag?: boolean + // The count of frames each fragment's sound is timed behind its own, none by default: a fragment carries the sound timed inside the frame that many + // frames before its own, which means the sound of a keyframe's frame arrives after the keyframe. + lag?: number // Whether the stream carries sound. sound?: boolean // Whether each sound opens with a table-of-contents octet the voice reader reads as its 20 ms, where by default it reads none. @@ -506,14 +507,14 @@ export function bufferCamera(recording?: CameraBufferRecordingOptions): BufferCa } // Writes a tier stream's frames from one index up to another at 30 a second, one fragment a frame, a keyframe every gop frames, the picture timed at its -// index and each fragment carrying the 20 ms sounds timed inside its frame, or inside the frame before it when the sound lags, behind a producer reference -// time box where a clock is given. +// index and each fragment carrying the 20 ms sounds timed inside its frame, or inside the frame `lag` frames before it when the sound lags, behind a +// producer reference time box where a clock is given. export function frames(stream: TierStream, from: number, to: number, options: FrameOptions = {}): void { const { gop = FRAMES_PER_SECOND, inBand = false, keyframeOctets, - lag = false, + lag = 0, octets = 100, readable = false, clock, @@ -530,9 +531,7 @@ export function frames(stream: TierStream, from: number, to: number, options: Fr for (let index = from; index < to; index++) { const keyframe = index % gop === 0 - const timed = lag - ? index - 1 - : index + const timed = index - lag // The sounds whose 20 ms start falls inside a frame of a thirtieth of a second, five for every three frames. const first = Math.ceil(timed * 5 / 3) const last = Math.ceil((timed + 1) * 5 / 3) @@ -645,6 +644,7 @@ export function buildMockConnection(): HAPConnection { getLocalAddress: vi.fn().mockReturnValue('127.0.0.1'), setMaxListeners: vi.fn(), getMaxListeners: vi.fn().mockReturnValue(10), + isAlive: vi.fn().mockReturnValue(true), isAuthenticated: vi.fn().mockReturnValue(true), on: vi.fn(), removeListener: vi.fn(), diff --git a/src/test-utils/connectionFixtures.ts b/src/test-utils/connectionFixtures.ts index 1214bdc02..ebb382fdb 100644 --- a/src/test-utils/connectionFixtures.ts +++ b/src/test-utils/connectionFixtures.ts @@ -5,26 +5,33 @@ import { EventEmitter } from 'node:events' import { HAPConnectionEvent } from '../lib/util/eventedhttp.js' -// A HAP connection's events and addresses on a plain emitter. Like a real connection whose socket closes, it reads as unauthenticated from the moment it -// emits its close, and a spec can close it while one of its writes waits. Its local address answers loopback in either family, and its server reports the -// family it was built with, as a HAP server listening on that family's wildcard does. +// A HAP connection's events and addresses on a plain emitter. Like a real connection whose socket closes, it reads as neither alive nor authenticated from +// the moment it emits its close, and a spec can close it while one of its writes waits. An unpaired one, which a server in insecure mode lets through, reads +// as alive and never as authenticated. Its local address answers loopback in either family, and its server reports the family it was built with, as a HAP +// server listening on that family's wildcard does. class EmitterConnection extends EventEmitter { readonly localAddress = '127.0.0.1' readonly remoteAddress = '192.168.1.2' readonly server: { address: () => { family: 'IPv4' | 'IPv6' } } + private readonly paired: boolean private closed = false - constructor(family: 'IPv4' | 'IPv6') { + constructor(family: 'IPv4' | 'IPv6', paired: boolean) { super() + this.paired = paired this.server = { address: () => ({ family }), } } - isAuthenticated(): boolean { + isAlive(): boolean { return !this.closed } + isAuthenticated(): boolean { + return this.paired && !this.closed + } + getLocalAddress(version: 'ipv4' | 'ipv6'): string { return version === 'ipv4' ? '127.0.0.1' @@ -40,6 +47,7 @@ class EmitterConnection extends EventEmitter { } } -export function buildEmitterConnection(family: 'IPv4' | 'IPv6' = 'IPv6'): HAPConnection { - return new EmitterConnection(family) as unknown as HAPConnection +// A connection of the family given, paired unless a row asks for one a server in insecure mode lets through. +export function buildEmitterConnection(family: 'IPv4' | 'IPv6' = 'IPv6', { paired = true }: { paired?: boolean } = {}): HAPConnection { + return new EmitterConnection(family, paired) as unknown as HAPConnection } diff --git a/src/test-utils/webRTCEngineFixtures.ts b/src/test-utils/webRTCEngineFixtures.ts index e2719d2f0..2e60d8c90 100644 --- a/src/test-utils/webRTCEngineFixtures.ts +++ b/src/test-utils/webRTCEngineFixtures.ts @@ -27,7 +27,7 @@ export const SENSOR_UUID = '7d3e0f9a-1b2c-4d5e-8f60-718293a4b5c6' // The settled entries of a literal tier set, by identifier, each frozen, carrying the sensor's UUID and marked to carry the sensor's sound, as the options // boundary leaves them for a sensor whose audio states its source 'tier'. -function settled(...tiers: Required[]): SensorStreamTiers['tiers'] { +function settled(...tiers: (Required & { recorded: boolean })[]): SensorStreamTiers['tiers'] { return new Map(tiers.map(tier => [ tier.id, Object.freeze({ ...tier, sensorUUID: SENSOR_UUID, sound: true }),