Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 42 additions & 10 deletions guides/HKSV3Protocol.md

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion guides/UpgradingCameraPlugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Moving a camera to the modern form means writing less code, not more. The librar
**What you provide:**

- **A description of the camera**: the video sizes and bitrates it offers.
- **A video stream for each of those**: fragmented MP4, with HEVC video and Opus audio, handed to the library as it arrives. `ffmpeg` writes it with two options.
- **A video stream for each of those**: fragmented MP4, with HEVC video and Opus audio, handed to the library as it arrives. `ffmpeg` writes it with two options, and a third states when each picture was taken.
- **A snapshot function** that answers a JPEG.
- **Motion**, reported with one call.
- **Optionally, somewhere to send a visitor's voice**, if the camera has a speaker.
Expand Down Expand Up @@ -163,6 +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.
- **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.
Expand Down Expand Up @@ -261,6 +262,7 @@ The request carries `keyframe` when a running tier has one: an MP4 holding a sin
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.
- **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.
Expand Down
6 changes: 4 additions & 2 deletions src/accessories/ModernCamera_example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ import { Accessory, CameraController, CameraSensorIntent, CameraVideoQuality, Ca
const PINCODE = '031-45-154'

// The arguments of one tier's encoder: ffmpeg's test pattern at the tier's size and frame rate and its tone, encoded to HEVC with a keyframe each second
// and to Opus, and written as fragmented MP4 one frame to a fragment, which keeps the delay a viewer sees to one frame.
// and to Opus, and written as fragmented MP4 one frame to a fragment, which keeps the delay a viewer sees to one frame. Each fragment carries a prft box
// stating the wall clock it was written at, which a recording is stamped from: `-write_prft wallclock` writes the computer's clock, where
// `-write_prft pts` would state the stream's own times as a date in 1970.
function encoderArguments(tier: TierStream['tier']): string[] {
const fragment = Math.round(1000000 / tier.frameRate)
const rate = tier.frameRate
Expand All @@ -34,7 +36,7 @@ function encoderArguments(tier: TierStream['tier']): string[] {
`-map 0:v:0 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 -x265-params keyint=${rate}:min-keyint=${rate}:scenecut=0:log-level=error`,
`-b:v ${tier.bitrate}k -maxrate ${tier.peakBitrate}k -bufsize ${tier.peakBitrate}k`,
'-map 1:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000',
`-f mp4 -movflags empty_moov+default_base_moof -frag_duration ${fragment} pipe:1`,
`-f mp4 -movflags empty_moov+default_base_moof -frag_duration ${fragment} -write_prft wallclock pipe:1`,
].join(' ').split(' ')
}

Expand Down
35 changes: 35 additions & 0 deletions src/lib/camera/RecordingManagement.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,41 @@ describe('RecordingManagement', () => {
})))
})

it('stamps a delegate\'s recording at the moment its first fragment is written, with a capability camera\'s box writing turned on, whatever wall '
+ 'clock its packets carry', async () => {
const [muxed, first, muxedSecond] = skeletonPackets()
// The skeleton's packets without the muxer's own producer reference time boxes, each carrying a member named as the recorder's wall clock is.
const wallClock = Date.parse('2020-01-01T00:00:00.000Z')
const delegate = recordingDelegate(async function* () {
yield {
data: muxed.subarray(0, muxed.length - 32),
isLast: false,
wallClock,
}
yield { data: first, isLast: false, wallClock }
yield {
data: muxedSecond.subarray(32),
isLast: true,
wallClock,
}
})
const management = recordingCamera(delegate)

// @ts-expect-error: private access
management.producerReferenceTime = true
vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-12T00:00:00.000Z'))

const client = await DataStreamClient.connect(management.dataStreamManagement)

open(client)
await settle()

const sent = dataEvents(client).map(({ packets: [{ data }] }) => data as Buffer)

expect(sent[1].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f8000000000000000000000000000')
expect(sent[2].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f800410666666000000000000f3d8')
})

it('closes a recording as an unexpected failure at a fragment before any initialization segment, with a capability camera\'s box writing turned on', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const [, first] = skeletonPackets()
Expand Down
14 changes: 10 additions & 4 deletions src/lib/camera/RecordingManagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { DelegateFailureReport } from '../util/promise-utils.js'
import type { CameraReporter, DebugWriter } from './diagnostics/CameraReporter.js'
import type { VideoCodecType } from './index.js'
import type { OperatingModeState } from './OperatingModePolicy.js'
import type { RecordingAdmission } from './recording/BufferRecorder.js'
import type { RecorderPacket, RecordingAdmission } from './recording/BufferRecorder.js'
import type { ServedRecording, ServedRecordings } from './recording/ServedRecording.js'
import type { H264CodecParameters, H264Level, H264Profile, Resolution } from './RTPStreamManagement.js'
import type { SnapshotFetchRequest, SnapshotRefusal } from './StreamingOptions.js'
Expand Down Expand Up @@ -1589,6 +1589,12 @@ class CameraRecordingStream extends EventEmitter {

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
? () => Date.now()
: packet => packet.wallClock ?? Date.now()

for await (const packet of recording.iterable) {
if (this.closed) {
debug('[HDS %s] Delegate yielded fragment after stream %d was already closed.', this.connection.remoteAddress, this.streamId)
Expand All @@ -1600,9 +1606,9 @@ class CameraRecordingStream extends EventEmitter {
continue
}

// The writer reads the wall clock once per packet and walks the packet once. The data size and chunks follow the bytes it answers, the data type
// still follows the packet's position in the recording, and the served recording takes what that one walk read.
const written = this.writer?.writePacket(packet.data, Date.now())
// The writer walks the packet once, handed the wall clock its first picture is stamped at. The data size and chunks follow the bytes it answers, the
// data type still follows the packet's position in the recording, and the served recording takes what that one walk read.
const written = this.writer?.writePacket(packet.data, clockOf(packet))
const fragment = written?.bytes ?? packet.data

if (written !== undefined) {
Expand Down
16 changes: 12 additions & 4 deletions src/lib/camera/StreamingOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,14 @@ export interface ResourceScope {
* cut by duration with `-frag_duration`, at any frame rate, a frame's length in microseconds giving the least delay; fragments written without
* `default_base_moof` place their data by an absolute file offset, which a stream cannot follow, and fail the tier.
*
* 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.
*
* 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
Expand Down Expand Up @@ -209,10 +217,10 @@ export interface TierStream extends ResourceScope {
*/
write(chunk: Buffer): void
/**
* Marks the source's restart, at a reconnect: the octets of a box read so far and a fragment waiting for its media data are dropped, the tracks read stay,
* and the next sample opens a new run of times for picture and sound alike, a fragment with no decode time of its own counting from zero. Inside a
* fragment's media data, the samples already read are sent in the pacer's next turn, with every sample of the run still waiting, and the rest of the box
* is dropped, and the next chunk is read from a box's first octet.
* Marks the source's restart, at a reconnect: the octets of a box read so far, a fragment waiting for its media data and a `prft` box waiting for its
* fragment are dropped, the tracks read stay, and the next sample opens a new run of times for picture and sound alike, a fragment with no decode time
* of its own counting from zero. Inside a fragment's media data, the samples already read are sent in the pacer's next turn, with every sample of the
* run still waiting, and the rest of the box is dropped, and the next chunk is read from a box's first octet.
*/
discontinuity(): void
/**
Expand Down
9 changes: 5 additions & 4 deletions src/lib/camera/TierTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1261,10 +1261,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, 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 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.
private take(sample: Mp4StreamSample): void {
if (!this.feeds) {
return
Expand Down
94 changes: 93 additions & 1 deletion src/lib/camera/buffer/CameraBuffer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Buffer } from 'node:buffer'
import { afterEach, describe, expect, it, vi } from 'vitest'

import {
prft,
sampleFragment,
soundSample,
TIER_STREAM_PARAMETER_SETS,
Expand All @@ -19,7 +20,7 @@ import {
} from '../../../test-utils/mp4Fixtures.js'
import { detachedReporter, problemsOf, REPORTER_ACCESSORY_UUID } from '../../../test-utils/reporterFixtures.js'
import { Mp4StreamReader } from '../mp4/Mp4StreamReader.js'
import { TierBuffer } from './CameraBuffer.js'
import { longestReach, takenAt, TierBuffer } from './CameraBuffer.js'

const SENSOR_UUID = 'a1b2c3d4-0000-4000-8000-000000000001'

Expand Down Expand Up @@ -306,6 +307,10 @@ describe('cameraBuffer', () => {
})

describe('the ceilings', () => {
it('answers how far back a buffer may reach as its span and the keyframe allowance, over a span of nothing and a prebuffer', () => {
expect([0, 5000].map(span => longestReach(span))).toEqual([10000, 15000])
})

it('drops to its next keyframe once it reaches back past its span and the keyframe allowance, telling its places once an episode, and holds nothing '
+ 'with no later keyframe', () => {
const { at, buffer, trims } = rig(5000)
Expand Down Expand Up @@ -344,6 +349,31 @@ describe('cameraBuffer', () => {
expect(times(short.buffer, 'video')).toEqual([13])
})

it('keeps its head keyframe with its newest picture exactly its span and the keyframe allowance from it, and drops to its next keyframe at a picture '
+ 'one tick of the picture\'s clock further', () => {
const { at, buffer, trims, write } = rig(5000)

for (let seconds = 0; seconds <= 15; seconds++) {
at(seconds, {
keyframe: [0, 12].includes(seconds),
})
}

expect([times(buffer, 'video')[0], trims.length]).toEqual([0, 0])

// A picture one tick past the newest, written at a picture time of its own where the rig's pictures stand whole seconds apart.
write(tierStreamFragment({
picture: [
tierPicture({}),
],
pictureTime: BigInt(15 * PICTURE_RATE) + 1n,
sound: [],
soundTime: BigInt(15 * SOUND_RATE),
}), 15000)

expect([times(buffer, 'video')[0], trims.length]).toEqual([12, 1])
})

it('drops to its next keyframe once its octets pass its reach at the segment rate, telling its places once for an episode of several drops, and holds '
+ 'nothing with no later keyframe', () => {
const { at, buffer, trims } = rig(2000)
Expand Down Expand Up @@ -819,4 +849,66 @@ describe('cameraBuffer', () => {
expect([buffer.head?.time, buffer.ready]).toEqual([2000000, true])
})
})

describe('the wall clock a sample was taken at', () => {
it('keeps the duration a sample states beside the wall clock its stream states for it, while the sample is its run\'s newest', () => {
const { buffer, write } = rig(0)

write(Buffer.concat([
prft({ mediaTime: 0n, ntpTime: 0xEE9F800000000000n, trackId: TIER_STREAM_PICTURE }),
tierStreamFragment({
picture: [
{
...tierPicture({ keyframe: true }),
duration: 4500,
},
],
pictureTime: 0n,
}),
]), 2500)

const [stated] = buffer.samples

expect([
stated.duration,
Object.hasOwn(stated, 'wallClock'),
]).toEqual([4500, true])
})

it('reads the wall clock its stream states for a kept sample, and for one it states none the wall clock less the steady clock\'s time since it '
+ 'arrived, rounded to a whole millisecond', () => {
vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-12T00:00:10.000Z'))
vi.spyOn(performance, 'now').mockReturnValue(10000.6)

const { buffer, write } = rig(0)

// The box states 2026-11-12T00:00:00.000Z at the keyframe's decode time, an NTP time the producer reference time writer's vectors hold.
write(Buffer.concat([
prft({ mediaTime: 0n, ntpTime: 0xEE9F800000000000n, trackId: TIER_STREAM_PICTURE }),
tierStreamFragment({
picture: [
tierPicture({ keyframe: true }),
],
pictureTime: 0n,
}),
]), 2500.2)
write(tierStreamFragment({
picture: [
tierPicture(),
],
pictureTime: 3000n,
}), 7499.9)

const [stated, arrived] = buffer.samples

expect([stated, arrived].map(sample => Object.hasOwn(sample, 'wallClock'))).toEqual([true, false])
expect([
takenAt(stated),
takenAt(arrived),
]).toEqual([
Date.parse('2026-11-12T00:00:00.000Z'),
Date.parse('2026-11-12T00:00:07.499Z'),
])
})
})
})
Loading
Loading