From 9492f69b3f3082bc9057b11d441fac36aab86c35 Mon Sep 17 00:00:00 2001 From: HJD Date: Sun, 29 Nov 2026 09:33:37 -0600 Subject: [PATCH 1/4] feat(camera): date each recording and its clip by when the video was taken --- src/accessories/ModernCamera_example.ts | 6 +- src/lib/camera/RecordingManagement.spec.ts | 35 +++ src/lib/camera/RecordingManagement.ts | 14 +- src/lib/camera/StreamingOptions.ts | 16 +- src/lib/camera/TierTable.ts | 9 +- src/lib/camera/buffer/CameraBuffer.spec.ts | 65 ++++- src/lib/camera/buffer/CameraBuffer.ts | 69 +++-- src/lib/camera/mp4/Mp4StreamReader.spec.ts | 272 +++++++++++++++++- src/lib/camera/mp4/Mp4StreamReader.ts | 129 +++++++-- src/lib/camera/mp4/mp4Boxes.spec.ts | 56 ++++ src/lib/camera/mp4/mp4Boxes.ts | 70 ++++- .../camera/recording/BufferRecorder.spec.ts | 48 ++++ src/lib/camera/recording/BufferRecorder.ts | 70 +++-- .../recording/CMAFRecordingManagement.spec.ts | 98 +++++++ .../recording/CMAFRecordingManagement.ts | 20 +- .../recording/ProducerReferenceTimeWriter.ts | 14 +- src/lib/camera/recording/ServedRecording.ts | 15 +- .../camera/recording/clipPackaging.spec.ts | 16 +- src/lib/camera/recording/clipPackaging.ts | 7 +- src/lib/camera/recording/clipSealing.spec.ts | 51 +++- src/lib/camera/recording/clipSealing.ts | 59 +++- src/lib/util/ntp.spec.ts | 83 +++++- src/lib/util/ntp.ts | 40 ++- src/test-utils/cameraFixtures.ts | 26 +- src/test-utils/mp4Fixtures.ts | 14 +- 25 files changed, 1170 insertions(+), 132 deletions(-) diff --git a/src/accessories/ModernCamera_example.ts b/src/accessories/ModernCamera_example.ts index 4c6501525..2f32145bd 100644 --- a/src/accessories/ModernCamera_example.ts +++ b/src/accessories/ModernCamera_example.ts @@ -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 @@ -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(' ') } diff --git a/src/lib/camera/RecordingManagement.spec.ts b/src/lib/camera/RecordingManagement.spec.ts index 5ef860526..2214a9d9a 100644 --- a/src/lib/camera/RecordingManagement.spec.ts +++ b/src/lib/camera/RecordingManagement.spec.ts @@ -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() diff --git a/src/lib/camera/RecordingManagement.ts b/src/lib/camera/RecordingManagement.ts index 6f8e171bd..e250e70c8 100644 --- a/src/lib/camera/RecordingManagement.ts +++ b/src/lib/camera/RecordingManagement.ts @@ -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' @@ -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) @@ -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) { diff --git a/src/lib/camera/StreamingOptions.ts b/src/lib/camera/StreamingOptions.ts index 5470fe623..57028e30d 100644 --- a/src/lib/camera/StreamingOptions.ts +++ b/src/lib/camera/StreamingOptions.ts @@ -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 @@ -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 /** diff --git a/src/lib/camera/TierTable.ts b/src/lib/camera/TierTable.ts index 8eb1e577d..42c4eed76 100644 --- a/src/lib/camera/TierTable.ts +++ b/src/lib/camera/TierTable.ts @@ -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 diff --git a/src/lib/camera/buffer/CameraBuffer.spec.ts b/src/lib/camera/buffer/CameraBuffer.spec.ts index 41dc8764f..0faa36f2a 100644 --- a/src/lib/camera/buffer/CameraBuffer.spec.ts +++ b/src/lib/camera/buffer/CameraBuffer.spec.ts @@ -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, @@ -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 { takenAt, TierBuffer } from './CameraBuffer.js' const SENSOR_UUID = 'a1b2c3d4-0000-4000-8000-000000000001' @@ -819,4 +820,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'), + ]) + }) + }) }) diff --git a/src/lib/camera/buffer/CameraBuffer.ts b/src/lib/camera/buffer/CameraBuffer.ts index 37e614f86..8b5964731 100644 --- a/src/lib/camera/buffer/CameraBuffer.ts +++ b/src/lib/camera/buffer/CameraBuffer.ts @@ -8,7 +8,8 @@ import { decodable } from '../rtp/FrameCutter.js' /* The camera buffer: the recent samples of each running tier, kept as the stream reader hands them over and never copied, since a chunk a plugin writes * belongs to the library. Every comparison of times is made on the stream's own times, each track's decode times converted from its timescale to - * microseconds: picture and sound are compared on one scale and the arrival of a sample decides nothing but a jump. + * microseconds: picture and sound are compared on one scale and the arrival of a sample decides nothing but a jump. A sample's arrival also gives the + * wall clock a recording is stamped with, where the stream states none for it. */ // The keyframe allowance, which a buffer may reach back beyond its span for one late keyframe, and the rate a buffer's octets are bounded at over its @@ -62,6 +63,11 @@ export interface BufferedSample { * The moment the sample arrived, in milliseconds of the steady clock. */ readonly arrival: number + /** + * The wall clock the sample was taken at, in whole milliseconds since the Unix epoch, as its stream states it: present only where the stream reader + * handed the sample one. + */ + readonly wallClock?: number /** * The sample's decode time in whole microseconds, which the buffer compares its tracks on. */ @@ -694,24 +700,51 @@ export class TierBuffer { } } -// 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 and its -// place in the delivery order. +/** + * The wall clock a kept sample was taken at, in whole milliseconds since the Unix epoch: the one its stream states, or the wall clock less the steady + * clock's time since the sample arrived, each clock read at the call, which keeps the answer true across a step of the wall clock since the arrival. + * @param sample - The sample. + * @returns The wall clock. + */ +export function takenAt(sample: BufferedSample): number { + return sample.wallClock ?? (Date.now() - Math.round(performance.now() - sample.arrival)) +} + +// 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 { - const { compositionOffset, data, decodeTime, duration, sync, track } = sample - - return { - arrival: moment, - compositionOffset, - data, - decodeTime, - duration, - fragment, - order, - settled: false, - sync, - time: Number(decodeTime * MICROSECONDS / BigInt(track.timescale)), - track, - } + const { compositionOffset, data, decodeTime, duration, sync, track, wallClock } = sample + const time = Number(decodeTime * MICROSECONDS / BigInt(track.timescale)) + + return wallClock === undefined + ? { + arrival: moment, + compositionOffset, + data, + decodeTime, + duration, + fragment, + order, + settled: false, + sync, + time, + track, + } + : { + arrival: moment, + compositionOffset, + data, + decodeTime, + duration, + fragment, + order, + settled: false, + sync, + time, + track, + wallClock, + } } // Whether a sample jumps from its track's run: timed more than the limit ahead of the sample before it and the time since that one arrived. diff --git a/src/lib/camera/mp4/Mp4StreamReader.spec.ts b/src/lib/camera/mp4/Mp4StreamReader.spec.ts index 94ff6830c..c5fa2d324 100644 --- a/src/lib/camera/mp4/Mp4StreamReader.spec.ts +++ b/src/lib/camera/mp4/Mp4StreamReader.spec.ts @@ -4,7 +4,7 @@ import type { Mp4StreamAudioTrack, Mp4StreamConsumer, Mp4StreamSample, Mp4Stream import { Buffer } from 'node:buffer' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { avcC, @@ -17,6 +17,7 @@ import { mp4aSampleEntry, openBox, opusSampleEntry, + prft, sampleFragment, uint32, uint64, @@ -1048,6 +1049,275 @@ describe('mp4StreamReader', () => { 'end', ]) }) + + describe('a stream\'s stated time', () => { + // The NTP time of 2026-11-12T00:00:00.000Z, as the producer reference time writer's vectors hold it, and of the minute after it. + const STATED_NTP = 0xEE9F800000000000n + const MINUTE_LATER_NTP = STATED_NTP + (60n << 32n) + + // Each sample a reader handed on, its medium beside the wall clock it states in ISO text, or `none` for a sample that carries none. + function statedOf(samples: readonly Mp4StreamSample[]): [StreamTierMedium, string][] { + return samples.map(sample => [ + sample.track.medium, + Object.hasOwn(sample, 'wallClock') + ? new Date(sample.wallClock!).toISOString() + : 'none', + ]) + } + + // A keyframe and the picture after it, from a decode time on track 1. + function pictures(decodeTime: bigint): Buffer { + return videoFragment(decodeTime, picture(HEVC[0].slice(3), true), picture(HEVC[1])) + } + + it('states each sample of the fragment a box fronts at the wall clock of its own presentation time, picture and sound each on its own timescale, a ' + + 'picture with a composition offset among them, and nothing for the next fragment, which no box fronts', () => { + const fragment = sampleFragment( + { + decodeTime: 90000n, + samples: [ + { + ...picture(HEVC[0].slice(3), true), + compositionOffset: 12000, + }, + { + ...picture(HEVC[1]), + compositionOffset: 0, + }, + ], + trackId: 1, + }, + { + decodeTime: 48000n, + samples: [ + sound(1), + sound(2), + ], + trackId: 2, + }, + ) + // The box states its time at the keyframe's presentation time, 102000 ticks at 90 kHz. + const { samples } = read(INITIALIZATION, prft({ mediaTime: 102000n, ntpTime: STATED_NTP }), fragment, videoFragment(102000n, picture(HEVC[2]))) + + expect(statedOf(samples)).toEqual([ + ['video', '2026-11-12T00:00:00.000Z'], + ['video', '2026-11-11T23:59:59.933Z'], + ['audio', '2026-11-11T23:59:59.867Z'], + ['audio', '2026-11-11T23:59:59.887Z'], + ['video', 'none'], + ]) + }) + + it('times a fragment from a box naming the sound track on that track\'s timescale, picture and sound each stating the box\'s time at its own ' + + 'presentation time', () => { + const fragment = sampleFragment( + { + decodeTime: 90000n, + samples: [ + picture(HEVC[0].slice(3), true), + picture(HEVC[1]), + ], + trackId: 1, + }, + { + decodeTime: 48000n, + samples: [ + sound(1), + sound(2), + ], + trackId: 2, + }, + ) + // The box states its time on track 2 at the first sound's presentation time, 48000 ticks at 48 kHz, which is one second, as the keyframe's 90000 + // ticks at 90 kHz are. + const { samples } = read(INITIALIZATION, prft({ mediaTime: 48000n, ntpTime: STATED_NTP, trackId: 2 }), fragment) + + expect(statedOf(samples)).toEqual([ + ['video', '2026-11-12T00:00:00.000Z'], + ['video', '2026-11-12T00:00:00.067Z'], + ['audio', '2026-11-12T00:00:00.000Z'], + ['audio', '2026-11-12T00:00:00.020Z'], + ]) + }) + + it('hands each sample the duration its stream states and the wall clock its fragment\'s box states, each present only where it is stated: a duration ' + + 'and a wall clock, a wall clock alone, and neither', () => { + const { data, flags } = picture(HEVC[0].slice(3), true) + // Pictures that state their durations behind a box, then a picture that states none behind a box, then one that states none behind no box. + const { samples } = read( + INITIALIZATION, + prft({ mediaTime: 0n, ntpTime: STATED_NTP }), + pictures(0n), + prft({ mediaTime: 12000n, ntpTime: MINUTE_LATER_NTP }), + videoFragment(12000n, { data, flags }), + videoFragment(18000n, { data, flags }), + ) + + expect(samples.map(sample => [ + Object.hasOwn(sample, 'duration') + ? sample.duration + : 'none', + Object.hasOwn(sample, 'wallClock') + ? new Date(sample.wallClock!).toISOString() + : 'none', + ])).toEqual([ + [6000, '2026-11-12T00:00:00.000Z'], + [6000, '2026-11-12T00:00:00.067Z'], + ['none', '2026-11-12T00:01:00.000Z'], + ['none', 'none'], + ]) + }) + + it('reads a version 0 box\'s 32-bit media time true against a track whose decode times have passed 2^32 ticks', () => { + const { samples } = read(INITIALIZATION, prft({ mediaTime: 90000n, ntpTime: STATED_NTP, version: 0 }), pictures(2n ** 32n + 90000n)) + + expect(statedOf(samples)).toEqual([ + ['video', '2026-11-12T00:00:00.000Z'], + ['video', '2026-11-12T00:00:00.067Z'], + ]) + }) + + it('reads a box stating a time past the NTP era\'s wrap in the era of the wall clock now, the clock set past the wrap for the read', () => { + // 2040-01-01T00:00:00.000Z, past the wrap on 2036-02-07, and its NTP time, which a 64-bit field holds as its seconds since the wrap. + const pastWrap = Date.parse('2040-01-01T00:00:00.000Z') + const pastWrapNtp = 0x0754FD0000000000n + const clock = vi.spyOn(Date, 'now').mockReturnValue(pastWrap) + let samples: Mp4StreamSample[] + + try { + ({ samples } = read(INITIALIZATION, prft({ mediaTime: 0n, ntpTime: pastWrapNtp }), pictures(0n))) + } finally { + clock.mockRestore() + } + + expect(statedOf(samples)).toEqual([ + ['video', '2040-01-01T00:00:00.000Z'], + ['video', '2040-01-01T00:00:00.067Z'], + ]) + }) + + it('states nothing for a box naming a track the reader does not read, or one whose track has no sample in the fragment', () => { + const unread = read( + INITIALIZATION, + prft({ mediaTime: 0n, ntpTime: STATED_NTP, trackId: 3 }), + pictures(0n), + prft({ mediaTime: 0n, ntpTime: STATED_NTP, trackId: 2 }), + videoFragment(12000n, picture(HEVC[2])), + ) + const { consumer, samples } = logging() + const silent = new Mp4StreamReader(consumer, { sound: false }) + + silent.write(Buffer.concat([ + INITIALIZATION, + prft({ mediaTime: 48000n, ntpTime: STATED_NTP, trackId: 2 }), + sampleFragment( + { + decodeTime: 48000n, + samples: [ + sound(1), + ], + trackId: 2, + }, + { + decodeTime: 90000n, + samples: [ + picture(HEVC[0].slice(3), true), + ], + trackId: 1, + }, + ), + ])) + + expect(statedOf(unread.samples)).toEqual([ + ['video', 'none'], + ['video', 'none'], + ['video', 'none'], + ]) + expect(statedOf(samples)).toEqual([ + ['video', 'none'], + ]) + }) + + it('times a fragment by the latest box in front of it, another box between them changing nothing and a box it cannot read stating nothing', () => { + const { samples } = read( + INITIALIZATION, + prft({ mediaTime: 0n, ntpTime: MINUTE_LATER_NTP }), + prft({ mediaTime: 0n, ntpTime: STATED_NTP }), + box('free', Buffer.alloc(6)), + pictures(0n), + prft({ mediaTime: 12000n, ntpTime: STATED_NTP }), + fullBox('prft', 2, 24, uint32(1), uint64(STATED_NTP), uint64(12000n)), + videoFragment(12000n, picture(HEVC[2])), + ) + + expect(statedOf(samples)).toEqual([ + ['video', '2026-11-12T00:00:00.000Z'], + ['video', '2026-11-12T00:00:00.067Z'], + ['video', 'none'], + ]) + }) + + it('gives a moof that replaces a waiting one only the box read since that one, and drops a box waiting for its moof at an initialization segment and ' + + 'at a discontinuity', () => { + const [waiting] = boxesOf(pictures(0n)) + const replaced = read(INITIALIZATION, prft({ mediaTime: 0n, ntpTime: STATED_NTP }), waiting, pictures(0n)) + const restated = read(INITIALIZATION, prft({ mediaTime: 0n, ntpTime: MINUTE_LATER_NTP }), waiting, prft({ mediaTime: 0n, ntpTime: STATED_NTP }), pictures(0n)) + const described = read(INITIALIZATION, prft({ mediaTime: 0n, ntpTime: STATED_NTP }), INITIALIZATION, pictures(0n)) + const restarted = read(INITIALIZATION, prft({ mediaTime: 0n, ntpTime: STATED_NTP })) + + restarted.reader.discontinuity() + restarted.reader.write(pictures(0n)) + + expect([ + replaced, + restated, + described, + restarted, + ].map(({ samples }) => statedOf(samples))).toEqual([ + [ + ['video', 'none'], + ['video', 'none'], + ], + [ + ['video', '2026-11-12T00:00:00.000Z'], + ['video', '2026-11-12T00:00:00.067Z'], + ], + [ + ['video', 'none'], + ['video', 'none'], + ], + [ + ['video', 'none'], + ['video', 'none'], + ], + ]) + }) + + it('reads a fragment whose runs count their data past a box between its moof and its mdat, the box stating the next fragment\'s clock and not that ' + + 'one\'s', () => { + const between = prft({ mediaTime: 12000n, ntpTime: STATED_NTP }) + const [moof, mdat] = boxesOf(pictures(0n)).map(part => Buffer.from(part)) + const traf = walkBoxes(moof, 8).boxes.find(({ type }) => type === 'traf')! + const trun = walkBoxes(moof, traf.payload, traf.end).boxes.find(({ type }) => type === 'trun')! + + // The run's data offset, after its version, flags and sample count, counted on past the box between, as a muxer writing that box counts it. + moof.writeInt32BE(moof.readInt32BE(trun.payload + 8) + between.length, trun.payload + 8) + + const { handed, samples } = read(INITIALIZATION, moof, between, mdat, videoFragment(12000n, picture(HEVC[2]))) + + expect(handed.filter(step => (typeof step === 'object') && ('fail' in step))).toEqual([]) + expect(samples.map(({ data }) => data)).toEqual([ + tierFrameData(HEVC[0].slice(3)), + tierFrameData(HEVC[1]), + tierFrameData(HEVC[2]), + ]) + expect(statedOf(samples)).toEqual([ + ['video', 'none'], + ['video', 'none'], + ['video', '2026-11-12T00:00:00.000Z'], + ]) + }) + }) }) describe('the live path\'s frames', () => { diff --git a/src/lib/camera/mp4/Mp4StreamReader.ts b/src/lib/camera/mp4/Mp4StreamReader.ts index a26cbdecf..4ab0afd07 100644 --- a/src/lib/camera/mp4/Mp4StreamReader.ts +++ b/src/lib/camera/mp4/Mp4StreamReader.ts @@ -1,14 +1,16 @@ import type { TierFrame } from '../StreamingOptions.js' -import type { Mp4Box, Mp4BoxHeader, Mp4Sample, Mp4SampleDefaults, Mp4TrackBox } from './mp4Boxes.js' +import type { Mp4Box, Mp4BoxHeader, Mp4ProducerReferenceTime, Mp4Sample, Mp4SampleDefaults, Mp4TrackBox } from './mp4Boxes.js' import { Buffer } from 'node:buffer' import { counted } from '../../util/counted.js' +import { ntpSpan, wallClockOf } from '../../util/ntp.js' import { HEVC_PARAMETER_SETS, parameterSetsIn } from '../rtp/FrameCutter.js' import { FRAME_LENGTH_SIZE, HEVC_HEADER_LENGTH, HEVC_TYPE_MASK } from '../StreamingOptions.js' import { LARGE_HEADER_SIZE, readBoxHeader, + readProducerReferenceTime, readSampleDefaults, readTrackBoxEntry, readTrackBoxEntryBytes, @@ -121,6 +123,11 @@ export interface Mp4StreamSample { * Whether the sample is a sync sample, one decoded with nothing before it. */ readonly sync: boolean + /** + * The wall clock the sample was taken at, in whole milliseconds since the Unix epoch, as the `prft` box in front of its fragment states it: present only + * where that box states its fragment's clock. + */ + readonly wallClock?: number } /** @@ -175,11 +182,12 @@ interface ReaderMovie { readonly defaults: ReadonlyMap } -// A moof waiting for its mdat, read in place, with the offset from its first octet at which the next box starts. +// A moof waiting for its mdat, read in place, with the offset from its first octet at which the next box starts, and the prft box read in front of it. interface PendingFragment { data: Buffer moof: Mp4Box end: number + readonly stated?: Mp4ProducerReferenceTime } // One track's samples a fragment places in its mdat, each checked to lie inside it, and the next to hand on. @@ -189,10 +197,19 @@ interface ArrivingRun { next: number } -// A fragment's media as its mdat's octets arrive: each track's run of samples, and the offset of the mdat's first octet from the moof's. +// The clock a fragment's prft box states: the NTP time at its tracks' time zero, and the wall clock read as its media started, which settles the NTP era +// each of its samples' wall clocks is read in. +interface FragmentClock { + readonly origin: bigint + readonly near: number +} + +// A fragment's media as its mdat's octets arrive: each track's run of samples, the offset of the mdat's first octet from the moof's, and the clock the +// fragment's box states, absent where it states none. interface ArrivingMedia { readonly runs: readonly ArrivingRun[] readonly base: number + readonly clock?: FragmentClock } // What one step of the reading hands on, in the stream's order, once the step is done. @@ -215,6 +232,14 @@ const FRAGMENT_END: ReaderEvent = { kind: 'end' } * value: one that falls from the counter's upper half to its lower by more than half its range is read as that wrap, and its track's decode times run on * past it. The reader refuses no stream for a track it lacks: it hands on the tracks it finds, and its consumer refuses a stream that lacks one it needs. * What the reader cannot read fails the stream once, through the consumer's `fail` with a reason saying what was wrong, after which every chunk is ignored. + * + * A `prft` box states the clock of the next `moof` in the stream's order, wherever it stands, and of no other fragment: a later box replaces it, a `moof` + * that replaces a waiting one takes only the box read since that one, and a later initialization segment or a discontinuity drops a box waiting for its + * fragment. The box's NTP time stands at its media time, a presentation time on the track it names, read at its distance from that track's first sample + * in the fragment modulo 2^32, the short way round, which reads a 32-bit media time or decode time true past its wrap. Each sample of the fragment, + * picture and sound alike, then states the wall clock at its own presentation time, each track on its own timescale, in the NTP era nearest the moment + * the fragment's media started. A box naming a track the reader does not read, or one whose track has no sample in the fragment, states nothing, as no + * box does, and a box of a version the reader does not know or too short for its fields states nothing and fails nothing. */ export class Mp4StreamReader { private readonly consumer: Mp4StreamConsumer @@ -234,6 +259,8 @@ export class Mp4StreamReader { private type = '' private movie?: ReaderMovie private pending?: PendingFragment + // The prft box read since the last moof, whose clock the next moof takes. + private stated?: Mp4ProducerReferenceTime private media?: ArrivingMedia private failed = false @@ -288,14 +315,15 @@ export class Mp4StreamReader { } /** - * 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 each track's next sample opens a new run of decode times, a fragment with no decode time of its own counting from zero. Inside a fragment's media - * data, the samples already handed on stand and the rest of the box is dropped, with no end told for it, 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 each track's next sample opens a new run of decode times, a fragment with no decode time of its own + * counting from zero. Inside a fragment's media data, the samples already handed on stand and the rest of the box is dropped, with no end told for it, + * and the next chunk is read from a box's first octet. */ discontinuity(): void { this.release() this.pending = undefined + this.stated = undefined for (const track of this.movie?.tracks ?? []) { track.decodeTime = 0n @@ -317,6 +345,7 @@ export class Mp4StreamReader { this.failed = true this.release() this.pending = undefined + this.stated = undefined this.events.length = 0 this.consumer.fail(reason) } @@ -442,7 +471,8 @@ export class Mp4StreamReader { return end } - // Reads a whole box by its type: a moov for its tracks and a moof held for its mdat. An mdat read whole is one no moof describes, which is passed over. + // Reads a whole box by its type: a moov for its tracks, a moof held for its mdat and a prft held for the next moof. An mdat read whole is one no moof + // describes, which is passed over. private readWhole(box: Buffer, type: string, headerLength: number): void { switch (type) { case 'moov': @@ -459,7 +489,8 @@ export class Mp4StreamReader { throw new RangeError('The stream holds a fragment before any initialization segment.') } - // A moof arriving while another waits for its mdat replaces it. + // A moof arriving while another waits for its mdat replaces it, the replaced fragment's prft box going with it, and takes the prft box read since the + // moof before it. this.pending = { data: box, end: box.length, @@ -469,14 +500,26 @@ export class Mp4StreamReader { start: 0, type, }, + stated: this.stated, } + this.stated = undefined break case 'mdat': break default: - // Every other box is passed over, and one between a moof and its mdat moves the mdat away from the moof. + // Every other box is passed over, and one between a moof and its mdat moves the mdat away from the moof. A prft is held besides for the next moof, + // a later one replacing it, and one the box reader cannot read holds no clock. + if (type === 'prft') { + this.stated = readProducerReferenceTime(box, { + end: box.length, + payload: headerLength, + start: 0, + type, + }) + } + if (this.pending !== undefined) { this.pending.end += box.length } @@ -524,12 +567,14 @@ export class Mp4StreamReader { this.movie = { defaults, tracks: read } this.pending = undefined + this.stated = undefined this.events.push({ kind: 'tracks', tracks }) } /* Reads each track's samples the waiting moof places in the mdat whose header is read, each checked to lie inside the extent the mdat's header announces - * and to rise past the decode time before it in its track's run before any sample is handed on. A fragment the reader cannot read whole hands on - * nothing, however its octets arrive, and no consumer reads a sample timed at or before the one before it. An mdat no moof describes is passed over. + * and to rise past the decode time before it in its track's run before any sample is handed on, and fixes the clock the moof's prft box states, which + * the media carries until its end. A fragment the reader cannot read whole hands on nothing, however its octets arrive, and no consumer reads a sample + * timed at or before the one before it. An mdat no moof describes is passed over. */ private startMedia(): void { const { headerLength, movie, pending } = this @@ -570,6 +615,7 @@ export class Mp4StreamReader { this.media = { base: pending.end, + clock: clockOf(pending.stated, read), runs: read.map(({ samples, track }) => ({ next: 0, samples, track })), } } @@ -577,7 +623,7 @@ export class Mp4StreamReader { /* Hands on each sample of the arriving media whose octets have arrived with those of every sample before it, taking at each step the track whose next * sample the mdat places first: the samples go out in the mdat's order across the tracks and in each track's own order within it. */ - private readArrived({ base, runs }: ArrivingMedia): void { + private readArrived({ base, clock, runs }: ArrivingMedia): void { for (let run = nextRun(runs); run !== undefined; run = nextRun(runs)) { const sample = run.samples[run.next] const start = sample.offset - base @@ -590,7 +636,7 @@ export class Mp4StreamReader { run.next++ this.events.push({ kind: 'sample', - sample: sampleOf(this.octets(start, end), sample, run.track), + sample: sampleOf(this.octets(start, end), sample, run.track, clock), }) } } @@ -731,8 +777,57 @@ function rises(samples: readonly Mp4Sample[], last: bigint | undefined): boolean return true } -// A sample as the consumer takes it, beside its track's description, stating a duration only where the stream states one. -function sampleOf(data: Buffer, { compositionOffset, decodeTime, duration, sync }: Mp4Sample, { description }: ReaderTrack): Mp4StreamSample { +/* The clock a fragment's prft box states, fixed as its media starts: the box's NTP time stands at its media time on the track it names, a presentation time, + * read at its distance from the presentation time of that track's first sample in the fragment modulo 2^32, the short way round. A box fronts the fragment + * it times, and a fragment spans far less than half that range: a 32-bit media time, or a 32-bit decode time the reader carries past its wrap, reads true. + * A box naming a track the reader does not read, or one whose track has no sample in the fragment, states nothing, as no box does. + */ +function clockOf(stated: Mp4ProducerReferenceTime | undefined, read: readonly { samples: readonly Mp4Sample[], track: ReaderTrack }[]): FragmentClock | undefined { + if (stated === undefined) { + return undefined + } + + const named = read.find(({ track }) => track.description.id === stated.trackId) + const first = named?.samples[0] + + if ((named === undefined) || (first === undefined)) { + return undefined + } + + const presentation = first.decodeTime + BigInt(first.compositionOffset) + const mediaTime = presentation - BigInt.asIntN(32, presentation - stated.mediaTime) + + return { + near: Date.now(), + origin: stated.ntpTime - ntpSpan(mediaTime, BigInt(named.track.description.timescale)), + } +} + +// A sample as the consumer takes it, beside its track's description, stating a duration only where the stream states one, and the wall clock at its +// presentation time only where its fragment's box states a clock. Each shape is a literal of its own, which builds a sample once and leaves out a member +// it does not state rather than holding it undefined. +function sampleOf(data: Buffer, { compositionOffset, decodeTime, duration, sync }: Mp4Sample, { description }: ReaderTrack, clock?: FragmentClock): Mp4StreamSample { + if (clock === undefined) { + return duration === undefined + ? { + compositionOffset, + data, + decodeTime, + sync, + track: description, + } + : { + compositionOffset, + data, + decodeTime, + duration, + sync, + track: description, + } + } + + const wallClock = wallClockOf(clock.origin + ntpSpan(decodeTime + BigInt(compositionOffset), BigInt(description.timescale)), clock.near) + return duration === undefined ? { compositionOffset, @@ -740,6 +835,7 @@ function sampleOf(data: Buffer, { compositionOffset, decodeTime, duration, sync decodeTime, sync, track: description, + wallClock, } : { compositionOffset, @@ -748,6 +844,7 @@ function sampleOf(data: Buffer, { compositionOffset, decodeTime, duration, sync duration, sync, track: description, + wallClock, } } diff --git a/src/lib/camera/mp4/mp4Boxes.spec.ts b/src/lib/camera/mp4/mp4Boxes.spec.ts index 93729bfbc..d973211c4 100644 --- a/src/lib/camera/mp4/mp4Boxes.spec.ts +++ b/src/lib/camera/mp4/mp4Boxes.spec.ts @@ -18,6 +18,7 @@ import { mediaFragment, mp4aSampleEntry, openBox, + prft, sampleFragment, skeletonPackets, trun, @@ -26,6 +27,7 @@ import { visualSampleEntry, } from '../../../test-utils/mp4Fixtures.js' import { + readProducerReferenceTime, readSampleDefaults, readTrackBoxEntry, readTrackBoxEntryBytes, @@ -267,6 +269,60 @@ describe('mp4Boxes', () => { }) }) + describe('producer reference times', () => { + it('reads a prft box of either version, its media time from 32 bits in version 0 and 64 bits in version 1, beside its track and NTP time', () => { + const [first, second] = [ + prft({ + mediaTime: 0x89ABCDEFn, + ntpTime: 0xEE9F800000000000n, + trackId: 2, + version: 0, + }), + prft({ + mediaTime: 0x123456789ABCDEFn, + ntpTime: 0xFFFFFFFFFFBE76C8n, + trackId: 1, + version: 1, + }), + ] + + expect([first, second].map(packet => packet.length)).toEqual([28, 32]) + expect(readProducerReferenceTime(first, only(first, 'prft'))).toEqual({ + mediaTime: 0x89ABCDEFn, + ntpTime: 0xEE9F800000000000n, + trackId: 2, + version: 0, + }) + expect(readProducerReferenceTime(second, only(second, 'prft'))).toEqual({ + mediaTime: 0x123456789ABCDEFn, + ntpTime: 0xFFFFFFFFFFBE76C8n, + trackId: 1, + version: 1, + }) + }) + + it.each([ + [ + 'of version 2', + fullBox('prft', 2, 24, uint32(1), uint64(0xEE9F800000000000n), uint64(1234n)), + ], + [ + 'too short for its version', + box('prft', Buffer.alloc(3)), + ], + [ + 'of version 0 too short for its media time', + fullBox('prft', 0, 24, uint32(1), uint64(0xEE9F800000000000n), Buffer.alloc(3)), + ], + [ + 'of version 1 holding a 32-bit media time', + fullBox('prft', 1, 24, uint32(1), uint64(0xEE9F800000000000n), uint32(1234)), + ], + ])('reads nothing from a prft box %s, and throws nothing', (_name, packet) => { + expect(readProducerReferenceTime(packet, only(packet, 'prft'))).toBeUndefined() + }) + }) + describe('durations', () => { const NO_DEFAULTS = new Map() diff --git a/src/lib/camera/mp4/mp4Boxes.ts b/src/lib/camera/mp4/mp4Boxes.ts index 83ff381e8..82039b1db 100644 --- a/src/lib/camera/mp4/mp4Boxes.ts +++ b/src/lib/camera/mp4/mp4Boxes.ts @@ -111,6 +111,28 @@ export interface Mp4TrackFragment { duration?: bigint } +/** + * A producer reference time box, `prft`, as the box reader reads it: the NTP time that stands at a media time of one track. + */ +export interface Mp4ProducerReferenceTime { + /** + * The identifier of the track whose timescale the media time counts in. + */ + readonly trackId: number + /** + * The NTP time, a 64-bit value in 32.32 fixed point. + */ + readonly ntpTime: bigint + /** + * The media time the NTP time stands at, in the track's timescale: 32 bits in version 0 and 64 bits in version 1. + */ + readonly mediaTime: bigint + /** + * The box's version, which decides the width of its media time. + */ + readonly version: 0 | 1 +} + /** * A track's first sample entry, as its `stsd` box describes it. */ @@ -407,25 +429,37 @@ function childOf(data: Buffer, box: Mp4Box, type: string, children = childrenOf( return child } -// A full box's version, refused past 1, and the offset of its fields, refused when the payload is shorter than the fields a version holds. -function fieldsOf(data: Buffer, box: Mp4Box, lengths: readonly [number, number]): { offset: number, version: 0 | 1 } { +// A full box's version and the offset of its fields, or why they cannot be read: a payload too short for its version, a version past 1, or a payload +// shorter than the fields its version holds. +function readFields(data: Buffer, box: Mp4Box, lengths: readonly [number, number]): { offset: number, version: 0 | 1 } | { refusal: string } { if (box.end - box.payload < 4) { - throw new RangeError(`An MP4 ${box.type} box is too short for its version.`) + return { refusal: `An MP4 ${box.type} box is too short for its version.` } } const version = data.readUInt8(box.payload) if (version !== 0 && version !== 1) { - throw new RangeError(`An MP4 ${box.type} box has version ${version}, which the library does not read.`) + return { refusal: `An MP4 ${box.type} box has version ${version}, which the library does not read.` } } if (box.end - box.payload - 4 < lengths[version]) { - throw new RangeError(`An MP4 ${box.type} box is too short for its fields.`) + return { refusal: `An MP4 ${box.type} box is too short for its fields.` } } return { offset: box.payload + 4, version } } +// A full box's version, refused past 1, and the offset of its fields, refused when the payload is shorter than the fields a version holds. +function fieldsOf(data: Buffer, box: Mp4Box, lengths: readonly [number, number]): { offset: number, version: 0 | 1 } { + const fields = readFields(data, box, lengths) + + if ('refusal' in fields) { + throw new RangeError(fields.refusal) + } + + return fields +} + // The 24 bits of flags after a full box's version, read once the box is known to hold them. function flagsOf(data: Buffer, box: Mp4Box): number { return data.readUIntBE(box.payload + 1, 3) @@ -1074,6 +1108,32 @@ export function readTrackFragments(data: Buffer, moof: Mp4Box, trackDefaults?: R }) } +/** + * Reads a `prft` box by its own version: a track identifier and a 64-bit NTP time, then a media time of 32 bits in version 0 and of 64 bits in version 1. + * The reading answers and never throws, which is why a box the stream reader meets never fails the stream it reads. + * @param data - The buffer holding the box. + * @param prft - The `prft` box. + * @returns The box's track, NTP time, media time and version, or `undefined` for a version past 1 or a box too short for its version's fields. + */ +export function readProducerReferenceTime(data: Buffer, prft: Mp4Box): Mp4ProducerReferenceTime | undefined { + const fields = readFields(data, prft, [16, 20]) + + if ('refusal' in fields) { + return undefined + } + + const { offset, version } = fields + + return { + mediaTime: version === 1 + ? data.readBigUInt64BE(offset + 12) + : BigInt(data.readUInt32BE(offset + 12)), + ntpTime: data.readBigUInt64BE(offset + 4), + trackId: data.readUInt32BE(offset), + version, + } +} + /** * Reads one track's samples from a `moof` box: each sample's offset from the box's first octet, its size, decode time, duration where one has a source, and * composition offset, and whether it is a sync sample. A sample's size, duration and flags are its own in its `trun`, else the run's default in `tfhd`, else diff --git a/src/lib/camera/recording/BufferRecorder.spec.ts b/src/lib/camera/recording/BufferRecorder.spec.ts index 97f30c88c..748d2adf3 100644 --- a/src/lib/camera/recording/BufferRecorder.spec.ts +++ b/src/lib/camera/recording/BufferRecorder.spec.ts @@ -1158,6 +1158,54 @@ describe('bufferRecorder', () => { ]) }) + // Each NTP time is the writer's vector for 2026-11-12T00:00:00.000Z, the moment the row's first picture arrives, or five minutes before it. + it.each([ + [ + 'that opens on its prebuffer with the wall clock its first picture arrived at, and not the moment its first segment is written', + 0xEE9F800000000000n, + {}, + ], + [ + 'whose stream states its pictures\' wall clock with the wall clock it states', + 0xEE9F800000000000n - (300n << 32n), + { clock: 0xEE9F800000000000n - (300n << 32n) }, + ], + ] as const)('stamps a recording %s', async (_name, stamped, options) => { + vi.useFakeTimers({ + now: Date.parse('2026-11-12T00:00:00.000Z'), + toFake: [ + 'setTimeout', + 'clearTimeout', + 'performance', + 'Date', + ], + }) + + const opened = rig({ prebuffer: 2000 }) + const { camera } = opened + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 30, options) + vi.advanceTimersByTime(1000) + frames(stream, 30, 61, options) + // The hub opens the recording a second and a half after its prebuffer's newest picture, and the first segment leaves once the keyframe at the segment + // target from its first picture arrives. + vi.advanceTimersByTime(1500) + + const client = await DataStreamClient.connect(camera.recordingManagement!.dataStreamManagement) + + openRecording(client, 1) + await settle() + frames(stream, 61, 121, options) + await settle() + + const [, first] = client.events(Protocols.DATA_SEND, Topics.DATA).map(({ packets: [{ data }] }) => data as Buffer) + const prft = walkBoxes(first).boxes.find(({ type }) => type === 'prft')! + + expect(first.readBigUInt64BE(prft.start + 16)).toBe(stamped) + }) + it('records each sample of a stream stating 0 or half a step at the step to its track\'s next decode time, picture and sound, a run\'s newest sample ' + 'keeping its stated duration and one stating 0 the duration of the sample before it, a run\'s last sound ending no later than its last picture', async () => { const opened = rig() diff --git a/src/lib/camera/recording/BufferRecorder.ts b/src/lib/camera/recording/BufferRecorder.ts index c3272a6c6..728aaa56e 100644 --- a/src/lib/camera/recording/BufferRecorder.ts +++ b/src/lib/camera/recording/BufferRecorder.ts @@ -19,6 +19,7 @@ import { Buffer } from 'node:buffer' import { HDSProtocolError, HDSProtocolSpecificErrorReason } from '../../datastream/DataStreamServer.js' import { counted } from '../../util/counted.js' +import { takenAt } from '../buffer/CameraBuffer.js' import { debugChannel } from '../diagnostics/debugChannels.js' import { readSampleEntryBoxes } from '../mp4/mp4Boxes.js' import { segmentLength, writeKeyframeInitializationSegment, writeSegment } from '../mp4/mp4Writer.js' @@ -130,6 +131,17 @@ export interface BufferRecorderOptions { */ 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 + * producer reference time box is anchored at. The initialization segment and the end marker carry none. + */ +export interface RecorderPacket extends RecordingPacket { + /** + * The wall clock the segment's first picture was taken at, in whole milliseconds since the Unix epoch. + */ + readonly wallClock?: number +} + /** * 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 @@ -140,7 +152,7 @@ export type RecordingAdmission = { readonly reason: HDSProtocolSpecificErrorReason } | { readonly admitted: true - readonly serve: (signal?: AbortSignal) => AsyncIterable + readonly serve: (signal?: AbortSignal) => AsyncIterable } // The one refusal the recorder gives, as busy, whatever it declined the open for. @@ -242,7 +254,8 @@ function matches(carried: Mp4StreamTrack, track: Mp4StreamTrack | undefined): bo * on the recording, the picture's end on the sound's timescale: a sound standing there or after is left out, and the last sound carried ends no later, * since no later sample of the run follows it. 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. + * 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. */ class OpenRecording implements BufferPlace { keyframe?: BufferedSample @@ -254,7 +267,7 @@ class OpenRecording implements BufferPlace { // The sound the recording carries, absent for a recording without sound. private readonly audio?: Mp4StreamAudioTrack private readonly routes: RecordingRoutes - private readonly queue: Buffer[] = [] + private readonly queue: RecorderPacket[] = [] // How the recording ended, and whether its iterable ends with the end marker. private finished?: { readonly marked: boolean } // Resolves the wait of the recording's iterable for its next packet. @@ -282,7 +295,10 @@ class OpenRecording implements BufferPlace { this.routes = routes this.streamId = streamId this.keyframe = head - this.queue.push(writeKeyframeInitializationSegment({ audio, keyframe: head.data, video })) + this.queue.push({ + data: writeKeyframeInitializationSegment({ audio, keyframe: head.data, video }), + isLast: false, + }) } // Sends the segments the buffer already holds whole, once the recording has begun. @@ -387,7 +403,7 @@ class OpenRecording implements BufferPlace { * @param signal - The stream's signal, which a close aborts. * @yields Each packet. */ - async* packets(signal?: AbortSignal): AsyncGenerator { + async* packets(signal?: AbortSignal): AsyncGenerator { signal?.addEventListener('abort', () => this.wake?.(), { once: true }) for (;;) { @@ -395,10 +411,10 @@ class OpenRecording implements BufferPlace { return } - const data = this.queue.shift() + const packet = this.queue.shift() - if (data !== undefined) { - yield { data, isLast: false } + if (packet !== undefined) { + yield packet continue } @@ -562,12 +578,12 @@ class OpenRecording implements BufferPlace { ]) } - /* Writes a segment and queues it: its picture from the recording's own decode time on, each sample's duration the one the buffer settled, the distance - * to its track's next decode time, or for a run's lone sample that states none the last its track sent, and its sound placed against its opening - * keyframe on the stream's times, an unsettled sound lasting as its packet states and the last sound of a segment closed as it stands ending no later - * than the segment's end. A run's lone sound whose length nothing tells, neither the stream, its packet nor a sound sent before it, is dropped: every - * sound the recording writes lasts some time. The place moves to the next segment's keyframe, or waits for the next keyframe after a segment a run's end - * closed as it stands, and the recording ends after a segment any other end closes as it stands. + /* Writes a segment and queues it with the wall clock its first picture was taken at: its picture from the recording's own decode time on, each sample's + * duration the one the buffer settled, the distance to its track's next decode time, or for a run's lone sample that states none the last its track + * sent, and its sound placed against its opening keyframe on the stream's times, an unsettled sound lasting as its packet states and the last sound of a + * segment closed as it stands ending no later than the segment's end. A run's lone sound whose length nothing tells, neither the stream, its packet nor + * a sound sent before it, is dropped: every sound the recording writes lasts some time. The place moves to the next segment's keyframe, or waits for + * the next keyframe after a segment a run's end closed as it stands, and the recording ends after a segment any other end closes as it stands. */ private send({ end, next, overCap, pictures, sounds }: Segment): void { const [open] = pictures @@ -607,16 +623,20 @@ class OpenRecording implements BufferPlace { this.soundDuration = own } - this.queue.push(writeSegment({ - audio: (this.audio !== undefined) && (timed.length > 0) - ? { - decodeTime: timed[0].sound.decodeTime + offset, - samples: audio, - } - : undefined, - sequenceNumber: this.sequenceNumber++, - video: { decodeTime: pictureTime, samples: video }, - })) + this.queue.push({ + data: writeSegment({ + audio: (this.audio !== undefined) && (timed.length > 0) + ? { + decodeTime: timed[0].sound.decodeTime + offset, + samples: audio, + } + : undefined, + sequenceNumber: this.sequenceNumber++, + video: { decodeTime: pictureTime, samples: video }, + }), + isLast: false, + wallClock: takenAt(open), + }) // The segment is counted and its pictures' time taken together, once it is queued: the length the end reports is that of the segments it counts. this.pictureTime = pictureTime + BigInt(durations.reduce((total, duration) => total + duration, 0)) this.segments++ @@ -788,7 +808,7 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { } // 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 { + private serve({ head, start, tier, video }: AdmittedRecording, signal?: AbortSignal): AsyncIterable { const { policy, reporter, sensorUUID, started, tierId } = this.options const { streamId } = start const recording: OpenRecording = new OpenRecording(tier, video, head, { diff --git a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts index 0e4b74609..95511a98a 100644 --- a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts +++ b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts @@ -454,6 +454,20 @@ function body(camera: Pick, path: string, cameraKey: CameraK ]) } +// The start a clip's multivariant playlist states in its date line, opened under the content key of the Camera Key given, as the text it seals. +function startOf(camera: Pick, path: string, cameraKey: CameraKeyPayload = CAMERA_KEY): string { + const value = /^#EXT-X-SESSION-DATA:DATA-ID="com\.apple\.encrypted-datetime\.timestamp",VALUE="([^"]+)"$/m.exec(body(camera, path).toString())![1] + const { ciphertext, iv, tag } = JSON.parse(Buffer.from(value, 'base64').toString('utf8')) as Record + const decipher = createDecipheriv('aes-256-gcm', contentKeyOf(cameraKey).key, Buffer.from(iv, 'base64'), { authTagLength: 16 }) + + decipher.setAuthTag(Buffer.from(tag, 'base64')) + + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, 'base64')), + decipher.final(), + ]).toString('utf8') +} + // A mock's answers by path: each path's sends answered in turn from its list, and 201 once a list runs out. function answers(script: Readonly>): (request: MockIngestRequest) => MockIngestAnswer { const sends = new Map() @@ -1373,6 +1387,90 @@ describe('cMAFRecordingManagement', () => { expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) }) + it('states each clip\'s start, sealed, in its multivariant playlist\'s date line after the session key line: the wall clock that placed the recording ' + + 'for a clip from its first fragment, and that wall clock and the durations before it for a clip from a later fragment', async () => { + await using camera = await clipCamera() + + serve(camera, 3) + await judge(camera, 0) + + const first = await startAt(camera, placeOf(camera, 0)) + + await stopAt(camera, endOf(camera, 0)) + + expect((await ended(camera, first)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + + await judge(camera, 1) + await judge(camera, 2) + + const later = await startAt(camera, placeOf(camera, 2), SESSION + 1n) + + await stopAt(camera, endOf(camera, 2), BufferUploadStopAction.FINALIZE, SESSION + 1n) + + expect((await ended(camera, later)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(body(camera, `session_${first}/index.m3u8`).toString()) + .toMatch(/\n#EXT-X-SESSION-KEY:[^\n]+\n#EXT-X-SESSION-DATA:DATA-ID="com\.apple\.encrypted-datetime\.timestamp",VALUE="[^"\n]+"\n\n#EXT-X-STREAM-INF:/) + // The later clip starts at fragment 2, past every fragment before it, each lasting its samples' durations at 90 kHz, ninety ticks a millisecond. + expect([ + startOf(camera, `session_${first}/index.m3u8`), + startOf(camera, `session_${later}/index.m3u8`), + ]).toEqual([ + new Date(WALL_CLOCK).toISOString(), + new Date(WALL_CLOCK + 2 * SAMPLES * SAMPLE_DURATION / 90).toISOString(), + ]) + }) + + it('states the clip\'s first fragment\'s wall clock in a multivariant playlist it sends again after a 208, later fragments read by then, as in the ' + + 'playlist the 208 answered', async () => { + // The 208 arrives once the later fragments are read, which makes the playlist the clip sends again one sent with those fragments read. + await using camera = await clipCamera({ + answer: answers({ + 'session_1/index.m3u8': [ + { delay: 300, status: 208 }, + ], + }), + }) + + serve(camera, 3) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await judge(camera, 1) + await judge(camera, 2) + await stopAt(camera, endOf(camera, 2)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(2n, 3)) + expect([ + startOf(camera, 'session_1/index.m3u8'), + startOf(camera, 'session_2/index.m3u8'), + ]).toEqual([ + new Date(WALL_CLOCK).toISOString(), + new Date(WALL_CLOCK).toISOString(), + ]) + }) + + it('states the wall clock past the NTP era\'s wrap that placed a clip\'s recording as the clip\'s start, the wall clock now in that era', async () => { + // 2040-01-01T00:00:00.000Z, past the wrap on 2036-02-07. The clock is set there only once the camera's certificate is issued, because the mock + // publishing point's TLS reads the certificate's dates against the system's own clock. + const pastWrap = Date.parse('2040-01-01T00:00:00.000Z') + + await using camera = await clipCamera() + + vi.spyOn(Date, 'now').mockReturnValue(pastWrap) + begin(camera, pastWrap) + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await stopAt(camera, endOf(camera, 0)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(startOf(camera, `session_${clipID}/index.m3u8`)).toBe(new Date(pastWrap).toISOString()) + }) + it.each([ [ 'no Camera Key', diff --git a/src/lib/camera/recording/CMAFRecordingManagement.ts b/src/lib/camera/recording/CMAFRecordingManagement.ts index 37b5790b3..2b395b421 100644 --- a/src/lib/camera/recording/CMAFRecordingManagement.ts +++ b/src/lib/camera/recording/CMAFRecordingManagement.ts @@ -32,6 +32,7 @@ import { DisposableStack } from '../../util/disposableStack.js' import { errorMessage } from '../../util/errors.js' import { HapStatusError } from '../../util/hapStatusError.js' import { libraryVersion } from '../../util/libraryVersion.js' +import { distance, wallClockOf } from '../../util/ntp.js' import { BufferActivity, BufferEventCommandType, @@ -77,9 +78,9 @@ import { segmentPath, sessionFolder, } from './clipPackaging.js' -import { contentKeyOf, keyAttributes, seal, SEALING_OVERHEAD } from './clipSealing.js' +import { contentKeyOf, keyAttributes, seal, SEALING_OVERHEAD, sealStart } from './clipSealing.js' import { IngestError, IngestSession, parsePublishingPointURL } from './IngestSession.js' -import { distance, SERVED_RECORDING_GRACE } from './ServedRecording.js' +import { SERVED_RECORDING_GRACE } from './ServedRecording.js' import { createSigningRequest } from './signingRequest.js' const CMAF_RECORDING_DEBUG = debugChannel('HAP-NodeJS:Camera:CMAFRecording') @@ -822,8 +823,8 @@ class ClipSession { return await sessionEnd(session) } - // The bytes, content type, headers and path of an object: each media segment sealed under the clip's content key, each playlist naming that key, and - // the initialization segment as the camera served it. + // The bytes, content type, headers and path of an object: each media segment sealed under the clip's content key, each playlist naming that key, the + // multivariant playlist stating the clip's start sealed under it, and the initialization segment as the camera served it. private payload(object: ClipObject): { body: Uint8Array, contentType: string, headers?: Record, path: string } { const { contentKey } = this.identity @@ -833,12 +834,13 @@ class ClipSession { ...this.requested, ...this.pending, ] - const { run } = this.requested[0] + const { fragment: first, run } = this.requested[0] const video = run.sampleEntries.get(run.video.id) // Each segment's bit rate counts it as sent, sealing's IV and tag around its bytes. const { average, peak } = bandwidthsOf(reads.map(({ fragment, seconds }) => ({ bytes: fragment.bytes.length + SEALING_OVERHEAD, seconds }))) + // The clip starts at the wall clock of its first fragment's place on the hub's timeline, the place read in the NTP era nearest the wall clock now. return { body: new TextEncoder().encode(multivariantPlaylist({ average, @@ -848,6 +850,7 @@ class ClipSession { resolution: video?.width === undefined || video.height === undefined ? undefined : { height: video.height, width: video.width }, + sealedStart: sealStart(contentKey, wallClockOf(first.place, Date.now())), })), contentType: CONTENT_TYPES.playlist, path: MULTIVARIANT_PLAYLIST, @@ -1028,9 +1031,10 @@ class ClipSession { * its recording served, a hub's Start for a recording already served opening a clip meanwhile. * * A clip's video and audio are always encrypted: each media segment uploads sealed under the content key of the Camera Key the clip opened with, while its - * initialization segment and its playlists upload readable, each playlist naming that key. A camera holding no Camera Key, or one no content key derives - * from, refuses every Start that would open a clip, with an upload-refused problem saying why at the first such refusal and again at most once per - * interval while they go on. A clip already open keeps the key it opened with. + * initialization segment and its playlists upload readable, each playlist naming that key and the multivariant playlist stating the clip's start, the + * wall clock of its first fragment's place, sealed under it. A camera holding no Camera Key, or one no content key derives from, refuses every Start that + * would open a clip, with an upload-refused problem saying why at the first such refusal and again at most once per interval while they go on. A clip + * already open keeps the key it opened with. */ export class CMAFRecordingManagement { /** diff --git a/src/lib/camera/recording/ProducerReferenceTimeWriter.ts b/src/lib/camera/recording/ProducerReferenceTimeWriter.ts index 5686f730f..180dfca4a 100644 --- a/src/lib/camera/recording/ProducerReferenceTimeWriter.ts +++ b/src/lib/camera/recording/ProducerReferenceTimeWriter.ts @@ -2,7 +2,7 @@ import type { Mp4Box, Mp4SampleEntry, Mp4Track, Mp4TrackBox, Mp4TrackFragment } import { Buffer } from 'node:buffer' -import { NTP_FRACTION_BITS, ntpTime } from '../../util/ntp.js' +import { ntpSpan, ntpTime } from '../../util/ntp.js' import { readTrackBoxEntry, readTrackBoxes, readTrackDefaults, readTrackFragments, readVideoTrackBox, walkBoxes } from '../mp4/mp4Boxes.js' /** @@ -114,8 +114,8 @@ function sampleEntriesOf(packet: Buffer, trackBoxes: readonly Mp4TrackBox[]): Ma /** * Writes a producer reference time box before each media fragment of one recording stream, the box a hub reads the recording's clock from. The video * track and its timescale come from the latest initialization segment. The clock is one anchor plus each fragment's decode time: the anchor is the wall - * clock at the stream's first stamped fragment less that fragment's decode time, and every later box counts on from the first by the recording's own - * timeline. + * clock handed with the stream's first stamped fragment, the one its first picture is stamped at, less that fragment's decode time, and every later box + * counts on from the first by the recording's own timeline. * * A packet holding no boxes, the one-byte end marker among them, or boxes holding neither an initialization segment nor a fragment, goes out as it came. * Every other packet the writer cannot place a box in, or time, is refused with an error naming the contract it breaks. @@ -133,7 +133,8 @@ export class ProducerReferenceTimeWriter { /** * Answers the packet to send in place of one the recording yielded. * @param packet - The packet as the delegate yielded it. - * @param wallClock - The wall clock in milliseconds since the Unix epoch, which only the stream's first stamped fragment uses. + * @param wallClock - The wall clock the packet's first picture is stamped at, in whole milliseconds since the Unix epoch, which only the stream's first + * stamped fragment uses. * @returns The packet with a `prft` box written immediately before each `moof` box, or the packet itself. * @throws Error naming the contract a packet breaks: a fragment before any initialization segment, one with no decode time for the video track, an * initialization segment with no video track, or boxes that cannot be read. @@ -145,7 +146,8 @@ export class ProducerReferenceTimeWriter { /** * Writes a packet as {@link write} does and answers what its walk read beside the bytes to send. * @param packet - The packet as the delegate yielded it. - * @param wallClock - The wall clock in milliseconds since the Unix epoch, which only the stream's first stamped fragment uses. + * @param wallClock - The wall clock the packet's first picture is stamped at, in whole milliseconds since the Unix epoch, which only the stream's first + * stamped fragment uses. * @returns The bytes to send, and the initialization segment and fragments they hold; a packet passed as it came carries no reading. * @throws Error naming the contract a packet breaks, as {@link write} does. */ @@ -257,7 +259,7 @@ export class ProducerReferenceTimeWriter { throw new Error(CONTRACT_ERRORS.untimeable) } - const elapsed = (decodeTime << NTP_FRACTION_BITS) / video.timescale + const elapsed = ntpSpan(decodeTime, video.timescale) this.anchor ??= ntpTime(wallClock) - elapsed diff --git a/src/lib/camera/recording/ServedRecording.ts b/src/lib/camera/recording/ServedRecording.ts index 72e7d281c..79167495b 100644 --- a/src/lib/camera/recording/ServedRecording.ts +++ b/src/lib/camera/recording/ServedRecording.ts @@ -4,7 +4,7 @@ import type { CameraReporter, DebugWriter } from '../diagnostics/CameraReporter. import type { Mp4SampleEntry, Mp4Track } from '../mp4/mp4Boxes.js' import type { WrittenPacket } from './ProducerReferenceTimeWriter.js' -import { NTP_FRACTION_BITS } from '../../util/ntp.js' +import { distance, ntpSpan } from '../../util/ntp.js' import { debugChannel } from '../diagnostics/debugChannels.js' const SERVED_RECORDING_DEBUG = debugChannel('HAP-NodeJS:Camera:ServedRecording') @@ -79,17 +79,6 @@ export interface ServedFragment { readonly bytes?: Buffer } -/** - * Serial arithmetic modulo 2^64: the signed distance from one place on the hub's timeline to another. A span across the NTP era's wrap reads as the - * short way round. - * @param from - The place the distance is read from. - * @param to - The place the distance is read to. - * @returns The distance, negative when `to` lies before `from`. - */ -export function distance(from: bigint, to: bigint): bigint { - return BigInt.asIntN(64, BigInt.asUintN(64, to) - from) -} - /** * One reader of a served recording: an async iterable of its fragments from an index, as they arrive, which ends at the recording's end, at a fragment * whose bytes are released, or at the reader's end. Until its clip ends it, the reader keeps every fragment from its start it has not reported sent. @@ -305,7 +294,7 @@ export class ServedRecording { } const place = this.next ?? ntpTime - const duration = (timescaleDuration << NTP_FRACTION_BITS) / BigInt(video.timescale) + const duration = ntpSpan(timescaleDuration, BigInt(video.timescale)) this.fragments.push({ bytes, diff --git a/src/lib/camera/recording/clipPackaging.spec.ts b/src/lib/camera/recording/clipPackaging.spec.ts index 0b65ffcbb..d9f266675 100644 --- a/src/lib/camera/recording/clipPackaging.spec.ts +++ b/src/lib/camera/recording/clipPackaging.spec.ts @@ -19,8 +19,12 @@ import { ProducerReferenceTimeWriter } from './ProducerReferenceTimeWriter.js' const KEY = 'METHOD=AES-256-GCM,URI="hksv3:10004000.key"' +// A sealed start as the packaging takes it, base64 text it writes as given. +const SEALED_START = 'c2VhbGVkIHN0YXJ0' + describe('clipPackaging', () => { - it('writes the multivariant playlist with its session key line, naming the one rendition with its bit rates, picture and codecs, leaving out any it lacks', () => { + it('writes the multivariant playlist with its session key line and its date line after it, naming the one rendition with its bit rates, picture and ' + + 'codecs, leaving out any it lacks', () => { const [named, partial] = [ multivariantPlaylist({ average: 400000, @@ -28,14 +32,21 @@ describe('clipPackaging', () => { keyAttributes: KEY, peak: 450000, resolution: { height: 1080, width: 1920 }, + sealedStart: SEALED_START, + }), + multivariantPlaylist({ + average: 1, + keyAttributes: KEY, + peak: 2, + sealedStart: SEALED_START, }), - multivariantPlaylist({ average: 1, keyAttributes: KEY, peak: 2 }), ] const header = [ '#EXTM3U', '#EXT-X-VERSION:7', '#EXT-X-INDEPENDENT-SEGMENTS', `#EXT-X-SESSION-KEY:${KEY}`, + `#EXT-X-SESSION-DATA:DATA-ID="com.apple.encrypted-datetime.timestamp",VALUE="${SEALED_START}"`, '', ] @@ -181,6 +192,7 @@ describe('clipPackaging', () => { codecs: codecsOf(initialization!.sampleEntries.values()), keyAttributes: KEY, peak: 450000, + sealedStart: SEALED_START, })).toContain('#EXT-X-STREAM-INF:BANDWIDTH=450000,AVERAGE-BANDWIDTH=400000,CODECS="hvc1.1.6.L120.90,mp4a.40.2"\n') }) diff --git a/src/lib/camera/recording/clipPackaging.ts b/src/lib/camera/recording/clipPackaging.ts index 7a2ea5d1e..9aa34e8ab 100644 --- a/src/lib/camera/recording/clipPackaging.ts +++ b/src/lib/camera/recording/clipPackaging.ts @@ -157,7 +157,7 @@ export function bandwidthsOf(segments: Iterable<{ bytes: number, seconds: number } /** - * The multivariant playlist, naming the one rendition. + * The multivariant playlist, naming the one rendition and stating the clip's start, sealed, in its date line. * @param options - The rendition's attributes. * @param options.average - Its average bit rate. * @param options.codecs - Its codecs, left out when absent. @@ -166,14 +166,16 @@ export function bandwidthsOf(segments: Iterable<{ bytes: number, seconds: number * @param options.resolution - Its picture's size, left out when absent. * @param options.resolution.height - The picture's height in pixels. * @param options.resolution.width - The picture's width in pixels. + * @param options.sealedStart - The clip's start sealed under its content key, which the date line after the session key line carries. * @returns The playlist, every line ending in a newline. */ -export function multivariantPlaylist({ average, codecs, keyAttributes, peak, resolution }: { +export function multivariantPlaylist({ average, codecs, keyAttributes, peak, resolution, sealedStart }: { average: number codecs?: string keyAttributes: string peak: number resolution?: { height: number, width: number } + sealedStart: string }): string { const attributes = [ `BANDWIDTH=${peak}`, @@ -191,6 +193,7 @@ export function multivariantPlaylist({ average, codecs, keyAttributes, peak, res '#EXT-X-VERSION:7', '#EXT-X-INDEPENDENT-SEGMENTS', `#EXT-X-SESSION-KEY:${keyAttributes}`, + `#EXT-X-SESSION-DATA:DATA-ID="com.apple.encrypted-datetime.timestamp",VALUE="${sealedStart}"`, '', `#EXT-X-STREAM-INF:${attributes.join(',')}`, MEDIA_PLAYLIST, diff --git a/src/lib/camera/recording/clipSealing.spec.ts b/src/lib/camera/recording/clipSealing.spec.ts index b5c095e45..68ae84f2a 100644 --- a/src/lib/camera/recording/clipSealing.spec.ts +++ b/src/lib/camera/recording/clipSealing.spec.ts @@ -3,7 +3,7 @@ import { createDecipheriv } from 'node:crypto' import { describe, expect, it } from 'vitest' -import { contentKeyOf, keyAttributes, seal } from './clipSealing.js' +import { contentKeyOf, keyAttributes, seal, sealStart } from './clipSealing.js' // A Camera Key of the bytes 0 to 31 and key number 0x1000. The content key was recomputed through WebCrypto's HKDF, independently of the module's. const CAMERA_KEY = { @@ -43,6 +43,55 @@ describe('clipSealing', () => { expect(seal(contentKey, segment).subarray(0, 16)).not.toEqual(seal(contentKey, segment).subarray(0, 16)) }) + it('seals a clip\'s start as the base64 of a JSON object of its method, IV, ciphertext, tag and key identifier in that order, its ciphertext opening ' + + 'under the content key to the start\'s ISO text, and its key identifier the one the key\'s address names', () => { + const contentKey = contentKeyOf(CAMERA_KEY) + const value = sealStart(contentKey, Date.parse('2026-11-12T00:00:05.321Z')) + const line = JSON.parse(Buffer.from(value, 'base64').toString('utf8')) as Record + const decipher = createDecipheriv('aes-256-gcm', contentKey.key, Buffer.from(line.iv, 'base64'), { authTagLength: 16 }) + + decipher.setAuthTag(Buffer.from(line.tag, 'base64')) + + // Each base64 text is the standard alphabet with its padding, which reads back as itself. + for (const text of [ + value, + line.iv, + line.ciphertext, + line.tag, + ]) { + expect(Buffer.from(text, 'base64').toString('base64')).toBe(text) + } + + expect(Object.keys(line)).toEqual([ + 'method', + 'iv', + 'ciphertext', + 'tag', + 'kid', + ]) + expect(line.method).toBe('AES-256-GCM') + expect([line.iv, line.tag].map(text => Buffer.from(text, 'base64').length)).toEqual([16, 16]) + expect(Buffer.concat([ + decipher.update(Buffer.from(line.ciphertext, 'base64')), + decipher.final(), + ]).toString('utf8')).toBe('2026-11-12T00:00:05.321Z') + expect(keyAttributes(contentKey)).toBe(`METHOD=AES-256-GCM,URI="hksv3:${line.kid}.key"`) + expect(line.kid).toBe('10004000') + expect(sealStart(contentKey, Date.parse('2026-11-12T00:00:05.321Z'))).not.toBe(value) + }) + + it('names a key whose identifier holds letters in lowercase, in a sealed start\'s key identifier and in the key\'s address alike', () => { + const contentKey = contentKeyOf({ + ...CAMERA_KEY, + keyNumber: 0xABCDEFn, + }) + const line = JSON.parse(Buffer.from(sealStart(contentKey, Date.parse('2026-11-12T00:00:05.321Z')), 'base64').toString('utf8')) as Record + + expect(contentKey.identifier).toBe(0xABCDEF4000n) + expect(line.kid).toBe('abcdef4000') + expect(keyAttributes(contentKey)).toBe('METHOD=AES-256-GCM,URI="hksv3:abcdef4000.key"') + }) + it.each([ [ 'a key of 31 bytes', diff --git a/src/lib/camera/recording/clipSealing.ts b/src/lib/camera/recording/clipSealing.ts index 62db64eff..3fd192ed0 100644 --- a/src/lib/camera/recording/clipSealing.ts +++ b/src/lib/camera/recording/clipSealing.ts @@ -13,13 +13,16 @@ const TAG_LENGTH = 16 const KEY_NUMBER_LIMIT = 2n ** 48n const CONTENT_KEY_TAG = 0x4000n +// The method a key line and a sealed start each name. +const METHOD = 'AES-256-GCM' + /** * The bytes sealing adds to a media segment: its IV before the ciphertext and its tag after. */ export const SEALING_OVERHEAD = IV_LENGTH + TAG_LENGTH /** - * The key a clip's media segments are sealed under, and the identifier its playlists name it by. + * The key a clip's media segments and its stated start are sealed under, and the identifier its playlists name it by. */ export interface ContentKey { /** @@ -61,7 +64,7 @@ export function contentKeyOf(cameraKey: CameraKeyPayload): ContentKey { * @returns The method and the key's address, its identifier in lowercase hexadecimal. */ export function keyAttributes(contentKey: ContentKey): string { - return `METHOD=AES-256-GCM,URI="hksv3:${contentKey.identifier.toString(16)}.key"` + return `METHOD=${METHOD},URI="hksv3:${identifierOf(contentKey)}.key"` } /** @@ -71,13 +74,55 @@ export function keyAttributes(contentKey: ContentKey): string { * @returns A fresh random 16-byte IV, the AES-256-GCM ciphertext of the segment with no additional data, and the 16-byte tag. */ export function seal(contentKey: ContentKey, segment: Uint8Array): Buffer { - const iv = randomBytes(IV_LENGTH) - const cipher = createCipheriv('aes-256-gcm', contentKey.key, iv, { authTagLength: TAG_LENGTH }) + const { ciphertext, iv, tag } = sealed(contentKey, segment) return Buffer.concat([ iv, - cipher.update(segment), - cipher.final(), - cipher.getAuthTag(), + ...ciphertext, + tag, ]) } + +/** + * Seals a clip's start under its content key as the value of the date line its multivariant playlist carries: the start's ISO 8601 text in UTC, sealed as + * {@link seal} seals a segment, its IV, ciphertext and tag each in standard base64 inside a JSON object that names the method and the key. + * @param contentKey - The clip's content key. + * @param start - The clip's start, in whole milliseconds since the Unix epoch. + * @returns The standard base64 of the object as UTF-8, its members `method`, `iv`, `ciphertext`, `tag` and `kid` in that order, `kid` the key's + * identifier as {@link keyAttributes} writes it in the key's address. + */ +export function sealStart(contentKey: ContentKey, start: number): string { + const { ciphertext, iv, tag } = sealed(contentKey, Buffer.from(new Date(start).toISOString(), 'utf8')) + + // The members stand in the order the date line's format names them, which is why they are not sorted. + return Buffer.from(JSON.stringify({ + method: METHOD, + iv: iv.toString('base64'), + ciphertext: Buffer.concat(ciphertext).toString('base64'), + tag: tag.toString('base64'), + kid: identifierOf(contentKey), + }), 'utf8').toString('base64') +} + +// The key's identifier as its address and a sealed start name it, in lowercase hexadecimal. +function identifierOf(contentKey: ContentKey): string { + return contentKey.identifier.toString(16) +} + +/* A plaintext sealed whole under a clip's content key: a fresh random 16-byte IV, the AES-256-GCM ciphertext with no additional data in the parts the + * cipher gave it, and the 16-byte tag. The parts stay apart, which is why a sealed segment's bytes are copied once, into the buffer that holds them. + */ +function sealed(contentKey: ContentKey, plaintext: Uint8Array): { ciphertext: readonly Buffer[], iv: Buffer, tag: Buffer } { + const iv = randomBytes(IV_LENGTH) + const cipher = createCipheriv('aes-256-gcm', contentKey.key, iv, { authTagLength: TAG_LENGTH }) + const ciphertext = [ + cipher.update(plaintext), + cipher.final(), + ] + + return { + ciphertext, + iv, + tag: cipher.getAuthTag(), + } +} diff --git a/src/lib/util/ntp.spec.ts b/src/lib/util/ntp.spec.ts index 46f192917..2b7334a44 100644 --- a/src/lib/util/ntp.spec.ts +++ b/src/lib/util/ntp.spec.ts @@ -2,7 +2,7 @@ import { Buffer } from 'node:buffer' import { describe, expect, it } from 'vitest' -import { ntpTime } from './ntp.js' +import { ntpSpan, ntpTime, wallClockOf } from './ntp.js' // The eight bytes of a 64-bit NTP field holding a value, reduced modulo 2^64 as a writer reduces it, in hexadecimal. function field(value: bigint): string { @@ -72,3 +72,84 @@ describe('ntpTime', () => { } }) }) + +describe('wallClockOf', () => { + // Each NTP field is one the vectors above hold or one beside the era's wrap, read nearest a wall clock hours away from the time it names. + it.each([ + [ + 'at whole seconds', + 0xEE9F800000000000n, + '2026-11-12T08:00:00.000Z', + '2026-11-12T00:00:00.000Z', + ], + [ + 'with the fraction the writer floored', + 0xEE9F800000C49BA5n, + '2026-11-11T20:00:00.000Z', + '2026-11-12T00:00:00.003Z', + ], + [ + 'past the era\'s wrap, from a wall clock before it', + 0x0000000080000000n, + '2036-02-07T04:00:00.000Z', + '2036-02-07T06:28:16.500Z', + ], + [ + 'before the era\'s wrap, from a wall clock past it', + 0xFFFFFFFFFFBE76C8n, + '2036-02-07T09:00:00.000Z', + '2036-02-07T06:28:15.999Z', + ], + ])('reads an NTP time %s as the wall clock it names nearest the one given', (_name, ntp, near, expected) => { + expect(new Date(wallClockOf(ntp, Date.parse(near))).toISOString()).toBe(expected) + }) + + it('reads the NTP time of a whole millisecond back as that millisecond, from a wall clock before it and after it, and across the era\'s wrap', () => { + const readings = [ + Date.parse('2026-11-12T00:00:00.000Z'), + Date.parse('2026-11-12T00:00:00.001Z'), + Date.parse('2026-11-12T00:00:00.003Z'), + Date.parse('2026-11-12T00:00:05.321Z'), + Date.parse('2026-11-12T00:00:39.999Z'), + Date.parse('2036-02-07T06:28:15.999Z'), + Date.parse('2036-02-07T06:28:16.000Z'), + Date.parse('2036-02-07T06:28:16.001Z'), + ] + // Each reading is read from a wall clock a span before it and the same span after it, the spans running from a millisecond to years. + const spans = [ + 1, + 7, + 5321, + 40000, + 3 * 60 * 60 * 1000, + 20 * 365 * 24 * 60 * 60 * 1000, + ] + + for (const reading of readings) { + for (const near of spans.flatMap(span => [reading - span, reading + span])) { + expect({ + near, + read: wallClockOf(BigInt.asUintN(64, ntpTime(reading)), near), + }).toEqual({ near, read: reading }) + } + } + }) +}) + +describe('ntpSpan', () => { + it('converts a span of a track\'s ticks to NTP units, the fraction divided away', () => { + expect([ + ntpSpan(90000n, 90000n), + ntpSpan(360000n, 90000n), + ntpSpan(3000n, 90000n), + ntpSpan(0n, 48000n), + ntpSpan(1n << 33n, 90000n), + ]).toEqual([ + 0x100000000n, + 0x400000000n, + 0x8888888n, + 0n, + 0x174D3B7BA7582n, + ]) + }) +}) diff --git a/src/lib/util/ntp.ts b/src/lib/util/ntp.ts index 031a16528..0425140fe 100644 --- a/src/lib/util/ntp.ts +++ b/src/lib/util/ntp.ts @@ -1,10 +1,10 @@ // NTP counts from 1900-01-01, this many milliseconds before the Unix epoch. const NTP_UNIX_OFFSET_MILLISECONDS = 2208988800000n -/** - * The width of an NTP time's fraction, as NTP time is 32.32 fixed point: whole seconds above 32 bits of fraction. - */ -export const NTP_FRACTION_BITS = 32n +// The width of an NTP time's fraction, as NTP time is 32.32 fixed point: whole seconds above 32 bits of fraction, and half the fraction's range, which +// rounds a count of milliseconds to the nearest as the fraction is shifted out of it. +const NTP_FRACTION_BITS = 32n +const HALF_FRACTION = 1n << (NTP_FRACTION_BITS - 1n) /** * Converts a wall clock time to NTP time in 32.32 fixed point: whole seconds since 1900-01-01 above 32 bits of fraction, the fraction floored. The value is @@ -15,3 +15,35 @@ export const NTP_FRACTION_BITS = 32n export function ntpTime(unixMilliseconds: number): bigint { return ((BigInt(unixMilliseconds) + NTP_UNIX_OFFSET_MILLISECONDS) << NTP_FRACTION_BITS) / 1000n } + +/** + * Serial arithmetic modulo 2^64: the signed distance from one NTP time to another. A span across the NTP era's wrap reads as the short way round. + * @param from - The time the distance is read from. + * @param to - The time the distance is read to. + * @returns The distance, negative when `to` lies before `from`. + */ +export function distance(from: bigint, to: bigint): bigint { + return BigInt.asIntN(64, BigInt.asUintN(64, to) - from) +} + +/** + * Converts a span of a track's ticks to an NTP time span in 32.32 fixed point, the fraction divided toward zero. + * @param ticks - The span in the track's ticks. + * @param timescale - The track's ticks in a second, never 0. + * @returns The span in NTP units. + */ +export function ntpSpan(ticks: bigint, timescale: bigint): bigint { + return (ticks << NTP_FRACTION_BITS) / timescale +} + +/** + * Converts a 64-bit NTP time to the wall clock it names nearest a wall clock the caller passes, which settles its era: the caller's wall clock moved by the + * distance from that wall clock's own NTP time, rounded to the nearest millisecond, for a time before it as for one after. The NTP time {@link ntpTime} + * gives a whole millisecond reads back as that millisecond. + * @param ntp - The NTP time, read modulo 2^64. + * @param near - The wall clock in whole milliseconds since the Unix epoch. + * @returns The wall clock in whole milliseconds since the Unix epoch. + */ +export function wallClockOf(ntp: bigint, near: number): number { + return near + Number((distance(ntpTime(near), ntp) * 1000n + HALF_FRACTION) >> NTP_FRACTION_BITS) +} diff --git a/src/test-utils/cameraFixtures.ts b/src/test-utils/cameraFixtures.ts index 665c771c6..bb700aa91 100644 --- a/src/test-utils/cameraFixtures.ts +++ b/src/test-utils/cameraFixtures.ts @@ -56,7 +56,7 @@ import { validateVideoSensors } from '../lib/camera/StreamingOptions.js' import { IdentifierCache } from '../lib/model/IdentifierCache.js' import { Service } from '../lib/Service.js' import * as uuid from '../lib/util/uuid.js' -import { soundSample, tierPicture, tierStreamFragment, writeTierFrame } from './mp4Fixtures.js' +import { prft, soundSample, TIER_STREAM_PICTURE, tierPicture, tierStreamFragment, writeTierFrame } from './mp4Fixtures.js' import { deferred } from './settle.js' export { buildEmitterConnection } from './connectionFixtures.js' @@ -90,6 +90,7 @@ export const FRAME_TICKS = 3000 export const SOUND_TICKS = 960 const FRAMES_PER_SECOND = 30 +const PICTURE_TICKS_PER_SECOND = BigInt(FRAME_TICKS * FRAMES_PER_SECOND) // How far a row's clock moves from one picture a kept stream hands over to the next, in milliseconds: well inside a demand's long-gap time, and a step // whose pictures stand no more than the buffer's jump limit ahead of their arrival on a clock that does not move. @@ -127,6 +128,9 @@ export interface FrameOptions { // The decode time a fragment's sound run states in place of the one its index times it at, from that index and that time, which lets a row move the sound // against its picture. retimeSound?: (index: number, decodeTime: number) => number + // The NTP time the stream states for its picture's decode time zero, through a producer reference time box in front of each fragment, the box stating + // that time moved on to its own picture's decode time. Absent, the stream carries no box. + clock?: bigint } export const MOCK_IMAGE = crypto.randomBytes(64) @@ -502,7 +506,8 @@ 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. +// 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. export function frames(stream: TierStream, from: number, to: number, options: FrameOptions = {}): void { const { gop = FRAMES_PER_SECOND, @@ -511,6 +516,7 @@ export function frames(stream: TierStream, from: number, to: number, options: Fr lag = false, octets = 100, readable = false, + clock, retimeSound, sound = true, stated, @@ -532,8 +538,7 @@ export function frames(stream: TierStream, from: number, to: number, options: Fr const last = Math.ceil((timed + 1) * 5 / 3) const pictureTime = index * FRAME_TICKS const soundTime = Math.max(first, 0) * SOUND_TICKS - - stream.write(tierStreamFragment({ + const fragment = tierStreamFragment({ picture: [ restated(tierPicture({ inBand, @@ -556,7 +561,18 @@ export function frames(stream: TierStream, from: number, to: number, options: Fr }) : [], soundTime: BigInt(retimeSound?.(index, soundTime) ?? soundTime), - })) + }) + + stream.write(clock === undefined + ? fragment + : Buffer.concat([ + prft({ + mediaTime: BigInt(pictureTime), + ntpTime: clock + (BigInt(pictureTime) << 32n) / PICTURE_TICKS_PER_SECOND, + trackId: TIER_STREAM_PICTURE, + }), + fragment, + ])) } } diff --git a/src/test-utils/mp4Fixtures.ts b/src/test-utils/mp4Fixtures.ts index 9246f7ac3..996a0c6dc 100644 --- a/src/test-utils/mp4Fixtures.ts +++ b/src/test-utils/mp4Fixtures.ts @@ -567,9 +567,17 @@ export function writeTierFrame(stream: TierStream, medium: StreamTierMedium, fra })) } -// A producer reference time box as a plugin or a muxer writes one. -export function prft(trackId = 1): Buffer { - return fullBox('prft', 1, 24, uint32(trackId), uint64(0xE000000000000000n), uint64(1234n)) +// A producer reference time box as a plugin or a muxer writes one, the NTP time given standing at the media time given on the track given: a version 1 box +// writes its media time in 64 bits, and a version 0 box in 32 bits, which takes the media time modulo 2^32. +export function prft({ mediaTime = 1234n, ntpTime = 0xE000000000000000n, trackId = 1, version = 1 }: { + mediaTime?: bigint + ntpTime?: bigint + trackId?: number + version?: 0 | 1 +} = {}): Buffer { + return fullBox('prft', version, 24, uint32(trackId), uint64(ntpTime), version === 1 + ? uint64(mediaTime) + : uint32(Number(BigInt.asUintN(32, mediaTime)))) } export const STYP = box('styp', Buffer.from('msdh', 'latin1'), uint32(0), Buffer.from('msdhmsix', 'latin1')) From 5c8bb056495294817701198aa65276ecfc70b486 Mon Sep 17 00:00:00 2001 From: HJD Date: Sun, 29 Nov 2026 09:33:37 -0600 Subject: [PATCH 2/4] feat(camera): seal a clip's initialization segment --- .../recording/CMAFRecordingManagement.spec.ts | 57 +++++++++++++++++-- .../recording/CMAFRecordingManagement.ts | 10 ++-- .../camera/recording/clipPackaging.spec.ts | 12 ++-- src/lib/camera/recording/clipPackaging.ts | 14 ++--- src/lib/camera/recording/clipSealing.ts | 8 +-- 5 files changed, 73 insertions(+), 28 deletions(-) diff --git a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts index 95511a98a..45145099f 100644 --- a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts +++ b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts @@ -435,12 +435,13 @@ function sent(camera: Pick, path: string): Buffer { return camera.mock.requests.findLast(request => request.path === `${POINT_PATH}${path}`)!.body } -// The body of the last request the mock read at a path, a media segment's body opened under the content key of the Camera Key given, which throws for a -// segment that does not open under it. A row reads a segment's media through this one reader. +// The body of the last request the mock read at a path, a segment's body, an initialization segment's or a media segment's, opened under the content key +// of the Camera Key given, which throws for a segment that does not open under it, and a playlist's as it was sent. A row reads a segment's bytes through +// this one reader. function body(camera: Pick, path: string, cameraKey: CameraKeyPayload = CAMERA_KEY): Buffer { const bytes = sent(camera, path) - if (!path.endsWith('.m4s')) { + if (path.endsWith('.m3u8')) { return bytes } @@ -1360,7 +1361,8 @@ describe('cMAFRecordingManagement', () => { expect(() => body(camera, 'session_1/high/segment_1002.m4s', renewedKey)).toThrow() }) - it('seals every media segment under the content key of the Camera Key held, the playlists carrying the key lines', async () => { + it('seals every media segment and the initialization segment under the content key of the Camera Key held, the playlists carrying the key lines, ' + + 'each before its map', async () => { await using camera = await clipCamera() serve(camera, 2) @@ -1381,12 +1383,55 @@ describe('cMAFRecordingManagement', () => { expect(body(camera, path)).toEqual(camera.served[index]) } + expect(sent(camera, 'session_1/high/high.init')).toHaveLength(camera.recording.run!.initialization.length + 32) expect(body(camera, 'session_1/high/high.init')).toEqual(camera.recording.run?.initialization) expect(body(camera, 'session_1/index.m3u8').toString()).toContain(`#EXT-X-INDEPENDENT-SEGMENTS\n#EXT-X-SESSION-KEY:${attributes}\n`) - expect(camera.mock.requests[1].body.toString()).toContain(`#EXT-X-MAP:URI="high.init"\n#EXT-X-KEY:${attributes}\n`) + expect(camera.mock.requests[1].body.toString()).toContain(`#EXT-X-KEY:${attributes}\n#EXT-X-MAP:URI="high.init"\n`) expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) }) + it('seals a later recording\'s initialization segment, sent after a discontinuity as a paused clip resumes on that recording, under the content key ' + + 'the clip opened with, the closing playlist\'s key line before its map', async () => { + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + const older = camera.recording + + expect(await stopAt(camera, endOf(camera, 1), BufferUploadStopAction.PAUSE)).toBe(clipID) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + older.end() + begin(camera, WALL_CLOCK + 60 * 1000) + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + expect(await startAt(camera, placeOf(camera, 0))).toBe(clipID) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1004.m4s')) + await stopAt(camera, endOf(camera, 1)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + + const attributes = keyAttributes(contentKeyOf(CAMERA_KEY)) + + expect(paths(camera).filter(path => path.endsWith('.init'))).toEqual(['session_1/high/high.init', 'session_1/high/high_2.init']) + + for (const [path, recording] of [ + ['session_1/high/high.init', older], + ['session_1/high/high_2.init', camera.recording], + ] as const) { + expect(sent(camera, path)).toHaveLength(recording.run!.initialization.length + 32) + expect(sent(camera, path).subarray(16, -16)).not.toEqual(recording.run!.initialization) + expect(body(camera, path)).toEqual(recording.run!.initialization) + } + + expect(body(camera, 'session_1/high/index.m3u8').toString()).toContain(`segment_1002.m4s\n#EXT-X-DISCONTINUITY\n#EXT-X-KEY:${attributes}\n` + + '#EXT-X-MAP:URI="high_2.init"\n') + }) + it('states each clip\'s start, sealed, in its multivariant playlist\'s date line after the session key line: the wall clock that placed the recording ' + 'for a clip from its first fragment, and that wall clock and the durations before it for a clip from a later fragment', async () => { await using camera = await clipCamera() @@ -3747,7 +3792,7 @@ describe('cMAFRecordingManagement', () => { const playlist = body(clip, `session_${clipID}/high/index.m3u8`).toString() - expect(playlist).toContain('segment_1002.m4s\n#EXT-X-DISCONTINUITY\n#EXT-X-MAP:URI="high_2.init"\n') + expect(playlist).toContain(`segment_1002.m4s\n#EXT-X-DISCONTINUITY\n#EXT-X-KEY:${keyAttributes(contentKeyOf(CAMERA_KEY))}\n#EXT-X-MAP:URI="high_2.init"\n`) expect(playlist).toBe(closingMediaPlaylist({ keyAttributes: keyAttributes(contentKeyOf(CAMERA_KEY)), segments: [1, 1, 2, 2].map(initialization => ({ initialization, seconds: 4 })), diff --git a/src/lib/camera/recording/CMAFRecordingManagement.ts b/src/lib/camera/recording/CMAFRecordingManagement.ts index 2b395b421..0f7bcc71b 100644 --- a/src/lib/camera/recording/CMAFRecordingManagement.ts +++ b/src/lib/camera/recording/CMAFRecordingManagement.ts @@ -823,8 +823,8 @@ class ClipSession { return await sessionEnd(session) } - // The bytes, content type, headers and path of an object: each media segment sealed under the clip's content key, each playlist naming that key, the - // multivariant playlist stating the clip's start sealed under it, and the initialization segment as the camera served it. + // The bytes, content type, headers and path of an object: each initialization segment and each media segment sealed under the clip's content key, each + // playlist naming that key, and the multivariant playlist stating the clip's start sealed under it. private payload(object: ClipObject): { body: Uint8Array, contentType: string, headers?: Record, path: string } { const { contentKey } = this.identity @@ -872,7 +872,7 @@ class ClipSession { case 'initialization': return { - body: object.read.run.initialization, + body: seal(contentKey, object.read.run.initialization), contentType: CONTENT_TYPES.initialization, path: initializationPath(this.initializations + 1), } @@ -1030,8 +1030,8 @@ class ClipSession { * disallowed or the accessory is unpublished no clip runs, and a camera whose source the plugin states away leaves each clip in flight to finish with what * its recording served, a hub's Start for a recording already served opening a clip meanwhile. * - * A clip's video and audio are always encrypted: each media segment uploads sealed under the content key of the Camera Key the clip opened with, while its - * initialization segment and its playlists upload readable, each playlist naming that key and the multivariant playlist stating the clip's start, the + * A clip's video and audio are always encrypted: each initialization segment and each media segment uploads sealed under the content key of the Camera + * Key the clip opened with, while its playlists upload readable, each playlist naming that key and the multivariant playlist stating the clip's start, the * wall clock of its first fragment's place, sealed under it. A camera holding no Camera Key, or one no content key derives from, refuses every Start that * would open a clip, with an upload-refused problem saying why at the first such refusal and again at most once per interval while they go on. A clip * already open keeps the key it opened with. diff --git a/src/lib/camera/recording/clipPackaging.spec.ts b/src/lib/camera/recording/clipPackaging.spec.ts index d9f266675..95e5898b2 100644 --- a/src/lib/camera/recording/clipPackaging.spec.ts +++ b/src/lib/camera/recording/clipPackaging.spec.ts @@ -64,7 +64,7 @@ describe('clipPackaging', () => { ].join('\n')) }) - it('writes the opening media playlist as an event from segment 1001 with its first map, and the key line after the map', () => { + it('writes the opening media playlist as an event from segment 1001 with its key line, and its first map after the key line', () => { expect(openingMediaPlaylist({ keyAttributes: KEY, targetDuration: 4 })).toBe([ '#EXTM3U', '#EXT-X-VERSION:7', @@ -72,8 +72,8 @@ describe('clipPackaging', () => { '#EXT-X-MEDIA-SEQUENCE:1001', '#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-INDEPENDENT-SEGMENTS', - '#EXT-X-MAP:URI="high.init"', `#EXT-X-KEY:${KEY}`, + '#EXT-X-MAP:URI="high.init"', '', ].join('\n')) }) @@ -93,8 +93,8 @@ describe('clipPackaging', () => { '#EXT-X-MEDIA-SEQUENCE:1001', '#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-INDEPENDENT-SEGMENTS', - '#EXT-X-MAP:URI="high.init"', `#EXT-X-KEY:${KEY}`, + '#EXT-X-MAP:URI="high.init"', '#EXTINF:4.000000,', 'segment_1001.m4s', '#EXTINF:3.966667,', @@ -106,7 +106,7 @@ describe('clipPackaging', () => { ].join('\n')) }) - it('opens a discontinuity with the later initialization segment\'s map named by its order, and its key line', () => { + it('opens a discontinuity with the key line, and after it the later initialization segment\'s map named by its order', () => { expect(closingMediaPlaylist({ keyAttributes: KEY, segments: [ @@ -121,13 +121,13 @@ describe('clipPackaging', () => { '#EXT-X-MEDIA-SEQUENCE:1001', '#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-INDEPENDENT-SEGMENTS', - '#EXT-X-MAP:URI="high.init"', `#EXT-X-KEY:${KEY}`, + '#EXT-X-MAP:URI="high.init"', '#EXTINF:4.000000,', 'segment_1001.m4s', '#EXT-X-DISCONTINUITY', - '#EXT-X-MAP:URI="high_2.init"', `#EXT-X-KEY:${KEY}`, + '#EXT-X-MAP:URI="high_2.init"', '#EXTINF:4.000000,', 'segment_1002.m4s', '#EXTINF:2.500000,', diff --git a/src/lib/camera/recording/clipPackaging.ts b/src/lib/camera/recording/clipPackaging.ts index 9aa34e8ab..dabf80936 100644 --- a/src/lib/camera/recording/clipPackaging.ts +++ b/src/lib/camera/recording/clipPackaging.ts @@ -201,9 +201,9 @@ export function multivariantPlaylist({ average, codecs, keyAttributes, peak, res } /** - * The media playlist's opening form, sent before any segment: its header and its first initialization segment's map and key line. + * The media playlist's opening form, sent before any segment: its header and its first initialization segment's key line and map. * @param options - The playlist's attributes. - * @param options.keyAttributes - The key's attributes, which the key line after the map carries. + * @param options.keyAttributes - The key's attributes, which the key line before the map carries. * @param options.targetDuration - The longest segment the clip expects, in whole seconds. * @returns The playlist, every line ending in a newline. */ @@ -213,9 +213,9 @@ export function openingMediaPlaylist({ keyAttributes, targetDuration }: { keyAtt /** * The media playlist's closing form, listing every segment the clip sent and ending the playlist. A segment that follows a later initialization segment - * opens a discontinuity with that segment's map and its key line. + * opens a discontinuity with the key line and that segment's map. * @param options - The playlist's attributes. - * @param options.keyAttributes - The key's attributes, which the key line after each map carries. + * @param options.keyAttributes - The key's attributes, which the key line before each map carries. * @param options.segments - Each segment the clip sent, in order. * @returns The playlist, every line ending in a newline. */ @@ -239,7 +239,7 @@ export function closingMediaPlaylist({ keyAttributes, segments }: { keyAttribute ]) } -// A media playlist's header, through its first initialization segment's map and key line. +// A media playlist's header, through its first initialization segment's key line and map. function mediaHeader(targetDuration: number, keyAttributes: string): string[] { return [ '#EXTM3U', @@ -252,11 +252,11 @@ function mediaHeader(targetDuration: number, keyAttributes: string): string[] { ] } -// An initialization segment's map, then the key line. +// The key line, then an initialization segment's map: a key line applies to the map after it, which states that the initialization segment is sealed. function mapLines(order: number, keyAttributes: string): string[] { return [ - `#EXT-X-MAP:URI="${initializationName(order)}"`, `#EXT-X-KEY:${keyAttributes}`, + `#EXT-X-MAP:URI="${initializationName(order)}"`, ] } diff --git a/src/lib/camera/recording/clipSealing.ts b/src/lib/camera/recording/clipSealing.ts index 3fd192ed0..cab6ed9c6 100644 --- a/src/lib/camera/recording/clipSealing.ts +++ b/src/lib/camera/recording/clipSealing.ts @@ -17,12 +17,12 @@ const CONTENT_KEY_TAG = 0x4000n const METHOD = 'AES-256-GCM' /** - * The bytes sealing adds to a media segment: its IV before the ciphertext and its tag after. + * The bytes sealing adds to a segment: its IV before the ciphertext and its tag after. */ export const SEALING_OVERHEAD = IV_LENGTH + TAG_LENGTH /** - * The key a clip's media segments and its stated start are sealed under, and the identifier its playlists name it by. + * The key a clip's segments, initialization and media alike, and its stated start are sealed under, and the identifier its playlists name it by. */ export interface ContentKey { /** @@ -59,7 +59,7 @@ export function contentKeyOf(cameraKey: CameraKeyPayload): ContentKey { } /** - * The attributes of the key lines a clip's playlists carry, naming the key its media segments are sealed under. + * The attributes of the key lines a clip's playlists carry, naming the key its segments are sealed under. * @param contentKey - The clip's content key. * @returns The method and the key's address, its identifier in lowercase hexadecimal. */ @@ -68,7 +68,7 @@ export function keyAttributes(contentKey: ContentKey): string { } /** - * Seals one media segment whole under a clip's content key. + * Seals one segment whole under a clip's content key, an initialization segment as a media segment is. * @param contentKey - The clip's content key. * @param segment - The segment. * @returns A fresh random 16-byte IV, the AES-256-GCM ciphertext of the segment with no additional data, and the 16-byte tag. From 61988e1c7cda89b9ca069ee13ff42cde8948d192 Mon Sep 17 00:00:00 2001 From: HJD Date: Sun, 29 Nov 2026 09:33:38 -0600 Subject: [PATCH 3/4] fix(camera): state one target duration for a clip --- src/lib/camera/buffer/CameraBuffer.spec.ts | 31 +++- src/lib/camera/buffer/CameraBuffer.ts | 15 +- .../camera/recording/BufferRecorder.spec.ts | 155 ++++++++++++++++++ src/lib/camera/recording/BufferRecorder.ts | 88 +++++++--- .../recording/CMAFRecordingManagement.spec.ts | 92 ++++++++++- .../recording/CMAFRecordingManagement.ts | 19 ++- .../camera/recording/clipPackaging.spec.ts | 15 +- src/lib/camera/recording/clipPackaging.ts | 11 +- src/lib/controller/CameraController.ts | 15 +- 9 files changed, 384 insertions(+), 57 deletions(-) diff --git a/src/lib/camera/buffer/CameraBuffer.spec.ts b/src/lib/camera/buffer/CameraBuffer.spec.ts index 0faa36f2a..7ff404a99 100644 --- a/src/lib/camera/buffer/CameraBuffer.spec.ts +++ b/src/lib/camera/buffer/CameraBuffer.spec.ts @@ -20,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 { takenAt, TierBuffer } from './CameraBuffer.js' +import { longestReach, takenAt, TierBuffer } from './CameraBuffer.js' const SENSOR_UUID = 'a1b2c3d4-0000-4000-8000-000000000001' @@ -307,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) @@ -345,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) diff --git a/src/lib/camera/buffer/CameraBuffer.ts b/src/lib/camera/buffer/CameraBuffer.ts index 8b5964731..a12bf8113 100644 --- a/src/lib/camera/buffer/CameraBuffer.ts +++ b/src/lib/camera/buffer/CameraBuffer.ts @@ -554,8 +554,9 @@ export class TierBuffer { * says the buffer holds less than its prebuffer only for a span that has one. */ private bound(): void { - const reachLimit = (this.spanTime + KEYFRAME_ALLOWANCE) * 1000 - const octetLimit = (this.spanTime + KEYFRAME_ALLOWANCE) * OCTETS_PER_MILLISECOND + const longest = longestReach(this.spanTime) + const reachLimit = longest * 1000 + const octetLimit = longest * OCTETS_PER_MILLISECOND let passed: 'octets' | 'reach' | undefined for (;;) { @@ -700,6 +701,16 @@ export class TierBuffer { } } +/** + * How far back a tier's buffer of a span may reach from its newest picture: its span and the keyframe allowance. A buffer reaching back further drops its + * head keyframe, which means no stretch from a keyframe it keeps to its newest picture reaches back further. + * @param span - The buffer's span, in milliseconds. + * @returns The reach, in milliseconds. + */ +export function longestReach(span: number): number { + return span + KEYFRAME_ALLOWANCE +} + /** * The wall clock a kept sample was taken at, in whole milliseconds since the Unix epoch: the one its stream states, or the wall clock less the steady * clock's time since the sample arrived, each clock read at the call, which keeps the answer true across a step of the wall clock since the arrival. diff --git a/src/lib/camera/recording/BufferRecorder.spec.ts b/src/lib/camera/recording/BufferRecorder.spec.ts index 748d2adf3..71520259a 100644 --- a/src/lib/camera/recording/BufferRecorder.spec.ts +++ b/src/lib/camera/recording/BufferRecorder.spec.ts @@ -1581,6 +1581,161 @@ describe('bufferRecorder', () => { }) }) + describe('its longest segment', () => { + // A keyframe every this many frames, further apart than any row's stretch: a stretch written with it holds the one keyframe it opens on. + const SPARSE = 600 + + // The duration a segment writes for each of its pictures, in the picture's ticks, and their sum. + function durationsOf({ video }: ReadSegment): number[] { + return video.map(({ duration }) => duration!) + } + + function spanOf(segment: ReadSegment): number { + 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. + function opened(prebuffer: number, options: FrameOptions): Rig & { reading: Reading } { + const made = rig({ audio: false, prebuffer }) + + initialize(made.stream()) + frames(made.stream(), 0, 61, options) + + return { + ...made, + reading: read(made.recorder.handleRecordingStreamRequest(1)), + } + } + + it.each([ + [0, 10], + [2000, 12], + ])('sends a stretch between keyframes just under the reach of a buffer of a prebuffer of %i milliseconds, %i seconds, as one segment within it, and ' + + 'sends none for a stretch past it, the trim ending its recording as failed', async (prebuffer, seconds) => { + // The frames the buffer's reach holds. + const reach = seconds * 30 + const under = opened(prebuffer, { gop: reach - 1 }) + const past = opened(prebuffer, { gop: reach + 1 }) + + frames(under.stream(), 61, reach, { gop: reach - 1 }) + frames(past.stream(), 61, reach + 2, { gop: reach + 1 }) + await settle() + + expect(segmentsOf(under.reading).map(spanOf)).toEqual([(reach - 1) * FRAME_TICKS]) + expect(under.ends).toEqual([]) + expect(segmentsOf(past.reading)).toEqual([]) + expect(past.ends.map(({ outcome }) => outcome)).toEqual(['failed']) + }) + + it.each([ + [ + 'a restart', + async ({ stream }: Rig): Promise => { + stream().discontinuity() + frames(stream(), 0, 1) + }, + ], + [ + 'a long gap', + async (): Promise => { + vi.advanceTimersByTime(10000) + }, + ], + ] as const)('closes a segment as it stands at %s at its limit where its stretch reaches back exactly that far, its newest picture left out and ' + + 'counted as dropped', async (_cut, cut) => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const events = captureDebugEvents('HAP-NodeJS:Camera:BufferRecorder') + const recording = opened(0, { gop: SPARSE }) + + // The newest picture stands 10 seconds from the keyframe, as far back as a buffer of no prebuffer reaches. + frames(recording.stream(), 61, 301, { gop: SPARSE }) + await cut(recording) + recording.recorder.acknowledgeStream(1) + await settle() + + const segments = segmentsOf(recording.reading) + + expect(segments.map(({ video }) => video.length)).toEqual([300]) + expect(segments.map(spanOf)).toEqual([10 * 30 * FRAME_TICKS]) + expect(events.filter(({ kind }) => kind === 'recording-ended').map(({ dropped }) => dropped)).toEqual([1]) + }) + + it('ends the sound of a segment closed as it stands at its limit where its bounded pictures end, the next run\'s sound starting there, its newest ' + + 'picture and the sound past that end counted as dropped', async () => { + const events = captureDebugEvents('HAP-NodeJS:Camera:BufferRecorder') + const options: FrameOptions = { + gop: SPARSE, + readable: true, + } + const recording = rig() + + initialize(recording.stream()) + frames(recording.stream(), 0, 61, options) + + const reading = read(recording.recorder.handleRecordingStreamRequest(1)) + + // The newest picture stands 10 seconds from the keyframe, where the bounded segment ends, and a run of its own follows each restart. + frames(recording.stream(), 61, 301, options) + recording.stream().discontinuity() + frames(recording.stream(), 0, 150, options) + recording.stream().discontinuity() + frames(recording.stream(), 0, 1, options) + recording.recorder.acknowledgeStream(1) + await settle() + + const [closed, after] = segmentsOf(reading) + // The end of the bounded segment's pictures on the sound's timescale. + const end = BigInt(10 * 30 * FRAME_TICKS) * 48000n / 90000n + const last = closed.audio.at(-1)! + + expect(spanOf(closed)).toBe(10 * 30 * FRAME_TICKS) + expect(last.decodeTime + BigInt(last.duration!)).toBe(end) + expect(after.audio[0].decodeTime).toBe(end) + expect(events.filter(({ kind }) => kind === 'recording-ended').map(({ dropped }) => dropped)).toEqual([3]) + }) + + it.each([ + [0, 10], + [2000, 12], + ])('cuts the stand-in of the newest picture of a segment closed as it stands to the time the limit of a prebuffer of %i milliseconds, %i seconds, ' + + 'leaves it, and writes a stand-in under that limit whole', async (prebuffer, seconds) => { + // The frames the limit holds, and the duration the newest picture states in place of its frame's step. + const limit = seconds * 30 + const stated = 15 * FRAME_TICKS + const closed = async (newest: number): Promise => { + const options: FrameOptions = { + gop: SPARSE, + stated: (step, index) => index === newest + ? stated + : step, + } + const recording = opened(prebuffer, options) + + frames(recording.stream(), 61, newest + 1, options) + recording.stream().discontinuity() + frames(recording.stream(), 0, 1) + await settle() + + return segmentsOf(recording.reading).map(durationsOf) + } + const frame = (count: number): number[] => Array.from({ length: count }).fill(FRAME_TICKS) + + // The newest picture of the first stands a frame before the limit, and the second's half the limit from its keyframe. + expect(await closed(limit - 1)).toEqual([ + frame(limit), + ]) + expect(await closed(limit / 2)).toEqual([ + [ + ...frame(limit / 2), + stated, + ], + ]) + }) + }) + 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. diff --git a/src/lib/camera/recording/BufferRecorder.ts b/src/lib/camera/recording/BufferRecorder.ts index 728aaa56e..887149ce4 100644 --- a/src/lib/camera/recording/BufferRecorder.ts +++ b/src/lib/camera/recording/BufferRecorder.ts @@ -19,7 +19,7 @@ import { Buffer } from 'node:buffer' import { HDSProtocolError, HDSProtocolSpecificErrorReason } from '../../datastream/DataStreamServer.js' import { counted } from '../../util/counted.js' -import { takenAt } from '../buffer/CameraBuffer.js' +import { longestReach, takenAt } from '../buffer/CameraBuffer.js' import { debugChannel } from '../diagnostics/debugChannels.js' import { readSampleEntryBoxes } from '../mp4/mp4Boxes.js' import { segmentLength, writeKeyframeInitializationSegment, writeSegment } from '../mp4/mp4Writer.js' @@ -173,11 +173,12 @@ interface RecordingRoutes { readonly end: (outcome: CameraRecordingOutcome) => void } -// One segment as an open recording cuts it: its pictures from its opening keyframe, its sound, the keyframe the next segment opens on, absent for a -// segment closed as it stands, whether it reached the cap, and for a segment closed as it stands the end of its sound on the stream's sound ticks, which -// its last sound ends no later than. +// One segment as an open recording cuts it: its pictures from its opening keyframe and the duration it writes for each, its sound, the keyframe the next +// segment opens on, absent for a segment closed as it stands, whether it reached the cap, and for a segment closed as it stands the end of its sound on +// the stream's sound ticks, which its last sound ends no later than. interface Segment { readonly pictures: readonly BufferedSample[] + readonly durations: readonly number[] readonly sounds: readonly BufferedSample[] readonly next?: BufferedSample readonly overCap: boolean @@ -252,10 +253,13 @@ function matches(carried: Mp4StreamTrack, track: Mp4StreamTrack | undefined): bo * 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 * on the recording, the picture's end on the sound's timescale: a sound standing there or after is left out, and the last sound carried ends no later, - * since no later sample of the run follows it. 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. + * since no later sample of the run follows it. Such a segment spans no more than the camera buffer's longest reach at the recording's prebuffer, which a + * 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. */ class OpenRecording implements BufferPlace { keyframe?: BufferedSample @@ -281,11 +285,14 @@ 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 // 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, routes, streamId }: { + constructor(buffer: TierBuffer, video: Mp4StreamVideoTrack, head: BufferedSample, { audio, prebuffer, routes, streamId }: { readonly audio?: Mp4StreamAudioTrack + readonly prebuffer: number readonly routes: RecordingRoutes readonly streamId: number }) { @@ -294,6 +301,7 @@ class OpenRecording implements BufferPlace { this.audio = audio this.routes = routes this.streamId = streamId + this.longest = BigInt(longestReach(prebuffer)) * BigInt(video.timescale) / 1000n this.keyframe = head this.queue.push({ data: writeKeyframeInitializationSegment({ audio, keyframe: head.data, video }), @@ -351,9 +359,10 @@ class OpenRecording implements BufferPlace { this.closeAsItStands() } - /* Closes the segment in progress as it stands, from the place's keyframe to the newest picture the buffer took, the sound that would stand at or past - * the end of its sound dropped, which is why its last sound ends no later than its picture's end. The call does nothing for a place that holds no keyframe. A segment - * whose pictures span no time is dropped whole, since a later run's first picture would take its picture's decode time. + /* Closes the segment in progress as it stands, from the place's keyframe to the newest picture the buffer took, bounded at the longest reach, the sound + * that would stand at or past the end of its sound dropped, which is why its last sound ends no later than its picture's end. The call does nothing for + * a place that holds no keyframe. A segment whose pictures span no time is dropped whole, since a later run's first picture would take its picture's + * decode time. */ closeAsItStands(): void { const open = this.keyframe @@ -362,11 +371,12 @@ class OpenRecording implements BufferPlace { return } - const { pictures, sounds } = this.stretch(open) - const span = this.pictureDurations(pictures).reduce((total, duration) => total + BigInt(duration), 0n) + const { pictures: walked, sounds } = this.stretch(open) + const { durations, pictures } = this.standing(walked) + const span = durations.reduce((total, duration) => total + BigInt(duration), 0n) if (span === 0n) { - this.droppedSamples += pictures.length + sounds.length + this.droppedSamples += walked.length + sounds.length this.keyframe = undefined this.sentUpTo = undefined return @@ -375,8 +385,9 @@ class OpenRecording implements BufferPlace { const end = this.soundEnd(open, this.pictureTime + span) const carried = sounds.filter(({ decodeTime }) => decodeTime < end) - this.droppedSamples += sounds.length - carried.length + this.droppedSamples += walked.length - pictures.length + sounds.length - carried.length this.send({ + durations, end, overCap: this.length(pictures, pictures.length, carried, carried.length) >= SEGMENT_CAP, pictures, @@ -501,18 +512,40 @@ class OpenRecording implements BufferPlace { : walked } - // The segment of the pictures before a closing keyframe and the sound timed before it. + // 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 { const next = pictures[close] + const cut = pictures.slice(0, close) return { + durations: this.pictureDurations(cut), next, overCap, - pictures: pictures.slice(0, close), + pictures: cut, sounds: sounds.filter(({ time }) => time < next.time), } } + /* 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 + * it keeps no keyframe its newest picture reaches back past. + */ + 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) + + if ((newest !== undefined) && (left > 0n)) { + durations.push(Math.min(newest, Number(left))) + } + + return { + durations, + pictures: walked.slice(0, durations.length), + } + } + // The duration the recording writes for each picture: the one the buffer settled, or its stand-in, or for a run's lone picture that states none the last // its track sent. private pictureDurations(pictures: readonly BufferedSample[]): number[] { @@ -578,18 +611,18 @@ class OpenRecording implements BufferPlace { ]) } - /* Writes a segment and queues it with the wall clock its first picture was taken at: its picture from the recording's own decode time on, each sample's - * duration the one the buffer settled, the distance to its track's next decode time, or for a run's lone sample that states none the last its track - * sent, and its sound placed against its opening keyframe on the stream's times, an unsettled sound lasting as its packet states and the last sound of a - * segment closed as it stands ending no later than the segment's end. A run's lone sound whose length nothing tells, neither the stream, its packet nor - * a sound sent before it, is dropped: every sound the recording writes lasts some time. The place moves to the next segment's keyframe, or waits for - * the next keyframe after a segment a run's end closed as it stands, and the recording ends after a segment any other end closes as it stands. + /* Writes a segment and queues it with the wall clock its first picture was taken at: its picture from the recording's own decode time on at the + * durations the segment carries, each sound's duration the one the buffer settled, the distance to its track's next decode time, or for a run's lone + * sound that states none the last its track sent, and its sound placed against its opening keyframe on the stream's times, an unsettled sound lasting as + * its packet states and the last sound of a segment closed as it stands ending no later than the segment's end. A run's lone sound whose length nothing + * tells, neither the stream, its packet nor a sound sent before it, is dropped: every sound the recording writes lasts some time. The place moves to the + * next segment's keyframe, or waits for the next keyframe after a segment a run's end closed as it stands, and the recording ends after a segment any + * other end closes as it stands. */ - private send({ end, next, overCap, pictures, sounds }: Segment): void { + private send({ durations, end, next, overCap, pictures, sounds }: Segment): void { const [open] = pictures const pictureTime = this.pictureTime const offset = this.soundOffset(open) - const durations = this.pictureDurations(pictures) const timed = sounds.map(sound => ({ own: this.durationOf(sound), sound, @@ -809,12 +842,13 @@ export class BufferRecorder implements CameraRecordingDelegate, Disposable { // 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, reporter, sensorUUID, started, tierId } = this.options + const { 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, + prebuffer, routes: { capped: () => { reporter.problem({ diff --git a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts index 45145099f..3d03da432 100644 --- a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts +++ b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts @@ -100,6 +100,10 @@ const USERNAME = '0E:AE:FC:45:7B:93' const OTHER_USERNAME = '0E:AE:FC:45:7B:94' const CAMERA = 'b1b2c3d4-0000-4000-8000-000000000001' +// The longest segment a management's camera can cut in these rows, in whole seconds, which each clip's media playlist states in its opening and its +// closing form. +const TARGET_DURATION = 15 + // The options of a feed whose problems no row here reads, its reporter of no camera and its recorded sensor a synthetic one. const QUIET_FEED: ServedRecordingsOptions = { reporter: detachedReporter(), @@ -140,13 +144,14 @@ function context(username?: string, accessoryUUID = CAMERA): ControllerAccessory } } -// The served recordings, the policy and the reporter a management takes, the policy bound to no service and allowing no recording, and the reporter one -// of no camera, which means each problem prints its bare sentence. +// The served recordings, the policy, the reporter and the target duration a management takes, the policy bound to no service and allowing no recording, +// and the reporter one of no camera, which means each problem prints its bare sentence. function options(): CMAFRecordingManagementOptions { return { feed: new ServedRecordings(QUIET_FEED), policy: new OperatingModePolicy(), reporter: detachedReporter(), + targetDuration: TARGET_DURATION, } } @@ -280,7 +285,12 @@ async function clipCamera( operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, true) const mock = await MockIngestServer.start({ clientCAs: authority.pem, ...mockOptions }) - const management = new CMAFRecordingManagement({ feed, policy, reporter }) + const management = new CMAFRecordingManagement({ + feed, + policy, + reporter, + targetDuration: TARGET_DURATION, + }) management.handleAccessoryContext({ accessoryInformation: information, @@ -489,11 +499,12 @@ function segmentsOf(clip: bigint, count: number): string[] { } // The closing playlist of a clip whose segments each last one fragment and follow its first initialization segment, its key lines naming the clip -// camera's content key. +// camera's content key and its target the one the clip camera's management is made with. function closing(count: number): string { return closingMediaPlaylist({ keyAttributes: keyAttributes(contentKeyOf(CAMERA_KEY)), segments: Array.from({ length: count }, () => ({ initialization: 1, seconds: 4 })), + targetDuration: TARGET_DURATION, }) } @@ -1160,6 +1171,51 @@ describe('cMAFRecordingManagement', () => { ]) }) + it('states the target duration its management is made with in the opening and the closing form of a clip\'s media playlist, its later segment lasting ' + + 'longer than that target', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1001.m4s')) + + // A later fragment that outlasts the target, its decode time counting on from the first's. + const written = camera.writer.writePacket(mediaFragment({ + decodeTime: FRAGMENT_TICKS, + defaultDuration: SAMPLE_DURATION, + samples: SAMPLES * 4, + trackId: 1, + }), camera.wallClock) + + camera.recording.add(written) + await judge(camera, 1) + + const later = camera.recording.fragment(1)! + + await stopAt(camera, BigInt.asUintN(64, later.place + later.duration)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + + // The opening form and the closing form, in the order the clip sent them. + const playlists = camera.mock.requests.filter(({ path }) => path === `${POINT_PATH}session_1/high/index.m3u8`).map(({ body }) => body.toString()) + + expect(playlists.map(playlist => /^#EXT-X-TARGETDURATION:(\d+)$/m.exec(playlist)?.[1])).toEqual([ + String(TARGET_DURATION), + String(TARGET_DURATION), + ]) + expect(playlists[1]).toBe(closingMediaPlaylist({ + keyAttributes: keyAttributes(contentKeyOf(CAMERA_KEY)), + segments: [ + { initialization: 1, seconds: 4 }, + { initialization: 1, seconds: 16 }, + ], + targetDuration: TARGET_DURATION, + })) + }) + it('saves each Clip ID as the clip mark before answering it, one with no mark, and a restarted camera\'s first passing the restored mark by seventeen', async () => { await using camera = await clipCamera() @@ -1181,6 +1237,7 @@ describe('cMAFRecordingManagement', () => { feed: camera.feed, policy: camera.policy, reporter: detachedReporter(), + targetDuration: TARGET_DURATION, }) restarted.handleAccessoryContext(context(USERNAME)) @@ -2561,6 +2618,7 @@ describe('cMAFRecordingManagement', () => { feed, policy: new OperatingModePolicy(), reporter: detachedReporter(), + targetDuration: TARGET_DURATION, }) management.handleAccessoryContext(context(USERNAME)) @@ -3098,6 +3156,10 @@ describe('cMAFRecordingManagement', () => { // The frames of a segment the recorder cuts from the recorded tier's stream of a keyframe every second, at its target of 4 seconds. const SEGMENT_FRAMES = 120 + // The target duration a wired camera's media playlist states in its opening and its closing form: the longest segment its recording can cut at a + // prebuffer of nothing, the camera buffer's keyframe allowance. + const WIRED_TARGET_DURATION = 10 + // The accessories and cameras a row builds, destroyed and removed after it. No clip, session or policy outlives its row. const accessories: Accessory[] = [] const cameras: CameraController[] = [] @@ -3144,10 +3206,10 @@ describe('cMAFRecordingManagement', () => { } } - // A camera with the capabilities block over the fixtures' video sensors that records from its camera buffer with no prebuffer, and the stream its - // recorded tier's demand handed out, which a row writes as fragmented MP4. - function wiredCamera(): { camera: CameraController, tier: () => TierStream } { - const { options, stream } = bufferCamera({ prebuffer: 0 }) + // 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 }) const camera = new CameraController(options) cameras.push(camera) @@ -3317,6 +3379,18 @@ describe('cMAFRecordingManagement', () => { expect(restored[KEYS.key]!.UUID).toBe(Service.CameraKeyManagement.UUID) }) + 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) => { + const { camera } = wiredCamera(prebuffer) + + camera.constructServices() + + // @ts-expect-error: private access + return managementOf(camera).clipContext.targetDuration as number + })).toEqual([10, 13, 15, 40]) + }) + it('writes the producer reference time box into a capability camera\'s recording and serves it to the feed, and a legacy camera\'s goes out as yielded', async () => { const { camera, tier } = wiredCamera() @@ -3548,6 +3622,7 @@ describe('cMAFRecordingManagement', () => { expect(body(clip, `session_${clipID}/high/index.m3u8`).toString()).toBe(closingMediaPlaylist({ keyAttributes: keyAttributes(contentKeyOf(CAMERA_KEY)), segments: Array.from({ length: SERVED }, () => ({ initialization: 1, seconds: 4 })), + targetDuration: WIRED_TARGET_DURATION, })) }) @@ -3796,6 +3871,7 @@ describe('cMAFRecordingManagement', () => { expect(playlist).toBe(closingMediaPlaylist({ keyAttributes: keyAttributes(contentKeyOf(CAMERA_KEY)), segments: [1, 1, 2, 2].map(initialization => ({ initialization, seconds: 4 })), + targetDuration: WIRED_TARGET_DURATION, })) }) diff --git a/src/lib/camera/recording/CMAFRecordingManagement.ts b/src/lib/camera/recording/CMAFRecordingManagement.ts index 0f7bcc71b..000187080 100644 --- a/src/lib/camera/recording/CMAFRecordingManagement.ts +++ b/src/lib/camera/recording/CMAFRecordingManagement.ts @@ -162,6 +162,11 @@ export interface CMAFRecordingManagementOptions { * recording provisioning record are the camera's problems. */ reporter: CameraReporter + /** + * The longest segment the camera's recording can cut, in whole seconds, which each clip's media playlist states as its target duration in its opening + * form and its closing form alike. + */ + targetDuration: number } // The identity a context names, which the management holds the package of. @@ -217,8 +222,8 @@ function readinessOf({ cameraKey, credential, publishingPoint }: RecordingProvis } // What a clip asks of its management: the next clip number saved as the mark, an event queued, its end reported, the failure that ended its upload -// reported as the camera's problem, and the camera's reporter, which its ingest session reports through, with its debug events on the management's -// debug name. +// reported as the camera's problem, the camera's reporter, which its ingest session reports through, with its debug events on the management's debug +// name, and the target duration its media playlist states in its opening and its closing form. interface ClipContext { readonly allocate: () => bigint readonly debug: DebugWriter @@ -226,6 +231,7 @@ interface ClipContext { readonly ended: (clip: ClipSession) => void readonly fail: (failure: string) => void readonly reporter: CameraReporter + readonly targetDuration: number } // One fragment a clip read, with the reader and recording it came from, its run and its duration in seconds. @@ -861,10 +867,7 @@ class ClipSession { return { body: new TextEncoder().encode(openingMediaPlaylist({ keyAttributes: keyAttributes(contentKey), - targetDuration: Math.ceil(Math.max(...[ - ...this.requested, - ...this.pending, - ].map(({ seconds }) => seconds))), + targetDuration: this.context.targetDuration, })), contentType: CONTENT_TYPES.playlist, path: MEDIA_PLAYLIST, @@ -892,6 +895,7 @@ class ClipSession { body: new TextEncoder().encode(closingMediaPlaylist({ keyAttributes: keyAttributes(contentKey), segments: this.segments, + targetDuration: this.context.targetDuration, })), contentType: CONTENT_TYPES.playlist, path: MEDIA_PLAYLIST, @@ -1114,7 +1118,7 @@ export class CMAFRecordingManagement { /** * Adopts the saved services or builds them, binds their characteristics, and ends every clip once recording is disallowed or its accessory is * unpublished. - * @param options - The camera's served recordings, its operating-mode policy and its reporter. + * @param options - The camera's served recordings, its operating-mode policy, its reporter and the longest segment its recording can cut. * @param services - The saved services to adopt, each built new when absent. */ constructor(options: CMAFRecordingManagementOptions, services: Partial = {}) { @@ -1129,6 +1133,7 @@ export class CMAFRecordingManagement { ended: clip => this.clipEnded(clip), fail: failure => this.reporter.problem({ kind: 'upload-failed', level: 'warning', sentence: `A clip's upload failed. ${failure}` }), reporter: options.reporter, + targetDuration: options.targetDuration, } this.services = { buffer: services.buffer ?? new Service.CameraBufferManagement('', ''), diff --git a/src/lib/camera/recording/clipPackaging.spec.ts b/src/lib/camera/recording/clipPackaging.spec.ts index 95e5898b2..28b45d268 100644 --- a/src/lib/camera/recording/clipPackaging.spec.ts +++ b/src/lib/camera/recording/clipPackaging.spec.ts @@ -22,6 +22,9 @@ const KEY = 'METHOD=AES-256-GCM,URI="hksv3:10004000.key"' // A sealed start as the packaging takes it, base64 text it writes as given. const SEALED_START = 'c2VhbGVkIHN0YXJ0' +// The longest segment a camera's recording can cut, which a media playlist states as its target duration in its opening and its closing form. +const TARGET_DURATION = 15 + describe('clipPackaging', () => { it('writes the multivariant playlist with its session key line and its date line after it, naming the one rendition with its bit rates, picture and ' + 'codecs, leaving out any it lacks', () => { @@ -65,10 +68,10 @@ describe('clipPackaging', () => { }) it('writes the opening media playlist as an event from segment 1001 with its key line, and its first map after the key line', () => { - expect(openingMediaPlaylist({ keyAttributes: KEY, targetDuration: 4 })).toBe([ + expect(openingMediaPlaylist({ keyAttributes: KEY, targetDuration: TARGET_DURATION })).toBe([ '#EXTM3U', '#EXT-X-VERSION:7', - '#EXT-X-TARGETDURATION:4', + '#EXT-X-TARGETDURATION:15', '#EXT-X-MEDIA-SEQUENCE:1001', '#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-INDEPENDENT-SEGMENTS', @@ -78,7 +81,7 @@ describe('clipPackaging', () => { ].join('\n')) }) - it('writes the closing media playlist listing every segment at six decimals, its target the longest rounded up, and its end', () => { + it('writes the closing media playlist listing every segment at six decimals, stating the target it is given whatever its segments last, and its end', () => { expect(closingMediaPlaylist({ keyAttributes: KEY, segments: [ @@ -86,10 +89,11 @@ describe('clipPackaging', () => { { initialization: 1, seconds: 3.9666666 }, { initialization: 1, seconds: 4.1 }, ], + targetDuration: TARGET_DURATION, })).toBe([ '#EXTM3U', '#EXT-X-VERSION:7', - '#EXT-X-TARGETDURATION:5', + '#EXT-X-TARGETDURATION:15', '#EXT-X-MEDIA-SEQUENCE:1001', '#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-INDEPENDENT-SEGMENTS', @@ -114,10 +118,11 @@ describe('clipPackaging', () => { { initialization: 2, seconds: 4 }, { initialization: 2, seconds: 2.5 }, ], + targetDuration: TARGET_DURATION, })).toBe([ '#EXTM3U', '#EXT-X-VERSION:7', - '#EXT-X-TARGETDURATION:4', + '#EXT-X-TARGETDURATION:15', '#EXT-X-MEDIA-SEQUENCE:1001', '#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-INDEPENDENT-SEGMENTS', diff --git a/src/lib/camera/recording/clipPackaging.ts b/src/lib/camera/recording/clipPackaging.ts index dabf80936..3c9d9af62 100644 --- a/src/lib/camera/recording/clipPackaging.ts +++ b/src/lib/camera/recording/clipPackaging.ts @@ -204,7 +204,7 @@ export function multivariantPlaylist({ average, codecs, keyAttributes, peak, res * The media playlist's opening form, sent before any segment: its header and its first initialization segment's key line and map. * @param options - The playlist's attributes. * @param options.keyAttributes - The key's attributes, which the key line before the map carries. - * @param options.targetDuration - The longest segment the clip expects, in whole seconds. + * @param options.targetDuration - The longest segment the camera's recording can cut, in whole seconds, which the closing form states too. * @returns The playlist, every line ending in a newline. */ export function openingMediaPlaylist({ keyAttributes, targetDuration }: { keyAttributes: string, targetDuration: number }): string { @@ -217,9 +217,14 @@ export function openingMediaPlaylist({ keyAttributes, targetDuration }: { keyAtt * @param options - The playlist's attributes. * @param options.keyAttributes - The key's attributes, which the key line before each map carries. * @param options.segments - Each segment the clip sent, in order. + * @param options.targetDuration - The longest segment the camera's recording can cut, in whole seconds, which the opening form states too. * @returns The playlist, every line ending in a newline. */ -export function closingMediaPlaylist({ keyAttributes, segments }: { keyAttributes: string, segments: readonly PlaylistSegment[] }): string { +export function closingMediaPlaylist({ keyAttributes, segments, targetDuration }: { + keyAttributes: string + segments: readonly PlaylistSegment[] + targetDuration: number +}): string { const body: string[] = [] let initialization = 1 @@ -233,7 +238,7 @@ export function closingMediaPlaylist({ keyAttributes, segments }: { keyAttribute } return lines([ - ...mediaHeader(Math.ceil(Math.max(0, ...segments.map(({ seconds }) => seconds))), keyAttributes), + ...mediaHeader(targetDuration, keyAttributes), ...body, '#EXT-X-ENDLIST', ]) diff --git a/src/lib/controller/CameraController.ts b/src/lib/controller/CameraController.ts index 30919e2ec..b7fba4411 100644 --- a/src/lib/controller/CameraController.ts +++ b/src/lib/controller/CameraController.ts @@ -55,7 +55,7 @@ import { EventEmitter } from 'node:events' import createDebug from 'debug' -import { TierBuffer } from '../camera/buffer/CameraBuffer.js' +import { longestReach, TierBuffer } from '../camera/buffer/CameraBuffer.js' import { TierKeeper } from '../camera/buffer/TierKeeper.js' import { CAPABILITY_KEY_PREFIX } from '../camera/capabilityKeys.js' import { accessoryNameOf, CameraReporter } from '../camera/diagnostics/CameraReporter.js' @@ -2310,10 +2310,17 @@ export class CameraController extends EventEmitter implements SerializableContro return management } - // The HKSV3 recording management takes the policy that gates its clips, the feed they upload from and this configuration's reporter, and the accessory's - // context once one is held. + /* The HKSV3 recording management takes the policy that gates its clips, the feed they upload from, this configuration's reporter and the longest segment + * the recording can cut, and the accessory's context once one is held. That segment is the camera buffer's longest reach at the recording's prebuffer, + * in whole seconds rounded up, since the recorder cuts none longer, at a keyframe or as it stands. + */ private createCMAFRecordingManagement(services: Partial): CMAFRecordingManagement { - const management = new CMAFRecordingManagement({ feed: this.servedRecordings!, policy: this.operatingMode, reporter: this.reporter! }, services) + const management = new CMAFRecordingManagement({ + feed: this.servedRecordings!, + policy: this.operatingMode, + reporter: this.reporter!, + targetDuration: Math.ceil(longestReach(this.bufferRecording!.prebuffer) / 1000), + }, services) this.cmafRecordingManagement = this.ownership.adopt(management, cmafRecordingManagement => void cmafRecordingManagement.destroy()) if (this.accessoryContext) { From 005483291380e2b10957d0f64a1e630274797372 Mon Sep 17 00:00:00 2001 From: HJD Date: Sun, 29 Nov 2026 09:33:38 -0600 Subject: [PATCH 4/4] docs(guides): update the camera guides --- guides/HKSV3Protocol.md | 52 ++++++++++++++++++++++++++------ guides/UpgradingCameraPlugins.md | 4 ++- 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/guides/HKSV3Protocol.md b/guides/HKSV3Protocol.md index a7e636a21..4df8cff51 100644 --- a/guides/HKSV3Protocol.md +++ b/guides/HKSV3Protocol.md @@ -625,6 +625,17 @@ The recording is fragmented MP4, sent as HAP's data stream recordings always hav A hub takes the clock time of the **first** fragment from its box, and counts forward from there by each fragment's duration. It doesn't use the times in the later boxes. +That time is **not required** to be the moment the video was taken. A recording whose box stated the moment it was sent, over video from several seconds earlier, was judged and kept, and one stamped with the time its first picture was taken was **accepted** the same way. State the true time. Every timestamp a hub writes back counts from it, and it's what lets a clip stand in the timeline where its video happened (section 8). + +**In HAP-NodeJS** a recording is stamped with the time its first picture was taken: the time the plugin's own stream states for it in a `prft` box where it carries one, and the moment the picture arrived otherwise. + +**A hub waits about 16 seconds for the first fragment.** A camera that answered the open and then sent nothing had its stream closed by the hub with the reason TIMEOUT, between 16 and 17 seconds after the open, on both of my hubs. A first fragment sent 15 seconds after the open was **accepted**, and its clip was kept like any other. One sent at 16 seconds was taken too, once, and I wouldn't count on it. + +- Only a fragment answers the wait. An initialization segment sent at once, with no fragment behind it, changed nothing about the close. +- A fragment can't leave until all of it exists. A camera that only starts its stream when the hub asks has 15 seconds, less the length of one fragment, to produce its first picture. With four-second fragments that's about 11 seconds. +- 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. + 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 @@ -668,7 +679,7 @@ A camera that won't serve a recording should say so in its answer to the `dataSe - **Not Allowed**: every hub in the home asks once for that motion, one after another, and none asks twice. - **Busy**: one hub asks once, and no other hub asks. - Either way no stream is left open, and the hubs ask again at the next motion. Four refusals in a row changed nothing about the fifth. -- Don't answer the open with success and then send an empty end of stream. A hub neither acknowledges that nor closes it, and the stream hangs until the camera gives up on it. +- Don't answer the open with success and then send an empty end of stream. In the 12 seconds I watched, a hub neither acknowledged that nor closed it, and the camera had to give up on the stream itself. The Home app showed nothing in its timeline for a declined motion. I checked that on the form I've just told you not to use, and not on the two refusals. @@ -700,24 +711,29 @@ Each of these is answered 201. - **The picture and the sound can share one track file**, as above, or go as a video track and an audio track with a playlist each. Both play. - The names aren't fixed. Tracks called `video` and `audio`, and segments numbered from 1, were accepted. So were segments without the `x-extinf-duration` header my uploads carry, and playlists without `#EXT-X-PLAYLIST-TYPE:EVENT`. +- **The media playlist's target duration can stand well above its segments' length.** Playlists that stated 15 and 40 over four-second segments were **accepted**, as were the playlists before them that stated 4 or 5, and their clips play. State one number, the same in the opening playlist and the closing one. - 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. + The playlists are in appendix A. #### Encryption -Every media segment is sealed, whole, before it's sent. The initialization segment is not. +Every media segment is sealed, whole, before it's sent. The initialization segment can be sealed the same way: a clip plays with it sealed, and it plays with it in the clear. - **A sealed segment** is a 16-byte IV, then the AES-256-GCM ciphertext of the entire segment, then the 16-byte tag. There's no additional authenticated data. Each segment gets a fresh random IV. - **The key is not the Camera Key itself.** It's a content key derived from it: HKDF-SHA-256 with the Camera Key as the input, an empty salt, the info `HomeKit 1.0 CMAF Content`, and 32 bytes out. -- **The playlists say which key.** Each media playlist carries `#EXT-X-KEY:METHOD=AES-256-GCM,URI="hksv3:.key"` straight after its `#EXT-X-MAP` line, in the opening playlist and the closing one. The multivariant playlist carries the same attributes on an `#EXT-X-SESSION-KEY` line. +- **The playlists say which key.** Each media playlist carries `#EXT-X-KEY:METHOD=AES-256-GCM,URI="hksv3:.key"` beside its `#EXT-X-MAP` line, in the opening playlist and the closing one. The multivariant playlist carries the same attributes on an `#EXT-X-SESSION-KEY` line. +- **Where the key line stands says what's sealed.** After the map, the initialization segment is in the clear. Before the map, the initialization segment is sealed too. Both were **accepted**. _Untested_: a sealed initialization segment under a key line that follows the map. +- **The multivariant playlist states when the clip starts, sealed.** One line after the session key line, an `#EXT-X-SESSION-DATA` line with the ID `com.apple.encrypted-datetime.timestamp`, carries the clip's start as text sealed under the same content key. It's what places the clip in the timeline. Appendix A has its layout. - **The identifier** is the Camera Key's key number shifted left 16 bits, with `0x4000` set in the low bits, written in hexadecimal with no prefix. - No key is ever uploaded. The Home app supplies the key itself, by the identifier the playlist names. This is the part of the protocol that took longest to find, because the service is no help: it answers 201 to media it can't possibly parse. A clip sealed under the wrong key, or naming its key with the wrong address, uploads perfectly and then refuses to play. Three things told me this form is right. The Home app's own player asks for a key at exactly the address a playlist names. A clip built this way plays, picture and sound, where every other form I tried showed a struck-through play button, a black picture or nothing at all. And it plays in every shape I've sent since: one track file or two, H.264 or HEVC, AAC or Opus, commanded by a hub or not, and from more than one camera's key. -The service also accepts a clip with no encryption at all, and the Home app plays it. Please don't. HomeKit Secure Video promises recordings only your own devices can read, and the hub hands you a key for a reason. **In HAP-NodeJS** there is no unencrypted upload: a camera without a usable key declines the hub's Start and uploads nothing. +The service also accepts a clip with no encryption at all, and the Home app plays it. Please don't. HomeKit Secure Video promises recordings only your own devices can read, and the hub hands you a key for a reason. **In HAP-NodeJS** there is no unencrypted upload: a camera without a usable key declines the hub's Start and uploads nothing. Every clip's initialization segment is sealed with its media, and every clip carries the date line. #### What The Service Answers @@ -748,9 +764,10 @@ The service also accepts a clip with no encryption at all, and the Home app play #### What The Home App Does With A Clip -- **A clip is placed in the timeline at the moment its first object arrives.** Nothing moves it: not the times in its `prft` boxes, not an `#EXT-X-PROGRAM-DATE-TIME` line, not the timestamps of the hub's command. A clip sent ten minutes after its command stood ten minutes late. -- The Home app ties a hub's event to an uploaded recording that starts within 5.0 seconds of where it expects one. Since a clip is dated by its arrival, it sits later than the hub's own reckoning of where the recording began, and one event whose expected start fell eight seconds before the upload arrived was dropped. Start uploading the moment the Start comes. -- Clips that overlap in time show as one clip. +- **A clip is placed in the timeline at the time its sealed date line states**, to the second. Clips whose lines stated times ten, fifteen and twenty minutes before they were sent stood at those times, and a camera's own clips stood at the start of their video, lead-up included. _Inferred_: it's the Home app that reads the line. The service takes a clip that carries it as it takes any other. +- **Without that line, a clip is placed at the moment its first object arrives**, and nothing else moves it: not the times in its `prft` boxes, not an `#EXT-X-PROGRAM-DATE-TIME` line, not the timestamps of the hub's command. A clip sent ten minutes after its command stood ten minutes late. +- The Home app ties a hub's event to an uploaded recording that starts within 5.0 seconds of where it expects one. A clip with no date line is dated by its arrival, which puts it later than the hub's own reckoning of where the recording began, and one event whose expected start fell eight seconds before the upload arrived was dropped. State the clip's start, and start uploading the moment the Start comes. +- Clips that overlap in time show as one clip, and so do two clips that meet end to end, as a hub's own cut at 300 seconds leaves them. Either way the one clip played with a brief stutter where its second clip begins. - **A clip needs nothing from the camera to play.** It plays while the camera is switched off. - The timeline shows the clips of whichever recording path the camera's current services belong to. A camera that moves from HAP's older recording to HKSV3 seems to lose its old clips, and gets them back if it returns. They're hidden, not deleted. - **Before you doubt an upload, restart things.** More than once the Home app showed a fresh clip's event and played nothing until the app was restarted. Once a single phone showed a clip as a black picture, while another device played it, until that phone was restarted. @@ -830,6 +847,7 @@ These are the questions whose answers would change what you build, or explain so - _Untested_: what a hub's analysis counts as worth keeping. A person walking into view turns the verdict, and so does a moving shape. One still, dark picture was also judged worth recording, and I can't say why. - _Untested_: the exact segment size limit, somewhere between 9.10 and 11.92 MB. - _Untested_: why some clips open late. Two clips of a camera's own stream, passed through at more than twice the guide's highest bitrate for its size, opened at their second segment, though they play whole when you seek back. One ordinary 60-second clip opened 24 seconds in. Clips at the guide's bitrates otherwise open at their start. +- _Untested_: what makes the join of two clips rough. A pair that met exactly and a pair that shared four seconds each played with a brief stutter at the join. - _Untested_: the StartAndStop command and the Pause stop action, which no hub has written. - _Untested_: whether a doorbell press over a perfectly still picture makes a hub keep a clip. Mine had something moving in view. @@ -889,22 +907,23 @@ A multivariant playlist, for one track file that holds picture and sound: #EXT-X-VERSION:7 #EXT-X-INDEPENDENT-SEGMENTS #EXT-X-SESSION-KEY:METHOD=AES-256-GCM,URI="hksv3:3a94c1f07be24000.key" +#EXT-X-SESSION-DATA:DATA-ID="com.apple.encrypted-datetime.timestamp",VALUE="" #EXT-X-STREAM-INF:BANDWIDTH=1800000,AVERAGE-BANDWIDTH=1700000,RESOLUTION=1920x1080,CODECS="hvc1.1.6.L120.b0,Opus" high/index.m3u8 ``` -Its media playlist, as it reads when the clip closes. The opening one is the same down to the `#EXT-X-KEY` line, and stops there. +Its media playlist, as it reads when the clip closes, with the initialization segment sealed. The opening one is the same down to the `#EXT-X-MAP` line, and stops there. With the initialization segment in the clear, the `#EXT-X-KEY` line follows the map. ```text #EXTM3U #EXT-X-VERSION:7 -#EXT-X-TARGETDURATION:4 +#EXT-X-TARGETDURATION:15 #EXT-X-MEDIA-SEQUENCE:1001 #EXT-X-PLAYLIST-TYPE:EVENT #EXT-X-INDEPENDENT-SEGMENTS -#EXT-X-MAP:URI="high.init" #EXT-X-KEY:METHOD=AES-256-GCM,URI="hksv3:3a94c1f07be24000.key" +#EXT-X-MAP:URI="high.init" #EXTINF:4.000000, segment_1001.m4s #EXTINF:4.000000, @@ -912,6 +931,17 @@ segment_1002.m4s #EXT-X-ENDLIST ``` +The value of the date line is the base64, with padding, of this JSON, its fields in this order: + +```text +{"method":"AES-256-GCM","iv":"","ciphertext":"","tag":"","kid":""} +``` + +- The plaintext is the clip's start as ISO 8601 text in UTC, such as `2026-01-15T18:30:05.321Z`. Whole seconds and milliseconds were both **accepted**. +- It's sealed as a segment is: AES-256-GCM under the clip's content key, with a fresh 16-byte IV, a 16-byte tag and no additional authenticated data. Here the IV, the ciphertext and the tag travel apart, each in base64. +- The `kid` is the key identifier as the key's address spells it, in lowercase hexadecimal, without `hksv3:` and `.key`. +- _Untested_: a start later than the clip's arrival, and how far back a start may reach. Twenty minutes back was placed. + A clip may name the sensor it came from with one more line in the multivariant playlist, after `#EXT-X-INDEPENDENT-SEGMENTS`: ```text @@ -1021,6 +1051,8 @@ All from my home, my network and my hubs. They show the pace of things and promi | A fragment sent | Its verdict | 0.26 to 0.92 seconds, most often about 0.3 | | A Should Record verdict | The Start command | 5 to 11 milliseconds | | Motion Detected | The Start command | Typically 2 to 4 seconds | +| The hub's request for a recording | Its TIMEOUT close, when no fragment comes | 16 to 17 seconds | +| A recording that timed out | The hub's second request, with motion still raised | 5 seconds | | The hub closing a recording | The Stop command | 5 to 38 milliseconds | | A clip's Start | A forced cut to a new clip | 300 seconds | | A viewer at home reading the database | Its Setup Endpoints write | 50 to 70 milliseconds | diff --git a/guides/UpgradingCameraPlugins.md b/guides/UpgradingCameraPlugins.md index 3c24a9b3c..df34a3ee0 100644 --- a/guides/UpgradingCameraPlugins.md +++ b/guides/UpgradingCameraPlugins.md @@ -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. @@ -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. @@ -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.