From 80ba3e7805dc19e340a02d892c06f8292b5f7488 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:41 -0600 Subject: [PATCH 01/16] fix(definitions): write only validated, lint-clean definitions from the generator --- package.json | 3 +- src/lib/definitions/generate-definitions.ts | 583 +++++++++++------- .../definitions/generator-configuration.ts | 23 +- 3 files changed, 378 insertions(+), 231 deletions(-) diff --git a/package.json b/package.json index 6772b15aa..6eb4604bf 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,8 @@ "clean": "rimraf dist && rimraf coverage", "lint": "eslint .", "build": "rimraf dist && tsc", - "generate-definitions": "tsx src/lib/definitions/generate-definitions.ts && eslint --fix src/lib/definitions src/lib/Characteristic.ts src/lib/Service.ts", + "generate-definitions": "tsx src/lib/definitions/generate-definitions.ts", + "postgenerate-definitions": "eslint src/lib/definitions src/lib/Characteristic.ts src/lib/Service.ts", "prepublishOnly": "npm run build", "postpublish": "npm run clean", "test": "vitest run", diff --git a/src/lib/definitions/generate-definitions.ts b/src/lib/definitions/generate-definitions.ts index 326b36625..f3bac784c 100644 --- a/src/lib/definitions/generate-definitions.ts +++ b/src/lib/definitions/generate-definitions.ts @@ -14,6 +14,7 @@ import { CharacteristicDeprecatedNames, CharacteristicHidden, CharacteristicManualAdditions, + CharacteristicManualOverlaps, CharacteristicNameOverrides, CharacteristicOverriding, CharacteristicSinceInformation, @@ -21,6 +22,7 @@ import { ServiceCharacteristicConfigurationOverrides, ServiceDeprecatedNames, ServiceManualAdditions, + ServiceManualOverlaps, ServiceNameOverrides, ServiceSinceInformation, } from './generator-configuration.js' @@ -170,6 +172,34 @@ export interface GeneratedService { optionalCharacteristics?: string[] } +// A definition namespace as the guards read it: the manual additions merged into it and the overlaps with the plist those additions declare. +interface Namespace { + kind: 'characteristic' | 'service' + manualAdditions: ReadonlyMap + overlaps: ReadonlyMap + overlapsName: string +} + +// A namespace's plist record as read before its manual additions merge into it. +interface PlistIndex { + ids: ReadonlySet + idsByUUID: ReadonlyMap +} + +const CHARACTERISTICS: Namespace = { + kind: 'characteristic', + manualAdditions: CharacteristicManualAdditions, + overlaps: CharacteristicManualOverlaps, + overlapsName: 'CharacteristicManualOverlaps', +} + +const SERVICES: Namespace = { + kind: 'service', + manualAdditions: ServiceManualAdditions, + overlaps: ServiceManualOverlaps, + overlapsName: 'ServiceManualOverlaps', +} + const plistData = plist.readFileSync(metadataFile) as PlistMetadata const simulatorPlistData = plist.readFileSync(defaultPlist) as SimulatorMetadata const simulatorMfiPlistData = fs.existsSync(defaultMfiPlist) @@ -240,20 +270,11 @@ for (const definition of Object.values(categories)) { } } -const characteristicOutput = fs.createWriteStream(path.join(import.meta.dirname, 'CharacteristicDefinitions.ts')) - -characteristicOutput.write('// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n') -characteristicOutput.write(`// V=${plistData.Version}\n`) -characteristicOutput.write('\n') - -characteristicOutput.write('import { Access, Characteristic, Formats, Perms, Units } from "../Characteristic.js";\n\n') - /** * Characteristics */ const generatedCharacteristics: Record = {} // indexed by id -const writtenCharacteristicEntries: Record = {} // indexed by class name for (const [id, definition] of Object.entries(characteristics)) { try { @@ -326,127 +347,22 @@ for (const [id, definition] of Object.entries(characteristics)) { CharacteristicOverriding.get(id)?.(generatedCharacteristic) generatedCharacteristics[id] = generatedCharacteristic - writtenCharacteristicEntries[className] = generatedCharacteristic - if (deprecatedClassName) { - writtenCharacteristicEntries[deprecatedClassName] = generatedCharacteristic - } } catch (error) { throw new Error(`Error thrown generating characteristic '${id}' (${definition.DefaultDescription}): ${errorMessage(error)}`, { cause: error }) } } +const plistCharacteristics = plistIndex(generatedCharacteristics) for (const [id, generated] of CharacteristicManualAdditions) { + checkManualAddition(CHARACTERISTICS, plistCharacteristics, id, generated.UUID) generatedCharacteristics[id] = generated - writtenCharacteristicEntries[generated.className] = generated - if (generated.deprecatedClassName) { - writtenCharacteristicEntries[generated.deprecatedClassName] = generated - } -} - -for (const generated of Object.values(generatedCharacteristics) - .sort((a, b) => a.className.localeCompare(b.className))) { - try { - characteristicOutput.write('/**\n') - characteristicOutput.write(` * Characteristic "${generated.name}"\n`) - if (generated.since) { - characteristicOutput.write(` * @since iOS ${generated.since}\n`) - } - if (generated.deprecatedNotice) { - characteristicOutput.write(` * @deprecated ${generated.deprecatedNotice}\n`) - } - characteristicOutput.write(' */\n') - - characteristicOutput.write(`export class ${generated.className} extends Characteristic {\n\n`) - - characteristicOutput.write(` public static readonly UUID: string = "${generated.UUID}";\n\n`) - - const classAdditions = generated.classAdditions - if (classAdditions) { - characteristicOutput.write(`${classAdditions.map(line => ` ${line}\n`).join('')}\n`) - } - - const validValuesEntries = Object.entries(generated.validValues ?? {}) - if (validValuesEntries.length) { - for (const [value, name] of validValuesEntries) { - if (!name) { - continue - } - const cleanName = name.replace(/_+$/, '') // remove any underscores at the end of the name - characteristicOutput.write(` public static readonly ${cleanName} = ${value};\n`) - } - characteristicOutput.write('\n') - } - if (generated.validBitMasks) { - for (const [value, name] of Object.entries(generated.validBitMasks)) { - characteristicOutput.write(` public static readonly ${name} = ${value};\n`) - } - characteristicOutput.write('\n') - } - - characteristicOutput.write(' constructor() {\n') - characteristicOutput.write(` super("${generated.name}", ${generated.className}.UUID, {\n`) - characteristicOutput.write(` format: Formats.${characteristicFormat(generated.format)},\n`) - characteristicOutput.write(` perms: [${generatePermsString(generated.properties)}],\n`) - if (generated.units && !undefinedUnits.includes(generated.units)) { - characteristicOutput.write(` unit: Units.${characteristicUnit(generated.units)},\n`) - } - if (generated.minValue != null) { - characteristicOutput.write(` minValue: ${generated.minValue},\n`) - } - if (generated.maxValue != null) { - characteristicOutput.write(` maxValue: ${generated.maxValue},\n`) - } - if (generated.stepValue != null) { - characteristicOutput.write(` minStep: ${generated.stepValue},\n`) - } - if (generated.maxLength != null) { - characteristicOutput.write(` maxLen: ${generated.maxLength},\n`) - } - if (validValuesEntries.length) { - characteristicOutput.write(` validValues: [${validValuesEntries.map(([value]) => value).join(', ')}],\n`) - } - if (generated.adminOnlyAccess) { - characteristicOutput.write(` adminOnlyAccess: [${ - generated.adminOnlyAccess.map(value => `Access.${characteristicAccess(value)}`).join(', ')}],\n`) - } - characteristicOutput.write(' });\n') - characteristicOutput.write(' this.value = this.getDefaultValue();\n') - characteristicOutput.write(' }\n') - characteristicOutput.write('}\n') - if (generated.deprecatedClassName) { - characteristicOutput.write('// noinspection JSDeprecatedSymbols\n') - characteristicOutput.write(`Characteristic.${generated.deprecatedClassName} = ${generated.className};\n`) - } - if (generated.deprecatedNotice) { - characteristicOutput.write('// noinspection JSDeprecatedSymbols\n') - } - characteristicOutput.write(`Characteristic.${generated.className} = ${generated.className};\n\n`) - } catch (error) { - throw new Error(`Error thrown writing characteristic '${generated.id}' (${generated.className}): ${errorMessage(error)}`, { cause: error }) - } } -characteristicOutput.end() - -const characteristicProperties = Object.entries(writtenCharacteristicEntries).sort(([a], [b]) => a.localeCompare(b)) -rewriteProperties('Characteristic', characteristicProperties) -writeCharacteristicTestFile() - /** * Services */ -const serviceOutput = fs.createWriteStream(path.join(import.meta.dirname, 'ServiceDefinitions.ts')) - -serviceOutput.write('// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n') -serviceOutput.write(`// V=${plistData.Version}\n`) -serviceOutput.write('\n') - -serviceOutput.write('import { Characteristic } from "../Characteristic.js";\n') -serviceOutput.write('import { Service } from "../Service.js";\n\n') - const generatedServices: Record = {} // indexed by id -const writtenServiceEntries: Record = {} // indexed by class name for (const [id, definition] of Object.entries(services)) { try { @@ -509,91 +425,196 @@ for (const [id, definition] of Object.entries(services)) { optionalCharacteristics, } generatedServices[id] = generatedService - writtenServiceEntries[className] = generatedService - if (deprecatedClassName) { - writtenServiceEntries[deprecatedClassName] = generatedService - } } catch (error) { throw new Error(`Error thrown generating service '${id}' (${definition.DefaultDescription}): ${errorMessage(error)}`, { cause: error }) } } +const plistServices = plistIndex(generatedServices) for (const [id, generated] of ServiceManualAdditions) { + checkManualAddition(SERVICES, plistServices, id, generated.UUID) generatedServices[id] = generated - writtenServiceEntries[generated.className] = generated - if (generated.deprecatedClassName) { - writtenServiceEntries[generated.deprecatedClassName] = generated +} + +/** + * Validation + */ + +// Every guard runs before the first output file opens: a regeneration that fails one leaves the committed files untouched. +checkOverlaps(CHARACTERISTICS, plistCharacteristics) +checkOverlaps(SERVICES, plistServices) +checkClassNames() +checkUUIDs(CHARACTERISTICS, generatedCharacteristics) +checkUUIDs(SERVICES, generatedServices) +checkServiceCharacteristics() + +/** + * Output + */ + +let characteristicOutput = '' + +characteristicOutput += '// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n' +characteristicOutput += `// V=${plistData.Version}\n` +characteristicOutput += '\n' + +characteristicOutput += 'import { Access, Characteristic, Formats, Perms, Units } from \'../Characteristic.js\'\n' + +for (const generated of Object.values(generatedCharacteristics) + .sort((a, b) => a.className.localeCompare(b.className))) { + try { + characteristicOutput += '\n/**\n' + characteristicOutput += ` * Characteristic "${generated.name}"\n` + if (generated.since) { + characteristicOutput += ` * @since iOS ${generated.since}\n` + } + if (generated.deprecatedNotice) { + characteristicOutput += ` * @deprecated ${generated.deprecatedNotice}\n` + } + characteristicOutput += ' */\n' + + characteristicOutput += `export class ${generated.className} extends Characteristic {\n` + + characteristicOutput += ` public static readonly UUID: string = ${quote(generated.UUID)}\n\n` + + const classAdditions = generated.classAdditions + if (classAdditions) { + characteristicOutput += `${classAdditions.map(line => ` ${line}\n`).join('')}\n` + } + + const validValuesEntries = Object.entries(generated.validValues ?? {}) + if (validValuesEntries.length) { + for (const [value, name] of validValuesEntries) { + if (!name) { + continue + } + const cleanName = name.replace(/_+$/, '') // remove any underscores at the end of the name + characteristicOutput += ` public static readonly ${cleanName} = ${value}\n` + } + characteristicOutput += '\n' + } + if (generated.validBitMasks) { + for (const [value, name] of Object.entries(generated.validBitMasks)) { + characteristicOutput += ` public static readonly ${name} = ${value}\n` + } + characteristicOutput += '\n' + } + + characteristicOutput += ' constructor() {\n' + characteristicOutput += ` super(${quote(generated.name)}, ${generated.className}.UUID, {\n` + characteristicOutput += ` format: Formats.${characteristicFormat(generated.format)},\n` + characteristicOutput += ` perms: ${arrayLiteral(generatePerms(generated.properties), ' ')},\n` + if (generated.units && !undefinedUnits.includes(generated.units)) { + characteristicOutput += ` unit: Units.${characteristicUnit(generated.units)},\n` + } + if (generated.minValue != null) { + characteristicOutput += ` minValue: ${generated.minValue},\n` + } + if (generated.maxValue != null) { + characteristicOutput += ` maxValue: ${generated.maxValue},\n` + } + if (generated.stepValue != null) { + characteristicOutput += ` minStep: ${generated.stepValue},\n` + } + if (generated.maxLength != null) { + characteristicOutput += ` maxLen: ${generated.maxLength},\n` + } + if (validValuesEntries.length) { + characteristicOutput += ` validValues: ${arrayLiteral(Object.keys(generated.validValues!), ' ')},\n` + } + if (generated.adminOnlyAccess) { + const access = generated.adminOnlyAccess.map(value => `Access.${characteristicAccess(value)}`) + characteristicOutput += ` adminOnlyAccess: ${arrayLiteral(access, ' ')},\n` + } + characteristicOutput += ' })\n' + characteristicOutput += ' this.value = this.getDefaultValue()\n' + characteristicOutput += ' }\n' + characteristicOutput += '}\n' + if (generated.deprecatedClassName) { + characteristicOutput += '// noinspection JSDeprecatedSymbols\n' + characteristicOutput += `Characteristic.${generated.deprecatedClassName} = ${generated.className}\n` + } + if (generated.deprecatedNotice) { + characteristicOutput += '// noinspection JSDeprecatedSymbols\n' + } + characteristicOutput += `Characteristic.${generated.className} = ${generated.className}\n` + } catch (error) { + throw new Error(`Error thrown writing characteristic '${generated.id}' (${generated.className}): ${errorMessage(error)}`, { cause: error }) } } +let serviceOutput = '' + +serviceOutput += '// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n' +serviceOutput += `// V=${plistData.Version}\n` +serviceOutput += '\n' + +serviceOutput += 'import { Characteristic } from \'../Characteristic.js\'\n' +serviceOutput += 'import { Service } from \'../Service.js\'\n' + for (const generated of Object.values(generatedServices) .sort((a, b) => a.className.localeCompare(b.className))) { try { - serviceOutput.write('/**\n') - serviceOutput.write(` * Service "${generated.name}"\n`) + serviceOutput += '\n/**\n' + serviceOutput += ` * Service "${generated.name}"\n` if (generated.since) { - serviceOutput.write(` * @since iOS ${generated.since}\n`) + serviceOutput += ` * @since iOS ${generated.since}\n` } if (generated.deprecatedNotice) { - serviceOutput.write(` * @deprecated ${generated.deprecatedNotice}\n`) + serviceOutput += ` * @deprecated ${generated.deprecatedNotice}\n` } - serviceOutput.write(' */\n') + serviceOutput += ' */\n' - serviceOutput.write(`export class ${generated.className} extends Service {\n\n`) + serviceOutput += `export class ${generated.className} extends Service {\n` - serviceOutput.write(` public static readonly UUID: string = "${generated.UUID}";\n\n`) + serviceOutput += ` public static readonly UUID: string = ${quote(generated.UUID)}\n\n` - serviceOutput.write(' constructor(displayName?: string, subtype?: string) {\n') - serviceOutput.write(` super(displayName, ${generated.className}.UUID, subtype);\n\n`) + serviceOutput += ' constructor(displayName?: string, subtype?: string) {\n' + serviceOutput += ` super(displayName, ${generated.className}.UUID, subtype)\n\n` - serviceOutput.write(' // Required Characteristics\n') + serviceOutput += ' // Required Characteristics\n' for (const required of generated.requiredCharacteristics) { - const characteristic = generatedCharacteristics[required] - if (!characteristic) { - console.warn(`Could not find required characteristic ${required} for ${generated.className}`) - continue - } - if (required === 'name') { - serviceOutput.write(' if (!this.testCharacteristic(Characteristic.Name)) { // workaround for Name characteristic collision in constructor\n') - serviceOutput.write(' this.addCharacteristic(Characteristic.Name).updateValue("Unnamed Service");\n') - serviceOutput.write(' }\n') + serviceOutput += ' if (!this.testCharacteristic(Characteristic.Name)) { // workaround for Name characteristic collision in constructor\n' + serviceOutput += ` this.addCharacteristic(Characteristic.Name).updateValue(${quote('Unnamed Service')})\n` + serviceOutput += ' }\n' } else { - serviceOutput.write(` this.addCharacteristic(Characteristic.${characteristic.className});\n`) + serviceOutput += ` this.addCharacteristic(Characteristic.${generatedCharacteristics[required].className})\n` } } if (generated.optionalCharacteristics?.length) { - serviceOutput.write('\n // Optional Characteristics\n') + serviceOutput += '\n // Optional Characteristics\n' for (const optional of generated.optionalCharacteristics) { - const characteristic = generatedCharacteristics[optional] - if (!characteristic) { - console.warn(`Could not find optional characteristic ${optional} for ${generated.className}`) - continue - } - serviceOutput.write(` this.addOptionalCharacteristic(Characteristic.${characteristic.className});\n`) + serviceOutput += ` this.addOptionalCharacteristic(Characteristic.${generatedCharacteristics[optional].className})\n` } } - serviceOutput.write(' }\n}\n') + serviceOutput += ' }\n}\n' if (generated.deprecatedClassName) { - serviceOutput.write('// noinspection JSDeprecatedSymbols\n') - serviceOutput.write(`Service.${generated.deprecatedClassName} = ${generated.className};\n`) + serviceOutput += '// noinspection JSDeprecatedSymbols\n' + serviceOutput += `Service.${generated.deprecatedClassName} = ${generated.className}\n` } if (generated.deprecatedNotice) { - serviceOutput.write('// noinspection JSDeprecatedSymbols\n') + serviceOutput += '// noinspection JSDeprecatedSymbols\n' } - serviceOutput.write(`Service.${generated.className} = ${generated.className};\n\n`) + serviceOutput += `Service.${generated.className} = ${generated.className}\n` } catch (error) { throw new Error(`Error thrown writing service '${generated.id}' (${generated.className}): ${errorMessage(error)}`, { cause: error }) } } -serviceOutput.end() - -const serviceProperties = Object.entries(writtenServiceEntries).sort(([a], [b]) => a.localeCompare(b)) -rewriteProperties('Service', serviceProperties) -writeServicesTestFile() +// Every generated file renders before the first is written: a throw while rendering any file leaves each one as it was. +const outputs = new Map() + .set(path.join(import.meta.dirname, 'CharacteristicDefinitions.ts'), characteristicOutput) + .set(classFile('Characteristic'), rewriteProperties('Characteristic', staticProperties(generatedCharacteristics))) + .set(path.resolve(import.meta.dirname, './CharacteristicDefinitions.spec.ts'), renderCharacteristicTestFile()) + .set(path.join(import.meta.dirname, 'ServiceDefinitions.ts'), serviceOutput) + .set(classFile('Service'), rewriteProperties('Service', staticProperties(generatedServices))) + .set(path.resolve(import.meta.dirname, './ServiceDefinitions.spec.ts'), renderServicesTestFile()) +for (const [filePath, content] of outputs) { + fs.writeFileSync(filePath, content, { encoding: 'utf8' }) +} // ------------------------ utils ------------------------ function checkDefined(input: T): T { @@ -659,7 +680,7 @@ function characteristicPerm(id: string): string | undefined { } } -function generatePermsString(propertiesBitMap: number): string { +function generatePerms(propertiesBitMap: number): string[] { const perms: string [] = [] for (const [bitMap, name] of properties) { @@ -672,9 +693,23 @@ function generatePermsString(propertiesBitMap: number): string { } } - const result = perms.join(', ') - assert(!!result, `perms string cannot be empty (${propertiesBitMap})`) - return result + assert(perms.length > 0, `perms cannot be empty (${propertiesBitMap})`) + return perms +} + +// The generated files are committed as the linter formats them, which is why the generator writes that text itself: a lint run with no fix checks it after every run. +function quote(value: string): string { + return `'${value.replaceAll('\\', '\\\\').replaceAll('\'', '\\\'')}'` +} + +// An array of four or more items whose inline form runs past 40 characters breaks one item per line, the defaults of antfu/reasonable-newline. +function arrayLiteral(items: string[], indent: string): string { + const inline = `[${items.join(', ')}]` + if (items.length < 4 || inline.length <= 40) { + return inline + } + + return `[\n${items.map(item => `${indent} ${item},\n`).join('')}${indent}]` } function checkWrittenVersion(filePath: string, parsingVersion: number): boolean { @@ -690,8 +725,116 @@ function checkWrittenVersion(filePath: string, parsingVersion: number): boolean return parsingVersion >= version } -function rewriteProperties(className: string, properties: [key: string, value: GeneratedCharacteristic | GeneratedService][]): void { - const filePath = path.resolve(import.meta.dirname, `../${className}.ts`) +function plistIndex(records: Record): PlistIndex { + return { + ids: new Set(Object.keys(records)), + idsByUUID: new Map(Object.entries(records).map(([id, record]) => [record.UUID, id])), + } +} + +function label(namespace: Namespace, id: string): string { + const origin = namespace.manualAdditions.has(id) + ? 'manual' + : 'plist' + return `${origin} ${namespace.kind} '${id}'` +} + +// A manual addition replaces a plist definition of its id, or shares a UUID with one, only where its namespace's overlap map declares it. +function checkManualAddition(namespace: Namespace, plist: PlistIndex, id: string, uuid: string): void { + if (plist.ids.has(id) && namespace.overlaps.get(id) !== id) { + throw new Error(`The ${label(namespace, id)} shadows the plist ${namespace.kind} of the same id, ` + + `and ${namespace.overlapsName} does not declare the overlap.`) + } + + const plistId = plist.idsByUUID.get(uuid) + if (plistId !== undefined && plistId !== id && namespace.overlaps.get(id) !== plistId) { + throw new Error(`The ${label(namespace, id)} uses UUID ${uuid} of the plist ${namespace.kind} '${plistId}', ` + + `and ${namespace.overlapsName} does not declare the overlap.`) + } +} + +// Each overlap entry must describe an overlap that occurs, because an entry left standing would silently waive the overlap checks for a later one nobody reviewed. +function checkOverlaps(namespace: Namespace, plist: PlistIndex): void { + for (const [id, plistId] of namespace.overlaps) { + const addition = namespace.manualAdditions.get(id) + const occurs = addition !== undefined && ((id === plistId && plist.ids.has(id)) || plist.idsByUUID.get(addition.UUID) === plistId) + if (!occurs) { + throw new Error(`The ${namespace.overlapsName} entry for '${id}' declares an overlap with the plist ${namespace.kind} '${plistId}' that does not occur.`) + } + } +} + +// The definitions barrel exports every generated class side by side. A class name is unique across the characteristic and service namespaces together. +function checkClassNames(): void { + const owners = new Map() + const claim = (namespace: Namespace, record: GeneratedCharacteristic | GeneratedService): void => { + for (const name of [record.className, record.deprecatedClassName]) { + if (name === undefined) { + continue + } + + const owner = `the ${label(namespace, record.id)}` + const previous = owners.get(name) + if (previous !== undefined) { + throw new Error(`The class name ${name} is used by both ${previous} and ${owner}.`) + } + owners.set(name, owner) + } + } + + for (const record of Object.values(generatedCharacteristics)) { + claim(CHARACTERISTICS, record) + } + for (const record of Object.values(generatedServices)) { + claim(SERVICES, record) + } +} + +function checkUUIDs(namespace: Namespace, records: Record): void { + const owners = new Map() + for (const record of Object.values(records)) { + const previous = owners.get(record.UUID) + if (previous !== undefined && namespace.overlaps.get(previous) !== record.id && namespace.overlaps.get(record.id) !== previous) { + throw new Error(`The ${namespace.kind} UUID ${record.UUID} is used by both the ${label(namespace, previous)} and the ${label(namespace, record.id)}, ` + + `and ${namespace.overlapsName} does not declare the overlap.`) + } + owners.set(record.UUID, record.id) + } +} + +// A plist service listing a characteristic the plist lacks is answered by a removedRequired or removedOptional override in the configuration. +function checkServiceCharacteristics(): void { + for (const service of Object.values(generatedServices)) { + for (const id of service.requiredCharacteristics.concat(service.optionalCharacteristics ?? [])) { + if (!Object.hasOwn(generatedCharacteristics, id)) { + if (CharacteristicHidden.has(id)) { + throw new Error(`The ${label(SERVICES, service.id)} lists the characteristic '${id}', which CharacteristicHidden hides.`) + } + throw new Error(`The ${label(SERVICES, service.id)} lists the characteristic '${id}', which neither the plist nor a manual addition defines.`) + } + } + } +} + +// A class file declares one static property per class name the merged definitions assign, and a plist record that a manual addition replaces leaves no property behind. +function staticProperties(records: Record): [key: string, value: GeneratedCharacteristic | GeneratedService][] { + const properties: [key: string, value: GeneratedCharacteristic | GeneratedService][] = [] + for (const record of Object.values(records)) { + for (const name of [record.className, record.deprecatedClassName]) { + if (name !== undefined) { + properties.push([name, record]) + } + } + } + return properties.sort(([a], [b]) => a.localeCompare(b)) +} + +function classFile(className: string): string { + return path.resolve(import.meta.dirname, `../${className}.ts`) +} + +function rewriteProperties(className: string, properties: [key: string, value: GeneratedCharacteristic | GeneratedService][]): string { + const filePath = classFile(className) if (!fs.existsSync(filePath)) { throw new Error(`File '${filePath}' does not exist!`) } @@ -741,10 +884,15 @@ function rewriteProperties(className: string, properties: [key: string, value: G throw new Error('Could not find stop pattern in file!') } + // The import block takes the natural order perfectionist/sort-named-imports checks, where PM2_5Density precedes PM10Density, while the static + // properties below keep the plain localeCompare order the corpus was written in. const importSize = importEnd - importStart - 1 + const naturalOrder = new Intl.Collator('en', { numeric: true }).compare const newImports = properties .filter(([key, value]) => key === value.className) - .map(([key]) => ` ${key},`) + .map(([key]) => key) + .sort(naturalOrder) + .map(key => ` ${key},`) lines.splice(importStart + 1, importSize, ...newImports) // remove current imports const importDelta = newImports.length - importSize @@ -772,91 +920,90 @@ function rewriteProperties(className: string, properties: [key: string, value: G } line += ' */\n' - line += ` public static ${key}: typeof ${value.className};` + line += ` public static ${key}: typeof ${value.className}` return line }) lines.splice(startIndex + 1, amount, ...newContentLines) // insert new lines - const resultContent = lines.join('\n') - fs.writeFileSync(filePath, resultContent, { encoding: 'utf8' }) + return lines.join('\n') } -function writeCharacteristicTestFile(): void { +function renderCharacteristicTestFile(): string { const characteristics = Object.values(generatedCharacteristics).sort((a, b) => a.className.localeCompare(b.className)) - const testOutput = fs.createWriteStream(path.resolve(import.meta.dirname, './CharacteristicDefinitions.spec.ts'), { encoding: 'utf8' }) - testOutput.write('// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n') - testOutput.write('import { describe, expect, it } from "vitest";\n') - testOutput.write('import "./index.js";\n\n') - testOutput.write('import { Characteristic } from "../Characteristic.js";\n\n') - testOutput.write('describe("CharacteristicDefinitions", () => {') + let testOutput = '' + testOutput += '// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n' + testOutput += 'import { describe, expect, it } from \'vitest\'\n\n' + testOutput += 'import { Characteristic } from \'../Characteristic.js\'\n\n' + testOutput += 'import \'./index.js\'\n\n' + testOutput += 'describe(\'CharacteristicDefinitions\', () => {' for (const generated of characteristics) { - testOutput.write('\n') - testOutput.write(` describe("${generated.className}", () => {\n`) + testOutput += '\n' + testOutput += ` describe(${quote(generated.className)}, () => {\n` // first test is just calling the constructor - testOutput.write(' it("should be able to construct", () => {\n') - testOutput.write(` expect(() => new Characteristic.${generated.className}()).not.toThrow();\n`) + testOutput += ' it(\'should be able to construct\', () => {\n' + testOutput += ` expect(() => new Characteristic.${generated.className}()).not.toThrow()\n` if (generated.deprecatedClassName) { - testOutput.write(' // noinspection JSDeprecatedSymbols\n') - testOutput.write(` expect(() => new Characteristic.${generated.deprecatedClassName}()).not.toThrow();\n`) + testOutput += ' // noinspection JSDeprecatedSymbols\n' + testOutput += ` expect(() => new Characteristic.${generated.deprecatedClassName}()).not.toThrow()\n` } - testOutput.write(' });\n') + testOutput += ' })\n' - testOutput.write(' });\n') + testOutput += ' })\n' } - testOutput.write('});\n') - testOutput.end() + testOutput += '})\n' + return testOutput } -function writeServicesTestFile(): void { +function renderServicesTestFile(): string { const services = Object.values(generatedServices).sort((a, b) => a.className.localeCompare(b.className)) - const testOutput = fs.createWriteStream(path.resolve(import.meta.dirname, './ServiceDefinitions.spec.ts'), { encoding: 'utf8' }) - testOutput.write('// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n') - testOutput.write('import { describe, expect, it } from "vitest";\n') - testOutput.write('import "./index.js";\n\n') - testOutput.write('import { Characteristic } from "../Characteristic.js";\n') - testOutput.write('import { Service } from "../Service.js";\n\n') - testOutput.write('describe("ServiceDefinitions", () => {') + let testOutput = '' + testOutput += '// THIS FILE IS AUTO-GENERATED - DO NOT MODIFY\n' + testOutput += 'import { describe, expect, it } from \'vitest\'\n\n' + testOutput += 'import { Characteristic } from \'../Characteristic.js\'\n' + testOutput += 'import { Service } from \'../Service.js\'\n\n' + testOutput += 'import \'./index.js\'\n\n' + testOutput += 'describe(\'ServiceDefinitions\', () => {' for (const generated of services) { - testOutput.write('\n') - testOutput.write(` describe("${generated.className}", () => {\n`) + testOutput += '\n' + testOutput += ` describe(${quote(generated.className)}, () => {\n` // first test is just calling the constructor - testOutput.write(' it("should be able to construct", () => {\n') + testOutput += ' it(\'should be able to construct\', () => {\n' - testOutput.write(` const service0 = new Service.${generated.className}();\n`) - testOutput.write(` const service1 = new Service.${generated.className}("test name");\n`) - testOutput.write(` const service2 = new Service.${generated.className}("test name", "test sub type");\n\n`) + testOutput += ` const service0 = new Service.${generated.className}()\n` + testOutput += ` const service1 = new Service.${generated.className}('test name')\n` + testOutput += ` const service2 = new Service.${generated.className}('test name', 'test sub type')\n\n` - testOutput.write(' expect(service0.displayName).toBe("");\n') - testOutput.write(` expect(service0.testCharacteristic(Characteristic.Name)).toBe(${generated.requiredCharacteristics.includes('name')});\n`) - testOutput.write(' expect(service0.subtype).toBeUndefined();\n\n') + testOutput += ' expect(service0.displayName).toBe(\'\')\n' + testOutput += ` expect(service0.testCharacteristic(Characteristic.Name)).toBe(${generated.requiredCharacteristics.includes('name')})\n` + testOutput += ' expect(service0.subtype).toBeUndefined()\n\n' - testOutput.write(' expect(service1.displayName).toBe("test name");\n') - testOutput.write(' expect(service1.testCharacteristic(Characteristic.Name)).toBe(true);\n') - testOutput.write(' expect(service1.getCharacteristic(Characteristic.Name).value).toBe("test name");\n') - testOutput.write(' expect(service1.subtype).toBeUndefined();\n\n') + testOutput += ' expect(service1.displayName).toBe(\'test name\')\n' + testOutput += ' expect(service1.testCharacteristic(Characteristic.Name)).toBe(true)\n' + testOutput += ' expect(service1.getCharacteristic(Characteristic.Name).value).toBe(\'test name\')\n' + testOutput += ' expect(service1.subtype).toBeUndefined()\n\n' - testOutput.write(' expect(service2.displayName).toBe("test name");\n') - testOutput.write(' expect(service2.testCharacteristic(Characteristic.Name)).toBe(true);\n') - testOutput.write(' expect(service2.getCharacteristic(Characteristic.Name).value).toBe("test name");\n') - testOutput.write(' expect(service2.subtype).toBe("test sub type");\n') + testOutput += ' expect(service2.displayName).toBe(\'test name\')\n' + testOutput += ' expect(service2.testCharacteristic(Characteristic.Name)).toBe(true)\n' + testOutput += ' expect(service2.getCharacteristic(Characteristic.Name).value).toBe(\'test name\')\n' + testOutput += ' expect(service2.subtype).toBe(\'test sub type\')\n' if (generated.deprecatedClassName) { - testOutput.write(' // noinspection JSDeprecatedSymbols\n') - testOutput.write(`\n expect(() => new Service.${generated.deprecatedClassName}()).not.toThrow();\n`) + testOutput += '\n // noinspection JSDeprecatedSymbols\n' + testOutput += ` expect(() => new Service.${generated.deprecatedClassName}()).not.toThrow()\n` } - testOutput.write(' });\n') + testOutput += ' })\n' - testOutput.write(' });\n') + testOutput += ' })\n' } - testOutput.write('});\n') - testOutput.end() + testOutput += '})\n' + return testOutput } diff --git a/src/lib/definitions/generator-configuration.ts b/src/lib/definitions/generator-configuration.ts index e40c32d38..d67cae329 100644 --- a/src/lib/definitions/generator-configuration.ts +++ b/src/lib/definitions/generator-configuration.ts @@ -409,18 +409,6 @@ export const CharacteristicManualAdditions: Map maxValue: 360, }, ], - [ - 'version', - { // don't know why, but version has notify permission even if it shouldn't have one - id: 'version', - UUID: '00000037-0000-1000-8000-0026BB765291', - name: 'Version', - className: 'Version', - format: 'string', - properties: 2, // paired read - maxLength: 64, - }, - ], [ 'crypto-hash', { @@ -644,6 +632,17 @@ export const ServiceManualAdditions: Map = new Map([ ], ]) +/** + * Manual additions that deliberately overlap a plist definition, each mapped to the id of the plist definition it overlaps. Regeneration fails on every + * other overlap: a manual id the plist also defines, a manual UUID the plist gives another id, and a UUID repeated within one namespace. + */ +export const CharacteristicManualOverlaps: Map = new Map([]) + +export const ServiceManualOverlaps: Map = new Map([ + // The original Speaker service shares its UUID with the plist speaker service, which generates as TelevisionSpeaker. + ['og-speaker', 'speaker'], +]) + export const CharacteristicSinceInformation: Map = new Map([ ['activity-interval', '14'], ['cca-energy-detect-threshold', '14'], From 3cb15bf29e1a7a1a6579aa0879d338735d43bb92 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:42 -0600 Subject: [PATCH 02/16] feat(tlv): read and write 64-bit integers as bigint --- src/hap.ts | 17 +++++++++- src/lib/util/tlv.spec.ts | 69 +++++++++++++++++++++++++++++++++++++++- src/lib/util/tlv.ts | 68 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 152 insertions(+), 2 deletions(-) diff --git a/src/hap.ts b/src/hap.ts index 5269522ad..aa85b8d12 100644 --- a/src/hap.ts +++ b/src/hap.ts @@ -37,7 +37,22 @@ export * from './lib/util/eventedhttp.js' export * from './lib/util/hapStatusError.js' export * from './lib/util/once.js' export * from './lib/util/time.js' -export * from './lib/util/tlv.js' +// The TLV module's helpers are named one by one: the 64-bit helpers the camera's fields read stay the library's own. +export type { TLVEncodable } from './lib/util/tlv.js' +export { + decode, + decodeList, + decodeWithLists, + encode, + readUInt16, + readUInt32, + readUInt64LE, + readVariableUIntLE, + writeFloat32LE, + writeUInt16, + writeUInt32, + writeVariableUIntLE, +} from './lib/util/tlv.js' /** * @group Utils diff --git a/src/lib/util/tlv.spec.ts b/src/lib/util/tlv.spec.ts index a6bd8bc10..d9eb61092 100644 --- a/src/lib/util/tlv.spec.ts +++ b/src/lib/util/tlv.spec.ts @@ -2,7 +2,19 @@ import { Buffer } from 'node:buffer' import { describe, expect, it } from 'vitest' -import { decode, decodeList, decodeWithLists, encode, readVariableUIntLE, writeVariableUIntLE } from './tlv.js' +import { + decode, + decodeList, + decodeWithLists, + encode, + readBigUInt64LE, + readUInt64LE, + readVariableBigUIntLE, + readVariableUIntLE, + writeBigUInt64LE, + writeVariableBigUIntLE, + writeVariableUIntLE, +} from './tlv.js' const HELLO_WORLD_BUFFER = Buffer.from('Hello World!') @@ -311,4 +323,59 @@ describe('tlv', () => { expect(readVariableUIntLE(buffer64)).toBe(input64) }) }) + + describe('bigint', () => { + it.each([ + ['0', 0n, '0000000000000000'], + ['1', 1n, '0100000000000000'], + ['255', 255n, 'ff00000000000000'], + ['2^32', 2n ** 32n, '0000000001000000'], + ['2^53 - 1', 2n ** 53n - 1n, 'ffffffffffff1f00'], + ['2^53', 2n ** 53n, '0000000000002000'], + ['2^53 + 1', 2n ** 53n + 1n, '0100000000002000'], + ['2^63', 2n ** 63n, '0000000000000080'], + ['2^64 - 1', 2n ** 64n - 1n, 'ffffffffffffffff'], + ])('writeBigUInt64LE and readBigUInt64LE round-trip %s exactly', (_, value, hex) => { + expect(writeBigUInt64LE(value).toString('hex')).toBe(hex) + expect(readBigUInt64LE(Buffer.from(hex, 'hex'))).toBe(value) + }) + + it.each([ + ['255', 255n, 'ff'], + ['256', 256n, '0001'], + ['65535', 65535n, 'ffff'], + ['65536', 65536n, '00000100'], + ['2^32 - 1', 2n ** 32n - 1n, 'ffffffff'], + ['2^32', 2n ** 32n, '0000000001000000'], + ['2^53 + 1', 2n ** 53n + 1n, '0100000000002000'], + ['2^64 - 1', 2n ** 64n - 1n, 'ffffffffffffffff'], + ])('writeVariableBigUIntLE and readVariableBigUIntLE round-trip %s in the fewest bytes', (_, value, hex) => { + expect(writeVariableBigUIntLE(value).toString('hex')).toBe(hex) + expect(readVariableBigUIntLE(Buffer.from(hex, 'hex'))).toBe(value) + }) + + it('readBigUInt64LE reads 2^53 + 1 exactly, where readUInt64LE rounds it to 2^53', () => { + const buffer = Buffer.from('0100000000002000', 'hex') + expect(readBigUInt64LE(buffer)).toBe(9007199254740993n) + expect(readUInt64LE(buffer)).toBe(9007199254740992) + }) + + it('readBigUInt64LE reads at an offset', () => { + expect(readBigUInt64LE(Buffer.from('aa0100000000002000', 'hex'), 1)).toBe(9007199254740993n) + }) + + it('the 64-bit writers throw a RangeError outside the uint64 range', () => { + expect(() => writeBigUInt64LE(2n ** 64n)).toThrow(RangeError) + expect(() => writeVariableBigUIntLE(2n ** 64n)).toThrow(RangeError) + expect(() => writeBigUInt64LE(-1n)).toThrow(RangeError) + }) + + it('writeVariableBigUIntLE rejects a negative integer', () => { + expect(() => writeVariableBigUIntLE(-1n)).toThrow('Can\'t encode a negative integer as unsigned integer') + }) + + it('readVariableBigUIntLE rejects a width it never writes', () => { + expect(() => readVariableBigUIntLE(Buffer.alloc(3))).toThrow('Can\'t read uint LE with length 3') + }) + }) }) diff --git a/src/lib/util/tlv.ts b/src/lib/util/tlv.ts index dcd9c6b30..0c5033d1f 100644 --- a/src/lib/util/tlv.ts +++ b/src/lib/util/tlv.ts @@ -275,6 +275,31 @@ export function readUInt64LE(buffer: Buffer, offset = 0): number { return buffer.readUInt32LE(offset + 4) * 0x100000000 + low } +/** + * Reads an unsigned 64-bit little-endian integer as a bigint, exact across the whole uint64 range. + * New code reads 64-bit values through this rather than {@link readUInt64LE}, whose number result loses precision above 2^53. + * @param buffer - The buffer to read from. + * @param offset - The byte offset the integer starts at. + * @returns The integer. + * @group TLV8 + */ +export function readBigUInt64LE(buffer: Buffer, offset = 0): bigint { + return buffer.readBigUInt64LE(offset) +} + +/** + * Writes an unsigned 64-bit little-endian integer from a bigint, exact across the whole uint64 range. + * A value outside the uint64 range throws the RangeError of the underlying `Buffer` write. + * @param value - The integer to write. + * @returns A new eight-byte buffer. + * @group TLV8 + */ +export function writeBigUInt64LE(value: bigint): Buffer { + const buffer = Buffer.alloc(8) + buffer.writeBigUInt64LE(value, 0) + return buffer +} + /** * `writeUint32LE` * @group TLV8 @@ -371,3 +396,46 @@ export function writeVariableUIntLE(number: number): Buffer { return buffer } } + +/** + * Reads a variable size unsigned integer as a bigint, the counterpart of {@link writeVariableBigUIntLE}. + * @param buffer - The buffer to read from. Its length is the integer's width, one of those {@link writeVariableBigUIntLE} writes. + * @returns The integer. + * @group TLV8 + */ +export function readVariableBigUIntLE(buffer: Buffer): bigint { + switch (buffer.length) { + case 1: + return BigInt(buffer.readUInt8(0)) + case 2: + return BigInt(buffer.readUInt16LE(0)) + case 4: + return BigInt(buffer.readUInt32LE(0)) + case 8: + return buffer.readBigUInt64LE(0) + default: + throw new Error(`Can't read uint LE with length ${buffer.length}`) + } +} + +/** + * Writes a bigint as a variable size unsigned integer in the fewest bytes that hold it: 1, 2, 4 or 8. + * @param value - The integer to write. A negative value fails an assertion, and a value past the uint64 range throws a RangeError. + * @returns A new buffer of the chosen size. + * @group TLV8 + */ +export function writeVariableBigUIntLE(value: bigint): Buffer { + assert(value >= 0n, 'Can\'t encode a negative integer as unsigned integer') + + if (value <= 0xFFn) { + const buffer = Buffer.alloc(1) + buffer.writeUInt8(Number(value), 0) + return buffer + } else if (value <= 0xFFFFn) { + return writeUInt16(Number(value)) + } else if (value <= 0xFFFFFFFFn) { + return writeUInt32(Number(value)) + } else { + return writeBigUInt64LE(value) + } +} From e5b2db2091ca4bbef0cd0066f8000487dfbc1e51 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:43 -0600 Subject: [PATCH 03/16] feat(characteristic): add the transient and sensitive props flags, which keep a control point's values from lingering and a key's value out of the debug log --- src/lib/Accessory.spec.ts | 240 ++++++++++++ src/lib/Accessory.ts | 14 +- src/lib/Characteristic.spec.ts | 404 ++++++++++++++++++++ src/lib/Characteristic.ts | 208 +++++++++- src/lib/definitions/generate-definitions.ts | 8 + src/test-utils/connectionFixtures.ts | 45 +++ 6 files changed, 909 insertions(+), 10 deletions(-) create mode 100644 src/test-utils/connectionFixtures.ts diff --git a/src/lib/Accessory.spec.ts b/src/lib/Accessory.spec.ts index 1651fd535..a2e8759cd 100644 --- a/src/lib/Accessory.spec.ts +++ b/src/lib/Accessory.spec.ts @@ -25,9 +25,12 @@ import type { PairingInformation } from './model/AccessoryInfo.js' import { Buffer } from 'node:buffer' import crypto from 'node:crypto' +import { format } from 'node:util' +import createDebug from 'debug' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { buildEmitterConnection } from '../test-utils/connectionFixtures.js' import { ResourceRequestType, } from '../types.js' @@ -2233,6 +2236,243 @@ describe('Accessory', () => { }) }) + it('answers a transient write response to its write and to a read on the writing connection, and the default value to another connection', async () => { + onCharacteristic.setProps({ + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + onCharacteristic.onSet(() => 'AQEB') + + // The write and the reads run on emitter connections, because the hold reads the writer's connection and the shared one carries none of its methods. + connection = buildEmitterConnection() + const other = buildEmitterConnection() + + await testRequestResponse({ + characteristics: [ + { + aid, + iid: iids.on, + value: 'AQEC', + r: true, + }, + ], + }, { + aid, + iid: iids.on, + status: HAPStatus.SUCCESS, + value: 'AQEB', + }) + + const readRequest = { + ids: [ + { aid, iid: iids.on }, + ], + includeMeta: false, + includeEvent: false, + includeType: false, + includePerms: false, + } + + // @ts-expect-error: private access + accessory.handleGetCharacteristics(connection, readRequest, callback) + + await callbackPromise + + const writerResponse: CharacteristicsReadResponse = { + characteristics: [ + { aid, iid: iids.on, value: 'AQEB' }, + ], + } + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback).toHaveBeenCalledWith(undefined, writerResponse) + + callback.mockReset() + + // @ts-expect-error: private access + accessory.handleGetCharacteristics(other, readRequest, callback) + + await callbackPromise + + const otherResponse: CharacteristicsReadResponse = { + characteristics: [ + { aid, iid: iids.on, value: '' }, + ], + } + + expect(callback).toHaveBeenCalledTimes(1) + expect(callback).toHaveBeenCalledWith(undefined, otherResponse) + }) + + /* Captures each debug line the accessory prints during a row of the describe that calls it, rendered as it would reach the log, which lets a row read the + * value each line carries. The hooks it registers put the debug module back after each row. + */ + function captureAccessoryDebugLines(): (needle: string) => string[] { + let originalEnable: string + let originalLog: (...args: unknown[]) => unknown + let captured: string[] + + beforeEach(() => { + captured = [] + originalEnable = createDebug.disable() + originalLog = createDebug.log + createDebug.log = (...args: unknown[]) => { + captured.push(format(...args)) + } + createDebug.enable('HAP-NodeJS:Accessory') + }) + + afterEach(() => { + createDebug.log = originalLog + createDebug.disable() + if (originalEnable) { + createDebug.enable(originalEnable) + } + }) + + return needle => captured.filter(line => line.includes(needle)) + } + + describe('write debug lines', () => { + const SECRET = 'U0VDUkVU' + + // Each debug line the accessory prints during a row, which lets a row read the value each line carries. + const linesWith = captureAccessoryDebugLines() + + // One successful write and one the handler refuses: the processing, setting and error lines each print the written value once or twice. + const writeSuccessThenRefusal = async (): Promise => { + onCharacteristic.onSet(() => {}) + + await testRequestResponse({ + characteristics: [ + { aid, iid: iids.on, value: SECRET }, + ], + }, { + aid, + iid: iids.on, + status: HAPStatus.SUCCESS, + }) + + onCharacteristic.onSet(() => { + throw new HapStatusError(HAPStatus.RESOURCE_BUSY) + }) + + await testRequestResponse({ + characteristics: [ + { aid, iid: iids.on, value: SECRET }, + ], + }, { + aid, + iid: iids.on, + status: HAPStatus.RESOURCE_BUSY, + }) + } + + it('print a marker in place of a value written to a sensitive characteristic', async () => { + onCharacteristic.setProps({ + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + sensitive: true, + }) + + await writeSuccessThenRefusal() + + expect(linesWith('Processing characteristic set')).toEqual([ + expect.stringContaining('"value":""'), + expect.stringContaining('"value":""'), + ]) + expect(linesWith('Setting Characteristic')).toEqual([ + expect.stringContaining('to value '), + ]) + expect(linesWith('Error setting Characteristic')).toEqual([ + expect.stringContaining('to value '), + ]) + expect(linesWith(SECRET)).toEqual([]) + }) + + it('print a TLV8 value written to a characteristic without the flag as its size, and the request with each value hidden', async () => { + onCharacteristic.setProps({ + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + + await writeSuccessThenRefusal() + + expect(linesWith('Processing characteristic set')).toEqual([ + expect.stringContaining('"value":""'), + expect.stringContaining('"value":""'), + ]) + expect(linesWith('Setting Characteristic')).toEqual([ + expect.stringContaining('to value '), + ]) + expect(linesWith('Error setting Characteristic')).toEqual([ + expect.stringContaining('to value '), + ]) + expect(linesWith('')).toEqual([]) + expect(linesWith(SECRET)).toEqual([]) + }) + }) + + describe('read debug lines', () => { + const SECRET = 'U0VDUkVU' + + // Each debug line the accessory prints during a row, which lets a row read the value each line carries. + const linesWith = captureAccessoryDebugLines() + + // One read the read handler answers with the secret. + const readSecret = async (): Promise => { + onCharacteristic.onGet(() => SECRET) + + // @ts-expect-error: private access + accessory.handleGetCharacteristics(connection, { + ids: [ + { aid, iid: iids.on }, + ], + includeMeta: false, + includeEvent: false, + includeType: false, + includePerms: false, + }, callback) + + await callbackPromise + } + + it('print a marker in place of a value read from a sensitive characteristic', async () => { + onCharacteristic.setProps({ + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + sensitive: true, + }) + + await readSecret() + + expect(linesWith('Got Characteristic')).toEqual([ + expect.stringContaining('value: ""'), + ]) + expect(linesWith(SECRET)).toEqual([]) + }) + + it('print a TLV8 value read from a characteristic without the flag as its size', async () => { + onCharacteristic.setProps({ + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + + await readSecret() + + expect(linesWith('Got Characteristic')).toEqual([ + expect.stringContaining('value: ""'), + ]) + expect(linesWith('')).toEqual([]) + expect(linesWith(SECRET)).toEqual([]) + }) + }) + it('write non-existent characteristic', async () => { await testRequestResponse({ characteristics: [ diff --git a/src/lib/Accessory.ts b/src/lib/Accessory.ts index 692cb481d..e5faeffd9 100644 --- a/src/lib/Accessory.ts +++ b/src/lib/Accessory.ts @@ -96,6 +96,8 @@ function isCharacteristicOperationContext(context: unknown): context is Characte const hksvDebug = createDebug('HAP-NodeJS:HKSV') const MAX_ACCESSORIES = 149 // Maximum number of bridged accessories per bridge. const MAX_SERVICES = 100 +// The debug lines print this in place of a value written to or read from a sensitive characteristic, because users paste debug logs into public issues. +const REDACTED_VALUE = '' /** * Known category values. Category is a hint to iOS clients about what "type" of Accessory this represents, for UI only. @@ -1862,7 +1864,10 @@ export class Accessory extends EventEmitter { return characteristic.handleGetRequest(connection).then((value) => { value = formatOutgoingCharacteristicValue(value, characteristic.props) - debug('[%s] Got Characteristic "%s" value: "%s"', this.displayName, characteristic.displayName, loggableValue(characteristic, value)) + debug('[%s] Got Characteristic "%s" value: "%s"', this.displayName, characteristic.displayName, + characteristic.props.sensitive + ? REDACTED_VALUE + : loggableValue(characteristic, value)) const data: PartialCharacteristicReadData = { value: value ?? null, @@ -2023,13 +2028,16 @@ export class Accessory extends EventEmitter { } const accessory = this.getAccessoryByAID(data.aid) + const loggedValue = characteristic.props.sensitive + ? REDACTED_VALUE + : loggableValue(characteristic, data.value) return characteristic.handleSetRequest(data.value, connection).then(async (value) => { if (data.value && accessory?.isIdentifyCharacteristic(characteristic)) { await accessory.handlePairedIdentify(characteristic) } return value }).then((value) => { - debug('[%s] Setting Characteristic "%s" to value %s', this.displayName, characteristic.displayName, loggableValue(characteristic, data.value)) + debug('[%s] Setting Characteristic "%s" to value %s', this.displayName, characteristic.displayName, loggedValue) return { // if write response is requested and a value is provided (0, false and '' are values too), return that value: data.r && value != null @@ -2039,7 +2047,7 @@ export class Accessory extends EventEmitter { status: HAPStatus.SUCCESS, } }, (status: HAPStatus) => { - debug('[%s] Error setting Characteristic "%s" to value %s: ', this.displayName, characteristic.displayName, loggableValue(characteristic, data.value), HAPStatus[status]) + debug('[%s] Error setting Characteristic "%s" to value %s: ', this.displayName, characteristic.displayName, loggedValue, HAPStatus[status]) return { status } }) diff --git a/src/lib/Characteristic.spec.ts b/src/lib/Characteristic.spec.ts index 9bcc96411..d18724120 100644 --- a/src/lib/Characteristic.spec.ts +++ b/src/lib/Characteristic.spec.ts @@ -11,6 +11,7 @@ import { Buffer } from 'node:buffer' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { buildEmitterConnection } from '../test-utils/connectionFixtures.js' import { CharacteristicWarningType } from './Accessory.js' import { Access, @@ -24,6 +25,7 @@ import { } from './Characteristic.js' import { SelectedRTPStreamConfiguration } from './definitions/index.js' import { HAPStatus } from './HAPServer.js' +import { HAPConnectionEvent } from './util/eventedhttp.js' import { HapStatusError } from './util/hapStatusError.js' import * as uuid from './util/uuid.js' @@ -2913,3 +2915,405 @@ describe('Characteristic', () => { }) }) }) + +describe('transient characteristics', () => { + const WRITE_RESPONSE_PERMS = [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE] + let connection: HAPConnection + + beforeEach(() => { + connection = buildEmitterConnection() + }) + + function createTransientCharacteristic(): Characteristic { + return createCharacteristicWithProps({ + format: Formats.TLV8, + perms: WRITE_RESPONSE_PERMS, + transient: true, + }) + } + + it('keeps the flag through construction and clears it with null', () => { + const characteristic = createTransientCharacteristic() + + expect(characteristic.props.transient).toBe(true) + expect(characteristic.value).toBeNull() + + characteristic.setProps({ transient: null }) + + expect(characteristic.props.transient).toBeUndefined() + }) + + it('resolves an onSet write response without storing it or emitting a change', async () => { + const characteristic = createTransientCharacteristic() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + characteristic.onSet(() => 'AQEB') + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB') + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('resolves an on(\'set\') write response without storing it or emitting a change', async () => { + const characteristic = createTransientCharacteristic() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + characteristic.on('set', (_value, callback) => { + callback(undefined, 'AQEB') + }) + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB') + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('stores no value and emits no change for an onSet write without a response', async () => { + const characteristic = createTransientCharacteristic() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + characteristic.onSet(vi.fn()) + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined() + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('stores no value and emits no change for a write without a handler', async () => { + const characteristic = createTransientCharacteristic() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined() + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('stores no value and emits no change for an on(\'set\') write without a response', async () => { + const characteristic = createTransientCharacteristic() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + characteristic.on('set', (_value, callback) => { + callback() + }) + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined() + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('reads the format\'s default value rather than a stored value when it has no read handler', async () => { + const characteristic = createTransientCharacteristic() + characteristic.value = 'AQEB' + + await expect(characteristic.handleGetRequest()).resolves.toBe('') + }) + + it('resolves an onGet value without storing it or emitting a change', async () => { + const characteristic = createTransientCharacteristic() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + characteristic.onGet(() => 'AgEA') + + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AgEA') + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('resolves an on(\'get\') value without storing it or emitting a change', async () => { + const characteristic = createTransientCharacteristic() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + characteristic.on(CharacteristicEventTypes.GET, (callback) => { + callback(undefined, 'AgEA') + }) + + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AgEA') + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('serves the format\'s default value from the cached representation', async () => { + const characteristic = createTransientCharacteristic() + characteristic.iid = 1 + characteristic.value = 'AQEB' + + const json = await characteristic.toHAP(connection, false) + + expect(json.value).toBe('') + }) + + it('serves the format\'s default value when the read handler throws', async () => { + const characteristic = createTransientCharacteristic() + characteristic.iid = 1 + characteristic.onGet(() => { + throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + }) + + const json = await characteristic.toHAP(connection) + + expect(json.value).toBe('') + }) + + it('serializes no value and keeps the flag', () => { + const characteristic = createTransientCharacteristic() + characteristic.value = 'AQEB' + + const json = Characteristic.serialize(characteristic) + + expect(json.value).toBeNull() + expect(json.props.transient).toBe(true) + }) + + it('keeps the flag through deserialize with and without a known constructor', () => { + const json = Characteristic.serialize(createTransientCharacteristic()) + + expect(Characteristic.deserialize(json).props.transient).toBe(true) + expect(Characteristic.deserialize({ ...json, constructorName: 'CryptoHash', UUID: Characteristic.CryptoHash.UUID }).props.transient).toBe(true) + }) + + it('stores and serves an onSet write response without the flag', async () => { + const characteristic = createCharacteristicWithProps({ format: Formats.TLV8, perms: WRITE_RESPONSE_PERMS }) + characteristic.onSet(() => 'AQEB') + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB') + expect(characteristic.value).toBe('AQEB') + await expect(characteristic.handleGetRequest()).resolves.toBe('AQEB') + }) + + it('stores and serves an on(\'set\') write response without the flag', async () => { + const characteristic = createCharacteristicWithProps({ format: Formats.TLV8, perms: WRITE_RESPONSE_PERMS }) + characteristic.on('set', (_value, callback) => { + callback(undefined, 'AQEB') + }) + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB') + expect(characteristic.value).toBe('AQEB') + await expect(characteristic.handleGetRequest()).resolves.toBe('AQEB') + }) + + it('restores no value from a cache that carries one, with and without a known constructor', () => { + const json: SerializedCharacteristic = { + displayName: 'Test', + UUID: uuid.generate('Foo'), + eventOnlyCharacteristic: false, + value: 'AQEB', + props: { + format: Formats.TLV8, + perms: WRITE_RESPONSE_PERMS, + transient: true, + }, + } + + expect(Characteristic.deserialize(json).value).toBeNull() + expect(Characteristic.deserialize({ ...json, constructorName: 'CryptoHash', UUID: Characteristic.CryptoHash.UUID }).value).toBe('') + }) + + it('holds an onSet answer for its writer, whose read answers it, while another connection and a read without one answer the default', async () => { + const characteristic = createTransientCharacteristic() + const other = buildEmitterConnection() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + characteristic.onSet(() => 'AQEB') + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB') + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQEB') + await expect(characteristic.handleGetRequest(other)).resolves.toBe('') + await expect(characteristic.handleGetRequest()).resolves.toBe('') + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('holds an on(\'set\') answer for its writer, whose read answers it, while another connection and a read without one answer the default', async () => { + const characteristic = createTransientCharacteristic() + const other = buildEmitterConnection() + const change = vi.fn() + characteristic.on(CharacteristicEventTypes.CHANGE, change) + characteristic.on('set', (_value, callback) => { + callback(undefined, 'AQEB') + }) + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB') + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQEB') + await expect(characteristic.handleGetRequest(other)).resolves.toBe('') + await expect(characteristic.handleGetRequest()).resolves.toBe('') + expect(characteristic.value).toBeNull() + expect(change).not.toHaveBeenCalled() + }) + + it('holds the answer of a transient characteristic without write response, resolving the write empty and warning of nothing', async () => { + const characteristic = createCharacteristicWithProps({ + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE], + transient: true, + }) + const warning = vi.fn() + characteristic.on(CharacteristicEventTypes.CHARACTERISTIC_WARNING, warning) + characteristic.onSet(() => 'AQEB') + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined() + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQEB') + expect(warning).not.toHaveBeenCalled() + }) + + it('replaces a held answer at the next answered write and releases it at an answerless, a refused, an invalid and a handlerless write', async () => { + const characteristic = createTransientCharacteristic() + const handler = { answer: 'AQEB' as string | undefined, refuses: false } + characteristic.onSet(() => { + if (handler.refuses) { + throw new HapStatusError(HAPStatus.RESOURCE_BUSY) + } + + return handler.answer + }) + + await characteristic.handleSetRequest('AQEC', connection) + handler.answer = 'AQED' + await characteristic.handleSetRequest('AQEC', connection) + + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQED') + expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(1) + + handler.answer = undefined + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined() + + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') + + handler.answer = 'AQEB' + await characteristic.handleSetRequest('AQEC', connection) + handler.refuses = true + await expect(characteristic.handleSetRequest('AQEC', connection)).rejects.toBe(HAPStatus.RESOURCE_BUSY) + + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') + + handler.refuses = false + await characteristic.handleSetRequest('AQEC', connection) + await expect(characteristic.handleSetRequest(1, connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') + + await characteristic.handleSetRequest('AQEC', connection) + characteristic.removeOnSet() + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBeUndefined() + + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') + expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0) + }) + + it('releases a held answer, its close listener and its extra max-listener slot at its writer\'s close', async () => { + const characteristic = createTransientCharacteristic() + const limit = connection.getMaxListeners() + characteristic.onSet(() => 'AQEB') + + await characteristic.handleSetRequest('AQEC', connection) + + expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(1) + expect(connection.getMaxListeners()).toBe(limit + 1) + + connection.emit(HAPConnectionEvent.CLOSED) + + expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0) + expect(connection.getMaxListeners()).toBe(limit) + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') + }) + + it('holds nothing and adds no listener for a write answered after its connection closed', async () => { + const characteristic = createTransientCharacteristic() + characteristic.onSet(() => 'AQEB') + + connection.emit(HAPConnectionEvent.CLOSED) + + await expect(characteristic.handleSetRequest('AQEC', connection)).resolves.toBe('AQEB') + expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0) + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') + }) + + it('serves a held answer ahead of an onGet handler, which the writer\'s read does not call and another connection\'s read does', async () => { + const characteristic = createTransientCharacteristic() + const other = buildEmitterConnection() + const getHandler = vi.fn(() => 'AgEA') + characteristic.onGet(getHandler) + characteristic.onSet(() => 'AQEB') + + await characteristic.handleSetRequest('AQEC', connection) + + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('AQEB') + expect(getHandler).not.toHaveBeenCalled() + await expect(characteristic.handleGetRequest(other)).resolves.toBe('AgEA') + expect(getHandler).toHaveBeenCalledTimes(1) + }) + + it('answers the default to a read after a refused write when it has no read handler, never the status the write left', async () => { + const characteristic = createTransientCharacteristic() + characteristic.onSet(() => { + throw new HapStatusError(HAPStatus.RESOURCE_BUSY) + }) + + await expect(characteristic.handleSetRequest('AQEC', connection)).rejects.toBe(HAPStatus.RESOURCE_BUSY) + + expect(characteristic.statusCode).toBe(HAPStatus.RESOURCE_BUSY) + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') + await expect(characteristic.handleGetRequest()).resolves.toBe('') + }) + + it('releases one connection\'s answer or every connection\'s at its release entry point, and leaves a connection holding none as it was', async () => { + const characteristic = createTransientCharacteristic() + const second = buildEmitterConnection() + const idle = buildEmitterConnection() + const limit = connection.getMaxListeners() + const unrelated = vi.fn() + idle.on(HAPConnectionEvent.CLOSED, unrelated) + characteristic.onSet(() => 'AQEB') + + createTransientCharacteristic().releaseTransientAnswers(idle) + + await characteristic.handleSetRequest('AQEC', connection) + await characteristic.handleSetRequest('AQEC', second) + characteristic.releaseTransientAnswers(connection) + + expect(connection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0) + expect(connection.getMaxListeners()).toBe(limit) + await expect(characteristic.handleGetRequest(connection)).resolves.toBe('') + expect(second.listenerCount(HAPConnectionEvent.CLOSED)).toBe(1) + expect(second.getMaxListeners()).toBe(limit + 1) + await expect(characteristic.handleGetRequest(second)).resolves.toBe('AQEB') + + characteristic.releaseTransientAnswers(idle) + + expect(idle.listenerCount(HAPConnectionEvent.CLOSED)).toBe(1) + expect(idle.getMaxListeners()).toBe(limit) + + characteristic.releaseTransientAnswers() + + expect(second.listenerCount(HAPConnectionEvent.CLOSED)).toBe(0) + expect(second.getMaxListeners()).toBe(limit) + await expect(characteristic.handleGetRequest(second)).resolves.toBe('') + }) +}) + +describe('sensitive characteristics', () => { + function createSensitiveCharacteristic(): Characteristic { + return createCharacteristicWithProps({ + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + sensitive: true, + }) + } + + it('keeps the flag through construction and clears it with null', () => { + const characteristic = createSensitiveCharacteristic() + + expect(characteristic.props.sensitive).toBe(true) + + characteristic.setProps({ sensitive: null }) + + expect(characteristic.props.sensitive).toBeUndefined() + }) + + it('keeps the flag through serialize and deserialize with and without a known constructor', () => { + const json = Characteristic.serialize(createSensitiveCharacteristic()) + + expect(json.props.sensitive).toBe(true) + expect(Characteristic.deserialize(json).props.sensitive).toBe(true) + expect(Characteristic.deserialize({ ...json, constructorName: 'CryptoHash' }).props.sensitive).toBe(true) + }) +}) diff --git a/src/lib/Characteristic.ts b/src/lib/Characteristic.ts index 25797d2ad..27ae06ddb 100644 --- a/src/lib/Characteristic.ts +++ b/src/lib/Characteristic.ts @@ -272,6 +272,7 @@ import { CharacteristicWarningType } from './Accessory.js' import { HAPStatus } from './HAPServer.js' import { clone } from './util/clone.js' import { errorMessage, errorStack } from './util/errors.js' +import { HAPConnectionEvent } from './util/eventedhttp.js' import { HapStatusError } from './util/hapStatusError.js' import { once } from './util/once.js' import { @@ -457,6 +458,22 @@ export interface CharacteristicProps { */ validValueRanges?: [min: number, max: number] adminOnlyAccess?: Access[] + /** + * Marks a control point whose values are transient: a value a HAP request carries never lingers in {@link Characteristic.value}, and it cannot + * reach another controller. The value the set handler returns for a write, Write Response or not, is held for the connection that wrote it and + * answers that connection's plain reads ahead of any read handler, until the connection's next write of the characteristic, a write that is refused + * or answers nothing, the connection's close, or the release the owning class calls when a session or the service ends. Every other read returns + * what the read handler supplies, or the format's default value when there is none, and never a status a write left. A write response reaches only + * the write that produced it. A write leaves the value unchanged and emits no change event. A serialized characteristic neither carries a value + * nor takes one back from the cache. + */ + transient?: boolean + /** + * Marks a characteristic whose values carry secret material, such as a key: the accessory's debug lines print `` in place of a value + * written to it or read from it. The flag governs logging alone: a control point that must also keep the value out of + * {@link Characteristic.value} and the cache sets {@link CharacteristicProps.transient} beside it. + */ + sensitive?: boolean } /** @@ -732,6 +749,13 @@ function minWithUndefined(a?: number, b?: number): number | undefined { } } +// The answer a transient characteristic holds for one connection: the value its last answered write returned, which a later answer replaces, and the +// close listener that releases it. The connection's close drops the answer with the connection. +interface TransientAnswer { + value: CharacteristicValue + readonly listener: () => void +} + /** * Characteristic represents a particular typed variable that can be assigned to a Service. For instance, a * "Hue" Characteristic might store a 'float' value of type 'arcdegrees'. You could add the Hue Characteristic @@ -1812,6 +1836,9 @@ export class Characteristic extends EventEmitter { private setHandler?: CharacteristicSetHandler private subscriptions = 0 + // The answers a transient characteristic holds, by the connection that wrote each. The map is created with the first answer: a characteristic no + // connection ever answered, which is nearly every one on a large bridge, allocates none. + private transientAnswers?: Map /** * @private */ @@ -2087,6 +2114,12 @@ export class Characteristic extends EventEmitter { if (props.adminOnlyAccess !== undefined) { this.props.adminOnlyAccess = props.adminOnlyAccess ?? undefined } + if (props.transient !== undefined) { + this.props.transient = props.transient ?? undefined + } + if (props.sensitive !== undefined) { + this.props.sensitive = props.sensitive ?? undefined + } if (this.props.minValue != null && this.props.maxValue != null) { // the eqeq instead of eqeqeq is important here if (this.props.minValue > this.props.maxValue) { // see https://github.com/homebridge/HAP-NodeJS/issues/690 @@ -2408,6 +2441,17 @@ export class Characteristic extends EventEmitter { throw HAPStatus.WRITE_ONLY_CHARACTERISTIC } + // A transient characteristic answers its writer's plain read with the answer that writer holds, ahead of any read handler, because a plain read is the + // only way an answer reaches a writer whose request asked for no write response. + const held = this.props.transient && connection + ? this.transientAnswers?.get(connection) + : undefined + + if (held) { + this.statusCode = HAPStatus.SUCCESS + return held.value + } + if (this.UUID === Characteristic.ProgrammableSwitchEvent.UUID) { // special workaround for event only programmable switch event, which must always return null return null @@ -2431,6 +2475,10 @@ export class Characteristic extends EventEmitter { return Promise.reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE) } + if (this.props.transient) { + return value + } + const oldValue = this.value this.value = value @@ -2464,6 +2512,11 @@ export class Characteristic extends EventEmitter { } if (this.listenerCount(CharacteristicEventTypes.GET) === 0) { + // A transient characteristic answers the default ahead of the status check: a status a refused write left never answers a read. + if (this.props.transient) { + return this.getDefaultValue() + } + if (this.statusCode) { throw this.statusCode } @@ -2506,6 +2559,12 @@ export class Characteristic extends EventEmitter { reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE) return } + + if (this.props.transient) { + resolve(value) + return + } + const oldValue = this.value this.value = value @@ -2552,6 +2611,7 @@ export class Characteristic extends EventEmitter { value = this.validateClientSuppliedValue(value) } catch (e) { debug(`[${this.displayName}]`, errorMessage(e)) + this.answerTransientWrite(connection) return Promise.reject(HAPStatus.INVALID_VALUE_IN_REQUEST) } } @@ -2571,13 +2631,26 @@ export class Characteristic extends EventEmitter { this.statusCode = HAPStatus.SUCCESS if (writeResponse != null && this.props.perms.includes(Perms.WRITE_RESPONSE)) { - this.value = this.validateUserInput(writeResponse) - return this.value! + const response = this.validateUserInput(writeResponse) + + if (this.props.transient) { + this.answerTransientWrite(connection, response) + } else { + this.value = response + } + + return response! } else { + if (this.props.transient) { + this.answerWithoutWriteResponse(connection, writeResponse) + return + } + if (writeResponse != null) { this.characteristicWarning('SET handler returned write response value, though the characteristic doesn\'t support write response', CharacteristicWarningType.DEBUG_MESSAGE) } + this.value = value this.emit( @@ -2593,6 +2666,8 @@ export class Characteristic extends EventEmitter { return } } catch (error) { + this.answerTransientWrite(connection) + if (typeof error === 'number') { const hapStatusError = new HapStatusError(error) this.statusCode = hapStatusError.hapStatus @@ -2608,6 +2683,11 @@ export class Characteristic extends EventEmitter { } if (this.listenerCount(CharacteristicEventTypes.SET) === 0) { + if (this.props.transient) { + this.answerTransientWrite(connection) + return Promise.resolve() + } + this.value = value this.emit(CharacteristicEventTypes.CHANGE, { originator: connection, @@ -2622,6 +2702,8 @@ export class Characteristic extends EventEmitter { try { this.emit(CharacteristicEventTypes.SET, value, once((status, writeResponse) => { if (status) { + this.answerTransientWrite(connection) + if (typeof status === 'number') { const hapStatusError = new HapStatusError(status) this.statusCode = hapStatusError.hapStatus @@ -2639,22 +2721,38 @@ export class Characteristic extends EventEmitter { if (writeResponse != null && this.props.perms.includes(Perms.WRITE_RESPONSE)) { // support write response simply by letting the implementor pass the response as second argument to the callback + let response: Nullable try { - this.value = this.validateUserInput(writeResponse) + response = this.validateUserInput(writeResponse) } catch (error) { // this runs inside the plugin's callback; a throw would land in the plugin and leave the request unanswered this.characteristicWarning(`An illegal write response value was supplied by the write handler for characteristic: ${errorMessage(error)}`, CharacteristicWarningType.WARN_MESSAGE, errorStack(error)) this.statusCode = HAPStatus.SERVICE_COMMUNICATION_FAILURE + this.answerTransientWrite(connection) reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE) return } - resolve(this.value!) + + if (this.props.transient) { + this.answerTransientWrite(connection, response) + } else { + this.value = response + } + + resolve(response!) } else { + if (this.props.transient) { + this.answerWithoutWriteResponse(connection, writeResponse) + resolve() + return + } + if (writeResponse != null) { this.characteristicWarning('SET handler returned write response value, though the characteristic doesn\'t support write response', CharacteristicWarningType.DEBUG_MESSAGE) } + this.value = value resolve() @@ -2674,12 +2772,103 @@ export class Characteristic extends EventEmitter { this.characteristicWarning(`Unhandled error thrown inside write handler for characteristic: ${errorMessage(error)}`, CharacteristicWarningType.ERROR_MESSAGE, errorStack(error)) this.statusCode = HAPStatus.SERVICE_COMMUNICATION_FAILURE + this.answerTransientWrite(connection) reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE) } }) } } + /** + * Releases the answers a transient characteristic holds for its writers: one connection's, its close listener and its extra max-listener slot with it, + * or every connection's when none is given. A connection that holds no answer is left as it was, its listeners and its max listeners untouched. The + * owning classes call this at each boundary that ends or bounds an answer, a session's end or the service's reset among them, and the connection's close + * and its refused or answerless writes reach it as well. + * @param connection - The connection whose answer goes, or `undefined` for every connection's. + * @private + */ + releaseTransientAnswers(connection?: HAPConnection): void { + const answers = this.transientAnswers + + if (!answers) { + return + } + + // The writers are read into an array first, which is why the loop deletes from a map it is not walking. + const writers = connection + ? [connection] + : Array.from(answers.keys()) + + for (const writer of writers) { + const answer = answers.get(writer) + + if (answer) { + answers.delete(writer) + writer.removeListener(HAPConnectionEvent.CLOSED, answer.listener) + writer.setMaxListeners(writer.getMaxListeners() - 1) + } + } + } + + /* Settles a transient write's answer for its writer: an answer holds, replacing the one the connection held, and a write that is refused or answers + * nothing releases it. A write without a connection, which a plugin makes, and a write to a characteristic that is not transient touch nothing. + */ + private answerTransientWrite(connection: HAPConnection | undefined, answer?: Nullable): void { + if (!this.props.transient || connection === undefined) { + return + } + + if (answer == null) { + this.releaseTransientAnswers(connection) + return + } + + // A connection that no longer reads as authenticated is closing or closed, and a closed one would never release an answer, because its close + // listeners have run and been removed: it holds nothing. + if (!connection.isAuthenticated()) { + this.releaseTransientAnswers(connection) + return + } + + this.transientAnswers ??= new Map() + + const held = this.transientAnswers.get(connection) + + if (held) { + held.value = answer + return + } + + // The first answer a connection holds adds one close listener and one max-listener slot, as ConnectionSessions does, and its release removes both. + const listener = (): void => this.releaseTransientAnswers(connection) + this.transientAnswers.set(connection, { listener, value: answer }) + connection.setMaxListeners(connection.getMaxListeners() + 1) + connection.on(HAPConnectionEvent.CLOSED, listener) + } + + /* A transient write's handler that returns an answer without the Write Response permission, Setup Endpoints' case, holds it once it validates as a write + * response would, because a plain read is the only way it reaches its writer. One that fails validation holds nothing and logs the warning any handler + * returning a response without the permission logs, and its author still hears of it. + */ + private answerWithoutWriteResponse(connection: HAPConnection | undefined, writeResponse: Nullable | void): void { + if (writeResponse == null) { + this.answerTransientWrite(connection) + return + } + + let answer: Nullable + try { + answer = this.validateUserInput(writeResponse) + } catch { + this.characteristicWarning('SET handler returned write response value, though the characteristic doesn\'t support write response', + CharacteristicWarningType.DEBUG_MESSAGE) + this.answerTransientWrite(connection) + return + } + + this.answerTransientWrite(connection, answer) + } + /** * Called once a HomeKit controller subscribes to events of this characteristic. * @private @@ -3161,7 +3350,9 @@ export class Characteristic extends EventEmitter { debug('[%s] Error getting value for characteristic on /accessories request. Returning default value instead: %s', this.displayName, `${value}`) return value // use default value }) - : this.value + : this.props.transient + ? this.getDefaultValue() + : this.value object.value = formatOutgoingCharacteristicValue(value, this.props) } @@ -3211,7 +3402,7 @@ export class Characteristic extends EventEmitter { UUID: characteristic.UUID, eventOnlyCharacteristic: characteristic.UUID === Characteristic.ProgrammableSwitchEvent.UUID, // support downgrades for now constructorName, - value: characteristic.value, + value: characteristic.props.transient ? null : characteristic.value, props: clone({}, characteristic.props), } } @@ -3239,7 +3430,10 @@ export class Characteristic extends EventEmitter { characteristic = new Characteristic(json.displayName, json.UUID, json.props) } - characteristic.value = json.value + // A transient characteristic takes no value from the cache, which can predate its flag and hold a value a HAP request carried. + if (!characteristic.props.transient) { + characteristic.value = json.value + } return characteristic } diff --git a/src/lib/definitions/generate-definitions.ts b/src/lib/definitions/generate-definitions.ts index f3bac784c..50e4afaa5 100644 --- a/src/lib/definitions/generate-definitions.ts +++ b/src/lib/definitions/generate-definitions.ts @@ -155,6 +155,8 @@ export interface GeneratedCharacteristic { validBitMasks?: Record adminOnlyAccess?: Access[] + transient?: boolean + sensitive?: boolean classAdditions?: string[] } @@ -526,6 +528,12 @@ for (const generated of Object.values(generatedCharacteristics) const access = generated.adminOnlyAccess.map(value => `Access.${characteristicAccess(value)}`) characteristicOutput += ` adminOnlyAccess: ${arrayLiteral(access, ' ')},\n` } + if (generated.transient) { + characteristicOutput += ' transient: true,\n' + } + if (generated.sensitive) { + characteristicOutput += ' sensitive: true,\n' + } characteristicOutput += ' })\n' characteristicOutput += ' this.value = this.getDefaultValue()\n' characteristicOutput += ' }\n' diff --git a/src/test-utils/connectionFixtures.ts b/src/test-utils/connectionFixtures.ts new file mode 100644 index 000000000..1214bdc02 --- /dev/null +++ b/src/test-utils/connectionFixtures.ts @@ -0,0 +1,45 @@ +// The HAP connection fixtures every spec shares, in a module of their own. A domain spec takes its connection from here and from no camera fixture. +import type { HAPConnection } from '../lib/util/eventedhttp.js' + +import { EventEmitter } from 'node:events' + +import { HAPConnectionEvent } from '../lib/util/eventedhttp.js' + +// A HAP connection's events and addresses on a plain emitter. Like a real connection whose socket closes, it reads as unauthenticated from the moment it +// emits its close, and a spec can close it while one of its writes waits. Its local address answers loopback in either family, and its server reports the +// family it was built with, as a HAP server listening on that family's wildcard does. +class EmitterConnection extends EventEmitter { + readonly localAddress = '127.0.0.1' + readonly remoteAddress = '192.168.1.2' + readonly server: { address: () => { family: 'IPv4' | 'IPv6' } } + private closed = false + + constructor(family: 'IPv4' | 'IPv6') { + super() + this.server = { + address: () => ({ family }), + } + } + + isAuthenticated(): boolean { + return !this.closed + } + + getLocalAddress(version: 'ipv4' | 'ipv6'): string { + return version === 'ipv4' + ? '127.0.0.1' + : '::1' + } + + override emit(event: string | symbol, ...args: unknown[]): boolean { + if (event === HAPConnectionEvent.CLOSED) { + this.closed = true + } + + return super.emit(event, ...args) + } +} + +export function buildEmitterConnection(family: 'IPv4' | 'IPv6' = 'IPv6'): HAPConnection { + return new EmitterConnection(family) as unknown as HAPConnection +} From b9024608448900120c6d18ee493617e59764d008 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:43 -0600 Subject: [PATCH 04/16] feat: raise the engine floor to Node 22.20 with the disposable stacks it lacks as globals --- README.md | 2 +- eslint.config.mjs | 10 + package-lock.json | 2 +- package.json | 2 +- src/lib/util/asyncDisposableStack.spec.ts | 572 ++++++++++++++++++++++ src/lib/util/asyncDisposableStack.ts | 161 ++++++ src/lib/util/disposableStack.spec.ts | 473 ++++++++++++++++++ src/lib/util/disposableStack.ts | 224 +++++++++ src/lib/util/runtimeFloor.spec.ts | 155 ++++++ tsconfig.json | 2 +- 10 files changed, 1599 insertions(+), 4 deletions(-) create mode 100644 src/lib/util/asyncDisposableStack.spec.ts create mode 100644 src/lib/util/asyncDisposableStack.ts create mode 100644 src/lib/util/disposableStack.spec.ts create mode 100644 src/lib/util/disposableStack.ts create mode 100644 src/lib/util/runtimeFloor.spec.ts diff --git a/README.md b/README.md index de6b52fac..a40b0c402 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ HAP-NodeJS is not an Apple certified HAP implementation, as this is only availab npm install @homebridge/hap-nodejs ``` -HAP-NodeJS needs Node.js `^22.12.0 || ^24 || ^26`. +HAP-NodeJS needs Node.js `^22.20.0 || ^24 || ^26`. The package is an ES module. Importing it works as usual, including `import hap from '@homebridge/hap-nodejs'`. CommonJS code can still `require('@homebridge/hap-nodejs')` on the Node.js versions above. diff --git a/eslint.config.mjs b/eslint.config.mjs index 5e01343fc..1e5c03e3a 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -14,6 +14,16 @@ export default antfu( 'new-cap': 'off', // HAP-NodeJS has no logger of its own; the console is where its warnings are meant to go 'no-console': 'off', + // The disposal stack globals arrive with Node 24 and the library shares its process with every plugin, which is why every site imports the internal stacks by + // name. The preset's own restrictions stay beside them, because this entry replaces its list. + 'no-restricted-globals': [ + 'error', + { message: 'Use `globalThis` instead.', name: 'global' }, + { message: 'Use `globalThis` instead.', name: 'self' }, + { message: 'Import DisposableStack from src/lib/util/disposableStack.ts, because Node 22 has no such global.', name: 'DisposableStack' }, + { message: 'Import AsyncDisposableStack from src/lib/util/asyncDisposableStack.ts, because Node 22 has no such global.', name: 'AsyncDisposableStack' }, + { message: 'Import SuppressedError from src/lib/util/disposableStack.ts, because Node 22 has no such global.', name: 'SuppressedError' }, + ], 'no-undef': 'error', 'perfectionist/sort-exports': 'error', 'perfectionist/sort-imports': [ diff --git a/package-lock.json b/package-lock.json index 69d466781..73e946f06 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,7 +36,7 @@ "vitest": "^5.1.1" }, "engines": { - "node": "^22.12.0 || ^24 || ^26" + "node": "^22.20.0 || ^24 || ^26" } }, "node_modules/@antfu/eslint-config": { diff --git a/package.json b/package.json index 6eb4604bf..a1dca9576 100644 --- a/package.json +++ b/package.json @@ -34,7 +34,7 @@ "dist" ], "engines": { - "node": "^22.12.0 || ^24 || ^26" + "node": "^22.20.0 || ^24 || ^26" }, "scripts": { "check": "npm install && npm outdated", diff --git a/src/lib/util/asyncDisposableStack.spec.ts b/src/lib/util/asyncDisposableStack.spec.ts new file mode 100644 index 000000000..55c204ea7 --- /dev/null +++ b/src/lib/util/asyncDisposableStack.spec.ts @@ -0,0 +1,572 @@ +import { setTimeout as delay } from 'node:timers/promises' + +import { describe, expect, it } from 'vitest' + +import { AsyncDisposableStack } from './asyncDisposableStack.js' + +// A factory of fresh stacks. The differential oracle drives one scenario through two factories, one over the local stack and one over the platform global, +// and compares what each observes; the instance type is the platform interface, which the local stack implements. +type StackFactory = () => InstanceType + +// A disposer that logs its start, waits, then logs its end. A disposal that awaits each disposer before the next never interleaves two of them: every +// start is followed at once by its own end, where a sweep that starts them all together interleaves the log. +function loggingDisposer(log: string[], label: string, ms: number): () => Promise { + return async (): Promise => { + log.push(`${label}-start`) + await delay(ms) + log.push(`${label}-end`) + } +} + +// A disposal that runs last in, first out, with the disposed flag before and after it. The first disposer registered is the slow one, which means a sweep that +// started every disposer at once would log its start before the fast ones end. +async function scenarioHappyLifo(makeStack: StackFactory): Promise<{ disposedAfter: boolean, disposedBefore: boolean, order: string[] }> { + const order: string[] = [] + const stack = makeStack() + const disposedBefore = stack.disposed + + stack.defer(loggingDisposer(order, 'a', 20)) + stack.defer(loggingDisposer(order, 'b', 1)) + stack.defer(loggingDisposer(order, 'c', 0)) + + await stack.disposeAsync() + + return { disposedAfter: stack.disposed, disposedBefore, order } +} + +// The pending disposers moved to a new stack and both stacks disposed: the source reads disposed and runs nothing, and the target runs the moved set last in, +// first out. +async function scenarioMoveThenDisposeBoth(makeStack: StackFactory): Promise<{ movedRan: string[], sourceDisposed: boolean, targetDisposedInitially: boolean }> { + const movedRan: string[] = [] + const stack = makeStack() + + stack.defer(() => void movedRan.push('x')) + stack.defer(() => void movedRan.push('y')) + + const moved = stack.move() + const sourceDisposed = stack.disposed + const targetDisposedInitially = moved.disposed + + await stack.disposeAsync() + await moved.disposeAsync() + + return { movedRan, sourceDisposed, targetDisposedInitially } +} + +// One rejecting disposer among others: every disposer runs and the one error is rethrown, unchanged, once the sweep ends. +async function scenarioSingleThrow(makeStack: StackFactory): Promise<{ order: string[], thrownMessage: string | null }> { + const order: string[] = [] + const stack = makeStack() + + stack.defer(() => void order.push('a')) + stack.defer(async () => { + order.push('b') + await delay(1) + throw new Error('boom') + }) + stack.defer(() => void order.push('c')) + + let thrownMessage: string | null = null + try { + await stack.disposeAsync() + } catch (error) { + thrownMessage = (error as Error).message + } + + return { order, thrownMessage } +} + +// Two rejecting disposers around one that does not: a SuppressedError links the newest failure, its `error`, to the earlier one, its `suppressed`, and +// every disposer runs. +async function scenarioMultiThrow( + makeStack: StackFactory, +): Promise<{ errorMessage: string | null, order: string[], suppressedMessage: string | null, thrownName: string | null }> { + const order: string[] = [] + const stack = makeStack() + + stack.defer(async () => { + order.push('a') + await delay(1) + throw new Error('first') + }) + stack.defer(() => void order.push('b')) + stack.defer(async () => { + order.push('c') + throw new Error('second') + }) + + let errorMessage: string | null = null + let suppressedMessage: string | null = null + let thrownName: string | null = null + try { + await stack.disposeAsync() + } catch (error) { + const suppressed = error as { error?: { message?: string }, name?: string, suppressed?: { message?: string } } + errorMessage = suppressed.error?.message ?? null + suppressedMessage = suppressed.suppressed?.message ?? null + thrownName = suppressed.name ?? null + } + + return { + errorMessage, + order, + suppressedMessage, + thrownName, + } +} + +// A resource carrying both disposal members, each changed after registration: the async method captured at registration runs, which shows both the capture +// and the preference for the async member. +async function scenarioCaptureThenMutate(makeStack: StackFactory): Promise<{ order: string[] }> { + const order: string[] = [] + const stack = makeStack() + const resource = { + [Symbol.asyncDispose]: async (): Promise => { + order.push('original-async') + }, + [Symbol.dispose]: (): void => { + order.push('original-sync') + }, + } + + stack.use(resource) + resource[Symbol.asyncDispose] = async (): Promise => { + order.push('mutated-async') + } + resource[Symbol.dispose] = (): void => { + order.push('mutated-sync') + } + + await stack.disposeAsync() + + return { order } +} + +// A resource carrying only the sync disposal member, which an async stack accepts and runs. +async function scenarioSyncDisposableAccepted(makeStack: StackFactory): Promise<{ order: string[] }> { + const order: string[] = [] + const stack = makeStack() + + stack.use({ + [Symbol.dispose]: (): void => { + order.push('sync-only') + }, + }) + + await stack.disposeAsync() + + return { order } +} + +// Null and undefined passed to use() register nothing, and only the deferred disposer runs. +async function scenarioUseNullPassthrough(makeStack: StackFactory): Promise<{ order: string[] }> { + const order: string[] = [] + const stack = makeStack() + + stack.use(null) + stack.use(undefined) + stack.defer(() => void order.push('d')) + + await stack.disposeAsync() + + return { order } +} + +// A defer() on a disposed stack throws a ReferenceError. +async function scenarioPostDisposeDefer(makeStack: StackFactory): Promise<{ threwReferenceError: boolean }> { + const stack = makeStack() + await stack.disposeAsync() + + let threwReferenceError = false + try { + stack.defer(() => undefined) + } catch (error) { + threwReferenceError = error instanceof ReferenceError + } + + return { threwReferenceError } +} + +// Every registration and the move attempted from inside a slow disposer that is still running. The disposed flag turns before any disposer runs, which is why all four +// are refused rather than queued behind work that would never run them. +async function scenarioRegisterDuringDisposal(makeStack: StackFactory): Promise<{ disposedMidFlight: boolean, rejections: string[] }> { + const rejections: string[] = [] + const stack = makeStack() + let disposedMidFlight = false + + stack.defer(async () => { + await delay(10) + disposedMidFlight = stack.disposed + + const attempts: { name: string, run: () => void }[] = [ + { + name: 'use', + run: () => void stack.use(null), + }, + { + name: 'adopt', + run: () => void stack.adopt({}, () => undefined), + }, + { + name: 'defer', + run: () => stack.defer(() => undefined), + }, + { + name: 'move', + run: () => void stack.move(), + }, + ] + + for (const attempt of attempts) { + try { + attempt.run() + rejections.push(`${attempt.name}:no-throw`) + } catch (error) { + const kind = error instanceof ReferenceError + ? 'ReferenceError' + : 'other' + rejections.push(`${attempt.name}:${kind}`) + } + } + }) + + await stack.disposeAsync() + + return { disposedMidFlight, rejections } +} + +// A second disposeAsync() while the first sweep still awaits a slow disposer: it resolves without running anything again, and without waiting out the first. +async function scenarioConcurrentDisposal(makeStack: StackFactory): Promise<{ ran: string[], secondSettledFirst: boolean }> { + const ran: string[] = [] + const stack = makeStack() + + stack.defer(loggingDisposer(ran, 'slow', 20)) + + const first = stack.disposeAsync() + const second = stack.disposeAsync() + const winner = await Promise.race([ + second.then(() => 'second'), + first.then(() => 'first'), + ]) + + await Promise.all([first, second]) + + return { ran, secondSettledFirst: winner === 'second' } +} + +// Which disposal member use() takes and how it runs it: a callable async member is taken with the sync member left unread, an async member that is neither +// callable nor absent is refused, a null one falls back to the sync member, and what a sync member returns is not awaited. +async function scenarioDisposalMemberChoice(makeStack: StackFactory): Promise<{ nonCallableAsync: string, nullAsync: string, order: string[], unreadSync: string }> { + // What registering a value does: it is accepted, or the name of what the registration throws. + const outcome = (value: unknown): string => { + try { + makeStack().use(value as AsyncDisposable) + + return 'accepted' + } catch (error) { + return (error as Error).constructor.name + } + } + const order: string[] = [] + const returned: Promise[] = [] + const stack = makeStack() + + // A sync member whose return settles after the disposal has, where the disposal does not wait for it. + stack.use({ + [Symbol.dispose]: (): Promise => { + const settles = delay(10).then(() => void order.push('sync-return-settled')) + + returned.push(settles) + + return settles + }, + }) + + await stack.disposeAsync() + order.push('disposed') + await Promise.all(returned) + + return { + nonCallableAsync: outcome({ + [Symbol.asyncDispose]: 42, + [Symbol.dispose]: (): void => {}, + }), + nullAsync: outcome({ + [Symbol.asyncDispose]: null, + [Symbol.dispose]: (): void => {}, + }), + order, + unreadSync: outcome({ + [Symbol.asyncDispose]: async (): Promise => {}, + get [Symbol.dispose](): never { + throw new Error('The sync member was read.') + }, + }), + } +} + +describe('asyncDisposableStack', () => { + describe('contract', () => { + // The slow disposer, registered first, runs last, and its start follows the start and end of each faster one, which a concurrent sweep would interleave. + it('disposes registered callbacks in last-in-first-out order, awaiting each before the next', async () => { + const result = await scenarioHappyLifo(() => new AsyncDisposableStack()) + + expect(result.order).toEqual([ + 'c-start', + 'c-end', + 'b-start', + 'b-end', + 'a-start', + 'a-end', + ]) + expect(result.disposedBefore).toBe(false) + expect(result.disposedAfter).toBe(true) + }) + + it('use() binds the disposal method to the value as its receiver', async () => { + const seen: string[] = [] + const resource = { + marker: 'R', + async [Symbol.asyncDispose](): Promise { + seen.push(this.marker) + }, + } + const stack = new AsyncDisposableStack() + + expect(stack.use(resource)).toBe(resource) + + await stack.disposeAsync() + + expect(seen).toEqual(['R']) + }) + + it('use() prefers the async disposal member and captures it at registration time', async () => { + expect((await scenarioCaptureThenMutate(() => new AsyncDisposableStack())).order).toEqual(['original-async']) + }) + + it('use() accepts a synchronous Disposable', async () => { + expect((await scenarioSyncDisposableAccepted(() => new AsyncDisposableStack())).order).toEqual(['sync-only']) + }) + + it('use() reads the sync disposal member only where the async one is absent, refuses an async one that is not callable, and awaits no sync return', async () => { + expect(await scenarioDisposalMemberChoice(() => new AsyncDisposableStack())).toEqual({ + nonCallableAsync: 'TypeError', + nullAsync: 'accepted', + order: [ + 'disposed', + 'sync-return-settled', + ], + unreadSync: 'accepted', + }) + }) + + it('use() passes null and undefined through without registering them', async () => { + const order: string[] = [] + const stack = new AsyncDisposableStack() + const nullResult: unknown = stack.use(null) + + expect(nullResult).toBeNull() + + stack.use(undefined) + stack.defer(() => void order.push('only')) + + await stack.disposeAsync() + + expect(order).toEqual(['only']) + }) + + it('adopt() invokes the callback with the value and returns the value unchanged', async () => { + const seen: string[] = [] + const value = { id: 'V' } + const stack = new AsyncDisposableStack() + + expect(stack.adopt(value, adopted => void seen.push(adopted.id))).toBe(value) + + await stack.disposeAsync() + + expect(seen).toEqual(['V']) + }) + + it('adopt() and defer() await a callback that returns a promise', async () => { + const order: string[] = [] + const stack = new AsyncDisposableStack() + + stack.adopt('V', async (value: string): Promise => { + order.push(`adopt-start:${value}`) + await delay(15) + order.push('adopt-end') + }) + stack.defer(loggingDisposer(order, 'defer', 1)) + + await stack.disposeAsync() + + expect(order).toEqual([ + 'defer-start', + 'defer-end', + 'adopt-start:V', + 'adopt-end', + ]) + }) + + it('use() throws a TypeError when neither disposal member is callable', async () => { + const stack = new AsyncDisposableStack() + + expect(() => stack.use({ [Symbol.asyncDispose]: 42 } as unknown as AsyncDisposable)).toThrow(TypeError) + expect(() => stack.use({} as unknown as AsyncDisposable)).toThrow(TypeError) + + await stack.disposeAsync() + }) + + it('adopt() throws a TypeError when onDisposeAsync is not a function', async () => { + const stack = new AsyncDisposableStack() + + expect(() => stack.adopt({}, 42 as unknown as (value: object) => void)).toThrow(TypeError) + + await stack.disposeAsync() + }) + + it('defer() throws a TypeError when the callback is not a function', async () => { + const stack = new AsyncDisposableStack() + + expect(() => stack.defer(42 as unknown as () => void)).toThrow(TypeError) + + await stack.disposeAsync() + }) + + it('use(), adopt(), defer(), and move() throw a ReferenceError once disposed', async () => { + const stack = new AsyncDisposableStack() + await stack.disposeAsync() + + expect(() => stack.use(null)).toThrow(ReferenceError) + expect(() => stack.adopt({}, () => undefined)).toThrow(ReferenceError) + expect(() => stack.defer(() => undefined)).toThrow(ReferenceError) + expect(() => stack.move()).toThrow(ReferenceError) + }) + + it('use(), adopt(), defer(), and move() throw a ReferenceError while a disposal is still in flight', async () => { + const result = await scenarioRegisterDuringDisposal(() => new AsyncDisposableStack()) + + expect(result.disposedMidFlight).toBe(true) + expect(result.rejections).toEqual([ + 'use:ReferenceError', + 'adopt:ReferenceError', + 'defer:ReferenceError', + 'move:ReferenceError', + ]) + }) + + it('move() transfers the pending disposers without running them and disposes the source', async () => { + const order: string[] = [] + const stack = new AsyncDisposableStack() + + stack.defer(() => void order.push('a')) + stack.defer(() => void order.push('b')) + + const moved = stack.move() + + expect(stack.disposed).toBe(true) + expect(moved.disposed).toBe(false) + expect(order).toEqual([]) + + await moved.disposeAsync() + + expect(order).toEqual(['b', 'a']) + }) + + it('disposeAsync() is safe to call more than once', async () => { + let count = 0 + const stack = new AsyncDisposableStack() + + stack.defer(() => { + count++ + }) + + await stack.disposeAsync() + await stack.disposeAsync() + + expect(count).toBe(1) + }) + + it('a second disposeAsync() during a slow first sweep resolves at once and re-runs nothing', async () => { + const result = await scenarioConcurrentDisposal(() => new AsyncDisposableStack()) + + expect(result.ran).toEqual(['slow-start', 'slow-end']) + expect(result.secondSettledFirst).toBe(true) + }) + + it('disposeAsync() runs every disposer and rethrows a single failure', async () => { + const result = await scenarioSingleThrow(() => new AsyncDisposableStack()) + + expect(result.order).toEqual(['c', 'b', 'a']) + expect(result.thrownMessage).toBe('boom') + }) + + it('disposeAsync() rethrows a single failure with its identity preserved', async () => { + const boom = new Error('boom') + const stack = new AsyncDisposableStack() + + stack.defer(async () => { + await delay(1) + throw boom + }) + + await expect(stack.disposeAsync()).rejects.toBe(boom) + }) + + it('disposeAsync() chains multiple failures through a SuppressedError', async () => { + const result = await scenarioMultiThrow(() => new AsyncDisposableStack()) + + expect(result.order).toEqual(['c', 'b', 'a']) + expect(result.thrownName).toBe('SuppressedError') + expect(result.errorMessage).toBe('first') + expect(result.suppressedMessage).toBe('second') + }) + + it('[Symbol.asyncDispose]() delegates to disposeAsync()', async () => { + let disposed = false + const stack = new AsyncDisposableStack() + + stack.defer(() => { + disposed = true + }) + + await stack[Symbol.asyncDispose]() + + expect(disposed).toBe(true) + expect(stack.disposed).toBe(true) + }) + + it('reports the platform toStringTag', () => { + expect(Object.prototype.toString.call(new AsyncDisposableStack())).toBe('[object AsyncDisposableStack]') + }) + + it('disposed transitions from false to true', async () => { + const stack = new AsyncDisposableStack() + + expect(stack.disposed).toBe(false) + + await stack.disposeAsync() + + expect(stack.disposed).toBe(true) + }) + }) + + // The oracle needs the platform class to differ against, which this machine's Node ships; the runtime floor this module serves lacks it. + describe.skipIf(typeof globalThis.AsyncDisposableStack !== 'function')('differential oracle against the platform global', () => { + it.each([ + { name: 'happy last-in-first-out disposal', run: scenarioHappyLifo }, + { name: 'move then dispose both stacks', run: scenarioMoveThenDisposeBoth }, + { name: 'single failure rethrow', run: scenarioSingleThrow }, + { name: 'multiple failures suppression chain', run: scenarioMultiThrow }, + { name: 'use()-time capture then mutate', run: scenarioCaptureThenMutate }, + { name: 'use() accepts a synchronous Disposable', run: scenarioSyncDisposableAccepted }, + { name: 'use() chooses and runs its disposal member', run: scenarioDisposalMemberChoice }, + { name: 'use() null and undefined passthrough', run: scenarioUseNullPassthrough }, + { name: 'defer after dispose', run: scenarioPostDisposeDefer }, + { name: 'registration during an in-flight disposal', run: scenarioRegisterDuringDisposal }, + { name: 'a concurrent second disposal', run: scenarioConcurrentDisposal }, + ] as { name: string, run: (makeStack: StackFactory) => Promise }[])('$name', async ({ run }) => { + expect(await run(() => new AsyncDisposableStack())).toStrictEqual(await run(() => new globalThis.AsyncDisposableStack())) + }) + }) +}) diff --git a/src/lib/util/asyncDisposableStack.ts b/src/lib/util/asyncDisposableStack.ts new file mode 100644 index 000000000..cc56db6ec --- /dev/null +++ b/src/lib/util/asyncDisposableStack.ts @@ -0,0 +1,161 @@ +import type { Nullable } from '../../types.js' + +import { createSuppressedError } from './disposableStack.js' + +/* The platform's AsyncDisposableStack for an engines floor whose Node ships Symbol.asyncDispose but not the stack globals, which arrive with Node 24. The + * library shares its process with every plugin, which is why it installs no global: every site imports the class by name, and a construction reads as it would + * against the platform class. It shares no base class with the sync stack in disposableStack.ts, because the two retire as whole files, and + * src/lib/util/runtimeFloor.spec.ts demands both deletions once the engines floor reaches Node 24. + */ + +/** + * A container of async and sync disposable resources that disposes them last in, first out, awaiting each before the next, when it is disposed itself. The + * `implements` clause binds the class to the platform's `AsyncDisposableStack`, and the compiler holds it to the contract its name promises. + */ +export class AsyncDisposableStack implements InstanceType { + // The pending disposers in registration order, and null once the stack is disposed. One field carries both: a disposed stack with pending work cannot + // be represented, and every member reads this field alone to decide whether it may still register or run work. + #disposers: Nullable<(() => Promise | void)[]> = [] + + // The platform's tag, which Object.prototype.toString reports. + readonly [Symbol.toStringTag] = 'AsyncDisposableStack' + + /** + * Whether the stack has been disposed. + */ + get disposed(): boolean { + return this.#disposers === null + } + + /** + * Registers a resource whose disposal method runs when the stack is disposed: `[Symbol.asyncDispose]` when it has one, as the platform prefers, and + * `[Symbol.dispose]` where that member is null or undefined, its return not awaited. Null and undefined pass through unregistered, and the method is + * captured now and called with the value as its receiver: a later change to either member cannot change what runs. + * @param value - The resource, or null or undefined to register nothing. + * @returns The value, unchanged. + */ + use(value: T): T { + if (this.#disposers === null) { + throw new ReferenceError('Cannot use a resource on a disposed AsyncDisposableStack.') + } + + if (value === null || typeof value === 'undefined') { + return value + } + + // Each member is read through unknown because use() is a trust boundary: a value can satisfy the type and still carry a member that is not callable + // at run time, which the spec refuses with a TypeError. The sync member is read only where the async one is null or undefined, as the platform reads + // them: a value with a callable async member never has its sync member touched, and an async member that is anything else is refused. + const asyncDisposeMethod: unknown = (value as Partial)[Symbol.asyncDispose] + const fallsBack = asyncDisposeMethod === null || typeof asyncDisposeMethod === 'undefined' + const disposeMethod: unknown = fallsBack + ? (value as Partial)[Symbol.dispose] + : asyncDisposeMethod + + if (typeof disposeMethod !== 'function') { + throw new TypeError('The value passed to AsyncDisposableStack.use() is not disposable.') + } + + // What a sync member returns is not awaited, as on the platform: a sync disposal is done when it returns. + this.#disposers.push(fallsBack + ? () => void disposeMethod.call(value) + : () => disposeMethod.call(value)) + + return value + } + + /** + * Registers a value with the callback that disposes it, called with the value and awaited when it returns a promise, when the stack is disposed. + * @param value - The value. + * @param onDisposeAsync - The callback, given the value. + * @returns The value, unchanged. + */ + adopt(value: T, onDisposeAsync: (value: T) => PromiseLike | void): T { + if (this.#disposers === null) { + throw new ReferenceError('Cannot adopt a resource on a disposed AsyncDisposableStack.') + } + + if (typeof onDisposeAsync !== 'function') { + throw new TypeError('The onDisposeAsync callback passed to AsyncDisposableStack.adopt() is not a function.') + } + + this.#disposers.push(async () => onDisposeAsync(value)) + + return value + } + + /** + * Registers a callback to run when the stack is disposed, awaited when it returns a promise. + * @param onDisposeAsync - The callback. + */ + defer(onDisposeAsync: () => PromiseLike | void): void { + if (this.#disposers === null) { + throw new ReferenceError('Cannot defer a callback on a disposed AsyncDisposableStack.') + } + + if (typeof onDisposeAsync !== 'function') { + throw new TypeError('The onDisposeAsync callback passed to AsyncDisposableStack.defer() is not a function.') + } + + this.#disposers.push(async () => onDisposeAsync()) + } + + /** + * Moves every pending disposer, in registration order, into a new stack and marks this one disposed without running any of them. After an acquisition + * succeeds, the move hands its resources to a stack that outlives the scope whose stack would otherwise release them. + * @returns The new stack, which owns the moved disposers. + */ + move(): AsyncDisposableStack { + if (this.#disposers === null) { + throw new ReferenceError('Cannot move a disposed AsyncDisposableStack.') + } + + const moved = new AsyncDisposableStack() + moved.#disposers = this.#disposers + this.#disposers = null + + return moved + } + + /** + * Disposes every registered resource, last in, first out, awaiting each before the next begins, and does nothing once the stack is disposed. Every + * disposer runs when an earlier one rejects: one failure is rethrown once the sweep ends, and several chain through a `SuppressedError`, the newest + * wrapping the rest. + */ + async disposeAsync(): Promise { + if (this.#disposers === null) { + return + } + + // The array is detached and the stack marked disposed synchronously, before the first await: a disposer that reaches back into the stack finds it + // disposed and a registration made while a slow disposer runs is refused rather than queued behind a sweep that would never run it. + const disposers = this.#disposers + this.#disposers = null + + let hasError = false + let heldError: unknown + + // The detached array is ours alone, which is why it is reversed in place. Each disposer is awaited before the next so resources release in dependency order. + for (const disposer of disposers.reverse()) { + try { + await disposer() + } catch (error) { + heldError = hasError + ? createSuppressedError(error, heldError) + : error + hasError = true + } + } + + if (hasError) { + throw heldError + } + } + + /** + * Disposes the stack, which is what an `await using` declaration calls. + */ + async [Symbol.asyncDispose](): Promise { + await this.disposeAsync() + } +} diff --git a/src/lib/util/disposableStack.spec.ts b/src/lib/util/disposableStack.spec.ts new file mode 100644 index 000000000..4609e0265 --- /dev/null +++ b/src/lib/util/disposableStack.spec.ts @@ -0,0 +1,473 @@ +import { describe, expect, it } from 'vitest' + +import { DisposableStack, SuppressedError } from './disposableStack.js' + +// A factory of fresh stacks. The differential oracle drives one scenario through two factories, one over the local stack and one over the platform global, +// and compares what each observes; the instance type is the platform interface, which the local stack implements. +type StackFactory = () => InstanceType + +// A disposal that runs last in, first out, with the disposed flag before and after it. +function scenarioHappyLifo(makeStack: StackFactory): { disposedAfter: boolean, disposedBefore: boolean, order: string[] } { + const order: string[] = [] + const stack = makeStack() + const disposedBefore = stack.disposed + + stack.defer(() => order.push('a')) + stack.defer(() => order.push('b')) + stack.defer(() => order.push('c')) + stack.dispose() + + return { disposedAfter: stack.disposed, disposedBefore, order } +} + +// The pending disposers moved to a new stack and both stacks disposed: the source reads disposed and runs nothing, and the target runs the moved set last in, +// first out. +function scenarioMoveThenDisposeBoth(makeStack: StackFactory): { movedRan: string[], sourceDisposed: boolean, targetDisposedInitially: boolean } { + const movedRan: string[] = [] + const stack = makeStack() + + stack.defer(() => movedRan.push('x')) + stack.defer(() => movedRan.push('y')) + + const moved = stack.move() + const sourceDisposed = stack.disposed + const targetDisposedInitially = moved.disposed + + stack.dispose() + moved.dispose() + + return { movedRan, sourceDisposed, targetDisposedInitially } +} + +// One throwing disposer among others: every disposer runs and the one error is rethrown once the sweep ends. +function scenarioSingleThrow(makeStack: StackFactory): { order: string[], thrownMessage: string | null } { + const order: string[] = [] + const stack = makeStack() + + stack.defer(() => order.push('a')) + stack.defer(() => { + order.push('b') + throw new Error('boom') + }) + stack.defer(() => order.push('c')) + + let thrownMessage: string | null = null + try { + stack.dispose() + } catch (error) { + thrownMessage = (error as Error).message + } + + return { order, thrownMessage } +} + +// Two throwing disposers around one that does not: a SuppressedError links the newest failure, its `error`, to the earlier one, its `suppressed`, and every +// disposer runs. +function scenarioMultiThrow(makeStack: StackFactory): { errorMessage: string | null, order: string[], suppressedMessage: string | null, thrownName: string | null } { + const order: string[] = [] + const stack = makeStack() + + stack.defer(() => { + order.push('a') + throw new Error('first') + }) + stack.defer(() => order.push('b')) + stack.defer(() => { + order.push('c') + throw new Error('second') + }) + + let errorMessage: string | null = null + let suppressedMessage: string | null = null + let thrownName: string | null = null + try { + stack.dispose() + } catch (error) { + const suppressed = error as { error?: { message?: string }, name?: string, suppressed?: { message?: string } } + errorMessage = suppressed.error?.message ?? null + suppressedMessage = suppressed.suppressed?.message ?? null + thrownName = suppressed.name ?? null + } + + return { + errorMessage, + order, + suppressedMessage, + thrownName, + } +} + +// A resource whose dispose method changes after registration: the method captured at registration runs. +function scenarioCaptureThenMutate(makeStack: StackFactory): { order: string[] } { + const order: string[] = [] + const stack = makeStack() + const resource = { + [Symbol.dispose]: (): void => { + order.push('original') + }, + } + + stack.use(resource) + resource[Symbol.dispose] = (): void => { + order.push('mutated') + } + stack.dispose() + + return { order } +} + +// Null and undefined passed to use() register nothing, and only the deferred disposer runs. +function scenarioUseNullPassthrough(makeStack: StackFactory): { order: string[] } { + const order: string[] = [] + const stack = makeStack() + + stack.use(null) + stack.use(undefined) + stack.defer(() => order.push('d')) + stack.dispose() + + return { order } +} + +// A defer() on a disposed stack throws a ReferenceError. +function scenarioPostDisposeDefer(makeStack: StackFactory): { threwReferenceError: boolean } { + const stack = makeStack() + stack.dispose() + + let threwReferenceError = false + try { + stack.defer(() => undefined) + } catch (error) { + threwReferenceError = error instanceof ReferenceError + } + + return { threwReferenceError } +} + +// An instance's own properties but its stack, each as its name and attribute flags, which lets the oracle tell a payload attached by plain assignment, enumerable, +// from the spec's non-enumerable one with the same value. +function ownPropertyShape(instance: object): string[] { + return Object.entries(Object.getOwnPropertyDescriptors(instance)) + .filter(([key]) => key !== 'stack') + .map(([key, descriptor]) => `${key}: configurable=${descriptor.configurable} enumerable=${descriptor.enumerable} writable=${descriptor.writable}`) + .sort() +} + +// What a constructed instance shows, which lets two call forms, or the local constructor and the platform global, compare on equal terms. +function shapeOf(thrown: unknown): { error: unknown, isError: boolean, message: string, name: string, ownProperties: string[], suppressed: unknown } { + const instance = thrown as Error & { error: unknown, suppressed: unknown } + + return { + error: instance.error, + isError: instance instanceof Error, + message: instance.message, + name: instance.name, + ownProperties: ownPropertyShape(instance), + suppressed: instance.suppressed, + } +} + +describe('disposableStack', () => { + describe('contract', () => { + it('disposes registered callbacks in last-in-first-out order', () => { + const order: string[] = [] + const stack = new DisposableStack() + + stack.defer(() => order.push('a')) + stack.defer(() => order.push('b')) + stack.defer(() => order.push('c')) + stack.dispose() + + expect(order).toEqual(['c', 'b', 'a']) + }) + + it('use() binds the disposal method to the value as its receiver', () => { + const seen: string[] = [] + const resource = { + marker: 'R', + [Symbol.dispose](): void { + seen.push(this.marker) + }, + } + const stack = new DisposableStack() + + expect(stack.use(resource)).toBe(resource) + + stack.dispose() + + expect(seen).toEqual(['R']) + }) + + it('use() passes null and undefined through without registering them', () => { + const order: string[] = [] + const stack = new DisposableStack() + const nullResult: unknown = stack.use(null) + + expect(nullResult).toBeNull() + + stack.use(undefined) + stack.defer(() => order.push('only')) + stack.dispose() + + expect(order).toEqual(['only']) + }) + + it('use() captures the dispose method at registration time', () => { + expect(scenarioCaptureThenMutate(() => new DisposableStack()).order).toEqual(['original']) + }) + + it('adopt() invokes the callback with the value and returns the value unchanged', () => { + const seen: string[] = [] + const value = { id: 'V' } + const stack = new DisposableStack() + + expect(stack.adopt(value, adopted => seen.push(adopted.id))).toBe(value) + + stack.dispose() + + expect(seen).toEqual(['V']) + }) + + it('use() throws a TypeError when the dispose member is not callable', () => { + const stack = new DisposableStack() + + expect(() => stack.use({ [Symbol.dispose]: 42 } as unknown as Disposable)).toThrow(TypeError) + }) + + it('adopt() throws a TypeError when onDispose is not a function', () => { + const stack = new DisposableStack() + + expect(() => stack.adopt({}, 42 as unknown as (value: object) => void)).toThrow(TypeError) + }) + + it('defer() throws a TypeError when the callback is not a function', () => { + const stack = new DisposableStack() + + expect(() => stack.defer(42 as unknown as () => void)).toThrow(TypeError) + }) + + it('use(), adopt(), defer(), and move() throw a ReferenceError once disposed', () => { + const stack = new DisposableStack() + stack.dispose() + + expect(() => stack.use(null)).toThrow(ReferenceError) + expect(() => stack.adopt({}, () => undefined)).toThrow(ReferenceError) + expect(() => stack.defer(() => undefined)).toThrow(ReferenceError) + expect(() => stack.move()).toThrow(ReferenceError) + }) + + it('move() transfers the pending disposers without running them and disposes the source', () => { + const order: string[] = [] + const stack = new DisposableStack() + + stack.defer(() => order.push('a')) + stack.defer(() => order.push('b')) + + const moved = stack.move() + + expect(stack.disposed).toBe(true) + expect(moved.disposed).toBe(false) + expect(order).toEqual([]) + + moved.dispose() + + expect(order).toEqual(['b', 'a']) + }) + + it('dispose() is safe to call more than once', () => { + let count = 0 + const stack = new DisposableStack() + + stack.defer(() => { + count++ + }) + stack.dispose() + stack.dispose() + + expect(count).toBe(1) + }) + + it('dispose() runs every disposer and rethrows a single failure', () => { + const result = scenarioSingleThrow(() => new DisposableStack()) + + expect(result.order).toEqual(['c', 'b', 'a']) + expect(result.thrownMessage).toBe('boom') + }) + + it('dispose() chains multiple failures through a SuppressedError', () => { + const result = scenarioMultiThrow(() => new DisposableStack()) + + expect(result.order).toEqual(['c', 'b', 'a']) + expect(result.thrownName).toBe('SuppressedError') + expect(result.errorMessage).toBe('first') + expect(result.suppressedMessage).toBe('second') + }) + + it('[Symbol.dispose]() delegates to dispose()', () => { + let disposed = false + const stack = new DisposableStack() + + stack.defer(() => { + disposed = true + }) + stack[Symbol.dispose]() + + expect(disposed).toBe(true) + expect(stack.disposed).toBe(true) + }) + + it('disposed transitions from false to true', () => { + const stack = new DisposableStack() + + expect(stack.disposed).toBe(false) + + stack.dispose() + + expect(stack.disposed).toBe(true) + }) + + // The aggregation a runtime without the SuppressedError global takes cannot run where the global ships: the row deletes it, drives a disposal that + // fails twice and puts the global back in a finally, which means the deletion never reaches another row. + it('falls back to the in-package SuppressedError when the platform global is absent', () => { + const savedSuppressedError = globalThis.SuppressedError + + try { + delete (globalThis as { SuppressedError?: unknown }).SuppressedError + + const order: string[] = [] + const firstError = new Error('first') + const secondError = new Error('second') + const stack = new DisposableStack() + + stack.defer(() => { + order.push('a') + throw firstError + }) + stack.defer(() => order.push('b')) + stack.defer(() => { + order.push('c') + throw secondError + }) + + let caught: unknown + try { + stack.dispose() + } catch (error) { + caught = error + } + + expect(caught).toBeInstanceOf(SuppressedError) + expect(caught).toBeInstanceOf(Error) + + const suppressed = caught as Error & { error: unknown, suppressed: unknown } + + expect(suppressed.name).toBe('SuppressedError') + expect(suppressed.error).toBe(firstError) + expect(suppressed.suppressed).toBe(secondError) + expect(order).toEqual(['c', 'b', 'a']) + } finally { + globalThis.SuppressedError = savedSuppressedError + } + }) + }) + + // The oracle needs the platform class to differ against, which this machine's Node ships; a runtime without it skips the describe. + describe.skipIf(typeof globalThis.DisposableStack !== 'function')('differential oracle against the platform global', () => { + it.each([ + { name: 'happy last-in-first-out disposal', run: scenarioHappyLifo }, + { name: 'move then dispose both stacks', run: scenarioMoveThenDisposeBoth }, + { name: 'single failure rethrow', run: scenarioSingleThrow }, + { name: 'multiple failures suppression chain', run: scenarioMultiThrow }, + { name: 'use()-time capture then mutate', run: scenarioCaptureThenMutate }, + { name: 'use() null and undefined passthrough', run: scenarioUseNullPassthrough }, + { name: 'defer after dispose', run: scenarioPostDisposeDefer }, + ] as { name: string, run: (makeStack: StackFactory) => unknown }[])('$name', ({ run }) => { + expect(run(() => new DisposableStack())).toStrictEqual(run(() => new globalThis.DisposableStack())) + }) + }) +}) + +describe('suppressedError', () => { + describe('construction duality', () => { + it('`new` construction carries the failures, the name, and the Error prototype', () => { + const newest = new Error('newest') + const accumulated = new Error('accumulated') + const chained = new SuppressedError(newest, accumulated) + + expect(chained).toBeInstanceOf(SuppressedError) + expect(chained).toBeInstanceOf(Error) + expect(chained.name).toBe('SuppressedError') + expect(chained.error).toBe(newest) + expect(chained.suppressed).toBe(accumulated) + }) + + // The bare call is the half of the contract a class cannot answer and the definition's type assertion cannot check, which is why this row is its proof. + it('a bare call constructs exactly as `new` does', () => { + const newest = new Error('newest') + const accumulated = new Error('accumulated') + const chained = SuppressedError(newest, accumulated) + + expect(chained).toBeInstanceOf(SuppressedError) + expect(chained).toBeInstanceOf(Error) + expect(chained.error).toBe(newest) + expect(chained.suppressed).toBe(accumulated) + }) + + it('both call forms produce structurally identical instances', () => { + const newest = new Error('newest') + const accumulated = new Error('accumulated') + + expect(shapeOf(new SuppressedError(newest, accumulated, 'both failed'))).toStrictEqual(shapeOf(SuppressedError(newest, accumulated, 'both failed'))) + }) + + it('an omitted message leaves the inherited empty message rather than the string "undefined"', () => { + const chained = new SuppressedError(new Error('a'), new Error('b')) + + expect(chained.message).toBe('') + expect(Object.getOwnPropertyDescriptor(chained, 'message')).toBeUndefined() + }) + + it('a supplied message is carried verbatim', () => { + expect(new SuppressedError(new Error('a'), new Error('b'), 'Two resources failed to dispose.').message).toBe('Two resources failed to dispose.') + }) + + it('non-Error failures are carried unchanged', () => { + const chained = new SuppressedError('a string failure', 42) + + expect(chained.error).toBe('a string failure') + expect(chained.suppressed).toBe(42) + }) + + it('the constructor and its prototype are linked in both directions', () => { + const chained = new SuppressedError(new Error('a'), new Error('b')) + + expect(Object.getPrototypeOf(chained)).toBe(SuppressedError.prototype) + expect(chained.constructor).toBe(SuppressedError) + expect(Object.getPrototypeOf(SuppressedError.prototype)).toBe(Error.prototype) + }) + }) + + // The oracle needs the platform constructor to differ against, which this machine's Node ships; the runtime floor this module serves lacks it. + describe.skipIf(typeof globalThis.SuppressedError !== 'function')('differential oracle against the platform global', () => { + it.each([ + { + name: 'new construction', + run: make => shapeOf(new make('e', 's')), + }, + { + name: 'bare call construction', + run: make => shapeOf(make('e', 's')), + }, + { + name: 'construction with a message', + run: make => shapeOf(make('e', 's', 'both failed')), + }, + { + name: 'construction from non-Error failures', + run: make => shapeOf(new make(42, { reason: 's' })), + }, + ] as { name: string, run: (make: SuppressedErrorConstructor) => unknown }[])('$name', ({ run }) => { + expect(run(SuppressedError)).toStrictEqual(run(globalThis.SuppressedError)) + }) + }) +}) diff --git a/src/lib/util/disposableStack.ts b/src/lib/util/disposableStack.ts new file mode 100644 index 000000000..115218a64 --- /dev/null +++ b/src/lib/util/disposableStack.ts @@ -0,0 +1,224 @@ +import type { Nullable } from '../../types.js' + +/* The platform's DisposableStack and SuppressedError for an engines floor whose Node ships Symbol.dispose and Symbol.asyncDispose but not the stack + * globals, which arrive with Node 24. The library shares its process with every plugin, which is why it installs no global: every site imports these by name, and a + * construction reads as it would against the platform class. src/lib/util/runtimeFloor.spec.ts demands this module's deletion, with the async stack's, + * once the engines floor reaches Node 24. + */ + +// The prototype every instance shares. It descends from Error.prototype, which means an instance is an Error and inherits its behavior. The prototype also carries the +// spec's `name` with a class member's flags, non-enumerable, writable and configurable, as the platform constructor's prototype does. +const suppressedErrorPrototype = Object.create(Error.prototype, { + name: { + configurable: true, + enumerable: false, + value: 'SuppressedError', + writable: true, + }, +}) as Error + +/* Builds an instance. A real Error gives it a stack trace from the construction site, which Object.create alone would not, and re-pointing its prototype + * makes it a SuppressedError. The message passes through untouched, and an omitted one leaves the inherited empty message rather than the string + * "undefined". The function shape is the contract's rather than a taste: the platform's SuppressedErrorConstructor declares a construct signature and a bare + * call signature, a class throws when it is called without `new`, and a function that returns the object it built answers both, because a construct call + * takes the returned object in place of the one it allocated. + */ +function constructSuppressedError(error: unknown, suppressed: unknown, message?: string): SuppressedError { + const instance = new Error(message) as SuppressedError + Object.setPrototypeOf(instance, suppressedErrorPrototype) + + // The spec makes `error` and `suppressed` non-enumerable own data properties, as Error makes `message`, and neither spills into a structural walk of the + // caught failure. A plain assignment would make them enumerable, which is the difference the differential oracle reads. + Object.defineProperties(instance, { + error: { + configurable: true, + enumerable: false, + value: error, + writable: true, + }, + suppressed: { + configurable: true, + enumerable: false, + value: suppressed, + writable: true, + }, + }) + + return instance +} + +// The constructor and its prototype link both ways through defineProperty. `prototype` stays read-only and `constructor` non-enumerable, the platform's +// own shape, rather than enumerable properties a structural comparison would read. +Object.defineProperty(constructSuppressedError, 'prototype', { value: suppressedErrorPrototype, writable: false }) +Object.defineProperty(suppressedErrorPrototype, 'constructor', { configurable: true, value: constructSuppressedError, writable: true }) + +/** + * The spec's `SuppressedError` constructor, which links a newer failure to the one it supersedes: a disposal that fails more than once loses none of its + * failures. Both `new SuppressedError(error, suppressed)` and `SuppressedError(error, suppressed)` construct, and an instance is an `Error` named + * `SuppressedError`. The one type assertion is a boundary the compiler cannot check: only a class carries a construct signature and a class refuses the bare + * call. The construct half rests on the duality rows and the differential oracle against the platform global. + */ +export const SuppressedError = constructSuppressedError as SuppressedErrorConstructor + +/** + * Builds the `SuppressedError` that links a newer disposal failure to the one it supersedes, for this stack and the async stack, which owe their callers the + * same aggregation. + * @param error - The newest failure. + * @param suppressed - The failure it supersedes. + * @returns The chained error. + */ +export function createSuppressedError(error: unknown, suppressed: unknown): unknown { + // The global is read at every call rather than cached, because it belongs to the surface Node 22 lacks; the optional type states what the platform lib + // cannot, that it may be absent here. + const platformConstructor = (globalThis as { SuppressedError?: typeof globalThis.SuppressedError }).SuppressedError + + if (platformConstructor !== undefined) { + return new platformConstructor(error, suppressed) + } + + // Without the global the local constructor answers, and the aggregation reads the same whether or not the platform ships one. + return new SuppressedError(error, suppressed) +} + +/** + * A container of disposable resources that disposes them last in, first out, when it is disposed itself. The `implements` clause binds the class to the + * platform's `DisposableStack`, and the compiler holds it to the contract its name promises. + */ +export class DisposableStack implements InstanceType { + // The pending disposers in registration order, and null once the stack is disposed. One field carries both: a disposed stack with pending work cannot + // be represented, and every member reads this field alone to decide whether it may still register or run work. + #disposers: Nullable<(() => void)[]> = [] + + // The platform's tag, which Object.prototype.toString reports. + readonly [Symbol.toStringTag] = 'DisposableStack' + + /** + * Whether the stack has been disposed. + */ + get disposed(): boolean { + return this.#disposers === null + } + + /** + * Registers a resource whose `[Symbol.dispose]()` runs when the stack is disposed. Null and undefined pass through unregistered, and the dispose method is + * captured now and called with the value as its receiver: a later change to the value's member cannot change what runs. + * @param value - The resource, or null or undefined to register nothing. + * @returns The value, unchanged. + */ + use(value: T): T { + if (this.#disposers === null) { + throw new ReferenceError('Cannot use a resource on a disposed DisposableStack.') + } + + if (value === null || typeof value === 'undefined') { + return value + } + + // The member is read through unknown because use() is a trust boundary: a value can satisfy the type and still carry a member that is not callable at + // run time, which the spec refuses with a TypeError. + const disposeMethod: unknown = value[Symbol.dispose] + + if (typeof disposeMethod !== 'function') { + throw new TypeError('The value passed to DisposableStack.use() is not disposable.') + } + + this.#disposers.push(() => { + disposeMethod.call(value) + }) + + return value + } + + /** + * Registers a value with the callback that disposes it, called with the value when the stack is disposed. + * @param value - The value. + * @param onDispose - The callback, given the value. + * @returns The value, unchanged. + */ + adopt(value: T, onDispose: (value: T) => void): T { + if (this.#disposers === null) { + throw new ReferenceError('Cannot adopt a resource on a disposed DisposableStack.') + } + + if (typeof onDispose !== 'function') { + throw new TypeError('The onDispose callback passed to DisposableStack.adopt() is not a function.') + } + + this.#disposers.push(() => onDispose(value)) + + return value + } + + /** + * Registers a callback to run when the stack is disposed. + * @param onDispose - The callback. + */ + defer(onDispose: () => void): void { + if (this.#disposers === null) { + throw new ReferenceError('Cannot defer a callback on a disposed DisposableStack.') + } + + if (typeof onDispose !== 'function') { + throw new TypeError('The onDispose callback passed to DisposableStack.defer() is not a function.') + } + + this.#disposers.push(onDispose) + } + + /** + * Moves every pending disposer, in registration order, into a new stack and marks this one disposed without running any of them. After an acquisition + * succeeds, the move hands its resources to a stack that outlives the scope whose stack would otherwise release them. + * @returns The new stack, which owns the moved disposers. + */ + move(): DisposableStack { + if (this.#disposers === null) { + throw new ReferenceError('Cannot move a disposed DisposableStack.') + } + + const moved = new DisposableStack() + moved.#disposers = this.#disposers + this.#disposers = null + + return moved + } + + /** + * Disposes every registered resource, last in, first out, and does nothing once the stack is disposed. Every disposer runs when an earlier one throws: one + * failure is rethrown once the sweep ends, and several chain through a `SuppressedError`, the newest wrapping the rest. + */ + dispose(): void { + if (this.#disposers === null) { + return + } + + // The array is detached and the stack marked disposed before anything runs: a disposer that reaches back into the stack finds it disposed. + const disposers = this.#disposers + this.#disposers = null + + let hasError = false + let heldError: unknown + + // The detached array is ours alone, which is why it is reversed in place. + for (const disposer of disposers.reverse()) { + try { + disposer() + } catch (error) { + heldError = hasError + ? createSuppressedError(error, heldError) + : error + hasError = true + } + } + + if (hasError) { + throw heldError + } + } + + /** + * Disposes the stack, which is what a `using` declaration calls. + */ + [Symbol.dispose](): void { + this.dispose() + } +} diff --git a/src/lib/util/runtimeFloor.spec.ts b/src/lib/util/runtimeFloor.spec.ts new file mode 100644 index 000000000..d1d56d373 --- /dev/null +++ b/src/lib/util/runtimeFloor.spec.ts @@ -0,0 +1,155 @@ +import { readdir, readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { describe, expect, it } from 'vitest' + +// The Node major that ships DisposableStack, AsyncDisposableStack and SuppressedError as globals, the floor at which the internal stacks retire. +const NODE_STACK_GLOBALS_MAJOR = 24 + +// The deletion checklist the live row fails with once the engines floor reaches that major, which makes the retirement a list the suite demands. +const SUNSET_CHECKLIST = [ + 'The engines floor has reached Node 24, which ships DisposableStack, AsyncDisposableStack and SuppressedError as globals. The internal stacks retire:', + 'delete src/lib/util/disposableStack.ts, src/lib/util/asyncDisposableStack.ts and their specs, construct the globals at every site that imports them,', + 'remove the no-restricted-globals entry for the three names from eslint.config.mjs, and delete this spec.', +].join(' ') + +// One alternative of an engines range: an optional ^, ~ or >= and then a version. +const RANGE_ALTERNATIVE = /^(?:\^|~|>=)?(\d+)(?:\.\d+){0,2}$/ + +/* Each name the internal stack modules supply, with the construction that would read the global Node 22 lacks unless the file imports the name, and the + * by-name import from its module through a relative specifier. The DisposableStack construction never matches an AsyncDisposableStack one, because the name + * must follow `new` directly. The lint gate's no-restricted-globals entry refuses every other bare reference to the three names, and this detector is the + * second net, the one the suite itself holds. + */ +const STACK_NAMES = [ + { + name: 'DisposableStack', + construction: /\bnew\s+DisposableStack\s*\(/, + importer: /\bimport\s*\{[^}]*\bDisposableStack\b[^}]*\}\s*from\s*'\.\.?\/(?:[^']*\/)?disposableStack\.js'/, + }, + { + name: 'AsyncDisposableStack', + construction: /\bnew\s+AsyncDisposableStack\s*\(/, + importer: /\bimport\s*\{[^}]*\bAsyncDisposableStack\b[^}]*\}\s*from\s*'\.\.?\/(?:[^']*\/)?asyncDisposableStack\.js'/, + }, + { + name: 'SuppressedError', + construction: /\bnew\s+SuppressedError\s*\(/, + importer: /\bimport\s*\{[^}]*\bSuppressedError\b[^}]*\}\s*from\s*'\.\.?\/(?:[^']*\/)?disposableStack\.js'/, + }, +] + +// The lowest Node major across an engines range's alternatives, which lets the floor the range admits decide the regime. Anything else in the range is refused, +// because a floor this helper cannot read could otherwise pass as compatible. +function floorMajor(range: string): number { + return Math.min(...range.split('||').map((alternative) => { + const match = RANGE_ALTERNATIVE.exec(alternative.trim()) + + if (!match) { + throw new Error(`Unable to parse the engines range "${range}".`) + } + + return Number(match[1]) + })) +} + +// Below the major that ships the globals the internal stacks stand in for them, and at or above it they retire. +function regimeOf(major: number): 'compat' | 'sunset' { + return major < NODE_STACK_GLOBALS_MAJOR + ? 'compat' + : 'sunset' +} + +// The engines check the live row runs: the deletion checklist once the floor reaches the major that ships the globals. +function assertCompatFloor(range: string): void { + if (regimeOf(floorMajor(range)) === 'sunset') { + throw new Error(SUNSET_CHECKLIST) + } +} + +// The names a source constructs without importing them by name, each a construction that would throw on the floor's Node. +function unimportedConstructions(source: string): string[] { + return STACK_NAMES.filter(({ construction, importer }) => construction.test(source) && !importer.test(source)).map(({ name }) => name) +} + +describe('runtimeFloor', () => { + describe('regime helpers', () => { + it('reads ^22.20.0 || ^24 || ^26 as major 22, the compat regime', () => { + expect(floorMajor('^22.20.0 || ^24 || ^26')).toBe(22) + expect(regimeOf(22)).toBe('compat') + }) + + it('reads ^24 || ^26 as major 24, the sunset regime', () => { + expect(floorMajor('^24 || ^26')).toBe(24) + expect(regimeOf(24)).toBe('sunset') + }) + + it('reads >=24 as major 24, the sunset regime', () => { + expect(floorMajor('>=24')).toBe(24) + expect(regimeOf(floorMajor('>=24'))).toBe('sunset') + }) + + it('refuses a range it cannot read, the empty range included', () => { + expect(() => floorMajor('not-a-version')).toThrow('Unable to parse the engines range "not-a-version".') + expect(() => floorMajor('')).toThrow('Unable to parse the engines range "".') + }) + + it('fails the sunset regime with the deletion checklist', () => { + expect(() => assertCompatFloor('^24 || ^26')).toThrow(SUNSET_CHECKLIST) + + for (const fragment of [ + 'src/lib/util/disposableStack.ts', + 'src/lib/util/asyncDisposableStack.ts', + 'their specs', + 'construct the globals', + 'eslint.config.mjs', + 'delete this spec', + ]) { + expect(SUNSET_CHECKLIST).toContain(fragment) + } + }) + + it('catches a construction of each name without its import, passes one with it, and keeps the async stack from the sync detector', () => { + expect(unimportedConstructions('const stack = new DisposableStack()')).toEqual(['DisposableStack']) + expect(unimportedConstructions('import { DisposableStack } from \'../util/disposableStack.js\'\nconst stack = new DisposableStack()')).toEqual([]) + expect(unimportedConstructions('const stack = new AsyncDisposableStack()')).toEqual(['AsyncDisposableStack']) + expect(unimportedConstructions('import { AsyncDisposableStack } from \'./asyncDisposableStack.js\'\nconst stack = new AsyncDisposableStack()')).toEqual([]) + expect(unimportedConstructions('throw new SuppressedError(error, suppressed)')).toEqual(['SuppressedError']) + expect(unimportedConstructions('import {\n DisposableStack,\n SuppressedError,\n} from \'./disposableStack.js\'\nthrow new SuppressedError(a, b)')).toEqual([]) + }) + }) + + describe('live conformance', () => { + it('keeps the compat regime and every construction of a stack global in src imported by name', async () => { + // The regime comes from the engines field alone, and the field stays the one statement of the floor. + const { engines } = JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf8')) as { engines: { node: string } } + assertCompatFloor(engines.node) + + // The stack modules, their specs and this spec construct the names or spell them out, and the walk leaves them out. + const excluded = new Set([ + 'disposableStack.ts', + 'disposableStack.spec.ts', + 'asyncDisposableStack.ts', + 'asyncDisposableStack.spec.ts', + 'runtimeFloor.spec.ts', + ].map(name => fileURLToPath(new URL(name, import.meta.url)))) + const files = (await readdir(fileURLToPath(new URL('../../', import.meta.url)), { recursive: true, withFileTypes: true })) + .filter(entry => entry.isFile() && entry.name.endsWith('.ts')) + .map(entry => join(entry.parentPath, entry.name)) + .filter(path => !excluded.has(path)) + + // A walk scoped wrong would read almost nothing and pass for want of files, which is why it must read the tree. + expect(files.length).toBeGreaterThanOrEqual(100) + + const offenders: string[] = [] + for (const path of files) { + for (const name of unimportedConstructions(await readFile(path, 'utf8'))) { + offenders.push(`${path} constructs ${name} without importing it by name.`) + } + } + + expect(offenders).toEqual([]) + }) + }) +}) diff --git a/tsconfig.json b/tsconfig.json index 34628a99f..d6cba15e6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "target": "ES2022", - "lib": ["ES2023"], + "lib": ["ES2023", "ESNext.Disposable"], "rootDir": "./src", "module": "NodeNext", "moduleResolution": "NodeNext", From d24410a45af76ffa6a26db6ceec24dc68cd6a192 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:44 -0600 Subject: [PATCH 05/16] fix(datastream): end a destroyed data stream server for good, releasing the data stream's resources from disposable stacks --- .../datastream/DataStreamManagement.spec.ts | 91 +++- src/lib/datastream/DataStreamManagement.ts | 16 +- src/lib/datastream/DataStreamServer.spec.ts | 500 +++++++++++++++--- src/lib/datastream/DataStreamServer.ts | 109 ++-- src/lib/util/eventedhttp.spec.ts | 2 +- src/test-utils/dataStreamClient.ts | 289 ++++++++++ 6 files changed, 877 insertions(+), 130 deletions(-) create mode 100644 src/test-utils/dataStreamClient.ts diff --git a/src/lib/datastream/DataStreamManagement.spec.ts b/src/lib/datastream/DataStreamManagement.spec.ts index 59d257e34..0aa7737cc 100644 --- a/src/lib/datastream/DataStreamManagement.spec.ts +++ b/src/lib/datastream/DataStreamManagement.spec.ts @@ -1,12 +1,101 @@ +import type { SetupWrite } from '../../test-utils/dataStreamClient.js' + import { Buffer } from 'node:buffer' +import crypto from 'node:crypto' -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { DataStreamClient, FAKE_SERVER_PORT, setupAnswer, setupWrite, verifiedConnection } from '../../test-utils/dataStreamClient.js' +import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' import { HAPStatus } from '../HAPServer.js' import * as tlv from '../util/tlv.js' import { DataStreamManagement } from './DataStreamManagement.js' +function setupCharacteristic(management: DataStreamManagement): Characteristic { + return management.getService().getCharacteristic(Characteristic.SetupDataStreamTransport) +} + describe('DataStreamManagement', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + it('answers a Setup Data Stream Transport write with its status, port and salt, and a read with the same without the salt', async () => { + const management = new DataStreamManagement() + const client = await DataStreamClient.connect(management) + + expect(client.setup.status).toBe(0) + expect(client.setup.port).toBe(FAKE_SERVER_PORT) + expect(client.setup.salt).toHaveLength(32) + expect(setupAnswer(await setupCharacteristic(management).handleGetRequest() as string)).toEqual({ + port: FAKE_SERVER_PORT, + salt: undefined, + status: 0, + }) + }) + + it.each<[string, Partial]>([ + [ + 'a transport other than the data stream', + { transport: 1 }, + ], + [ + 'a salt of other than 32 bytes', + { + salt: crypto.randomBytes(31), + }, + ], + [ + 'a command other than start', + { command: 1 }, + ], + ])('refuses a write of %s as an invalid value', async (_name, overrides) => { + const management = new DataStreamManagement() + const value = setupWrite({ + salt: crypto.randomBytes(32), + ...overrides, + }) + + await expect(setupCharacteristic(management).handleSetRequest(value, verifiedConnection())).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + }) + + it('refuses a write that comes from no HAP connection as an invalid value', async () => { + const management = new DataStreamManagement() + + await expect(setupCharacteristic(management).handleSetRequest(setupWrite({ + salt: crypto.randomBytes(32), + }))).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + }) + + it('removes its read handler and write listeners and forgets its answer at destroy, and a second destroy throws nothing', async () => { + const management = new DataStreamManagement() + + await DataStreamClient.connect(management) + management.destroy() + + const characteristic = setupCharacteristic(management) + + // @ts-expect-error: private access + expect(characteristic.getHandler).toBeUndefined() + expect(characteristic.listenerCount(CharacteristicEventTypes.SET)).toBe(0) + // @ts-expect-error: private access + expect(management.lastSetupDataStreamTransportResponse).toBe('') + expect(() => management.destroy()).not.toThrow() + }) + + it('answers a write a destroyed data stream server refuses as a communication failure', async () => { + const management = new DataStreamManagement() + + // @ts-expect-error: private access + management.dataStreamServer.destroy() + + await expect(setupCharacteristic(management).handleSetRequest(setupWrite({ + salt: crypto.randomBytes(32), + }), verifiedConnection())) + .rejects + .toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + }) + it('should reject a setup write which is not a string as an invalid value', () => { const management = new DataStreamManagement() const callback = vi.fn() diff --git a/src/lib/datastream/DataStreamManagement.ts b/src/lib/datastream/DataStreamManagement.ts index 9506dbd0a..91bb8eef6 100644 --- a/src/lib/datastream/DataStreamManagement.ts +++ b/src/lib/datastream/DataStreamManagement.ts @@ -14,6 +14,7 @@ import createDebug from 'debug' import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' import { HAPStatus } from '../HAPServer.js' import { Service } from '../Service.js' +import { DisposableStack } from '../util/disposableStack.js' import * as tlv from '../util/tlv.js' import { DataStreamServer, @@ -75,19 +76,21 @@ export class DataStreamManagement { private readonly supportedDataStreamTransportConfiguration: string private lastSetupDataStreamTransportResponse = '' // stripped. excludes ACCESSORY_KEY_SALT + // What destroy releases: the data stream server, adopted last so it is destroyed first, then the Setup Data Stream Transport read handler and every + // write listener. + private readonly stack = new DisposableStack() + constructor(service?: DataStreamTransportManagement) { const supportedConfiguration: TransportType[] = [TransportType.HOMEKIT_DATA_STREAM] this.supportedDataStreamTransportConfiguration = this.buildSupportedDataStreamTransportConfigurationTLV(supportedConfiguration) this.dataStreamTransportManagementService = service || this.constructService() this.setupServiceHandlers() + this.stack.adopt(this.dataStreamServer, server => server.destroy()) } public destroy(): void { - this.dataStreamServer.destroy() // removes ALL listeners - this.dataStreamTransportManagementService.getCharacteristic(Characteristic.SetupDataStreamTransport) - .removeOnGet() - .removeAllListeners(CharacteristicEventTypes.SET) + this.stack.dispose() this.lastSetupDataStreamTransportResponse = '' } @@ -235,7 +238,10 @@ export class DataStreamManagement { } private setupServiceHandlers() { - this.dataStreamTransportManagementService.getCharacteristic(Characteristic.SetupDataStreamTransport) + const setupDataStreamTransport = this.dataStreamTransportManagementService.getCharacteristic(Characteristic.SetupDataStreamTransport) + + this.stack.defer(() => setupDataStreamTransport.removeOnGet().removeAllListeners(CharacteristicEventTypes.SET)) + setupDataStreamTransport .onGet(() => this.lastSetupDataStreamTransportResponse) .on(CharacteristicEventTypes.SET, (value, callback, _context, connection) => { if (!connection) { diff --git a/src/lib/datastream/DataStreamServer.spec.ts b/src/lib/datastream/DataStreamServer.spec.ts index 95ff06a28..01310488e 100644 --- a/src/lib/datastream/DataStreamServer.spec.ts +++ b/src/lib/datastream/DataStreamServer.spec.ts @@ -1,26 +1,29 @@ import type { Socket } from 'node:net' +import type { Mock } from 'vitest' import type { HAPConnection } from '../util/eventedhttp.js' -import type { DataStreamConnection, PreparedDataStreamSession } from './DataStreamServer.js' +import type { DataStreamConnection, PreparedDataStreamSession, PrepareSessionCallback, ResponseHandler } from './DataStreamServer.js' import { Buffer } from 'node:buffer' import crypto from 'node:crypto' import { EventEmitter } from 'node:events' +import net from 'node:net' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as hapCrypto from '../util/hapCrypto.js' -import { DataStreamParser, DataStreamReader, DataStreamWriter } from './DataStreamParser.js' -import { DataStreamServer, DataStreamServerEvent, HDSConnectionError, HDSStatus } from './DataStreamServer.js' - -class FakeSocket extends EventEmitter { - remoteAddress = '192.0.2.1' - setNoDelay = vi.fn() - setKeepAlive = vi.fn() - write = vi.fn() - end = vi.fn() - destroy = vi.fn() -} +import { + DataStreamClient, + encryptedFrame, + FAKE_SERVER_PORT, + FakeServer, + FakeSocket, + messagePayload, + sentFrame, + verifiedConnection, +} from '../../test-utils/dataStreamClient.js' +import { HAPConnectionEvent } from '../util/eventedhttp.js' +import { DataStreamManagement } from './DataStreamManagement.js' +import { DataStreamServer, DataStreamServerEvent, HDSConnectionError, HDSConnectionErrorType, HDSStatus, Protocols, Topics } from './DataStreamServer.js' interface TestSession { server: DataStreamServer @@ -56,31 +59,11 @@ function setupSession(): TestSession { } } -// builds a frame encrypted with the controller-to-accessory key of the session -function encryptedFrame(session: TestSession, payload: Buffer): Buffer { - const header = Buffer.from([0x01, 0, 0, 0]) - header.writeUIntBE(payload.length, 1, 3) - - const nonce = Buffer.alloc(8) - hapCrypto.writeUInt64LE(session.nonce++, nonce) - const encrypted = hapCrypto.chacha20_poly1305_encryptAndSeal(session.prepared.controllerToAccessoryEncryptionKey, nonce, header, payload) - - return Buffer.concat([header, encrypted.ciphertext, encrypted.authTag]) -} - -function messagePayload(header: Record, message: unknown = {}): Buffer { - const headerWriter = new DataStreamWriter() - const messageWriter = new DataStreamWriter() - DataStreamParser.encode(header, headerWriter) - DataStreamParser.encode(message, messageWriter) - - return Buffer.concat([ - Buffer.from([ - headerWriter.length(), - ]), - headerWriter.getData(), - messageWriter.getData(), - ]) +// A session whose connection was identified by its hello, the hello's answer the first frame the accessory wrote. +function identifiedSession(): TestSession { + const session = setupSession() + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'control', request: 'hello', id: 1 }))) + return session } describe('DataStreamServer', () => { @@ -99,6 +82,7 @@ describe('DataStreamServer', () => { afterEach(() => { vi.useRealTimers() + vi.restoreAllMocks() }) describe('tcp server errors', () => { @@ -151,22 +135,18 @@ describe('DataStreamServer', () => { }) describe('destroy of a server which never started', () => { - it('should still prepare a session afterwards', async () => { - vi.useRealTimers() + it('should refuse a session prepared afterwards', () => { const server = new DataStreamServer() + const callback = vi.fn() server.destroy() - expect((server as any).state).toBe(0) // not closing: there is no tcp server which could report that it closed + expect((server as any).state).toBe(4) // destroyed, although there is no tcp server which could report that it closed - const session = await new Promise((resolve, reject) => { - server.prepareSession(hapConnection(), crypto.randomBytes(32), (error, prepared) => error - ? reject(error) - : resolve(prepared)) - }) - expect(session?.port).toBeGreaterThan(0) + server.prepareSession(hapConnection(), crypto.randomBytes(32), callback) - server.destroy() - clearTimeout(session?.connectTimeout) + expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The data stream server was destroyed.')) + expect((server as any).tcpServer).toBeUndefined() + expect((server as any).preparedSessions).toHaveLength(0) }) it('should remove all listeners', () => { @@ -211,7 +191,29 @@ describe('DataStreamServer', () => { } expect((server as any).preparedSessions).toHaveLength(0) expect((server as any).pendingBinds).toHaveLength(0) - expect((server as any).state).toBe(0) // the next session starts a new server + expect((server as any).state).toBe(4) // destroyed: every later session is refused + }) + + it('should answer a prepare still waiting on a closing server once with the destroyed error', async () => { + const server = new DataStreamServer() + const callback = vi.fn() + server.prepareSession(hapConnection(), crypto.randomBytes(32), callback) + const tcpServer = (server as any).tcpServer + const closed = new Promise(resolve => tcpServer.once('close', resolve)) + + // The server binds (state 1) with the prepare waiting for its port. The prepared session's connect timer runs out before the server listens, and the + // server begins to close (state 3) with the prepare still unanswered. + expect((server as any).state).toBe(1) + vi.advanceTimersByTime(10000) + expect((server as any).state).toBe(3) + expect(callback).not.toHaveBeenCalled() + + // The destroy answers the waiting prepare once, and the server reads destroyed (state 4). + server.destroy() + await closed + + expect(callback).toHaveBeenCalledExactlyOnceWith(new Error('The data stream server was destroyed.')) + expect((server as any).state).toBe(4) }) }) @@ -240,12 +242,6 @@ describe('DataStreamServer', () => { }) describe('malformed frames', () => { - function identifiedSession(): TestSession { - const session = setupSession() - session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'control', request: 'hello', id: 1 }))) - return session - } - it.each([ [ 'an empty payload', @@ -420,6 +416,221 @@ describe('DataStreamServer', () => { }) }) + describe('hello', () => { + it('should end a connection that sends no hello at 10 seconds, not before', () => { + const { socket } = setupSession() + + vi.advanceTimersByTime(9999) + expect(socket.end).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + expect(socket.end).toHaveBeenCalledTimes(1) + }) + + it('should stop the hello timer of a connection whose socket closed before its hello, which then writes and ends nothing', () => { + const { socket } = setupSession() + + socket.emit('close') + expect(vi.getTimerCount()).toBe(0) + + vi.advanceTimersByTime(10000) + expect(socket.write).not.toHaveBeenCalled() + expect(socket.end).not.toHaveBeenCalled() + }) + }) + + describe('destroying', () => { + // Every TCP server the data stream server creates, in order. + let tcpServers: FakeServer[] + + beforeEach(() => { + tcpServers = [] + vi.spyOn(net, 'createServer').mockImplementation(() => { + const tcpServer = new FakeServer() + tcpServers.push(tcpServer) + return tcpServer as unknown as net.Server + }) + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + function hapConnection(): HAPConnection { + return Object.assign(new EventEmitter(), { + encryption: { + sharedSecret: crypto.randomBytes(32), + }, + sessionID: crypto.randomUUID(), + }) as unknown as HAPConnection + } + + function prepare(server: DataStreamServer): Mock { + const callback = vi.fn() + server.prepareSession(hapConnection(), crypto.randomBytes(32), callback) + return callback + } + + // Prepares a session on a TCP server that binds, opens the server's one connection on it and identifies that connection by its hello. + function listeningSession(server: DataStreamServer): TestSession { + const callback = prepare(server) + const tcpServer = tcpServers.at(-1)! + tcpServer.emit('listening') + + const socket = new FakeSocket() + tcpServer.emit('connection', socket) + // @ts-expect-error: private property access + const connection: DataStreamConnection = server.connections[0] + const session: TestSession = { + server, + socket, + connection, + prepared: callback.mock.calls[0][1]!, + nonce: 0, + } + socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'control', request: 'hello', id: 1 }))) + + return session + } + + it('should let a connection closing after the TCP server closed reach its listeners, and only then drop them', () => { + const server = new DataStreamServer() + const { connection, socket } = listeningSession(server) + const heard: { connection: DataStreamConnection, listeners: number }[] = [] + server.on('connection-closed', (closed) => { + heard.push({ + connection: closed, + listeners: server.listenerCount('connection-closed'), + }) + }) + + server.destroy() + expect(socket.end).toHaveBeenCalledTimes(1) + + // The TCP server's close arrives ahead of its last connection's close. + tcpServers[0].emit('close') + expect(server.listenerCount('connection-closed')).toBe(1) + + expect(() => socket.emit('close')).not.toThrow() + expect(heard).toHaveLength(1) + expect(heard[0].connection).toBe(connection) + expect(heard[0].listeners).toBe(1) + expect(server.listenerCount('connection-closed')).toBe(0) + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + expect(tcpServers).toHaveLength(1) + }) + + it('should drop a pending prepared session, and its timeout after the TCP server closed closes nothing', () => { + const server = new DataStreamServer() + prepare(server) + tcpServers[0].emit('listening') + + server.destroy() + expect(server.preparedSessions).toHaveLength(0) + expect(vi.getTimerCount()).toBe(0) + + tcpServers[0].emit('close') + expect(() => vi.advanceTimersByTime(10000)).not.toThrow() + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + expect(tcpServers).toHaveLength(1) + }) + + it('should answer each prepare waiting for the TCP server to bind with the error a later prepare gets', () => { + const server = new DataStreamServer() + const first = prepare(server) + const second = prepare(server) + + server.destroy() + // A TCP server closed while it binds emits close and never listening. + tcpServers[0].emit('close') + + expect(first).toHaveBeenCalledExactlyOnceWith(expect.any(Error)) + expect(second).toHaveBeenCalledExactlyOnceWith(first.mock.calls[0][0]) + expect(prepare(server)).toHaveBeenCalledExactlyOnceWith(first.mock.calls[0][0]) + expect(server.preparedSessions).toHaveLength(0) + expect(vi.getTimerCount()).toBe(0) + expect(tcpServers).toHaveLength(1) + }) + + it.each([ + [ + 'after its TCP server listened and closed', + (server: DataStreamServer): void => { + prepare(server) + tcpServers[0].emit('listening') + server.destroy() + tcpServers[0].emit('close') + }, + ], + [ + 'before it ever started a TCP server', + (server: DataStreamServer): void => { + server.destroy() + }, + ], + ])('should answer a prepare on a server destroyed %s with an error, holding no prepared session, timer or TCP server', (_, destroy) => { + const server = new DataStreamServer() + destroy(server) + const created = tcpServers.length + const callback = vi.fn() + + expect(() => server.prepareSession(hapConnection(), crypto.randomBytes(32), callback)).not.toThrow() + expect(callback).toHaveBeenCalledExactlyOnceWith(expect.any(Error)) + expect(server.preparedSessions).toHaveLength(0) + expect(vi.getTimerCount()).toBe(0) + expect(tcpServers).toHaveLength(created) + }) + + it('should serve a new prepared session on a new TCP server once it closed after its last connection closed', () => { + const server = new DataStreamServer() + const first = listeningSession(server) + + first.socket.emit('close') + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + tcpServers[0].emit('close') + + const next = listeningSession(server) + expect(tcpServers).toHaveLength(2) + expect(next.prepared.port).toBe(FAKE_SERVER_PORT) + // The one write is the hello response. + expect(next.socket.write).toHaveBeenCalledTimes(1) + expect(next.socket.end).not.toHaveBeenCalled() + }) + + it('should drop its own listeners at once when destroyed holding no connection', () => { + const server = new DataStreamServer() + + server.on(DataStreamServerEvent.CONNECTION_OPENED, vi.fn()) + server.on(DataStreamServerEvent.CONNECTION_CLOSED, vi.fn()) + prepare(server) + tcpServers[0].emit('listening') + server.destroy() + + expect(server.eventNames()).toEqual([]) + }) + + it('should answer a prepare made while the TCP server closes with the next TCP server\'s port, once the old one closed and 10 ms passed', () => { + const server = new DataStreamServer() + const first = listeningSession(server) + + first.socket.emit('close') + expect(tcpServers[0].close).toHaveBeenCalledTimes(1) + + const callback = prepare(server) + tcpServers[0].emit('close') + + vi.advanceTimersByTime(9) + expect(tcpServers).toHaveLength(1) + + vi.advanceTimersByTime(1) + expect(tcpServers).toHaveLength(2) + + tcpServers[1].address.mockReturnValue({ address: '0.0.0.0', family: 'IPv4', port: FAKE_SERVER_PORT + 1 }) + tcpServers[1].emit('listening') + expect(callback).toHaveBeenCalledExactlyOnceWith(undefined, expect.objectContaining({ port: FAKE_SERVER_PORT + 1 })) + }) + }) + describe('messages after a close', () => { it('should not hand on the messages which follow a close in the same chunk', () => { const session = setupSession() @@ -662,26 +873,6 @@ describe('DataStreamServer', () => { }) describe('unhandled requests', () => { - // decrypts the n-th frame the accessory wrote and returns its decoded header - function sentHeader(session: TestSession, index: number): unknown { - const frame: Buffer = session.socket.write.mock.calls[index][0] - const header = frame.subarray(0, 4) - const ciphertext = frame.subarray(4, frame.length - 16) - const authTag = frame.subarray(frame.length - 16) - - const nonce = Buffer.alloc(8) - hapCrypto.writeUInt64LE(index, nonce) - const payload = hapCrypto.chacha20_poly1305_decryptAndVerify(session.prepared.accessoryToControllerEncryptionKey, nonce, header, ciphertext, authTag) - - return DataStreamParser.decode(new DataStreamReader(payload.subarray(1, 1 + payload.readUInt8(0)))) - } - - function identifiedSession(): TestSession { - const session = setupSession() - session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'control', request: 'hello', id: 1 }))) - return session - } - it.each([ ['an unknown protocol', 'unknownProtocol'], ['a known protocol', 'control'], @@ -691,7 +882,7 @@ describe('DataStreamServer', () => { session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol, request: 'unknownTopic', id: 7 }))) expect(session.socket.write).toHaveBeenCalledTimes(2) // hello response + our answer - expect(sentHeader(session, 1)).toEqual({ + expect(sentFrame(session, 1).header).toEqual({ protocol, response: 'unknownTopic', id: 7, @@ -710,7 +901,7 @@ describe('DataStreamServer', () => { session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol, request: topic, id: 7 }))) expect(session.socket.write).toHaveBeenCalledTimes(2) // hello response + our answer - expect(sentHeader(session, 1)).toMatchObject({ + expect(sentFrame(session, 1).header).toMatchObject({ response: topic, id: 7, status: HDSStatus.MISSING_PROTOCOL, @@ -728,4 +919,157 @@ describe('DataStreamServer', () => { expect(session.socket.write).toHaveBeenCalledTimes(1) // only the hello response }) }) + + describe('requests', () => { + it('should hand a response to its request\'s handler once and clear the request\'s timer', () => { + const session = identifiedSession() + const handler = vi.fn() + + session.connection.sendRequest('test', 'ping', { value: 1 }, handler) + + const { header } = sentFrame(session, 1) + const response = messagePayload({ + protocol: 'test', + response: 'ping', + id: header.id, + status: HDSStatus.SUCCESS, + }, { value: 2 }) + + session.socket.emit('data', encryptedFrame(session, response)) + session.socket.emit('data', encryptedFrame(session, response)) + + expect(header).toMatchObject({ protocol: 'test', request: 'ping' }) + expect(handler).toHaveBeenCalledExactlyOnceWith(undefined, HDSStatus.SUCCESS, { value: 2 }) + expect(vi.getTimerCount()).toBe(0) + }) + + it('should end the socket at a request unanswered for 10 seconds and tell its handler of the timeout', () => { + const session = identifiedSession() + const handler = vi.fn() + + session.connection.sendRequest('test', 'ping', {}, handler) + + vi.advanceTimersByTime(9999) + expect(session.socket.end).not.toHaveBeenCalled() + expect(handler).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + expect(session.socket.end).toHaveBeenCalledTimes(1) + expect(handler).toHaveBeenCalledExactlyOnceWith(new Error('timeout'), undefined, {}) + }) + + it('should hand a request waiting at its socket\'s close the closed socket error, with no status and an empty message', async () => { + const client = await DataStreamClient.connect(new DataStreamManagement()) + const handler = vi.fn() + + client.connection.sendRequest('test', 'ping', {}, handler) + client.closeSocket() + + expect(handler).toHaveBeenCalledExactlyOnceWith(new HDSConnectionError('The connection was closed', HDSConnectionErrorType.CLOSED_SOCKET), undefined, {}) + expect(handler.mock.calls[0][0]).toHaveProperty('type', HDSConnectionErrorType.CLOSED_SOCKET) + }) + }) + + describe('the HAP connection', () => { + it('should end the socket when its HAP connection closes, and drop its listener and its listener allowance once the socket closes', async () => { + const hapConnection = verifiedConnection() + const listeners = hapConnection.listenerCount(HAPConnectionEvent.CLOSED) + const maxListeners = hapConnection.getMaxListeners() + const client = await DataStreamClient.connect(new DataStreamManagement(), hapConnection) + + expect(hapConnection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(listeners + 1) + expect(hapConnection.getMaxListeners()).toBe(maxListeners + 1) + + hapConnection.emit(HAPConnectionEvent.CLOSED) + expect(client.socket.end).toHaveBeenCalledTimes(1) + + client.closeSocket() + expect(hapConnection.listenerCount(HAPConnectionEvent.CLOSED)).toBe(listeners) + expect(hapConnection.getMaxListeners()).toBe(maxListeners) + }) + }) + + describe('dispatch', () => { + it('should leave a request unanswered when its global handler throws', () => { + const session = identifiedSession() + + session.server.onRequestMessage('test', 'fail', () => { + throw new Error('The handler failed.') + }) + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'test', request: 'fail', id: 7 }))) + + // The one write is the hello response. + expect(session.socket.write).toHaveBeenCalledTimes(1) + }) + + it('should keep the first protocol handler when a second is added for its protocol', () => { + const session = identifiedSession() + const first = { + eventHandler: { + tick: vi.fn(), + }, + } + const second = { + eventHandler: { + tick: vi.fn(), + }, + } + + expect(session.connection.addProtocolHandler('test', first)).toBe(true) + expect(session.connection.addProtocolHandler('test', second)).toBe(false) + + session.socket.emit('data', encryptedFrame(session, messagePayload({ protocol: 'test', event: 'tick' }, { value: 1 }))) + expect(first.eventHandler.tick).toHaveBeenCalledExactlyOnceWith({ value: 1 }) + expect(second.eventHandler.tick).not.toHaveBeenCalled() + }) + + it('should send a protocol\'s messages to its connection handler alone, refusing a request it cannot take, and to the global handlers once removed', async () => { + const management = new DataStreamManagement() + const handler = { + eventHandler: { + [Topics.DATA]: vi.fn(), + }, + } + const whoami = vi.fn((connection: DataStreamConnection) => { + connection.addProtocolHandler(Protocols.DATA_SEND, handler) + }) + const globalData = vi.fn() + const globalOpen = vi.fn() + const closed = vi.fn() + + management.onEventMessage(Protocols.TARGET_CONTROL, Topics.WHOAMI, whoami) + management.onEventMessage(Protocols.DATA_SEND, Topics.DATA, globalData) + management.onRequestMessage(Protocols.DATA_SEND, Topics.OPEN, globalOpen) + management.onServerEvent(DataStreamServerEvent.CONNECTION_CLOSED, closed) + + const client = await DataStreamClient.connect(management) + + client.event(Protocols.TARGET_CONTROL, Topics.WHOAMI, { identifier: 1 }) + client.event(Protocols.DATA_SEND, Topics.DATA, { streamId: 1 }) + + const refused = client.request(Protocols.DATA_SEND, Topics.OPEN, { streamId: 1 }) + + expect(whoami).toHaveBeenCalledExactlyOnceWith(client.connection, { identifier: 1 }) + expect(handler.eventHandler[Topics.DATA]).toHaveBeenCalledExactlyOnceWith({ streamId: 1 }) + expect(client.answerTo(refused)?.header).toEqual({ + protocol: Protocols.DATA_SEND, + response: Topics.OPEN, + id: refused, + status: HDSStatus.MISSING_PROTOCOL, + }) + expect(globalData).not.toHaveBeenCalled() + expect(globalOpen).not.toHaveBeenCalled() + + client.connection.removeProtocolHandler(Protocols.DATA_SEND, handler) + client.event(Protocols.DATA_SEND, Topics.DATA, { streamId: 2 }) + + const heard = client.request(Protocols.DATA_SEND, Topics.OPEN, { streamId: 2 }) + + expect(globalData).toHaveBeenCalledExactlyOnceWith(client.connection, { streamId: 2 }) + expect(globalOpen).toHaveBeenCalledExactlyOnceWith(client.connection, heard, { streamId: 2 }) + + client.closeSocket() + expect(closed).toHaveBeenCalledExactlyOnceWith(client.connection) + }) + }) }) diff --git a/src/lib/datastream/DataStreamServer.ts b/src/lib/datastream/DataStreamServer.ts index 08e163fcd..c8cdeb129 100644 --- a/src/lib/datastream/DataStreamServer.ts +++ b/src/lib/datastream/DataStreamServer.ts @@ -11,6 +11,7 @@ import net from 'node:net' import createDebug from 'debug' +import { DisposableStack } from '../util/disposableStack.js' import { errorMessage, errorStack } from '../util/errors.js' import { HAPConnectionEvent } from '../util/eventedhttp.js' import * as hapCrypto from '../util/hapCrypto.js' @@ -18,6 +19,9 @@ import { DataStreamParser, DataStreamReader, DataStreamWriter, Int64 } from './D const debug = createDebug('HAP-NodeJS:DataStream:Server') +// A destroyed server answers every prepare it still holds, and every later one, with this message. +const SERVER_DESTROYED_MESSAGE = 'The data stream server was destroyed.' + /** * @group HomeKit Data Streams (HDS) */ @@ -171,6 +175,8 @@ enum ServerState { BINDING, // server is created and is currently trying to bind LISTENING, // server is created and currently listening for new connections CLOSING, + // The server was destroyed and never starts again. It comes last: a check for a state below CLOSING never matches a destroyed server. + DESTROYED, } enum ConnectionState { @@ -307,7 +313,6 @@ export class DataStreamServer extends EventEmitter { preparedSessions: PreparedDataStreamSession[] = [] private readonly connections: DataStreamConnection[] = [] - private removeListenersOnceClosed = false private readonly internalEventEmitter: EventEmitter = new EventEmitter() // used for message event and message request handlers @@ -407,12 +412,20 @@ export class DataStreamServer extends EventEmitter { private timeoutPreparedSession(preparedSession: PreparedDataStreamSession) { debug('Prepared HDS session timed out since no connection was opened for 10 seconds (%s)', preparedSession.connection.sessionID) + this.dropPreparedSession(preparedSession) + + this.checkCloseable() + } + + // Forgets a prepared session and stops its connect timer: it neither identifies a later connection nor times out into checkCloseable. + private dropPreparedSession(preparedSession: PreparedDataStreamSession): void { + clearTimeout(preparedSession.connectTimeout) + preparedSession.connectTimeout = undefined + const index = this.preparedSessions.indexOf(preparedSession) if (index >= 0) { this.preparedSessions.splice(index, 1) } - - this.checkCloseable() } private checkTCPServerEstablished(preparedSession: PreparedDataStreamSession, callback: (error?: Error) => void) { @@ -443,6 +456,11 @@ export class DataStreamServer extends EventEmitter { debug('TCP socket is currently closing. Trying again when server is fully closed and opening a new one then.') this.tcpServer!.once('close', () => setTimeout(() => this.checkTCPServerEstablished(preparedSession, callback), 10)) break + case ServerState.DESTROYED: + debug('Refusing to prepare a data stream session on a destroyed server (%s)', preparedSession.connection.sessionID) + this.dropPreparedSession(preparedSession) + callback(new Error(SERVER_DESTROYED_MESSAGE)) + break } } @@ -490,11 +508,7 @@ export class DataStreamServer extends EventEmitter { */ private failPendingBinds(error: Error) { for (const { preparedSession, callback } of this.pendingBinds.splice(0)) { - clearTimeout(preparedSession.connectTimeout) - const index = this.preparedSessions.indexOf(preparedSession) - if (index >= 0) { - this.preparedSessions.splice(index, 1) - } + this.dropPreparedSession(preparedSession) callback(error) } } @@ -529,13 +543,7 @@ export class DataStreamServer extends EventEmitter { if (identifiedSession) { debug('[%s] Connection was successfully identified (linked with sessionId: %s)', connection.remoteAddress, identifiedSession.connection.sessionID) - const index = this.preparedSessions.indexOf(identifiedSession) - if (index >= 0) { - this.preparedSessions.splice(index, 1) - } - - clearTimeout(identifiedSession.connectTimeout) - identifiedSession.connectTimeout = undefined + this.dropPreparedSession(identifiedSession) // we have currently no experience with data stream connections, maybe it would be good to index active connections // by their hap sessionId in order to clear out old but still open connections when the controller opens a new one @@ -581,9 +589,14 @@ export class DataStreamServer extends EventEmitter { this.emit(DataStreamServerEvent.CONNECTION_CLOSED, connection) this.checkCloseable() + this.releaseListenersOnceDestroyed() + } - if (this.state === ServerState.CLOSING && this.removeListenersOnceClosed && this.connections.length === 0) { - this.removeAllListeners() // see this.destroy() + // A destroyed server drops its own listeners once it holds no connection: at the destroy itself when it holds none, and otherwise after its last + // connection's CONNECTION_CLOSED, which is why a listener registered before the destroy still hears the close of every connection the destroy ends. + private releaseListenersOnceDestroyed(): void { + if (this.state === ServerState.DESTROYED && this.connections.length === 0) { + this.removeAllListeners() } } @@ -598,36 +611,38 @@ export class DataStreamServer extends EventEmitter { } /** - * This method will fully stop the DataStreamServer + * This method will fully stop the DataStreamServer. + * A destroyed server stays destroyed: it never starts a TCP server again, and every later `prepareSession` is answered with an error. */ public destroy(): void { if (this.tcpServer && this.state < ServerState.CLOSING) { - // Only a TCP server reports `close`, which is what leaves the closing state again. - // A server which never started would stay in it for ever, and could not prepare a session anymore. + // Only a running TCP server is closed. The closing state holds while the waiting prepares are answered below, and the destroyed state follows. this.state = ServerState.CLOSING this.tcpServer.close() for (const connection of this.connections) { connection.close() } - - // A server which is closed before it listens never reports `listening`, - // so nobody would answer those who still wait for its port. - this.failPendingBinds(new Error('The HomeKit Data Stream server was destroyed before it started to listen')) } - if (this.connections.length > 0) { - this.removeListenersOnceClosed = true // the connections still have to report that they closed - } else { - this.removeAllListeners() + // A prepare still waiting for the TCP server's port is answered here whatever state the destroy finds, since a destroyed server never listens again. + this.failPendingBinds(new Error(SERVER_DESTROYED_MESSAGE)) + + for (const preparedSession of [...this.preparedSessions]) { + this.dropPreparedSession(preparedSession) } + + this.state = ServerState.DESTROYED this.internalEventEmitter.removeAllListeners() + this.releaseListenersOnceDestroyed() } private closed() { this.tcpServer = undefined this.tcpPort = undefined - this.state = ServerState.UNINITIALIZED + if (this.state !== ServerState.DESTROYED) { + this.state = ServerState.UNINITIALIZED + } } } @@ -726,14 +741,16 @@ export class DataStreamConnection extends EventEmitter { private incompleteFrameLength = 0 private incompleteFrameNeeded = 0 // the total length the bytes need before there is something new to decode - private readonly hapConnectionClosedListener: () => void + // What the connection releases once its socket closes: the HAP connection's close listener with the listener allowance made for it, and the socket's + // end timer. Each release is deferred as its resource is taken. + private readonly stack = new DisposableStack() + private protocolHandlers: Record = {} // used to store protocolHandlers identified by their protocol name private responseHandlers: Record = {} // used to store responseHandlers indexed by their respective requestId private responseTimers: Record = {} // used to store response timeouts indexed by their respective requestId private helloTimer?: NodeJS.Timeout - private socketEndTimer?: NodeJS.Timeout constructor(socket: Socket) { super() @@ -748,8 +765,6 @@ export class DataStreamConnection extends EventEmitter { this.controllerToAccessoryNonce = 0 this.controllerToAccessoryNonceBuffer = Buffer.alloc(8) - this.hapConnectionClosedListener = this.onHAPSessionClosed.bind(this) - this.addProtocolHandler(Protocols.CONTROL, { requestHandler: { [Topics.HELLO]: this.handleHello.bind(this), @@ -941,9 +956,17 @@ export class DataStreamConnection extends EventEmitter { this.controllerToAccessoryEncryptionKey = identifiedSession.controllerToAccessoryEncryptionKey this.state = ConnectionState.EXPECTING_HELLO - // below listener is removed in .close() - this.connection.setMaxListeners(this.connection.getMaxListeners() + 1) - this.connection.on(HAPConnectionEvent.CLOSED, this.hapConnectionClosedListener) // register close listener + // The HAP connection's close closes this connection too. Its listener and the allowance made for it are released from the stack once the + // socket closes. + const hapConnection = identifiedSession.connection + const hapConnectionClosed = (): void => this.onHAPSessionClosed() + + hapConnection.setMaxListeners(hapConnection.getMaxListeners() + 1) + hapConnection.on(HAPConnectionEvent.CLOSED, hapConnectionClosed) + this.stack.defer(() => { + hapConnection.removeListener(HAPConnectionEvent.CLOSED, hapConnectionClosed) + hapConnection.setMaxListeners(hapConnection.getMaxListeners() - 1) + }) debug('[%s] Registering CLOSED handler to HAP connection. Connection currently has %d close handlers!', this.remoteAddress, this.connection.listenerCount(HAPConnectionEvent.CLOSED)) @@ -1291,11 +1314,13 @@ export class DataStreamConnection extends EventEmitter { this.socket.end() // a remote which never closes its side would otherwise keep the half-closed socket (and this connection) around forever - this.socketEndTimer = setTimeout(() => { + const socketEndTimer = setTimeout(() => { debug('[%s] Remote did not close the socket in time. Destroying it now.', this.remoteAddress) this.socket.destroy() }, DataStreamConnection.SOCKET_END_TIMEOUT) - this.socketEndTimer.unref() + + socketEndTimer.unref() + this.stack.defer(() => clearTimeout(socketEndTimer)) } isConsideredClosed(): boolean { @@ -1317,10 +1342,6 @@ export class DataStreamConnection extends EventEmitter { // this instance is now considered completely dead this.state = ConnectionState.CLOSED - if (this.socketEndTimer) { - clearTimeout(this.socketEndTimer) - this.socketEndTimer = undefined - } if (this.helloTimer) { clearTimeout(this.helloTimer) this.helloTimer = undefined @@ -1342,9 +1363,7 @@ export class DataStreamConnection extends EventEmitter { } this.emit(DataStreamConnectionEvent.CLOSED) - - this.connection?.removeListener(HAPConnectionEvent.CLOSED, this.hapConnectionClosedListener) - this.connection?.setMaxListeners(this.connection.getMaxListeners() - 1) + this.stack.dispose() this.removeAllListeners() } } diff --git a/src/lib/util/eventedhttp.spec.ts b/src/lib/util/eventedhttp.spec.ts index d9fd8d98a..2af06cedc 100644 --- a/src/lib/util/eventedhttp.spec.ts +++ b/src/lib/util/eventedhttp.spec.ts @@ -555,8 +555,8 @@ describe('EventedHTTPServer', () => { } finally { // @ts-expect-error: private access clearTimeout(server.connectionIdleTimeout) - vi.useRealTimers() vi.restoreAllMocks() + vi.useRealTimers() } }) }) diff --git a/src/test-utils/dataStreamClient.ts b/src/test-utils/dataStreamClient.ts new file mode 100644 index 000000000..ca5d6fdf0 --- /dev/null +++ b/src/test-utils/dataStreamClient.ts @@ -0,0 +1,289 @@ +/* The data stream harness the data stream and recording suites share: an in-memory socket and TCP server, the frames a controller encrypts and decodes, + * and a client that sets a session up through a management's Setup Data Stream Transport write and then talks to the accessory as a controller does. + * Every byte passes through the accessory's own decoding, decryption, dispatch, encoding and encryption; only the TCP transport is in memory, and a row's + * fake timers drive every timer of the session exactly. + */ +import type { Mock } from 'vitest' + +import type { DataStreamManagement } from '../lib/datastream/DataStreamManagement.js' +import type { DataStreamConnection, DataStreamServer, PreparedDataStreamSession } from '../lib/datastream/DataStreamServer.js' +import type { HAPConnection } from '../lib/util/eventedhttp.js' + +import { Buffer } from 'node:buffer' +import crypto from 'node:crypto' +import { EventEmitter } from 'node:events' +import net from 'node:net' + +import { vi } from 'vitest' + +import { Characteristic } from '../lib/Characteristic.js' +import { DataStreamParser, DataStreamReader, DataStreamWriter } from '../lib/datastream/DataStreamParser.js' +import * as hapCrypto from '../lib/util/hapCrypto.js' +import * as tlv from '../lib/util/tlv.js' +import { buildEmitterConnection } from './connectionFixtures.js' + +export class FakeSocket extends EventEmitter { + remoteAddress = '192.0.2.1' + setNoDelay: Mock<() => void> = vi.fn() + setKeepAlive: Mock<() => void> = vi.fn() + write: Mock<(data: Buffer) => boolean> = vi.fn() + end: Mock<() => void> = vi.fn() + destroy: Mock<() => void> = vi.fn() +} + +export const FAKE_SERVER_PORT = 49152 + +// Stands in for the TCP server. A row or the client emits its listening, connection and close events itself: every order the row reads is forced. +export class FakeServer extends EventEmitter { + listen: Mock<() => void> = vi.fn() + close: Mock<() => void> = vi.fn() + address: Mock<() => { address: string, family: string, port: number }> = vi.fn(() => ({ address: '0.0.0.0', family: 'IPv4', port: FAKE_SERVER_PORT })) +} + +// The keys of one data stream session, each named for the direction it encrypts. +export type SessionKeys = Pick + +// What a controller holds to write frames on a session: its keys, and the nonce of the next frame it writes. +export interface FrameWriter { + prepared: SessionKeys + nonce: number +} + +// What a controller reads the accessory's frames with: the socket the accessory wrote them to, and the session's keys. +export interface FrameReader { + prepared: SessionKeys + socket: FakeSocket +} + +// One message the accessory wrote, its header and its message decoded. +export interface WrittenMessage { + header: Record + message: Record +} + +// The values of a Setup Data Stream Transport write: its salt, and its command and transport, which default to what a controller starting a session writes. +export interface SetupWrite { + command?: number + salt: Buffer + transport?: number +} + +// What a Setup Data Stream Transport answer reads as: its status, its port and, from a write, the accessory's key salt. +export interface SetupAnswer { + port?: number + salt?: Buffer + status: number +} + +const ACCESSORY_TO_CONTROLLER_INFO = Buffer.from('HDS-Read-Encryption-Key') +const CONTROLLER_TO_ACCESSORY_INFO = Buffer.from('HDS-Write-Encryption-Key') + +// Builds a frame encrypted with the controller-to-accessory key of the session, taking the session's next nonce. +export function encryptedFrame(session: FrameWriter, payload: Buffer): Buffer { + const header = Buffer.from([0x01, 0, 0, 0]) + header.writeUIntBE(payload.length, 1, 3) + + const nonce = Buffer.alloc(8) + hapCrypto.writeUInt64LE(session.nonce++, nonce) + const encrypted = hapCrypto.chacha20_poly1305_encryptAndSeal(session.prepared.controllerToAccessoryEncryptionKey, nonce, header, payload) + + return Buffer.concat([header, encrypted.ciphertext, encrypted.authTag]) +} + +// A message's payload, its header and its body each encoded, the body of any shape a row hands, a malformed one among them. +export function messagePayload(header: Record, message: unknown = {}): Buffer { + const headerWriter = new DataStreamWriter() + const messageWriter = new DataStreamWriter() + DataStreamParser.encode(header, headerWriter) + DataStreamParser.encode(message, messageWriter) + + return Buffer.concat([ + Buffer.from([ + headerWriter.length(), + ]), + headerWriter.getData(), + messageWriter.getData(), + ]) +} + +// Decrypts the n-th frame the accessory wrote and decodes its header and message. The accessory takes one nonce per frame from 0, which means the frame's index +// among the socket's writes is its nonce. +export function sentFrame(session: FrameReader, index: number): WrittenMessage { + const frame: Buffer = session.socket.write.mock.calls[index][0] + const header = frame.subarray(0, 4) + const ciphertext = frame.subarray(4, frame.length - 16) + const authTag = frame.subarray(frame.length - 16) + + const nonce = Buffer.alloc(8) + hapCrypto.writeUInt64LE(index, nonce) + const payload = hapCrypto.chacha20_poly1305_decryptAndVerify(session.prepared.accessoryToControllerEncryptionKey, nonce, header, ciphertext, authTag) + const headerLength = payload.readUInt8(0) + + // The accessory writes a dictionary for each, which is what a row reads. + return { + header: DataStreamParser.decode(new DataStreamReader(payload.subarray(1, 1 + headerLength))) as WrittenMessage['header'], + message: DataStreamParser.decode(new DataStreamReader(payload.subarray(1 + headerLength))) as WrittenMessage['message'], + } +} + +// A HAP connection's events on a plain emitter, carrying the shared secret and the session ID the data stream server reads from a verified connection. +export function verifiedConnection(): HAPConnection { + return Object.assign(buildEmitterConnection(), { + encryption: { + sharedSecret: crypto.randomBytes(32), + }, + sessionID: crypto.randomUUID(), + }) +} + +// The base64 TLV of a Setup Data Stream Transport write. +export function setupWrite({ command = 0, salt, transport = 0 }: SetupWrite): string { + return Buffer.concat([ + tlv.encode(1, command), + tlv.encode(2, transport), + tlv.encode(3, salt), + ]).toString('base64') +} + +// Reads a Setup Data Stream Transport answer's base64 TLV. +export function setupAnswer(value: string): SetupAnswer { + const answer = tlv.decode(Buffer.from(value, 'base64')) + const parameters = answer[2] === undefined + ? undefined + : tlv.decode(answer[2]) + + return { + port: parameters?.[1]?.readUInt16LE(0), + salt: answer[3], + status: answer[1].readUInt8(0), + } +} + +// The TCP server a management's data stream server holds, read through private access. +function tcpServerOf(management: DataStreamManagement): FakeServer { + const server = (management as unknown as { dataStreamServer: DataStreamServer }).dataStreamServer + + return (server as unknown as { tcpServer: FakeServer }).tcpServer +} + +/** + * A controller's side of one data stream session on a management, from its Setup Data Stream Transport write to its socket's close. + */ +export class DataStreamClient implements FrameReader, FrameWriter { + readonly hapConnection: HAPConnection + readonly setup: SetupAnswer + readonly prepared: SessionKeys + readonly socket: FakeSocket + readonly connection: DataStreamConnection + nonce = 0 + + private nextRequestId = 1 + + private constructor({ connection, hapConnection, prepared, setup, socket }: { + connection: DataStreamConnection + hapConnection: HAPConnection + prepared: SessionKeys + setup: SetupAnswer + socket: FakeSocket + }) { + this.hapConnection = hapConnection + this.setup = setup + this.prepared = prepared + this.socket = socket + this.connection = connection + } + + /** + * Sets a session up through the management's Setup Data Stream Transport write, derives its keys as a controller does, opens its socket on the + * management's TCP server, which is a fake that binds no port, and says hello. + * @param management - The data stream management to connect to. + * @param hapConnection - The verified HAP connection the write comes from. + * @returns The client, its hello answered. + */ + static async connect(management: DataStreamManagement, hapConnection: HAPConnection = verifiedConnection()): Promise { + vi.spyOn(net, 'createServer').mockImplementation(() => new FakeServer() as unknown as net.Server) + + const controllerKeySalt = crypto.randomBytes(32) + const characteristic = management.getService().getCharacteristic(Characteristic.SetupDataStreamTransport) + const writing = characteristic.handleSetRequest(setupWrite({ salt: controllerKeySalt }), hapConnection) + const tcpServer = tcpServerOf(management) + + // The first prepare on a server starts its TCP server and waits for it to bind; a later one finds it listening. + if (tcpServer.listenerCount('listening') > 0) { + tcpServer.emit('listening') + } + + const setup = setupAnswer(await writing as string) + const salt = Buffer.concat([controllerKeySalt, setup.salt!]) + const sharedSecret = hapConnection.encryption!.sharedSecret + const prepared: SessionKeys = { + accessoryToControllerEncryptionKey: hapCrypto.HKDF('sha512', salt, sharedSecret, ACCESSORY_TO_CONTROLLER_INFO, 32), + controllerToAccessoryEncryptionKey: hapCrypto.HKDF('sha512', salt, sharedSecret, CONTROLLER_TO_ACCESSORY_INFO, 32), + } + const socket = new FakeSocket() + + tcpServer.emit('connection', socket) + + const connections = (management as unknown as { dataStreamServer: { connections: DataStreamConnection[] } }).dataStreamServer.connections + const client = new DataStreamClient({ + connection: connections.at(-1)!, + hapConnection, + prepared, + setup, + socket, + }) + + client.send(client.requestFrame('control', 'hello')) + + return client + } + + // An encrypted frame of a request, taking the client's next request ID. + requestFrame(protocol: string, topic: string, message: Record = {}): Buffer { + return encryptedFrame(this, messagePayload({ id: this.nextRequestId++, protocol, request: topic }, message)) + } + + // An encrypted frame of an event. + eventFrame(protocol: string, topic: string, message: Record = {}): Buffer { + return encryptedFrame(this, messagePayload({ event: topic, protocol }, message)) + } + + // Writes frames to the accessory in one socket read. + send(...frames: Buffer[]): void { + this.socket.emit('data', Buffer.concat(frames)) + } + + // Sends a request in a read of its own and returns its request ID. + request(protocol: string, topic: string, message: Record = {}): number { + const id = this.nextRequestId + + this.send(this.requestFrame(protocol, topic, message)) + + return id + } + + // Sends an event in a read of its own. + event(protocol: string, topic: string, message: Record = {}): void { + this.send(this.eventFrame(protocol, topic, message)) + } + + // Every message the accessory wrote, in order, the hello's answer first. + get written(): WrittenMessage[] { + return this.socket.write.mock.calls.map((_call, index) => sentFrame(this, index)) + } + + // The messages of every event of a protocol and topic the accessory wrote, in order. + events(protocol: string, topic: string): Record[] { + return this.written.filter(({ header }) => header.protocol === protocol && header.event === topic).map(({ message }) => message) + } + + // The accessory's answer to a request, or undefined while it has none. + answerTo(id: number): WrittenMessage | undefined { + return this.written.find(({ header }) => header.response !== undefined && header.id === id) + } + + // Closes the socket from the controller's side. + closeSocket(): void { + this.socket.emit('close') + } +} From 46bcc43cc415f5c1c205538cb3cccdd7909ef5cc Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:45 -0600 Subject: [PATCH 06/16] feat(definitions): add the camera services and characteristics for tiered streams, WebRTC views and buffered recording --- src/lib/Characteristic.ts | 135 +++++ src/lib/Service.ts | 40 ++ .../CharacteristicDefinitions.spec.ts | 162 ++++++ .../definitions/CharacteristicDefinitions.ts | 464 +++++++++++++++ .../DefinitionsConformance.spec.ts | 535 ++++++++++++++++++ .../definitions/ServiceDefinitions.spec.ts | 176 ++++++ src/lib/definitions/ServiceDefinitions.ts | 158 ++++++ .../definitions/generator-configuration.ts | 457 +++++++++++++++ 8 files changed, 2127 insertions(+) create mode 100644 src/lib/definitions/DefinitionsConformance.spec.ts diff --git a/src/lib/Characteristic.ts b/src/lib/Characteristic.ts index 27ae06ddb..b23843dd1 100644 --- a/src/lib/Characteristic.ts +++ b/src/lib/Characteristic.ts @@ -18,8 +18,20 @@ import type { AudioFeedback, BatteryLevel, Brightness, + BufferActivityCommand, + BufferEventCommand, + BufferEventSequenceNumber, + BufferUploadCommand, ButtonEvent, + CameraCapabilitiesData, + CameraClientCertificate, + CameraClientCertificateStatus, + CameraClientCSR, + CameraKey, + CameraKeyID, CameraOperatingModeIndicator, + CameraRecordingPublishingPoint, + CameraZones, CarbonDioxideDetected, CarbonDioxideLevel, CarbonDioxidePeakLevel, @@ -37,6 +49,7 @@ import type { ConfiguredName, ConnectionHealthMonitor, ContactSensorState, + ContributingSensors, CoolingThresholdTemperature, CryptoHash, CurrentAirPurifierState, @@ -108,6 +121,7 @@ import type { MetricsBufferFullState, Model, MotionDetected, + MotionEnabled, MultifunctionButton, Mute, Name, @@ -156,6 +170,7 @@ import type { RotationDirection, RotationSpeed, RouterStatus, + RTPStreamingControl, Saturation, SecuritySystemAlarmType, SecuritySystemCurrentState, @@ -166,6 +181,7 @@ import type { SelectedRTPStreamConfiguration, SelectedSessionKeepaliveConfigurationList, SelectedSleepConfiguration, + SensorUUID, SerialNumber, ServiceLabelIndex, ServiceLabelNamespace, @@ -193,11 +209,13 @@ import type { StatusJammed, StatusLowBattery, StatusTampered, + StreamingEnabled, StreamingStatus, SulphurDioxideDensity, SupportedAssetTypes, SupportedAudioRecordingConfiguration, SupportedAudioStreamConfiguration, + SupportedAudioStreamTiers, SupportedCameraRecordingConfiguration, SupportedCharacteristicValueTransitionConfiguration, SupportedDataStreamTransportConfiguration, @@ -212,6 +230,7 @@ import type { SupportedTransferTransportConfiguration, SupportedVideoRecordingConfiguration, SupportedVideoStreamConfiguration, + SupportedVideoStreamTiers, SwingMode, TapType, TargetAirPurifierState, @@ -255,6 +274,14 @@ import type { WANConfigurationList, WANStatusList, WaterLevel, + WebRTCNumberOfActiveSessions, + WebRTCProvideAnswer, + WebRTCReoffer, + WebRTCSolicitOffer, + WebRTCStreamingControl, + WebRTCSupportedAudioStreamTiers, + WebRTCSupportedVideoStreamTiers, + WebRTCUpdateSession, WiFiCapabilities, WiFiConfigurationControl, WiFiSatelliteStatus, @@ -843,14 +870,62 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static Brightness: typeof Brightness + /** + * @group Characteristic Definitions + */ + public static BufferActivityCommand: typeof BufferActivityCommand + /** + * @group Characteristic Definitions + */ + public static BufferEventCommand: typeof BufferEventCommand + /** + * @group Characteristic Definitions + */ + public static BufferEventSequenceNumber: typeof BufferEventSequenceNumber + /** + * @group Characteristic Definitions + */ + public static BufferUploadCommand: typeof BufferUploadCommand /** * @group Characteristic Definitions */ public static ButtonEvent: typeof ButtonEvent + /** + * @group Characteristic Definitions + */ + public static CameraCapabilitiesData: typeof CameraCapabilitiesData + /** + * @group Characteristic Definitions + */ + public static CameraClientCertificate: typeof CameraClientCertificate + /** + * @group Characteristic Definitions + */ + public static CameraClientCertificateStatus: typeof CameraClientCertificateStatus + /** + * @group Characteristic Definitions + */ + public static CameraClientCSR: typeof CameraClientCSR + /** + * @group Characteristic Definitions + */ + public static CameraKey: typeof CameraKey + /** + * @group Characteristic Definitions + */ + public static CameraKeyID: typeof CameraKeyID /** * @group Characteristic Definitions */ public static CameraOperatingModeIndicator: typeof CameraOperatingModeIndicator + /** + * @group Characteristic Definitions + */ + public static CameraRecordingPublishingPoint: typeof CameraRecordingPublishingPoint + /** + * @group Characteristic Definitions + */ + public static CameraZones: typeof CameraZones /** * @group Characteristic Definitions */ @@ -919,6 +994,10 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static ContactSensorState: typeof ContactSensorState + /** + * @group Characteristic Definitions + */ + public static ContributingSensors: typeof ContributingSensors /** * @group Characteristic Definitions */ @@ -1203,6 +1282,10 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static MotionDetected: typeof MotionDetected + /** + * @group Characteristic Definitions + */ + public static MotionEnabled: typeof MotionEnabled /** * @group Characteristic Definitions */ @@ -1398,6 +1481,10 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static RouterStatus: typeof RouterStatus + /** + * @group Characteristic Definitions + */ + public static RTPStreamingControl: typeof RTPStreamingControl /** * @group Characteristic Definitions */ @@ -1438,6 +1525,10 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static SelectedSleepConfiguration: typeof SelectedSleepConfiguration + /** + * @group Characteristic Definitions + */ + public static SensorUUID: typeof SensorUUID /** * @group Characteristic Definitions */ @@ -1546,6 +1637,10 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static StatusTampered: typeof StatusTampered + /** + * @group Characteristic Definitions + */ + public static StreamingEnabled: typeof StreamingEnabled /** * @group Characteristic Definitions */ @@ -1566,6 +1661,10 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static SupportedAudioStreamConfiguration: typeof SupportedAudioStreamConfiguration + /** + * @group Characteristic Definitions + */ + public static SupportedAudioStreamTiers: typeof SupportedAudioStreamTiers /** * @group Characteristic Definitions */ @@ -1622,6 +1721,10 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static SupportedVideoStreamConfiguration: typeof SupportedVideoStreamConfiguration + /** + * @group Characteristic Definitions + */ + public static SupportedVideoStreamTiers: typeof SupportedVideoStreamTiers /** * @group Characteristic Definitions */ @@ -1800,6 +1903,38 @@ export class Characteristic extends EventEmitter { * @group Characteristic Definitions */ public static WaterLevel: typeof WaterLevel + /** + * @group Characteristic Definitions + */ + public static WebRTCNumberOfActiveSessions: typeof WebRTCNumberOfActiveSessions + /** + * @group Characteristic Definitions + */ + public static WebRTCProvideAnswer: typeof WebRTCProvideAnswer + /** + * @group Characteristic Definitions + */ + public static WebRTCReoffer: typeof WebRTCReoffer + /** + * @group Characteristic Definitions + */ + public static WebRTCSolicitOffer: typeof WebRTCSolicitOffer + /** + * @group Characteristic Definitions + */ + public static WebRTCStreamingControl: typeof WebRTCStreamingControl + /** + * @group Characteristic Definitions + */ + public static WebRTCSupportedAudioStreamTiers: typeof WebRTCSupportedAudioStreamTiers + /** + * @group Characteristic Definitions + */ + public static WebRTCSupportedVideoStreamTiers: typeof WebRTCSupportedVideoStreamTiers + /** + * @group Characteristic Definitions + */ + public static WebRTCUpdateSession: typeof WebRTCUpdateSession /** * @group Characteristic Definitions */ diff --git a/src/lib/Service.ts b/src/lib/Service.ts index ce15f668f..892f8a37e 100644 --- a/src/lib/Service.ts +++ b/src/lib/Service.ts @@ -14,9 +14,17 @@ import type { Assistant, AudioStreamManagement, Battery, + CameraBufferManagement, + CameraCapabilities, + CameraClientCertificateManagement, + CameraGlobalOperatingMode, + CameraKeyManagement, + CameraMotionZones, + CameraMultiTierRTPStreamManagement, CameraOperatingMode, CameraRecordingManagement, CameraRTPStreamManagement, + CameraWebRTCStreamManagement, CarbonDioxideSensor, CarbonMonoxideSensor, CloudRelay, @@ -218,6 +226,34 @@ export class Service extends EventEmitter { * @group Service Definitions */ public static Battery: typeof Battery + /** + * @group Service Definitions + */ + public static CameraBufferManagement: typeof CameraBufferManagement + /** + * @group Service Definitions + */ + public static CameraCapabilities: typeof CameraCapabilities + /** + * @group Service Definitions + */ + public static CameraClientCertificateManagement: typeof CameraClientCertificateManagement + /** + * @group Service Definitions + */ + public static CameraGlobalOperatingMode: typeof CameraGlobalOperatingMode + /** + * @group Service Definitions + */ + public static CameraKeyManagement: typeof CameraKeyManagement + /** + * @group Service Definitions + */ + public static CameraMotionZones: typeof CameraMotionZones + /** + * @group Service Definitions + */ + public static CameraMultiTierRTPStreamManagement: typeof CameraMultiTierRTPStreamManagement /** * @group Service Definitions */ @@ -230,6 +266,10 @@ export class Service extends EventEmitter { * @group Service Definitions */ public static CameraRTPStreamManagement: typeof CameraRTPStreamManagement + /** + * @group Service Definitions + */ + public static CameraWebRTCStreamManagement: typeof CameraWebRTCStreamManagement /** * @group Service Definitions */ diff --git a/src/lib/definitions/CharacteristicDefinitions.spec.ts b/src/lib/definitions/CharacteristicDefinitions.spec.ts index a9d131e31..cb2fdf6cb 100644 --- a/src/lib/definitions/CharacteristicDefinitions.spec.ts +++ b/src/lib/definitions/CharacteristicDefinitions.spec.ts @@ -114,18 +114,90 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('BufferActivityCommand', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.BufferActivityCommand()).not.toThrow() + }) + }) + + describe('BufferEventCommand', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.BufferEventCommand()).not.toThrow() + }) + }) + + describe('BufferEventSequenceNumber', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.BufferEventSequenceNumber()).not.toThrow() + }) + }) + + describe('BufferUploadCommand', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.BufferUploadCommand()).not.toThrow() + }) + }) + describe('ButtonEvent', () => { it('should be able to construct', () => { expect(() => new Characteristic.ButtonEvent()).not.toThrow() }) }) + describe('CameraCapabilitiesData', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.CameraCapabilitiesData()).not.toThrow() + }) + }) + + describe('CameraClientCertificate', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.CameraClientCertificate()).not.toThrow() + }) + }) + + describe('CameraClientCertificateStatus', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.CameraClientCertificateStatus()).not.toThrow() + }) + }) + + describe('CameraClientCSR', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.CameraClientCSR()).not.toThrow() + }) + }) + + describe('CameraKey', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.CameraKey()).not.toThrow() + }) + }) + + describe('CameraKeyID', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.CameraKeyID()).not.toThrow() + }) + }) + describe('CameraOperatingModeIndicator', () => { it('should be able to construct', () => { expect(() => new Characteristic.CameraOperatingModeIndicator()).not.toThrow() }) }) + describe('CameraRecordingPublishingPoint', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.CameraRecordingPublishingPoint()).not.toThrow() + }) + }) + + describe('CameraZones', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.CameraZones()).not.toThrow() + }) + }) + describe('CarbonDioxideDetected', () => { it('should be able to construct', () => { expect(() => new Characteristic.CarbonDioxideDetected()).not.toThrow() @@ -228,6 +300,12 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('ContributingSensors', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.ContributingSensors()).not.toThrow() + }) + }) + describe('CoolingThresholdTemperature', () => { it('should be able to construct', () => { expect(() => new Characteristic.CoolingThresholdTemperature()).not.toThrow() @@ -654,6 +732,12 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('MotionEnabled', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.MotionEnabled()).not.toThrow() + }) + }) + describe('MultifunctionButton', () => { it('should be able to construct', () => { expect(() => new Characteristic.MultifunctionButton()).not.toThrow() @@ -942,6 +1026,12 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('RTPStreamingControl', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.RTPStreamingControl()).not.toThrow() + }) + }) + describe('Saturation', () => { it('should be able to construct', () => { expect(() => new Characteristic.Saturation()).not.toThrow() @@ -1002,6 +1092,12 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('SensorUUID', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.SensorUUID()).not.toThrow() + }) + }) + describe('SerialNumber', () => { it('should be able to construct', () => { expect(() => new Characteristic.SerialNumber()).not.toThrow() @@ -1164,6 +1260,12 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('StreamingEnabled', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.StreamingEnabled()).not.toThrow() + }) + }) + describe('StreamingStatus', () => { it('should be able to construct', () => { expect(() => new Characteristic.StreamingStatus()).not.toThrow() @@ -1194,6 +1296,12 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('SupportedAudioStreamTiers', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.SupportedAudioStreamTiers()).not.toThrow() + }) + }) + describe('SupportedCameraRecordingConfiguration', () => { it('should be able to construct', () => { expect(() => new Characteristic.SupportedCameraRecordingConfiguration()).not.toThrow() @@ -1278,6 +1386,12 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('SupportedVideoStreamTiers', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.SupportedVideoStreamTiers()).not.toThrow() + }) + }) + describe('SwingMode', () => { it('should be able to construct', () => { expect(() => new Characteristic.SwingMode()).not.toThrow() @@ -1536,6 +1650,54 @@ describe('CharacteristicDefinitions', () => { }) }) + describe('WebRTCNumberOfActiveSessions', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.WebRTCNumberOfActiveSessions()).not.toThrow() + }) + }) + + describe('WebRTCProvideAnswer', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.WebRTCProvideAnswer()).not.toThrow() + }) + }) + + describe('WebRTCReoffer', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.WebRTCReoffer()).not.toThrow() + }) + }) + + describe('WebRTCSolicitOffer', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.WebRTCSolicitOffer()).not.toThrow() + }) + }) + + describe('WebRTCStreamingControl', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.WebRTCStreamingControl()).not.toThrow() + }) + }) + + describe('WebRTCSupportedAudioStreamTiers', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.WebRTCSupportedAudioStreamTiers()).not.toThrow() + }) + }) + + describe('WebRTCSupportedVideoStreamTiers', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.WebRTCSupportedVideoStreamTiers()).not.toThrow() + }) + }) + + describe('WebRTCUpdateSession', () => { + it('should be able to construct', () => { + expect(() => new Characteristic.WebRTCUpdateSession()).not.toThrow() + }) + }) + describe('WiFiCapabilities', () => { it('should be able to construct', () => { expect(() => new Characteristic.WiFiCapabilities()).not.toThrow() diff --git a/src/lib/definitions/CharacteristicDefinitions.ts b/src/lib/definitions/CharacteristicDefinitions.ts index 28d35391c..4b23739ba 100644 --- a/src/lib/definitions/CharacteristicDefinitions.ts +++ b/src/lib/definitions/CharacteristicDefinitions.ts @@ -338,6 +338,72 @@ export class Brightness extends Characteristic { } Characteristic.Brightness = Brightness +/** + * Characteristic "Buffer Activity Command" + */ +export class BufferActivityCommand extends Characteristic { + public static readonly UUID: string = '00008017-0000-1000-8000-0026BB765291' + + constructor() { + super('Buffer Activity Command', BufferActivityCommand.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_WRITE], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.BufferActivityCommand = BufferActivityCommand + +/** + * Characteristic "Buffer Event Command" + */ +export class BufferEventCommand extends Characteristic { + public static readonly UUID: string = '00008014-0000-1000-8000-0026BB765291' + + constructor() { + super('Buffer Event Command', BufferEventCommand.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.BufferEventCommand = BufferEventCommand + +/** + * Characteristic "Buffer Event Sequence Number" + */ +export class BufferEventSequenceNumber extends Characteristic { + public static readonly UUID: string = '00008015-0000-1000-8000-0026BB765291' + + constructor() { + super('Buffer Event Sequence Number', BufferEventSequenceNumber.UUID, { + format: Formats.UINT32, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.BufferEventSequenceNumber = BufferEventSequenceNumber + +/** + * Characteristic "Buffer Upload Command" + */ +export class BufferUploadCommand extends Characteristic { + public static readonly UUID: string = '00008013-0000-1000-8000-0026BB765291' + + constructor() { + super('Buffer Upload Command', BufferUploadCommand.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.BufferUploadCommand = BufferUploadCommand + /** * Characteristic "Button Event" */ @@ -355,6 +421,107 @@ export class ButtonEvent extends Characteristic { } Characteristic.ButtonEvent = ButtonEvent +/** + * Characteristic "Camera Capabilities" + */ +export class CameraCapabilitiesData extends Characteristic { + public static readonly UUID: string = '00008011-0000-1000-8000-0026BB765291' + + constructor() { + super('Camera Capabilities', CameraCapabilitiesData.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.CameraCapabilitiesData = CameraCapabilitiesData + +/** + * Characteristic "Camera Client Certificate" + */ +export class CameraClientCertificate extends Characteristic { + public static readonly UUID: string = '00008082-0000-1000-8000-0026BB765291' + + constructor() { + super('Camera Client Certificate', CameraClientCertificate.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.TIMED_WRITE], + transient: true, + sensitive: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.CameraClientCertificate = CameraClientCertificate + +/** + * Characteristic "Camera Client Certificate Status" + */ +export class CameraClientCertificateStatus extends Characteristic { + public static readonly UUID: string = '00008083-0000-1000-8000-0026BB765291' + + constructor() { + super('Camera Client Certificate Status', CameraClientCertificateStatus.UUID, { + format: Formats.TLV8, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.CameraClientCertificateStatus = CameraClientCertificateStatus + +/** + * Characteristic "Camera Client CSR" + */ +export class CameraClientCSR extends Characteristic { + public static readonly UUID: string = '00008081-0000-1000-8000-0026BB765291' + + constructor() { + super('Camera Client CSR', CameraClientCSR.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.CameraClientCSR = CameraClientCSR + +/** + * Characteristic "Camera Key" + */ +export class CameraKey extends Characteristic { + public static readonly UUID: string = '00008051-0000-1000-8000-0026BB765291' + + constructor() { + super('Camera Key', CameraKey.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_WRITE, Perms.TIMED_WRITE], + transient: true, + sensitive: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.CameraKey = CameraKey + +/** + * Characteristic "Camera Key ID" + */ +export class CameraKeyID extends Characteristic { + public static readonly UUID: string = '00008052-0000-1000-8000-0026BB765291' + + constructor() { + super('Camera Key ID', CameraKeyID.UUID, { + format: Formats.TLV8, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.CameraKeyID = CameraKeyID + /** * Characteristic "Camera Operating Mode Indicator" */ @@ -383,6 +550,38 @@ export class CameraOperatingModeIndicator extends Characteristic { } Characteristic.CameraOperatingModeIndicator = CameraOperatingModeIndicator +/** + * Characteristic "Camera Recording Publishing Point" + */ +export class CameraRecordingPublishingPoint extends Characteristic { + public static readonly UUID: string = '00008016-0000-1000-8000-0026BB765291' + + constructor() { + super('Camera Recording Publishing Point', CameraRecordingPublishingPoint.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.CameraRecordingPublishingPoint = CameraRecordingPublishingPoint + +/** + * Characteristic "Camera Zones" + */ +export class CameraZones extends Characteristic { + public static readonly UUID: string = '00008022-0000-1000-8000-0026BB765291' + + constructor() { + super('Camera Zones', CameraZones.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.CameraZones = CameraZones + /** * Characteristic "Carbon Dioxide Detected" */ @@ -711,6 +910,22 @@ export class ContactSensorState extends Characteristic { } Characteristic.ContactSensorState = ContactSensorState +/** + * Characteristic "Contributing Sensors" + */ +export class ContributingSensors extends Characteristic { + public static readonly UUID: string = '00008086-0000-1000-8000-0026BB765291' + + constructor() { + super('Contributing Sensors', ContributingSensors.UUID, { + format: Formats.TLV8, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.ContributingSensors = ContributingSensors + /** * Characteristic "Cooling Threshold Temperature" */ @@ -2121,6 +2336,28 @@ export class MotionDetected extends Characteristic { } Characteristic.MotionDetected = MotionDetected +/** + * Characteristic "Motion Enabled" + */ +export class MotionEnabled extends Characteristic { + public static readonly UUID: string = '00008087-0000-1000-8000-0026BB765291' + + constructor() { + super('Motion Enabled', MotionEnabled.UUID, { + format: Formats.BOOL, + perms: [ + Perms.NOTIFY, + Perms.PAIRED_READ, + Perms.PAIRED_WRITE, + Perms.TIMED_WRITE, + ], + adminOnlyAccess: [Access.WRITE], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.MotionEnabled = MotionEnabled + /** * Characteristic "Multifunction Button" */ @@ -3087,6 +3324,23 @@ export class RouterStatus extends Characteristic { } Characteristic.RouterStatus = RouterStatus +/** + * Characteristic "RTP Streaming Control" + */ +export class RTPStreamingControl extends Characteristic { + public static readonly UUID: string = '00008045-0000-1000-8000-0026BB765291' + + constructor() { + super('RTP Streaming Control', RTPStreamingControl.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.RTPStreamingControl = RTPStreamingControl + /** * Characteristic "Saturation" */ @@ -3282,6 +3536,22 @@ export class SelectedSleepConfiguration extends Characteristic { } Characteristic.SelectedSleepConfiguration = SelectedSleepConfiguration +/** + * Characteristic "Sensor UUID" + */ +export class SensorUUID extends Characteristic { + public static readonly UUID: string = '0000805B-0000-1000-8000-0026BB765291' + + constructor() { + super('Sensor UUID', SensorUUID.UUID, { + format: Formats.DATA, + perms: [Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.SensorUUID = SensorUUID + /** * Characteristic "Serial Number" */ @@ -3403,6 +3673,8 @@ export class SetupEndpoints extends Characteristic { super('Setup Endpoints', SetupEndpoints.UUID, { format: Formats.TLV8, perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE], + transient: true, + sensitive: true, }) this.value = this.getDefaultValue() } @@ -3796,6 +4068,28 @@ export class StatusTampered extends Characteristic { } Characteristic.StatusTampered = StatusTampered +/** + * Characteristic "Streaming Enabled" + */ +export class StreamingEnabled extends Characteristic { + public static readonly UUID: string = '00008041-0000-1000-8000-0026BB765291' + + constructor() { + super('Streaming Enabled', StreamingEnabled.UUID, { + format: Formats.BOOL, + perms: [ + Perms.NOTIFY, + Perms.PAIRED_READ, + Perms.PAIRED_WRITE, + Perms.TIMED_WRITE, + ], + adminOnlyAccess: [Access.WRITE], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.StreamingEnabled = StreamingEnabled + /** * Characteristic "Streaming Status" */ @@ -3879,6 +4173,22 @@ export class SupportedAudioStreamConfiguration extends Characteristic { } Characteristic.SupportedAudioStreamConfiguration = SupportedAudioStreamConfiguration +/** + * Characteristic "Supported Audio Stream Tiers" + */ +export class SupportedAudioStreamTiers extends Characteristic { + public static readonly UUID: string = '00008044-0000-1000-8000-0026BB765291' + + constructor() { + super('Supported Audio Stream Tiers', SupportedAudioStreamTiers.UUID, { + format: Formats.TLV8, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.SupportedAudioStreamTiers = SupportedAudioStreamTiers + /** * Characteristic "Supported Camera Recording Configuration" */ @@ -4106,6 +4416,22 @@ export class SupportedVideoStreamConfiguration extends Characteristic { } Characteristic.SupportedVideoStreamConfiguration = SupportedVideoStreamConfiguration +/** + * Characteristic "Supported Video Stream Tiers" + */ +export class SupportedVideoStreamTiers extends Characteristic { + public static readonly UUID: string = '00008043-0000-1000-8000-0026BB765291' + + constructor() { + super('Supported Video Stream Tiers', SupportedVideoStreamTiers.UUID, { + format: Formats.TLV8, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.SupportedVideoStreamTiers = SupportedVideoStreamTiers + /** * Characteristic "Swing Mode" */ @@ -4965,6 +5291,144 @@ export class WaterLevel extends Characteristic { } Characteristic.WaterLevel = WaterLevel +/** + * Characteristic "WebRTC Number Of Active Sessions" + */ +export class WebRTCNumberOfActiveSessions extends Characteristic { + public static readonly UUID: string = '00008057-0000-1000-8000-0026BB765291' + + constructor() { + super('WebRTC Number Of Active Sessions', WebRTCNumberOfActiveSessions.UUID, { + format: Formats.UINT8, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + minValue: 0, + maxValue: 255, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.WebRTCNumberOfActiveSessions = WebRTCNumberOfActiveSessions + +/** + * Characteristic "WebRTC Provide Answer" + */ +export class WebRTCProvideAnswer extends Characteristic { + public static readonly UUID: string = '00008054-0000-1000-8000-0026BB765291' + + constructor() { + super('WebRTC Provide Answer', WebRTCProvideAnswer.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.WebRTCProvideAnswer = WebRTCProvideAnswer + +/** + * Characteristic "WebRTC Reoffer" + */ +export class WebRTCReoffer extends Characteristic { + public static readonly UUID: string = '00008058-0000-1000-8000-0026BB765291' + + constructor() { + super('WebRTC Reoffer', WebRTCReoffer.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + sensitive: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.WebRTCReoffer = WebRTCReoffer + +/** + * Characteristic "WebRTC Solicit Offer" + */ +export class WebRTCSolicitOffer extends Characteristic { + public static readonly UUID: string = '00008053-0000-1000-8000-0026BB765291' + + constructor() { + super('WebRTC Solicit Offer', WebRTCSolicitOffer.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + sensitive: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.WebRTCSolicitOffer = WebRTCSolicitOffer + +/** + * Characteristic "WebRTC Streaming Control" + */ +export class WebRTCStreamingControl extends Characteristic { + public static readonly UUID: string = '00008056-0000-1000-8000-0026BB765291' + + constructor() { + super('WebRTC Streaming Control', WebRTCStreamingControl.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.WebRTCStreamingControl = WebRTCStreamingControl + +/** + * Characteristic "WebRTC Supported Audio Stream Tiers" + */ +export class WebRTCSupportedAudioStreamTiers extends Characteristic { + public static readonly UUID: string = '0000805A-0000-1000-8000-0026BB765291' + + constructor() { + super('WebRTC Supported Audio Stream Tiers', WebRTCSupportedAudioStreamTiers.UUID, { + format: Formats.TLV8, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.WebRTCSupportedAudioStreamTiers = WebRTCSupportedAudioStreamTiers + +/** + * Characteristic "WebRTC Supported Video Stream Tiers" + */ +export class WebRTCSupportedVideoStreamTiers extends Characteristic { + public static readonly UUID: string = '00008059-0000-1000-8000-0026BB765291' + + constructor() { + super('WebRTC Supported Video Stream Tiers', WebRTCSupportedVideoStreamTiers.UUID, { + format: Formats.TLV8, + perms: [Perms.NOTIFY, Perms.PAIRED_READ], + }) + this.value = this.getDefaultValue() + } +} +Characteristic.WebRTCSupportedVideoStreamTiers = WebRTCSupportedVideoStreamTiers + +/** + * Characteristic "WebRTC Update Session" + */ +export class WebRTCUpdateSession extends Characteristic { + public static readonly UUID: string = '0000805C-0000-1000-8000-0026BB765291' + + constructor() { + super('WebRTC Update Session', WebRTCUpdateSession.UUID, { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + sensitive: true, + }) + this.value = this.getDefaultValue() + } +} +Characteristic.WebRTCUpdateSession = WebRTCUpdateSession + /** * Characteristic "Wi-Fi Capabilities" * @since iOS 14 diff --git a/src/lib/definitions/DefinitionsConformance.spec.ts b/src/lib/definitions/DefinitionsConformance.spec.ts new file mode 100644 index 000000000..18ca4ce38 --- /dev/null +++ b/src/lib/definitions/DefinitionsConformance.spec.ts @@ -0,0 +1,535 @@ +import type { WithUUID } from '../../types.js' + +import { describe, expect, it } from 'vitest' + +import { Access, Characteristic, Formats, Perms } from '../Characteristic.js' +import { Service } from '../Service.js' +import * as definitions from './index.js' + +/* + * The camera definitions held to Apple's HomeKit Secure Video open source compatibility guide. Each characteristic and service row is transcribed from the + * specification's tables except the Camera Recording Management row, which keeps the characteristics the corpus is committed with, and the R17 + * characteristics the services reuse are held to the UUIDs the corpus already defines them with. Nothing is read from the generator or its configuration: + * a regeneration that drifts from the specification or from the committed corpus fails here. + */ + +interface CharacteristicRow { + displayName: string + type: WithUUID Characteristic> + UUID: string + format: Formats + perms: Perms[] + adminOnlyAccess?: Access[] + transient?: boolean + sensitive?: boolean + minValue?: number + maxValue?: number +} + +interface ServiceRow { + name: string + type: WithUUID Service> + UUID: string + required: string[] + optional: string[] +} + +// Section 3: each characteristic the specification defines, its display name the title with every word capitalized. +const CAMERA_CHARACTERISTICS: CharacteristicRow[] = [ + { + displayName: 'Sensor UUID', + type: Characteristic.SensorUUID, + UUID: '0000805B-0000-1000-8000-0026BB765291', + format: Formats.DATA, + perms: [Perms.PAIRED_READ], + }, + { + displayName: 'Motion Enabled', + type: Characteristic.MotionEnabled, + UUID: '00008087-0000-1000-8000-0026BB765291', + format: Formats.BOOL, + perms: [ + Perms.PAIRED_READ, + Perms.PAIRED_WRITE, + Perms.NOTIFY, + Perms.TIMED_WRITE, + ], + adminOnlyAccess: [Access.WRITE], + }, + { + displayName: 'Supported Video Stream Tiers', + type: Characteristic.SupportedVideoStreamTiers, + UUID: '00008043-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, + { + displayName: 'Supported Audio Stream Tiers', + type: Characteristic.SupportedAudioStreamTiers, + UUID: '00008044-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, + { + displayName: 'Camera Capabilities', + type: Characteristic.CameraCapabilitiesData, + UUID: '00008011-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ], + }, + { + displayName: 'Contributing Sensors', + type: Characteristic.ContributingSensors, + UUID: '00008086-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, + { + displayName: 'Camera Key', + type: Characteristic.CameraKey, + UUID: '00008051-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_WRITE, Perms.TIMED_WRITE], + transient: true, + sensitive: true, + }, + { + displayName: 'Camera Key ID', + type: Characteristic.CameraKeyID, + UUID: '00008052-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, + { + displayName: 'Buffer Upload Command', + type: Characteristic.BufferUploadCommand, + UUID: '00008013-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }, + { + displayName: 'Buffer Activity Command', + type: Characteristic.BufferActivityCommand, + UUID: '00008017-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_WRITE], + }, + { + displayName: 'Buffer Event Command', + type: Characteristic.BufferEventCommand, + UUID: '00008014-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }, + { + displayName: 'Buffer Event Sequence Number', + type: Characteristic.BufferEventSequenceNumber, + UUID: '00008015-0000-1000-8000-0026BB765291', + format: Formats.UINT32, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, + { + displayName: 'Camera Recording Publishing Point', + type: Characteristic.CameraRecordingPublishingPoint, + UUID: '00008016-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE], + }, + { + displayName: 'Camera Zones', + type: Characteristic.CameraZones, + UUID: '00008022-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE], + }, + { + displayName: 'Streaming Enabled', + type: Characteristic.StreamingEnabled, + UUID: '00008041-0000-1000-8000-0026BB765291', + format: Formats.BOOL, + perms: [ + Perms.PAIRED_READ, + Perms.PAIRED_WRITE, + Perms.NOTIFY, + Perms.TIMED_WRITE, + ], + adminOnlyAccess: [Access.WRITE], + }, + { + displayName: 'RTP Streaming Control', + type: Characteristic.RTPStreamingControl, + UUID: '00008045-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }, + { + displayName: 'WebRTC Solicit Offer', + type: Characteristic.WebRTCSolicitOffer, + UUID: '00008053-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + sensitive: true, + }, + { + displayName: 'WebRTC Provide Answer', + type: Characteristic.WebRTCProvideAnswer, + UUID: '00008054-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }, + { + displayName: 'WebRTC Streaming Control', + type: Characteristic.WebRTCStreamingControl, + UUID: '00008056-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }, + { + displayName: 'WebRTC Number Of Active Sessions', + type: Characteristic.WebRTCNumberOfActiveSessions, + UUID: '00008057-0000-1000-8000-0026BB765291', + format: Formats.UINT8, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + minValue: 0, + maxValue: 255, + }, + { + displayName: 'WebRTC Reoffer', + type: Characteristic.WebRTCReoffer, + UUID: '00008058-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + sensitive: true, + }, + { + displayName: 'WebRTC Update Session', + type: Characteristic.WebRTCUpdateSession, + UUID: '0000805C-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_WRITE, Perms.PAIRED_READ, Perms.WRITE_RESPONSE], + transient: true, + sensitive: true, + }, + { + displayName: 'WebRTC Supported Video Stream Tiers', + type: Characteristic.WebRTCSupportedVideoStreamTiers, + UUID: '00008059-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, + { + displayName: 'WebRTC Supported Audio Stream Tiers', + type: Characteristic.WebRTCSupportedAudioStreamTiers, + UUID: '0000805A-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, + { + displayName: 'Camera Client CSR', + type: Characteristic.CameraClientCSR, + UUID: '00008081-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }, + { + displayName: 'Camera Client Certificate', + type: Characteristic.CameraClientCertificate, + UUID: '00008082-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.TIMED_WRITE], + transient: true, + sensitive: true, + }, + { + displayName: 'Camera Client Certificate Status', + type: Characteristic.CameraClientCertificateStatus, + UUID: '00008083-0000-1000-8000-0026BB765291', + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, +] + +// Section 5: the R17 characteristics the services reuse, by the UUIDs the corpus already defines them with, beside the ones the committed Motion +// Sensor and Camera Recording Management services list. +const EXISTING_CHARACTERISTIC_UUIDS: Record = { + 'Active': '000000B0-0000-1000-8000-0026BB765291', + 'Camera Operating Mode Indicator': '0000021D-0000-1000-8000-0026BB765291', + 'HomeKit Camera Active': '0000021B-0000-1000-8000-0026BB765291', + 'Manually Disabled': '00000227-0000-1000-8000-0026BB765291', + 'Motion Detected': '00000022-0000-1000-8000-0026BB765291', + 'Name': '00000023-0000-1000-8000-0026BB765291', + 'Night Vision': '0000011B-0000-1000-8000-0026BB765291', + 'Recording Audio Active': '00000226-0000-1000-8000-0026BB765291', + 'Selected Camera Recording Configuration': '00000209-0000-1000-8000-0026BB765291', + 'Setup Endpoints': '00000118-0000-1000-8000-0026BB765291', + 'Status Active': '00000075-0000-1000-8000-0026BB765291', + 'Status Fault': '00000077-0000-1000-8000-0026BB765291', + 'Status Low Battery': '00000079-0000-1000-8000-0026BB765291', + 'Status Tampered': '0000007A-0000-1000-8000-0026BB765291', + 'Supported Audio Recording Configuration': '00000207-0000-1000-8000-0026BB765291', + 'Supported Camera Recording Configuration': '00000205-0000-1000-8000-0026BB765291', + 'Supported RTP Configuration': '00000116-0000-1000-8000-0026BB765291', + 'Supported Video Recording Configuration': '00000206-0000-1000-8000-0026BB765291', + 'Third Party Camera Active': '0000021C-0000-1000-8000-0026BB765291', + 'Version': '00000037-0000-1000-8000-0026BB765291', +} + +const CHARACTERISTIC_UUIDS: Record = { + ...EXISTING_CHARACTERISTIC_UUIDS, + ...Object.fromEntries(CAMERA_CHARACTERISTICS.map(row => [row.displayName, row.UUID])), +} + +// Section 2: each service the specification defines, and the Motion Sensor it extends, its characteristics listed by their titles. +const CAMERA_SERVICES: ServiceRow[] = [ + { + name: 'Camera Capabilities', + type: Service.CameraCapabilities, + UUID: '00008010-0000-1000-8000-0026BB765291', + required: ['Version', 'Camera Capabilities'], + optional: ['Manually Disabled'], + }, + { + name: 'Camera Global Operating Mode', + type: Service.CameraGlobalOperatingMode, + UUID: '00008032-0000-1000-8000-0026BB765291', + required: ['HomeKit Camera Active', 'Streaming Enabled', 'Camera Operating Mode Indicator'], + optional: ['Manually Disabled', 'Night Vision', 'Third Party Camera Active'], + }, + { + name: 'Motion Sensor', + type: Service.MotionSensor, + UUID: '00000085-0000-1000-8000-0026BB765291', + required: ['Motion Detected'], + optional: [ + 'Name', + 'Status Active', + 'Status Fault', + 'Status Tampered', + 'Status Low Battery', + 'Contributing Sensors', + 'Motion Enabled', + ], + }, + { + name: 'Camera Motion Zones', + type: Service.CameraMotionZones, + UUID: '00008021-0000-1000-8000-0026BB765291', + required: ['Version', 'Active', 'Camera Zones'], + optional: [], + }, + { + name: 'Camera Buffer Management', + type: Service.CameraBufferManagement, + UUID: '00008000-0000-1000-8000-0026BB765291', + required: [ + 'Buffer Upload Command', + 'Buffer Activity Command', + 'Buffer Event Command', + 'Buffer Event Sequence Number', + 'Camera Recording Publishing Point', + ], + optional: [], + }, + { + name: 'Camera Multi-Tier RTP Stream Management', + type: Service.CameraMultiTierRTPStreamManagement, + UUID: '00008031-0000-1000-8000-0026BB765291', + required: [ + 'Streaming Enabled', + 'Status Active', + 'Supported Video Stream Tiers', + 'Supported Audio Stream Tiers', + 'Supported RTP Configuration', + 'Setup Endpoints', + 'RTP Streaming Control', + 'Sensor UUID', + ], + optional: [], + }, + { + name: 'Camera WebRTC Stream Management', + type: Service.CameraWebRTCStreamManagement, + UUID: '00008033-0000-1000-8000-0026BB765291', + required: [ + 'WebRTC Solicit Offer', + 'WebRTC Provide Answer', + 'WebRTC Streaming Control', + 'WebRTC Number Of Active Sessions', + 'WebRTC Reoffer', + 'WebRTC Update Session', + 'WebRTC Supported Video Stream Tiers', + 'WebRTC Supported Audio Stream Tiers', + 'Streaming Enabled', + 'Sensor UUID', + ], + optional: [], + }, + // Section 2.8 makes Recording Audio Active required; the service keeps the characteristics it is committed with, Recording Audio Active optional. + { + name: 'Camera Recording Management', + type: Service.CameraRecordingManagement, + UUID: '00000204-0000-1000-8000-0026BB765291', + required: ['Active'], + optional: [ + 'Recording Audio Active', + 'Selected Camera Recording Configuration', + 'Supported Audio Recording Configuration', + 'Supported Camera Recording Configuration', + 'Supported Video Recording Configuration', + ], + }, + { + name: 'Camera Key Management', + type: Service.CameraKeyManagement, + UUID: '00008050-0000-1000-8000-0026BB765291', + required: ['Camera Key', 'Camera Key ID'], + optional: [], + }, + { + name: 'Camera Client Certificate Management', + type: Service.CameraClientCertificateManagement, + UUID: '00008080-0000-1000-8000-0026BB765291', + required: ['Camera Client CSR', 'Camera Client Certificate', 'Camera Client Certificate Status'], + optional: [], + }, +] + +// Every class-valued static a namespace carries under its own class name, as class name to UUID; a deprecated alias carries another class's name. +function definitionsOf(namespace: object, base: abstract new (...args: never[]) => unknown): Map { + const definitions = new Map() + for (const [key, value] of Object.entries(namespace)) { + if (typeof value === 'function' && value.name === key && value.prototype instanceof base) { + definitions.set(key, value.UUID) + } + } + return definitions +} + +// The class names that share a UUID, one sorted group per shared UUID. +function sharedUUIDs(definitions: Map): string[][] { + const namesByUUID = new Map() + for (const [name, uuid] of definitions) { + const names = namesByUUID.get(uuid) ?? [] + names.push(name) + namesByUUID.set(uuid, names) + } + return Array.from(namesByUUID.values()).filter(names => names.length > 1).map(names => names.sort()) +} + +describe('definitionsConformance', () => { + describe('camera characteristics', () => { + it.each(CAMERA_CHARACTERISTICS)('$displayName', (row) => { + const characteristic = new row.type() + + expect(row.type.UUID).toBe(row.UUID) + expect(characteristic.displayName).toBe(row.displayName) + expect(characteristic.props.format).toBe(row.format) + expect(new Set(characteristic.props.perms)).toEqual(new Set(row.perms)) + expect(characteristic.props.adminOnlyAccess).toEqual(row.adminOnlyAccess) + expect(characteristic.props.transient).toBe(row.transient) + expect(characteristic.props.sensitive).toBe(row.sensitive) + expect(characteristic.props.minValue).toBe(row.minValue) + expect(characteristic.props.maxValue).toBe(row.maxValue) + }) + }) + + describe('characteristic flags', () => { + // The class name of each characteristic the definitions export whose definition carries the flag. The set is read across the whole corpus. + function flagged(flag: 'sensitive' | 'transient'): string[] { + return Object.entries(definitions) + .filter(([, value]) => value.prototype instanceof Characteristic && new (value as new () => Characteristic)().props[flag]) + .map(([name]) => name) + .sort() + } + + it('marks exactly the write response control points, Setup Endpoints, Camera Key and Camera Client Certificate transient', () => { + expect(flagged('transient')).toEqual([ + 'BufferEventCommand', + 'BufferUploadCommand', + 'CameraClientCSR', + 'CameraClientCertificate', + 'CameraKey', + 'RTPStreamingControl', + 'SetupEndpoints', + 'WebRTCProvideAnswer', + 'WebRTCReoffer', + 'WebRTCSolicitOffer', + 'WebRTCStreamingControl', + 'WebRTCUpdateSession', + ]) + }) + + it('marks exactly the characteristics whose values carry keys or credentials sensitive', () => { + expect(flagged('sensitive')).toEqual([ + 'CameraClientCertificate', + 'CameraKey', + 'SetupEndpoints', + 'WebRTCReoffer', + 'WebRTCSolicitOffer', + 'WebRTCUpdateSession', + ]) + }) + }) + + describe('camera services', () => { + it.each(CAMERA_SERVICES)('$name', (row) => { + const service = new row.type() + + expect(row.type.UUID).toBe(row.UUID) + expect(new Set(service.characteristics.map(characteristic => characteristic.UUID))) + .toEqual(new Set(row.required.map(title => CHARACTERISTIC_UUIDS[title]))) + expect(new Set(service.optionalCharacteristics.map(characteristic => characteristic.UUID))) + .toEqual(new Set(row.optional.map(title => CHARACTERISTIC_UUIDS[title]))) + }) + }) + + describe('class namespaces', () => { + it('gives the Camera Capabilities service and characteristic their own class names', () => { + expect(Service.CameraCapabilities.UUID).toBe('00008010-0000-1000-8000-0026BB765291') + expect(Characteristic.CameraCapabilitiesData.UUID).toBe('00008011-0000-1000-8000-0026BB765291') + expect(new Characteristic.CameraCapabilitiesData().displayName).toBe('Camera Capabilities') + }) + + it('defines no characteristic UUID twice', () => { + const characteristics = definitionsOf(Characteristic, Characteristic) + + expect(characteristics.get('CameraCapabilitiesData')).toBe('00008011-0000-1000-8000-0026BB765291') + expect(sharedUUIDs(characteristics)).toEqual([]) + }) + + it('shares a service UUID only between Speaker and TelevisionSpeaker', () => { + expect(sharedUUIDs(definitionsOf(Service, Service))).toEqual([ + ['Speaker', 'TelevisionSpeaker'], + ]) + }) + + it('uses no class name in both namespaces', () => { + const services = definitionsOf(Service, Service) + const characteristics = definitionsOf(Characteristic, Characteristic) + + expect(services.get('CameraCapabilities')).toBe('00008010-0000-1000-8000-0026BB765291') + expect(Array.from(characteristics.keys()).filter(name => services.has(name))).toEqual([]) + }) + + it('walks every class the definitions export, and declares no static without one', () => { + const exported = (base: abstract new (...args: never[]) => unknown): string[] => Object.entries(definitions) + .filter(([, value]) => value.prototype instanceof base) + .map(([name]) => name) + .sort() + + expect(Array.from(definitionsOf(Characteristic, Characteristic).keys()).sort()).toEqual(exported(Characteristic)) + expect(Array.from(definitionsOf(Service, Service).keys()).sort()).toEqual(exported(Service)) + // A declared static compiles to a class field holding undefined until its definition assigns it, which means an undefined entry is a static with no class. + expect(Object.entries(Characteristic).filter(([, value]) => value === undefined).map(([name]) => name)).toEqual([]) + expect(Object.entries(Service).filter(([, value]) => value === undefined).map(([name]) => name)).toEqual([]) + }) + }) +}) diff --git a/src/lib/definitions/ServiceDefinitions.spec.ts b/src/lib/definitions/ServiceDefinitions.spec.ts index 7261403fb..9380fe4c7 100644 --- a/src/lib/definitions/ServiceDefinitions.spec.ts +++ b/src/lib/definitions/ServiceDefinitions.spec.ts @@ -249,6 +249,160 @@ describe('ServiceDefinitions', () => { }) }) + describe('CameraBufferManagement', () => { + it('should be able to construct', () => { + const service0 = new Service.CameraBufferManagement() + const service1 = new Service.CameraBufferManagement('test name') + const service2 = new Service.CameraBufferManagement('test name', 'test sub type') + + expect(service0.displayName).toBe('') + expect(service0.testCharacteristic(Characteristic.Name)).toBe(false) + expect(service0.subtype).toBeUndefined() + + expect(service1.displayName).toBe('test name') + expect(service1.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service1.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service1.subtype).toBeUndefined() + + expect(service2.displayName).toBe('test name') + expect(service2.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service2.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service2.subtype).toBe('test sub type') + }) + }) + + describe('CameraCapabilities', () => { + it('should be able to construct', () => { + const service0 = new Service.CameraCapabilities() + const service1 = new Service.CameraCapabilities('test name') + const service2 = new Service.CameraCapabilities('test name', 'test sub type') + + expect(service0.displayName).toBe('') + expect(service0.testCharacteristic(Characteristic.Name)).toBe(false) + expect(service0.subtype).toBeUndefined() + + expect(service1.displayName).toBe('test name') + expect(service1.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service1.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service1.subtype).toBeUndefined() + + expect(service2.displayName).toBe('test name') + expect(service2.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service2.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service2.subtype).toBe('test sub type') + }) + }) + + describe('CameraClientCertificateManagement', () => { + it('should be able to construct', () => { + const service0 = new Service.CameraClientCertificateManagement() + const service1 = new Service.CameraClientCertificateManagement('test name') + const service2 = new Service.CameraClientCertificateManagement('test name', 'test sub type') + + expect(service0.displayName).toBe('') + expect(service0.testCharacteristic(Characteristic.Name)).toBe(false) + expect(service0.subtype).toBeUndefined() + + expect(service1.displayName).toBe('test name') + expect(service1.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service1.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service1.subtype).toBeUndefined() + + expect(service2.displayName).toBe('test name') + expect(service2.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service2.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service2.subtype).toBe('test sub type') + }) + }) + + describe('CameraGlobalOperatingMode', () => { + it('should be able to construct', () => { + const service0 = new Service.CameraGlobalOperatingMode() + const service1 = new Service.CameraGlobalOperatingMode('test name') + const service2 = new Service.CameraGlobalOperatingMode('test name', 'test sub type') + + expect(service0.displayName).toBe('') + expect(service0.testCharacteristic(Characteristic.Name)).toBe(false) + expect(service0.subtype).toBeUndefined() + + expect(service1.displayName).toBe('test name') + expect(service1.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service1.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service1.subtype).toBeUndefined() + + expect(service2.displayName).toBe('test name') + expect(service2.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service2.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service2.subtype).toBe('test sub type') + }) + }) + + describe('CameraKeyManagement', () => { + it('should be able to construct', () => { + const service0 = new Service.CameraKeyManagement() + const service1 = new Service.CameraKeyManagement('test name') + const service2 = new Service.CameraKeyManagement('test name', 'test sub type') + + expect(service0.displayName).toBe('') + expect(service0.testCharacteristic(Characteristic.Name)).toBe(false) + expect(service0.subtype).toBeUndefined() + + expect(service1.displayName).toBe('test name') + expect(service1.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service1.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service1.subtype).toBeUndefined() + + expect(service2.displayName).toBe('test name') + expect(service2.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service2.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service2.subtype).toBe('test sub type') + }) + }) + + describe('CameraMotionZones', () => { + it('should be able to construct', () => { + const service0 = new Service.CameraMotionZones() + const service1 = new Service.CameraMotionZones('test name') + const service2 = new Service.CameraMotionZones('test name', 'test sub type') + + expect(service0.displayName).toBe('') + expect(service0.testCharacteristic(Characteristic.Name)).toBe(false) + expect(service0.subtype).toBeUndefined() + + expect(service1.displayName).toBe('test name') + expect(service1.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service1.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service1.subtype).toBeUndefined() + + expect(service2.displayName).toBe('test name') + expect(service2.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service2.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service2.subtype).toBe('test sub type') + }) + }) + + describe('CameraMultiTierRTPStreamManagement', () => { + it('should be able to construct', () => { + const service0 = new Service.CameraMultiTierRTPStreamManagement() + const service1 = new Service.CameraMultiTierRTPStreamManagement('test name') + const service2 = new Service.CameraMultiTierRTPStreamManagement('test name', 'test sub type') + + expect(service0.displayName).toBe('') + expect(service0.testCharacteristic(Characteristic.Name)).toBe(false) + expect(service0.subtype).toBeUndefined() + + expect(service1.displayName).toBe('test name') + expect(service1.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service1.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service1.subtype).toBeUndefined() + + expect(service2.displayName).toBe('test name') + expect(service2.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service2.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service2.subtype).toBe('test sub type') + }) + }) + describe('CameraOperatingMode', () => { it('should be able to construct', () => { const service0 = new Service.CameraOperatingMode() @@ -315,6 +469,28 @@ describe('ServiceDefinitions', () => { }) }) + describe('CameraWebRTCStreamManagement', () => { + it('should be able to construct', () => { + const service0 = new Service.CameraWebRTCStreamManagement() + const service1 = new Service.CameraWebRTCStreamManagement('test name') + const service2 = new Service.CameraWebRTCStreamManagement('test name', 'test sub type') + + expect(service0.displayName).toBe('') + expect(service0.testCharacteristic(Characteristic.Name)).toBe(false) + expect(service0.subtype).toBeUndefined() + + expect(service1.displayName).toBe('test name') + expect(service1.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service1.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service1.subtype).toBeUndefined() + + expect(service2.displayName).toBe('test name') + expect(service2.testCharacteristic(Characteristic.Name)).toBe(true) + expect(service2.getCharacteristic(Characteristic.Name).value).toBe('test name') + expect(service2.subtype).toBe('test sub type') + }) + }) + describe('CarbonDioxideSensor', () => { it('should be able to construct', () => { const service0 = new Service.CarbonDioxideSensor() diff --git a/src/lib/definitions/ServiceDefinitions.ts b/src/lib/definitions/ServiceDefinitions.ts index de84678b2..58198cf44 100644 --- a/src/lib/definitions/ServiceDefinitions.ts +++ b/src/lib/definitions/ServiceDefinitions.ts @@ -237,6 +237,138 @@ export class Battery extends Service { } Service.Battery = Battery +/** + * Service "Camera Buffer Management" + */ +export class CameraBufferManagement extends Service { + public static readonly UUID: string = '00008000-0000-1000-8000-0026BB765291' + + constructor(displayName?: string, subtype?: string) { + super(displayName, CameraBufferManagement.UUID, subtype) + + // Required Characteristics + this.addCharacteristic(Characteristic.BufferUploadCommand) + this.addCharacteristic(Characteristic.BufferActivityCommand) + this.addCharacteristic(Characteristic.BufferEventCommand) + this.addCharacteristic(Characteristic.BufferEventSequenceNumber) + this.addCharacteristic(Characteristic.CameraRecordingPublishingPoint) + } +} +Service.CameraBufferManagement = CameraBufferManagement + +/** + * Service "Camera Capabilities" + */ +export class CameraCapabilities extends Service { + public static readonly UUID: string = '00008010-0000-1000-8000-0026BB765291' + + constructor(displayName?: string, subtype?: string) { + super(displayName, CameraCapabilities.UUID, subtype) + + // Required Characteristics + this.addCharacteristic(Characteristic.Version) + this.addCharacteristic(Characteristic.CameraCapabilitiesData) + + // Optional Characteristics + this.addOptionalCharacteristic(Characteristic.ManuallyDisabled) + } +} +Service.CameraCapabilities = CameraCapabilities + +/** + * Service "Camera Client Certificate Management" + */ +export class CameraClientCertificateManagement extends Service { + public static readonly UUID: string = '00008080-0000-1000-8000-0026BB765291' + + constructor(displayName?: string, subtype?: string) { + super(displayName, CameraClientCertificateManagement.UUID, subtype) + + // Required Characteristics + this.addCharacteristic(Characteristic.CameraClientCSR) + this.addCharacteristic(Characteristic.CameraClientCertificate) + this.addCharacteristic(Characteristic.CameraClientCertificateStatus) + } +} +Service.CameraClientCertificateManagement = CameraClientCertificateManagement + +/** + * Service "Camera Global Operating Mode" + */ +export class CameraGlobalOperatingMode extends Service { + public static readonly UUID: string = '00008032-0000-1000-8000-0026BB765291' + + constructor(displayName?: string, subtype?: string) { + super(displayName, CameraGlobalOperatingMode.UUID, subtype) + + // Required Characteristics + this.addCharacteristic(Characteristic.HomeKitCameraActive) + this.addCharacteristic(Characteristic.StreamingEnabled) + this.addCharacteristic(Characteristic.CameraOperatingModeIndicator) + + // Optional Characteristics + this.addOptionalCharacteristic(Characteristic.ManuallyDisabled) + this.addOptionalCharacteristic(Characteristic.NightVision) + this.addOptionalCharacteristic(Characteristic.ThirdPartyCameraActive) + } +} +Service.CameraGlobalOperatingMode = CameraGlobalOperatingMode + +/** + * Service "Camera Key Management" + */ +export class CameraKeyManagement extends Service { + public static readonly UUID: string = '00008050-0000-1000-8000-0026BB765291' + + constructor(displayName?: string, subtype?: string) { + super(displayName, CameraKeyManagement.UUID, subtype) + + // Required Characteristics + this.addCharacteristic(Characteristic.CameraKey) + this.addCharacteristic(Characteristic.CameraKeyID) + } +} +Service.CameraKeyManagement = CameraKeyManagement + +/** + * Service "Camera Motion Zones" + */ +export class CameraMotionZones extends Service { + public static readonly UUID: string = '00008021-0000-1000-8000-0026BB765291' + + constructor(displayName?: string, subtype?: string) { + super(displayName, CameraMotionZones.UUID, subtype) + + // Required Characteristics + this.addCharacteristic(Characteristic.Version) + this.addCharacteristic(Characteristic.Active) + this.addCharacteristic(Characteristic.CameraZones) + } +} +Service.CameraMotionZones = CameraMotionZones + +/** + * Service "Camera Multi-Tier RTP Stream Management" + */ +export class CameraMultiTierRTPStreamManagement extends Service { + public static readonly UUID: string = '00008031-0000-1000-8000-0026BB765291' + + constructor(displayName?: string, subtype?: string) { + super(displayName, CameraMultiTierRTPStreamManagement.UUID, subtype) + + // Required Characteristics + this.addCharacteristic(Characteristic.StreamingEnabled) + this.addCharacteristic(Characteristic.StatusActive) + this.addCharacteristic(Characteristic.SupportedVideoStreamTiers) + this.addCharacteristic(Characteristic.SupportedAudioStreamTiers) + this.addCharacteristic(Characteristic.SupportedRTPConfiguration) + this.addCharacteristic(Characteristic.SetupEndpoints) + this.addCharacteristic(Characteristic.RTPStreamingControl) + this.addCharacteristic(Characteristic.SensorUUID) + } +} +Service.CameraMultiTierRTPStreamManagement = CameraMultiTierRTPStreamManagement + /** * Service "Camera Operating Mode" */ @@ -306,6 +438,30 @@ export class CameraRTPStreamManagement extends Service { } Service.CameraRTPStreamManagement = CameraRTPStreamManagement +/** + * Service "Camera WebRTC Stream Management" + */ +export class CameraWebRTCStreamManagement extends Service { + public static readonly UUID: string = '00008033-0000-1000-8000-0026BB765291' + + constructor(displayName?: string, subtype?: string) { + super(displayName, CameraWebRTCStreamManagement.UUID, subtype) + + // Required Characteristics + this.addCharacteristic(Characteristic.WebRTCSolicitOffer) + this.addCharacteristic(Characteristic.WebRTCProvideAnswer) + this.addCharacteristic(Characteristic.WebRTCStreamingControl) + this.addCharacteristic(Characteristic.WebRTCNumberOfActiveSessions) + this.addCharacteristic(Characteristic.WebRTCReoffer) + this.addCharacteristic(Characteristic.WebRTCUpdateSession) + this.addCharacteristic(Characteristic.WebRTCSupportedVideoStreamTiers) + this.addCharacteristic(Characteristic.WebRTCSupportedAudioStreamTiers) + this.addCharacteristic(Characteristic.StreamingEnabled) + this.addCharacteristic(Characteristic.SensorUUID) + } +} +Service.CameraWebRTCStreamManagement = CameraWebRTCStreamManagement + /** * Service "Carbon Dioxide Sensor" */ @@ -891,6 +1047,8 @@ export class MotionSensor extends Service { this.addOptionalCharacteristic(Characteristic.StatusFault) this.addOptionalCharacteristic(Characteristic.StatusLowBattery) this.addOptionalCharacteristic(Characteristic.StatusTampered) + this.addOptionalCharacteristic(Characteristic.ContributingSensors) + this.addOptionalCharacteristic(Characteristic.MotionEnabled) } } Service.MotionSensor = MotionSensor diff --git a/src/lib/definitions/generator-configuration.ts b/src/lib/definitions/generator-configuration.ts index d67cae329..b5b6dc9e4 100644 --- a/src/lib/definitions/generator-configuration.ts +++ b/src/lib/definitions/generator-configuration.ts @@ -391,6 +391,14 @@ export const CharacteristicOverriding: Map { + // The answer carries the accessory's SRTP master keys and salts and reaches its writer only through a plain read, which is why it is held per connection. + generated.transient = true + generated.sensitive = true + }, + ], ]) export const CharacteristicManualAdditions: Map = new Map([ @@ -532,6 +540,325 @@ export const CharacteristicManualAdditions: Map properties: 3, // read, notify }, ], + [ + 'sensor-uuid', + { + id: 'sensor-uuid', + UUID: '0000805B-0000-1000-8000-0026BB765291', + name: 'Sensor UUID', + className: 'SensorUUID', + format: 'data', + properties: 2, // paired read + }, + ], + [ + 'motion-enabled', + { + id: 'motion-enabled', + UUID: '00008087-0000-1000-8000-0026BB765291', + name: 'Motion Enabled', + className: 'MotionEnabled', + format: 'bool', + properties: 39, // notify, paired read, paired write, timed write + adminOnlyAccess: [Access.WRITE], + }, + ], + [ + 'supported-video-stream-tiers', + { + id: 'supported-video-stream-tiers', + UUID: '00008043-0000-1000-8000-0026BB765291', + name: 'Supported Video Stream Tiers', + className: 'SupportedVideoStreamTiers', + format: 'tlv8', + properties: 3, // notify, paired read + }, + ], + [ + 'supported-audio-stream-tiers', + { + id: 'supported-audio-stream-tiers', + UUID: '00008044-0000-1000-8000-0026BB765291', + name: 'Supported Audio Stream Tiers', + className: 'SupportedAudioStreamTiers', + format: 'tlv8', + properties: 3, // notify, paired read + }, + ], + // The Camera Capabilities service (0x8010) owns the class name CameraCapabilities, which is why this characteristic is CameraCapabilitiesData. Once the plist defines + // camera-capabilities, CharacteristicManualOverlaps must map that id to itself, and this entry then replaces the plist definition under its own class name. + [ + 'camera-capabilities', + { + id: 'camera-capabilities', + UUID: '00008011-0000-1000-8000-0026BB765291', + name: 'Camera Capabilities', + className: 'CameraCapabilitiesData', + format: 'tlv8', + properties: 2, // paired read + }, + ], + [ + 'contributing-sensors', + { + id: 'contributing-sensors', + UUID: '00008086-0000-1000-8000-0026BB765291', + name: 'Contributing Sensors', + className: 'ContributingSensors', + format: 'tlv8', + properties: 3, // notify, paired read + }, + ], + [ + 'camera-key', + { + id: 'camera-key', + UUID: '00008051-0000-1000-8000-0026BB765291', + name: 'Camera Key', + className: 'CameraKey', + format: 'tlv8', + properties: 36, // paired write, timed write + transient: true, + sensitive: true, + }, + ], + [ + 'camera-key-id', + { + id: 'camera-key-id', + UUID: '00008052-0000-1000-8000-0026BB765291', + name: 'Camera Key ID', + className: 'CameraKeyID', + format: 'tlv8', + properties: 3, // notify, paired read + }, + ], + [ + 'camera-buffer-command', + { + id: 'camera-buffer-command', + UUID: '00008013-0000-1000-8000-0026BB765291', + name: 'Buffer Upload Command', + className: 'BufferUploadCommand', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + }, + ], + [ + 'camera-activity-command', + { + id: 'camera-activity-command', + UUID: '00008017-0000-1000-8000-0026BB765291', + name: 'Buffer Activity Command', + className: 'BufferActivityCommand', + format: 'tlv8', + properties: 4, // paired write + }, + ], + [ + 'camera-buffer-event-command', + { + id: 'camera-buffer-event-command', + UUID: '00008014-0000-1000-8000-0026BB765291', + name: 'Buffer Event Command', + className: 'BufferEventCommand', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + }, + ], + [ + 'camera-buffer-event-sequence-number', + { + id: 'camera-buffer-event-sequence-number', + UUID: '00008015-0000-1000-8000-0026BB765291', + name: 'Buffer Event Sequence Number', + className: 'BufferEventSequenceNumber', + format: 'uint32', + properties: 3, // notify, paired read + }, + ], + [ + 'camera-recording-publishing-point', + { + id: 'camera-recording-publishing-point', + UUID: '00008016-0000-1000-8000-0026BB765291', + name: 'Camera Recording Publishing Point', + className: 'CameraRecordingPublishingPoint', + format: 'tlv8', + properties: 6, // paired read, paired write + }, + ], + [ + 'camera-zones', + { + id: 'camera-zones', + UUID: '00008022-0000-1000-8000-0026BB765291', + name: 'Camera Zones', + className: 'CameraZones', + format: 'tlv8', + properties: 6, // paired read, paired write + }, + ], + [ + 'streaming-enabled', + { + id: 'streaming-enabled', + UUID: '00008041-0000-1000-8000-0026BB765291', + name: 'Streaming Enabled', + className: 'StreamingEnabled', + format: 'bool', + properties: 39, // notify, paired read, paired write, timed write + adminOnlyAccess: [Access.WRITE], + }, + ], + [ + 'rtp-streaming-control', + { + id: 'rtp-streaming-control', + UUID: '00008045-0000-1000-8000-0026BB765291', + name: 'RTP Streaming Control', + className: 'RTPStreamingControl', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + }, + ], + [ + 'webrtc-solicit-offer', + { + id: 'webrtc-solicit-offer', + UUID: '00008053-0000-1000-8000-0026BB765291', + name: 'WebRTC Solicit Offer', + className: 'WebRTCSolicitOffer', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + sensitive: true, + }, + ], + [ + 'webrtc-provide-answer', + { + id: 'webrtc-provide-answer', + UUID: '00008054-0000-1000-8000-0026BB765291', + name: 'WebRTC Provide Answer', + className: 'WebRTCProvideAnswer', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + }, + ], + [ + 'webrtc-streaming-control', + { + id: 'webrtc-streaming-control', + UUID: '00008056-0000-1000-8000-0026BB765291', + name: 'WebRTC Streaming Control', + className: 'WebRTCStreamingControl', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + }, + ], + [ + 'webrtc-number-of-active-sessions', + { + id: 'webrtc-number-of-active-sessions', + UUID: '00008057-0000-1000-8000-0026BB765291', + name: 'WebRTC Number Of Active Sessions', + className: 'WebRTCNumberOfActiveSessions', + format: 'uint8', + properties: 3, // notify, paired read + minValue: 0, + maxValue: 255, + }, + ], + [ + 'webrtc-reoffer', + { + id: 'webrtc-reoffer', + UUID: '00008058-0000-1000-8000-0026BB765291', + name: 'WebRTC Reoffer', + className: 'WebRTCReoffer', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + sensitive: true, + }, + ], + [ + 'webrtc-update-session', + { + id: 'webrtc-update-session', + UUID: '0000805C-0000-1000-8000-0026BB765291', + name: 'WebRTC Update Session', + className: 'WebRTCUpdateSession', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + sensitive: true, + }, + ], + [ + 'webrtc-supported-video-stream-tiers', + { + id: 'webrtc-supported-video-stream-tiers', + UUID: '00008059-0000-1000-8000-0026BB765291', + name: 'WebRTC Supported Video Stream Tiers', + className: 'WebRTCSupportedVideoStreamTiers', + format: 'tlv8', + properties: 3, // notify, paired read + }, + ], + [ + 'webrtc-supported-audio-stream-tiers', + { + id: 'webrtc-supported-audio-stream-tiers', + UUID: '0000805A-0000-1000-8000-0026BB765291', + name: 'WebRTC Supported Audio Stream Tiers', + className: 'WebRTCSupportedAudioStreamTiers', + format: 'tlv8', + properties: 3, // notify, paired read + }, + ], + [ + 'camera-client-csr', + { + id: 'camera-client-csr', + UUID: '00008081-0000-1000-8000-0026BB765291', + name: 'Camera Client CSR', + className: 'CameraClientCSR', + format: 'tlv8', + properties: 134, // paired read, paired write, write response + transient: true, + }, + ], + [ + 'camera-client-certificate', + { + id: 'camera-client-certificate', + UUID: '00008082-0000-1000-8000-0026BB765291', + name: 'Camera Client Certificate', + className: 'CameraClientCertificate', + format: 'tlv8', + properties: 38, // paired read, paired write, timed write + transient: true, + sensitive: true, + }, + ], + [ + 'camera-client-certificate-status', + { + id: 'camera-client-certificate-status', + UUID: '00008083-0000-1000-8000-0026BB765291', + name: 'Camera Client Certificate Status', + className: 'CameraClientCertificateStatus', + format: 'tlv8', + properties: 3, // notify, paired read + }, + ], ]) export const ServiceNameOverrides: Map = new Map([ @@ -567,6 +894,12 @@ export const ServiceCharacteristicConfigurationOverrides: Map = new Map([ @@ -630,6 +963,130 @@ export const ServiceManualAdditions: Map = new Map([ ], }, ], + [ + 'camera-capabilities', + { + id: 'camera-capabilities', + UUID: '00008010-0000-1000-8000-0026BB765291', + name: 'Camera Capabilities', + className: 'CameraCapabilities', + requiredCharacteristics: ['version', 'camera-capabilities'], + optionalCharacteristics: ['manually-disabled'], + }, + ], + [ + 'camera-global-operating-mode', + { + id: 'camera-global-operating-mode', + UUID: '00008032-0000-1000-8000-0026BB765291', + name: 'Camera Global Operating Mode', + className: 'CameraGlobalOperatingMode', + requiredCharacteristics: [ + 'homekit-camera-active', + 'streaming-enabled', + 'camera-operating-mode-indicator', + ], + optionalCharacteristics: [ + 'manually-disabled', + 'night-vision', + 'third-party-camera-active', + ], + }, + ], + [ + 'camera-motion-zones', + { + id: 'camera-motion-zones', + UUID: '00008021-0000-1000-8000-0026BB765291', + name: 'Camera Motion Zones', + className: 'CameraMotionZones', + requiredCharacteristics: [ + 'version', + 'active', + 'camera-zones', + ], + }, + ], + [ + 'camera-buffer-management', + { + id: 'camera-buffer-management', + UUID: '00008000-0000-1000-8000-0026BB765291', + name: 'Camera Buffer Management', + className: 'CameraBufferManagement', + requiredCharacteristics: [ + 'camera-buffer-command', + 'camera-activity-command', + 'camera-buffer-event-command', + 'camera-buffer-event-sequence-number', + 'camera-recording-publishing-point', + ], + }, + ], + [ + 'camera-multi-tier-rtp-stream-management', + { + id: 'camera-multi-tier-rtp-stream-management', + UUID: '00008031-0000-1000-8000-0026BB765291', + name: 'Camera Multi-Tier RTP Stream Management', + className: 'CameraMultiTierRTPStreamManagement', + requiredCharacteristics: [ + 'streaming-enabled', + 'status-active', + 'supported-video-stream-tiers', + 'supported-audio-stream-tiers', + 'supported-rtp-configuration', + 'setup-stream-endpoint', + 'rtp-streaming-control', + 'sensor-uuid', + ], + }, + ], + [ + 'camera-webrtc-stream-management', + { + id: 'camera-webrtc-stream-management', + UUID: '00008033-0000-1000-8000-0026BB765291', + name: 'Camera WebRTC Stream Management', + className: 'CameraWebRTCStreamManagement', + requiredCharacteristics: [ + 'webrtc-solicit-offer', + 'webrtc-provide-answer', + 'webrtc-streaming-control', + 'webrtc-number-of-active-sessions', + 'webrtc-reoffer', + 'webrtc-update-session', + 'webrtc-supported-video-stream-tiers', + 'webrtc-supported-audio-stream-tiers', + 'streaming-enabled', + 'sensor-uuid', + ], + }, + ], + [ + 'camera-key-management', + { + id: 'camera-key-management', + UUID: '00008050-0000-1000-8000-0026BB765291', + name: 'Camera Key Management', + className: 'CameraKeyManagement', + requiredCharacteristics: ['camera-key', 'camera-key-id'], + }, + ], + [ + 'camera-client-certificate-management', + { + id: 'camera-client-certificate-management', + UUID: '00008080-0000-1000-8000-0026BB765291', + name: 'Camera Client Certificate Management', + className: 'CameraClientCertificateManagement', + requiredCharacteristics: [ + 'camera-client-csr', + 'camera-client-certificate', + 'camera-client-certificate-status', + ], + }, + ], ]) /** From 303ce798a08023f91f1d60fea0817f553fd08355 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:46 -0600 Subject: [PATCH 07/16] feat(camera): add the TLV8 codecs of the camera characteristics over one field layer --- eslint.config.mjs | 7 + .../camera/capabilities/cameraBuffer.spec.ts | 178 +++++ src/lib/camera/capabilities/cameraBuffer.ts | 614 ++++++++++++++++ .../camera/capabilities/cameraSensors.spec.ts | 203 ++++++ src/lib/camera/capabilities/cameraSensors.ts | 354 +++++++++ src/lib/camera/capabilities/index.ts | 8 + .../camera/capabilities/provisioning.spec.ts | 131 ++++ src/lib/camera/capabilities/provisioning.ts | 241 +++++++ .../camera/capabilities/rtpStreaming.spec.ts | 102 +++ src/lib/camera/capabilities/rtpStreaming.ts | 177 +++++ src/lib/camera/capabilities/setupEndpoints.ts | 347 +++++++++ .../camera/capabilities/streamTiers.spec.ts | 112 +++ src/lib/camera/capabilities/streamTiers.ts | 344 +++++++++ .../supportedRtpConfiguration.spec.ts | 38 + .../capabilities/supportedRtpConfiguration.ts | 41 ++ src/lib/camera/capabilities/tlvFields.spec.ts | 170 +++++ src/lib/camera/capabilities/tlvFields.ts | 298 ++++++++ src/lib/camera/capabilities/webrtc.spec.ts | 261 +++++++ src/lib/camera/capabilities/webrtc.ts | 676 ++++++++++++++++++ src/lib/camera/capabilities/zones.spec.ts | 103 +++ src/lib/camera/capabilities/zones.ts | 188 +++++ src/lib/camera/index.ts | 1 + src/lib/util/counted.spec.ts | 43 ++ src/lib/util/counted.ts | 27 + 24 files changed, 4664 insertions(+) create mode 100644 src/lib/camera/capabilities/cameraBuffer.spec.ts create mode 100644 src/lib/camera/capabilities/cameraBuffer.ts create mode 100644 src/lib/camera/capabilities/cameraSensors.spec.ts create mode 100644 src/lib/camera/capabilities/cameraSensors.ts create mode 100644 src/lib/camera/capabilities/index.ts create mode 100644 src/lib/camera/capabilities/provisioning.spec.ts create mode 100644 src/lib/camera/capabilities/provisioning.ts create mode 100644 src/lib/camera/capabilities/rtpStreaming.spec.ts create mode 100644 src/lib/camera/capabilities/rtpStreaming.ts create mode 100644 src/lib/camera/capabilities/setupEndpoints.ts create mode 100644 src/lib/camera/capabilities/streamTiers.spec.ts create mode 100644 src/lib/camera/capabilities/streamTiers.ts create mode 100644 src/lib/camera/capabilities/supportedRtpConfiguration.spec.ts create mode 100644 src/lib/camera/capabilities/supportedRtpConfiguration.ts create mode 100644 src/lib/camera/capabilities/tlvFields.spec.ts create mode 100644 src/lib/camera/capabilities/tlvFields.ts create mode 100644 src/lib/camera/capabilities/webrtc.spec.ts create mode 100644 src/lib/camera/capabilities/webrtc.ts create mode 100644 src/lib/camera/capabilities/zones.spec.ts create mode 100644 src/lib/camera/capabilities/zones.ts create mode 100644 src/lib/util/counted.spec.ts create mode 100644 src/lib/util/counted.ts diff --git a/eslint.config.mjs b/eslint.config.mjs index 1e5c03e3a..ff7a83f07 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -149,3 +149,10 @@ export default antfu( 'test/valid-title': 'error', }, }) + .append({ + // A constant set and the type derived from it share one name in the capability codecs, which this rule reads as a redeclaration. + files: ['src/lib/camera/capabilities/**/*.ts'], + rules: { + 'ts/no-redeclare': 'off', + }, + }) diff --git a/src/lib/camera/capabilities/cameraBuffer.spec.ts b/src/lib/camera/capabilities/cameraBuffer.spec.ts new file mode 100644 index 000000000..79023e720 --- /dev/null +++ b/src/lib/camera/capabilities/cameraBuffer.spec.ts @@ -0,0 +1,178 @@ +import type { + BufferActivityCommandRequest, + BufferEventCommandRequest, + BufferEventCommandResponse, + BufferUploadCommandRequest, + BufferUploadCommandResponse, + CameraRecordingPublishingPointPayload, +} from './cameraBuffer.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + BufferActivity, + BufferEventCommandType, + BufferUploadCommandType, + BufferUploadStopAction, + CameraBufferEventType, + CMAFError, + decodeBufferActivityCommandRequest, + decodeBufferEventCommandRequest, + decodeBufferEventCommandResponse, + decodeBufferUploadCommandRequest, + decodeBufferUploadCommandResponse, + decodeCameraRecordingPublishingPoint, + encodeBufferActivityCommandRequest, + encodeBufferEventCommandRequest, + encodeBufferEventCommandResponse, + encodeBufferUploadCommandRequest, + encodeBufferUploadCommandResponse, + encodeCameraRecordingPublishingPoint, +} from './cameraBuffer.js' + +// The golden vectors are computed from the spec's tables by an independent TLV8 writer, every integer little-endian at its table width. +const P53 = 2n ** 53n + 1n +const MAX64 = 2n ** 64n - 1n +// An NTP timestamp, 2025-11-05 and about 0.123456789 seconds as NTP seconds and fraction, which, like the stop thirty seconds after it, no number holds exactly. +const NTP = (3971289600n << 32n) | 0x1F9ADD37n + +const BUFFER_UPLOAD_START_AND_STOP: BufferUploadCommandRequest = { + sessionID: MAX64, + command: BufferUploadCommandType.START_AND_STOP, + start: NTP, + stop: NTP + (30n << 32n), + stopAction: BufferUploadStopAction.FINALIZE, +} +const BUFFER_UPLOAD_START_AND_STOP_HEX = '0108ffffffffffffffff020102030837dd9a1f0012b5ec040837dd9a1f1e12b5ec050102' + +const BUFFER_UPLOAD_START: BufferUploadCommandRequest = { sessionID: P53, command: BufferUploadCommandType.START, start: NTP } +const BUFFER_UPLOAD_START_HEX = '01080100000000002000020101030837dd9a1f0012b5ec' + +const BUFFER_UPLOAD_RESPONSE: BufferUploadCommandResponse = { clipID: P53 } +const BUFFER_UPLOAD_RESPONSE_HEX = '01080100000000002000' + +const BUFFER_ACTIVITY: BufferActivityCommandRequest = { start: NTP, duration: 15000n, activity: BufferActivity.SHOULD_RECORD } +const BUFFER_ACTIVITY_HEX = '010837dd9a1f0012b5ec0208983a000000000000030101' + +const BUFFER_EVENT_QUERY: BufferEventCommandRequest = { command: BufferEventCommandType.QUERY, sequenceNumber: P53, limit: 50n } +const BUFFER_EVENT_QUERY_HEX = '0101010208010000000000200003083200000000000000' + +const BUFFER_EVENT_ACKNOWLEDGE: BufferEventCommandRequest = { command: BufferEventCommandType.ACKNOWLEDGE, sequenceNumber: P53 + 3n } +const BUFFER_EVENT_ACKNOWLEDGE_HEX = '01010202080400000000002000' + +const BUFFER_EVENT_RESPONSE: BufferEventCommandResponse = { + events: [ + { sequenceNumber: P53, type: CameraBufferEventType.CMAF_SESSION_START, cmafSessionID: 42n }, + { sequenceNumber: P53 + 1n, type: CameraBufferEventType.MOTION, active: true }, + { + sequenceNumber: P53 + 2n, + type: CameraBufferEventType.CMAF_ERROR, + cmafSessionID: 42n, + cmafError: CMAFError.HTTP_INVALID_TOKEN, + }, + { sequenceNumber: MAX64, type: CameraBufferEventType.CMAF_SESSION_STOP, cmafSessionID: 42n }, + ], +} +const BUFFER_EVENT_RESPONSE_HEX = '011901080100000000002000020101030a01082a00000000000000000001120108020000000000200002010305030101010000011c010803' + + '00000000002000020104060d01082a00000000000000020110000001190108ffffffffffffffff020102040a01082a00000000000000' + +const PUBLISHING_POINT: CameraRecordingPublishingPointPayload = { + url: 'https://ingest.example.com/cmaf/', + serverCACertificates: [ + { + certificate: Buffer.from('3003020101', 'hex'), + }, + { + certificate: Buffer.from('3003020102', 'hex'), + }, + ], +} +const PUBLISHING_POINT_HEX = '012068747470733a2f2f696e676573742e6578616d706c652e636f6d2f636d61662f0207010530030201010000020701053003020102' + +// The start and stop with its Session ID seven bytes long. +const SEVEN_BYTE_SESSION_ID_START_AND_STOP_HEX = '0107ffffffffffffff020102030837dd9a1f0012b5ec040837dd9a1f1e12b5ec050102' + +describe('camera buffer', () => { + it('encodes and decodes a buffer upload start and stop', () => { + const value = Buffer.from(BUFFER_UPLOAD_START_AND_STOP_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeBufferUploadCommandRequest(BUFFER_UPLOAD_START_AND_STOP), 'base64').toString('hex')).toBe(BUFFER_UPLOAD_START_AND_STOP_HEX) + expect(decodeBufferUploadCommandRequest(value)).toEqual(BUFFER_UPLOAD_START_AND_STOP) + }) + + it('encodes and decodes a buffer upload start', () => { + const value = Buffer.from(BUFFER_UPLOAD_START_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeBufferUploadCommandRequest(BUFFER_UPLOAD_START), 'base64').toString('hex')).toBe(BUFFER_UPLOAD_START_HEX) + expect(decodeBufferUploadCommandRequest(value)).toEqual(BUFFER_UPLOAD_START) + }) + + it('encodes and decodes a buffer upload response', () => { + const value = Buffer.from(BUFFER_UPLOAD_RESPONSE_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeBufferUploadCommandResponse(BUFFER_UPLOAD_RESPONSE), 'base64').toString('hex')).toBe(BUFFER_UPLOAD_RESPONSE_HEX) + expect(decodeBufferUploadCommandResponse(value)).toEqual(BUFFER_UPLOAD_RESPONSE) + }) + + it('encodes and decodes a buffer activity command', () => { + const value = Buffer.from(BUFFER_ACTIVITY_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeBufferActivityCommandRequest(BUFFER_ACTIVITY), 'base64').toString('hex')).toBe(BUFFER_ACTIVITY_HEX) + expect(decodeBufferActivityCommandRequest(value)).toEqual(BUFFER_ACTIVITY) + }) + + it('encodes and decodes a buffer event query', () => { + const value = Buffer.from(BUFFER_EVENT_QUERY_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeBufferEventCommandRequest(BUFFER_EVENT_QUERY), 'base64').toString('hex')).toBe(BUFFER_EVENT_QUERY_HEX) + expect(decodeBufferEventCommandRequest(value)).toEqual(BUFFER_EVENT_QUERY) + }) + + it('encodes and decodes a buffer event acknowledgement', () => { + const value = Buffer.from(BUFFER_EVENT_ACKNOWLEDGE_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeBufferEventCommandRequest(BUFFER_EVENT_ACKNOWLEDGE), 'base64').toString('hex')).toBe(BUFFER_EVENT_ACKNOWLEDGE_HEX) + expect(decodeBufferEventCommandRequest(value)).toEqual(BUFFER_EVENT_ACKNOWLEDGE) + }) + + it('encodes and decodes a buffer event response', () => { + const value = Buffer.from(BUFFER_EVENT_RESPONSE_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeBufferEventCommandResponse(BUFFER_EVENT_RESPONSE), 'base64').toString('hex')).toBe(BUFFER_EVENT_RESPONSE_HEX) + expect(decodeBufferEventCommandResponse(value)).toEqual(BUFFER_EVENT_RESPONSE) + }) + + it('encodes and decodes a publishing point', () => { + const value = Buffer.from(PUBLISHING_POINT_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraRecordingPublishingPoint(PUBLISHING_POINT), 'base64').toString('hex')).toBe(PUBLISHING_POINT_HEX) + expect(decodeCameraRecordingPublishingPoint(value)).toEqual(PUBLISHING_POINT) + }) + + it('ignores an unknown tag', () => { + const value = Buffer.from(`${BUFFER_UPLOAD_START_AND_STOP_HEX}ff0100`, 'hex').toString('base64') + + expect(decodeBufferUploadCommandRequest(value)).toEqual(BUFFER_UPLOAD_START_AND_STOP) + }) + + it('refuses a write without its session id, naming the field', () => { + const value = Buffer.from(BUFFER_UPLOAD_START_AND_STOP_HEX.replace(/^0108f{16}/, ''), 'hex').toString('base64') + + expect(() => decodeBufferUploadCommandRequest(value)).toThrow('The Session ID field is missing.') + }) + + it('decodes a buffer upload start and stop whose session id is seven bytes long', () => { + const value = Buffer.from(SEVEN_BYTE_SESSION_ID_START_AND_STOP_HEX, 'hex').toString('base64') + + expect(decodeBufferUploadCommandRequest(value)).toEqual({ ...BUFFER_UPLOAD_START_AND_STOP, sessionID: 2n ** 56n - 1n }) + }) + + it('refuses a session id nine bytes long, naming the field', () => { + const value = Buffer.from(BUFFER_UPLOAD_START_AND_STOP_HEX.replace(/^0108f{16}/, '0109ffffffffffffffff00'), 'hex').toString('base64') + + expect(() => decodeBufferUploadCommandRequest(value)).toThrow(RangeError) + expect(() => decodeBufferUploadCommandRequest(value)).toThrow('The Session ID field is 9 bytes long, but its format takes at most 8 bytes.') + }) +}) diff --git a/src/lib/camera/capabilities/cameraBuffer.ts b/src/lib/camera/capabilities/cameraBuffer.ts new file mode 100644 index 000000000..c8cadd8da --- /dev/null +++ b/src/lib/camera/capabilities/cameraBuffer.ts @@ -0,0 +1,614 @@ +import { Buffer } from 'node:buffer' + +import { encode } from '../../util/tlv.js' +import { + decodeBase64Fields, + decodeFields, + encodeOptional, + listField, + optionalField, + readBoolean, + readEnum, + readString, + readUInt64, + requiredField, + writeBoolean, + writeString, + writeUInt8, + writeUInt64, +} from './tlvFields.js' + +const BufferUploadCommandRequestTypes = { + SESSION_ID: 0x01, + COMMAND: 0x02, + START: 0x03, + STOP: 0x04, + STOP_ACTION: 0x05, +} as const + +const BufferUploadCommandResponseTypes = { + CLIP_ID: 0x01, +} as const + +const BufferActivityCommandRequestTypes = { + START: 0x01, + DURATION: 0x02, + ACTIVITY: 0x03, +} as const + +const BufferEventCommandRequestTypes = { + COMMAND: 0x01, + SEQUENCE_NUMBER: 0x02, + LIMIT: 0x03, +} as const + +const BufferEventCommandResponseTypes = { + EVENTS: 0x01, +} as const + +const CameraBufferEventTypes = { + SEQUENCE_NUMBER: 0x01, + TYPE: 0x02, + CMAF_SESSION_START: 0x03, + CMAF_SESSION_STOP: 0x04, + MOTION: 0x05, + CMAF_ERROR: 0x06, +} as const + +const CMAFSessionTypes = { + CMAF_SESSION_ID: 0x01, +} as const + +const MotionTypes = { + ACTIVE: 0x01, +} as const + +const CMAFErrorTypes = { + CMAF_SESSION_ID: 0x01, + CMAF_ERROR: 0x02, +} as const + +const CameraRecordingPublishingPointTypes = { + URL: 0x01, + SERVER_CA_CERTIFICATES: 0x02, +} as const + +const PublishingPointCertificateTypes = { + CERTIFICATE: 0x01, +} as const + +/** + * The command a Buffer Upload Command write carries. + */ +export const BufferUploadCommandType = { + START: 1, + START_AND_STOP: 2, + STOP: 3, +} as const + +export type BufferUploadCommandType = (typeof BufferUploadCommandType)[keyof typeof BufferUploadCommandType] + +const BUFFER_UPLOAD_COMMAND_TYPE_VALUES: ReadonlySet = new Set(Object.values(BufferUploadCommandType)) + +/** + * What a stopped upload does with its clip. + */ +export const BufferUploadStopAction = { + PAUSE: 1, + FINALIZE: 2, +} as const + +export type BufferUploadStopAction = (typeof BufferUploadStopAction)[keyof typeof BufferUploadStopAction] + +const BUFFER_UPLOAD_STOP_ACTION_VALUES: ReadonlySet = new Set(Object.values(BufferUploadStopAction)) + +/** + * The activity a Buffer Activity Command asks of the buffer. + */ +export const BufferActivity = { + SHOULD_RECORD: 1, + SHOULD_NOT_RECORD: 2, +} as const + +export type BufferActivity = (typeof BufferActivity)[keyof typeof BufferActivity] + +const BUFFER_ACTIVITY_VALUES: ReadonlySet = new Set(Object.values(BufferActivity)) + +/** + * The command a Buffer Event Command write carries. + */ +export const BufferEventCommandType = { + QUERY: 1, + ACKNOWLEDGE: 2, +} as const + +export type BufferEventCommandType = (typeof BufferEventCommandType)[keyof typeof BufferEventCommandType] + +const BUFFER_EVENT_COMMAND_TYPE_VALUES: ReadonlySet = new Set(Object.values(BufferEventCommandType)) + +/** + * The type of an event in the camera event queue. + */ +export const CameraBufferEventType = { + CMAF_SESSION_START: 1, + CMAF_SESSION_STOP: 2, + MOTION: 3, + CMAF_ERROR: 4, +} as const + +export type CameraBufferEventType = (typeof CameraBufferEventType)[keyof typeof CameraBufferEventType] + +const CAMERA_BUFFER_EVENT_TYPE_VALUES: ReadonlySet = new Set(Object.values(CameraBufferEventType)) + +/** + * The error a CMAF error event reports. + */ +export const CMAFError = { + NONE: 0, + UNKNOWN: 1, + CANNOT_FIND_HOST: 2, + CERT_CONNECTION_FAILURE: 3, + CANNOT_CERTIFY: 4, + INVALID_STATE: 5, + REQUIRES_RETRY: 6, + NO_RESPONSE: 7, + MAX_SESSION_TIME_EXCEEDED: 8, + CANCELED: 9, + MP4_ERROR: 10, + CONNECTION_FAILED: 11, + TIMEOUT: 12, + OUT_OF_RESOURCES: 13, + INVALID_DATA: 14, + HTTP_BAD_REQUEST: 15, + HTTP_INVALID_TOKEN: 16, + HTTP_CAMERA_ZONE_DISABLED: 17, + HTTP_MISMATCHED_TOKEN: 18, + HTTP_NOT_FOUND: 19, + HTTP_INIT_MISSING: 20, + HTTP_UNSUPPORTED_MEDIA_TYPE: 21, + HTTP_BLOCKED: 22, + HTTP_CERTIFICATE_EXPIRED: 23, + HTTP_INTERNAL_SERVER_ERROR: 24, + HTTP_SERVICE_UNAVAILABLE: 25, + HTTP_CAMERA_ZONE_DOES_NOT_EXIST: 26, +} as const + +export type CMAFError = (typeof CMAFError)[keyof typeof CMAFError] + +const CMAF_ERROR_VALUES: ReadonlySet = new Set(Object.values(CMAFError)) + +/** + * A write to Buffer Upload Command, which asks for a recording from the buffer. The spec does not say which optional fields each command carries, which is why + * the codec requires none of them. + */ +export interface BufferUploadCommandRequest { + /** + * The session's identifier. The spec's description calls it a UUID while its table types it uint64, and it is carried as the uint64 the table states. + */ + sessionID: bigint + /** + * The command. + */ + command: BufferUploadCommandType + /** + * The timestamp the uploaded clip begins at. + */ + start?: bigint + /** + * The timestamp the uploaded clip stops at. + */ + stop?: bigint + /** + * What the stopped upload does with its clip. + */ + stopAction?: BufferUploadStopAction +} + +/** + * The write response of Buffer Upload Command. + */ +export interface BufferUploadCommandResponse { + /** + * The ID of the uploaded clip. + */ + clipID: bigint +} + +/** + * A write to Buffer Activity Command, which asks the buffer to perform an activity. + */ +export interface BufferActivityCommandRequest { + /** + * The NTP timestamp the activity starts at. + */ + start: bigint + /** + * The activity's duration, in milliseconds. + */ + duration: bigint + /** + * The activity. + */ + activity: BufferActivity +} + +/** + * A write to Buffer Event Command, which fetches or acknowledges events from the camera event queue. + */ +export interface BufferEventCommandRequest { + /** + * The command. + */ + command: BufferEventCommandType + /** + * The sequence number the command names. + */ + sequenceNumber: bigint + /** + * The command's limit. + */ + limit?: bigint +} + +/** + * One event of the camera event queue, a union on its type. + */ +export type CameraBufferEvent = { + /** + * The event's sequence number. + */ + sequenceNumber: bigint + /** + * The event's type. + */ + type: typeof CameraBufferEventType.CMAF_SESSION_START | typeof CameraBufferEventType.CMAF_SESSION_STOP + /** + * The CMAF session that started or stopped. + */ + cmafSessionID: bigint +} | { + /** + * The event's sequence number. + */ + sequenceNumber: bigint + /** + * The event's type. + */ + type: typeof CameraBufferEventType.MOTION + /** + * Whether motion was active. + */ + active: boolean +} | { + /** + * The event's sequence number. + */ + sequenceNumber: bigint + /** + * The event's type. + */ + type: typeof CameraBufferEventType.CMAF_ERROR + /** + * The CMAF session the error concerns. + */ + cmafSessionID: bigint + /** + * The error. + */ + cmafError: CMAFError +} + +/** + * The write response of Buffer Event Command. + */ +export interface BufferEventCommandResponse { + /** + * One entry per event. + */ + events: CameraBufferEvent[] +} + +/** + * One server certificate of a publishing point. + */ +export interface PublishingPointCertificate { + /** + * The certificate, in DER format. + */ + certificate: Buffer +} + +/** + * The value of Camera Recording Publishing Point: the URL and server certificates recorded clips are published to. + */ +export interface CameraRecordingPublishingPointPayload { + /** + * The CMAF publishing point URL, which the spec has end in a slash. + */ + url: string + /** + * The server's CA certificates. + */ + serverCACertificates: PublishingPointCertificate[] +} + +function encodeCMAFSession(cmafSessionID: bigint): Buffer { + return encode(CMAFSessionTypes.CMAF_SESSION_ID, writeUInt64(cmafSessionID)) +} + +function readCMAFSessionID(buffer: Buffer): bigint { + return readUInt64(requiredField(decodeFields(buffer), CMAFSessionTypes.CMAF_SESSION_ID, 'CMAF Session ID')) +} + +function encodeCameraBufferEvent(event: CameraBufferEvent): Buffer { + const header = encode( + CameraBufferEventTypes.SEQUENCE_NUMBER, writeUInt64(event.sequenceNumber), + CameraBufferEventTypes.TYPE, writeUInt8(event.type), + ) + + switch (event.type) { + case CameraBufferEventType.CMAF_SESSION_START: + return Buffer.concat([ + header, + encode(CameraBufferEventTypes.CMAF_SESSION_START, encodeCMAFSession(event.cmafSessionID)), + ]) + case CameraBufferEventType.CMAF_SESSION_STOP: + return Buffer.concat([ + header, + encode(CameraBufferEventTypes.CMAF_SESSION_STOP, encodeCMAFSession(event.cmafSessionID)), + ]) + case CameraBufferEventType.MOTION: + return Buffer.concat([ + header, + encode(CameraBufferEventTypes.MOTION, encode(MotionTypes.ACTIVE, writeBoolean(event.active))), + ]) + case CameraBufferEventType.CMAF_ERROR: + return Buffer.concat([ + header, + encode(CameraBufferEventTypes.CMAF_ERROR, encode( + CMAFErrorTypes.CMAF_SESSION_ID, writeUInt64(event.cmafSessionID), + CMAFErrorTypes.CMAF_ERROR, writeUInt8(event.cmafError), + )), + ]) + } +} + +function decodeCameraBufferEvent(buffer: Buffer): CameraBufferEvent { + const fields = decodeFields(buffer) + const sequenceNumber = readUInt64(requiredField(fields, CameraBufferEventTypes.SEQUENCE_NUMBER, 'Sequence Number')) + const type = readEnum(requiredField(fields, CameraBufferEventTypes.TYPE, 'Type'), CAMERA_BUFFER_EVENT_TYPE_VALUES) + + switch (type) { + case CameraBufferEventType.CMAF_SESSION_START: + return { + sequenceNumber, + type, + cmafSessionID: readCMAFSessionID(requiredField(fields, CameraBufferEventTypes.CMAF_SESSION_START, 'CMAF Session Start').value), + } + case CameraBufferEventType.CMAF_SESSION_STOP: + return { + sequenceNumber, + type, + cmafSessionID: readCMAFSessionID(requiredField(fields, CameraBufferEventTypes.CMAF_SESSION_STOP, 'CMAF Session Stop').value), + } + case CameraBufferEventType.MOTION: { + const motion = decodeFields(requiredField(fields, CameraBufferEventTypes.MOTION, 'Motion').value) + + return { + sequenceNumber, + type, + active: readBoolean(requiredField(motion, MotionTypes.ACTIVE, 'Active')), + } + } + case CameraBufferEventType.CMAF_ERROR: { + const error = decodeFields(requiredField(fields, CameraBufferEventTypes.CMAF_ERROR, 'CMAF Error').value) + + return { + sequenceNumber, + type, + cmafSessionID: readUInt64(requiredField(error, CMAFErrorTypes.CMAF_SESSION_ID, 'CMAF Session ID')), + cmafError: readEnum(requiredField(error, CMAFErrorTypes.CMAF_ERROR, 'CMAF Error'), CMAF_ERROR_VALUES), + } + } + } +} + +function encodePublishingPointCertificate(certificate: PublishingPointCertificate): Buffer { + return encode(PublishingPointCertificateTypes.CERTIFICATE, certificate.certificate) +} + +function decodePublishingPointCertificate(buffer: Buffer): PublishingPointCertificate { + return { + certificate: requiredField(decodeFields(buffer), PublishingPointCertificateTypes.CERTIFICATE, 'Certificate').value, + } +} + +/** + * Encodes a Buffer Upload Command write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeBufferUploadCommandRequest(request: BufferUploadCommandRequest): string { + return Buffer.concat([ + encode( + BufferUploadCommandRequestTypes.SESSION_ID, writeUInt64(request.sessionID), + BufferUploadCommandRequestTypes.COMMAND, writeUInt8(request.command), + ), + encodeOptional( + BufferUploadCommandRequestTypes.START, + request.start === undefined + ? undefined + : writeUInt64(request.start), + ), + encodeOptional( + BufferUploadCommandRequestTypes.STOP, + request.stop === undefined + ? undefined + : writeUInt64(request.stop), + ), + encodeOptional( + BufferUploadCommandRequestTypes.STOP_ACTION, + request.stopAction === undefined + ? undefined + : writeUInt8(request.stopAction), + ), + ]).toString('base64') +} + +/** + * Decodes a Buffer Upload Command write. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeBufferUploadCommandRequest(value: string): BufferUploadCommandRequest { + const fields = decodeBase64Fields(value) + const start = optionalField(fields, BufferUploadCommandRequestTypes.START, 'Start') + const stop = optionalField(fields, BufferUploadCommandRequestTypes.STOP, 'Stop') + const stopAction = optionalField(fields, BufferUploadCommandRequestTypes.STOP_ACTION, 'Stop Action') + + return { + sessionID: readUInt64(requiredField(fields, BufferUploadCommandRequestTypes.SESSION_ID, 'Session ID')), + command: readEnum(requiredField(fields, BufferUploadCommandRequestTypes.COMMAND, 'Command'), BUFFER_UPLOAD_COMMAND_TYPE_VALUES), + ...(start && { + start: readUInt64(start), + }), + ...(stop && { + stop: readUInt64(stop), + }), + ...(stopAction && { + stopAction: readEnum(stopAction, BUFFER_UPLOAD_STOP_ACTION_VALUES), + }), + } +} + +/** + * Encodes the write response of Buffer Upload Command. + * @param response - The response's model. + * @returns The base64 characteristic value. + */ +export function encodeBufferUploadCommandResponse(response: BufferUploadCommandResponse): string { + return encode(BufferUploadCommandResponseTypes.CLIP_ID, writeUInt64(response.clipID)).toString('base64') +} + +/** + * Decodes the write response of Buffer Upload Command. + * @param value - The base64 characteristic value. + * @returns The response's model. + */ +export function decodeBufferUploadCommandResponse(value: string): BufferUploadCommandResponse { + return { + clipID: readUInt64(requiredField(decodeBase64Fields(value), BufferUploadCommandResponseTypes.CLIP_ID, 'Clip ID')), + } +} + +/** + * Encodes a Buffer Activity Command write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeBufferActivityCommandRequest(request: BufferActivityCommandRequest): string { + return encode( + BufferActivityCommandRequestTypes.START, writeUInt64(request.start), + BufferActivityCommandRequestTypes.DURATION, writeUInt64(request.duration), + BufferActivityCommandRequestTypes.ACTIVITY, writeUInt8(request.activity), + ).toString('base64') +} + +/** + * Decodes a Buffer Activity Command write. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeBufferActivityCommandRequest(value: string): BufferActivityCommandRequest { + const fields = decodeBase64Fields(value) + + return { + start: readUInt64(requiredField(fields, BufferActivityCommandRequestTypes.START, 'Start')), + duration: readUInt64(requiredField(fields, BufferActivityCommandRequestTypes.DURATION, 'Duration')), + activity: readEnum(requiredField(fields, BufferActivityCommandRequestTypes.ACTIVITY, 'Activity'), BUFFER_ACTIVITY_VALUES), + } +} + +/** + * Encodes a Buffer Event Command write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeBufferEventCommandRequest(request: BufferEventCommandRequest): string { + return Buffer.concat([ + encode( + BufferEventCommandRequestTypes.COMMAND, writeUInt8(request.command), + BufferEventCommandRequestTypes.SEQUENCE_NUMBER, writeUInt64(request.sequenceNumber), + ), + encodeOptional( + BufferEventCommandRequestTypes.LIMIT, + request.limit === undefined + ? undefined + : writeUInt64(request.limit), + ), + ]).toString('base64') +} + +/** + * Decodes a Buffer Event Command write. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeBufferEventCommandRequest(value: string): BufferEventCommandRequest { + const fields = decodeBase64Fields(value) + const limit = optionalField(fields, BufferEventCommandRequestTypes.LIMIT, 'Limit') + + return { + command: readEnum(requiredField(fields, BufferEventCommandRequestTypes.COMMAND, 'Command'), BUFFER_EVENT_COMMAND_TYPE_VALUES), + sequenceNumber: readUInt64(requiredField(fields, BufferEventCommandRequestTypes.SEQUENCE_NUMBER, 'Sequence Number')), + ...(limit && { + limit: readUInt64(limit), + }), + } +} + +/** + * Encodes the write response of Buffer Event Command. + * @param response - The response's model. + * @returns The base64 characteristic value. + */ +export function encodeBufferEventCommandResponse(response: BufferEventCommandResponse): string { + return encode(BufferEventCommandResponseTypes.EVENTS, response.events.map(encodeCameraBufferEvent)).toString('base64') +} + +/** + * Decodes the write response of Buffer Event Command. + * @param value - The base64 characteristic value. + * @returns The response's model. + */ +export function decodeBufferEventCommandResponse(value: string): BufferEventCommandResponse { + return { + events: listField(decodeBase64Fields(value), BufferEventCommandResponseTypes.EVENTS).map(decodeCameraBufferEvent), + } +} + +/** + * Encodes a Camera Recording Publishing Point value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraRecordingPublishingPoint(payload: CameraRecordingPublishingPointPayload): string { + return encode( + CameraRecordingPublishingPointTypes.URL, writeString(payload.url), + CameraRecordingPublishingPointTypes.SERVER_CA_CERTIFICATES, payload.serverCACertificates.map(encodePublishingPointCertificate), + ).toString('base64') +} + +/** + * Decodes a Camera Recording Publishing Point value. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeCameraRecordingPublishingPoint(value: string): CameraRecordingPublishingPointPayload { + const fields = decodeBase64Fields(value) + + return { + url: readString(requiredField(fields, CameraRecordingPublishingPointTypes.URL, 'URL')), + serverCACertificates: listField(fields, CameraRecordingPublishingPointTypes.SERVER_CA_CERTIFICATES).map(decodePublishingPointCertificate), + } +} diff --git a/src/lib/camera/capabilities/cameraSensors.spec.ts b/src/lib/camera/capabilities/cameraSensors.spec.ts new file mode 100644 index 000000000..5d70d704f --- /dev/null +++ b/src/lib/camera/capabilities/cameraSensors.spec.ts @@ -0,0 +1,203 @@ +import type { CameraCapabilitiesPayload, ContributingSensorsPayload, SensorConfiguration } from './cameraSensors.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + CameraSensorIntent, + CameraSensorType, + decodeCameraCapabilities, + decodeContributingSensors, + encodeCameraCapabilities, + encodeContributingSensors, + sensorUUIDValue, +} from './cameraSensors.js' +import { CameraVideoQuality } from './streamTiers.js' + +// The golden vectors are computed from the spec's tables by an independent TLV8 writer, every integer little-endian at its table width. +const SENSOR_1 = '0a1b2c3d-4e5f-4061-8293-a4b5c6d7e8f9' +const SENSOR_2 = 'f0e1d2c3-b4a5-4697-8879-6a5b4c3d2e1f' + +function capabilityIdentifier(n: number): string { + return `c000000${n}-0000-4000-8000-00000000000${n}` +} + +const S1: SensorConfiguration = { + sensorDimensions: { width: 3840, height: 2160 }, + sensorUUID: SENSOR_1, + sensorType: CameraSensorType.PRIMARY, + sensorIntent: CameraSensorIntent.MAIN, + videoStreamCapabilities: [ + { + identifier: capabilityIdentifier(1), + videoQuality: CameraVideoQuality.HIGH, + width: 3840, + height: 2160, + framesPerSecond: 30, + averageBitRate: 4500, + peakBitRate: 5000, + }, + { + identifier: capabilityIdentifier(2), + videoQuality: CameraVideoQuality.MEDIUM, + width: 1920, + height: 1080, + framesPerSecond: 30, + averageBitRate: 1700, + peakBitRate: 1800, + }, + { + identifier: capabilityIdentifier(3), + videoQuality: CameraVideoQuality.LOW, + width: 640, + height: 360, + framesPerSecond: 15, + averageBitRate: 180, + peakBitRate: 190, + }, + ], +} + +const S2: SensorConfiguration = { + sensorDimensions: { width: 1600, height: 1200 }, + sensorUUID: SENSOR_2, + sensorType: CameraSensorType.GENERIC, + sensorIntent: CameraSensorIntent.PACKAGE, + videoStreamCapabilities: [ + { + identifier: capabilityIdentifier(4), + videoQuality: CameraVideoQuality.HIGH, + width: 1600, + height: 1200, + framesPerSecond: 30, + averageBitRate: 1700, + peakBitRate: 1800, + }, + { + identifier: capabilityIdentifier(5), + videoQuality: CameraVideoQuality.MEDIUM, + width: 1440, + height: 1080, + framesPerSecond: 30, + averageBitRate: 768, + peakBitRate: 800, + }, + { + identifier: capabilityIdentifier(6), + videoQuality: CameraVideoQuality.LOW, + width: 480, + height: 360, + framesPerSecond: 15, + averageBitRate: 180, + peakBitRate: 190, + }, + ], +} + +const CAMERA_CAPABILITIES_ONE_SENSOR: CameraCapabilitiesPayload = { + version: 1, + cameraSensors: [S1], +} +const CAMERA_CAPABILITIES_ONE_SENSOR_HEX = '01010102b201b001080102000f0202700802100a1b2c3d4e5f40618293a4b5c6d7e8f9030101040101052c0110c000000100004000800000' + + '00000000010201020302000f0402700805011e0604941100000704881300000000052c0110c0000002000040008000000000000002020103' + + '030280070402380405011e0604a40600000704080700000000052c0110c00000030000400080000000000000030201040302800204026801' + + '05010f0604b40000000704be000000' + +// The Camera Sensors item is longer than 255 bytes, and it fragments. +const CAMERA_CAPABILITIES_TWO_SENSORS: CameraCapabilitiesPayload = { + version: 1, + cameraSensors: [S1, S2], +} +const CAMERA_CAPABILITIES_TWO_SENSORS_HEX = '01010102ff01b001080102000f0202700802100a1b2c3d4e5f40618293a4b5c6d7e8f9030101040101052c0110c000000100004000800000' + + '00000000010201020302000f0402700805011e0604941100000704881300000000052c0110c0000002000040008000000000000002020103' + + '030280070402380405011e0604a40600000704080700000000052c0110c00000030000400080000000000000030201040302800204026801' + + '05010f0604b40000000704be000000000001b00108010240060202b0040210f0e1d2c3b4a5469788796a5b4c3d2e1f0301ff040102052c01' + + '10c0000004000040008000000000000004020102030240060402b00405011e0604a406000267000704080700000000052c0110c000000500' + + '00400080000000000000050201030302a0050402380405011e0604000300000704200300000000052c0110c0000006000040008000000000' + + '0000060201040302e0010402680105010f0604b40000000704be000000' + +const CONTRIBUTING_SENSORS: ContributingSensorsPayload = { + sensorList: [ + { sensorUUID: SENSOR_1 }, + { sensorUUID: SENSOR_2 }, + ], +} +const CONTRIBUTING_SENSORS_HEX = '011201100a1b2c3d4e5f40618293a4b5c6d7e8f9000001120110f0e1d2c3b4a5469788796a5b4c3d2e1f' + +const CONTRIBUTING_SENSORS_EMPTY: ContributingSensorsPayload = { sensorList: [] } +const CONTRIBUTING_SENSORS_EMPTY_HEX = '0100' + +// The one-sensor value with the sensor dimensions' Width one byte long, every enclosing length recomputed. +const ONE_BYTE_SENSOR_WIDTH_CAPABILITIES_HEX = '01010102b101af01070101000202700802100a1b2c3d4e5f40618293a4b5c6d7e8f9030101040101052c0110c00000010000400080000000' + + '000000010201020302000f0402700805011e0604941100000704881300000000052c0110c000000200004000800000000000000202010303' + + '0280070402380405011e0604a40600000704080700000000052c0110c0000003000040008000000000000003020104030280020402680105' + + '010f0604b40000000704be000000' + +describe('camera sensors', () => { + it('encodes and decodes camera capabilities with one sensor', () => { + const value = Buffer.from(CAMERA_CAPABILITIES_ONE_SENSOR_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraCapabilities(CAMERA_CAPABILITIES_ONE_SENSOR), 'base64').toString('hex')).toBe(CAMERA_CAPABILITIES_ONE_SENSOR_HEX) + expect(decodeCameraCapabilities(value)).toEqual(CAMERA_CAPABILITIES_ONE_SENSOR) + }) + + it('encodes and decodes camera capabilities with two sensors, their camera sensors item fragmenting', () => { + const value = Buffer.from(CAMERA_CAPABILITIES_TWO_SENSORS_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraCapabilities(CAMERA_CAPABILITIES_TWO_SENSORS), 'base64').toString('hex')).toBe(CAMERA_CAPABILITIES_TWO_SENSORS_HEX) + expect(decodeCameraCapabilities(value)).toEqual(CAMERA_CAPABILITIES_TWO_SENSORS) + }) + + it('encodes and decodes contributing sensors', () => { + const value = Buffer.from(CONTRIBUTING_SENSORS_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeContributingSensors(CONTRIBUTING_SENSORS), 'base64').toString('hex')).toBe(CONTRIBUTING_SENSORS_HEX) + expect(decodeContributingSensors(value)).toEqual(CONTRIBUTING_SENSORS) + }) + + it('encodes and decodes an empty contributing sensors list', () => { + const value = Buffer.from(CONTRIBUTING_SENSORS_EMPTY_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeContributingSensors(CONTRIBUTING_SENSORS_EMPTY), 'base64').toString('hex')).toBe(CONTRIBUTING_SENSORS_EMPTY_HEX) + expect(decodeContributingSensors(value)).toEqual(CONTRIBUTING_SENSORS_EMPTY) + }) + + it('ignores an unknown tag', () => { + const value = Buffer.from(`${CAMERA_CAPABILITIES_ONE_SENSOR_HEX}ff0100`, 'hex').toString('base64') + + expect(decodeCameraCapabilities(value)).toEqual(CAMERA_CAPABILITIES_ONE_SENSOR) + }) + + it('refuses a value without its version, naming the field', () => { + const value = Buffer.from(CAMERA_CAPABILITIES_ONE_SENSOR_HEX.replace(/^010101/, ''), 'hex').toString('base64') + + expect(() => decodeCameraCapabilities(value)).toThrow('The Version field is missing.') + }) + + it('decodes a sensor whose width is one byte long', () => { + const value = Buffer.from(ONE_BYTE_SENSOR_WIDTH_CAPABILITIES_HEX, 'hex').toString('base64') + + expect(decodeCameraCapabilities(value)).toEqual({ + version: 1, + cameraSensors: [ + { + ...S1, + sensorDimensions: { width: 0, height: 2160 }, + }, + ], + }) + }) + + it('refuses a sensor width three bytes long, naming the field', () => { + const value = Buffer.from(CAMERA_CAPABILITIES_ONE_SENSOR_HEX.replace('02b201b001080102000f', '02b301b101090103000f00'), 'hex').toString('base64') + + expect(() => decodeCameraCapabilities(value)).toThrow(RangeError) + expect(() => decodeCameraCapabilities(value)).toThrow('The Width field is 3 bytes long, but its format takes at most 2 bytes.') + }) + + it('encodes a sensor uuid value from the uuid in either case', () => { + expect(sensorUUIDValue('a1b2c3d4-0000-4000-8000-000000000001')).toBe('obLD1AAAQACAAAAAAAAAAQ==') + expect(sensorUUIDValue('A1B2C3D4-0000-4000-8000-000000000001')).toBe('obLD1AAAQACAAAAAAAAAAQ==') + }) +}) diff --git a/src/lib/camera/capabilities/cameraSensors.ts b/src/lib/camera/capabilities/cameraSensors.ts new file mode 100644 index 000000000..68b601a57 --- /dev/null +++ b/src/lib/camera/capabilities/cameraSensors.ts @@ -0,0 +1,354 @@ +import type { Buffer } from 'node:buffer' + +import type { CameraVideoQuality } from './streamTiers.js' + +import { encode } from '../../util/tlv.js' +import { CAMERA_VIDEO_QUALITY_VALUES } from './streamTiers.js' +import { + decodeBase64Fields, + decodeFields, + listField, + readEnum, + readUInt8, + readUInt16, + readUInt32, + readUUID, + requiredField, + writeUInt8, + writeUInt16, + writeUInt32, + writeUUID, +} from './tlvFields.js' + +const CameraCapabilitiesTypes = { + VERSION: 0x01, + CAMERA_SENSORS: 0x02, +} as const + +const CameraSensorsTypes = { + CAMERA_SENSORS: 0x01, +} as const + +const SensorConfigurationTypes = { + SENSOR_DIMENSIONS: 0x01, + SENSOR_UUID: 0x02, + SENSOR_TYPE: 0x03, + SENSOR_INTENT: 0x04, + VIDEO_STREAM_CAPABILITIES: 0x05, +} as const + +const SensorDimensionsTypes = { + WIDTH: 0x01, + HEIGHT: 0x02, +} as const + +const CameraVideoStreamCapabilitiesTypes = { + IDENTIFIER: 0x01, + VIDEO_QUALITY: 0x02, + WIDTH: 0x03, + HEIGHT: 0x04, + FRAMES_PER_SECOND: 0x05, + AVERAGE_BIT_RATE: 0x06, + PEAK_BIT_RATE: 0x07, +} as const + +const ContributingSensorsTypes = { + SENSOR_LIST: 0x01, +} as const + +const ContributingSensorTypes = { + SENSOR_UUID: 0x01, +} as const + +/** + * The specification version a camera's Version characteristics carry, beside Camera Capabilities and every other service that names it. A hub reads the + * Camera Capabilities service with this version as the sign that the camera implements the specification. + */ +export const CAMERA_SPECIFICATION_VERSION = '17.99' + +/** + * The version of the Camera Capabilities data, the Version field of its value, the one the hubs accept. + */ +export const CAMERA_CAPABILITIES_DATA_VERSION = 1 + +/** + * The type of a camera sensor. + */ +export const CameraSensorType = { + UNKNOWN: 0, + PRIMARY: 1, + GENERIC: 255, +} as const + +export type CameraSensorType = (typeof CameraSensorType)[keyof typeof CameraSensorType] + +const CAMERA_SENSOR_TYPE_VALUES: ReadonlySet = new Set(Object.values(CameraSensorType)) + +/** + * What a camera sensor is meant to watch. A plugin reads it through `api.hap`, as in `hap.CameraSensorIntent.MAIN`. + * @enum + * @group Camera + */ +export const CameraSensorIntent = { + UNKNOWN: 0, + MAIN: 1, + PACKAGE: 2, + GENERIC: 255, +} as const + +export type CameraSensorIntent = (typeof CameraSensorIntent)[keyof typeof CameraSensorIntent] + +/** + * The values of {@link CameraSensorIntent}, which the options boundary reads as well. + */ +export const CAMERA_SENSOR_INTENT_VALUES: ReadonlySet = new Set(Object.values(CameraSensorIntent)) + +/** + * The dimensions of a camera sensor, in pixels of sensor space, whose top-left corner is pixel (0, 0). + * @group Camera + */ +export interface SensorDimensions { + /** + * The width, in pixels. + */ + width: number + /** + * The height, in pixels. + */ + height: number +} + +/** + * One video configuration a camera sensor supports. + */ +export interface CameraVideoStreamCapabilities { + /** + * The UUID identifying this video configuration, an identifier space apart from the stream tiers' uint32 identifiers. + */ + identifier: string + /** + * The configuration's quality class. The spec names no enumeration for this field, which is why it reads the stream tiers' quality classes. + */ + videoQuality: CameraVideoQuality + /** + * The width, in pixels. + */ + width: number + /** + * The height, in pixels. + */ + height: number + /** + * The frame rate, in frames per second. + */ + framesPerSecond: number + /** + * The average bit rate, in kbps. + */ + averageBitRate: number + /** + * The peak bit rate, in kbps. + */ + peakBitRate: number +} + +/** + * The configuration of one camera sensor. + */ +export interface SensorConfiguration { + /** + * The sensor's dimensions. + */ + sensorDimensions: SensorDimensions + /** + * The sensor's UUID. + */ + sensorUUID: string + /** + * The sensor's type. A sensor labelled Primary comes first in the order the camera controller's `cameraCapabilities.videoSensors` option documents. + */ + sensorType: CameraSensorType + /** + * What the sensor is meant to watch. + */ + sensorIntent: CameraSensorIntent + /** + * One entry per video configuration the sensor supports. + */ + videoStreamCapabilities: CameraVideoStreamCapabilities[] +} + +/** + * The value of Camera Capabilities, which advertises what a camera can do. The spec's Camera Sensors TLV8 holds only its list, which is why the list is carried here + * directly. + */ +export interface CameraCapabilitiesPayload { + /** + * The version of the capabilities data. + */ + version: number + /** + * One entry per camera sensor. + */ + cameraSensors: SensorConfiguration[] +} + +/** + * One sensor that contributed to the motion currently detected. + */ +export interface ContributingSensor { + /** + * The sensor's UUID. + */ + sensorUUID: string +} + +/** + * The value of Contributing Sensors: the sensors that contributed to the motion currently detected. + */ +export interface ContributingSensorsPayload { + /** + * One entry per contributing sensor. + */ + sensorList: ContributingSensor[] +} + +function encodeCameraVideoStreamCapabilities(capabilities: CameraVideoStreamCapabilities): Buffer { + return encode( + CameraVideoStreamCapabilitiesTypes.IDENTIFIER, writeUUID(capabilities.identifier, 'Identifier'), + CameraVideoStreamCapabilitiesTypes.VIDEO_QUALITY, writeUInt8(capabilities.videoQuality), + CameraVideoStreamCapabilitiesTypes.WIDTH, writeUInt16(capabilities.width), + CameraVideoStreamCapabilitiesTypes.HEIGHT, writeUInt16(capabilities.height), + CameraVideoStreamCapabilitiesTypes.FRAMES_PER_SECOND, writeUInt8(capabilities.framesPerSecond), + CameraVideoStreamCapabilitiesTypes.AVERAGE_BIT_RATE, writeUInt32(capabilities.averageBitRate), + CameraVideoStreamCapabilitiesTypes.PEAK_BIT_RATE, writeUInt32(capabilities.peakBitRate), + ) +} + +function decodeCameraVideoStreamCapabilities(buffer: Buffer): CameraVideoStreamCapabilities { + const fields = decodeFields(buffer) + + return { + identifier: readUUID(requiredField(fields, CameraVideoStreamCapabilitiesTypes.IDENTIFIER, 'Identifier')), + videoQuality: readEnum(requiredField(fields, CameraVideoStreamCapabilitiesTypes.VIDEO_QUALITY, 'Video Quality'), + CAMERA_VIDEO_QUALITY_VALUES), + width: readUInt16(requiredField(fields, CameraVideoStreamCapabilitiesTypes.WIDTH, 'Width')), + height: readUInt16(requiredField(fields, CameraVideoStreamCapabilitiesTypes.HEIGHT, 'Height')), + framesPerSecond: readUInt8(requiredField(fields, CameraVideoStreamCapabilitiesTypes.FRAMES_PER_SECOND, 'Frames Per Second')), + averageBitRate: readUInt32(requiredField(fields, CameraVideoStreamCapabilitiesTypes.AVERAGE_BIT_RATE, 'Average Bit Rate')), + peakBitRate: readUInt32(requiredField(fields, CameraVideoStreamCapabilitiesTypes.PEAK_BIT_RATE, 'Peak Bit Rate')), + } +} + +function encodeSensorDimensions(dimensions: SensorDimensions): Buffer { + return encode( + SensorDimensionsTypes.WIDTH, writeUInt16(dimensions.width), + SensorDimensionsTypes.HEIGHT, writeUInt16(dimensions.height), + ) +} + +function decodeSensorDimensions(buffer: Buffer): SensorDimensions { + const fields = decodeFields(buffer) + + return { + width: readUInt16(requiredField(fields, SensorDimensionsTypes.WIDTH, 'Width')), + height: readUInt16(requiredField(fields, SensorDimensionsTypes.HEIGHT, 'Height')), + } +} + +/** + * Encodes one Sensor Configuration TLV8, the entry a Camera Capabilities value lists per sensor. + * @param sensor - The sensor's configuration. + * @returns The encoded TLV8. + */ +export function encodeSensorConfiguration(sensor: SensorConfiguration): Buffer { + return encode( + SensorConfigurationTypes.SENSOR_DIMENSIONS, encodeSensorDimensions(sensor.sensorDimensions), + SensorConfigurationTypes.SENSOR_UUID, writeUUID(sensor.sensorUUID, 'Sensor UUID'), + SensorConfigurationTypes.SENSOR_TYPE, writeUInt8(sensor.sensorType), + SensorConfigurationTypes.SENSOR_INTENT, writeUInt8(sensor.sensorIntent), + SensorConfigurationTypes.VIDEO_STREAM_CAPABILITIES, sensor.videoStreamCapabilities.map(encodeCameraVideoStreamCapabilities), + ) +} + +function decodeSensorConfiguration(buffer: Buffer): SensorConfiguration { + const fields = decodeFields(buffer) + + return { + sensorDimensions: decodeSensorDimensions(requiredField(fields, SensorConfigurationTypes.SENSOR_DIMENSIONS, 'Sensor Dimensions').value), + sensorUUID: readUUID(requiredField(fields, SensorConfigurationTypes.SENSOR_UUID, 'Sensor UUID')), + sensorType: readEnum(requiredField(fields, SensorConfigurationTypes.SENSOR_TYPE, 'Sensor Type'), CAMERA_SENSOR_TYPE_VALUES), + sensorIntent: readEnum(requiredField(fields, SensorConfigurationTypes.SENSOR_INTENT, 'Sensor Intent'), CAMERA_SENSOR_INTENT_VALUES), + videoStreamCapabilities: listField(fields, SensorConfigurationTypes.VIDEO_STREAM_CAPABILITIES).map(decodeCameraVideoStreamCapabilities), + } +} + +function encodeContributingSensor(sensor: ContributingSensor): Buffer { + return encode(ContributingSensorTypes.SENSOR_UUID, writeUUID(sensor.sensorUUID, 'Sensor UUID')) +} + +function decodeContributingSensor(buffer: Buffer): ContributingSensor { + const fields = decodeFields(buffer) + + return { + sensorUUID: readUUID(requiredField(fields, ContributingSensorTypes.SENSOR_UUID, 'Sensor UUID')), + } +} + +/** + * Encodes a Camera Capabilities value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraCapabilities(payload: CameraCapabilitiesPayload): string { + return encode( + CameraCapabilitiesTypes.VERSION, writeUInt8(payload.version), + CameraCapabilitiesTypes.CAMERA_SENSORS, encode(CameraSensorsTypes.CAMERA_SENSORS, payload.cameraSensors.map(encodeSensorConfiguration)), + ).toString('base64') +} + +/** + * Decodes a Camera Capabilities value. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeCameraCapabilities(value: string): CameraCapabilitiesPayload { + const fields = decodeBase64Fields(value) + const cameraSensors = decodeFields(requiredField(fields, CameraCapabilitiesTypes.CAMERA_SENSORS, 'Camera Sensors').value) + + return { + version: readUInt8(requiredField(fields, CameraCapabilitiesTypes.VERSION, 'Version')), + cameraSensors: listField(cameraSensors, CameraSensorsTypes.CAMERA_SENSORS).map(decodeSensorConfiguration), + } +} + +/** + * Encodes a Sensor UUID value, the sixteen bytes of the UUID that names the sensor a stream service serves. + * @param sensorUUID - The sensor's UUID, in upper or lower case. + * @returns The base64 characteristic value. + */ +export function sensorUUIDValue(sensorUUID: string): string { + return writeUUID(sensorUUID, 'Sensor UUID').toString('base64') +} + +/** + * Encodes a Contributing Sensors value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeContributingSensors(payload: ContributingSensorsPayload): string { + return encode(ContributingSensorsTypes.SENSOR_LIST, payload.sensorList.map(encodeContributingSensor)).toString('base64') +} + +/** + * Decodes a Contributing Sensors value. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeContributingSensors(value: string): ContributingSensorsPayload { + const fields = decodeBase64Fields(value) + + return { + sensorList: listField(fields, ContributingSensorsTypes.SENSOR_LIST).map(decodeContributingSensor), + } +} diff --git a/src/lib/camera/capabilities/index.ts b/src/lib/camera/capabilities/index.ts new file mode 100644 index 000000000..ac2a0cd1c --- /dev/null +++ b/src/lib/camera/capabilities/index.ts @@ -0,0 +1,8 @@ +// Only what a plugin writes or reads is exported, the sensor and zone types and the constant sets a plugin states: the wire models, the codecs and the +// field layer under them stay internal, because each export is a promise to keep. A set of named constants new to the library is declared as these +// are, a constant object with a type of its name, and an enum the library has released keeps its kind. +export type { SensorDimensions } from './cameraSensors.js' +export { CameraSensorIntent } from './cameraSensors.js' +export { CameraVideoQuality } from './streamTiers.js' +export type { CameraZoneData, CameraZonePolygon, CameraZoneVertex } from './zones.js' +export { CameraZoneApplicationMethod } from './zones.js' diff --git a/src/lib/camera/capabilities/provisioning.spec.ts b/src/lib/camera/capabilities/provisioning.spec.ts new file mode 100644 index 000000000..b04b6151a --- /dev/null +++ b/src/lib/camera/capabilities/provisioning.spec.ts @@ -0,0 +1,131 @@ +import type { + CameraClientCertificateRequest, + CameraClientCertificateStatusPayload, + CameraClientCSRRequest, + CameraClientCSRResponse, + CameraKeyIDPayload, + CameraKeyPayload, +} from './provisioning.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + decodeCameraClientCertificateRequest, + decodeCameraClientCertificateStatus, + decodeCameraClientCSRRequest, + decodeCameraClientCSRResponse, + decodeCameraKey, + decodeCameraKeyID, + encodeCameraClientCertificateRequest, + encodeCameraClientCertificateStatus, + encodeCameraClientCSRRequest, + encodeCameraClientCSRResponse, + encodeCameraKey, + encodeCameraKeyID, +} from './provisioning.js' + +// The golden vectors are computed from the spec's tables by an independent TLV8 writer, every integer little-endian at its table width. +const P53 = 2n ** 53n + 1n +const MAX64 = 2n ** 64n - 1n +const KEY_32 = Buffer.from('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', 'hex') +const NONCE = Buffer.from('202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f', 'hex') + +const CAMERA_KEY: CameraKeyPayload = { key: KEY_32, keyNumber: P53 } +const CAMERA_KEY_HEX = '0120000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f02080100000000002000' + +const CAMERA_KEY_ID: CameraKeyIDPayload = { keyID: MAX64 } +const CAMERA_KEY_ID_HEX = '0108ffffffffffffffff' + +const CAMERA_CLIENT_CSR_REQUEST: CameraClientCSRRequest = { nonce: NONCE } +const CAMERA_CLIENT_CSR_REQUEST_HEX = '0120202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f' + +const CAMERA_CLIENT_CSR_RESPONSE: CameraClientCSRResponse = { + csr: Buffer.from('3081020101', 'hex'), + nonceSignature: Buffer.from('304402200102', 'hex'), +} +const CAMERA_CLIENT_CSR_RESPONSE_HEX = '010530810201010206304402200102' + +const CAMERA_CLIENT_CERTIFICATE_REQUEST: CameraClientCertificateRequest = { + clientCertificate: Buffer.from('3082010a01', 'hex'), + ca: Buffer.from('3082010a02', 'hex'), +} +const CAMERA_CLIENT_CERTIFICATE_REQUEST_HEX = '01053082010a0102053082010a02' + +const CAMERA_CLIENT_CERTIFICATE_STATUS: CameraClientCertificateStatusPayload = { needsUpdate: true } +const CAMERA_CLIENT_CERTIFICATE_STATUS_HEX = '010101' + +// The camera key with its Key Number seven bytes long. +const SEVEN_BYTE_KEY_NUMBER_CAMERA_KEY_HEX = '0120000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f020701000000000020' + +describe('provisioning', () => { + it('encodes and decodes a camera key', () => { + const value = Buffer.from(CAMERA_KEY_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraKey(CAMERA_KEY), 'base64').toString('hex')).toBe(CAMERA_KEY_HEX) + expect(decodeCameraKey(value)).toEqual(CAMERA_KEY) + }) + + it('encodes and decodes a camera key id', () => { + const value = Buffer.from(CAMERA_KEY_ID_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraKeyID(CAMERA_KEY_ID), 'base64').toString('hex')).toBe(CAMERA_KEY_ID_HEX) + expect(decodeCameraKeyID(value)).toEqual(CAMERA_KEY_ID) + }) + + it('encodes and decodes a camera client csr request', () => { + const value = Buffer.from(CAMERA_CLIENT_CSR_REQUEST_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraClientCSRRequest(CAMERA_CLIENT_CSR_REQUEST), 'base64').toString('hex')).toBe(CAMERA_CLIENT_CSR_REQUEST_HEX) + expect(decodeCameraClientCSRRequest(value)).toEqual(CAMERA_CLIENT_CSR_REQUEST) + }) + + it('encodes and decodes a camera client csr response', () => { + const value = Buffer.from(CAMERA_CLIENT_CSR_RESPONSE_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraClientCSRResponse(CAMERA_CLIENT_CSR_RESPONSE), 'base64').toString('hex')).toBe(CAMERA_CLIENT_CSR_RESPONSE_HEX) + expect(decodeCameraClientCSRResponse(value)).toEqual(CAMERA_CLIENT_CSR_RESPONSE) + }) + + it('encodes and decodes a camera client certificate request', () => { + const value = Buffer.from(CAMERA_CLIENT_CERTIFICATE_REQUEST_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraClientCertificateRequest(CAMERA_CLIENT_CERTIFICATE_REQUEST), 'base64').toString('hex')) + .toBe(CAMERA_CLIENT_CERTIFICATE_REQUEST_HEX) + expect(decodeCameraClientCertificateRequest(value)).toEqual(CAMERA_CLIENT_CERTIFICATE_REQUEST) + }) + + it('encodes and decodes a camera client certificate status', () => { + const value = Buffer.from(CAMERA_CLIENT_CERTIFICATE_STATUS_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraClientCertificateStatus(CAMERA_CLIENT_CERTIFICATE_STATUS), 'base64').toString('hex')) + .toBe(CAMERA_CLIENT_CERTIFICATE_STATUS_HEX) + expect(decodeCameraClientCertificateStatus(value)).toEqual(CAMERA_CLIENT_CERTIFICATE_STATUS) + }) + + it('ignores an unknown tag', () => { + const value = Buffer.from(`${CAMERA_KEY_HEX}ff0100`, 'hex').toString('base64') + + expect(decodeCameraKey(value)).toEqual(CAMERA_KEY) + }) + + it('refuses a camera key without its key, naming the field', () => { + const value = Buffer.from(CAMERA_KEY_HEX.replace(/^0120[0-9a-f]{64}/, ''), 'hex').toString('base64') + + expect(() => decodeCameraKey(value)).toThrow('The Key field is missing.') + }) + + it('decodes a camera key whose key number is seven bytes long', () => { + const value = Buffer.from(SEVEN_BYTE_KEY_NUMBER_CAMERA_KEY_HEX, 'hex').toString('base64') + + expect(decodeCameraKey(value)).toEqual(CAMERA_KEY) + }) + + it('refuses a key number nine bytes long, naming the field', () => { + const value = Buffer.from(CAMERA_KEY_HEX.replace(/02080100000000002000$/, '0209010000000000200000'), 'hex').toString('base64') + + expect(() => decodeCameraKey(value)).toThrow(RangeError) + expect(() => decodeCameraKey(value)).toThrow('The Key Number field is 9 bytes long, but its format takes at most 8 bytes.') + }) +}) diff --git a/src/lib/camera/capabilities/provisioning.ts b/src/lib/camera/capabilities/provisioning.ts new file mode 100644 index 000000000..8749d26fa --- /dev/null +++ b/src/lib/camera/capabilities/provisioning.ts @@ -0,0 +1,241 @@ +import type { Buffer } from 'node:buffer' + +import { encode } from '../../util/tlv.js' +import { decodeBase64Fields, readBoolean, readUInt64, requiredField, writeBoolean, writeUInt64 } from './tlvFields.js' + +const CameraKeyTypes = { + KEY: 0x01, + KEY_NUMBER: 0x02, +} as const + +const CameraKeyIDTypes = { + KEY_ID: 0x01, +} as const + +const CameraClientCSRRequestTypes = { + NONCE: 0x01, +} as const + +const CameraClientCSRResponseTypes = { + CSR: 0x01, + NONCE_SIGNATURE: 0x02, +} as const + +const CameraClientCertificateRequestTypes = { + CLIENT_CERTIFICATE: 0x01, + CA: 0x02, +} as const + +const CameraClientCertificateStatusTypes = { + NEEDS_UPDATE: 0x01, +} as const + +/** + * The value a controller writes to Camera Key, which the accessory never serves back. + */ +export interface CameraKeyPayload { + /** + * The key data. + */ + key: Buffer + /** + * The key number. + */ + keyNumber: bigint +} + +/** + * The value of Camera Key ID: the identifier of the accessory's key. + */ +export interface CameraKeyIDPayload { + /** + * The key's identifier. + */ + keyID: bigint +} + +/** + * A write to Camera Client CSR, which asks for a certificate signing request. + */ +export interface CameraClientCSRRequest { + /** + * The nonce, a random 32-byte string. + */ + nonce: Buffer +} + +/** + * The write response of Camera Client CSR. + */ +export interface CameraClientCSRResponse { + /** + * The certificate signing request, in DER format. + */ + csr: Buffer + /** + * The elliptic curve signature of the nonce, made with the CSR's private key. + */ + nonceSignature: Buffer +} + +/** + * A write to Camera Client Certificate, which provides the client certificate. + */ +export interface CameraClientCertificateRequest { + /** + * The issued client certificate, in DER format. + */ + clientCertificate: Buffer + /** + * The certificate authority of the client certificate, in DER format. + */ + ca: Buffer +} + +/** + * The value of Camera Client Certificate Status. + */ +export interface CameraClientCertificateStatusPayload { + /** + * Whether the client certificate is expiring or has expired, which means it needs an update. + */ + needsUpdate: boolean +} + +/** + * Encodes a Camera Key value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraKey(payload: CameraKeyPayload): string { + return encode( + CameraKeyTypes.KEY, payload.key, + CameraKeyTypes.KEY_NUMBER, writeUInt64(payload.keyNumber), + ).toString('base64') +} + +/** + * Decodes a Camera Key value. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeCameraKey(value: string): CameraKeyPayload { + const fields = decodeBase64Fields(value) + + return { + key: requiredField(fields, CameraKeyTypes.KEY, 'Key').value, + keyNumber: readUInt64(requiredField(fields, CameraKeyTypes.KEY_NUMBER, 'Key Number')), + } +} + +/** + * Encodes a Camera Key ID value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraKeyID(payload: CameraKeyIDPayload): string { + return encode(CameraKeyIDTypes.KEY_ID, writeUInt64(payload.keyID)).toString('base64') +} + +/** + * Decodes a Camera Key ID value. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeCameraKeyID(value: string): CameraKeyIDPayload { + return { + keyID: readUInt64(requiredField(decodeBase64Fields(value), CameraKeyIDTypes.KEY_ID, 'Key ID')), + } +} + +/** + * Encodes a Camera Client CSR write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraClientCSRRequest(request: CameraClientCSRRequest): string { + return encode(CameraClientCSRRequestTypes.NONCE, request.nonce).toString('base64') +} + +/** + * Decodes a Camera Client CSR write. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeCameraClientCSRRequest(value: string): CameraClientCSRRequest { + return { + nonce: requiredField(decodeBase64Fields(value), CameraClientCSRRequestTypes.NONCE, 'Nonce').value, + } +} + +/** + * Encodes the write response of Camera Client CSR. + * @param response - The response's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraClientCSRResponse(response: CameraClientCSRResponse): string { + return encode( + CameraClientCSRResponseTypes.CSR, response.csr, + CameraClientCSRResponseTypes.NONCE_SIGNATURE, response.nonceSignature, + ).toString('base64') +} + +/** + * Decodes the write response of Camera Client CSR. + * @param value - The base64 characteristic value. + * @returns The response's model. + */ +export function decodeCameraClientCSRResponse(value: string): CameraClientCSRResponse { + const fields = decodeBase64Fields(value) + + return { + csr: requiredField(fields, CameraClientCSRResponseTypes.CSR, 'CSR').value, + nonceSignature: requiredField(fields, CameraClientCSRResponseTypes.NONCE_SIGNATURE, 'Nonce Signature').value, + } +} + +/** + * Encodes a Camera Client Certificate write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraClientCertificateRequest(request: CameraClientCertificateRequest): string { + return encode( + CameraClientCertificateRequestTypes.CLIENT_CERTIFICATE, request.clientCertificate, + CameraClientCertificateRequestTypes.CA, request.ca, + ).toString('base64') +} + +/** + * Decodes a Camera Client Certificate write. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeCameraClientCertificateRequest(value: string): CameraClientCertificateRequest { + const fields = decodeBase64Fields(value) + + return { + clientCertificate: requiredField(fields, CameraClientCertificateRequestTypes.CLIENT_CERTIFICATE, 'Client Certificate').value, + ca: requiredField(fields, CameraClientCertificateRequestTypes.CA, 'CA').value, + } +} + +/** + * Encodes a Camera Client Certificate Status value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraClientCertificateStatus(payload: CameraClientCertificateStatusPayload): string { + return encode(CameraClientCertificateStatusTypes.NEEDS_UPDATE, writeBoolean(payload.needsUpdate)).toString('base64') +} + +/** + * Decodes a Camera Client Certificate Status value. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeCameraClientCertificateStatus(value: string): CameraClientCertificateStatusPayload { + return { + needsUpdate: readBoolean(requiredField(decodeBase64Fields(value), CameraClientCertificateStatusTypes.NEEDS_UPDATE, 'Needs Update')), + } +} diff --git a/src/lib/camera/capabilities/rtpStreaming.spec.ts b/src/lib/camera/capabilities/rtpStreaming.spec.ts new file mode 100644 index 000000000..d1194dc95 --- /dev/null +++ b/src/lib/camera/capabilities/rtpStreaming.spec.ts @@ -0,0 +1,102 @@ +import type { RTPStreamingControlRequest, RTPStreamingControlResponse } from './rtpStreaming.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + decodeRTPStreamingControlRequest, + decodeRTPStreamingControlResponse, + encodeRTPStreamingControlRequest, + encodeRTPStreamingControlResponse, + RTPStreamingCommand, + RTPStreamingStatus, +} from './rtpStreaming.js' + +// The golden vectors are computed from the spec's tables by an independent TLV8 writer, every integer little-endian at its table width. +const SESSION = 'e7f1c3a2-5b4d-4e6f-9a8b-0c1d2e3f4a5b' + +const RTP_STREAMING_CONTROL_START: RTPStreamingControlRequest = { + sessionIdentifier: SESSION, + command: RTPStreamingCommand.START, + videoTier: 2, + videoSSRC: 0x9A3F1C27, + audioTier: 1, + audioSSRC: 4294967295, +} +const RTP_STREAMING_CONTROL_START_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b0201020304020000000404271c3f9a0504010000000604ffffffff' + +const RTP_STREAMING_CONTROL_END: RTPStreamingControlRequest = { sessionIdentifier: SESSION, command: RTPStreamingCommand.END } +const RTP_STREAMING_CONTROL_END_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b020101' + +const RTP_STREAMING_CONTROL_RESPONSE: RTPStreamingControlResponse = { sessionIdentifier: SESSION, status: RTPStreamingStatus.NO_SUCH_STREAM } +const RTP_STREAMING_CONTROL_RESPONSE_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b020102' + +// The start with its Video Tier three bytes long. +const THREE_BYTE_VIDEO_TIER_START_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b02010203030200000404271c3f9a0504010000000604ffffffff' + +// A start of the shape a hub writes, its Video Tier and Audio Tier each one byte long. +const HUB_START: RTPStreamingControlRequest = { + sessionIdentifier: 'a1b2c3d4-0000-4000-8000-0000000000c1', + command: RTPStreamingCommand.START, + videoTier: 3, + videoSSRC: 0xC1C2C3C4, + audioTier: 1, + audioSSRC: 0xD1D2D3D4, +} +const HUB_START_HEX = '0110a1b2c3d40000400080000000000000c10201020301030404c4c3c2c10501010604d4d3d2d1' + +describe('rtp streaming', () => { + it('encodes and decodes a start', () => { + const value = Buffer.from(RTP_STREAMING_CONTROL_START_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeRTPStreamingControlRequest(RTP_STREAMING_CONTROL_START), 'base64').toString('hex')).toBe(RTP_STREAMING_CONTROL_START_HEX) + expect(decodeRTPStreamingControlRequest(value)).toEqual(RTP_STREAMING_CONTROL_START) + }) + + it('encodes and decodes an end', () => { + const value = Buffer.from(RTP_STREAMING_CONTROL_END_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeRTPStreamingControlRequest(RTP_STREAMING_CONTROL_END), 'base64').toString('hex')).toBe(RTP_STREAMING_CONTROL_END_HEX) + expect(decodeRTPStreamingControlRequest(value)).toEqual(RTP_STREAMING_CONTROL_END) + }) + + it('encodes and decodes a status', () => { + const value = Buffer.from(RTP_STREAMING_CONTROL_RESPONSE_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeRTPStreamingControlResponse(RTP_STREAMING_CONTROL_RESPONSE), 'base64').toString('hex')) + .toBe(RTP_STREAMING_CONTROL_RESPONSE_HEX) + expect(decodeRTPStreamingControlResponse(value)).toEqual(RTP_STREAMING_CONTROL_RESPONSE) + }) + + it('ignores an unknown tag', () => { + const value = Buffer.from(`${RTP_STREAMING_CONTROL_START_HEX}ff0100`, 'hex').toString('base64') + + expect(decodeRTPStreamingControlRequest(value)).toEqual(RTP_STREAMING_CONTROL_START) + }) + + it('refuses a write without its session identifier, naming the field', () => { + const value = Buffer.from(RTP_STREAMING_CONTROL_START_HEX.replace(/^0110[0-9a-f]{32}/, ''), 'hex').toString('base64') + + expect(() => decodeRTPStreamingControlRequest(value)).toThrow('The Session Identifier field is missing.') + }) + + it('decodes a start whose video tier is three bytes long', () => { + const value = Buffer.from(THREE_BYTE_VIDEO_TIER_START_HEX, 'hex').toString('base64') + + expect(decodeRTPStreamingControlRequest(value)).toEqual(RTP_STREAMING_CONTROL_START) + }) + + it('decodes a start from a hub, both tiers one byte long', () => { + const value = Buffer.from(HUB_START_HEX, 'hex').toString('base64') + + expect(decodeRTPStreamingControlRequest(value)).toEqual(HUB_START) + }) + + it('refuses a video tier five bytes long, naming the field', () => { + const value = Buffer.from(RTP_STREAMING_CONTROL_START_HEX.replace('030402000000', '03050200000000'), 'hex').toString('base64') + + expect(() => decodeRTPStreamingControlRequest(value)).toThrow(RangeError) + expect(() => decodeRTPStreamingControlRequest(value)).toThrow('The Video Tier field is 5 bytes long, but its format takes at most 4 bytes.') + }) +}) diff --git a/src/lib/camera/capabilities/rtpStreaming.ts b/src/lib/camera/capabilities/rtpStreaming.ts new file mode 100644 index 000000000..188a74b0a --- /dev/null +++ b/src/lib/camera/capabilities/rtpStreaming.ts @@ -0,0 +1,177 @@ +import { Buffer } from 'node:buffer' + +import { encode } from '../../util/tlv.js' +import { decodeBase64Fields, readEnum, readUInt32, readUUID, requiredField, writeUInt8, writeUInt32, writeUUID } from './tlvFields.js' + +const RTPStreamingControlTypes = { + SESSION_IDENTIFIER: 0x01, + COMMAND: 0x02, + VIDEO_TIER: 0x03, + VIDEO_SSRC: 0x04, + AUDIO_TIER: 0x05, + AUDIO_SSRC: 0x06, +} as const + +const RTPStreamingStatusTypes = { + SESSION_IDENTIFIER: 0x01, + STATUS: 0x02, +} as const + +/** + * The command an RTP Streaming Control write carries. + */ +export const RTPStreamingCommand = { + END: 1, + START: 2, +} as const + +export type RTPStreamingCommand = (typeof RTPStreamingCommand)[keyof typeof RTPStreamingCommand] + +const RTP_STREAMING_COMMAND_VALUES: ReadonlySet = new Set(Object.values(RTPStreamingCommand)) + +/** + * The status of an RTP Streaming Control command. + */ +export const RTPStreamingStatus = { + SUCCESS: 0, + UNKNOWN_SESSION_IDENTIFIER: 1, + /** + * An end for a stream that is not started. + */ + NO_SUCH_STREAM: 2, + BUSY: 3, + ERROR: 4, +} as const + +export type RTPStreamingStatus = (typeof RTPStreamingStatus)[keyof typeof RTPStreamingStatus] + +const RTP_STREAMING_STATUS_VALUES: ReadonlySet = new Set(Object.values(RTPStreamingStatus)) + +/** + * A write to RTP Streaming Control, a union on its command: only a start names the tiers and SSRCs of the stream, as the spec sends them only with one. + */ +export type RTPStreamingControlRequest = { + /** + * The UUID identifying the session, the one written to Setup Endpoints. + */ + sessionIdentifier: string + /** + * The command. + */ + command: typeof RTPStreamingCommand.END +} | { + /** + * The UUID identifying the session, the one written to Setup Endpoints. + */ + sessionIdentifier: string + /** + * The command. + */ + command: typeof RTPStreamingCommand.START + /** + * The identifier of the video tier to stream, one that Supported Video Stream Tiers advertises. + */ + videoTier: number + /** + * The SSRC of the video RTP stream. + */ + videoSSRC: number + /** + * The identifier of the audio tier to stream, one that Supported Audio Stream Tiers advertises. + */ + audioTier: number + /** + * The SSRC of the audio RTP stream. + */ + audioSSRC: number +} + +/** + * The status of an RTP Streaming Control command, which both its write response and the next read of the characteristic carry. + */ +export interface RTPStreamingControlResponse { + /** + * The UUID identifying the session, the one the command named. + */ + sessionIdentifier: string + /** + * The command's status. + */ + status: RTPStreamingStatus +} + +/** + * Encodes an RTP Streaming Control write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeRTPStreamingControlRequest(request: RTPStreamingControlRequest): string { + const commandFields = encode( + RTPStreamingControlTypes.SESSION_IDENTIFIER, writeUUID(request.sessionIdentifier, 'Session Identifier'), + RTPStreamingControlTypes.COMMAND, writeUInt8(request.command), + ) + + if (request.command === RTPStreamingCommand.END) { + return commandFields.toString('base64') + } + + return Buffer.concat([ + commandFields, + encode( + RTPStreamingControlTypes.VIDEO_TIER, writeUInt32(request.videoTier), + RTPStreamingControlTypes.VIDEO_SSRC, writeUInt32(request.videoSSRC), + RTPStreamingControlTypes.AUDIO_TIER, writeUInt32(request.audioTier), + RTPStreamingControlTypes.AUDIO_SSRC, writeUInt32(request.audioSSRC), + ), + ]).toString('base64') +} + +/** + * Decodes an RTP Streaming Control write. An end ignores any tier or SSRC field it carries. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeRTPStreamingControlRequest(value: string): RTPStreamingControlRequest { + const fields = decodeBase64Fields(value) + const sessionIdentifier = readUUID(requiredField(fields, RTPStreamingControlTypes.SESSION_IDENTIFIER, 'Session Identifier')) + const command = readEnum(requiredField(fields, RTPStreamingControlTypes.COMMAND, 'Command'), RTP_STREAMING_COMMAND_VALUES) + + if (command === RTPStreamingCommand.END) { + return { sessionIdentifier, command } + } + + return { + sessionIdentifier, + command, + videoTier: readUInt32(requiredField(fields, RTPStreamingControlTypes.VIDEO_TIER, 'Video Tier')), + videoSSRC: readUInt32(requiredField(fields, RTPStreamingControlTypes.VIDEO_SSRC, 'Video SSRC')), + audioTier: readUInt32(requiredField(fields, RTPStreamingControlTypes.AUDIO_TIER, 'Audio Tier')), + audioSSRC: readUInt32(requiredField(fields, RTPStreamingControlTypes.AUDIO_SSRC, 'Audio SSRC')), + } +} + +/** + * Encodes the status of an RTP Streaming Control command. + * @param response - The status's model. + * @returns The base64 characteristic value. + */ +export function encodeRTPStreamingControlResponse(response: RTPStreamingControlResponse): string { + return encode( + RTPStreamingStatusTypes.SESSION_IDENTIFIER, writeUUID(response.sessionIdentifier, 'Session Identifier'), + RTPStreamingStatusTypes.STATUS, writeUInt8(response.status), + ).toString('base64') +} + +/** + * Decodes the status of an RTP Streaming Control command. + * @param value - The base64 characteristic value. + * @returns The status's model. + */ +export function decodeRTPStreamingControlResponse(value: string): RTPStreamingControlResponse { + const fields = decodeBase64Fields(value) + + return { + sessionIdentifier: readUUID(requiredField(fields, RTPStreamingStatusTypes.SESSION_IDENTIFIER, 'Session Identifier')), + status: readEnum(requiredField(fields, RTPStreamingStatusTypes.STATUS, 'Status'), RTP_STREAMING_STATUS_VALUES), + } +} diff --git a/src/lib/camera/capabilities/setupEndpoints.ts b/src/lib/camera/capabilities/setupEndpoints.ts new file mode 100644 index 000000000..ee678420d --- /dev/null +++ b/src/lib/camera/capabilities/setupEndpoints.ts @@ -0,0 +1,347 @@ +import { Buffer } from 'node:buffer' + +import { encode } from '../../util/tlv.js' +import { + decodeBase64Fields, + decodeFields, + optionalField, + readEnum, + readString, + readUInt16, + readUInt32, + readUUID, + requiredField, + writeString, + writeUInt8, + writeUInt16, + writeUInt32, + writeUUID, +} from './tlvFields.js' + +/* The Setup Endpoints codec, one for every stream management service that carries the characteristic, because the hubs write the same R15 bytes to the + * legacy and the multi-tier service alike. The tag enums carry the names the stream management spec's comments use for R15's tables. A key and a salt are + * carried as their raw bytes with no length rule, and the Disabled suite reads an absent key or salt as zero-length, the form R15 requires that suite to + * send. + */ + +enum SetupEndpointsTypes { + SESSION_ID = 0x01, + CONTROLLER_ADDRESS = 0x03, + VIDEO_SRTP_PARAMETERS = 0x04, + AUDIO_SRTP_PARAMETERS = 0x05, +} + +enum AddressTypes { + ADDRESS_VERSION = 0x01, + ADDRESS = 0x02, + VIDEO_RTP_PORT = 0x03, + AUDIO_RTP_PORT = 0x04, +} + +enum IPAddressVersion { + IPV4 = 0x00, + IPV6 = 0x01, +} + +const IP_ADDRESS_VERSION_VALUES: ReadonlySet = new Set([ + IPAddressVersion.IPV4, + IPAddressVersion.IPV6, +]) + +enum SRTPParametersTypes { + SRTP_CRYPTO_SUITE = 0x01, + MASTER_KEY = 0x02, + MASTER_SALT = 0x03, +} + +enum SetupEndpointsResponseTypes { + SESSION_ID = 0x01, + STATUS = 0x02, + ACCESSORY_ADDRESS = 0x03, + VIDEO_SRTP_PARAMETERS = 0x04, + AUDIO_SRTP_PARAMETERS = 0x05, + VIDEO_SSRC = 0x06, + AUDIO_SSRC = 0x07, +} + +/** + * @group Camera + */ +export enum SRTPCryptoSuites { // public API + AES_CM_128_HMAC_SHA1_80 = 0x00, + AES_CM_256_HMAC_SHA1_80 = 0x01, + NONE = 0x02, +} + +// The SRTP Crypto Suite values R15 defines, which every codec that reads the field decodes against. +export const SRTP_CRYPTO_SUITES_VALUES: ReadonlySet = new Set([ + SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + SRTPCryptoSuites.AES_CM_256_HMAC_SHA1_80, + SRTPCryptoSuites.NONE, +]) + +/** + * The status a Setup Endpoints answer carries. + */ +export enum SetupEndpointsStatus { + SUCCESS = 0, + /** + * Every stream the service offers is in use. + */ + BUSY = 1, + ERROR = 2, +} + +const SETUP_ENDPOINTS_STATUS_VALUES: ReadonlySet = new Set([ + SetupEndpointsStatus.SUCCESS, + SetupEndpointsStatus.BUSY, + SetupEndpointsStatus.ERROR, +]) + +/** + * The address and RTP ports of one end of a streaming session: the controller's in a Setup Endpoints write, the accessory's in its answer. + */ +export interface SetupEndpointsAddress { + /** + * The IP version of the address, which the answer's address shares with the write's. + */ + addressVersion: 'ipv4' | 'ipv6' + /** + * The IP address. + */ + address: string + /** + * The port that receives the video RTP stream. + */ + videoRTPPort: number + /** + * The port that receives the audio RTP stream, present even when audio and video share one port. + */ + audioRTPPort: number +} + +/** + * The SRTP crypto suite and keys of one stream of a session. + */ +export interface SRTPParameters { + /** + * The crypto suite. + */ + cryptoSuite: SRTPCryptoSuites + /** + * The master key: 16 bytes for AES_CM_128_HMAC_SHA1_80, 32 for AES_256_CM_HMAC_SHA1_80, and zero-length for the Disabled suite. + */ + masterKey: Buffer + /** + * The master salt: 14 bytes, and zero-length for the Disabled suite. + */ + masterSalt: Buffer +} + +/** + * A write to Setup Endpoints: the controller's end of a streaming session and the SRTP parameters of each stream. + */ +export interface SetupEndpointsRequest { + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The controller's address and ports. + */ + controllerAddress: SetupEndpointsAddress + /** + * The SRTP parameters of the video stream. + */ + videoSRTPParameters: SRTPParameters + /** + * The SRTP parameters of the audio stream. + */ + audioSRTPParameters: SRTPParameters +} + +/** + * The answer a read of Setup Endpoints carries, a union on its status: only a success names the accessory's end of the session, and a busy or an error + * names the session it answers when there is one, an error answering a read before any write naming none. + */ +export type SetupEndpointsResponse = { + /** + * The status. + */ + status: SetupEndpointsStatus.SUCCESS + /** + * The UUID identifying the session, the one the write named. + */ + sessionIdentifier: string + /** + * The accessory's address and ports, its IP version the write's. + */ + accessoryAddress: SetupEndpointsAddress + /** + * The SRTP parameters of the video stream. + */ + videoSRTPParameters: SRTPParameters + /** + * The SRTP parameters of the audio stream. + */ + audioSRTPParameters: SRTPParameters + /** + * The SSRC of the video RTP stream. + */ + videoSSRC: number + /** + * The SSRC of the audio RTP stream. + */ + audioSSRC: number +} | { + /** + * The status. + */ + status: SetupEndpointsStatus.BUSY | SetupEndpointsStatus.ERROR + /** + * The UUID identifying the session, the one the write named, absent from an answer to a read before any write. + */ + sessionIdentifier?: string +} + +function encodeAddress(address: SetupEndpointsAddress): Buffer { + return encode( + AddressTypes.ADDRESS_VERSION, writeUInt8(address.addressVersion === 'ipv6' + ? IPAddressVersion.IPV6 + : IPAddressVersion.IPV4), + AddressTypes.ADDRESS, writeString(address.address), + AddressTypes.VIDEO_RTP_PORT, writeUInt16(address.videoRTPPort), + AddressTypes.AUDIO_RTP_PORT, writeUInt16(address.audioRTPPort), + ) +} + +function decodeAddress(buffer: Buffer): SetupEndpointsAddress { + const fields = decodeFields(buffer) + const version = readEnum(requiredField(fields, AddressTypes.ADDRESS_VERSION, 'IP address version'), IP_ADDRESS_VERSION_VALUES) + + return { + addressVersion: version === IPAddressVersion.IPV6 + ? 'ipv6' + : 'ipv4', + address: readString(requiredField(fields, AddressTypes.ADDRESS, 'IP Address')), + videoRTPPort: readUInt16(requiredField(fields, AddressTypes.VIDEO_RTP_PORT, 'Video RTP port')), + audioRTPPort: readUInt16(requiredField(fields, AddressTypes.AUDIO_RTP_PORT, 'Audio RTP port')), + } +} + +function encodeSRTPParameters(parameters: SRTPParameters): Buffer { + return encode( + SRTPParametersTypes.SRTP_CRYPTO_SUITE, writeUInt8(parameters.cryptoSuite), + SRTPParametersTypes.MASTER_KEY, parameters.masterKey, + SRTPParametersTypes.MASTER_SALT, parameters.masterSalt, + ) +} + +function decodeSRTPParameters(buffer: Buffer): SRTPParameters { + const fields = decodeFields(buffer) + const cryptoSuite = readEnum(requiredField(fields, SRTPParametersTypes.SRTP_CRYPTO_SUITE, 'SRTP Crypto Suite'), SRTP_CRYPTO_SUITES_VALUES) + + // The Disabled suite sends a zero-length key and salt: an absent one reads the same, while every other suite needs the key and the salt. + const keyField = (tag: number, name: string): Buffer => cryptoSuite === SRTPCryptoSuites.NONE + ? optionalField(fields, tag, name)?.value ?? Buffer.alloc(0) + : requiredField(fields, tag, name).value + + return { + cryptoSuite, + masterKey: keyField(SRTPParametersTypes.MASTER_KEY, 'SRTP Master Key'), + masterSalt: keyField(SRTPParametersTypes.MASTER_SALT, 'SRTP Master Salt'), + } +} + +/** + * Decodes a Setup Endpoints write, checking every field before the caller changes any state. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeSetupEndpointsRequest(value: string): SetupEndpointsRequest { + const fields = decodeBase64Fields(value) + + return { + sessionIdentifier: readUUID(requiredField(fields, SetupEndpointsTypes.SESSION_ID, 'Session ID')), + controllerAddress: decodeAddress(requiredField(fields, SetupEndpointsTypes.CONTROLLER_ADDRESS, 'Controller Address').value), + videoSRTPParameters: decodeSRTPParameters(requiredField(fields, SetupEndpointsTypes.VIDEO_SRTP_PARAMETERS, 'SRTP Parameters for Video').value), + audioSRTPParameters: decodeSRTPParameters(requiredField(fields, SetupEndpointsTypes.AUDIO_SRTP_PARAMETERS, 'SRTP Parameters for Audio').value), + } +} + +/** + * Encodes a Setup Endpoints answer. + * @param response - The answer's model. + * @returns The base64 characteristic value. + */ +export function encodeSetupEndpointsResponse(response: SetupEndpointsResponse): string { + const session = response.sessionIdentifier === undefined + ? Buffer.alloc(0) + : encode(SetupEndpointsResponseTypes.SESSION_ID, writeUUID(response.sessionIdentifier, 'Session Identifier')) + const status = encode(SetupEndpointsResponseTypes.STATUS, writeUInt8(response.status)) + + if (response.status !== SetupEndpointsStatus.SUCCESS) { + return Buffer.concat([session, status]).toString('base64') + } + + return Buffer.concat([ + session, + status, + encode( + SetupEndpointsResponseTypes.ACCESSORY_ADDRESS, encodeAddress(response.accessoryAddress), + SetupEndpointsResponseTypes.VIDEO_SRTP_PARAMETERS, encodeSRTPParameters(response.videoSRTPParameters), + SetupEndpointsResponseTypes.AUDIO_SRTP_PARAMETERS, encodeSRTPParameters(response.audioSRTPParameters), + SetupEndpointsResponseTypes.VIDEO_SSRC, writeUInt32(response.videoSSRC), + SetupEndpointsResponseTypes.AUDIO_SSRC, writeUInt32(response.audioSSRC), + ), + ]).toString('base64') +} + +// The answer to a read from a connection that holds no answer of its own, before any write, after a refused one, without a connection or while +// streaming is disabled: Error, naming no session, as R15 requires of a read before any write. +export const SETUP_ENDPOINTS_ERROR = encodeSetupEndpointsResponse({ status: SetupEndpointsStatus.ERROR }) + +/** + * Encodes a Setup Endpoints write, as a controller sends it. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeSetupEndpointsRequest(request: SetupEndpointsRequest): string { + return encode( + SetupEndpointsTypes.SESSION_ID, writeUUID(request.sessionIdentifier, 'Session ID'), + SetupEndpointsTypes.CONTROLLER_ADDRESS, encodeAddress(request.controllerAddress), + SetupEndpointsTypes.VIDEO_SRTP_PARAMETERS, encodeSRTPParameters(request.videoSRTPParameters), + SetupEndpointsTypes.AUDIO_SRTP_PARAMETERS, encodeSRTPParameters(request.audioSRTPParameters), + ).toString('base64') +} + +/** + * Decodes a Setup Endpoints answer, as a controller reads it. + * @param value - The base64 characteristic value. + * @returns The answer's model. + */ +export function decodeSetupEndpointsResponse(value: string): SetupEndpointsResponse { + const fields = decodeBase64Fields(value) + const status = readEnum(requiredField(fields, SetupEndpointsResponseTypes.STATUS, 'Status'), SETUP_ENDPOINTS_STATUS_VALUES) + + if (status !== SetupEndpointsStatus.SUCCESS) { + const session = optionalField(fields, SetupEndpointsResponseTypes.SESSION_ID, 'Session Identifier') + + return session === undefined + ? { status } + : { + status, + sessionIdentifier: readUUID(session), + } + } + + return { + status, + sessionIdentifier: readUUID(requiredField(fields, SetupEndpointsResponseTypes.SESSION_ID, 'Session Identifier')), + accessoryAddress: decodeAddress(requiredField(fields, SetupEndpointsResponseTypes.ACCESSORY_ADDRESS, 'Accessory Address').value), + videoSRTPParameters: decodeSRTPParameters(requiredField(fields, SetupEndpointsResponseTypes.VIDEO_SRTP_PARAMETERS, 'SRTP Parameters for Video').value), + audioSRTPParameters: decodeSRTPParameters(requiredField(fields, SetupEndpointsResponseTypes.AUDIO_SRTP_PARAMETERS, 'SRTP Parameters for Audio').value), + videoSSRC: readUInt32(requiredField(fields, SetupEndpointsResponseTypes.VIDEO_SSRC, 'SynchronizationSource for Video')), + audioSSRC: readUInt32(requiredField(fields, SetupEndpointsResponseTypes.AUDIO_SSRC, 'SynchronizationSource for Audio')), + } +} diff --git a/src/lib/camera/capabilities/streamTiers.spec.ts b/src/lib/camera/capabilities/streamTiers.spec.ts new file mode 100644 index 000000000..1b1e26deb --- /dev/null +++ b/src/lib/camera/capabilities/streamTiers.spec.ts @@ -0,0 +1,112 @@ +import type { SupportedAudioStreamTiersPayload, SupportedVideoStreamTiersPayload } from './streamTiers.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + CameraVideoQuality, + decodeSupportedAudioStreamTiers, + decodeSupportedVideoStreamTiers, + encodeSupportedAudioStreamTiers, + encodeSupportedVideoStreamTiers, + TieredAudioBitDepth, + TieredAudioCodecType, + TieredAudioSampleRate, + TieredVideoCodecType, +} from './streamTiers.js' + +// The golden vectors are computed from the spec's tables by an independent TLV8 writer, every integer little-endian at its table width. +const SUPPORTED_VIDEO_STREAM_TIERS: SupportedVideoStreamTiersPayload = { + codec: TieredVideoCodecType.H265, + payloadType: 99, + tiers: [ + { + identifier: 1, + quality: CameraVideoQuality.HIGH, + targetAverageBitrate: 4500, + width: 3840, + height: 2160, + frameRate: 30, + }, + { + identifier: 2, + quality: CameraVideoQuality.MEDIUM, + targetAverageBitrate: 1700, + width: 1920, + height: 1080, + frameRate: 30, + }, + { + identifier: 4294967295, + quality: CameraVideoQuality.LOW, + targetAverageBitrate: 180, + width: 640, + height: 360, + frameRate: 15, + }, + ], +} +const SUPPORTED_VIDEO_STREAM_TIERS_HEX = '010102020163031a0104010000000201020304941100000402000f0502700806011e0000031a0104020000000201030304a4060000040280' + + '070502380406011e0000031a0104ffffffff0201040304b4000000040280020502680106010f' + +const SUPPORTED_AUDIO_STREAM_TIERS: SupportedAudioStreamTiersPayload = { + codec: TieredAudioCodecType.OPUS, + payloadType: 110, + tiers: [ + { + identifier: 1, + targetAverageBitrate: 24000, + sampleRate: TieredAudioSampleRate.KHZ_48, + bitDepth: TieredAudioBitDepth.BITS_16, + packetTime: 20, + numberOfChannels: 1, + }, + ], +} +const SUPPORTED_AUDIO_STREAM_TIERS_HEX = '01010302016e03180104010000000204c05d0000030104040102050114060101' + +// The first tier's Identifier three bytes long, every enclosing length recomputed. +const THREE_BYTE_IDENTIFIER_STREAM_TIERS_HEX = '010102020163031901030100000201020304941100000402000f0502700806011e0000031a0104020000000201030304a406000004028007' + + '0502380406011e0000031a0104ffffffff0201040304b4000000040280020502680106010f' + +describe('stream tiers', () => { + it('encodes and decodes supported video stream tiers', () => { + const value = Buffer.from(SUPPORTED_VIDEO_STREAM_TIERS_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeSupportedVideoStreamTiers(SUPPORTED_VIDEO_STREAM_TIERS), 'base64').toString('hex')).toBe(SUPPORTED_VIDEO_STREAM_TIERS_HEX) + expect(decodeSupportedVideoStreamTiers(value)).toEqual(SUPPORTED_VIDEO_STREAM_TIERS) + }) + + it('encodes and decodes supported audio stream tiers', () => { + const value = Buffer.from(SUPPORTED_AUDIO_STREAM_TIERS_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeSupportedAudioStreamTiers(SUPPORTED_AUDIO_STREAM_TIERS), 'base64').toString('hex')).toBe(SUPPORTED_AUDIO_STREAM_TIERS_HEX) + expect(decodeSupportedAudioStreamTiers(value)).toEqual(SUPPORTED_AUDIO_STREAM_TIERS) + }) + + it('ignores an unknown tag', () => { + const value = Buffer.from(`${SUPPORTED_VIDEO_STREAM_TIERS_HEX}ff0100`, 'hex').toString('base64') + + expect(decodeSupportedVideoStreamTiers(value)).toEqual(SUPPORTED_VIDEO_STREAM_TIERS) + }) + + it('refuses a value without its codec, naming the field', () => { + const value = Buffer.from(SUPPORTED_VIDEO_STREAM_TIERS_HEX.replace(/^010102/, ''), 'hex').toString('base64') + + expect(() => decodeSupportedVideoStreamTiers(value)).toThrow('The Codec field is missing.') + }) + + it('decodes a tier whose identifier is three bytes long', () => { + const value = Buffer.from(THREE_BYTE_IDENTIFIER_STREAM_TIERS_HEX, 'hex').toString('base64') + + expect(decodeSupportedVideoStreamTiers(value)).toEqual(SUPPORTED_VIDEO_STREAM_TIERS) + }) + + it('refuses a tier identifier five bytes long, naming the field', () => { + const value = Buffer.from(SUPPORTED_VIDEO_STREAM_TIERS_HEX.replace('031a010401000000', '031b01050100000000'), 'hex').toString('base64') + + expect(() => decodeSupportedVideoStreamTiers(value)).toThrow(RangeError) + expect(() => decodeSupportedVideoStreamTiers(value)).toThrow('The Identifier field is 5 bytes long, but its format takes at most 4 bytes.') + }) +}) diff --git a/src/lib/camera/capabilities/streamTiers.ts b/src/lib/camera/capabilities/streamTiers.ts new file mode 100644 index 000000000..07d84ea86 --- /dev/null +++ b/src/lib/camera/capabilities/streamTiers.ts @@ -0,0 +1,344 @@ +import type { Buffer } from 'node:buffer' + +import { encode } from '../../util/tlv.js' +import { + decodeBase64Fields, + decodeFields, + listField, + readEnum, + readUInt8, + readUInt16, + readUInt32, + requiredField, + writeUInt8, + writeUInt16, + writeUInt32, +} from './tlvFields.js' + +const SupportedVideoStreamTiersTypes = { + CODEC: 0x01, + PAYLOAD_TYPE: 0x02, + TIERS: 0x03, +} as const + +const VideoStreamTierTypes = { + IDENTIFIER: 0x01, + QUALITY: 0x02, + TARGET_AVERAGE_BITRATE: 0x03, + WIDTH: 0x04, + HEIGHT: 0x05, + FRAME_RATE: 0x06, +} as const + +const SupportedAudioStreamTiersTypes = { + CODEC: 0x01, + PAYLOAD_TYPE: 0x02, + TIERS: 0x03, +} as const + +const AudioStreamTierTypes = { + IDENTIFIER: 0x01, + TARGET_AVERAGE_BITRATE: 0x02, + SAMPLE_RATE: 0x03, + BIT_DEPTH: 0x04, + PACKET_TIME: 0x05, + NUMBER_OF_CHANNELS: 0x06, +} as const + +/** + * The video codecs the stream tier characteristics' wire format numbers, of which a camera's stream tiers take HEVC alone. + * + * It is a separate set from {@link VideoCodecType}, the RTP stream configuration's, which numbers H.264 0 where this one numbers it 1: the two are + * different wire vocabularies, and each keeps its own numbering. + */ +export const TieredVideoCodecType = { + /** + * Advanced Video Coding (AVC). + */ + H264: 1, + /** + * High Efficiency Video Coding (HEVC). + */ + H265: 2, +} as const + +export type TieredVideoCodecType = (typeof TieredVideoCodecType)[keyof typeof TieredVideoCodecType] + +const TIERED_VIDEO_CODEC_TYPE_VALUES: ReadonlySet = new Set(Object.values(TieredVideoCodecType)) + +/** + * The quality class of a video stream tier or of a camera video stream capability. A plugin reads it through `api.hap`, as in `hap.CameraVideoQuality.HIGH`. + * @enum + * @group Camera + */ +export const CameraVideoQuality = { + /** + * The 4K stream of a camera that offers a 2K stream as High at the same time; any other camera does not use it. + */ + HIGHEST: 1, + /** + * The high quality stream: 4K, 2K or 1080p, depending on the hardware. + */ + HIGH: 2, + /** + * The medium quality stream: 1080p when the High stream is 2K or 4K, and 720p otherwise. + */ + MEDIUM: 3, + /** + * The lowest quality stream: 360p at 15 frames per second, or 240p at 30. + */ + LOW: 4, +} as const + +export type CameraVideoQuality = (typeof CameraVideoQuality)[keyof typeof CameraVideoQuality] + +/** + * The values of {@link CameraVideoQuality}, which the capabilities codec reads as well. + */ +export const CAMERA_VIDEO_QUALITY_VALUES: ReadonlySet = new Set(Object.values(CameraVideoQuality)) + +/** + * The audio codec an audio stream tier advertises. The RTP stream configuration numbers Opus 3 as well. + */ +export const TieredAudioCodecType = { + /** + * Opus. + */ + OPUS: 3, +} as const + +export type TieredAudioCodecType = (typeof TieredAudioCodecType)[keyof typeof TieredAudioCodecType] + +const TIERED_AUDIO_CODEC_TYPE_VALUES: ReadonlySet = new Set(Object.values(TieredAudioCodecType)) + +/** + * The sample rate of an audio stream tier. + * + * It is a separate set from {@link AudioSamplerate}, the RTP stream configuration's, which numbers 8 kHz 0, and from {@link AudioRecordingSamplerate}, + * the recording configuration's, which matches it through 32 kHz but numbers 48 kHz 5 where this one numbers it 4. + */ +export const TieredAudioSampleRate = { + KHZ_16: 1, + KHZ_24: 2, + KHZ_32: 3, + KHZ_48: 4, +} as const + +export type TieredAudioSampleRate = (typeof TieredAudioSampleRate)[keyof typeof TieredAudioSampleRate] + +const TIERED_AUDIO_SAMPLE_RATE_VALUES: ReadonlySet = new Set(Object.values(TieredAudioSampleRate)) + +/** + * The bit depth of an audio stream tier. + */ +export const TieredAudioBitDepth = { + BITS_8: 1, + BITS_16: 2, + BITS_24: 3, +} as const + +export type TieredAudioBitDepth = (typeof TieredAudioBitDepth)[keyof typeof TieredAudioBitDepth] + +const TIERED_AUDIO_BIT_DEPTH_VALUES: ReadonlySet = new Set(Object.values(TieredAudioBitDepth)) + +/** + * One video stream tier a camera offers. + */ +export interface VideoStreamTier { + /** + * The tier's identifier, which an RTP Streaming Control start names. + */ + identifier: number + /** + * The tier's quality class. + */ + quality: CameraVideoQuality + /** + * The target average bitrate, in kbps. + */ + targetAverageBitrate: number + /** + * The width of the video frames, in pixels. + */ + width: number + /** + * The height of the video frames, in pixels. + */ + height: number + /** + * The frame rate, in frames per second. + */ + frameRate: number +} + +/** + * The value of Supported Video Stream Tiers, and of WebRTC Supported Video Stream Tiers, which shares its shape: the parameters a camera supports for + * streaming video. + */ +export interface SupportedVideoStreamTiersPayload { + /** + * The video codec. + */ + codec: TieredVideoCodecType + /** + * The payload type, as RFC 3551 defines it. + */ + payloadType: number + /** + * One entry per supported tier. + */ + tiers: VideoStreamTier[] +} + +/** + * One audio stream tier a camera offers. + */ +export interface AudioStreamTier { + /** + * The tier's identifier, which an RTP Streaming Control start names. + */ + identifier: number + /** + * The target average bitrate, in bits per second where a video tier's is in kbps. + */ + targetAverageBitrate: number + /** + * The sample rate. + */ + sampleRate: TieredAudioSampleRate + /** + * The bit depth. + */ + bitDepth: TieredAudioBitDepth + /** + * The packet time, in milliseconds. + */ + packetTime: number + /** + * The number of channels. + */ + numberOfChannels: number +} + +/** + * The value of Supported Audio Stream Tiers, and of WebRTC Supported Audio Stream Tiers, which shares its shape: the parameters a camera supports for + * streaming audio. + */ +export interface SupportedAudioStreamTiersPayload { + /** + * The audio codec. + */ + codec: TieredAudioCodecType + /** + * The payload type, as RFC 3551 defines it. + */ + payloadType: number + /** + * One entry per supported tier. + */ + tiers: AudioStreamTier[] +} + +function encodeVideoStreamTier(tier: VideoStreamTier): Buffer { + return encode( + VideoStreamTierTypes.IDENTIFIER, writeUInt32(tier.identifier), + VideoStreamTierTypes.QUALITY, writeUInt8(tier.quality), + VideoStreamTierTypes.TARGET_AVERAGE_BITRATE, writeUInt32(tier.targetAverageBitrate), + VideoStreamTierTypes.WIDTH, writeUInt16(tier.width), + VideoStreamTierTypes.HEIGHT, writeUInt16(tier.height), + VideoStreamTierTypes.FRAME_RATE, writeUInt8(tier.frameRate), + ) +} + +function decodeVideoStreamTier(buffer: Buffer): VideoStreamTier { + const fields = decodeFields(buffer) + + return { + identifier: readUInt32(requiredField(fields, VideoStreamTierTypes.IDENTIFIER, 'Identifier')), + quality: readEnum(requiredField(fields, VideoStreamTierTypes.QUALITY, 'Quality'), CAMERA_VIDEO_QUALITY_VALUES), + targetAverageBitrate: readUInt32(requiredField(fields, VideoStreamTierTypes.TARGET_AVERAGE_BITRATE, 'Target Average Bitrate')), + width: readUInt16(requiredField(fields, VideoStreamTierTypes.WIDTH, 'Width')), + height: readUInt16(requiredField(fields, VideoStreamTierTypes.HEIGHT, 'Height')), + frameRate: readUInt8(requiredField(fields, VideoStreamTierTypes.FRAME_RATE, 'Frame Rate')), + } +} + +function encodeAudioStreamTier(tier: AudioStreamTier): Buffer { + return encode( + AudioStreamTierTypes.IDENTIFIER, writeUInt32(tier.identifier), + AudioStreamTierTypes.TARGET_AVERAGE_BITRATE, writeUInt32(tier.targetAverageBitrate), + AudioStreamTierTypes.SAMPLE_RATE, writeUInt8(tier.sampleRate), + AudioStreamTierTypes.BIT_DEPTH, writeUInt8(tier.bitDepth), + AudioStreamTierTypes.PACKET_TIME, writeUInt8(tier.packetTime), + AudioStreamTierTypes.NUMBER_OF_CHANNELS, writeUInt8(tier.numberOfChannels), + ) +} + +function decodeAudioStreamTier(buffer: Buffer): AudioStreamTier { + const fields = decodeFields(buffer) + + return { + identifier: readUInt32(requiredField(fields, AudioStreamTierTypes.IDENTIFIER, 'Identifier')), + targetAverageBitrate: readUInt32(requiredField(fields, AudioStreamTierTypes.TARGET_AVERAGE_BITRATE, 'Target Average Bitrate')), + sampleRate: readEnum(requiredField(fields, AudioStreamTierTypes.SAMPLE_RATE, 'Sample Rate'), TIERED_AUDIO_SAMPLE_RATE_VALUES), + bitDepth: readEnum(requiredField(fields, AudioStreamTierTypes.BIT_DEPTH, 'Bit Depth'), TIERED_AUDIO_BIT_DEPTH_VALUES), + packetTime: readUInt8(requiredField(fields, AudioStreamTierTypes.PACKET_TIME, 'Packet Time')), + numberOfChannels: readUInt8(requiredField(fields, AudioStreamTierTypes.NUMBER_OF_CHANNELS, 'Number of Channels')), + } +} + +/** + * Encodes a Supported Video Stream Tiers value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeSupportedVideoStreamTiers(payload: SupportedVideoStreamTiersPayload): string { + return encode( + SupportedVideoStreamTiersTypes.CODEC, writeUInt8(payload.codec), + SupportedVideoStreamTiersTypes.PAYLOAD_TYPE, writeUInt8(payload.payloadType), + SupportedVideoStreamTiersTypes.TIERS, payload.tiers.map(encodeVideoStreamTier), + ).toString('base64') +} + +/** + * Decodes a Supported Video Stream Tiers value. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeSupportedVideoStreamTiers(value: string): SupportedVideoStreamTiersPayload { + const fields = decodeBase64Fields(value) + + return { + codec: readEnum(requiredField(fields, SupportedVideoStreamTiersTypes.CODEC, 'Codec'), TIERED_VIDEO_CODEC_TYPE_VALUES), + payloadType: readUInt8(requiredField(fields, SupportedVideoStreamTiersTypes.PAYLOAD_TYPE, 'Payload Type')), + tiers: listField(fields, SupportedVideoStreamTiersTypes.TIERS).map(decodeVideoStreamTier), + } +} + +/** + * Encodes a Supported Audio Stream Tiers value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeSupportedAudioStreamTiers(payload: SupportedAudioStreamTiersPayload): string { + return encode( + SupportedAudioStreamTiersTypes.CODEC, writeUInt8(payload.codec), + SupportedAudioStreamTiersTypes.PAYLOAD_TYPE, writeUInt8(payload.payloadType), + SupportedAudioStreamTiersTypes.TIERS, payload.tiers.map(encodeAudioStreamTier), + ).toString('base64') +} + +/** + * Decodes a Supported Audio Stream Tiers value. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeSupportedAudioStreamTiers(value: string): SupportedAudioStreamTiersPayload { + const fields = decodeBase64Fields(value) + + return { + codec: readEnum(requiredField(fields, SupportedAudioStreamTiersTypes.CODEC, 'Codec'), TIERED_AUDIO_CODEC_TYPE_VALUES), + payloadType: readUInt8(requiredField(fields, SupportedAudioStreamTiersTypes.PAYLOAD_TYPE, 'Payload Type')), + tiers: listField(fields, SupportedAudioStreamTiersTypes.TIERS).map(decodeAudioStreamTier), + } +} diff --git a/src/lib/camera/capabilities/supportedRtpConfiguration.spec.ts b/src/lib/camera/capabilities/supportedRtpConfiguration.spec.ts new file mode 100644 index 000000000..d53238be0 --- /dev/null +++ b/src/lib/camera/capabilities/supportedRtpConfiguration.spec.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' + +import { SRTPCryptoSuites } from './setupEndpoints.js' +import { decodeSupportedRTPConfiguration, encodeSupportedRTPConfiguration } from './supportedRtpConfiguration.js' + +// The legacy class's own bytes at the base, the parity vectors: one suite, both suites delimited, and the Disabled suite alone. +const AES_ONLY = 'AgEA' +const AES_THEN_NONE = 'AgEAAAACAQI=' +const NONE_ONLY = 'AgEC' + +describe('supportedRtpConfiguration', () => { + it('encodes AES_CM_128_HMAC_SHA1_80 alone', () => { + expect(encodeSupportedRTPConfiguration([SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80])).toBe(AES_ONLY) + }) + + it('encodes AES_CM_128_HMAC_SHA1_80 then NONE as two delimited items', () => { + expect(encodeSupportedRTPConfiguration([SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, SRTPCryptoSuites.NONE])).toBe(AES_THEN_NONE) + }) + + it('encodes NONE alone', () => { + expect(encodeSupportedRTPConfiguration([SRTPCryptoSuites.NONE])).toBe(NONE_ONLY) + }) + + it('decodes each vector back to its suites', () => { + expect(decodeSupportedRTPConfiguration(AES_ONLY)).toEqual([SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80]) + expect(decodeSupportedRTPConfiguration(AES_THEN_NONE)).toEqual([SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, SRTPCryptoSuites.NONE]) + expect(decodeSupportedRTPConfiguration(NONE_ONLY)).toEqual([SRTPCryptoSuites.NONE]) + }) + + it('refuses to encode an empty suite list', () => { + expect(() => encodeSupportedRTPConfiguration([])).toThrow(new RangeError('The Supported RTP Configuration needs at least one SRTP Crypto Suite.')) + }) + + it('refuses a suite outside its values and an empty value, naming the field', () => { + expect(() => decodeSupportedRTPConfiguration('AgED')).toThrow('The SRTP Crypto Suite field holds 3, which is not one of its values.') + expect(() => decodeSupportedRTPConfiguration('')).toThrow('The SRTP Crypto Suite field is missing.') + }) +}) diff --git a/src/lib/camera/capabilities/supportedRtpConfiguration.ts b/src/lib/camera/capabilities/supportedRtpConfiguration.ts new file mode 100644 index 000000000..6b67e1150 --- /dev/null +++ b/src/lib/camera/capabilities/supportedRtpConfiguration.ts @@ -0,0 +1,41 @@ +import type { SRTPCryptoSuites } from './setupEndpoints.js' + +import { encode } from '../../util/tlv.js' +import { SRTP_CRYPTO_SUITES_VALUES } from './setupEndpoints.js' +import { decodeBase64Fields, listField, readEnum, writeUInt8 } from './tlvFields.js' + +/* The Supported RTP Configuration codec, R15 9.74's table: one SRTP Crypto Suite item per suite the camera supports, each one octet under its own tag and + * delimited from the next. The legacy and the multi-tier stream management services both advertise through it. The bytes a hub reads are written once. + */ + +enum SupportedRTPConfigurationTypes { + SRTP_CRYPTO_SUITE = 0x02, +} + +/** + * Encodes the Supported RTP Configuration value for the suites a camera supports, in their order. + * @param cryptoSuites - The supported SRTP crypto suites, at least one. + * @returns The base64 TLV8 value. + */ +export function encodeSupportedRTPConfiguration(cryptoSuites: readonly SRTPCryptoSuites[]): string { + if (cryptoSuites.length === 0) { + throw new RangeError('The Supported RTP Configuration needs at least one SRTP Crypto Suite.') + } + + return encode(SupportedRTPConfigurationTypes.SRTP_CRYPTO_SUITE, cryptoSuites.map(writeUInt8)).toString('base64') +} + +/** + * Decodes a Supported RTP Configuration value into the suites it lists, in their order. + * @param value - The base64 TLV8 value. + * @returns The SRTP crypto suites. + */ +export function decodeSupportedRTPConfiguration(value: string): SRTPCryptoSuites[] { + const suites = listField(decodeBase64Fields(value), SupportedRTPConfigurationTypes.SRTP_CRYPTO_SUITE) + + if (suites.length === 0) { + throw new RangeError('The SRTP Crypto Suite field is missing.') + } + + return suites.map(suite => readEnum({ name: 'SRTP Crypto Suite', value: suite }, SRTP_CRYPTO_SUITES_VALUES)) +} diff --git a/src/lib/camera/capabilities/tlvFields.spec.ts b/src/lib/camera/capabilities/tlvFields.spec.ts new file mode 100644 index 000000000..f4580a1f9 --- /dev/null +++ b/src/lib/camera/capabilities/tlvFields.spec.ts @@ -0,0 +1,170 @@ +import type { TLVField } from './tlvFields.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + decodeBase64Fields, + decodeFields, + listField, + readBoolean, + readEnum, + readUInt8, + readUInt16, + readUInt32, + readUInt64, + readUUID, + requiredField, + writeUUID, +} from './tlvFields.js' + +function field(name: string, hex: string): TLVField { + return { + name, + value: Buffer.from(hex, 'hex'), + } +} + +describe('tlvFields', () => { + it.each([ + ['no field', '', []], + ['a lone zero-length item', '0100', []], + [ + 'one entry', + '0101aa', + ['aa'], + ], + [ + 'two delimited entries', + '0101aa00000101bb', + ['aa', 'bb'], + ], + ])('listField reads %s as its entries', (_, hex, entries) => { + expect(listField(decodeFields(Buffer.from(hex, 'hex')), 1).map(entry => entry.toString('hex'))).toEqual(entries) + }) + + it('the uint8 reader refuses an empty field, naming it', () => { + expect(() => readUInt8(field('Codec', ''))).toThrow(RangeError) + expect(() => readUInt8(field('Codec', ''))).toThrow('The Codec field is empty, but its format takes at least 1 byte.') + }) + + it('the uint8 reader refuses a field two bytes long, naming it', () => { + expect(() => readUInt8(field('Codec', 'aabb'))).toThrow(RangeError) + expect(() => readUInt8(field('Codec', 'aabb'))).toThrow('The Codec field is 2 bytes long, but its format takes at most 1 byte.') + }) + + it.each([ + ['03', 3], + ['0300', 3], + ])('the uint16 reader reads %s as %s', (hex, expected) => { + expect(readUInt16(field('Width', hex))).toBe(expected) + }) + + it('the uint16 reader refuses an empty field, naming it', () => { + expect(() => readUInt16(field('Width', ''))).toThrow(RangeError) + expect(() => readUInt16(field('Width', ''))).toThrow('The Width field is empty, but its format takes at least 1 byte.') + }) + + it('the uint16 reader refuses a field three bytes long, naming it', () => { + expect(() => readUInt16(field('Width', '030000'))).toThrow(RangeError) + expect(() => readUInt16(field('Width', '030000'))).toThrow('The Width field is 3 bytes long, but its format takes at most 2 bytes.') + }) + + // The 000001 row sets only its field's top byte: a reader that stops short of the field's last byte reads it wrong. + it.each([ + ['03', 3], + ['030000', 3], + ['03000000', 3], + ['000001', 65536], + ])('the uint32 reader reads %s as %s', (hex, expected) => { + expect(readUInt32(field('Video Tier', hex))).toBe(expected) + }) + + it('the uint32 reader refuses an empty field, naming it', () => { + expect(() => readUInt32(field('Video Tier', ''))).toThrow(RangeError) + expect(() => readUInt32(field('Video Tier', ''))).toThrow('The Video Tier field is empty, but its format takes at least 1 byte.') + }) + + it('the uint32 reader refuses a field five bytes long, naming it', () => { + expect(() => readUInt32(field('Video Tier', '0300000000'))).toThrow(RangeError) + expect(() => readUInt32(field('Video Tier', '0300000000'))).toThrow('The Video Tier field is 5 bytes long, but its format takes at most 4 bytes.') + }) + + // The 0000000001 row sets only its field's top byte: a reader that stops short of the field's last byte reads it wrong. + it.each([ + ['03', 3n], + ['0300000000', 3n], + ['0300000000000000', 3n], + ['0000000001', 4294967296n], + ])('the uint64 reader reads %s as %s', (hex, expected) => { + expect(readUInt64(field('Key Number', hex))).toBe(expected) + }) + + it('the uint64 reader refuses an empty field, naming it', () => { + expect(() => readUInt64(field('Key Number', ''))).toThrow(RangeError) + expect(() => readUInt64(field('Key Number', ''))).toThrow('The Key Number field is empty, but its format takes at least 1 byte.') + }) + + it('the uint64 reader refuses a field nine bytes long, naming it', () => { + expect(() => readUInt64(field('Key Number', '030000000000000000'))).toThrow(RangeError) + expect(() => readUInt64(field('Key Number', '030000000000000000'))).toThrow('The Key Number field is 9 bytes long, but its format takes at most 8 bytes.') + }) + + it('the uuid reader refuses a field fifteen bytes long, naming it', () => { + const fifteenBytes = '000102030405060708090a0b0c0d0e' + + expect(() => readUUID(field('Sensor UUID', fifteenBytes))).toThrow(RangeError) + expect(() => readUUID(field('Sensor UUID', fifteenBytes))).toThrow('The Sensor UUID field is 15 bytes long, but its format takes 16 bytes.') + }) + + it.each([ + ['00', false], + ['01', true], + ])('the boolean reader reads %s as %s', (hex, expected) => { + expect(readBoolean(field('Active', hex))).toBe(expected) + }) + + it('the boolean reader refuses a byte other than 0 or 1', () => { + expect(() => readBoolean(field('Active', '02'))).toThrow('The Active field holds 2, but a boolean holds 0 or 1.') + }) + + it('the enum reader refuses a value outside its set', () => { + expect(() => readEnum(field('Codec', '03'), new Set([1, 2]))).toThrow('The Codec field holds 3, which is not one of its values.') + }) + + it('requiredField refuses an absent field', () => { + expect(() => requiredField(decodeFields(Buffer.from('0201aa', 'hex')), 1, 'Codec')).toThrow('The Codec field is missing.') + }) + + it('requiredField refuses a repeated field', () => { + expect(() => requiredField(decodeFields(Buffer.from('0101aa00000101bb', 'hex')), 1, 'Codec')).toThrow('The Codec field appears more than once.') + }) + + it('the uuid writer refuses a string that is not a uuid', () => { + expect(() => writeUUID('not-a-uuid', 'Session Identifier')).toThrow('The Session Identifier field takes a UUID, but "not-a-uuid" is not one.') + }) + + it.each([ + { name: 'the empty value', value: '', hex: '' }, + { name: 'one empty item', value: 'AQA=', hex: '0100' }, + { name: 'one item of one byte', value: 'AQEA', hex: '010100' }, + ])('the base64 reader decodes $name, which is canonical base64', ({ value, hex }) => { + expect(decodeBase64Fields(value)).toEqual(decodeFields(Buffer.from(hex, 'hex'))) + }) + + // Node's decoder reads each value below as whole TLV items or none. Only the canonical check refuses it, and each refusal's message is matched whole + // against one fixed sentence, which means it quotes none of the value. + it.each([ + { name: 'characters outside the alphabet', value: '!!!!' }, + { name: 'a value behind a space', value: ' AQEA' }, + { name: 'a value without its padding', value: 'AQA' }, + { name: 'a last character with spare bits set', value: 'AQB=' }, + { name: 'a value followed by a line feed', value: 'AQA=\n' }, + { name: 'the URL-safe alphabet', value: 'AQH_' }, + { name: 'two values joined', value: 'AQA=AQA=' }, + ])('the base64 reader refuses $name with a type error that quotes none of the value', ({ value }) => { + expect(() => decodeBase64Fields(value)).toThrow(TypeError) + expect(() => decodeBase64Fields(value)).toThrow(/^The value is not canonical base64, which means its TLV8 fields cannot be read\.$/) + }) +}) diff --git a/src/lib/camera/capabilities/tlvFields.ts b/src/lib/camera/capabilities/tlvFields.ts new file mode 100644 index 000000000..3d62d35fd --- /dev/null +++ b/src/lib/camera/capabilities/tlvFields.ts @@ -0,0 +1,298 @@ +import { Buffer } from 'node:buffer' + +import { counted } from '../../util/counted.js' +import { decodeWithLists, encode, readBigUInt64LE, writeBigUInt64LE } from '../../util/tlv.js' +import * as uuid from '../../util/uuid.js' + +/* The field layer every codec of the camera stack reads and writes through. The width checks, the list rule and the error sentences are written once + * rather than in each codec. An integer is read at any width from one byte up to its spec-table width, the missing high bytes zero, because a TLV8 + * integer takes the minimum number of bytes that holds it and the hubs write the camera tables that way, while the encoders write the table width, which + * every controller reads. A base64 value is read only in its canonical form, the one that encodes back to itself, because Node's decoder skips what it + * cannot read and stops at padding: a value no controller writes would decode as whatever its readable part holds. Each error names the field by its + * spec name, and a refusal reads against the table it came from. The module is internal to the codecs: nothing here reaches the public API. + */ + +export { writeUInt16, writeUInt32 } from '../../util/tlv.js' + +/** + * The fields of one decoded TLV8 value by tag, a field that a delimiter repeats holding every entry. + */ +export type TLVFields = Record + +/** + * One field of a decoded TLV8 value, carried with its spec name so every error a reader throws names it. + */ +export interface TLVField { + /** + * The field's name in its spec table. + */ + readonly name: string + /** + * The field's value bytes. + */ + readonly value: Buffer +} + +function checkWidth(field: TLVField, width: number): Buffer { + if (field.value.length !== width) { + throw new RangeError(`The ${field.name} field is ${counted(field.value.length, 'byte')} long, but its format takes ${counted(width, 'byte')}.`) + } + + return field.value +} + +function checkIntegerWidth(field: TLVField, width: number): Buffer { + if (field.value.length === 0) { + throw new RangeError(`The ${field.name} field is empty, but its format takes at least 1 byte.`) + } + + if (field.value.length > width) { + throw new RangeError(`The ${field.name} field is ${counted(field.value.length, 'byte')} long, but its format takes at most ${counted(width, 'byte')}.`) + } + + if (field.value.length === width) { + return field.value + } + + // A narrower integer is copied into a zeroed buffer of the format's width. Each reader keeps its one full-width read and only a narrow field allocates. + const padded = Buffer.alloc(width) + field.value.copy(padded) + return padded +} + +/** + * Decodes a TLV8 buffer into its fields, a repeated field's entries kept apart rather than joined. + * @param buffer - The TLV8 bytes. + * @returns The fields by tag. + */ +export function decodeFields(buffer: Buffer): TLVFields { + return decodeWithLists(buffer) +} + +/** + * Decodes a base64 characteristic value into its TLV8 fields. A value that is not canonical base64, one that does not encode back to itself, is refused + * with a `TypeError` whose message quotes none of the value, because a control point's value can carry a key and a refusal's message reaches a debug line. + * @param value - The characteristic value. + * @returns The fields by tag. + */ +export function decodeBase64Fields(value: string): TLVFields { + const buffer = Buffer.from(value, 'base64') + + if (buffer.toString('base64') !== value) { + throw new TypeError('The value is not canonical base64, which means its TLV8 fields cannot be read.') + } + + return decodeFields(buffer) +} + +/** + * Reads a field that may be absent. + * @param fields - The decoded fields. + * @param tag - The field's tag. + * @param name - The field's spec name. + * @returns The field, or undefined when it is absent. + */ +export function optionalField(fields: TLVFields, tag: number, name: string): TLVField | undefined { + const value = fields[tag] + + if (value === undefined) { + return undefined + } + + if (Array.isArray(value)) { + throw new TypeError(`The ${name} field appears more than once.`) + } + + return { name, value } +} + +/** + * Reads a field the spec requires. + * @param fields - The decoded fields. + * @param tag - The field's tag. + * @param name - The field's spec name. + * @returns The field. + */ +export function requiredField(fields: TLVFields, tag: number, name: string): TLVField { + const field = optionalField(fields, tag, name) + + if (field === undefined) { + throw new TypeError(`The ${name} field is missing.`) + } + + return field +} + +/** + * Reads a repeated field's entries. + * @param fields - The decoded fields. + * @param tag - The field's tag. + * @returns Each entry's bytes, none when the field is absent. + */ +export function listField(fields: TLVFields, tag: number): Buffer[] { + const value = fields[tag] + + if (value === undefined) { + return [] + } + + if (Array.isArray(value)) { + return value + } + + // An empty list encodes as one zero-length item, and a lone empty entry reads as no entries. + return value.length === 0 + ? [] + : [value] +} + +/** + * Reads a uint8 field. + * @param field - The field. + * @returns The integer. + */ +export function readUInt8(field: TLVField): number { + return checkIntegerWidth(field, 1).readUInt8(0) +} + +/** + * Reads a little-endian uint16 field. + * @param field - The field. + * @returns The integer. + */ +export function readUInt16(field: TLVField): number { + return checkIntegerWidth(field, 2).readUInt16LE(0) +} + +/** + * Reads a little-endian uint32 field. + * @param field - The field. + * @returns The integer. + */ +export function readUInt32(field: TLVField): number { + return checkIntegerWidth(field, 4).readUInt32LE(0) +} + +/** + * Reads a little-endian uint64 field as a bigint, exact across the whole range. + * @param field - The field. + * @returns The integer. + */ +export function readUInt64(field: TLVField): bigint { + return readBigUInt64LE(checkIntegerWidth(field, 8)) +} + +/** + * Reads a boolean field, one byte holding 0 or 1. + * @param field - The field. + * @returns The boolean. + */ +export function readBoolean(field: TLVField): boolean { + const value = readUInt8(field) + + if (value > 1) { + throw new RangeError(`The ${field.name} field holds ${value}, but a boolean holds 0 or 1.`) + } + + return value === 1 +} + +/** + * Reads a sixteen-byte UUID data field. + * @param field - The field. + * @returns The UUID in its lowercase canonical form. + */ +export function readUUID(field: TLVField): string { + return uuid.unparse(checkWidth(field, 16)) +} + +/** + * Reads a UTF-8 string field. + * @param field - The field. + * @returns The string. + */ +export function readString(field: TLVField): string { + return field.value.toString('utf8') +} + +/** + * Reads a one-byte enumerated field, refusing a value outside its set. + * @param field - The field. + * @param values - The set's values. + * @returns The value read. + */ +export function readEnum(field: TLVField, values: ReadonlySet): T { + const value = readUInt8(field) + + if (!values.has(value)) { + throw new RangeError(`The ${field.name} field holds ${value}, which is not one of its values.`) + } + + return value as T +} + +/** + * Writes a uint8, a value outside the range throwing the RangeError of the underlying `Buffer` write. + * @param value - The integer. + * @returns A new one-byte buffer. + */ +export function writeUInt8(value: number): Buffer { + const buffer = Buffer.alloc(1) + buffer.writeUInt8(value, 0) + return buffer +} + +/** + * Writes a little-endian uint64 from a bigint, exact across the whole range. + * @param value - The integer. + * @returns A new eight-byte buffer. + */ +export function writeUInt64(value: bigint): Buffer { + return writeBigUInt64LE(value) +} + +/** + * Writes a boolean as one byte holding 0 or 1. + * @param value - The boolean. + * @returns A new one-byte buffer. + */ +export function writeBoolean(value: boolean): Buffer { + return writeUInt8(value ? 1 : 0) +} + +/** + * Writes a UUID as its sixteen bytes. + * @param value - The UUID. + * @param name - The field's spec name. + * @returns A new sixteen-byte buffer. + */ +export function writeUUID(value: string, name: string): Buffer { + const buffer = uuid.write(value) + + if (buffer.length !== 16) { + throw new RangeError(`The ${name} field takes a UUID, but "${value}" is not one.`) + } + + return buffer +} + +/** + * Writes a string as UTF-8. + * @param value - The string. + * @returns A new buffer. + */ +export function writeString(value: string): Buffer { + return Buffer.from(value, 'utf8') +} + +/** + * Encodes a field that may be absent, writing nothing when it is. + * @param tag - The field's tag. + * @param value - The field's bytes, or undefined when it is absent. + * @returns The encoded item, or an empty buffer. + */ +export function encodeOptional(tag: number, value: Buffer | undefined): Buffer { + return value === undefined + ? Buffer.alloc(0) + : encode(tag, value) +} diff --git a/src/lib/camera/capabilities/webrtc.spec.ts b/src/lib/camera/capabilities/webrtc.spec.ts new file mode 100644 index 000000000..e9e16af67 --- /dev/null +++ b/src/lib/camera/capabilities/webrtc.spec.ts @@ -0,0 +1,261 @@ +import type { + WebRTCICECandidate, + WebRTCProvideAnswerRequest, + WebRTCReofferRequest, + WebRTCReofferResponse, + WebRTCSessionStatusResponse, + WebRTCSolicitOfferRequest, + WebRTCSolicitOfferResponse, + WebRTCStreamingControlRequest, + WebRTCUpdateSessionRequest, +} from './webrtc.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + decodeWebRTCProvideAnswerRequest, + decodeWebRTCReofferRequest, + decodeWebRTCReofferResponse, + decodeWebRTCSessionStatusResponse, + decodeWebRTCSolicitOfferRequest, + decodeWebRTCSolicitOfferResponse, + decodeWebRTCStreamingControlRequest, + decodeWebRTCUpdateSessionRequest, + encodeWebRTCProvideAnswerRequest, + encodeWebRTCReofferRequest, + encodeWebRTCReofferResponse, + encodeWebRTCSessionStatusResponse, + encodeWebRTCSolicitOfferRequest, + encodeWebRTCSolicitOfferResponse, + encodeWebRTCStreamingControlRequest, + encodeWebRTCUpdateSessionRequest, + WebRTCSolicitOfferStatus, + WebRTCStreamingCommand, + WebRTCStreamingStatus, +} from './webrtc.js' + +// The golden vectors are computed from the spec's tables by an independent TLV8 writer, every integer little-endian at its table width. +const SESSION = 'e7f1c3a2-5b4d-4e6f-9a8b-0c1d2e3f4a5b' +const P53 = 2n ** 53n + 1n +const MAX64 = 2n ** 64n - 1n +const KEY_16 = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex') +const KEY_16_REVERSED = Buffer.from('0f0e0d0c0b0a09080706050403020100', 'hex') +// An offer long enough that its SDP Offer item fragments. +const SDP_OFFER = `v=0\r\n${'a=x\r\n'.repeat(60)}` +const SDP_ANSWER = 'v=0\r\no=- 1 1 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n' + +const ICE_1: WebRTCICECandidate = { + candidate: 'candidate:1 1 udp 2130706431 192.168.1.10 50000 typ host', + sdpMid: '0', + sdpMLineIndex: 0, +} +const ICE_2: WebRTCICECandidate = { candidate: 'candidate:2 1 udp 1694498815 203.0.113.7 50001 typ srflx' } + +const SOLICIT_OFFER_REQUEST: WebRTCSolicitOfferRequest = { + options: { sframeEnabled: true }, +} +const SOLICIT_OFFER_REQUEST_HEX = '0103010101' + +const SOLICIT_OFFER_RESPONSE: WebRTCSolicitOfferResponse = { + status: WebRTCSolicitOfferStatus.SUCCESS, + sessionIdentifier: SESSION, + sdpOffer: SDP_OFFER, + additionalCandidates: [ICE_1, ICE_2], + sframeConfiguration: { key: KEY_16, kid: MAX64 }, +} +const SOLICIT_OFFER_RESPONSE_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b02ff763d300d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a61' + + '3d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d' + + '780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d78' + + '0d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d' + + '0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a0232613d78' + + '0d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a613d780d0a0341013863616e6469' + + '646174653a312031207564702032313330373036343331203139322e3136382e312e31302035303030302074797020686f73740201300302' + + '00000000033a013863616e6469646174653a322031207564702031363934343938383135203230332e302e3131332e372035303030312074' + + '7970207372666c78040100051c0110000102030405060708090a0b0c0d0e0f0208ffffffffffffffff' + +const SOLICIT_OFFER_RESPONSE_PRIVACY: WebRTCSolicitOfferResponse = { status: WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE } +const SOLICIT_OFFER_RESPONSE_PRIVACY_HEX = '040101' + +const PROVIDE_ANSWER_REQUEST: WebRTCProvideAnswerRequest = { + sessionIdentifier: SESSION, + sdpAnswer: SDP_ANSWER, + additionalCandidates: [ICE_1], +} +const PROVIDE_ANSWER_REQUEST_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b0229763d300d0a6f3d2d2031203120494e2049503420302e302e302e300d0a733d2d0d0a743d' + + '3020300d0a0341013863616e6469646174653a312031207564702032313330373036343331203139322e3136382e312e3130203530303030' + + '2074797020686f737402013003020000' + +const SESSION_STATUS_RESPONSE: WebRTCSessionStatusResponse = { sessionIdentifier: SESSION, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } +const SESSION_STATUS_RESPONSE_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b020101' + +const STREAMING_CONTROL_REQUEST: WebRTCStreamingControlRequest = { sessionIdentifier: SESSION, command: WebRTCStreamingCommand.END } +const STREAMING_CONTROL_REQUEST_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b020101' + +const REOFFER_REQUEST: WebRTCReofferRequest = { + sessionIdentifier: SESSION, + sdpOffer: SDP_ANSWER, + options: { sframeEnabled: false }, +} +const REOFFER_REQUEST_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b0229763d300d0a6f3d2d2031203120494e2049503420302e302e302e300d0a733d2d0d0a743d' + + '3020300d0a0303010100' + +const REOFFER_RESPONSE: WebRTCReofferResponse = { + sessionIdentifier: SESSION, + status: WebRTCStreamingStatus.SUCCESS, + sdpAnswer: SDP_ANSWER, + sframeConfiguration: { key: KEY_16, kid: P53 }, +} +const REOFFER_RESPONSE_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b0229763d300d0a6f3d2d2031203120494e2049503420302e302e302e300d0a733d2d0d0a743d' + + '3020300d0a030100041c0110000102030405060708090a0b0c0d0e0f02080100000000002000' + +const REOFFER_RESPONSE_BUSY: WebRTCReofferResponse = { sessionIdentifier: SESSION, status: WebRTCStreamingStatus.BUSY } +const REOFFER_RESPONSE_BUSY_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b030102' + +const UPDATE_SESSION_REQUEST: WebRTCUpdateSessionRequest = { + sessionIdentifier: SESSION, + receiveKeysToAdd: [ + { key: KEY_16, kid: 1n }, + { key: KEY_16_REVERSED, kid: P53 }, + ], + receiveKIDsToRemove: [ + { kid: 0n }, + { kid: MAX64 }, + ], +} +const UPDATE_SESSION_REQUEST_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b021c0110000102030405060708090a0b0c0d0e0f020801000000000000000000021c01100f0e' + + '0d0c0b0a0908070605040302010002080100000000002000030a010800000000000000000000030a0108ffffffffffffffff' + +// The provide answer write with its candidate's SDP MLine Index one byte long, every enclosing length recomputed. +const ONE_BYTE_SDP_MLINE_INDEX_PROVIDE_ANSWER_HEX = '0110e7f1c3a25b4d4e6f9a8b0c1d2e3f4a5b0229763d300d0a6f3d2d2031203120494e2049503420302e302e302e300d0a733d2d0d0a743d' + + '3020300d0a0340013863616e6469646174653a312031207564702032313330373036343331203139322e3136382e312e3130203530303030' + + '2074797020686f7374020130030100' + +describe('webrtc', () => { + it('encodes and decodes a solicit offer request', () => { + const value = Buffer.from(SOLICIT_OFFER_REQUEST_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCSolicitOfferRequest(SOLICIT_OFFER_REQUEST), 'base64').toString('hex')).toBe(SOLICIT_OFFER_REQUEST_HEX) + expect(decodeWebRTCSolicitOfferRequest(value)).toEqual(SOLICIT_OFFER_REQUEST) + }) + + it('encodes and decodes a solicit offer response, its sdp offer item fragmenting', () => { + const value = Buffer.from(SOLICIT_OFFER_RESPONSE_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCSolicitOfferResponse(SOLICIT_OFFER_RESPONSE), 'base64').toString('hex')).toBe(SOLICIT_OFFER_RESPONSE_HEX) + expect(decodeWebRTCSolicitOfferResponse(value)).toEqual(SOLICIT_OFFER_RESPONSE) + }) + + it('encodes and decodes a solicit offer response with privacy mode active', () => { + const value = Buffer.from(SOLICIT_OFFER_RESPONSE_PRIVACY_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCSolicitOfferResponse(SOLICIT_OFFER_RESPONSE_PRIVACY), 'base64').toString('hex')) + .toBe(SOLICIT_OFFER_RESPONSE_PRIVACY_HEX) + expect(decodeWebRTCSolicitOfferResponse(value)).toEqual(SOLICIT_OFFER_RESPONSE_PRIVACY) + }) + + it('encodes and decodes a provide answer request', () => { + const value = Buffer.from(PROVIDE_ANSWER_REQUEST_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCProvideAnswerRequest(PROVIDE_ANSWER_REQUEST), 'base64').toString('hex')).toBe(PROVIDE_ANSWER_REQUEST_HEX) + expect(decodeWebRTCProvideAnswerRequest(value)).toEqual(PROVIDE_ANSWER_REQUEST) + }) + + it('encodes and decodes a session status response', () => { + const value = Buffer.from(SESSION_STATUS_RESPONSE_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCSessionStatusResponse(SESSION_STATUS_RESPONSE), 'base64').toString('hex')).toBe(SESSION_STATUS_RESPONSE_HEX) + expect(decodeWebRTCSessionStatusResponse(value)).toEqual(SESSION_STATUS_RESPONSE) + }) + + it('encodes and decodes a streaming control request', () => { + const value = Buffer.from(STREAMING_CONTROL_REQUEST_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCStreamingControlRequest(STREAMING_CONTROL_REQUEST), 'base64').toString('hex')).toBe(STREAMING_CONTROL_REQUEST_HEX) + expect(decodeWebRTCStreamingControlRequest(value)).toEqual(STREAMING_CONTROL_REQUEST) + }) + + it('encodes and decodes a reoffer request', () => { + const value = Buffer.from(REOFFER_REQUEST_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCReofferRequest(REOFFER_REQUEST), 'base64').toString('hex')).toBe(REOFFER_REQUEST_HEX) + expect(decodeWebRTCReofferRequest(value)).toEqual(REOFFER_REQUEST) + }) + + it('encodes and decodes a reoffer response', () => { + const value = Buffer.from(REOFFER_RESPONSE_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCReofferResponse(REOFFER_RESPONSE), 'base64').toString('hex')).toBe(REOFFER_RESPONSE_HEX) + expect(decodeWebRTCReofferResponse(value)).toEqual(REOFFER_RESPONSE) + }) + + it('encodes and decodes a busy reoffer response', () => { + const value = Buffer.from(REOFFER_RESPONSE_BUSY_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCReofferResponse(REOFFER_RESPONSE_BUSY), 'base64').toString('hex')).toBe(REOFFER_RESPONSE_BUSY_HEX) + expect(decodeWebRTCReofferResponse(value)).toEqual(REOFFER_RESPONSE_BUSY) + }) + + it('encodes and decodes an update session request', () => { + const value = Buffer.from(UPDATE_SESSION_REQUEST_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeWebRTCUpdateSessionRequest(UPDATE_SESSION_REQUEST), 'base64').toString('hex')).toBe(UPDATE_SESSION_REQUEST_HEX) + expect(decodeWebRTCUpdateSessionRequest(value)).toEqual(UPDATE_SESSION_REQUEST) + }) + + it('ignores an unknown tag', () => { + const value = Buffer.from(`${SOLICIT_OFFER_REQUEST_HEX}ff0100`, 'hex').toString('base64') + + expect(decodeWebRTCSolicitOfferRequest(value)).toEqual(SOLICIT_OFFER_REQUEST) + }) + + it('decodes a solicit offer request without its options, the empty value among them, as not requesting sframe', () => { + const unknownTagAlone = Buffer.from('ff0100', 'hex').toString('base64') + + expect(decodeWebRTCSolicitOfferRequest('')).toEqual({ + options: { sframeEnabled: false }, + }) + expect(decodeWebRTCSolicitOfferRequest(unknownTagAlone)).toEqual({ + options: { sframeEnabled: false }, + }) + }) + + it('refuses a solicit offer request whose options are empty, naming the sframe enabled field', () => { + const value = Buffer.from(SOLICIT_OFFER_REQUEST_HEX.replace(/^0103010101/, '0100'), 'hex').toString('base64') + + expect(() => decodeWebRTCSolicitOfferRequest(value)).toThrow('The SFrame Enabled field is missing.') + }) + + it('decodes a reoffer request without its options as not requesting sframe', () => { + const value = Buffer.from(REOFFER_REQUEST_HEX.replace(/0303010100$/, ''), 'hex').toString('base64') + + expect(decodeWebRTCReofferRequest(value)).toEqual({ + ...REOFFER_REQUEST, + options: { sframeEnabled: false }, + }) + }) + + it('refuses a reoffer request without its session identifier or its sdp offer, or with empty options, naming the field', () => { + const withoutSessionIdentifier = Buffer.from(REOFFER_REQUEST_HEX.replace(`0110${SESSION.replaceAll('-', '')}`, ''), 'hex').toString('base64') + const withoutSDPOffer = Buffer.from(REOFFER_REQUEST_HEX.replace(`0229${Buffer.from(SDP_ANSWER).toString('hex')}`, ''), 'hex').toString('base64') + const withEmptyOptions = Buffer.from(REOFFER_REQUEST_HEX.replace(/0303010100$/, '0300'), 'hex').toString('base64') + + expect(() => decodeWebRTCReofferRequest(withoutSessionIdentifier)).toThrow('The Session Identifier field is missing.') + expect(() => decodeWebRTCReofferRequest(withoutSDPOffer)).toThrow('The SDP Offer field is missing.') + expect(() => decodeWebRTCReofferRequest(withEmptyOptions)).toThrow('The SFrame Enabled field is missing.') + }) + + it('decodes a provide answer request whose sdp mline index is one byte long', () => { + const value = Buffer.from(ONE_BYTE_SDP_MLINE_INDEX_PROVIDE_ANSWER_HEX, 'hex').toString('base64') + + expect(decodeWebRTCProvideAnswerRequest(value)).toEqual(PROVIDE_ANSWER_REQUEST) + }) + + it('refuses an sdp mline index three bytes long, naming the field', () => { + const value = Buffer.from(PROVIDE_ANSWER_REQUEST_HEX.replace('0341', '0342').replace(/03020000$/, '0303000000'), 'hex').toString('base64') + + expect(() => decodeWebRTCProvideAnswerRequest(value)).toThrow(RangeError) + expect(() => decodeWebRTCProvideAnswerRequest(value)).toThrow('The SDP MLine Index field is 3 bytes long, but its format takes at most 2 bytes.') + }) +}) diff --git a/src/lib/camera/capabilities/webrtc.ts b/src/lib/camera/capabilities/webrtc.ts new file mode 100644 index 000000000..932645efe --- /dev/null +++ b/src/lib/camera/capabilities/webrtc.ts @@ -0,0 +1,676 @@ +import type { TLVField } from './tlvFields.js' + +import { Buffer } from 'node:buffer' + +import { encode } from '../../util/tlv.js' +import { + decodeBase64Fields, + decodeFields, + encodeOptional, + listField, + optionalField, + readBoolean, + readEnum, + readString, + readUInt16, + readUInt64, + readUUID, + requiredField, + writeBoolean, + writeString, + writeUInt8, + writeUInt16, + writeUInt64, + writeUUID, +} from './tlvFields.js' + +const WebRTCOfferOptionsTypes = { + SFRAME_ENABLED: 0x01, +} as const + +const WebRTCICECandidateTypes = { + CANDIDATE: 0x01, + SDP_MID: 0x02, + SDP_MLINE_INDEX: 0x03, +} as const + +const SFrameKeyDataTypes = { + KEY: 0x01, + KID: 0x02, +} as const + +const SFrameKIDTypes = { + KID: 0x01, +} as const + +const WebRTCSolicitOfferRequestTypes = { + OPTIONS: 0x01, +} as const + +const WebRTCSolicitOfferResponseTypes = { + SESSION_IDENTIFIER: 0x01, + SDP_OFFER: 0x02, + ADDITIONAL_CANDIDATES: 0x03, + STATUS: 0x04, + SFRAME_CONFIGURATION: 0x05, +} as const + +const WebRTCProvideAnswerRequestTypes = { + SESSION_IDENTIFIER: 0x01, + SDP_ANSWER: 0x02, + ADDITIONAL_CANDIDATES: 0x03, +} as const + +const WebRTCSessionStatusResponseTypes = { + SESSION_IDENTIFIER: 0x01, + STATUS: 0x02, +} as const + +const WebRTCStreamingControlRequestTypes = { + SESSION_IDENTIFIER: 0x01, + COMMAND: 0x02, +} as const + +const WebRTCReofferRequestTypes = { + SESSION_IDENTIFIER: 0x01, + SDP_OFFER: 0x02, + OPTIONS: 0x03, +} as const + +const WebRTCReofferResponseTypes = { + SESSION_IDENTIFIER: 0x01, + SDP_ANSWER: 0x02, + STATUS: 0x03, + SFRAME_CONFIGURATION: 0x04, +} as const + +const WebRTCUpdateSessionRequestTypes = { + SESSION_IDENTIFIER: 0x01, + RECEIVE_KEYS_TO_ADD: 0x02, + RECEIVE_KIDS_TO_REMOVE: 0x03, +} as const + +/** + * The status of a WebRTC Solicit Offer write. + */ +export const WebRTCSolicitOfferStatus = { + SUCCESS: 0, + PRIVACY_MODE_ACTIVE: 1, + ERROR: 2, +} as const + +export type WebRTCSolicitOfferStatus = (typeof WebRTCSolicitOfferStatus)[keyof typeof WebRTCSolicitOfferStatus] + +const WEBRTC_SOLICIT_OFFER_STATUS_VALUES: ReadonlySet = new Set(Object.values(WebRTCSolicitOfferStatus)) + +/** + * The status of a command on a WebRTC session, which the Provide Answer, Streaming Control, Reoffer and Update Session responses carry. + */ +export const WebRTCStreamingStatus = { + SUCCESS: 0, + UNKNOWN_SESSION_IDENTIFIER: 1, + BUSY: 2, + ERROR: 3, +} as const + +export type WebRTCStreamingStatus = (typeof WebRTCStreamingStatus)[keyof typeof WebRTCStreamingStatus] + +const WEBRTC_STREAMING_STATUS_VALUES: ReadonlySet = new Set(Object.values(WebRTCStreamingStatus)) + +/** + * The command a WebRTC Streaming Control write carries. + */ +export const WebRTCStreamingCommand = { + END: 1, +} as const + +export type WebRTCStreamingCommand = (typeof WebRTCStreamingCommand)[keyof typeof WebRTCStreamingCommand] + +const WEBRTC_STREAMING_COMMAND_VALUES: ReadonlySet = new Set(Object.values(WebRTCStreamingCommand)) + +/** + * The options of a WebRTC offer. + */ +export interface WebRTCOfferOptions { + /** + * Whether the controller requests end-to-end media encryption for the session. A Solicit Offer or Reoffer write that carries no options reads as false. + */ + sframeEnabled: boolean +} + +/** + * One ICE candidate of a WebRTC session. + */ +export interface WebRTCICECandidate { + /** + * The RFC 8825-compliant ICE candidate. + */ + candidate: string + /** + * The media stream identification tag of the media stream the candidate is associated with, absent when there is none. + */ + sdpMid?: string + /** + * The zero-based index of the media description (RFC 8866) the candidate is associated with, absent when there is none. + */ + sdpMLineIndex?: number +} + +/** + * One SFrame key. + */ +export interface SFrameKeyData { + /** + * The raw key data. + */ + key: Buffer + /** + * The SFrame key ID. + */ + kid: bigint +} + +/** + * The ID of one SFrame key. + */ +export interface SFrameKID { + /** + * The SFrame key ID. + */ + kid: bigint +} + +/** + * A write to WebRTC Solicit Offer, which solicits a streaming offer. + */ +export interface WebRTCSolicitOfferRequest { + /** + * The offer's options. + */ + options: WebRTCOfferOptions +} + +/** + * The write response of WebRTC Solicit Offer, a union on its status: only a success carries the offer. + */ +export type WebRTCSolicitOfferResponse = { + /** + * The status. + */ + status: typeof WebRTCSolicitOfferStatus.SUCCESS + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The RFC 8866-compliant SDP offer. + */ + sdpOffer: string + /** + * The ICE candidates the offer does not carry. + */ + additionalCandidates: WebRTCICECandidate[] + /** + * The SFrame key of the session's media. + */ + sframeConfiguration?: SFrameKeyData +} | { + /** + * The status. + */ + status: typeof WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE | typeof WebRTCSolicitOfferStatus.ERROR +} + +/** + * A write to WebRTC Provide Answer, which carries the answer to a session's offer. + */ +export interface WebRTCProvideAnswerRequest { + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The RFC 8866-compliant SDP answer. + */ + sdpAnswer: string + /** + * The ICE candidates the answer does not carry. + */ + additionalCandidates: WebRTCICECandidate[] +} + +/** + * The write response of WebRTC Provide Answer, WebRTC Streaming Control and WebRTC Update Session, whose tables are the same. + */ +export interface WebRTCSessionStatusResponse { + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The command's status. + */ + status: WebRTCStreamingStatus +} + +/** + * A write to WebRTC Streaming Control, which controls a session's stream. + */ +export interface WebRTCStreamingControlRequest { + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The command. + */ + command: WebRTCStreamingCommand +} + +/** + * A write to WebRTC Reoffer, which renegotiates an existing session. + */ +export interface WebRTCReofferRequest { + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The RFC 8866-compliant SDP offer. + */ + sdpOffer: string + /** + * The offer's options. + */ + options: WebRTCOfferOptions +} + +/** + * The write response of WebRTC Reoffer, a union on its status: only a success carries the answer. + */ +export type WebRTCReofferResponse = { + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The status. + */ + status: typeof WebRTCStreamingStatus.SUCCESS + /** + * The RFC 8866-compliant SDP answer. + */ + sdpAnswer: string + /** + * The SFrame key of the session's media. + */ + sframeConfiguration?: SFrameKeyData +} | { + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The status. + */ + status: typeof WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER | typeof WebRTCStreamingStatus.BUSY | typeof WebRTCStreamingStatus.ERROR +} + +/** + * A write to WebRTC Update Session, which updates the receive keys of an existing session. + */ +export interface WebRTCUpdateSessionRequest { + /** + * The UUID identifying the session. + */ + sessionIdentifier: string + /** + * The SFrame receive keys to add. + */ + receiveKeysToAdd: SFrameKeyData[] + /** + * The SFrame key IDs of the receive keys to remove. + */ + receiveKIDsToRemove: SFrameKID[] +} + +function encodeOfferOptions(options: WebRTCOfferOptions): Buffer { + return encode(WebRTCOfferOptionsTypes.SFRAME_ENABLED, writeBoolean(options.sframeEnabled)) +} + +// Decodes the Options field of a Solicit Offer or Reoffer write. A write that carries no Options field asks for no option, and it reads as not requesting +// SFrame, while an Options field that is present must carry SFrame Enabled. +function decodeOfferOptions(field: TLVField | undefined): WebRTCOfferOptions { + if (field === undefined) { + return { sframeEnabled: false } + } + + return { + sframeEnabled: readBoolean(requiredField(decodeFields(field.value), WebRTCOfferOptionsTypes.SFRAME_ENABLED, 'SFrame Enabled')), + } +} + +function encodeICECandidate(candidate: WebRTCICECandidate): Buffer { + return Buffer.concat([ + encode(WebRTCICECandidateTypes.CANDIDATE, writeString(candidate.candidate)), + encodeOptional( + WebRTCICECandidateTypes.SDP_MID, + candidate.sdpMid === undefined + ? undefined + : writeString(candidate.sdpMid), + ), + encodeOptional( + WebRTCICECandidateTypes.SDP_MLINE_INDEX, + candidate.sdpMLineIndex === undefined + ? undefined + : writeUInt16(candidate.sdpMLineIndex), + ), + ]) +} + +function decodeICECandidate(buffer: Buffer): WebRTCICECandidate { + const fields = decodeFields(buffer) + const sdpMid = optionalField(fields, WebRTCICECandidateTypes.SDP_MID, 'SDP Mid') + const sdpMLineIndex = optionalField(fields, WebRTCICECandidateTypes.SDP_MLINE_INDEX, 'SDP MLine Index') + + return { + candidate: readString(requiredField(fields, WebRTCICECandidateTypes.CANDIDATE, 'Candidate')), + ...(sdpMid && { + sdpMid: readString(sdpMid), + }), + ...(sdpMLineIndex && { + sdpMLineIndex: readUInt16(sdpMLineIndex), + }), + } +} + +function encodeSFrameKeyData(keyData: SFrameKeyData): Buffer { + return encode( + SFrameKeyDataTypes.KEY, keyData.key, + SFrameKeyDataTypes.KID, writeUInt64(keyData.kid), + ) +} + +function decodeSFrameKeyData(buffer: Buffer): SFrameKeyData { + const fields = decodeFields(buffer) + + return { + key: requiredField(fields, SFrameKeyDataTypes.KEY, 'Key').value, + kid: readUInt64(requiredField(fields, SFrameKeyDataTypes.KID, 'KID')), + } +} + +function encodeSFrameKID(kid: SFrameKID): Buffer { + return encode(SFrameKIDTypes.KID, writeUInt64(kid.kid)) +} + +function decodeSFrameKID(buffer: Buffer): SFrameKID { + return { + kid: readUInt64(requiredField(decodeFields(buffer), SFrameKIDTypes.KID, 'KID')), + } +} + +/** + * Encodes a WebRTC Solicit Offer write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeWebRTCSolicitOfferRequest(request: WebRTCSolicitOfferRequest): string { + return encode(WebRTCSolicitOfferRequestTypes.OPTIONS, encodeOfferOptions(request.options)).toString('base64') +} + +/** + * Decodes a WebRTC Solicit Offer write. A write without its Options field, the empty value among them, reads as not requesting SFrame. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeWebRTCSolicitOfferRequest(value: string): WebRTCSolicitOfferRequest { + return { + options: decodeOfferOptions(optionalField(decodeBase64Fields(value), WebRTCSolicitOfferRequestTypes.OPTIONS, 'Options')), + } +} + +/** + * Encodes the write response of WebRTC Solicit Offer. + * @param response - The response's model. + * @returns The base64 characteristic value. + */ +export function encodeWebRTCSolicitOfferResponse(response: WebRTCSolicitOfferResponse): string { + if (response.status !== WebRTCSolicitOfferStatus.SUCCESS) { + return encode(WebRTCSolicitOfferResponseTypes.STATUS, writeUInt8(response.status)).toString('base64') + } + + return Buffer.concat([ + encode( + WebRTCSolicitOfferResponseTypes.SESSION_IDENTIFIER, writeUUID(response.sessionIdentifier, 'Session Identifier'), + WebRTCSolicitOfferResponseTypes.SDP_OFFER, writeString(response.sdpOffer), + WebRTCSolicitOfferResponseTypes.ADDITIONAL_CANDIDATES, response.additionalCandidates.map(encodeICECandidate), + WebRTCSolicitOfferResponseTypes.STATUS, writeUInt8(response.status), + ), + encodeOptional( + WebRTCSolicitOfferResponseTypes.SFRAME_CONFIGURATION, + response.sframeConfiguration === undefined + ? undefined + : encodeSFrameKeyData(response.sframeConfiguration), + ), + ]).toString('base64') +} + +/** + * Decodes the write response of WebRTC Solicit Offer. A status other than success ignores any other field it carries. + * @param value - The base64 characteristic value. + * @returns The response's model. + */ +export function decodeWebRTCSolicitOfferResponse(value: string): WebRTCSolicitOfferResponse { + const fields = decodeBase64Fields(value) + const status = readEnum(requiredField(fields, WebRTCSolicitOfferResponseTypes.STATUS, 'Status'), WEBRTC_SOLICIT_OFFER_STATUS_VALUES) + + if (status !== WebRTCSolicitOfferStatus.SUCCESS) { + return { status } + } + + const sframeConfiguration = optionalField(fields, WebRTCSolicitOfferResponseTypes.SFRAME_CONFIGURATION, 'SFrame Configuration') + + return { + status, + sessionIdentifier: readUUID(requiredField(fields, WebRTCSolicitOfferResponseTypes.SESSION_IDENTIFIER, 'Session Identifier')), + sdpOffer: readString(requiredField(fields, WebRTCSolicitOfferResponseTypes.SDP_OFFER, 'SDP Offer')), + additionalCandidates: listField(fields, WebRTCSolicitOfferResponseTypes.ADDITIONAL_CANDIDATES).map(decodeICECandidate), + ...(sframeConfiguration && { + sframeConfiguration: decodeSFrameKeyData(sframeConfiguration.value), + }), + } +} + +/** + * Encodes a WebRTC Provide Answer write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeWebRTCProvideAnswerRequest(request: WebRTCProvideAnswerRequest): string { + return encode( + WebRTCProvideAnswerRequestTypes.SESSION_IDENTIFIER, writeUUID(request.sessionIdentifier, 'Session Identifier'), + WebRTCProvideAnswerRequestTypes.SDP_ANSWER, writeString(request.sdpAnswer), + WebRTCProvideAnswerRequestTypes.ADDITIONAL_CANDIDATES, request.additionalCandidates.map(encodeICECandidate), + ).toString('base64') +} + +/** + * Decodes a WebRTC Provide Answer write. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeWebRTCProvideAnswerRequest(value: string): WebRTCProvideAnswerRequest { + const fields = decodeBase64Fields(value) + + return { + sessionIdentifier: readUUID(requiredField(fields, WebRTCProvideAnswerRequestTypes.SESSION_IDENTIFIER, 'Session Identifier')), + sdpAnswer: readString(requiredField(fields, WebRTCProvideAnswerRequestTypes.SDP_ANSWER, 'SDP Answer')), + additionalCandidates: listField(fields, WebRTCProvideAnswerRequestTypes.ADDITIONAL_CANDIDATES).map(decodeICECandidate), + } +} + +/** + * Encodes the write response of WebRTC Provide Answer, WebRTC Streaming Control or WebRTC Update Session. + * @param response - The response's model. + * @returns The base64 characteristic value. + */ +export function encodeWebRTCSessionStatusResponse(response: WebRTCSessionStatusResponse): string { + return encode( + WebRTCSessionStatusResponseTypes.SESSION_IDENTIFIER, writeUUID(response.sessionIdentifier, 'Session Identifier'), + WebRTCSessionStatusResponseTypes.STATUS, writeUInt8(response.status), + ).toString('base64') +} + +/** + * Decodes the write response of WebRTC Provide Answer, WebRTC Streaming Control or WebRTC Update Session. + * @param value - The base64 characteristic value. + * @returns The response's model. + */ +export function decodeWebRTCSessionStatusResponse(value: string): WebRTCSessionStatusResponse { + const fields = decodeBase64Fields(value) + + return { + sessionIdentifier: readUUID(requiredField(fields, WebRTCSessionStatusResponseTypes.SESSION_IDENTIFIER, 'Session Identifier')), + status: readEnum(requiredField(fields, WebRTCSessionStatusResponseTypes.STATUS, 'Status'), WEBRTC_STREAMING_STATUS_VALUES), + } +} + +/** + * Encodes a WebRTC Streaming Control write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeWebRTCStreamingControlRequest(request: WebRTCStreamingControlRequest): string { + return encode( + WebRTCStreamingControlRequestTypes.SESSION_IDENTIFIER, writeUUID(request.sessionIdentifier, 'Session Identifier'), + WebRTCStreamingControlRequestTypes.COMMAND, writeUInt8(request.command), + ).toString('base64') +} + +/** + * Decodes a WebRTC Streaming Control write. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeWebRTCStreamingControlRequest(value: string): WebRTCStreamingControlRequest { + const fields = decodeBase64Fields(value) + + return { + sessionIdentifier: readUUID(requiredField(fields, WebRTCStreamingControlRequestTypes.SESSION_IDENTIFIER, 'Session Identifier')), + command: readEnum(requiredField(fields, WebRTCStreamingControlRequestTypes.COMMAND, 'Command'), WEBRTC_STREAMING_COMMAND_VALUES), + } +} + +/** + * Encodes a WebRTC Reoffer write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeWebRTCReofferRequest(request: WebRTCReofferRequest): string { + return encode( + WebRTCReofferRequestTypes.SESSION_IDENTIFIER, writeUUID(request.sessionIdentifier, 'Session Identifier'), + WebRTCReofferRequestTypes.SDP_OFFER, writeString(request.sdpOffer), + WebRTCReofferRequestTypes.OPTIONS, encodeOfferOptions(request.options), + ).toString('base64') +} + +/** + * Decodes a WebRTC Reoffer write. A write without its Options field reads as not requesting SFrame, while its Session Identifier and SDP Offer are + * required. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeWebRTCReofferRequest(value: string): WebRTCReofferRequest { + const fields = decodeBase64Fields(value) + + return { + sessionIdentifier: readUUID(requiredField(fields, WebRTCReofferRequestTypes.SESSION_IDENTIFIER, 'Session Identifier')), + sdpOffer: readString(requiredField(fields, WebRTCReofferRequestTypes.SDP_OFFER, 'SDP Offer')), + options: decodeOfferOptions(optionalField(fields, WebRTCReofferRequestTypes.OPTIONS, 'Options')), + } +} + +/** + * Encodes the write response of WebRTC Reoffer. + * @param response - The response's model. + * @returns The base64 characteristic value. + */ +export function encodeWebRTCReofferResponse(response: WebRTCReofferResponse): string { + const sessionIdentifier = encode(WebRTCReofferResponseTypes.SESSION_IDENTIFIER, writeUUID(response.sessionIdentifier, 'Session Identifier')) + + if (response.status !== WebRTCStreamingStatus.SUCCESS) { + return Buffer.concat([ + sessionIdentifier, + encode(WebRTCReofferResponseTypes.STATUS, writeUInt8(response.status)), + ]).toString('base64') + } + + return Buffer.concat([ + sessionIdentifier, + encode( + WebRTCReofferResponseTypes.SDP_ANSWER, writeString(response.sdpAnswer), + WebRTCReofferResponseTypes.STATUS, writeUInt8(response.status), + ), + encodeOptional( + WebRTCReofferResponseTypes.SFRAME_CONFIGURATION, + response.sframeConfiguration === undefined + ? undefined + : encodeSFrameKeyData(response.sframeConfiguration), + ), + ]).toString('base64') +} + +/** + * Decodes the write response of WebRTC Reoffer. A status other than success ignores any answer or SFrame field it carries. + * @param value - The base64 characteristic value. + * @returns The response's model. + */ +export function decodeWebRTCReofferResponse(value: string): WebRTCReofferResponse { + const fields = decodeBase64Fields(value) + const sessionIdentifier = readUUID(requiredField(fields, WebRTCReofferResponseTypes.SESSION_IDENTIFIER, 'Session Identifier')) + const status = readEnum(requiredField(fields, WebRTCReofferResponseTypes.STATUS, 'Status'), WEBRTC_STREAMING_STATUS_VALUES) + + if (status !== WebRTCStreamingStatus.SUCCESS) { + return { sessionIdentifier, status } + } + + const sframeConfiguration = optionalField(fields, WebRTCReofferResponseTypes.SFRAME_CONFIGURATION, 'SFrame Configuration') + + return { + sessionIdentifier, + status, + sdpAnswer: readString(requiredField(fields, WebRTCReofferResponseTypes.SDP_ANSWER, 'SDP Answer')), + ...(sframeConfiguration && { + sframeConfiguration: decodeSFrameKeyData(sframeConfiguration.value), + }), + } +} + +/** + * Encodes a WebRTC Update Session write. + * @param request - The write's model. + * @returns The base64 characteristic value. + */ +export function encodeWebRTCUpdateSessionRequest(request: WebRTCUpdateSessionRequest): string { + return encode( + WebRTCUpdateSessionRequestTypes.SESSION_IDENTIFIER, writeUUID(request.sessionIdentifier, 'Session Identifier'), + WebRTCUpdateSessionRequestTypes.RECEIVE_KEYS_TO_ADD, request.receiveKeysToAdd.map(encodeSFrameKeyData), + WebRTCUpdateSessionRequestTypes.RECEIVE_KIDS_TO_REMOVE, request.receiveKIDsToRemove.map(encodeSFrameKID), + ).toString('base64') +} + +/** + * Decodes a WebRTC Update Session write. + * @param value - The base64 characteristic value. + * @returns The write's model. + */ +export function decodeWebRTCUpdateSessionRequest(value: string): WebRTCUpdateSessionRequest { + const fields = decodeBase64Fields(value) + + return { + sessionIdentifier: readUUID(requiredField(fields, WebRTCUpdateSessionRequestTypes.SESSION_IDENTIFIER, 'Session Identifier')), + receiveKeysToAdd: listField(fields, WebRTCUpdateSessionRequestTypes.RECEIVE_KEYS_TO_ADD).map(decodeSFrameKeyData), + receiveKIDsToRemove: listField(fields, WebRTCUpdateSessionRequestTypes.RECEIVE_KIDS_TO_REMOVE).map(decodeSFrameKID), + } +} diff --git a/src/lib/camera/capabilities/zones.spec.ts b/src/lib/camera/capabilities/zones.spec.ts new file mode 100644 index 000000000..e5e4913cf --- /dev/null +++ b/src/lib/camera/capabilities/zones.spec.ts @@ -0,0 +1,103 @@ +import type { CameraZonePolygon, CameraZonesPayload } from './zones.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { CameraZoneApplicationMethod, decodeCameraZones, encodeCameraZones } from './zones.js' + +// The golden vectors are computed from the spec's tables by an independent TLV8 writer, every integer little-endian at its table width. +const ZONE_1_POLYGON: CameraZonePolygon = { + identifier: 'a0000001-0000-4000-8000-000000000001', + vertices: [ + [0, 0], + [1920, 0], + [1920, 1080], + [0, 1080], + ], +} + +const ZONE_2_POLYGON: CameraZonePolygon = { + identifier: 'a0000002-0000-4000-8000-000000000002', + vertices: [ + [100, 200], + [300, 200], + [200, 400], + ], +} + +const CAMERA_ZONES: CameraZonesPayload = { + zoneDataVersion: 2, + zoneData: [ + { + method: CameraZoneApplicationMethod.NORMAL, + polygons: [ZONE_1_POLYGON, ZONE_2_POLYGON], + }, + ], +} +const CAMERA_ZONES_HEX = '010102024d01010103240110a0000001000040008000000000000001031000000000800700008007380400003804000003200110a0000002' + + '000040008000000000000002030c6400c8002c01c800c8009001' + +// A second Zone Data entry: the field is read as a list rather than one value. +const CAMERA_ZONES_TWO_ENTRIES: CameraZonesPayload = { + zoneDataVersion: 2, + zoneData: [ + { + method: CameraZoneApplicationMethod.NORMAL, + polygons: [ZONE_1_POLYGON, ZONE_2_POLYGON], + }, + { + method: CameraZoneApplicationMethod.INVERTED, + polygons: [ZONE_2_POLYGON], + }, + ], +} +const CAMERA_ZONES_TWO_ENTRIES_HEX = '010102024d01010103240110a0000001000040008000000000000001031000000000800700008007380400003804000003200110a0000002' + + '000040008000000000000002030c6400c8002c01c800c80090010000022501010203200110a0000002000040008000000000000002030c64' + + '00c8002c01c800c8009001' + +// The zones value with the first polygon's Vertices fifteen bytes long, every enclosing length recomputed. +const WRONG_WIDTH_ZONES_HEX = '010102024c01010103230110a0000001000040008000000000000001030f000000008007000080073804000038000003200110a000000200' + + '0040008000000000000002030c6400c8002c01c800c8009001' + +describe('zones', () => { + it('encodes and decodes camera zones', () => { + const value = Buffer.from(CAMERA_ZONES_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraZones(CAMERA_ZONES), 'base64').toString('hex')).toBe(CAMERA_ZONES_HEX) + expect(decodeCameraZones(value)).toEqual(CAMERA_ZONES) + }) + + it('encodes and decodes camera zones with two zone data entries', () => { + const value = Buffer.from(CAMERA_ZONES_TWO_ENTRIES_HEX, 'hex').toString('base64') + + expect(Buffer.from(encodeCameraZones(CAMERA_ZONES_TWO_ENTRIES), 'base64').toString('hex')).toBe(CAMERA_ZONES_TWO_ENTRIES_HEX) + expect(decodeCameraZones(value)).toEqual(CAMERA_ZONES_TWO_ENTRIES) + }) + + it('ignores an unknown tag', () => { + const value = Buffer.from(`${CAMERA_ZONES_HEX}ff0100`, 'hex').toString('base64') + + expect(decodeCameraZones(value)).toEqual(CAMERA_ZONES) + }) + + it('refuses a value without its zone data version, naming the field', () => { + const value = Buffer.from(CAMERA_ZONES_HEX.replace(/^010102/, ''), 'hex').toString('base64') + + expect(() => decodeCameraZones(value)).toThrow('The Zone Data Version field is missing.') + }) + + it('refuses a zone data version other than 2, naming the field', () => { + const value = Buffer.from(CAMERA_ZONES_HEX.replace(/^010102/, '010101'), 'hex').toString('base64') + + expect(() => decodeCameraZones(value)).toThrow(RangeError) + expect(() => decodeCameraZones(value)).toThrow('The Zone Data Version field holds 1, but only version 2 is read.') + }) + + it('refuses vertices fifteen bytes long, naming the field', () => { + const value = Buffer.from(WRONG_WIDTH_ZONES_HEX, 'hex').toString('base64') + + expect(() => decodeCameraZones(value)).toThrow(RangeError) + expect(() => decodeCameraZones(value)).toThrow('The length of the Vertices field, 15, is not a whole number of four-byte vertices.') + }) +}) diff --git a/src/lib/camera/capabilities/zones.ts b/src/lib/camera/capabilities/zones.ts new file mode 100644 index 000000000..6e7bc3d1e --- /dev/null +++ b/src/lib/camera/capabilities/zones.ts @@ -0,0 +1,188 @@ +import type { TLVField } from './tlvFields.js' + +import { Buffer } from 'node:buffer' + +import { encode } from '../../util/tlv.js' +import { decodeBase64Fields, decodeFields, listField, readEnum, readUInt8, readUUID, requiredField, writeUInt8, writeUUID } from './tlvFields.js' + +const CameraZonesTypes = { + ZONE_DATA_VERSION: 0x01, + ZONE_DATA: 0x02, +} as const + +const ZoneDataTypes = { + METHOD: 0x01, + POLYGONS: 0x03, +} as const + +const PolygonTypes = { + IDENTIFIER: 0x01, + VERTICES: 0x03, +} as const + +// The Zone Data version the spec has implementations write, and the only one whose Zone Data layout it defines. +export const ZONE_DATA_VERSION = 2 + +// A vertex is two little-endian uint16 coordinates. +const VERTEX_LENGTH = 4 + +/** + * How the zones of a Zone Data entry form its region of interest. A plugin reads it through `api.hap`, as in `hap.CameraZoneApplicationMethod.NORMAL`. + * @enum + * @group Camera + */ +export const CameraZoneApplicationMethod = { + /** + * The union of the zones' interiors forms the region of interest. + */ + NORMAL: 1, + /** + * The intersection of the zones' exteriors forms the region of interest. + */ + INVERTED: 2, +} as const + +export type CameraZoneApplicationMethod = (typeof CameraZoneApplicationMethod)[keyof typeof CameraZoneApplicationMethod] + +const CAMERA_ZONE_APPLICATION_METHOD_VALUES: ReadonlySet = new Set(Object.values(CameraZoneApplicationMethod)) + +/** + * One vertex of a zone polygon, in the sensor's coordinate space, whose top-left corner is (0, 0). + * @group Camera + */ +export type CameraZoneVertex = [x: number, y: number] + +/** + * One zone: a non-self-intersecting polygon, an edge implied between each vertex and the next and between the last vertex and the first. + * @group Camera + */ +export interface CameraZonePolygon { + /** + * The UUID identifying the zone. + */ + identifier: string + /** + * The polygon's vertices. + */ + vertices: CameraZoneVertex[] +} + +/** + * One Zone Data entry: a set of zones and how they form a region of interest. + * @group Camera + */ +export interface CameraZoneData { + /** + * How the zones form the region of interest. + */ + method: CameraZoneApplicationMethod + /** + * One entry per zone. + */ + polygons: CameraZonePolygon[] +} + +/** + * The value of Camera Zones: the user's zones over the image. + */ +export interface CameraZonesPayload { + /** + * The version of the Zone Data, which the decoder reads only at 2, the version the spec has implementations write. + */ + zoneDataVersion: number + /** + * One entry per Zone Data TLV8. + */ + zoneData: CameraZoneData[] +} + +function writeVertices(vertices: CameraZoneVertex[]): Buffer { + const buffer = Buffer.alloc(vertices.length * VERTEX_LENGTH) + + for (const [index, [x, y]] of vertices.entries()) { + buffer.writeUInt16LE(x, index * VERTEX_LENGTH) + buffer.writeUInt16LE(y, index * VERTEX_LENGTH + 2) + } + + return buffer +} + +function readVertices(field: TLVField): CameraZoneVertex[] { + if (field.value.length % VERTEX_LENGTH !== 0) { + throw new RangeError(`The length of the ${field.name} field, ${field.value.length}, is not a whole number of four-byte vertices.`) + } + + const vertices: CameraZoneVertex[] = [] + + for (let offset = 0; offset < field.value.length; offset += VERTEX_LENGTH) { + vertices.push([ + field.value.readUInt16LE(offset), + field.value.readUInt16LE(offset + 2), + ]) + } + + return vertices +} + +function encodePolygon(polygon: CameraZonePolygon): Buffer { + return encode( + PolygonTypes.IDENTIFIER, writeUUID(polygon.identifier, 'Identifier'), + PolygonTypes.VERTICES, writeVertices(polygon.vertices), + ) +} + +function decodePolygon(buffer: Buffer): CameraZonePolygon { + const fields = decodeFields(buffer) + + return { + identifier: readUUID(requiredField(fields, PolygonTypes.IDENTIFIER, 'Identifier')), + vertices: readVertices(requiredField(fields, PolygonTypes.VERTICES, 'Vertices')), + } +} + +function encodeZoneData(zoneData: CameraZoneData): Buffer { + return encode( + ZoneDataTypes.METHOD, writeUInt8(zoneData.method), + ZoneDataTypes.POLYGONS, zoneData.polygons.map(encodePolygon), + ) +} + +function decodeZoneData(buffer: Buffer): CameraZoneData { + const fields = decodeFields(buffer) + + return { + method: readEnum(requiredField(fields, ZoneDataTypes.METHOD, 'Method'), CAMERA_ZONE_APPLICATION_METHOD_VALUES), + polygons: listField(fields, ZoneDataTypes.POLYGONS).map(decodePolygon), + } +} + +/** + * Encodes a Camera Zones value. + * @param payload - The value's model. + * @returns The base64 characteristic value. + */ +export function encodeCameraZones(payload: CameraZonesPayload): string { + return encode( + CameraZonesTypes.ZONE_DATA_VERSION, writeUInt8(payload.zoneDataVersion), + CameraZonesTypes.ZONE_DATA, payload.zoneData.map(encodeZoneData), + ).toString('base64') +} + +/** + * Decodes a Camera Zones value, refusing a Zone Data version other than 2, since the version decides how the Zone Data reads. + * @param value - The base64 characteristic value. + * @returns The value's model. + */ +export function decodeCameraZones(value: string): CameraZonesPayload { + const fields = decodeBase64Fields(value) + const zoneDataVersion = readUInt8(requiredField(fields, CameraZonesTypes.ZONE_DATA_VERSION, 'Zone Data Version')) + + if (zoneDataVersion !== ZONE_DATA_VERSION) { + throw new RangeError(`The Zone Data Version field holds ${zoneDataVersion}, but only version ${ZONE_DATA_VERSION} is read.`) + } + + return { + zoneDataVersion, + zoneData: listField(fields, CameraZonesTypes.ZONE_DATA).map(decodeZoneData), + } +} diff --git a/src/lib/camera/index.ts b/src/lib/camera/index.ts index 320a11f5b..4a4ef1739 100644 --- a/src/lib/camera/index.ts +++ b/src/lib/camera/index.ts @@ -1,3 +1,4 @@ +export * from './capabilities/index.js' export * from './RecordingManagement.js' export * from './RTPProxy.js' export * from './RTPStreamManagement.js' diff --git a/src/lib/util/counted.spec.ts b/src/lib/util/counted.spec.ts new file mode 100644 index 000000000..fd61c6dc2 --- /dev/null +++ b/src/lib/util/counted.spec.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest' + +import { counted, nounFor } from './counted.js' + +describe('nounFor', () => { + it('answers the plural at zero', () => { + expect(nounFor(0, 'segment')).toBe('segments') + }) + + it('answers the singular at one', () => { + expect(nounFor(1, 'segment')).toBe('segment') + }) + + it('answers the plural at two', () => { + expect(nounFor(2, 'segment')).toBe('segments') + }) + + it('answers a stated plural that is no added "s" at every count but one, and the singular at one', () => { + expect([0, 1, 2].map(count => nounFor(count, 'vertex', 'vertices'))).toEqual(['vertices', 'vertex', 'vertices']) + }) + + it('defaults the plural to the singular with "s" when the plural is passed as undefined, as counted passes an unstated one', () => { + expect([0, 1, 2].map(count => nounFor(count, 'receive key', undefined))).toEqual(['receive keys', 'receive key', 'receive keys']) + }) +}) + +describe('counted', () => { + it('answers the count and the plural at zero', () => { + expect(counted(0, 'segment')).toBe('0 segments') + }) + + it('answers the count and the singular at one', () => { + expect(counted(1, 'segment')).toBe('1 segment') + }) + + it('answers the count and the plural at two', () => { + expect(counted(2, 'segment')).toBe('2 segments') + }) + + it('answers the count and a stated plural that is no added "s" at every count but one', () => { + expect([0, 1, 2].map(count => counted(count, 'vertex', 'vertices'))).toEqual(['0 vertices', '1 vertex', '2 vertices']) + }) +}) diff --git a/src/lib/util/counted.ts b/src/lib/util/counted.ts new file mode 100644 index 000000000..d4f96bbc1 --- /dev/null +++ b/src/lib/util/counted.ts @@ -0,0 +1,27 @@ +/* The form a noun takes beside a count in a sentence the library prints: the singular at one and the plural at every other count, zero among them. A + * sentence whose noun follows its count takes `counted`, and one with words between the count and its noun takes `nounFor`. + */ + +/** + * The form a noun takes beside a count: the singular at one and the plural at every other count, zero among them. + * @param count - The count the noun stands beside. + * @param singular - The noun's singular. + * @param plural - The noun's plural, the singular with "s" unless stated. + * @returns The noun in the form its count takes. + */ +export function nounFor(count: number, singular: string, plural = `${singular}s`): string { + return count === 1 + ? singular + : plural +} + +/** + * A count, a space and its noun in the form the count takes, as "1 segment" and "3 segments". + * @param count - The count. + * @param singular - The noun's singular. + * @param plural - The noun's plural, the singular with "s" unless stated. + * @returns The count and its noun. + */ +export function counted(count: number, singular: string, plural?: string): string { + return `${count} ${nounFor(count, singular, plural)}` +} From 193a6b1f287d4e9150278a4343d9fbb07e10a792 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:46 -0600 Subject: [PATCH 08/16] feat(camera): add the camera diagnostics and the session plane every service a hub commands shares, each controller handed its accessory's context --- src/lib/Accessory.ts | 81 ++++ src/lib/camera/StreamingOptions.ts | 37 ++ .../camera/diagnostics/CameraReporter.spec.ts | 281 +++++++++++++ src/lib/camera/diagnostics/CameraReporter.ts | 251 +++++++++++ .../camera/diagnostics/debugChannels.spec.ts | 61 +++ src/lib/camera/diagnostics/debugChannels.ts | 96 +++++ src/lib/camera/diagnostics/problems.spec.ts | 180 ++++++++ src/lib/camera/diagnostics/problems.ts | 210 ++++++++++ src/lib/camera/index.ts | 4 + src/lib/camera/session/CommandQueue.spec.ts | 84 ++++ src/lib/camera/session/CommandQueue.ts | 22 + .../camera/session/ConnectionSessions.spec.ts | 391 ++++++++++++++++++ src/lib/camera/session/ConnectionSessions.ts | 258 ++++++++++++ src/lib/camera/session/HandleScope.spec.ts | 262 ++++++++++++ src/lib/camera/session/HandleScope.ts | 107 +++++ src/lib/camera/session/controlPoint.spec.ts | 195 +++++++++ src/lib/camera/session/controlPoint.ts | 104 +++++ src/lib/camera/session/settleWithin.spec.ts | 101 +++++ src/lib/camera/session/settleWithin.ts | 66 +++ src/lib/controller/Controller.ts | 41 ++ src/lib/util/promise-utils.spec.ts | 181 ++++++++ src/lib/util/promise-utils.ts | 84 ++++ src/test-utils/reporterFixtures.ts | 72 ++++ src/test-utils/settle.ts | 50 +++ 24 files changed, 3219 insertions(+) create mode 100644 src/lib/camera/StreamingOptions.ts create mode 100644 src/lib/camera/diagnostics/CameraReporter.spec.ts create mode 100644 src/lib/camera/diagnostics/CameraReporter.ts create mode 100644 src/lib/camera/diagnostics/debugChannels.spec.ts create mode 100644 src/lib/camera/diagnostics/debugChannels.ts create mode 100644 src/lib/camera/diagnostics/problems.spec.ts create mode 100644 src/lib/camera/diagnostics/problems.ts create mode 100644 src/lib/camera/session/CommandQueue.spec.ts create mode 100644 src/lib/camera/session/CommandQueue.ts create mode 100644 src/lib/camera/session/ConnectionSessions.spec.ts create mode 100644 src/lib/camera/session/ConnectionSessions.ts create mode 100644 src/lib/camera/session/HandleScope.spec.ts create mode 100644 src/lib/camera/session/HandleScope.ts create mode 100644 src/lib/camera/session/controlPoint.spec.ts create mode 100644 src/lib/camera/session/controlPoint.ts create mode 100644 src/lib/camera/session/settleWithin.spec.ts create mode 100644 src/lib/camera/session/settleWithin.ts create mode 100644 src/lib/util/promise-utils.spec.ts create mode 100644 src/test-utils/reporterFixtures.ts create mode 100644 src/test-utils/settle.ts diff --git a/src/lib/Accessory.ts b/src/lib/Accessory.ts index e5faeffd9..9f49f65a0 100644 --- a/src/lib/Accessory.ts +++ b/src/lib/Accessory.ts @@ -26,6 +26,8 @@ import type { ControllerIdentifier, ControllerServiceMap, } from './controller/Controller.js' +import type { ControllerAccessoryContext } from './controller/index.js' +import type { AccessoryInformation } from './definitions/index.js' import type { AccessoriesCallback, AddPairingCallback, @@ -83,6 +85,7 @@ import { clone } from './util/clone.js' import { errorMessage, errorStack } from './util/errors.js' import { HapStatusError } from './util/hapStatusError.js' import { once } from './util/once.js' +import { callDelegate } from './util/promise-utils.js' import { extractHAPStatusFromError, formatOutgoingCharacteristicValue } from './util/request-util.js' import * as uuid from './util/uuid.js' import { toShortForm } from './util/uuid.js' @@ -759,6 +762,7 @@ export class Accessory extends EventEmitter { this.bridgedAccessories.push(accessory) this.controllerStorage.linkAccessory(accessory) // init controllers of bridged accessory + accessory.handAccessoryContext() if (!deferUpdate) { this.enqueueConfigurationUpdate() @@ -804,6 +808,7 @@ export class Accessory extends EventEmitter { } this.controllerStorage.unlinkAccessory(accessory) + accessory.handAccessoryContext() if (!deferUpdate) { this.enqueueConfigurationUpdate() @@ -938,6 +943,8 @@ export class Accessory extends EventEmitter { if (controller instanceof CameraController) { // save CameraController for Snapshot handling this.activeCameraController = controller } + + this.handAccessoryContext() } /** @@ -961,6 +968,10 @@ export class Accessory extends EventEmitter { if (isSerializableController(controller)) { // this will reset the state change delegate before we call handleControllerRemoved() this.controllerStorage.untrackController(controller) + // The controller leaves the accessory, and it alone is handed a context reading not published, before its factory reset, through the hand's guard: + // a failure there is logged and the removal runs on. + callDelegate(() => controller.handleAccessoryContext?.(this.accessoryContext(false)), + `[${this.displayName}] A controller failed to take its accessory's context`) } if (controller.handleFactoryReset) { @@ -986,6 +997,42 @@ export class Accessory extends EventEmitter { } } + /* Hands each serializable controller of this accessory the accessory's context: its Accessory Information service, its UUID, the username it is + * published under and whether it is published, which it is while it holds a server, the username and the server read from its bridge for a bridged + * accessory. It runs at every controller configure, at every publish once the controller storage has restored what it holds and again at the publish's + * end, at the unpublish that drops the server, before its first wait, and at every link and unlink. A destroy hands it reading not published once its + * data is removed, and a controller being removed is handed it alone, reading not published, before its factory reset. A controller treats a context + * whose username, UUID and published state are unchanged as no change. + * + * Each controller's hand is guarded: a throw or a rejection is logged once as that controller's failure, and the hand goes on to the accessory's other + * controllers, a bridge's to every bridged accessory after it, and its caller runs to its end. A controller's handler writes characteristics, a camera's + * as it leaves service, and the library emits a characteristic's change event with no guard. A listener a plugin attached there can throw out of the + * hand, and Homebridge's shutdown calls unpublish with nothing above it to answer for a failure. A controller whose handler failed is left as far as its + * handler got. + */ + private handAccessoryContext(published = (this.bridged ? this.bridge?._server : this._server) !== undefined): void { + const context = this.accessoryContext(published) + + for (const { controller } of Object.values(this.controllers)) { + if (isSerializableController(controller)) { + callDelegate(() => controller.handleAccessoryContext?.(context), `[${this.displayName}] A controller failed to take its accessory's context`) + } + } + } + + // The context a controller of this accessory is handed, its username read from its bridge for a bridged accessory. + private accessoryContext(published: boolean): ControllerAccessoryContext { + const accessoryInformation = this.getService(Service.AccessoryInformation) as AccessoryInformation + const username = (this.bridged ? this.bridge?._accessoryInfo : this._accessoryInfo)?.username + + return { + accessoryInformation, + accessoryUUID: this.UUID, + published, + username, + } + } + private handleAccessoryUnpairedForControllers(): void { for (const context of Object.values(this.controllers)) { const controller = context.controller @@ -1399,6 +1446,12 @@ export class Accessory extends EventEmitter { this.controllerStorage.load(info.username) // initializing controller data } + // The accessory's controllers and every bridged accessory's learn the username they are published under, after the first publish's restore above. + this.handAccessoryContext() + for (const accessory of this.bridgedAccessories) { + accessory.handAccessoryContext() + } + // assign aid/iid this._assignIDs(this._identifierCache) @@ -1491,12 +1544,21 @@ export class Accessory extends EventEmitter { this._server.listen(info.port, parsed.serverAddress) this.initialized = true + + // The accessory's controllers and every bridged accessory's learn that it is published once it holds its server, in this call rather than at the + // server's listening event. + this.handAccessoryContext() + for (const accessory of this.bridgedAccessories) { + accessory.handAccessoryContext() + } } /** * Removes this Accessory from the local network * Accessory object will no longer be valid after invoking this method * Trying to invoke publish() on the object will result in undefined behavior + * + * Its controllers, and those of each accessory bridged to it, hear that it is not published, and a camera ends its own streams within the call. */ public destroy(): Promise { const promise = this.unpublish() @@ -1509,11 +1571,23 @@ export class Accessory extends EventEmitter { this.controllerStorage.cancelQueuedSave() // it would write the file again which was just removed this.controllerStorage = new ControllerStorage(this) } + + // The controllers and every bridged accessory's learn, once the data is removed, that the accessory is not published and, unless it is bridged, is + // published under no username: none writes its removed data again. + this.handAccessoryContext(false) + for (const accessory of this.bridgedAccessories) { + accessory.handAccessoryContext(false) + } this.removeAllListeners() return promise } + /** + * Removes this accessory from the network, closing its HAP server and ending its advertisement. Its controllers, and those of each accessory bridged to + * it, hear that it is not published before the call's first wait, which means a camera ends its own streams within the call's synchronous part. A controller's + * failure there is logged and stops nothing of the unpublish. + */ public async unpublish(): Promise { this.unpublishCount++ // cancels a publish() which is still checking its advertiser if (this.configurationChangeDebounceTimeout) { @@ -1524,6 +1598,13 @@ export class Accessory extends EventEmitter { if (this._server) { this._server.destroy() this._server = undefined + + // The controllers and every bridged accessory's learn that the accessory is not published before the first wait, which means the call's synchronous part + // tells them. + this.handAccessoryContext() + for (const accessory of this.bridgedAccessories) { + accessory.handAccessoryContext() + } } if (this._advertiser) { // noinspection JSIgnoredPromiseFromCall diff --git a/src/lib/camera/StreamingOptions.ts b/src/lib/camera/StreamingOptions.ts new file mode 100644 index 000000000..268d76757 --- /dev/null +++ b/src/lib/camera/StreamingOptions.ts @@ -0,0 +1,37 @@ +/** + * How a plugin registers what it makes on a handle the library gives it, for something whose life the library decides: the plugin registers each resource + * as it makes it, and the library releases every registration once, where the handle's life ends, whichever way it ends, and the plugin releases none of + * it itself. + * + * The release calls each cleanup in that one call, newest first, through the library's guard, and awaits none: a throw, or the rejection of a promise a + * cleanup answers, is a `plugin-failure` problem on the camera's channel, printed where nothing subscribes, and every other cleanup is still called. A + * cleanup's answer is read for a promise's rejection alone, and a cleanup that answers a promise carries on past that call. A plugin that needs one + * cleanup finished before another begins registers one function that awaits the first and then calls the second. A registration made once the release has + * begun is released in a turn of its own, never inside the call that registers it: the line after it always runs first. The platform's + * `AsyncDisposableStack` differs here, since it awaits each cleanup before the next and refuses a registration once it is disposed. A value with neither + * dispose method, or a `defer` of no function, throws a `TypeError`. + * + * `use` and `defer` are called on their handle, as `stream.use(...)` and `talker.defer(...)` are, and one taken off a tier's stream and called alone throws + * a `TypeError`, as a method taken off the platform's stack does. + * + * Nothing registered is taken back. A plugin that replaces its source at a reconnect registers one function, once, that stops whichever source is + * current, rather than each source it makes, which would keep every earlier source for the handle's life. + * + * @group Camera + */ +export interface ResourceScope { + /** + * Registers a disposable, which the library disposes at the release through its `[Symbol.asyncDispose]` where it has one and its `[Symbol.dispose]` + * otherwise, as `await using` chooses, the method read as the value is registered and called on the value. A resource is made and registered in one + * line. Null and undefined register nothing. A value with neither method throws a `TypeError` and registers nothing. + * @param value - The disposable, or null or undefined. + * @returns The value, unchanged. + */ + use(value: T): T + /** + * Registers a function, which the library calls with no argument at the release, for what has a stop of its own and no dispose method. A value that is + * no function throws a `TypeError` and registers nothing. + * @param release - The function. + */ + defer(release: () => unknown): void +} diff --git a/src/lib/camera/diagnostics/CameraReporter.spec.ts b/src/lib/camera/diagnostics/CameraReporter.spec.ts new file mode 100644 index 000000000..a86f6b7b9 --- /dev/null +++ b/src/lib/camera/diagnostics/CameraReporter.spec.ts @@ -0,0 +1,281 @@ +import type { ControllerAccessoryContext } from '../../controller/Controller.js' +import type { CameraProblemReport, DebugBody } from './CameraReporter.js' +import type { CameraProblem } from './problems.js' + +import { channel, subscribe, unsubscribe } from 'node:diagnostics_channel' + +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' + +import { detachedReporter, namedReporter, problemsOf, reporterContext } from '../../../test-utils/reporterFixtures.js' +import { settle } from '../../../test-utils/settle.js' +import * as uuid from '../../util/uuid.js' +import { CameraReporter } from './CameraReporter.js' +import { DEBUG_NAMES } from './debugChannels.js' +import { cameraProblemsChannel } from './problems.js' + +// The synthetic cameras the rows report for, and the video sensor their problems name. +const CAMERA = uuid.generate('reporter spec camera') +const OTHER_CAMERA = uuid.generate('reporter spec other camera') +const SENSOR = uuid.generate('reporter spec sensor') + +// A problem at each level, as a part of the camera reports it. +const STALLED: CameraProblemReport = { + kind: 'tier-stalled', + level: 'warning', + sensorUUID: SENSOR, + sentence: 'The synthetic tier handed over no sample.', + tierId: 1, +} +const REFUSED: CameraProblemReport = { + kind: 'plugin-failure', + level: 'error', + sensorUUID: SENSOR, + sentence: 'The synthetic function answered no picture.', +} + +// The failure sentence the guard rows name. +const FAILURE = 'The synthetic function failed' + +// A debug channel no name of the debug list names: a DEBUG setting in the shell that runs the suite attaches no printer to it. +const SPEC_CHANNEL = 'HAP-NodeJS:Camera:ReporterSpec' + +// Every message published on the channel named while the row runs, kept as published. +function heardOn(name: string): Message[] { + const heard: Message[] = [] + const hear = (message: unknown): void => { + heard.push(message as Message) + } + + subscribe(name, hear) + onTestFinished(() => { + unsubscribe(name, hear) + }) + + return heard +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('cameraReporter', () => { + it('prints a problem\'s bare sentence at its level and publishes nothing while it reads no context, and publishes once it reads one', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const heard = heardOn(cameraProblemsChannel(CAMERA)) + let context: ControllerAccessoryContext | undefined + const reporter = new CameraReporter(() => context) + + reporter.problem(STALLED) + reporter.problem(REFUSED) + + expect(warn).toHaveBeenCalledExactlyOnceWith(STALLED.sentence) + expect(error).toHaveBeenCalledExactlyOnceWith(REFUSED.sentence) + expect(heard).toEqual([]) + expect(reporter.name).toBeUndefined() + + context = reporterContext('Camera', CAMERA) + reporter.problem(STALLED) + + expect(heard).toEqual([ + { ...STALLED, accessoryUUID: CAMERA }, + ]) + expect([warn.mock.calls.length, error.mock.calls.length]).toEqual([1, 1]) + }) + + it('prints a problem opened by its camera\'s Name at its level where the camera\'s channel has no subscriber', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const reporter = namedReporter('Front Door', CAMERA) + + reporter.problem(STALLED) + reporter.problem(REFUSED) + + expect(warn).toHaveBeenCalledExactlyOnceWith(`[Front Door] ${STALLED.sentence}`) + expect(error).toHaveBeenCalledExactlyOnceWith(`[Front Door] ${REFUSED.sentence}`) + expect(reporter.name).toBe('Front Door') + }) + + it('publishes a problem as one frozen object carrying its camera\'s accessory UUID where the camera\'s channel has a subscriber, and prints nothing', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { problems, reporter } = problemsOf(CAMERA) + + reporter.problem(STALLED) + + expect(problems).toEqual([ + { ...STALLED, accessoryUUID: CAMERA }, + ]) + expect(Object.isFrozen(problems[0])).toBe(true) + expect(warn).not.toHaveBeenCalled() + }) + + it('reports a failure at the level error, its sentence the failure\'s followed by the thrown value as it renders, the value and the fields kept', () => { + const { problems, reporter } = problemsOf(CAMERA) + const thrown = Object.assign(new Error('The synthetic call failed.'), { code: 'E_SYNTHETIC' }) + + reporter.failure('library-failure', FAILURE, thrown, { sensorUUID: SENSOR, tierId: 2 }) + reporter.failure('plugin-failure', FAILURE, 'A synthetic reason.') + + expect(problems).toEqual([ + { + accessoryUUID: CAMERA, + error: thrown, + kind: 'library-failure', + level: 'error', + sensorUUID: SENSOR, + sentence: `${FAILURE}: ${thrown.stack} {\n code: 'E_SYNTHETIC'\n}`, + tierId: 2, + }, + { + accessoryUUID: CAMERA, + error: 'A synthetic reason.', + kind: 'plugin-failure', + level: 'error', + sentence: `${FAILURE}: A synthetic reason.`, + }, + ]) + }) + + it('reports a guarded call\'s throw and its rejection and a rejection it is handed as failures of their kinds with their fields, writing no console ' + + 'line, and nothing for a rejection that settles while its signal reads aborted', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { problems, reporter } = problemsOf(CAMERA) + const thrown = new Error('The synthetic call threw.') + const rejected = new Error('The synthetic call rejected.') + const handed = new Error('The synthetic answer rejected.') + const controller = new AbortController() + + reporter.guard('plugin-failure', () => { + throw thrown + }, FAILURE, { sensorUUID: SENSOR }) + reporter.guard('library-failure', async () => { + throw rejected + }, FAILURE, { sessionIdentifier: 'synthetic-session' }) + reporter.rejection('plugin-failure', Promise.reject(handed), FAILURE, undefined, { tierId: 3 }) + reporter.rejection('plugin-failure', Promise.reject(new Error('The synthetic answer was cut.')), FAILURE, controller.signal) + controller.abort() + await settle() + + expect(problems.map(problem => [problem.kind, problem.sentence, 'error' in problem && problem.error])).toEqual([ + ['plugin-failure', `${FAILURE}: ${thrown.stack}`, thrown], + ['library-failure', `${FAILURE}: ${rejected.stack}`, rejected], + ['plugin-failure', `${FAILURE}: ${handed.stack}`, handed], + ]) + expect(problems.map(({ sensorUUID, sessionIdentifier, tierId }: Partial>) => ({ sensorUUID, sessionIdentifier, tierId }))) + .toEqual([ + { sensorUUID: SENSOR, sessionIdentifier: undefined, tierId: undefined }, + { sensorUUID: undefined, sessionIdentifier: 'synthetic-session', tierId: undefined }, + { sensorUUID: undefined, sessionIdentifier: undefined, tierId: 3 }, + ]) + expect(error).not.toHaveBeenCalled() + }) + + it('builds no debug event while its channel has no subscriber, and publishes a frozen one carrying its camera\'s accessory UUID otherwise, and none ' + + 'for a camera that holds no context, its writer alike', () => { + const debugChannel = channel(SPEC_CHANNEL) + const build = vi.fn<() => DebugBody>(() => ({ sentence: 'The synthetic tier ran past its peak.', tierId: 4 })) + const reporter = namedReporter('Camera', CAMERA) + + reporter.debug(debugChannel, 'peak-passed', build) + reporter.writer(debugChannel)('peak-passed', build) + + expect(DEBUG_NAMES).not.toContain(SPEC_CHANNEL) + expect(build).not.toHaveBeenCalled() + + const heard = heardOn>(SPEC_CHANNEL) + + reporter.debug(debugChannel, 'peak-passed', build) + reporter.writer(debugChannel)('peak-passed', build) + detachedReporter().debug(debugChannel, 'peak-passed', build) + + const event = { kind: 'peak-passed', sentence: 'The synthetic tier ran past its peak.', tierId: 4 } + + expect(heard).toEqual([ + { ...event, accessoryUUID: CAMERA }, + { ...event, accessoryUUID: CAMERA }, + event, + ]) + expect(heard.map(published => Object.isFrozen(published))).toEqual([true, true, true]) + expect('accessoryUUID' in heard[2]).toBe(false) + expect(build).toHaveBeenCalledTimes(3) + }) + + it('keeps the context its reader answered at its retirement for every later report and its Name, whatever the reader answers after', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const heard = heardOn(cameraProblemsChannel(CAMERA)) + let context: ControllerAccessoryContext | undefined = reporterContext('Camera', CAMERA) + const reporter = new CameraReporter(() => context) + + reporter.retire() + context = undefined + reporter.problem(STALLED) + context = reporterContext('Other Camera', OTHER_CAMERA) + reporter.problem(STALLED) + + expect(heard).toEqual([ + { ...STALLED, accessoryUUID: CAMERA }, + { ...STALLED, accessoryUUID: CAMERA }, + ]) + expect(reporter.name).toBe('Camera') + expect(warn).not.toHaveBeenCalled() + }) + + describe('a restore\'s problems', () => { + it('holds each problem while it reads no context, publishing and printing none, reports them in their order at its release through the context it ' + + 'reads then, and holds and prints nothing after, at the end of the step among them', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const heard = heardOn(cameraProblemsChannel(CAMERA)) + let context: ControllerAccessoryContext | undefined + const reporter = new CameraReporter(() => context) + + reporter.holdProblems() + reporter.problem(STALLED) + reporter.problem(REFUSED) + + const before = [heard.length, warn.mock.calls.length, error.mock.calls.length] + + context = reporterContext('Camera', CAMERA) + reporter.releaseProblems() + + const released = [...heard] + + context = undefined + await settle() + + expect(before).toEqual([0, 0, 0]) + expect(released).toEqual([ + { ...STALLED, accessoryUUID: CAMERA }, + { ...REFUSED, accessoryUUID: CAMERA }, + ]) + expect([heard.length, warn.mock.calls.length, error.mock.calls.length]).toEqual([2, 0, 0]) + }) + + it('prints each held problem\'s bare sentence once at the end of the step where no context arrives', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const reporter = detachedReporter() + + reporter.holdProblems() + reporter.problem(STALLED) + reporter.problem(REFUSED) + + const before = [warn.mock.calls.length, error.mock.calls.length] + + await settle() + + const atEnd = [warn.mock.calls.length, error.mock.calls.length] + + // The step's end released the hold, and a later release finds nothing held and prints nothing more. + reporter.releaseProblems() + await settle() + + expect([before, atEnd]).toEqual([ + [0, 0], + [1, 1], + ]) + expect(warn).toHaveBeenCalledExactlyOnceWith(STALLED.sentence) + expect(error).toHaveBeenCalledExactlyOnceWith(REFUSED.sentence) + }) + }) +}) diff --git a/src/lib/camera/diagnostics/CameraReporter.ts b/src/lib/camera/diagnostics/CameraReporter.ts new file mode 100644 index 000000000..48b4bfd84 --- /dev/null +++ b/src/lib/camera/diagnostics/CameraReporter.ts @@ -0,0 +1,251 @@ +import type { Channel } from 'node:diagnostics_channel' + +import type { ControllerAccessoryContext } from '../../controller/Controller.js' +import type { DelegateFailureReport } from '../../util/promise-utils.js' +import type { CameraProblem } from './problems.js' + +import { channel } from 'node:diagnostics_channel' + +import { Characteristic } from '../../Characteristic.js' +import { callDelegate, logDelegateRejection, renderThrown } from '../../util/promise-utils.js' +import { cameraProblemsChannel } from './problems.js' + +// A problem's own fields, every member of the union but the accessory's UUID, which the reporter adds from the context it reads. +type WithoutUUID = Problem extends unknown ? Omit : never + +/** + * A problem as a part of the camera reports it, without the accessory's UUID. + */ +export type CameraProblemReport = WithoutUUID + +/** + * What a failure concerns, where it concerns a video sensor, a session or a video tier. + */ +export interface FailureFields { + readonly sensorUUID?: string + readonly sessionIdentifier?: string + readonly tierId?: number +} + +/** + * A debug event as a part of the camera builds it: its sentence and the values the sentence names. + */ +export type DebugBody = Readonly> & { + readonly sentence: string +} + +/** + * A reporter's debug events bound to one channel, for a shared helper that writes under its owner's debug name. + */ +export type DebugWriter = (kind: string, build: () => DebugBody) => void + +/** + * The Name of an accessory's Accessory Information service, as a camera's lines open with it, and empty where the service holds none. + * @param context - The context the accessory handed the camera's controller. + * @returns The accessory's Name. + */ +export function accessoryNameOf(context: ControllerAccessoryContext): string { + return String(context.accessoryInformation.getCharacteristic(Characteristic.Name).value ?? '') +} + +/** + * How a camera with the camera capabilities block reports, one for each configuration of its controller, which hands it to every part it builds. It reads + * the camera's accessory from the context the controller holds, and the camera's identity has one source: a problem is published on the camera's channel + * where that channel has a subscriber and printed opened by the camera's name where it has none, a problem of a camera that holds no accessory yet prints + * its sentence alone, and a debug event is built and published only where its channel has a subscriber. The reporter reports nothing of its own. + * + * A problem raised while the camera restores its saved state before its accessory hands it a context is held, from {@link holdProblems} to its release, + * and reported once that context arrives, named by it, or bare at the end of that step where none arrives. The restore's problems reach the camera's + * channel. The reporter keeps such problems for that step alone, and a reporter never told to hold reports each problem at once, as a class built alone + * does. + */ +export class CameraReporter { + private context: () => ControllerAccessoryContext | undefined + + // The problems a hold keeps, in the order raised, and none while no hold stands. + private held?: CameraProblemReport[] + + /** + * @param context - The reader of the context the controller holds, none before its first and after its removal. + */ + constructor(context: () => ControllerAccessoryContext | undefined) { + this.context = context + } + + /** + * The camera's Name from its Accessory Information, and none where the camera holds no accessory. + */ + get name(): string | undefined { + const context = this.context() + + return context && accessoryNameOf(context) + } + + /** + * Reports a problem. Whether it is published or printed is read from the camera's channel at each problem: nothing is kept between them, and a + * problem raised while a hold stands and the reporter reads no context is kept for the hold's release. + * @param problem - The problem, without the accessory's UUID. + */ + problem(problem: CameraProblemReport): void { + const context = this.context() + + if (!context) { + if (this.held) { + this.held.push(problem) + } else { + print(problem.level, problem.sentence) + } + + return + } + + const { accessoryUUID } = context + const problems = channel(cameraProblemsChannel(accessoryUUID)) + + if (problems.hasSubscribers) { + problems.publish(Object.freeze({ ...problem, accessoryUUID })) + + return + } + + print(problem.level, `[${accessoryNameOf(context)}] ${problem.sentence}`) + } + + /** + * Reports a failed call as a problem at the level `error`, its sentence the failure's followed by the thrown value as it renders. + * @param kind - Whose code failed. + * @param failure - The failure's sentence without its closing period. + * @param error - The value the call threw or rejected with. + * @param fields - What the failure concerns. + */ + failure(kind: 'library-failure' | 'plugin-failure', failure: string, error: unknown, fields?: FailureFields): void { + this.problem({ + ...fields, + error, + kind, + level: 'error', + sentence: `${failure}: ${renderThrown(error)}`, + }) + } + + /** + * A function that reports each failure it is handed as a {@link failure} of the kind and the fields given, for a guard of `promise-utils` to report + * through. + * @param kind - Whose code the guarded call runs. + * @param fields - What the guarded call concerns. + * @returns The report. + */ + sink(kind: 'library-failure' | 'plugin-failure', fields?: FailureFields): DelegateFailureReport { + return (failure, error) => this.failure(kind, failure, error, fields) + } + + /** + * Runs one call through `callDelegate`: the call's synchronous throw and the rejection of the thenable it returns are each a failure of the kind given. + * @param kind - Whose code the call runs. + * @param call - The call. + * @param failure - The failure's sentence without its closing period. + * @param fields - What the call concerns. + */ + guard(kind: 'library-failure' | 'plugin-failure', call: () => unknown, failure: string, fields?: FailureFields): void { + callDelegate(call, failure, this.sink(kind, fields)) + } + + /** + * Reports the rejection of a thenable a call returned through `logDelegateRejection`, as a failure of the kind given, and nothing for a rejection that + * settles while the signal given reads aborted. + * @param kind - Whose code the call ran. + * @param result - What the call returned. + * @param failure - The failure's sentence without its closing period. + * @param signal - The call's cancel signal, if it has one. + * @param fields - What the call concerns. + */ + rejection(kind: 'library-failure' | 'plugin-failure', result: unknown, failure: string, signal?: AbortSignal, fields?: FailureFields): void { + logDelegateRejection(result, failure, signal, this.sink(kind, fields)) + } + + /** + * Publishes a debug event on the channel given, built only where that channel has a subscriber: a quiet camera makes no event and no value for one. + * @param channel - The channel of the event's debug name. + * @param kind - The event's kind. + * @param build - Builds the event's sentence and the values it names. + */ + debug(channel: Channel, kind: string, build: () => DebugBody): void { + if (!channel.hasSubscribers) { + return + } + + const { sentence, ...details } = build() + const context = this.context() + + channel.publish(Object.freeze({ + ...details, + ...(context && { accessoryUUID: context.accessoryUUID }), + kind, + sentence, + })) + } + + /** + * The reporter's {@link debug} bound to one channel. + * @param channel - The channel of the owner's debug name. + * @returns The writer. + */ + writer(channel: Channel): DebugWriter { + return (kind, build) => this.debug(channel, kind, build) + } + + /** + * Begins holding each problem raised while the reporter reads no context, for a restore of the camera's saved state that runs before its accessory hands + * it a context, and changes nothing while a hold already stands. The hold ends with the step that began it: a microtask queued here releases whatever + * that hold still keeps, bare where no context arrived, and a step that ends before its context, as a throw out of the restore's own factory reset ends + * it, still prints its problems. + */ + holdProblems(): void { + if (this.held) { + return + } + + const held: CameraProblemReport[] = [] + + this.held = held + + queueMicrotask(() => { + if (this.held === held) { + this.releaseProblems() + } + }) + } + + /** + * Reports each problem the hold keeps, in the order raised, through {@link problem} as the reporter reads its context then, and holds nothing after: + * the first context names the restore's problems. A call while no hold stands does nothing. + */ + releaseProblems(): void { + const held = this.held + + this.held = undefined + + for (const problem of held ?? []) { + this.problem(problem) + } + } + + /** + * Holds the context the reader answers at this call in place of the reader. Every later report of a configuration the controller lets go names the + * camera it belonged to, whatever the controller holds after. + */ + retire(): void { + const context = this.context() + + this.context = () => context + } +} + +// Prints a problem's line at its level. +function print(level: CameraProblem['level'], line: string): void { + if (level === 'error') { + console.error(line) + } else { + console.warn(line) + } +} diff --git a/src/lib/camera/diagnostics/debugChannels.spec.ts b/src/lib/camera/diagnostics/debugChannels.spec.ts new file mode 100644 index 000000000..aefdbd9ce --- /dev/null +++ b/src/lib/camera/diagnostics/debugChannels.spec.ts @@ -0,0 +1,61 @@ +import { execFile } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' + +import { describe, expect, it } from 'vitest' + +// The repository's root, where the child process resolves the source and tsx. +const ROOT = fileURLToPath(new URL('../../../../', import.meta.url)) + +// The Tier event's sentence, carrying a percent sign alone and the marks a format string would read. +const SENTENCE = 'The synthetic tier ran at 100% of its peak, past the marks %s, %o and %%.' + +/* The child's script: it imports the debug module, which attaches its printers as it loads, attaches them a second time, publishes one event on the Tier + * channel and one on the MultiTier channel, and writes to its standard output whether each channel has a subscriber. + */ +const SCRIPT = [ + 'import { attachDebugPrinters, debugChannel } from \'./src/lib/camera/diagnostics/debugChannels.ts\'', + 'attachDebugPrinters()', + 'const tier = debugChannel(\'HAP-NodeJS:Camera:Tier\')', + 'const multiTier = debugChannel(\'HAP-NodeJS:Camera:MultiTier\')', + `tier.publish({ kind: 'peak-passed', sentence: ${JSON.stringify(SENTENCE)} })`, + 'multiTier.publish({ kind: \'packet-sent\', sentence: \'The synthetic multi-tier session sent a packet.\' })', + 'process.stdout.write(JSON.stringify({ multiTier: multiTier.hasSubscribers, tier: tier.hasSubscribers }))', +].join('\n') + +/* Runs the script in a child process of the Node line the suite runs on, its environment built from nothing but the path, tsx's cache turned off so it + * writes nothing, and the DEBUG setting given. Neither the shell's own DEBUG nor its color settings reach it. + */ +async function run(debug?: string): Promise<{ stderr: string, stdout: string }> { + const env: Record = { PATH: process.env.PATH, TSX_DISABLE_CACHE: '1' } + + if (debug !== undefined) { + env.DEBUG = debug + } + + return await promisify(execFile)(process.execPath, [ + '--import', + 'tsx', + '--input-type=module', + '-e', + SCRIPT, + ], { cwd: ROOT, env }) +} + +describe('attachDebugPrinters', () => { + it('prints each event of a name the DEBUG setting turned on at the load once, its sentence after the name with every percent sign as itself, and ' + + 'subscribes to no other name, nor to any with no DEBUG setting', async () => { + const [on, off] = await Promise.all([ + run('HAP-NodeJS:Camera:Tier'), + run(), + ]) + + expect(on.stderr.split(`HAP-NodeJS:Camera:Tier ${SENTENCE}\n`).length - 1).toBe(1) + expect(on.stderr).not.toContain('multi-tier') + expect(JSON.parse(on.stdout)).toEqual({ multiTier: false, tier: true }) + expect(off).toEqual({ + stderr: '', + stdout: JSON.stringify({ multiTier: false, tier: false }), + }) + }, 60000) +}) diff --git a/src/lib/camera/diagnostics/debugChannels.ts b/src/lib/camera/diagnostics/debugChannels.ts new file mode 100644 index 000000000..52e63f0c8 --- /dev/null +++ b/src/lib/camera/diagnostics/debugChannels.ts @@ -0,0 +1,96 @@ +import type { Channel } from 'node:diagnostics_channel' + +import { channel, subscribe } from 'node:diagnostics_channel' +import { inspect } from 'node:util' + +import createDebug from 'debug' + +/* The debug output of a camera with the camera capabilities block: every line that is not a problem is a debug event on a channel of + * `node:diagnostics_channel` named exactly as its debug name, shared by every camera, each event carrying its camera's accessory UUID. The one list of + * names below serves the channels and the DEBUG setting alike. A name a user turns on is the channel a tool subscribes to. + * + * A printer writes each event's sentence through the debug package under its channel's name, attached once, as the library loads, for each name the DEBUG + * setting turns on then. The setting is read once, as the debug package itself reads it, and a later `enable` of the debug package turns on no camera name. + * werift's own output keeps its own switch, in `werift.ts`. + */ +export const DEBUG_NAMES = [ + 'HAP-NodeJS:Camera:BufferRecorder', + 'HAP-NodeJS:Camera:CMAFRecording', + 'HAP-NodeJS:Camera:Controller', + 'HAP-NodeJS:Camera:Ingest', + 'HAP-NodeJS:Camera:MultiTier', + 'HAP-NodeJS:Camera:Recording', + 'HAP-NodeJS:Camera:RecordingManagement', + 'HAP-NodeJS:Camera:ServedRecording', + 'HAP-NodeJS:Camera:Tier', + 'HAP-NodeJS:Camera:WebRTC', + 'HAP-NodeJS:Camera:WebRTC:engine', + 'HAP-NodeJS:RecordingProvisioning', +] as const + +export type DebugName = typeof DEBUG_NAMES[number] + +/** + * A debug event, as a camera's reporter publishes it on its debug name's channel: its camera's accessory UUID, absent where the camera holds no accessory + * yet, its kind, its sentence, and the values its sentence names under the names its call site holds them by. `accessoryUUID`, `kind` and `sentence` are + * promised on every event, and every field of these events is promised too: `recording-ended` on `HAP-NodeJS:Camera:BufferRecorder` carries `dropped`, + * `outcome`, `seconds`, `segments`, `sensorUUID`, `streamId` and `tierId`, its `seconds` the length of the video in the segments it counts, the prebuffer + * among them, and `clip-finalized` on `HAP-NodeJS:Camera:CMAFRecording` carries `clipID`, `seconds` and `segments`, its `seconds` the durations its media + * playlist states for the segments it uploaded, summed. A sentence's wording is never a promise, and every other event's kind and details may change in + * any release. + */ +export interface CameraDebugEvent { + readonly accessoryUUID?: string + readonly kind: string + readonly sentence: string + readonly [detail: string]: unknown +} + +// The key of the process's registry of the names a printer writes, a key of the process rather than of this module: every copy of the library loaded +// in one process reads the one registry. +const PRINTED_NAMES = Symbol.for('HAP-NodeJS:Camera:DebugPrinters') + +/** + * The channel of one debug name. + * @param name - The debug name. + * @returns The channel named exactly as the debug name. + */ +export function debugChannel(name: DebugName): Channel { + return channel(name) +} + +/** + * A value as a debug event's sentence shows it, the form the debug package's `%o` writes with its colors off: inspected, each line trimmed and the lines + * joined by a space. An array long enough for inspect to break over several lines stays on one. + * @param value - The value. + * @returns The value's text. + */ +export function inspectInline(value: unknown): string { + return inspect(value).split('\n').map(line => line.trim()).join(' ') +} + +/** + * Attaches the printer of each debug name the DEBUG setting turns on and the process's registry does not yet hold. A channel's name is the process's, which is why the + * registry, kept on `globalThis`, lets a second copy of the library loaded in the same process, or a second call, attach no second printer, and each line + * prints once. A name joins the registry once and never leaves it, as its printer is never removed. Each printer hands the debug package the sentence as an + * argument of `%s`, and a `%` in a sentence prints as itself. + */ +export function attachDebugPrinters(): void { + const registry = globalThis as typeof globalThis & { [PRINTED_NAMES]?: Set } + const printed = registry[PRINTED_NAMES] ??= new Set() + + for (const name of DEBUG_NAMES) { + if (!createDebug.enabled(name) || printed.has(name)) { + continue + } + + const write = createDebug(name) + + printed.add(name) + subscribe(name, (event) => { + write('%s', (event as CameraDebugEvent).sentence) + }) + } +} + +attachDebugPrinters() diff --git a/src/lib/camera/diagnostics/problems.spec.ts b/src/lib/camera/diagnostics/problems.spec.ts new file mode 100644 index 000000000..109cb844c --- /dev/null +++ b/src/lib/camera/diagnostics/problems.spec.ts @@ -0,0 +1,180 @@ +import type { CameraProblemReport } from './CameraReporter.js' +import type { CameraProblem } from './problems.js' + +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' + +import { namedReporter } from '../../../test-utils/reporterFixtures.js' +import { settle } from '../../../test-utils/settle.js' +import * as uuid from '../../util/uuid.js' +import { cameraProblemsChannel, onCameraProblem } from './problems.js' + +// The synthetic camera whose problems the rows publish, and the video sensor its tier problems name. +const CAMERA = uuid.generate('problems spec camera') +const SENSOR = uuid.generate('problems spec sensor') + +// The problems the rows publish, each as a part of the camera reports it. +const STALLED: CameraProblemReport = { + kind: 'tier-stalled', + level: 'warning', + sensorUUID: SENSOR, + sentence: 'The synthetic tier handed over no sample.', + tierId: 1, +} +const RESUMED: CameraProblemReport = { + kind: 'tier-resumed', + level: 'warning', + sensorUUID: SENSOR, + sentence: 'The synthetic tier hands over its samples again.', + tierId: 1, +} +const FAILED: CameraProblemReport = { + kind: 'tier-failed', + level: 'warning', + sensorUUID: SENSOR, + sentence: 'The synthetic tier failed, and the library asks for it again.', + tierId: 1, +} + +// A subscription that ends as its row finishes, whatever the row reads. No row's subscriber hears another's problems. +function subscribed(accessoryUUID: string, subscriber: (problem: CameraProblem) => void): Disposable { + const subscription = onCameraProblem(accessoryUUID, subscriber) + + onTestFinished(() => { + subscription[Symbol.dispose]() + }) + + return subscription +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('cameraProblemsChannel', () => { + it('names a camera\'s problems channel by its accessory\'s UUID', () => { + expect(cameraProblemsChannel(CAMERA)).toBe(`HAP-NodeJS:Camera:Problems:${CAMERA}`) + }) +}) + +describe('onCameraProblem', () => { + it('hands each problem published from the subscription on to every subscriber in order, as one frozen object, and none published before it', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const reporter = namedReporter('Camera', CAMERA) + const first: CameraProblem[] = [] + const second: CameraProblem[] = [] + + reporter.problem(STALLED) + subscribed(CAMERA, problem => first.push(problem)) + subscribed(CAMERA, problem => second.push(problem)) + reporter.problem(FAILED) + reporter.problem(RESUMED) + await settle() + + expect(first).toEqual([ + { ...FAILED, accessoryUUID: CAMERA }, + { ...RESUMED, accessoryUUID: CAMERA }, + ]) + expect(second.map((problem, index) => problem === first[index])).toEqual([true, true]) + expect(first.map(problem => Object.isFrozen(problem))).toEqual([true, true]) + expect(warn).toHaveBeenCalledExactlyOnceWith(`[Camera] ${STALLED.sentence}`) + }) + + it('logs a subscriber\'s throw and its rejection once each under the sentence that carries the problem\'s, and still calls the next subscriber, ' + + 'raising no uncaught exception and no unhandled rejection', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const uncaught = vi.fn<(thrown: unknown) => void>() + const unhandled = vi.fn<(reason: unknown) => void>() + const thrown = new Error('The subscriber failed.') + const rejected = new Error('The subscriber rejected.') + const heard: string[] = [] + + process.on('uncaughtException', uncaught) + process.on('unhandledRejection', unhandled) + onTestFinished(() => { + process.off('uncaughtException', uncaught) + process.off('unhandledRejection', unhandled) + }) + subscribed(CAMERA, () => { + throw thrown + }) + subscribed(CAMERA, async () => { + throw rejected + }) + subscribed(CAMERA, problem => heard.push(problem.kind)) + namedReporter('Camera', CAMERA).problem(STALLED) + await settle() + await settle() + + const failure = `A subscriber of the problems of the camera ${CAMERA} failed on the problem "${STALLED.sentence}"` + + expect(error.mock.calls).toEqual([ + [`${failure}: ${thrown.stack}`], + [`${failure}: ${rejected.stack}`], + ]) + expect(heard).toEqual(['tier-stalled']) + expect([uncaught.mock.calls, unhandled.mock.calls]).toEqual([[], []]) + }) + + it('calls a subscriber once the publishing call has returned and its microtasks run, in the order the problems were published, and hands a problem it ' + + 'publishes from inside its call over in a later microtask', async () => { + const reporter = namedReporter('Camera', CAMERA) + const heard: string[] = [] + + subscribed(CAMERA, (problem) => { + heard.push(problem.kind) + + if (problem.kind === 'tier-stalled') { + reporter.problem(RESUMED) + heard.push('published from inside') + } + }) + reporter.problem(STALLED) + reporter.problem(FAILED) + + expect(heard).toEqual([]) + + await settle() + + expect(heard).toEqual([ + 'tier-stalled', + 'published from inside', + 'tier-failed', + 'tier-resumed', + ]) + }) + + it('ends a subscription at its disposal, dropping a problem published before it and not yet handed over, and does nothing at a second disposal', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const reporter = namedReporter('Camera', CAMERA) + const ended: string[] = [] + const standing: string[] = [] + const subscription = subscribed(CAMERA, problem => ended.push(problem.kind)) + + subscribed(CAMERA, problem => standing.push(problem.kind)) + reporter.problem(STALLED) + subscription[Symbol.dispose]() + reporter.problem(RESUMED) + subscription[Symbol.dispose]() + reporter.problem(FAILED) + await settle() + + expect([ended, standing]).toEqual([ + [], + ['tier-stalled', 'tier-resumed', 'tier-failed'], + ]) + expect(warn).not.toHaveBeenCalled() + }) + + it('hands a subscription made before any reporter of its camera exists the problems of a reporter made after it', async () => { + const later = uuid.generate('problems spec later camera') + const heard: CameraProblem[] = [] + + subscribed(later, problem => heard.push(problem)) + namedReporter('Camera', later).problem(STALLED) + await settle() + + expect(heard).toEqual([ + { ...STALLED, accessoryUUID: later }, + ]) + }) +}) diff --git a/src/lib/camera/diagnostics/problems.ts b/src/lib/camera/diagnostics/problems.ts new file mode 100644 index 000000000..ae98ad79a --- /dev/null +++ b/src/lib/camera/diagnostics/problems.ts @@ -0,0 +1,210 @@ +import { subscribe, unsubscribe } from 'node:diagnostics_channel' + +import { callDelegate } from '../../util/promise-utils.js' + +// The opening of every camera's problems channel, which the accessory's UUID completes. +const PROBLEMS_CHANNEL = 'HAP-NodeJS:Camera:Problems:' + +/** + * A problem of a camera with the camera capabilities block: something a user would want to know about without turning on a debug name, published on its + * camera's channel, frozen, and handed to every subscriber as one object. Where that channel has no subscriber, the library prints the problem's sentence at + * its level, opened by the camera's name in brackets. + * + * The channel's name, `kind`, `accessoryUUID`, `level`, `sentence` and each kind's own fields are stable, and kinds are only ever added. A plugin may act + * on a kind and its fields. A sentence's wording is never a promise and may change in any release. A plugin narrows a problem to its kind's fields by + * `kind`. + * + * @group Camera + */ +export type CameraProblem = { + /** + * The UUID of the camera's accessory, as the accessory holds it. + */ + readonly accessoryUUID: string + /** + * The console level the library prints the problem at where its channel has no subscriber. + */ + readonly level: 'error' | 'warning' + /** + * What happened, as a whole sentence for a person to read. + */ + readonly sentence: string +} & ({ + /** + * A problem of one video tier of a video sensor. + */ + readonly kind: 'buffer-trimmed' | 'recording-declined' | 'segment-over-cap' | 'stream-failed' | 'stream-fault' | 'tier-failed' | 'tier-resumed' | 'tier-stalled' + /** + * The video sensor the problem concerns, in lowercase. + */ + readonly sensorUUID: string + /** + * The video tier the problem concerns. + */ + readonly tierId: number +} | { + /** + * A problem of the recordings the camera serves. + */ + readonly kind: 'store-full' + /** + * The video sensor the camera records, in lowercase. + */ + readonly sensorUUID: string +} | { + /** + * A failure of the plugin's code or of the library's own. + */ + readonly kind: 'library-failure' | 'plugin-failure' + /** + * The value the failing call threw or rejected with, as thrown, for a failure that has one. + */ + readonly error?: unknown + /** + * The video sensor the failure concerns, in lowercase, where it concerns one. + */ + readonly sensorUUID?: string + /** + * The session the failure concerns, where it concerns one. + */ + readonly sessionIdentifier?: string + /** + * The video tier the failure concerns, where it concerns one. + */ + readonly tierId?: number +} | { + /** + * A view that ended on a failure or never started. + */ + readonly kind: 'view-failed' + /** + * The video sensor viewed, in lowercase. + */ + readonly sensorUUID: string + /** + * The identifier of the view's session. + */ + readonly sessionIdentifier: string + /** + * The video tier that refused the view, for a view a tier refused. + */ + readonly tierId?: number +} | { + /** + * A record the camera keeps that could not be written. + */ + readonly kind: 'storage-failed' + /** + * The value the store threw, as thrown. + */ + readonly error: unknown +} | { + /** + * A problem of a clip's upload. + */ + readonly kind: 'upload-failed' | 'upload-refused' +} | { + /** + * A value handed to the library that it refused or corrected. + */ + readonly kind: 'value-refused' + /** + * The video sensor the value concerns, in lowercase, where it concerns one. + */ + readonly sensorUUID?: string +}) + +/** + * The kind of a {@link CameraProblem}. A tier's outage, from a stall or a failure to its next picture, is told of once however many asks it takes, as is + * the silence of a tier's stream. + * + * - `tier-stalled`: a tier the library holds stopped handing over pictures. + * - `tier-resumed`: that tier handed over a picture again, ending its outage. + * - `tier-failed`: that tier's stream failed, a silence among the failures, its start was refused or did not settle in time, or the library's own reading + * of that tier's camera buffer threw, and the library asks for it again. + * - `buffer-trimmed`: the camera buffer of that tier passed a ceiling and dropped its oldest samples, holding less than its prebuffer where the tier has + * one. + * - `segment-over-cap`: the stretch from one keyframe to the next alone reached the cap on an uploaded segment, and the segment left as it stood. + * - `store-full`: the camera's served recordings passed their ceiling of 100 MB and released their oldest bytes, whoever needed them, naming the recorded + * sensor. + * - `recording-declined`: a hub's recording was declined, the camera buffer not being ready to serve it. + * - `plugin-failure`: a function of the plugin's threw, rejected, did not settle within its bound, or answered a value the library cannot use. + * - `stream-failed`: a tier's stream failed, by the plugin's own `fail`, by the library refusing its bytes or by a silence, whoever holds the tier, and + * every session on the tier ends. A silence is a stream that hands over no first picture within 30 seconds of its start's settling, or no picture for 10 seconds + * after one or for 30 seconds from its source being stated reconnecting, sound counting for nothing, and it is told once until the tier hands over a + * picture again. + * - `stream-fault`: a tier's stream carries a fault the library sends on as it stands: a keyframe without its parameter sets, under `strict` a rate past + * twice the tier's peak, or no Opus track in the stream of the sound tier of a sensor whose audio states its source `'shared'`. + * - `view-failed`: a view from away ended on a failure, or never started: no answer accepted, a lost connection, a failed DTLS transport, no connection + * in time, or a tier that refused it. + * - `upload-failed`: a clip's upload failed. + * - `upload-refused`: no clip is uploaded, because the camera holds no usable Camera Key, told of at most once an hour. + * - `storage-failed`: a record the camera keeps could not be written. + * - `value-refused`: a value handed to the library was refused or corrected: a motion report's sensor names, a motion update with no motion sensor, a + * zones write, or saved zones that cannot be restored. + * - `library-failure`: the library's own code failed. + * + * @group Camera + */ +export type CameraProblemKind = CameraProblem['kind'] + +/** + * The name of the channel of `node:diagnostics_channel` a camera's problems are published on, for a tool that subscribes to that channel itself. + * + * A subscriber on the bare channel is called inside the library's own work as each problem is published: it must not call back into the camera, and a + * throw from it or the rejection of a promise it returns raises an uncaught exception or an unhandled rejection, which ends a Homebridge bridge. A plugin + * subscribes through {@link onCameraProblem}, which guards its subscriber and calls it after the library's work. + * + * @param accessoryUUID - The UUID of the camera's accessory, as the accessory holds it. + * @returns The channel's name. + * + * @group Camera + */ +export function cameraProblemsChannel(accessoryUUID: string): string { + return `${PROBLEMS_CHANNEL}${accessoryUUID}` +} + +/** + * Subscribes a plugin's function to the problems of the camera whose accessory has the UUID given, from the subscription on, with nothing replayed. The + * subscription is by the accessory's UUID. A plugin may make it before the camera's controller exists, and it outlasts a controller made again for that + * accessory. A plugin subscribes before it configures the camera's controller on its accessory: it hears a problem the camera's restore of its saved + * state raises, which the library holds until the accessory hands the camera its context. + * + * The subscriber is called once the library's call that raised a problem has finished, in the order the problems were raised. It may call back into the + * camera, and a problem can reach it after a controller event the same call raised. A throw from the subscriber or the rejection of a promise it returns is + * logged under a sentence of its own, which carries the problem's, and the next subscriber is still called. While any subscriber of a camera stands, the + * library prints none of that camera's problems. + * + * ```ts + * const problems = hap.onCameraProblem(accessory.UUID, problem => log.warn(problem.sentence)) + * ``` + * + * @param accessoryUUID - The UUID of the camera's accessory, as the accessory holds it. + * @param subscriber - The function each problem is handed to. + * @returns A disposable that ends the subscription at once, a problem raised and not yet handed over among those it drops, and a second disposal does + * nothing. + * + * @group Camera + */ +export function onCameraProblem(accessoryUUID: string, subscriber: (problem: CameraProblem) => void): Disposable { + const name = cameraProblemsChannel(accessoryUUID) + let live = true + const deliver = (message: unknown): void => { + const problem = message as CameraProblem + + queueMicrotask(() => { + if (live) { + callDelegate(() => subscriber(problem), `A subscriber of the problems of the camera ${accessoryUUID} failed on the problem "${problem.sentence}"`) + } + }) + } + + subscribe(name, deliver) + + return { + [Symbol.dispose]: () => { + live = false + unsubscribe(name, deliver) + }, + } +} diff --git a/src/lib/camera/index.ts b/src/lib/camera/index.ts index 4a4ef1739..bef3b58e1 100644 --- a/src/lib/camera/index.ts +++ b/src/lib/camera/index.ts @@ -1,4 +1,8 @@ export * from './capabilities/index.js' +export * from './diagnostics/problems.js' export * from './RecordingManagement.js' export * from './RTPProxy.js' export * from './RTPStreamManagement.js' +export type { + ResourceScope, +} from './StreamingOptions.js' diff --git a/src/lib/camera/session/CommandQueue.spec.ts b/src/lib/camera/session/CommandQueue.spec.ts new file mode 100644 index 000000000..c459b8b18 --- /dev/null +++ b/src/lib/camera/session/CommandQueue.spec.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' + +import { deferred, settle } from '../../../test-utils/settle.js' +import { CommandQueue } from './CommandQueue.js' + +// A command that records its start and settles only when its test releases it. +function heldCommand(log: string[], name: string): { command: () => Promise, resolve: (value: T) => void, reject: (reason: Error) => void } { + const { promise, resolve, reject } = deferred() + + return { + command: async () => { + log.push(`${name} started`) + return promise + }, + resolve, + reject, + } +} + +describe('commandQueue', () => { + it('runs commands in arrival order, one at a time', async () => { + const queue = new CommandQueue() + const log: string[] = [] + const first = heldCommand(log, 'first') + const second = heldCommand(log, 'second') + const third = heldCommand(log, 'third') + + const results = [ + queue.run(first.command), + queue.run(second.command), + queue.run(third.command), + ] + await settle() + + expect(log).toEqual(['first started']) + + first.resolve('one') + await settle() + + expect(log).toEqual(['first started', 'second started']) + + second.resolve('two') + third.resolve('three') + + await expect(Promise.all(results)).resolves.toEqual(['one', 'two', 'three']) + expect(log).toEqual(['first started', 'second started', 'third started']) + }) + + it('rejects only the caller whose command rejects and runs the next command', async () => { + const queue = new CommandQueue() + const log: string[] = [] + const failing = heldCommand(log, 'failing') + const next = heldCommand(log, 'next') + const failure = new Error('The command failed.') + + const failed = queue.run(failing.command) + const following = queue.run(next.command) + + failing.reject(failure) + + await expect(failed).rejects.toBe(failure) + await settle() + + expect(log).toEqual(['failing started', 'next started']) + + next.resolve('ran') + + await expect(following).resolves.toBe('ran') + }) + + it('answers each caller with its own command\'s value', async () => { + const queue = new CommandQueue() + + const [number, text, object] = await Promise.all([ + queue.run(async () => 1), + queue.run(async () => 'two'), + queue.run(async () => ({ three: 3 })), + ]) + + expect(number).toBe(1) + expect(text).toBe('two') + expect(object).toEqual({ three: 3 }) + }) +}) diff --git a/src/lib/camera/session/CommandQueue.ts b/src/lib/camera/session/CommandQueue.ts new file mode 100644 index 000000000..f5cee3337 --- /dev/null +++ b/src/lib/camera/session/CommandQueue.ts @@ -0,0 +1,22 @@ +/** + * Runs a service's control-point commands one at a time, in the order they arrive. A command that awaits a delegate holds the queue until it settles. + * The capacity check, the change to the session table and the response it makes are atomic across those awaits, which `handleSetRequest` alone does not + * guarantee. A command's rejection reaches only its own caller, and the next command runs as if it had resolved. The queue sets no timer and no capacity: + * a command that must be bounded bounds its own awaits. + */ +export class CommandQueue { + // The settlement of the most recent command, never a rejection: each command starts once every earlier one has resolved or rejected. + private tail: Promise = Promise.resolve() + + /** + * Runs a command once every command queued before it has settled. + * @param command - The command, started only when its turn comes. + * @returns The command's own result, or its rejection. + */ + run(command: () => Promise): Promise { + const result = this.tail.then(command) + this.tail = result.then(() => undefined, () => undefined) + + return result + } +} diff --git a/src/lib/camera/session/ConnectionSessions.spec.ts b/src/lib/camera/session/ConnectionSessions.spec.ts new file mode 100644 index 000000000..022882e3f --- /dev/null +++ b/src/lib/camera/session/ConnectionSessions.spec.ts @@ -0,0 +1,391 @@ +import type { HAPConnection } from '../../util/eventedhttp.js' +import type { DebugWriter } from '../diagnostics/CameraReporter.js' +import type { CameraDebugEvent } from '../diagnostics/debugChannels.js' +import type { TableSession } from './ConnectionSessions.js' + +import { describe, expect, it, vi } from 'vitest' + +import { buildEmitterConnection } from '../../../test-utils/connectionFixtures.js' +import { deferred, settle } from '../../../test-utils/settle.js' +import { Characteristic, Formats, Perms } from '../../Characteristic.js' +import { Service } from '../../Service.js' +import * as uuid from '../../util/uuid.js' +import { ConnectionSessions } from './ConnectionSessions.js' + +// The word the exit's line names a session by here. +const KIND = 'fixture' + +// The answers the rows' connections hold on the control point, each a value the control point's handler answers its writer with. +const ANSWER = 'AQA=' +const OTHER_ANSWER = 'AgA=' + +// A table over a service with one transient control point, whose handler answers each write with the value written, which means a connection that writes holds that +// answer, and over a debug writer that records each event the exit writes. +function table(): { controlPoint: Characteristic, exits: CameraDebugEvent[], sessions: ConnectionSessions } { + const service = new Service('Session Table', uuid.generate('ConnectionSessions')) + const controlPoint = service.addCharacteristic(new Characteristic('Control Point', uuid.generate('ConnectionSessions control point'), { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + })) + const exits: CameraDebugEvent[] = [] + const debug: DebugWriter = (kind, build) => { + exits.push({ + ...build(), + kind, + }) + } + + controlPoint.onSet(value => value) + + return { + controlPoint, + exits, + sessions: new ConnectionSessions(service, debug, KIND), + } +} + +// The debug event the exit writes for a session, its sentence naming the session by the table's word. +function exitEvent(sessionIdentifier: string, remoteAddress: string, reason: string): CameraDebugEvent { + return { + kind: 'session-ending', + reason, + remoteAddress, + sentence: `Ending ${KIND} session ${sessionIdentifier} from ${remoteAddress}: ${reason}.`, + sessionIdentifier, + } +} + +// A session on a connection whose disposal hands the row's callback its identifier and the session. +function session( + sessionIdentifier: string, + connection: HAPConnection, + disposed: (sessionIdentifier: string, session: TableSession) => unknown = () => undefined, +): TableSession { + const fixture: TableSession = { + sessionIdentifier, + connection, + [Symbol.asyncDispose]: async () => { + await disposed(sessionIdentifier, fixture) + }, + } + + return fixture +} + +describe('connectionSessions', () => { + it('adds, gets and removes sessions and reports their count and identifiers', () => { + const { sessions } = table() + const connection = buildEmitterConnection() + const a = session('a', connection) + const b = session('b', connection) + + sessions.add(a) + sessions.add(b) + const identifiers = sessions.identifiers() + + expect(sessions.size).toBe(2) + expect(sessions.get('a')).toBe(a) + expect(sessions.get('c')).toBeUndefined() + expect(sessions.remove('a')).toBe(a) + expect(sessions.remove('a')).toBeUndefined() + expect(sessions.size).toBe(1) + expect(sessions.identifiers()).toEqual(['b']) + expect(identifiers).toEqual(['a', 'b']) + }) + + it('holds one close listener and one listener slot per connection until its last session leaves', () => { + const { sessions } = table() + const connection = buildEmitterConnection() + const limit = connection.getMaxListeners() + + sessions.add(session('a', connection)) + sessions.add(session('b', connection)) + + expect(connection.listenerCount('closed')).toBe(1) + expect(connection.getMaxListeners()).toBe(limit + 1) + + sessions.remove('a') + + expect(connection.listenerCount('closed')).toBe(1) + expect(connection.getMaxListeners()).toBe(limit + 1) + + sessions.remove('b') + + expect(connection.listenerCount('closed')).toBe(0) + expect(connection.getMaxListeners()).toBe(limit) + }) + + it('hands each session of a closing connection and none of another to a callback that removes it', () => { + const closed = vi.fn<(sessionIdentifier: string, session: TableSession) => void>() + const { sessions } = table() + const closing = buildEmitterConnection() + const other = buildEmitterConnection() + const a1 = session('a1', closing, closed) + const a2 = session('a2', closing, closed) + + closed.mockImplementation((sessionIdentifier) => { + sessions.remove(sessionIdentifier) + }) + sessions.add(a1) + sessions.add(a2) + sessions.add(session('b1', other, closed)) + closing.emit('closed') + + expect(closed.mock.calls).toEqual([ + ['a1', a1], + ['a2', a2], + ]) + expect(sessions.identifiers()).toEqual(['b1']) + expect(closing.listenerCount('closed')).toBe(0) + expect(other.listenerCount('closed')).toBe(1) + }) + + it('skips a session of a closing connection that an earlier callback removed', () => { + const closed = vi.fn<(sessionIdentifier: string, session: TableSession) => void>() + const { sessions } = table() + const connection = buildEmitterConnection() + const a1 = session('a1', connection, closed) + + closed.mockImplementation(() => { + for (const sessionIdentifier of sessions.identifiers()) { + sessions.remove(sessionIdentifier) + } + }) + sessions.add(a1) + sessions.add(session('a2', connection, closed)) + connection.emit('closed') + + expect(closed).toHaveBeenCalledExactlyOnceWith('a1', a1) + expect(sessions.size).toBe(0) + }) + + it('refuses a second session under a registered identifier and leaves the table as it was', () => { + const { sessions } = table() + const first = buildEmitterConnection() + const second = buildEmitterConnection() + const a = session('a', first) + + const refusal = new Error('The session identifier a is registered already, and the table refuses a second session under it.') + sessions.add(a) + + expect(() => sessions.add(session('a', second))).toThrow(refusal) + expect(sessions.get('a')).toBe(a) + expect(sessions.identifiers()).toEqual(['a']) + expect(first.listenerCount('closed')).toBe(1) + expect(second.listenerCount('closed')).toBe(0) + }) + + it('serves an authenticated connection until the table is marked destroyed, and never a connection that is not authenticated', () => { + const { sessions } = table() + const connection = buildEmitterConnection() + const closed = buildEmitterConnection() + + closed.emit('closed') + + expect(sessions.serves(connection)).toBe(true) + expect(sessions.serves(closed)).toBe(false) + + sessions.markDestroyed() + + expect(sessions.serves(connection)).toBe(false) + }) + + it('answers a session to its opener alone, and to nobody once its opener is not authenticated or the table is marked destroyed', () => { + const { sessions } = table() + const opener = buildEmitterConnection() + const other = buildEmitterConnection() + const a = session('a', opener) + + sessions.add(a) + + expect(sessions.liveSession('a', opener)).toBe(a) + expect(sessions.liveSession('a', other)).toBeUndefined() + expect(sessions.liveSession('b', opener)).toBeUndefined() + + const authenticated = vi.spyOn(opener, 'isAuthenticated').mockReturnValue(false) + + expect(sessions.liveSession('a', opener)).toBeUndefined() + + authenticated.mockRestore() + sessions.markDestroyed() + + expect(sessions.liveSession('a', opener)).toBeUndefined() + expect(sessions.get('a')).toBe(a) + }) + + it('opens a disposal once, releasing its connection\'s answer then and nothing after, and leaves another connection\'s answer held', async () => { + const { controlPoint, sessions } = table() + const opener = buildEmitterConnection() + const other = buildEmitterConnection() + const a = session('a', opener) + + sessions.add(a) + await controlPoint.handleSetRequest(ANSWER, opener) + await controlPoint.handleSetRequest(OTHER_ANSWER, other) + + expect(sessions.holds(a)).toBe(true) + expect(sessions.beginDisposal(a)).toBe(true) + expect(sessions.holds(a)).toBe(false) + await expect(controlPoint.handleGetRequest(opener)).resolves.toBe('') + await expect(controlPoint.handleGetRequest(other)).resolves.toBe(OTHER_ANSWER) + + await controlPoint.handleSetRequest(ANSWER, opener) + + expect(sessions.beginDisposal(a)).toBe(false) + await expect(controlPoint.handleGetRequest(opener)).resolves.toBe(ANSWER) + await expect(controlPoint.handleGetRequest(other)).resolves.toBe(OTHER_ANSWER) + }) + + it('leaves a later session under the same identifier registered when a replaced session\'s disposal opens again', async () => { + const { controlPoint, sessions } = table() + const connection = buildEmitterConnection() + const replaced = session('a', connection) + const successor = session('a', connection) + + sessions.add(replaced) + + expect(sessions.beginDisposal(replaced)).toBe(true) + + sessions.add(successor) + await controlPoint.handleSetRequest(ANSWER, connection) + + expect(sessions.beginDisposal(replaced)).toBe(false) + expect(sessions.get('a')).toBe(successor) + expect(sessions.holds(successor)).toBe(true) + await expect(controlPoint.handleGetRequest(connection)).resolves.toBe(ANSWER) + }) + + it('exits each session of a closing connection through the exit, its reason in the line, and none of another connection\'s', () => { + const { exits, sessions } = table() + const disposed = vi.fn<(sessionIdentifier: string) => void>() + const close = (sessionIdentifier: string, fixture: TableSession): void => { + if (sessions.beginDisposal(fixture)) { + disposed(sessionIdentifier) + } + } + const closing = buildEmitterConnection() + const other = buildEmitterConnection() + + sessions.add(session('a1', closing, close)) + sessions.add(session('a2', closing, close)) + sessions.add(session('b1', other, close)) + closing.emit('closed') + + expect(exits).toEqual([ + exitEvent('a1', closing.remoteAddress, 'its connection closed'), + exitEvent('a2', closing.remoteAddress, 'its connection closed'), + ]) + expect(disposed.mock.calls).toEqual([ + ['a1'], + ['a2'], + ]) + expect(sessions.identifiers()).toEqual(['b1']) + expect(closing.listenerCount('closed')).toBe(0) + expect(other.listenerCount('closed')).toBe(1) + }) + + it('resolves an end only once the session\'s whole disposal has, its promise pending after a settle while the disposal is held', async () => { + const { sessions } = table() + const held = deferred() + const resolved: string[] = [] + + sessions.add(session('a', buildEmitterConnection(), async (_sessionIdentifier, fixture) => { + if (sessions.beginDisposal(fixture)) { + await held.promise + } + })) + + const ending = sessions.end('a', 'its owner ended it').then(() => { + resolved.push('end') + }) + await settle() + + expect(sessions.size).toBe(0) + expect(resolved).toEqual([]) + + held.resolve() + await ending + + expect(resolved).toEqual(['end']) + }) + + it('prints the exit\'s debug line on a second exit of a session the table has already removed', async () => { + const { exits, sessions } = table() + const connection = buildEmitterConnection() + const a = session('a', connection, (_sessionIdentifier, fixture) => sessions.beginDisposal(fixture)) + + sessions.add(a) + await sessions.exit(a, 'its controller ended it') + await sessions.exit(a, 'its connection closed') + + expect(sessions.holds(a)).toBe(false) + expect(exits).toEqual([ + exitEvent('a', connection.remoteAddress, 'its controller ended it'), + exitEvent('a', connection.remoteAddress, 'its connection closed'), + ]) + }) + + it('passes over a connection\'s close once an earlier listener of that close has ended its last session', () => { + const { exits, sessions } = table() + const connection = buildEmitterConnection() + const a = session('a', connection, (_sessionIdentifier, fixture) => sessions.beginDisposal(fixture)) + + connection.on('closed', () => void sessions.exit(a, 'its owner ended it')) + sessions.add(a) + + expect(() => connection.emit('closed')).not.toThrow() + expect(exits).toEqual([ + exitEvent('a', connection.remoteAddress, 'its owner ended it'), + ]) + expect(sessions.size).toBe(0) + expect(connection.listenerCount('closed')).toBe(1) + }) + + it('releases every answer, a connection\'s without a session among them, before any exit starts, and starts every exit before the first resolves', async () => { + const { controlPoint, exits, sessions } = table() + const release = vi.spyOn(controlPoint, 'releaseTransientAnswers') + const held = deferred() + const started = vi.fn<(sessionIdentifier: string) => void>() + const finished = vi.fn<(sessionIdentifier: string) => void>() + const dispose = async (sessionIdentifier: string, fixture: TableSession): Promise => { + started(sessionIdentifier) + + if (sessions.beginDisposal(fixture)) { + await held.promise + finished(sessionIdentifier) + } + } + const idle = buildEmitterConnection() + const first = buildEmitterConnection() + const second = buildEmitterConnection() + + sessions.add(session('a', first, dispose)) + sessions.add(session('b', second, dispose)) + await controlPoint.handleSetRequest(ANSWER, idle) + + const ending = sessions.endAll('its owner ended it') + + expect(release.mock.calls[0]).toEqual([undefined]) + expect(release.mock.invocationCallOrder[0]).toBeLessThan(started.mock.invocationCallOrder[0]) + expect(started.mock.calls).toEqual([ + ['a'], + ['b'], + ]) + expect(finished).not.toHaveBeenCalled() + await expect(controlPoint.handleGetRequest(idle)).resolves.toBe('') + + held.resolve() + await ending + + expect(finished.mock.calls).toEqual([ + ['a'], + ['b'], + ]) + expect(exits).toEqual([ + exitEvent('a', first.remoteAddress, 'its owner ended it'), + exitEvent('b', second.remoteAddress, 'its owner ended it'), + ]) + expect(sessions.size).toBe(0) + }) +}) diff --git a/src/lib/camera/session/ConnectionSessions.ts b/src/lib/camera/session/ConnectionSessions.ts new file mode 100644 index 000000000..a7b888fc6 --- /dev/null +++ b/src/lib/camera/session/ConnectionSessions.ts @@ -0,0 +1,258 @@ +import type { Service } from '../../Service.js' +import type { HAPConnection } from '../../util/eventedhttp.js' +import type { DebugWriter } from '../diagnostics/CameraReporter.js' + +import { HAPConnectionEvent } from '../../util/eventedhttp.js' +import { releaseControlPointAnswers } from './controlPoint.js' + +// One connection's close listener and the identifiers of the sessions it opened. +interface ConnectionEntry { + readonly identifiers: Set + readonly listener: () => void +} + +/** + * A session as the session table holds it: its identifier, the HAP connection that opened it, and the disposal the table's exit runs. The disposal opens + * with {@link ConnectionSessions.beginDisposal} and does nothing more when that answers false. + */ +export interface TableSession extends AsyncDisposable { + /** + * The session's identifier, unique among the table's sessions. + */ + readonly sessionIdentifier: string + /** + * The HAP connection that opened the session. + */ + readonly connection: HAPConnection +} + +/** + * The sessions a stream service holds and the session plane over them: each session keyed by its identifier and tied to the HAP connection that opened + * it, the mark that the service is destroyed, the reads a write's handler is served by, and the one exit every path that ends a session takes. A + * connection that closes ends each of its sessions through that exit, and it never leaves a session or a slot behind. Each connection carries one close + * listener and one extra max-listener slot while it has a session here, however many it opens. + */ +export class ConnectionSessions { + private readonly sessions = new Map() + private readonly connections = new Map() + private readonly service: Service + private readonly debug: DebugWriter + private readonly kind: string + private destroyed = false + + /** + * Holds one stream service's sessions. + * @param service - The service whose control points hold the answers the table releases: a connection's when one of its sessions ends, and every one + * when every session ends. + * @param debug - The owner's debug writer. The exit's debug event goes on the owner's debug name's channel. + * @param kind - The word the exit's debug event names a session by, such as `WebRTC`. + */ + constructor(service: Service, debug: DebugWriter, kind: string) { + this.service = service + this.debug = debug + this.kind = kind + } + + /** + * The number of registered sessions. + */ + get size(): number { + return this.sessions.size + } + + /** + * Registers a session under its identifier and ties it to its connection, adding the connection's close listener with its first session. An identifier a + * registered session holds is refused with an `Error` and the table left as it was, because a caller checks the table first and only a defect reaches it. + * @param session - The session, whose identifier is unique among the registered sessions. + */ + add(session: Session): void { + const { connection, sessionIdentifier } = session + + if (this.sessions.has(sessionIdentifier)) { + throw new Error(`The session identifier ${sessionIdentifier} is registered already, and the table refuses a second session under it.`) + } + + let entry = this.connections.get(connection) + + if (!entry) { + entry = { + identifiers: new Set(), + listener: () => this.handleClosed(connection), + } + this.connections.set(connection, entry) + connection.setMaxListeners(connection.getMaxListeners() + 1) + connection.on(HAPConnectionEvent.CLOSED, entry.listener) + } + + entry.identifiers.add(sessionIdentifier) + this.sessions.set(sessionIdentifier, session) + } + + /** + * The session registered under an identifier. + * @param sessionIdentifier - The session's identifier. + * @returns The session, or `undefined` when none is registered under the identifier. + */ + get(sessionIdentifier: string): Session | undefined { + return this.sessions.get(sessionIdentifier) + } + + /** + * Whether the table still holds a session, which a command reads after each await, because an exit can run while it waits. + * @param session - The session. + * @returns Whether the session is registered under its identifier. + */ + holds(session: Session): boolean { + return this.sessions.get(session.sessionIdentifier) === session + } + + /** + * Removes a session, and with a connection's last session its close listener and its extra max-listener slot. + * @param sessionIdentifier - The session's identifier. + * @returns The removed session, or `undefined` when none was registered under the identifier. + */ + remove(sessionIdentifier: string): Session | undefined { + const session = this.sessions.get(sessionIdentifier) + + if (!session) { + return undefined + } + + this.sessions.delete(sessionIdentifier) + + const { connection } = session + const connectionEntry = this.connections.get(connection)! + + connectionEntry.identifiers.delete(sessionIdentifier) + + if (connectionEntry.identifiers.size === 0) { + this.connections.delete(connection) + connection.removeListener(HAPConnectionEvent.CLOSED, connectionEntry.listener) + connection.setMaxListeners(connection.getMaxListeners() - 1) + } + + return session + } + + /** + * The identifiers of the registered sessions. + * @returns A snapshot, which later changes to the table leave as it is. + */ + identifiers(): string[] { + return Array.from(this.sessions.keys()) + } + + /** + * Marks the service destroyed, and {@link serves} answers false from then on. It ends nothing: the owner ends its sessions after it. + */ + markDestroyed(): void { + this.destroyed = true + } + + /** + * Whether a write's handler serves it. A write waits in the service's queue, which is why its handler serves it only while the service stands and the writer's + * connection has not closed meanwhile, and a write it does not serve calls no delegate and registers nothing. + * @param connection - The writer's connection. + * @returns Whether the service is not destroyed and the connection is authenticated. + */ + serves(connection: HAPConnection): boolean { + return !this.destroyed && connection.isAuthenticated() + } + + /** + * The session a command names, when the handler serves its writer and the writer opened it. A command from any other connection finds none. + * @param sessionIdentifier - The identifier the command names. + * @param connection - The writer's connection. + * @returns The session, or `undefined` when the command reaches none. + */ + liveSession(sessionIdentifier: string, connection: HAPConnection): Session | undefined { + const session = this.serves(connection) + ? this.sessions.get(sessionIdentifier) + : undefined + + return session?.connection === connection + ? session + : undefined + } + + /** + * Ends a session through its disposal, the one exit every path that ends a session takes. The debug event comes first and on every call, a call for a + * session already removed included. The disposal starts in the caller's turn, and the promise resolves once the whole disposal has. + * @param session - The session. + * @param reason - Why the session ends, for the debug event. + */ + async exit(session: Session, reason: string): Promise { + await using ending = session + this.debug('session-ending', () => { + const { connection: { remoteAddress }, sessionIdentifier } = ending + + return { + reason, + remoteAddress, + sentence: `Ending ${this.kind} session ${sessionIdentifier} from ${remoteAddress}: ${reason}.`, + sessionIdentifier, + } + }) + } + + /** + * Opens a session's disposal. Removal comes first and guards the rest: a session the table holds goes, and the answers its connection holds on every + * control point go with it, another live session's answer on that connection among them, because an answer is held per connection and not per session. + * A session the table does not hold is left alone, and so is whatever session is registered under its identifier by then. The second disposal of a + * session whose identifier a later session has taken never removes that later session. + * @param session - The session whose disposal opens. + * @returns Whether the table held the session: a disposal that finds it gone has run already and does nothing more. + */ + beginDisposal(session: Session): boolean { + if (!this.holds(session)) { + return false + } + + this.remove(session.sessionIdentifier) + releaseControlPointAnswers(this.service, session.connection) + + return true + } + + /** + * Ends the session registered under an identifier through the exit. An identifier no registered session carries is ignored. + * @param sessionIdentifier - The session's identifier. + * @param reason - Why the session ends, for the debug event. + */ + async end(sessionIdentifier: string, reason: string): Promise { + const session = this.sessions.get(sessionIdentifier) + + if (session) { + await this.exit(session, reason) + } + } + + /** + * Releases every answer the service's control points hold, then starts every session's exit in one turn, over a snapshot of their identifiers. A + * connection can hold an answer with no session left, which is why the release reaches every connection and not only those whose sessions end here. + * @param reason - Why the sessions end, for each one's debug event. + */ + async endAll(reason: string): Promise { + releaseControlPointAnswers(this.service) + await Promise.all(this.identifiers().map(sessionIdentifier => this.end(sessionIdentifier, reason))) + } + + // A connection's close exits each of its sessions over a snapshot of their identifiers: an exit may change the table as it runs, and a session an + // earlier exit removed is passed over. The entry's last removal takes the listener with it, yet an emit under way still calls a listener that an earlier + // listener of the same emit removed. A close that finds no entry has no session left to exit and does nothing. + private handleClosed(connection: HAPConnection): void { + const entry = this.connections.get(connection) + + if (!entry) { + return + } + + for (const sessionIdentifier of Array.from(entry.identifiers)) { + const session = this.sessions.get(sessionIdentifier) + + if (session) { + void this.exit(session, 'its connection closed') + } + } + } +} diff --git a/src/lib/camera/session/HandleScope.spec.ts b/src/lib/camera/session/HandleScope.spec.ts new file mode 100644 index 000000000..8a96f0c58 --- /dev/null +++ b/src/lib/camera/session/HandleScope.spec.ts @@ -0,0 +1,262 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { detachedReporter, problemsOf } from '../../../test-utils/reporterFixtures.js' +import { settle } from '../../../test-utils/settle.js' +import { HandleScope } from './HandleScope.js' + +// The sentence the rows' scope logs a failed cleanup under, and the refusals of a registration of the wrong shape. +const FAILURE = 'The synthetic handle failed to end' +const NOT_DISPOSABLE = 'The value registered with use is not disposable: its [Symbol.asyncDispose], or its [Symbol.dispose] where that is absent, is not a function.' +const NOT_A_FUNCTION = 'The cleanup registered with defer is not a function.' + +// Each line a console spy took, its first line alone, since a logged error renders with its stack. +function firstLines(log: { mock: { calls: unknown[][] } }): string[] { + return log.mock.calls.map(([line]) => String(line).split('\n')[0]) +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('handleScope', () => { + it('answers each value use registers, calls its [Symbol.asyncDispose] where it has both and its [Symbol.dispose] where it has only that, each read as ' + + 'it is registered and called on its value, and passes null and undefined through', () => { + const scope = new HandleScope(FAILURE, detachedReporter(), {}) + const calls: [string, unknown][] = [] + const both = { + async [Symbol.asyncDispose](): Promise { + calls.push(['asyncDispose', this]) + }, + [Symbol.dispose](): void { + calls.push(['dispose', this]) + }, + } + const syncOnly = { + [Symbol.dispose](): void { + calls.push(['dispose', this]) + }, + } + + expect(scope.use(both)).toBe(both) + expect(scope.use(syncOnly)).toBe(syncOnly) + expect([ + scope.use(null), + scope.use(undefined), + ]).toEqual([null, undefined]) + + // A method assigned to a value after its registration is not the one the release calls. + both[Symbol.asyncDispose] = async (): Promise => { + calls.push(['assigned', both]) + } + syncOnly[Symbol.dispose] = (): void => { + calls.push(['assigned', syncOnly]) + } + scope.release() + + expect(calls.map(([name]) => name)).toEqual(['dispose', 'asyncDispose']) + expect(calls[0][1]).toBe(syncOnly) + expect(calls[1][1]).toBe(both) + }) + + it('calls each function defer registers at the release, with no argument', () => { + const scope = new HandleScope(FAILURE, detachedReporter(), {}) + const release = vi.fn<(...values: unknown[]) => void>() + + scope.defer(release) + + expect(release).not.toHaveBeenCalled() + + scope.release() + + expect(release.mock.calls).toEqual([[]]) + }) + + it('calls every cleanup newest first inside the release\'s own call, awaiting none, which is why a synchronous cleanup has run before the release returns and an ' + + 'asynchronous one carries on after it, and calls nothing at a second release', async () => { + const scope = new HandleScope(FAILURE, detachedReporter(), {}) + const order: string[] = [] + + scope.defer(() => { + order.push('oldest') + }) + scope.defer(async () => { + order.push('asynchronous begun') + await Promise.resolve() + order.push('asynchronous finished') + }) + scope.use({ + [Symbol.dispose]: () => { + order.push('newest') + }, + }) + scope.release() + order.push('released') + await settle() + scope.release() + await settle() + + expect(order).toEqual([ + 'newest', + 'asynchronous begun', + 'oldest', + 'released', + 'asynchronous finished', + ]) + }) + + it('logs a cleanup that throws and one that rejects once each under the scope\'s sentence, and calls every other cleanup', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const scope = new HandleScope(FAILURE, detachedReporter(), {}) + const called = vi.fn<() => void>() + + scope.defer(called) + scope.defer(async () => { + throw new Error('The synthetic feed would not close.') + }) + scope.defer(() => { + throw new Error('The synthetic encoder would not stop.') + }) + scope.defer(called) + scope.release() + await settle() + + expect(called).toHaveBeenCalledTimes(2) + expect(firstLines(error)).toEqual([ + `${FAILURE}: Error: The synthetic encoder would not stop.`, + `${FAILURE}: Error: The synthetic feed would not close.`, + ]) + }) + + it.each([ + { + cleanup: 'that throws', + // The cleanup throws in the release's own call. + defer: (scope: HandleScope, failure: Error): void => { + scope.defer(() => { + throw failure + }) + }, + }, + { + cleanup: 'that rejects', + // The cleanup's promise rejects after the release's call. + defer: (scope: HandleScope, failure: Error): void => { + scope.defer(async () => { + throw failure + }) + }, + }, + ])('raises one plugin-failure problem at the level error with the scope\'s fields and the value thrown for a cleanup $cleanup', async ({ defer }) => { + const { problems, reporter } = problemsOf() + const failure = new Error('The synthetic encoder would not stop.') + const scope = new HandleScope(FAILURE, reporter, { sensorUUID: 'synthetic-sensor', sessionIdentifier: 'synthetic-session', tierId: 2 }) + + defer(scope, failure) + scope.release() + await settle() + + // Each problem is read whole, its sentence's wording aside, and a field it gains or loses is read too. + expect(problems).toEqual([ + { + accessoryUUID: expect.any(String), + error: failure, + kind: 'plugin-failure', + level: 'error', + sensorUUID: 'synthetic-sensor', + sentence: expect.any(String), + sessionIdentifier: 'synthetic-session', + tierId: 2, + }, + ]) + }) + + it('releases in a microtask of its own a registration made inside a cleanup and one made after the release, each after the line that follows it, and ' + + 'logs its throw under the scope\'s sentence', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const scope = new HandleScope(FAILURE, detachedReporter(), {}) + const order: string[] = [] + + scope.defer(() => { + scope.defer(() => { + order.push('inside released') + }) + order.push('after the registration inside') + }) + scope.release() + order.push('released') + scope.use({ + [Symbol.dispose]: () => { + order.push('after released') + throw new Error('The synthetic late feed would not close.') + }, + }) + order.push('after the registration after') + + expect(order).toEqual(['after the registration inside', 'released', 'after the registration after']) + + await settle() + + expect(order).toEqual([ + 'after the registration inside', + 'released', + 'after the registration after', + 'inside released', + 'after released', + ]) + expect(firstLines(error)).toEqual([`${FAILURE}: Error: The synthetic late feed would not close.`]) + }) + + it('refuses a value with neither dispose method and a defer of no function with a TypeError, open and released alike, registering nothing, and passes ' + + 'null through a released scope', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const scope = new HandleScope(FAILURE, detachedReporter(), {}) + const seven = 7 as unknown as Disposable + const notAFunction = 7 as unknown as () => unknown + + for (const released of [false, true]) { + if (released) { + scope.release() + } + + expect(() => scope.use(seven)).toThrow(TypeError) + expect(() => scope.use(seven)).toThrow(NOT_DISPOSABLE) + expect(() => scope.defer(notAFunction)).toThrow(TypeError) + expect(() => scope.defer(notAFunction)).toThrow(NOT_A_FUNCTION) + } + + expect(scope.use(null)).toBe(null) + + await settle() + + expect(error).not.toHaveBeenCalled() + }) + + it('reads a value\'s [Symbol.dispose] only where its [Symbol.asyncDispose] is null or undefined, as the platform\'s stack does: an async member that is ' + + 'not callable is refused with a TypeError though the sync one is callable, and a callable async member leaves the sync one unread', () => { + const scope = new HandleScope(FAILURE, detachedReporter(), {}) + const calls: string[] = [] + const malformed = { + [Symbol.asyncDispose]: 7, + [Symbol.dispose]: (): void => void calls.push('dispose'), + } as unknown as Disposable + const nullAsync = { + [Symbol.asyncDispose]: null, + [Symbol.dispose]: (): void => void calls.push('fallback'), + } as unknown as Disposable + const unreadSync = { + [Symbol.asyncDispose]: async (): Promise => void calls.push('asyncDispose'), + get [Symbol.dispose](): never { + throw new Error('The sync member was read.') + }, + } + + expect(() => scope.use(malformed)).toThrow(TypeError) + expect(() => scope.use(malformed)).toThrow(NOT_DISPOSABLE) + expect(scope.use(nullAsync)).toBe(nullAsync) + expect(scope.use(unreadSync)).toBe(unreadSync) + + scope.release() + + expect(calls).toEqual(['asyncDispose', 'fallback']) + }) +}) diff --git a/src/lib/camera/session/HandleScope.ts b/src/lib/camera/session/HandleScope.ts new file mode 100644 index 000000000..c5bb24405 --- /dev/null +++ b/src/lib/camera/session/HandleScope.ts @@ -0,0 +1,107 @@ +import type { Nullable } from '../../../types.js' +import type { CameraReporter, FailureFields } from '../diagnostics/CameraReporter.js' +import type { ResourceScope } from '../StreamingOptions.js' + +// The refusals of a registration of the wrong shape, which a plugin reads behind the failure sentence of the start or the call its throw refuses. +const NOT_DISPOSABLE = 'The value registered with use is not disposable: its [Symbol.asyncDispose], or its [Symbol.dispose] where that is absent, is not a function.' +const NOT_A_FUNCTION = 'The cleanup registered with defer is not a function.' + +/** + * The list of what a plugin registered on one handle the library gives it, and its release, which the handle's owner calls where the handle's life ends. + * The release calls every cleanup in its one call, newest first, each through the reporter's guard and none awaited: a cleanup's throw or rejection is + * a plugin-failure problem under the handle's sentence and every other cleanup is still called, and whatever the owner does after the release comes after + * every cleanup has been called. A registration made once the release has begun is released in a microtask of its own. A resource a plugin makes after + * the handle's end is still released, and the line after its registration runs first. + */ +export class HandleScope implements ResourceScope { + // The sentence a cleanup's throw or rejection is reported under, the handle's own. + private readonly failure: string + // The camera's reporter, through which a cleanup's failure is the plugin's, with what the handle concerns. + private readonly reporter: CameraReporter + private readonly fields: FailureFields + // The cleanups in registration order: absent until the first registration, a list while the handle is open, and null once its release has begun. A + // released handle with cleanups still pending cannot be represented. + private cleanups?: Nullable<(() => unknown)[]> + + /** + * Makes an open scope, which holds nothing until its first registration. + * @param failure - The sentence a cleanup's throw or rejection is reported under. + * @param reporter - The camera's reporter, which reports a cleanup's failure as the plugin's. + * @param fields - What the handle concerns, which each failure of its cleanups carries. + */ + constructor(failure: string, reporter: CameraReporter, fields: FailureFields) { + this.failure = failure + this.reporter = reporter + this.fields = fields + } + + /** + * Registers a disposable, its shape read first: null and undefined pass through, and the value's `[Symbol.asyncDispose]`, or its `[Symbol.dispose]` + * where that member is null or undefined, is read as the value is registered and called on the value at the release, which means a method the value + * takes later changes nothing. The member is chosen as the platform's own stacks choose it: a value whose chosen member is no function throws a + * `TypeError`, open or released alike, and registers nothing. + * @param value - The disposable, or null or undefined. + * @returns The value, unchanged. + */ + use(value: T): T { + if ((value === null) || (value === undefined)) { + return value + } + + // Each member is read through unknown, since a plugin's value can satisfy the type and still carry a member that is not callable at run time. The + // sync member is read only where the async one is null or undefined: an async member that is anything else is the value's disposal, callable or not. + const dispose: unknown = (value as Partial)[Symbol.asyncDispose] ?? (value as Partial)[Symbol.dispose] + + if (typeof dispose !== 'function') { + throw new TypeError(NOT_DISPOSABLE) + } + + this.register(() => dispose.call(value)) + + return value + } + + /** + * Registers a function, called with no argument at the release. A value that is no function throws a `TypeError`, open or released alike, and registers + * nothing. + * @param release - The function. + */ + defer(release: () => unknown): void { + if (typeof release !== 'function') { + throw new TypeError(NOT_A_FUNCTION) + } + + this.register(release) + } + + /** + * Releases every registration, newest first, in this one call, and closes the scope before the first cleanup is called: a cleanup that registers + * again is released in a microtask and a second release calls nothing. + */ + release(): void { + const cleanups = this.cleanups + + this.cleanups = null + + // The list is the release's own once the field is closed, which is why it is reversed in place. + for (const cleanup of cleanups?.reverse() ?? []) { + this.guard(cleanup) + } + } + + // An open scope keeps a cleanup for its release, and a released one calls it through the guard in a microtask, never inside the registering call. + private register(cleanup: () => unknown): void { + if (this.cleanups === null) { + queueMicrotask(() => this.guard(cleanup)) + + return + } + + (this.cleanups ??= []).push(cleanup) + } + + // Calls one cleanup through the reporter's guard, its throw and its rejection each the plugin's failure under the handle's sentence. + private guard(cleanup: () => unknown): void { + this.reporter.guard('plugin-failure', cleanup, this.failure, this.fields) + } +} diff --git a/src/lib/camera/session/controlPoint.spec.ts b/src/lib/camera/session/controlPoint.spec.ts new file mode 100644 index 000000000..e7cc722c8 --- /dev/null +++ b/src/lib/camera/session/controlPoint.spec.ts @@ -0,0 +1,195 @@ +import type { HAPConnection } from '../../util/eventedhttp.js' +import type { DebugWriter } from '../diagnostics/CameraReporter.js' + +import { Buffer } from 'node:buffer' + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { buildEmitterConnection } from '../../../test-utils/connectionFixtures.js' +import { deferred } from '../../../test-utils/settle.js' +import { Characteristic, Formats, Perms } from '../../Characteristic.js' +import { HAPStatus } from '../../HAPServer.js' +import * as uuid from '../../util/uuid.js' +import { CommandQueue } from './CommandQueue.js' +import { wireControlPoint } from './controlPoint.js' + +// A decoded request and the response the handler answers it with, the status the helper logs. +interface Response { + readonly request: string + readonly status: number +} + +// The written value this decoder refuses, which lets a row drive the refusal. +const MALFORMED = 'AA==' + +function decode(value: string): string { + if (value === MALFORMED) { + throw new Error('The request is malformed.') + } + + return Buffer.from(value, 'base64').toString('utf8') +} + +function encode(response: Response): string { + return Buffer.from(`${response.request}:${response.status}`).toString('base64') +} + +function write(request: string): string { + return Buffer.from(request).toString('base64') +} + +describe('wireControlPoint', () => { + let characteristic: Characteristic + let connection: HAPConnection + let decoder: ReturnType> + let handler: ReturnType Promise>> + + beforeEach(() => { + // A transient control point with Write Response, as the definitions declare each one the helper wires. + characteristic = new Characteristic('Control Point', uuid.generate('wireControlPoint'), { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + connection = buildEmitterConnection() + decoder = vi.fn(decode) + handler = vi.fn(async (request: string) => ({ request, status: 0 })) + wireControlPoint(characteristic, new CommandQueue(), vi.fn(), decoder, handler, encode) + }) + + it('refuses a write without a connection as an invalid value, calling neither the decoder nor the handler', async () => { + await expect(characteristic.handleSetRequest(write('end'))).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(decoder).not.toHaveBeenCalled() + expect(handler).not.toHaveBeenCalled() + }) + + it('refuses a write the decoder refuses as an invalid value, calling no handler', async () => { + await expect(characteristic.handleSetRequest(MALFORMED, connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(decoder).toHaveBeenCalledExactlyOnceWith(MALFORMED) + expect(handler).not.toHaveBeenCalled() + }) + + it('answers a decoded write with the encoded response as its write response and on its writer\'s next plain read', async () => { + const answer = encode({ request: 'end', status: 0 }) + + await expect(characteristic.handleSetRequest(write('end'), connection)).resolves.toBe(answer) + expect(handler).toHaveBeenCalledExactlyOnceWith('end', connection) + await expect(characteristic.handleGetRequest(connection)).resolves.toBe(answer) + }) + + it('runs two writes one at a time, in the order they arrive', async () => { + const order: string[] = [] + const firstStarted = deferred() + const gate = deferred() + handler.mockImplementation(async (request: string) => { + order.push(`${request}-start`) + + if (request === 'first') { + firstStarted.resolve() + await gate.promise + } + + order.push(`${request}-end`) + + return { request, status: 0 } + }) + + const first = characteristic.handleSetRequest(write('first'), connection) + const second = characteristic.handleSetRequest(write('second'), connection) + await firstStarted.promise + + expect(order).toEqual(['first-start']) + + gate.resolve() + await Promise.all([first, second]) + + expect(order).toEqual([ + 'first-start', + 'first-end', + 'second-start', + 'second-end', + ]) + }) + + it('answers a response its encoder refuses with the refusal\'s response inside the same command, and rejects it without a refusal', async () => { + const order: string[] = [] + const failure = new RangeError('The response cannot be encoded.') + let thrown = false + const refusalStarted = deferred() + const refusalGate = deferred() + const secondGate = deferred() + + // The encoder throws for the first response it meets and encodes every later one. + const refusingEncode = (response: Response): string => { + if (!thrown) { + thrown = true + throw failure + } + + return encode(response) + } + const refusal = vi.fn(async (response: Response): Promise => { + order.push('refusal-start') + refusalStarted.resolve() + await refusalGate.promise + order.push('refusal-end') + + return { request: response.request, status: 2 } + }) + handler.mockImplementation(async (request: string) => { + order.push(`${request}-start`) + + if (request === 'second') { + await secondGate.promise + } + + return { request, status: 0 } + }) + + const refusing = new Characteristic('Refusing Control Point', uuid.generate('wireControlPoint refusal'), { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + wireControlPoint(refusing, new CommandQueue(), vi.fn(), decoder, handler, refusingEncode, refusal) + + const first = refusing.handleSetRequest(write('first'), connection) + const second = refusing.handleSetRequest(write('second'), connection) + + // The first write settles only after its refusal, and a write that settles before the refusal starts fails the row here rather than at its timeout. + await Promise.race([refusalStarted.promise, first]) + + expect(order).toEqual([ + 'first-start', + 'refusal-start', + ]) + + refusalGate.resolve() + + await expect(first).resolves.toBe(encode({ request: 'first', status: 2 })) + await expect(refusing.handleGetRequest(connection)).resolves.toBe(encode({ request: 'first', status: 2 })) + expect(refusal).toHaveBeenCalledExactlyOnceWith({ request: 'first', status: 0 }, failure) + + secondGate.resolve() + + await expect(second).resolves.toBe(encode({ request: 'second', status: 0 })) + expect(order).toEqual([ + 'first-start', + 'refusal-start', + 'refusal-end', + 'second-start', + ]) + + // The same write through a helper wired without a refusal rejects, as a handler's throw does. + const plain = new Characteristic('Plain Control Point', uuid.generate('wireControlPoint plain'), { + format: Formats.TLV8, + perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE, Perms.WRITE_RESPONSE], + transient: true, + }) + wireControlPoint(plain, new CommandQueue(), vi.fn(), decoder, handler, () => { + throw failure + }) + + await expect(plain.handleSetRequest(write('first'), connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + }) +}) diff --git a/src/lib/camera/session/controlPoint.ts b/src/lib/camera/session/controlPoint.ts new file mode 100644 index 000000000..b980de3b5 --- /dev/null +++ b/src/lib/camera/session/controlPoint.ts @@ -0,0 +1,104 @@ +import type { Characteristic } from '../../Characteristic.js' +import type { Service } from '../../Service.js' +import type { HAPConnection } from '../../util/eventedhttp.js' +import type { DebugWriter } from '../diagnostics/CameraReporter.js' +import type { CommandQueue } from './CommandQueue.js' + +import { HAPStatus } from '../../HAPServer.js' +import { errorMessage } from '../../util/errors.js' +import { HapStatusError } from '../../util/hapStatusError.js' + +/** + * Wires a control point's writes. A write without a connection, which only a plugin makes, and a write the decoder refuses are refused with + * {@link HAPStatus.INVALID_VALUE_IN_REQUEST}; every other write runs its handler and encodes the response inside one command of the service's queue, which + * makes each command atomic across its awaits, and answers with the encoded response. A response the encoder refuses goes to the refusal, inside the same + * command, and the refusal's own response is encoded and answers the write; without a refusal, the encoder's throw rejects the write. The control point is + * transient by its definition. The Characteristic holds that answer for its writer, and it reaches the writer in the write response and on the writer's + * plain reads alone. A control point with no write response encodes no answer: its writer holds none and its plain reads reach its read handler. + * @param characteristic - The control point. + * @param queue - The service's command queue. + * @param debug - The owner's debug writer. Each write's debug events go on the owner's debug name's channel. + * @param decode - Decodes a written value, and throws on one it refuses. + * @param handle - Answers a decoded request for the connection that wrote it. + * @param encode - Encodes a response, and throws on one its codec cannot carry; it answers nothing for a control point with no write response. + * @param refuse - Answers a response the encoder refuses, given that response and the encoder's error. + */ +export function wireControlPoint( + characteristic: Characteristic, + queue: CommandQueue, + debug: DebugWriter, + decode: (value: string) => Request, + handle: (request: Request, connection: HAPConnection) => Promise, + encode: (response: Response) => string | undefined, + refuse?: (response: Response, error: unknown) => Promise, +): void { + characteristic.onSet(async (value, _context, connection) => { + if (!connection) { + debug('write-refused-no-connection', () => ({ + characteristic: characteristic.displayName, + sentence: `${characteristic.displayName} refuses a write without a connection.`, + })) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + let request: Request + try { + request = decode(value as string) + } catch (error) { + debug('write-refused-undecodable', () => ({ + characteristic: characteristic.displayName, + message: errorMessage(error), + sentence: `${characteristic.displayName} refuses a write it cannot decode: ${errorMessage(error)}`, + })) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + // The response is encoded inside its command, and a refusal answers from the state the command left, before any later write runs. + return await queue.run(async () => { + let response = await handle(request, connection) + let encoded: string | undefined + + try { + encoded = encode(response) + } catch (error) { + if (!refuse) { + throw error + } + + response = await refuse(response, error) + encoded = encode(response) + } + + if ('status' in response && typeof response.status === 'number') { + const status: number = response.status + + debug('write-answered', () => ({ + characteristic: characteristic.displayName, + sentence: `${characteristic.displayName} answers with status ${status}.`, + status, + })) + } else { + debug('write-answered', () => ({ + characteristic: characteristic.displayName, + sentence: `${characteristic.displayName} answers.`, + })) + } + + return encoded + }) + }) +} + +/** + * Releases the answers a connection holds on every control point of a service, or every connection's. The control points are the service's transient + * characteristics, and the definitions' flag names each one this releases. + * @param service - The service whose control points hold the answers. + * @param connection - The connection whose answers are released, or none to release every connection's. + */ +export function releaseControlPointAnswers(service: Service, connection?: HAPConnection): void { + for (const characteristic of service.characteristics) { + if (characteristic.props.transient) { + characteristic.releaseTransientAnswers(connection) + } + } +} diff --git a/src/lib/camera/session/settleWithin.spec.ts b/src/lib/camera/session/settleWithin.spec.ts new file mode 100644 index 000000000..142149996 --- /dev/null +++ b/src/lib/camera/session/settleWithin.spec.ts @@ -0,0 +1,101 @@ +import type { BoundedSettlement } from './settleWithin.js' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { fakeTimeoutSignals } from '../../../test-utils/settle.js' +import { DELEGATE_CALL_TIMEOUT, settleWithinBound } from './settleWithin.js' + +// A delegate call that never settles. +function never(): Promise { + return new Promise(() => undefined) +} + +// Records a settlement once it arrives rather than awaiting it: a wait the bound does not end fails an assertion instead of the row's timeout. +function recorded(settlement: Promise>): { settled?: BoundedSettlement } { + const record: { settled?: BoundedSettlement } = {} + + void settlement.then((settled) => { + record.settled = settled + }) + + return record +} + +describe('settleWithinBound', () => { + beforeEach(() => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('answers the value of a call that resolves, not cut at the bound', async () => { + expect(await settleWithinBound(Promise.resolve(7))).toEqual({ + cutAtBound: false, + outcome: { value: 7 }, + }) + }) + + it('answers no outcome for a call that rejects, not cut at the bound', async () => { + expect(await settleWithinBound(Promise.reject(new Error('The delegate failed.')))).toEqual({ cutAtBound: false, outcome: undefined }) + }) + + it('answers no outcome, not cut at the bound, when the caller\'s signal aborts first, and at once for a signal already aborted', async () => { + const controller = new AbortController() + const first = recorded(settleWithinBound(never(), controller.signal)) + + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT - 1) + controller.abort() + await vi.advanceTimersByTimeAsync(0) + + expect(first.settled).toEqual({ cutAtBound: false, outcome: undefined }) + + const aborted = recorded(settleWithinBound(never(), AbortSignal.abort())) + await vi.advanceTimersByTimeAsync(0) + + expect(aborted.settled).toEqual({ cutAtBound: false, outcome: undefined }) + }) + + it('answers no outcome, cut at the bound, for a call that never settles, with a signal and with none', async () => { + for (const signal of [undefined, new AbortController().signal]) { + const settlement = recorded(settleWithinBound(never(), signal)) + + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT - 1) + + expect(settlement.settled).toBeUndefined() + + await vi.advanceTimersByTimeAsync(1) + + expect(settlement.settled).toEqual({ cutAtBound: true, outcome: undefined }) + } + }) + + it('counts the bound from the call, and each of two calls made apart is cut its own bound after its own start', async () => { + const apart = 10 * 1000 + const first = recorded(settleWithinBound(never())) + + await vi.advanceTimersByTimeAsync(apart) + const second = recorded(settleWithinBound(never())) + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT - apart - 1) + + expect(first.settled).toBeUndefined() + + await vi.advanceTimersByTimeAsync(1) + + expect(first.settled).toEqual({ cutAtBound: true, outcome: undefined }) + expect(second.settled).toBeUndefined() + + await vi.advanceTimersByTimeAsync(apart - 1) + + expect(second.settled).toBeUndefined() + + await vi.advanceTimersByTimeAsync(1) + + expect(second.settled).toEqual({ cutAtBound: true, outcome: undefined }) + }) +}) diff --git a/src/lib/camera/session/settleWithin.ts b/src/lib/camera/session/settleWithin.ts new file mode 100644 index 000000000..176291eb9 --- /dev/null +++ b/src/lib/camera/session/settleWithin.ts @@ -0,0 +1,66 @@ +/** + * The bound an awaited delegate call is cut at. A service runs its commands one at a time: a call that never settles would hold every later write behind + * it. + */ +export const DELEGATE_CALL_TIMEOUT = 30 * 1000 + +/** + * Awaits a delegate call until it settles or the signal aborts, answering its value, or undefined for a rejection or a cut. A late result is dropped. + * @param pending - The delegate call's promise. + * @param signal - The signal that cuts the wait. + * @returns An object holding the call's value, or `undefined` when it rejected or the wait was cut. + */ +export async function settleWithin(pending: Promise, signal: AbortSignal): Promise<{ value: T } | undefined> { + if (signal.aborted) { + return undefined + } + + let abort!: () => void + const aborted = new Promise((resolve) => { + abort = () => resolve(undefined) + signal.addEventListener('abort', abort, { once: true }) + }) + + try { + return await Promise.race([ + pending.then(value => ({ value }), () => undefined), + aborted, + ]) + } finally { + signal.removeEventListener('abort', abort) + } +} + +/** + * A delegate call's outcome within the delegate call bound, and whether the bound ended the wait. + */ +export interface BoundedSettlement { + /** + * Whether the bound ended the wait, which holds only when neither the call nor the caller's signal ended it first. + */ + readonly cutAtBound: boolean + /** + * An object holding the call's value, or `undefined` when the call rejected or the wait was cut. + */ + readonly outcome: { value: T } | undefined +} + +/** + * Awaits a delegate call until it settles, the caller's signal aborts or `DELEGATE_CALL_TIMEOUT` passes, the bound counted from this call. Time a command + * spent queued before it takes nothing from its delegate's bound. A caller words its own warning on `cutAtBound`, because each sentence names its own service. + * @param pending - The delegate call's promise. + * @param signal - A signal that also cuts the wait, such as the session's or the service's own. + * @returns The call's outcome and whether the bound cut the wait. + */ +export async function settleWithinBound(pending: Promise, signal?: AbortSignal): Promise> { + const bound = AbortSignal.timeout(DELEGATE_CALL_TIMEOUT) + const cut = signal + ? AbortSignal.any([signal, bound]) + : bound + const outcome = await settleWithin(pending, cut) + + return { + cutAtBound: outcome === undefined && bound.aborted && !signal?.aborted, + outcome, + } +} diff --git a/src/lib/controller/Controller.ts b/src/lib/controller/Controller.ts index 9d9b141c0..88160f986 100644 --- a/src/lib/controller/Controller.ts +++ b/src/lib/controller/Controller.ts @@ -1,3 +1,5 @@ +import type { MacAddress } from '../../types.js' +import type { AccessoryInformation } from '../definitions/index.js' import type { Service } from '../Service.js' /** @@ -49,6 +51,33 @@ export interface ControllerConstructor { new(): Controller } +/** + * The context of the accessory a {@link SerializableController} is configured on, which the accessory hands the controller through + * {@link SerializableController.handleAccessoryContext}. + * + * @group Controller API + */ +export interface ControllerAccessoryContext { + /** + * The accessory's Accessory Information service. + */ + readonly accessoryInformation: AccessoryInformation + /** + * The accessory's UUID. + */ + readonly accessoryUUID: string + /** + * Whether the accessory the controller is configured on is published, which for a bridged accessory is whether its bridge is published. It reads false in + * every context a destroy of the accessory, or of its bridge, hands, and in the context a controller being removed is handed. + */ + readonly published: boolean + /** + * The username the accessory is published under, which for a bridged accessory is its bridge's username. It is absent before the accessory, or its bridge, is first + * published and after it is destroyed. + */ + readonly username?: MacAddress +} + /** * A Controller represents a somewhat more complex arrangement of multiple services which together form an accessory * like for example cameras, remotes, tvs or routers. @@ -188,6 +217,18 @@ export interface SerializableController { + vi.restoreAllMocks() +}) + +describe('callDelegate', () => { + it('logs an error the call throws in the calling turn, as the failure sentence and the error\'s stack', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const thrown = new Error('The change could not be applied.') + + callDelegate(() => { + throw thrown + }, FAILURE) + + expect(error).toHaveBeenCalledExactlyOnceWith(`${FAILURE}: ${thrown.stack}`) + }) + + it('logs an error\'s own properties after its stack', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const thrown = Object.assign(new Error('The change could not be applied.'), { code: 'E_APPLY' }) + + callDelegate(() => { + throw thrown + }, FAILURE) + + expect(error).toHaveBeenCalledExactlyOnceWith(`${FAILURE}: ${thrown.stack} {\n code: 'E_APPLY'\n}`) + }) + + it('logs a returned promise\'s rejection with a string once it rejects, as the failure sentence and the string', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const reason = 'The change could not be applied.' + const held = deferred() + + callDelegate(async () => { + await held.promise + throw reason + }, FAILURE) + await settle() + + expect(error).not.toHaveBeenCalled() + + held.resolve() + await settle() + + expect(error).toHaveBeenCalledExactlyOnceWith(`${FAILURE}: ${reason}`) + }) + + it.each([ + { + kind: 'object with no prototype', + value: Object.create(null) as object, + }, + { + kind: 'object whose toString throws', + value: { + toString: (): string => { + throw new Error('The value cannot be converted.') + }, + }, + }, + { + kind: 'object whose custom inspect hook throws', + value: { + [inspect.custom]: (): string => { + throw new Error('The value cannot be inspected.') + }, + }, + }, + { + kind: 'object whose stack getter throws', + value: { + get stack(): string { + throw new Error('The value has no stack.') + }, + }, + }, + ])('logs a thrown $kind under the failure sentence without throwing itself', ({ value }) => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + + expect(() => callDelegate(() => { + throw value + }, FAILURE)).not.toThrow() + expect(error).toHaveBeenCalledExactlyOnceWith(expect.stringMatching(`^${FAILURE}:`)) + }) + + it('logs a constant text for a thrown value inspect cannot render, without throwing itself', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + + // Inspect reads a set's size through the value itself once the set holds an entry, and this getter's throw escapes inspect with its custom hook off. + class UnrenderableSet extends Set { + override get size(): number { + throw new Error('The set has no size.') + } + } + + expect(() => callDelegate(() => { + throw new UnrenderableSet([1]) + }, FAILURE)).not.toThrow() + expect(error).toHaveBeenCalledExactlyOnceWith(`${FAILURE}: a value that could not be rendered`) + }) + + it('reports a thrown value and a returned promise\'s rejection through the report it is handed, in place of the console line', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const report = vi.fn<(failure: string, error: unknown) => void>() + const thrown = new Error('The change could not be applied.') + const reason = 'The change was refused.' + + callDelegate(() => { + throw thrown + }, FAILURE, report) + callDelegate(async () => { + throw reason + }, FAILURE, report) + await settle() + + expect(report.mock.calls).toEqual([ + [FAILURE, thrown], + [FAILURE, reason], + ]) + expect(error).not.toHaveBeenCalled() + }) +}) + +describe('logDelegateRejection', () => { + it('reports a rejection through the report it is handed, in place of the console line, and none that settles while its signal reads aborted', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const report = vi.fn<(failure: string, error: unknown) => void>() + const controller = new AbortController() + const reason = new Error('The change was refused.') + const held = deferred() + + logDelegateRejection(Promise.reject(reason), FAILURE, undefined, report) + logDelegateRejection(held.promise, FAILURE, controller.signal, report) + controller.abort() + held.reject(new Error('The change was cut.')) + await settle() + + expect(report).toHaveBeenCalledExactlyOnceWith(FAILURE, reason) + expect(error).not.toHaveBeenCalled() + }) +}) + +describe('renderThrown', () => { + it('renders a string as itself, an error as its stack and its own properties, an object whose toString throws by its contents, and a value inspect ' + + 'cannot render as a constant text, throwing for none', () => { + const thrown = Object.assign(new Error('The change could not be applied.'), { code: 'E_APPLY' }) + const unconvertible = { + toString: (): string => { + throw new Error('The value cannot be converted.') + }, + } + + // Inspect reads a set's size through the value itself once the set holds an entry, and this getter's throw escapes inspect with its custom hook off. + class UnrenderableSet extends Set { + override get size(): number { + throw new Error('The set has no size.') + } + } + + expect([ + renderThrown('The change could not be applied.'), + renderThrown(thrown), + renderThrown(unconvertible), + renderThrown(new UnrenderableSet([1])), + ]).toEqual([ + 'The change could not be applied.', + `${thrown.stack} {\n code: 'E_APPLY'\n}`, + '{ toString: [Function: toString] }', + 'a value that could not be rendered', + ]) + }) +}) diff --git a/src/lib/util/promise-utils.ts b/src/lib/util/promise-utils.ts index 0dfcc3947..906e2c0d7 100644 --- a/src/lib/util/promise-utils.ts +++ b/src/lib/util/promise-utils.ts @@ -1,6 +1,8 @@ /* global NodeJS */ import type { EventEmitter } from 'node:events' +import { inspect } from 'node:util' + /** * @group Utils */ @@ -41,3 +43,85 @@ export function awaitEventOnce void + +/** + * Whether a value a delegate call returned is a promise or any other thenable, read as the promise protocol reads one: a value whose `then` is a function. + * A plugin may implement a delegate method as async whatever the contract types it as returning, which is why a call site reads the answer through here before it + * treats the answer as anything else. + * + * @group Utils + */ +export function isThenable(value: unknown): value is PromiseLike { + return typeof (value as PromiseLike | undefined)?.then === 'function' +} + +/** + * Logs the rejection of a promise a delegate call returned, under the sentence its call site names. A plugin may implement a delegate method as async though + * the contract types it as returning nothing, and a rejection no handler takes ends the process, which is why a call site hands over whatever its call returned. A + * synchronous throw stays the call site's, for a site whose own handler answers HomeKit for it. A call site that hands its delegate a cancel signal hands + * it here too, and a rejection that settles while that signal reads aborted is not logged, since it follows the library's own abort rather than the + * delegate's failure. A rejection is reported through `report`, which logs it where the call site hands none. + * + * @group Utils + */ +export function logDelegateRejection(result: unknown, failure: string, signal?: AbortSignal, report: DelegateFailureReport = logDelegateFailure): void { + if (isThenable(result)) { + result.then(undefined, (error: unknown) => { + if (!signal?.aborted) { + report(failure, error) + } + }) + } +} + +/** + * Runs one delegate call and logs a synchronous throw and a returned promise's rejection alike, under the sentence its call site names: a delegate's + * failure stays the delegate's where nothing above the call answers for it. Each is reported through `report`, which logs it where the call site hands + * none. + * + * @group Utils + */ +export function callDelegate(call: () => unknown, failure: string, report: DelegateFailureReport = logDelegateFailure): void { + try { + logDelegateRejection(call(), failure, undefined, report) + } catch (error) { + report(failure, error) + } +} diff --git a/src/test-utils/reporterFixtures.ts b/src/test-utils/reporterFixtures.ts new file mode 100644 index 000000000..25fa423e2 --- /dev/null +++ b/src/test-utils/reporterFixtures.ts @@ -0,0 +1,72 @@ +// The camera reporters a spec hands a class it builds alone, in a module of their own. No spec imports another. +import type { CameraProblem } from '../lib/camera/diagnostics/problems.js' +import type { ControllerAccessoryContext } from '../lib/controller/Controller.js' +import type { AccessoryInformation } from '../lib/definitions/index.js' + +import { subscribe, unsubscribe } from 'node:diagnostics_channel' + +import { onTestFinished } from 'vitest' + +import { CameraReporter } from '../lib/camera/diagnostics/CameraReporter.js' +import { cameraProblemsChannel } from '../lib/camera/diagnostics/problems.js' +import { Service } from '../lib/Service.js' +import * as uuid from '../lib/util/uuid.js' + +// The accessory a named reporter and a problems reporter stand for where a row names none. +export const REPORTER_ACCESSORY_UUID = uuid.generate('reporter camera accessory') + +/** + * The context of a synthetic camera's accessory: its UUID, and an Accessory Information service carrying the Name given. + * @param name - The accessory's Name. + * @param accessoryUUID - The accessory's UUID. + * @returns The context, as a published accessory with no username hands it. + */ +export function reporterContext(name: string, accessoryUUID = REPORTER_ACCESSORY_UUID): ControllerAccessoryContext { + return { + accessoryInformation: new Service.AccessoryInformation(name) as AccessoryInformation, + accessoryUUID, + published: true, + } +} + +// A reporter of no camera, as a class built alone holds one: each problem prints its bare sentence. +export function detachedReporter(): CameraReporter { + return new CameraReporter(() => undefined) +} + +// A reporter of a synthetic camera holding a context of the Name given and subscribing to nothing: each problem prints opened by that Name. +export function namedReporter(name: string, accessoryUUID = REPORTER_ACCESSORY_UUID): CameraReporter { + const context = reporterContext(name, accessoryUUID) + + return new CameraReporter(() => context) +} + +/** + * A reporter of a synthetic camera and the problems heard on that camera's channel while the row runs. + */ +export interface ReportedProblems { + readonly problems: CameraProblem[] + readonly reporter: CameraReporter +} + +/* A reporter of a synthetic camera with the UUID and the Name given, and the problems a subscription to that camera's channel hears while the row runs, in + * the order they were published, which a camera holding a context of that UUID publishes on too. The subscription is on the bare channel, which means each problem + * is kept as it is published and a row reads it in the turn that raised it. The subscription ends as the row finishes. + */ +export function problemsOf(accessoryUUID = REPORTER_ACCESSORY_UUID, name = 'Camera'): ReportedProblems { + const problems: CameraProblem[] = [] + const channel = cameraProblemsChannel(accessoryUUID) + const hear = (message: unknown): void => { + problems.push(message as CameraProblem) + } + + subscribe(channel, hear) + onTestFinished(() => { + unsubscribe(channel, hear) + }) + + return { + problems, + reporter: namedReporter(name, accessoryUUID), + } +} diff --git a/src/test-utils/settle.ts b/src/test-utils/settle.ts new file mode 100644 index 000000000..b18d18ef7 --- /dev/null +++ b/src/test-utils/settle.ts @@ -0,0 +1,50 @@ +// The waiting helpers every spec shares, in a module of their own. No spec carries its own copy. +import { expect, vi } from 'vitest' + +// The most reads a wait makes of its check before it fails its row. +const UNTIL_READS = 10000 + +// Lets every settled promise run its reactions: each write, exit and log line that can run has run. +export async function settle(): Promise { + await new Promise(resolve => setImmediate(resolve)) +} + +/* Reads a check until it holds, pausing between reads: by default one turn of the event loop, which advances no fake timer. A row's own work runs in each pause, a + * WebRTC engine's certificate and its gather among it, with the clock faked or not. A check that has not held after the most reads fails its row by + * assertion, and a row's own timeout bounds a wait on real time. + */ +export async function until(check: () => boolean, pause: () => Promise = settle): Promise { + for (let read = 0; (read < UNTIL_READS) && !check(); read++) { + await pause() + } + + expect(check()).toBe(true) +} + +// A promise a row settles by hand, which a scripted delegate returns to hold its call open until the row resolves or rejects it. +export interface Deferred { + promise: Promise + resolve: (value: T) => void + reject: (reason: Error) => void +} + +export function deferred(): Deferred { + let resolve!: (value: T) => void + let reject!: (reason: Error) => void + const promise = new Promise((onResolve, onReject) => { + resolve = onResolve + reject = onReject + }) + + return { promise, resolve, reject } +} + +// Node's AbortSignal.timeout runs on timers the fake clock does not replace, which is why the rows of a bounded wait route it through the faked setTimeout instead. +export function fakeTimeoutSignals(): void { + vi.spyOn(AbortSignal, 'timeout').mockImplementation((delay) => { + const controller = new AbortController() + setTimeout(() => controller.abort(new DOMException('The operation timed out.', 'TimeoutError')), delay) + + return controller.signal + }) +} From 589ad7a3eeab6a7262ec5f588046971d8b3beecf Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:47 -0600 Subject: [PATCH 09/16] feat(camera): add the modern camera's options and its own services: operating modes, video sensors and capabilities, motion attribution and motion zones --- src/lib/Characteristic.ts | 20 + src/lib/camera/GlobalOperatingMode.ts | 61 ++ src/lib/camera/MotionAttribution.ts | 143 +++ src/lib/camera/MotionZonesManagement.ts | 451 ++++++++ src/lib/camera/OperatingModePolicy.spec.ts | 1147 ++++++++++++++++++++ src/lib/camera/OperatingModePolicy.ts | 1104 +++++++++++++++++++ src/lib/camera/SensorRegistry.ts | 119 ++ src/lib/camera/StreamingOptions.ts | 988 +++++++++++++++++ src/lib/camera/capabilityKeys.ts | 49 + src/lib/camera/index.ts | 12 + src/lib/util/valueGuard.ts | 67 ++ 11 files changed, 4161 insertions(+) create mode 100644 src/lib/camera/GlobalOperatingMode.ts create mode 100644 src/lib/camera/MotionAttribution.ts create mode 100644 src/lib/camera/MotionZonesManagement.ts create mode 100644 src/lib/camera/OperatingModePolicy.spec.ts create mode 100644 src/lib/camera/OperatingModePolicy.ts create mode 100644 src/lib/camera/SensorRegistry.ts create mode 100644 src/lib/camera/capabilityKeys.ts create mode 100644 src/lib/util/valueGuard.ts diff --git a/src/lib/Characteristic.ts b/src/lib/Characteristic.ts index b23843dd1..b5872c870 100644 --- a/src/lib/Characteristic.ts +++ b/src/lib/Characteristic.ts @@ -312,6 +312,7 @@ import { numericUpperBound, } from './util/request-util.js' import { BASE_UUID, toShortForm } from './util/uuid.js' +import { lendGuardInstall } from './util/valueGuard.js' const debug = createDebug('HAP-NodeJS:Characteristic') @@ -1949,6 +1950,25 @@ export class Characteristic extends EventEmitter { public static WiFiSatelliteStatus: typeof WiFiSatelliteStatus // =-=-=-=-=-=-=-=-=-=-=-=-=-=-= + /* The class lends the one way to give a single characteristic a clean-up step of its own, which the library's guards install. Every path that stores + * or answers a value a plugin supplies runs the class's step first, through the characteristic itself, which means that characteristic alone runs anything more: + * its own step runs the class's and answers the guard's value for the result, and its disposal deletes it. The class's step shows again. An + * accessory listing that asks no read handler answers the held value as stored, with no step. + */ + static { + lendGuardInstall((characteristic, guard) => { + const clean = characteristic.validateUserInput.bind(characteristic) + + characteristic.validateUserInput = (value, warningType) => guard(clean(value, warningType)) + + return { + [Symbol.dispose]: () => { + Reflect.deleteProperty(characteristic, 'validateUserInput') + }, + } + }) + } + // NOTICE: when adding/changing properties, remember to possibly adjust the serialize/deserialize functions public displayName: string public UUID: string diff --git a/src/lib/camera/GlobalOperatingMode.ts b/src/lib/camera/GlobalOperatingMode.ts new file mode 100644 index 000000000..820ae1a0b --- /dev/null +++ b/src/lib/camera/GlobalOperatingMode.ts @@ -0,0 +1,61 @@ +import type { ControllerServiceMap } from '../controller/index.js' +import type { CameraGlobalOperatingMode } from '../definitions/index.js' +import type { OperatingModePolicy } from './OperatingModePolicy.js' + +import { Characteristic } from '../Characteristic.js' +import { Service } from '../Service.js' +import { CAPABILITY_KEY_PREFIX } from './capabilityKeys.js' + +/** + * The Camera Global Operating Mode service, which projects the operating-mode policy's camera-wide fields. It holds no state of its own: every value the + * service shows is a field of the policy, which binds the service's characteristics and marks the admin-only ones. + */ +export class GlobalOperatingMode { + /** + * The key the service carries in the camera's service map. + */ + static readonly SERVICE_KEY = `${CAPABILITY_KEY_PREFIX}globalOperatingMode` + + /** + * The camera's `CameraGlobalOperatingMode` service. + */ + readonly service: CameraGlobalOperatingMode + + /** + * Adopts the saved service, or builds one whose characteristics read the policy's values, and binds it to the policy. + * @param policy - The camera's operating-mode policy. + * @param service - The saved service, when the camera restores one. + */ + constructor(policy: OperatingModePolicy, service?: CameraGlobalOperatingMode) { + this.service = service ?? GlobalOperatingMode.constructService(policy) + policy.bindGlobalOperatingMode(this.service) + } + + /** + * Reconciles the surface in a restored service map, adopting its saved service or creating and inserting one. A camera without the camera capabilities + * block reconciles no surface, and the capability key sweep deletes a saved one. + * @param serviceMap - The camera's service map, changed in place. + * @param create - Builds the surface over the saved service, or over a new one when it is given none. + * @returns Whether the map changed. + */ + static reconcile(serviceMap: ControllerServiceMap, create: (service?: CameraGlobalOperatingMode) => GlobalOperatingMode): boolean { + const saved = serviceMap[GlobalOperatingMode.SERVICE_KEY] as CameraGlobalOperatingMode | undefined + const surface = create(saved) + + if (saved) { + return false + } + + serviceMap[GlobalOperatingMode.SERVICE_KEY] = surface.service + return true + } + + // A fresh characteristic reads its format's default, the camera off and streaming disabled among them, which is why each starts at the field the policy holds. + private static constructService(policy: OperatingModePolicy): CameraGlobalOperatingMode { + const service = new Service.CameraGlobalOperatingMode('', '') + service.setCharacteristic(Characteristic.HomeKitCameraActive, policy.homeKitCameraActive) + service.setCharacteristic(Characteristic.StreamingEnabled, policy.globalStreamingEnabled) + service.setCharacteristic(Characteristic.CameraOperatingModeIndicator, policy.operatingModeIndicator) + return service + } +} diff --git a/src/lib/camera/MotionAttribution.ts b/src/lib/camera/MotionAttribution.ts new file mode 100644 index 000000000..299a366df --- /dev/null +++ b/src/lib/camera/MotionAttribution.ts @@ -0,0 +1,143 @@ +import type { MotionSensor } from '../definitions/index.js' +import type { CameraReporter } from './diagnostics/CameraReporter.js' + +import { Characteristic } from '../Characteristic.js' +import { admitsValue } from '../util/valueGuard.js' +import { encodeContributingSensors } from './capabilities/cameraSensors.js' + +/** + * The owner of a camera's motion sensor's Contributing Sensors, whether the camera controller built the sensor or the plugin supplied it. The list names the + * video sensors that contribute to the motion currently detected. It follows Motion Detected: motion a plugin raises by writing Motion Detected without + * naming sensors belongs to every video sensor, and motion at rest lists none. A report writes the list before Motion Detected, and the camera controller + * hands the attribution each edge of Motion Detected from its one listener, registered ahead of the service's own: a direct write's list is written + * before the service forwards the motion change too, and a hub that reads the list on the motion notification finds it. A sensor whose Contributing Sensors + * a plugin removes gets no list, because the attribution writes only the characteristic it took at its construction. + */ +export class MotionAttribution { + private readonly motionDetected: Characteristic + private readonly contributingSensors: Characteristic + + /** + * The camera's reporter, through which a value of a report the attribution cannot place is a refused value of the camera's. + */ + private readonly reporter: CameraReporter + + /** + * The video sensors' UUIDs in the registry's order, in lowercase. + */ + private readonly sensorUUIDs: readonly string[] + + /** + * Set while a report writes Motion Detected. The edge the write causes leaves the list the report wrote. + */ + private reporting = false + + /** + * Adds Contributing Sensors when the sensor lacks it and writes it from the sensor's current Motion Detected, which means a cached list is corrected. + * @param motionSensor - The camera's motion sensor. + * @param sensorUUIDs - The video sensors' UUIDs in the registry's order, in lowercase. + * @param reporter - The camera's reporter. + */ + constructor(motionSensor: MotionSensor, sensorUUIDs: readonly string[], reporter: CameraReporter) { + this.sensorUUIDs = sensorUUIDs + this.reporter = reporter + this.motionDetected = motionSensor.getCharacteristic(Characteristic.MotionDetected) + this.contributingSensors = motionSensor.getCharacteristic(Characteristic.ContributingSensors) + this.write(this.motionDetected.value + ? sensorUUIDs + : []) + } + + /** + * Raises or clears motion and names the video sensors that saw it, writing Contributing Sensors and then Motion Detected when it moves. Detected motion + * lists each named sensor the camera has once, in the registry's order, whatever the case of its UUID, and a report that names none it has lists every + * sensor. An entry that names no sensor of the camera, or that is no string, is left out with one value-refused problem, and a value that is no list + * names none. Cleared motion lists none and reads no names. Motion the guard of Motion Detected does not store, motion while Motion Enabled reads off, + * is asked of that guard first, and its report writes no characteristic, reads no names and raises no problem. + * @param detected - Whether motion is detected. + * @param sensorUUIDs - The video sensors that saw the motion. + */ + report(detected: boolean, sensorUUIDs?: readonly string[]): void { + if (!admitsValue(this.motionDetected, detected)) { + return + } + + this.write(detected + ? this.attributed(sensorUUIDs) + : []) + + if (!!this.motionDetected.value === detected) { + return + } + + this.reporting = true + + try { + this.motionDetected.updateValue(detected) + } finally { + this.reporting = false + } + } + + /** + * Takes an edge of Motion Detected, which the camera controller hands it only when the value moves. A write that leaves it as it stands keeps a list + * a report named. A direct write of Motion Detected attributes the motion to every video sensor, and an edge a report causes leaves the list the report + * wrote. + * @param detected - Whether motion is detected. + */ + motionChanged(detected: boolean): void { + if (this.reporting) { + return + } + + this.write(detected + ? this.sensorUUIDs + : []) + } + + // The named sensors the camera has, in the registry's order. A plugin's runtime value takes the report-and-coerce path rather than a throw: an entry + // the camera cannot place is left out with a value-refused problem and a value that is no list names none. + private attributed(named: unknown): readonly string[] { + if (named === undefined) { + return this.sensorUUIDs + } + + if (!Array.isArray(named)) { + this.refused(`A motion report named its video sensors with ${String(named)}, which is no list. The motion belongs to every video sensor.`) + return this.sensorUUIDs + } + + const known = new Set() + + for (const entry of named) { + if (typeof entry !== 'string') { + this.refused(`A motion report named the video sensor ${String(entry)}, which is no sensor UUID, and the report leaves it out.`) + continue + } + + const sensorUUID = entry.toLowerCase() + + if (!this.sensorUUIDs.includes(sensorUUID)) { + this.refused(`A motion report named the video sensor "${entry}", which the camera does not have, and the report leaves it out.`) + continue + } + + known.add(sensorUUID) + } + + return known.size === 0 + ? this.sensorUUIDs + : this.sensorUUIDs.filter(sensorUUID => known.has(sensorUUID)) + } + + // Reports a value of a motion report the attribution cannot place as a refused value of the camera's, at the level the console warns at. + private refused(sentence: string): void { + this.reporter.problem({ kind: 'value-refused', level: 'warning', sentence }) + } + + private write(sensorUUIDs: readonly string[]): void { + const sensorList = sensorUUIDs.map(sensorUUID => ({ sensorUUID })) + + this.contributingSensors.updateValue(encodeContributingSensors({ sensorList })) + } +} diff --git a/src/lib/camera/MotionZonesManagement.ts b/src/lib/camera/MotionZonesManagement.ts new file mode 100644 index 000000000..0abf6e5dd --- /dev/null +++ b/src/lib/camera/MotionZonesManagement.ts @@ -0,0 +1,451 @@ +import type { CharacteristicValue } from '../../types.js' +import type { ControllerServiceMap, StateChangeDelegate } from '../controller/index.js' +import type { CameraMotionZones } from '../definitions/index.js' +import type { SensorDimensions } from './capabilities/cameraSensors.js' +import type { CameraZoneData, CameraZonesPayload } from './capabilities/zones.js' +import type { CameraReporter } from './diagnostics/CameraReporter.js' +import type { CameraChangeReason } from './OperatingModePolicy.js' +import type { CameraVideoSensor } from './StreamingOptions.js' + +import { Characteristic } from '../Characteristic.js' +import { HAPStatus } from '../HAPServer.js' +import { Service } from '../Service.js' +import { counted } from '../util/counted.js' +import { HapStatusError } from '../util/hapStatusError.js' +import { CAMERA_SPECIFICATION_VERSION } from './capabilities/cameraSensors.js' +import { decodeCameraZones, encodeCameraZones, ZONE_DATA_VERSION } from './capabilities/zones.js' +import { reconcileSensorServices, sensorServiceKey } from './capabilityKeys.js' +import { CommandQueue } from './session/CommandQueue.js' +import { DELEGATE_CALL_TIMEOUT, settleWithinBound } from './session/settleWithin.js' + +/** + * One video sensor's motion zones: whether the Camera Motion Zones service's `Active` is on, and the Zone Data entries of its Camera Zones. + * + * @group Camera + */ +export interface MotionZones { + /** + * Whether the service's `Active` is on. + */ + readonly active: boolean + /** + * Each Zone Data entry of the service's Camera Zones, in the order the hub wrote them, each vertex within the sensor's dimensions. + */ + readonly zoneData: readonly CameraZoneData[] +} + +/** + * The persisted state of one video sensor's Camera Motion Zones service. + */ +export interface MotionZonesManagementState { + /** + * Whether the service's `Active` is on. + */ + active: boolean + /** + * The Camera Zones value as the hub wrote it. + */ + zones: string +} + +/** + * The options of one video sensor's motion zones management, which the camera controller builds from the validated block. + */ +export interface MotionZonesManagementOptions { + /** + * The sensor's `motionZones` function, called as a plain function. + */ + motionZones: NonNullable + /** + * The camera's reporter, through which zones the sensor refuses are refused values of the camera's, and a rejection of the sensor's function or a write + * it does not settle within its bound is the plugin's failure. + */ + reporter: CameraReporter + /** + * The video sensor's UUID, in lowercase. + */ + sensorUUID: string + /** + * The video sensor's dimensions, which bound every vertex of its zones. + */ + sensorDimensions: SensorDimensions +} + +// The zones a service starts with and a factory reset restores: Active on and Zone Data of the version the spec has implementations write, with no entry. +const DEFAULT_ZONES = encodeCameraZones({ zoneDataVersion: ZONE_DATA_VERSION, zoneData: [] }) +const DEFAULT_STATE: Readonly = { active: true, zones: DEFAULT_ZONES } + +// The reasons the class calls the sensor's function under, a write's awaited and a restore's or a reset's not. +type ToldReason = Exclude + +// How each reason's failure of the sensor's function is reported, the delegate helpers adding the failure itself. +const FAILURES: Readonly> = { + write: 'The motionZones function failed to apply a write of the motion zones of video sensor', + restore: 'The motionZones function failed to apply the restored motion zones of video sensor', + reset: 'The motionZones function failed to apply the reset motion zones of video sensor', +} + +/* Why a decoded Camera Zones value does not fit the sensor, as a clause naming the rule, or undefined for a value it takes. The spec forms each zone from a + * polygon in the sensor's coordinate space and names each zone by its identifier: a polygon needs three vertices, every vertex lies within the sensor's + * width and height, and an identifier names one zone across the whole value. An empty list and a Zone Data entry with no polygons clear the zones, and a + * self-intersecting polygon is left to the plugin. + */ +function refusal(payload: CameraZonesPayload, dimensions: SensorDimensions): string | undefined { + const identifiers = new Set() + + for (const { polygons } of payload.zoneData) { + for (const { identifier, vertices } of polygons) { + if (vertices.length < 3) { + return `the zone ${identifier} has ${counted(vertices.length, 'vertex', 'vertices')}, where a polygon needs at least three` + } + + for (const [x, y] of vertices) { + if (x > dimensions.width || y > dimensions.height) { + return `the zone ${identifier} has the vertex (${x}, ${y}) outside the sensor's ${dimensions.width} by ${dimensions.height} pixels` + } + } + + if (identifiers.has(identifier)) { + return `the zone identifier ${identifier} appears more than once` + } + + identifiers.add(identifier) + } + } + + return undefined +} + +// A failure's message as a clause, its closing period dropped, because the problem that carries it has one sentence. +function messageOf(error: unknown): string { + return ((error as Error | undefined)?.message ?? String(error)).replace(/\.$/, '') +} + +/** + * Serves one video sensor's Camera Motion Zones service: it holds the zones in force and whether they are active, hands each change a write asks for to + * the sensor's `motionZones` function and keeps it once the function accepts it. The service runs its writes one at a time, in the order they arrive. + * A write of `Active` behind a write of Camera Zones hands the function the zones that write left in force. + * + * A Camera Zones write is refused with `INVALID_VALUE_IN_REQUEST` before it waits, with one value-refused problem naming the sensor and the rule, when its + * value does not decode, a polygon has fewer than three vertices, a vertex lies beyond the sensor's width or height, or an identifier repeats within the + * value. The refusal is a problem rather than a debug event, because it means zones a user drew are not in force. A write the function rejects or leaves + * unsettled at the bound fails with `SERVICE_COMMUNICATION_FAILURE` and keeps the zones in force, and a read answers those zones rather than the failed + * write's status. + * + * The accessory answers a hub's write as timed out well before the delegate call bound, while the wait runs on to the bound: a write the hub saw time out + * still applies when the function settles within the bound, and the hub reads the zones in force back. Camera Zones carries no notify permission, and a hub + * learns of the zones a restore or a factory reset put in force at its next read. A saved slice a restore refuses stays saved until the camera's next save. + */ +export class MotionZonesManagement { + /** + * The service's key in the camera's service map. + * @private + */ + readonly serviceKey: string + private readonly motionZones: NonNullable + private readonly reporter: CameraReporter + private readonly sensorUUID: string + private readonly sensorDimensions: SensorDimensions + private readonly service: CameraMotionZones + private readonly queue = new CommandQueue() + private stateChangeDelegate?: StateChangeDelegate + + /** + * The zones in force, which answer reads, the sensor's function and `serialize`; the characteristics' values follow them. + */ + private state: Readonly = DEFAULT_STATE + + /** + * The abort controller of the current generation of writes. A factory reset aborts it and starts a new one, and a destroy aborts it alone. A write + * that arrived under an aborted controller fails at its turn, one the sensor's function holds is cut, and one whose call settled fails when the + * controller it arrived under was aborted before its turn resumed. No call of the function listens on it: a write's call's signal is aborted through + * the write in flight, and a restore's or a reset's never is. + */ + private generation = new AbortController() + + /** + * The controller of the write whose call of the sensor's function the class is making or waiting on: set before the write's call is made, since the + * function can set off a factory reset or the camera's removal inside its own call, and cleared as its wait ends, by the call's settling, its bound or the + * generation. It holds no other write's, since a later write's turn begins only once the one before it has returned. The write's own bound aborts it, + * and a factory reset and a destroy abort it before anything else: a pending write's signal reads aborted before a reset's own call of the function is + * made, a reset made inside the write's own call among them. + */ + private writeInFlight?: AbortController + + /** + * Adopts the saved service or builds one, and writes its version and the defaults to it. Its characteristics and the zones in force agree before a + * restore. + * @param options - The sensor's options. + * @param service - A saved service to adopt. + */ + constructor(options: MotionZonesManagementOptions, service?: CameraMotionZones) { + this.motionZones = options.motionZones + this.reporter = options.reporter + this.sensorUUID = options.sensorUUID.toLowerCase() + this.sensorDimensions = options.sensorDimensions + this.serviceKey = MotionZonesManagement.serviceKey(this.sensorUUID) + this.service = service ?? new Service.CameraMotionZones('', this.sensorUUID) + + this.service.updateCharacteristic(Characteristic.Version, CAMERA_SPECIFICATION_VERSION) + this.project() + this.setupServiceHandlers() + } + + /** + * The key a video sensor's service carries in the camera's service map. + * @param sensorUUID - The video sensor's UUID. + * @returns The capability prefix, `motionZones:` and the UUID in lowercase. + * @private + */ + static serviceKey(sensorUUID: string): string { + return sensorServiceKey('motionZones', sensorUUID) + } + + /** + * Reconciles every listed video sensor's service in a restored service map, in the order given: a sensor's saved service under its key is adopted, and a + * sensor without one gets a new service, inserted. The key of a sensor the camera does not list is left to the capability key sweep. + * @param serviceMap - The camera's service map, changed in place. + * @param sensors - Each listed video sensor's options, in the camera's order. + * @param create - Builds a sensor's management over its saved service, or over a new one when it is given none. + * @returns Whether the map changed. + * @private + */ + static reconcile( + serviceMap: ControllerServiceMap, + sensors: readonly MotionZonesManagementOptions[], + create: (options: MotionZonesManagementOptions, service?: CameraMotionZones) => MotionZonesManagement, + ): boolean { + return reconcileSensorServices( + serviceMap, + sensors, + options => MotionZonesManagement.serviceKey(options.sensorUUID), + (options, service?: CameraMotionZones) => create(options, service).getService(), + ) + } + + /** + * The Camera Motion Zones service. + * @returns The service. + */ + getService(): CameraMotionZones { + return this.service + } + + /** + * The state to persist. + * @returns Whether `Active` is on and the Camera Zones value in force. + * @private + */ + serialize(): MotionZonesManagementState { + return { ...this.state } + } + + /** + * Restores persisted state: a slice whose `active` is a boolean and whose `zones` decodes and fits the sensor's current dimensions is put in force, and + * any other leaves the defaults in force, with one value-refused problem. Active and Camera Zones take the zones in force, no save is requested, and the + * sensor's function is called with them under `'restore'` without being awaited. + * @param state - The persisted state. + * @private + */ + deserialize(state: MotionZonesManagementState): void { + const refused = this.refusalOfSaved(state) + + if (refused === undefined) { + this.state = { active: state.active, zones: state.zones } + } else { + this.reporter.problem({ + kind: 'value-refused', + level: 'warning', + sensorUUID: this.sensorUUID, + sentence: `The saved motion zones of video sensor ${this.sensorUUID} cannot be restored because ${refused}. The defaults apply.`, + }) + this.state = DEFAULT_STATE + } + + this.project() + this.tell('restore') + } + + /** + * Sets the delegate an accepted write and a factory reset call, which is how the owner persists the zones. + * @param delegate - The delegate, or `undefined` to clear it. + * @private + */ + setupStateChangeDelegate(delegate?: StateChangeDelegate): void { + this.stateChangeDelegate = delegate + } + + /** + * Puts the defaults in force: the signal of the write whose call the class is making or waiting on is aborted first, which is why the plugin hears that the + * write is not wanted before it hears the defaults. Every write still waiting fails, a write the sensor's function holds included, the + * characteristics take the defaults, the owner is asked to save, and the function is called with them under `'reset'` without being awaited, with a + * signal nothing aborts. A restore's or an earlier reset's call still unsettled is not aborted. + */ + handleFactoryReset(): void { + this.writeInFlight?.abort() + this.generation.abort() + this.generation = new AbortController() + this.state = DEFAULT_STATE + this.project() + this.stateChangeDelegate?.() + this.tell('reset') + } + + /** + * Aborts the signal of the write whose call the class is making or waiting on, then fails every write still waiting, a write the sensor's function + * holds included, and every write that arrives later, before the service is dropped. A restore's or a reset's call still unsettled is not aborted. + * The write handlers stay, and a later write fails at its turn rather than writing the characteristic. Safe to call more than once. + */ + destroy(): void { + this.writeInFlight?.abort() + this.generation.abort() + } + + // Each write takes the generation it arrived under before it queues, and a read answers the zones in force, because a refused or failed write leaves its + // status on the characteristic and a plain read would answer that status. + private setupServiceHandlers(): void { + const active = this.service.getCharacteristic(Characteristic.Active) + const zones = this.service.getCharacteristic(Characteristic.CameraZones) + + active.onGet(() => this.activeValue()) + zones.onGet(() => this.state.zones) + + active.onSet(async (value) => { + const { generation } = this + + await this.queue.run(async () => this.apply(generation, { active: !!value })) + }) + + zones.onSet(async (value) => { + this.refuseWrite(value) + + const { generation } = this + + await this.queue.run(async () => this.apply(generation, { zones: value as string })) + }) + } + + // A Camera Zones value that does not decode or does not fit the sensor is refused before it waits, and a refusal never holds the queue. + private refuseWrite(value: CharacteristicValue): void { + let refused: string | undefined + + try { + refused = refusal(decodeCameraZones(value as string), this.sensorDimensions) + } catch (error) { + refused = `its value does not decode as Camera Zones (${messageOf(error)})` + } + + if (refused !== undefined) { + this.reporter.problem({ + kind: 'value-refused', + level: 'warning', + sensorUUID: this.sensorUUID, + sentence: `A write of the motion zones of video sensor ${this.sensorUUID} was refused because ${refused}. The zones in force stand.`, + }) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + } + + /* A write's turn. A write a factory reset or a destroy overtook fails without reaching the sensor's function. Otherwise the function is called with the + * zones the write asks for, read over the zones in force at this turn, and awaited within the delegate call bound counted from this call: time spent + * queued takes nothing from it. Only a call that settles puts the zones in force and asks the owner to save, and the characteristic takes the written + * value after. A call that settled fails its write all the same when a factory reset or a destroy passed before the turn resumed, as a call still + * pending does. A reset's defaults, which the function hears last, stay in force. The call's controller is made here and is the write in flight from + * before the function is called until the wait ends, which is why a factory reset or a destroy aborts the call's signal, one the function sets off inside its own + * call among them. The zones are read before the field is set: nothing between the set and the wait can throw and leave it held. A call cut at its + * bound is unsettled there, and its signal is aborted. + */ + private async apply(generation: AbortController, change: Partial): Promise { + if (generation.signal.aborted) { + throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + const next = { + ...this.state, + ...change, + } + const zones = this.zonesOf(next) + const call = new AbortController() + + this.writeInFlight = call + + const pending = this.call('write', zones, call) + const { cutAtBound, outcome } = await settleWithinBound(pending, generation.signal) + + this.writeInFlight = undefined + + if (!outcome || generation.signal.aborted) { + if (cutAtBound) { + call.abort() + this.reporter.problem({ + kind: 'plugin-failure', + level: 'warning', + sensorUUID: this.sensorUUID, + sentence: `The motionZones function did not settle a write of the motion zones of video sensor ${this.sensorUUID} within ` + + `${DELEGATE_CALL_TIMEOUT / 1000} seconds: the write fails and the zones in force stand.`, + }) + } + + throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + this.state = next + this.stateChangeDelegate?.() + } + + // Why a saved slice cannot be put in force, as a clause, or undefined for one that can, checked against the sensor's current dimensions. + private refusalOfSaved(state: MotionZonesManagementState): string | undefined { + if (typeof state.active !== 'boolean') { + return 'its active flag is no boolean' + } + + try { + return refusal(decodeCameraZones(state.zones), this.sensorDimensions) + } catch (error) { + return `its zones do not decode as Camera Zones (${messageOf(error)})` + } + } + + /* Calls the sensor's function with the zones in force without awaiting it, its failure a plugin-failure problem under the reason's sentence, under a + * controller of its own that nothing aborts: only a write's controller is the write in flight, set before its call is made. + */ + private tell(reason: 'restore' | 'reset'): void { + void this.call(reason, this.zonesOf(this.state), new AbortController()) + } + + /* One call of the sensor's function, a write's, a restore's or a reset's, under the controller its caller made, whose signal listens on nothing, and + * answers the call's promise. A write's controller is the write in flight from before this call, since the function can set off a factory reset or the + * camera's removal inside its own call, which aborts it there as at any later moment of the write's wait; its bound aborts it too. A restore's or a + * reset's is never aborted, and every rejection of theirs is reported. A timeout signal or the generation's own, handed to the function, would abort long + * after a call that settled. A rejection is reported under the reason's sentence unless the call's signal was aborted first. The function is called with no + * receiver. + */ + private call(reason: ToldReason, zones: MotionZones, call: AbortController): Promise { + const motionZones = this.motionZones + const pending = (async () => motionZones(zones, reason, call.signal))() + + this.reporter.rejection('plugin-failure', pending, `${FAILURES[reason]} ${this.sensorUUID}`, call.signal, { sensorUUID: this.sensorUUID }) + + return pending + } + + // Writes the zones in force to Active and Camera Zones through updateCharacteristic, never a set path. No write of the class's own reaches a handler. + private project(): void { + this.service.updateCharacteristic(Characteristic.Active, this.activeValue()) + this.service.updateCharacteristic(Characteristic.CameraZones, this.state.zones) + } + + private activeValue(): number { + return this.state.active + ? Characteristic.Active.ACTIVE + : Characteristic.Active.INACTIVE + } + + // The zones a state holds, decoded afresh: a function that changes what it was handed changes nothing the class keeps. + private zonesOf(state: MotionZonesManagementState): MotionZones { + return { + active: state.active, + zoneData: decodeCameraZones(state.zones).zoneData, + } + } +} diff --git a/src/lib/camera/OperatingModePolicy.spec.ts b/src/lib/camera/OperatingModePolicy.spec.ts new file mode 100644 index 000000000..42155aeda --- /dev/null +++ b/src/lib/camera/OperatingModePolicy.spec.ts @@ -0,0 +1,1147 @@ +import type { Mock } from 'vitest' + +import type { WithUUID } from '../../types.js' +import type { CameraGlobalOperatingMode, CameraOperatingMode, CameraRecordingManagement } from '../definitions/index.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { OperatingModeChange, OperatingModeField, OperatingModeState } from './OperatingModePolicy.js' + +import { describe, expect, it, vi } from 'vitest' + +import { Access, Characteristic, CharacteristicEventTypes } from '../Characteristic.js' +import { Service, ServiceEventTypes } from '../Service.js' +import { OperatingModePolicy } from './OperatingModePolicy.js' + +import '../definitions/index.js' + +// The policy's rows run over real services and no controller. Each one reads the policy's own bindings, refresh and derivations. +interface Camera { + policy: OperatingModePolicy + recordingManagement: CameraRecordingManagement + operatingMode: CameraOperatingMode + global: CameraGlobalOperatingMode + changes: OperatingModeChange[] + saves: Mock +} + +const HUB = {} as HAPConnection + +const PERSISTED_SLICE: OperatingModeState = { + recordingActive: false, + recordingAudioActive: false, + eventSnapshotsActive: true, + homeKitCameraActive: true, + periodicSnapshotsActive: true, +} + +// The services a recording camera and the global service start with, each characteristic at its field's default. +function services(): Pick { + const recordingManagement = new Service.CameraRecordingManagement('', '') + recordingManagement.setCharacteristic(Characteristic.Active, false) + recordingManagement.setCharacteristic(Characteristic.RecordingAudioActive, false) + + const operatingMode = new Service.CameraOperatingMode('', '') + operatingMode.setCharacteristic(Characteristic.EventSnapshotsActive, true) + operatingMode.setCharacteristic(Characteristic.HomeKitCameraActive, true) + operatingMode.setCharacteristic(Characteristic.PeriodicSnapshotsActive, true) + + const global = new Service.CameraGlobalOperatingMode('', '') + global.setCharacteristic(Characteristic.HomeKitCameraActive, true) + global.setCharacteristic(Characteristic.StreamingEnabled, true) + global.setCharacteristic(Characteristic.CameraOperatingModeIndicator, true) + + return { recordingManagement, operatingMode, global } +} + +// A policy bound to the recording services and, unless a row leaves it out, the global service, its hook and its delegate recorded, the hook handing each +// change it records to the row's reaction with the camera: a row reads the policy or writes a characteristic as each change arrives. +function camera( + withGlobal = true, + prepare: (camera: Omit) => void = () => undefined, + react: (change: OperatingModeChange, camera: Camera) => void = () => undefined, +): Camera { + const changes: OperatingModeChange[] = [] + const saves = vi.fn() + const bound = services() + const made: Camera = { + policy: new OperatingModePolicy({ + fieldChanged: (change) => { + changes.push(change) + react(change, made) + }, + }), + changes, + saves, + ...bound, + } + + prepare(bound) + made.policy.setupStateChangeDelegate(saves) + made.policy.bindRecording(bound.recordingManagement, bound.operatingMode) + if (withGlobal) { + made.policy.bindGlobalOperatingMode(bound.global) + } + + return made +} + +// Gives the legacy and the global operating-mode services every field characteristic each can carry before the policy binds them, getCharacteristic adding +// each one absent. +function addEveryOptional({ operatingMode, global }: Pick): void { + for (const optional of [ + Characteristic.CameraOperatingModeIndicator, + Characteristic.ManuallyDisabled, + Characteristic.NightVision, + Characteristic.ThirdPartyCameraActive, + ]) { + operatingMode.getCharacteristic(optional) + global.getCharacteristic(optional) + } +} + +// The listeners on each service and on each of its characteristics, the ones the services add for themselves among them, in a fixed order. +function listenerCounts(...services: Service[]): number[] { + return services.flatMap(service => [ + service.listenerCount(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE), + ...service.characteristics.map(characteristic => characteristic.listenerCount(CharacteristicEventTypes.CHANGE)), + ]) +} + +describe('operating-mode policy', () => { + it('reads an unprojected field as its default through a restore, and serializes nothing for a slice without a global field', () => { + const changes: OperatingModeChange[] = [] + const saves = vi.fn() + const policy = new OperatingModePolicy({ + fieldChanged: change => changes.push(change), + }) + policy.setupStateChangeDelegate(saves) + + policy.restore({ + ...PERSISTED_SLICE, + recordingActive: true, + homeKitCameraActive: false, + }) + + expect(policy.homeKitCameraActive).toBe(true) + expect(policy.recordingActive).toBe(false) + expect(policy.serialize()).toBeUndefined() + expect(changes).toEqual([]) + expect(saves).not.toHaveBeenCalled() + }) + + it('reads a field with one projection through it, a direct assignment included', () => { + const { policy, operatingMode } = camera(false) + + operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.OFF + + expect(policy.homeKitCameraActive).toBe(false) + }) + + it('seeds the stored value from the first projection at the second bind and refreshes a disagreeing second to it, telling no one', () => { + const subscriber = vi.fn() + const { policy, global, changes, saves } = camera(false, ({ operatingMode, global }) => { + operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.OFF + global.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.ON + }) + policy.subscribe('homeKitCameraActive', subscriber) + + policy.bindGlobalOperatingMode(global) + + expect(policy.homeKitCameraActive).toBe(false) + expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF) + expect(subscriber).not.toHaveBeenCalled() + expect(changes).toEqual([]) + expect(saves).not.toHaveBeenCalled() + }) + + it('refreshes the global projection at a write of the legacy one and tells each listener once', async () => { + const subscriber = vi.fn() + const { policy, operatingMode, global, changes, saves } = camera() + policy.subscribe('homeKitCameraActive', subscriber) + + await operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(Characteristic.HomeKitCameraActive.OFF, HUB) + + expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF) + expect(policy.homeKitCameraActive).toBe(false) + expect(subscriber.mock.calls).toEqual([ + [false], + ]) + expect(changes).toHaveLength(1) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('refreshes the legacy projection at a write of the global one and tells each listener once', async () => { + const subscriber = vi.fn() + const { policy, operatingMode, global, changes, saves } = camera() + policy.subscribe('homeKitCameraActive', subscriber) + + await global.getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(Characteristic.HomeKitCameraActive.OFF, HUB) + + expect(operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(0) + expect(policy.homeKitCameraActive).toBe(false) + expect(subscriber.mock.calls).toEqual([ + [false], + ]) + expect(changes).toHaveLength(1) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('moves no gate at a direct assignment to one of two projections', () => { + const { policy, global } = camera() + + global.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.OFF + + expect(policy.homeKitCameraActive).toBe(true) + expect(policy.streamingAllowed()).toBe(true) + }) + + it('reads through the remaining projection when the second goes and reads the default when the last goes', () => { + const allowed = vi.fn() + const { policy, operatingMode, global } = camera(true, ({ operatingMode, global }) => { + operatingMode.addCharacteristic(Characteristic.ManuallyDisabled) + global.addCharacteristic(Characteristic.ManuallyDisabled) + }) + policy.subscribeDerivation('streamingAllowed', allowed) + const legacy = operatingMode.getCharacteristic(Characteristic.ManuallyDisabled) + + legacy.updateValue(1) + legacy.value = 0 + global.removeCharacteristic(global.getCharacteristic(Characteristic.ManuallyDisabled)) + + expect(legacy.value).toBe(1) + expect(policy.manuallyDisabled).toBe(true) + + operatingMode.removeCharacteristic(legacy) + + expect(policy.manuallyDisabled).toBe(false) + expect(allowed.mock.calls).toEqual([ + [false], + [true], + ]) + }) + + it('runs the subscribers again at an unchanged write', () => { + const subscriber = vi.fn() + const { policy, operatingMode } = camera(false) + policy.subscribe('homeKitCameraActive', subscriber) + + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON) + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON) + + expect(subscriber.mock.calls).toEqual([ + [true], + [true], + ]) + }) + + it('refreshes a further projection to the stored value as it binds, telling no one', () => { + const { policy, operatingMode, changes, saves } = camera() + const further = services().global + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + changes.length = 0 + saves.mockClear() + + // The policy treats every projection alike, which is why a second global service stands in for a third service that projects the camera state. + policy.bindGlobalOperatingMode(further) + + expect(further.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF) + expect(policy.homeKitCameraActive).toBe(false) + expect(changes).toEqual([]) + expect(saves).not.toHaveBeenCalled() + }) + + it('allows streaming only while the camera and streaming are on and the camera is not manually disabled', () => { + const { policy, global } = camera(true, ({ global }) => { + global.addCharacteristic(Characteristic.ManuallyDisabled) + }) + + for (const cameraActive of [false, true]) { + for (const streamingEnabled of [false, true]) { + for (const manuallyDisabled of [false, true]) { + global.updateCharacteristic(Characteristic.HomeKitCameraActive, cameraActive ? 1 : 0) + global.updateCharacteristic(Characteristic.StreamingEnabled, streamingEnabled) + global.updateCharacteristic(Characteristic.ManuallyDisabled, manuallyDisabled ? 1 : 0) + + expect(policy.streamingAllowed()).toBe(cameraActive && streamingEnabled && !manuallyDisabled) + } + } + } + }) + + it('derives a stream service\'s status active from its bound streaming enabled and reads an unbound key\'s as on', () => { + const { policy } = camera() + const streamingEnabled = new Characteristic.StreamingEnabled() + streamingEnabled.updateValue(true) + policy.bindStreamingEnabled('multiTierStream:a', streamingEnabled) + + expect(policy.statusActive('multiTierStream:a')).toBe(true) + + streamingEnabled.updateValue(false) + + expect(policy.statusActive('multiTierStream:a')).toBe(false) + expect(policy.statusActive('multiTierStream:b')).toBe(true) + }) + + it('reads a stream service\'s status active on and its stream open off while the camera is out of service with its switches on, both off while it is ' + + 'switched off in service or not and both on in service and switched on, telling its stream open listener first and dropping both at disposal', () => { + const state = { away: false, published: true } + const policy = new OperatingModePolicy({ + published: () => state.published, + sourceAway: () => state.away, + }) + const { global, operatingMode, recordingManagement } = services() + const heard: [string, boolean][] = [] + // The key's Status Active and whether it may stream, as the policy answers them. + const reading = (): boolean[] => [ + policy.statusActive('multiTierStream:a'), + policy.streamOpen('multiTierStream:a'), + ] + const read: boolean[][] = [] + + policy.bindRecording(recordingManagement, operatingMode) + policy.bindGlobalOperatingMode(global) + policy.subscribeDerivation('statusActive', active => heard.push(['statusActive', active]), 'multiTierStream:a') + policy.subscribeDerivation('streamOpen', open => heard.push(['streamOpen', open]), 'multiTierStream:a') + read.push(reading()) + state.away = true + policy.serviceChanged() + read.push(reading()) + state.away = false + policy.serviceChanged() + + const leftAndBack = heard.splice(0) + + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + read.push(reading()) + state.published = false + policy.serviceChanged() + read.push(reading()) + + const switchedOff = heard.splice(0) + + policy[Symbol.dispose]() + state.published = true + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON) + policy.serviceChanged() + + expect(read).toEqual([ + [true, true], + [true, false], + [false, false], + [false, false], + ]) + expect(leftAndBack).toEqual([ + ['streamOpen', false], + ['streamOpen', true], + ]) + expect(switchedOff).toEqual([ + ['streamOpen', false], + ['statusActive', false], + ]) + expect(heard).toEqual([]) + }) + + it('tells every key\'s stream open listener before any key\'s status active listener at a recompute that moves both of two keys', () => { + const { policy, global } = camera() + const heard: string[] = [] + + // The listeners are subscribed each key's status active first and the second key before the first. The order heard is the recompute's own. + for (const key of ['multiTierStream:b', 'multiTierStream:a']) { + policy.subscribeDerivation('statusActive', active => heard.push(`${key} statusActive ${active}`), key) + policy.subscribeDerivation('streamOpen', open => heard.push(`${key} streamOpen ${open}`), key) + } + + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + + expect(heard).toEqual([ + 'multiTierStream:b streamOpen false', + 'multiTierStream:a streamOpen false', + 'multiTierStream:b statusActive false', + 'multiTierStream:a statusActive false', + ]) + }) + + it('tells a key\'s stream open listener before its status active listener at a change of its own streaming enabled', () => { + const { policy } = camera() + const streamingEnabled = new Characteristic.StreamingEnabled() + const heard: string[] = [] + + streamingEnabled.updateValue(true) + policy.bindStreamingEnabled('multiTierStream:a', streamingEnabled) + policy.subscribeDerivation('statusActive', active => heard.push(`statusActive ${active}`), 'multiTierStream:a') + policy.subscribeDerivation('streamOpen', open => heard.push(`streamOpen ${open}`), 'multiTierStream:a') + streamingEnabled.updateValue(false) + + expect(heard).toEqual([ + 'streamOpen false', + 'statusActive false', + ]) + }) + + it('moves recording published with the user\'s switches and the accessory\'s publication and never with the source, its listener hearing after ' + + 'recording in service\'s at a recompute', () => { + const state = { away: false, published: true } + const policy = new OperatingModePolicy({ + published: () => state.published, + sourceAway: () => state.away, + }) + const { global, operatingMode, recordingManagement } = services() + const heard: string[] = [] + const read: boolean[] = [] + + policy.bindRecording(recordingManagement, operatingMode) + policy.bindGlobalOperatingMode(global) + recordingManagement.updateCharacteristic(Characteristic.Active, true) + + // Recording published is subscribed first, which means the order heard is the recompute's own. + policy.subscribeDerivation('recordingPublished', published => heard.push(`recordingPublished ${published}`)) + policy.subscribeDerivation('recordingInService', inService => heard.push(`recordingInService ${inService}`)) + read.push(policy.recordingPublished()) + + // The source stated away and back moves recording in service alone. + state.away = true + policy.serviceChanged() + read.push(policy.recordingPublished()) + state.away = false + policy.serviceChanged() + + const sourced = heard.splice(0) + + // The accessory unpublished and published again, and recording switched off, each move recording in service and then recording published. + state.published = false + policy.serviceChanged() + read.push(policy.recordingPublished()) + state.published = true + policy.serviceChanged() + read.push(policy.recordingPublished()) + recordingManagement.updateCharacteristic(Characteristic.Active, false) + read.push(policy.recordingPublished()) + + expect(read).toEqual([true, true, false, true, false]) + expect(sourced).toEqual([ + 'recordingInService false', + 'recordingInService true', + ]) + expect(heard).toEqual([ + 'recordingInService false', + 'recordingPublished false', + 'recordingInService true', + 'recordingPublished true', + 'recordingInService false', + 'recordingPublished false', + ]) + }) + + it('tells a derivation\'s listener only when its value moves', () => { + const allowed = vi.fn() + const { policy, global } = camera() + policy.subscribeDerivation('streamingAllowed', allowed) + + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + + expect(allowed.mock.calls).toEqual([ + [false], + ]) + }) + + it('allows recording only while recording is active, the camera is on and it is not manually disabled', () => { + const { policy, recordingManagement, global } = camera(true, ({ global }) => { + global.addCharacteristic(Characteristic.ManuallyDisabled) + }) + + for (const recordingActive of [false, true]) { + for (const cameraActive of [false, true]) { + for (const manuallyDisabled of [false, true]) { + recordingManagement.updateCharacteristic(Characteristic.Active, recordingActive ? 1 : 0) + global.updateCharacteristic(Characteristic.HomeKitCameraActive, cameraActive ? 1 : 0) + global.updateCharacteristic(Characteristic.ManuallyDisabled, manuallyDisabled ? 1 : 0) + + expect(policy.recordingAllowed()).toBe(recordingActive && cameraActive && !manuallyDisabled) + } + } + } + }) + + it('tells a recording allowed listener each time a write of either input moves the value, and nothing at a write that leaves it as it stands', () => { + const allowed = vi.fn() + const { policy, recordingManagement, operatingMode } = camera() + policy.subscribeDerivation('recordingAllowed', allowed) + + recordingManagement.updateCharacteristic(Characteristic.Active, true) + recordingManagement.updateCharacteristic(Characteristic.Active, true) + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + recordingManagement.updateCharacteristic(Characteristic.Active, false) + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON) + + expect(allowed.mock.calls).toEqual([ + [true], + [false], + ]) + }) + + it('drops a recording allowed listener at disposal, and a later reset tells it nothing', () => { + const allowed = vi.fn() + const { policy, recordingManagement } = camera() + policy.subscribeDerivation('recordingAllowed', allowed) + recordingManagement.updateCharacteristic(Characteristic.Active, true) + + policy[Symbol.dispose]() + policy.reset() + + expect(policy.recordingAllowed()).toBe(false) + expect(allowed.mock.calls).toEqual([ + [true], + ]) + }) + + it('tells a status active listener of its own key and of the camera-wide inputs, never of another key', () => { + const statusActive = vi.fn() + const { policy, global } = camera() + const first = new Characteristic.StreamingEnabled() + const second = new Characteristic.StreamingEnabled() + first.updateValue(true) + second.updateValue(true) + policy.bindStreamingEnabled('multiTierStream:a', first) + policy.bindStreamingEnabled('multiTierStream:b', second) + policy.subscribeDerivation('statusActive', statusActive, 'multiTierStream:a') + + second.updateValue(false) + first.updateValue(false) + first.updateValue(true) + global.updateCharacteristic(Characteristic.StreamingEnabled, false) + + expect(statusActive.mock.calls).toEqual([ + [false], + [true], + [false], + ]) + }) + + it('disables a legacy stream at each global input', () => { + const { policy, global } = camera(true, ({ global }) => { + global.addCharacteristic(Characteristic.ManuallyDisabled) + }) + const stream = new Service.CameraRTPStreamManagement('', '0') + stream.setCharacteristic(Characteristic.Active, true) + policy.bindStream(0, stream) + + expect(policy.legacyStreamingDisabled(0)).toBe(false) + + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + expect(policy.legacyStreamingDisabled(0)).toBe(true) + + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON) + global.updateCharacteristic(Characteristic.StreamingEnabled, false) + expect(policy.legacyStreamingDisabled(0)).toBe(true) + + global.updateCharacteristic(Characteristic.StreamingEnabled, true) + global.updateCharacteristic(Characteristic.ManuallyDisabled, 1) + expect(policy.legacyStreamingDisabled(0)).toBe(true) + + global.updateCharacteristic(Characteristic.ManuallyDisabled, 0) + expect(policy.legacyStreamingDisabled(0)).toBe(false) + }) + + it('serializes the persisted fields without the global service and every field with it', () => { + expect(Object.keys(camera(false).policy.serialize()!)).toEqual([ + 'recordingActive', + 'recordingAudioActive', + 'eventSnapshotsActive', + 'homeKitCameraActive', + 'periodicSnapshotsActive', + ]) + expect(camera().policy.serialize()).toEqual({ + ...PERSISTED_SLICE, + globalStreamingEnabled: true, + operatingModeIndicator: true, + manuallyDisabled: false, + nightVision: false, + thirdPartyCameraActive: false, + motionEnabled: true, + }) + expect(Object.keys(camera().policy.serialize()!)).toEqual([ + 'recordingActive', + 'recordingAudioActive', + 'eventSnapshotsActive', + 'homeKitCameraActive', + 'periodicSnapshotsActive', + 'globalStreamingEnabled', + 'operatingModeIndicator', + 'manuallyDisabled', + 'nightVision', + 'thirdPartyCameraActive', + 'motionEnabled', + ]) + }) + + it('leaves a field the restored slice lacks as the policy holds it', () => { + const { policy, global } = camera() + global.getCharacteristic(Characteristic.NightVision).updateValue(true) + + policy.restore(PERSISTED_SLICE) + + expect(policy.nightVision).toBe(true) + expect(global.getCharacteristic(Characteristic.NightVision).value).toBe(true) + }) + + it('writes every default through every projection at a reset', () => { + const { policy, recordingManagement, operatingMode, global } = camera(true, addEveryOptional) + policy.restore({ + recordingActive: true, + recordingAudioActive: true, + eventSnapshotsActive: false, + homeKitCameraActive: false, + periodicSnapshotsActive: false, + globalStreamingEnabled: false, + operatingModeIndicator: false, + manuallyDisabled: true, + nightVision: true, + thirdPartyCameraActive: true, + }) + + policy.reset() + + expect(recordingManagement.getCharacteristic(Characteristic.Active).value).toBe(0) + expect(recordingManagement.getCharacteristic(Characteristic.RecordingAudioActive).value).toBe(0) + expect(operatingMode.getCharacteristic(Characteristic.EventSnapshotsActive).value).toBe(1) + expect(operatingMode.getCharacteristic(Characteristic.PeriodicSnapshotsActive).value).toBe(1) + expect(global.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true) + for (const service of [operatingMode, global]) { + expect(service.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(1) + expect(service.getCharacteristic(Characteristic.CameraOperatingModeIndicator).value).toBe(1) + expect(service.getCharacteristic(Characteristic.ManuallyDisabled).value).toBe(0) + expect(service.getCharacteristic(Characteristic.NightVision).value).toBe(false) + expect(service.getCharacteristic(Characteristic.ThirdPartyCameraActive).value).toBe(0) + } + }) + + it('reports a write from a controller with the write reason', async () => { + const { global, changes } = camera() + + await global.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, HUB) + + expect(changes).toEqual([ + { field: 'globalStreamingEnabled', value: false, reason: 'write' }, + ]) + }) + + it('reports a plugin update with the update reason', () => { + const { global, changes } = camera() + + global.updateCharacteristic(Characteristic.CameraOperatingModeIndicator, 0) + + expect(changes).toEqual([ + { field: 'operatingModeIndicator', value: false, reason: 'update' }, + ]) + }) + + it('reports a restored field with the restore reason', () => { + const { policy, changes } = camera(false) + + policy.restore({ homeKitCameraActive: false }) + + expect(changes).toEqual([ + { field: 'homeKitCameraActive', value: false, reason: 'restore' }, + ]) + }) + + it('reports each reset field with the reset reason', () => { + const { policy, changes } = camera(false) + + policy.reset() + + expect(changes).toEqual([ + { field: 'recordingActive', value: false, reason: 'reset' }, + { field: 'recordingAudioActive', value: false, reason: 'reset' }, + { field: 'eventSnapshotsActive', value: true, reason: 'reset' }, + { field: 'periodicSnapshotsActive', value: true, reason: 'reset' }, + { field: 'homeKitCameraActive', value: true, reason: 'reset' }, + ]) + }) + + it.each<[string, Partial, OperatingModeField[]]>([ + [ + 'HomeKit Camera Active off', + { homeKitCameraActive: false }, + [ + 'recordingActive', + 'recordingAudioActive', + 'eventSnapshotsActive', + 'periodicSnapshotsActive', + 'homeKitCameraActive', + ], + ], + [ + 'Manually Disabled on', + { manuallyDisabled: true }, + [ + 'recordingActive', + 'recordingAudioActive', + 'eventSnapshotsActive', + 'periodicSnapshotsActive', + 'homeKitCameraActive', + 'manuallyDisabled', + ], + ], + ])('reads the whole restored state at every change of a restore of recording on with %s, the changes in the write order, each one saved, and tells ' + + 'a recording allowed listener nothing', (_, saved, order) => { + const read: boolean[][] = [] + const allowed = vi.fn() + const state: Partial = { + ...PERSISTED_SLICE, + recordingActive: true, + ...saved, + } + // The global service carries Manually Disabled: a restore that defines it writes it rather than holding it, and each reading takes it. + const { policy, changes, saves } = camera(true, ({ global }) => { + global.addCharacteristic(Characteristic.ManuallyDisabled) + }, (_change, made) => { + read.push([ + made.policy.streamingAllowed(), + made.policy.recordingAllowed(), + ]) + }) + policy.subscribeDerivation('recordingAllowed', allowed) + + policy.restore(state) + + expect(changes).toEqual(order.map(field => ({ field, value: state[field], reason: 'restore' }))) + expect(read).toEqual(order.map(() => [false, false])) + expect(saves).toHaveBeenCalledTimes(order.length) + expect(allowed).not.toHaveBeenCalled() + }) + + it('stores every field a restore writes before it tells of any, each characteristic\'s own change event arriving in the write order, and tells a ' + + 'derivation the restore moves once, ahead of the first change', () => { + const heard: string[] = [] + const { policy, recordingManagement, operatingMode, global } = camera(true, undefined, ({ field }) => { + heard.push(`told ${field}`) + }) + + // Each characteristic that projects a field the restore writes, in the write order, HomeKit Camera Active on the legacy service and on the global one. + for (const [field, service, projection] of [ + ['recordingActive', recordingManagement, Characteristic.Active], + ['recordingAudioActive', recordingManagement, Characteristic.RecordingAudioActive], + ['eventSnapshotsActive', operatingMode, Characteristic.EventSnapshotsActive], + ['periodicSnapshotsActive', operatingMode, Characteristic.PeriodicSnapshotsActive], + ['homeKitCameraActive', operatingMode, Characteristic.HomeKitCameraActive], + ['homeKitCameraActive', global, Characteristic.HomeKitCameraActive], + ] as const) { + service.getCharacteristic(projection).on(CharacteristicEventTypes.CHANGE, () => { + heard.push(`stored ${field}`) + }) + } + + policy.subscribeDerivation('recordingAllowed', () => { + heard.push('recording allowed') + }) + + policy.restore({ + ...PERSISTED_SLICE, + recordingActive: true, + }) + + expect(heard).toEqual([ + 'stored recordingActive', + 'stored recordingAudioActive', + 'stored eventSnapshotsActive', + 'stored periodicSnapshotsActive', + 'stored homeKitCameraActive', + 'stored homeKitCameraActive', + 'recording allowed', + 'told recordingActive', + 'told recordingAudioActive', + 'told eventSnapshotsActive', + 'told periodicSnapshotsActive', + 'told homeKitCameraActive', + ]) + }) + + it('reads the whole reset state at every change of a reset of a camera with recording on and HomeKit Camera Active off, each one saved', () => { + const read: boolean[][] = [] + const { policy, recordingManagement, global, changes, saves } = camera(true, undefined, (_change, made) => { + read.push([ + made.policy.streamingAllowed(), + made.policy.recordingAllowed(), + ]) + }) + recordingManagement.updateCharacteristic(Characteristic.Active, true) + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + changes.length = 0 + read.length = 0 + saves.mockClear() + + policy.reset() + + expect(changes.map(({ field }) => field)).toEqual([ + 'recordingActive', + 'recordingAudioActive', + 'eventSnapshotsActive', + 'periodicSnapshotsActive', + 'homeKitCameraActive', + 'globalStreamingEnabled', + 'operatingModeIndicator', + ]) + expect(read).toEqual(changes.map(() => [true, false])) + expect(saves).toHaveBeenCalledTimes(changes.length) + }) + + it.each<{ + name: string + run: (policy: OperatingModePolicy) => void + write: number + told: OperatingModeChange[] + }>([ + { + name: 'restore', + run: policy => policy.restore({ + recordingActive: true, + homeKitCameraActive: false, + }), + write: Characteristic.HomeKitCameraActive.ON, + told: [ + { field: 'recordingActive', value: true, reason: 'restore' }, + { field: 'homeKitCameraActive', value: true, reason: 'update' }, + ], + }, + { + name: 'reset', + run: policy => policy.reset(), + write: Characteristic.HomeKitCameraActive.OFF, + told: [ + { field: 'recordingActive', value: false, reason: 'reset' }, + { field: 'homeKitCameraActive', value: false, reason: 'update' }, + { field: 'recordingAudioActive', value: false, reason: 'reset' }, + { field: 'eventSnapshotsActive', value: true, reason: 'reset' }, + { field: 'periodicSnapshotsActive', value: true, reason: 'reset' }, + { field: 'globalStreamingEnabled', value: true, reason: 'reset' }, + { field: 'operatingModeIndicator', value: true, reason: 'reset' }, + ], + }, + ])('lets a field the hook writes through its characteristic at a $name\'s first change stand, told by that write alone and never again by the ' + + '$name, each change saved', ({ run, write, told }) => { + const { policy, changes, saves } = camera(true, undefined, (_change, made) => { + if (made.changes.length === 1) { + made.operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, write) + } + }) + + run(policy) + + expect(changes).toEqual(told) + expect(policy.homeKitCameraActive).toBe(write === Characteristic.HomeKitCameraActive.ON) + expect(saves).toHaveBeenCalledTimes(told.length) + }) + + it('binds a field characteristic a plugin adds and drops one it removes', async () => { + const { policy, operatingMode, global } = camera() + + const legacy = operatingMode.getCharacteristic(Characteristic.NightVision) + const current = global.getCharacteristic(Characteristic.NightVision) + await current.handleSetRequest(true, HUB) + + expect(legacy.value).toBe(true) + + operatingMode.removeCharacteristic(legacy) + current.value = false + + expect(policy.nightVision).toBe(false) + }) + + it('binds each projection once however often its service changes configuration', () => { + const subscriber = vi.fn() + const { policy, global, saves } = camera() + policy.subscribe('homeKitCameraActive', subscriber) + const characteristic = global.getCharacteristic(Characteristic.HomeKitCameraActive) + + characteristic.setProps({}) + characteristic.setProps({}) + characteristic.updateValue(Characteristic.HomeKitCameraActive.OFF) + + expect(subscriber).toHaveBeenCalledTimes(1) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('marks every projection of an admin-only field and no other', () => { + const { recordingManagement, operatingMode, global } = camera(true, addEveryOptional) + const adminOnly = (service: Service, type: WithUUID<{ new (): Characteristic }>): unknown => service.getCharacteristic(type).props.adminOnlyAccess + + expect(adminOnly(recordingManagement, Characteristic.Active)).toEqual([Access.WRITE]) + expect(adminOnly(recordingManagement, Characteristic.RecordingAudioActive)).toBeUndefined() + expect(adminOnly(operatingMode, Characteristic.EventSnapshotsActive)).toEqual([Access.WRITE]) + expect(adminOnly(operatingMode, Characteristic.PeriodicSnapshotsActive)).toEqual([Access.WRITE]) + for (const service of [operatingMode, global]) { + expect(adminOnly(service, Characteristic.HomeKitCameraActive)).toEqual([Access.WRITE]) + expect(adminOnly(service, Characteristic.CameraOperatingModeIndicator)).toEqual([Access.WRITE]) + expect(adminOnly(service, Characteristic.ManuallyDisabled)).toBeUndefined() + expect(adminOnly(service, Characteristic.NightVision)).toBeUndefined() + expect(adminOnly(service, Characteristic.ThirdPartyCameraActive)).toBeUndefined() + } + }) + + it('removes every listener it added at disposal and tells no one afterward, disposed twice', () => { + const subscriber = vi.fn() + const derivationListener = vi.fn() + let unbound: number[] = [] + const { policy, recordingManagement, operatingMode, global, changes, saves } = camera(true, (bound) => { + unbound = listenerCounts(bound.recordingManagement, bound.operatingMode, bound.global) + }) + const streamingEnabled = new Characteristic.StreamingEnabled() + streamingEnabled.updateValue(true) + policy.bindStreamingEnabled('multiTierStream:a', streamingEnabled) + policy.subscribe('homeKitCameraActive', subscriber) + policy.subscribeDerivation('streamingAllowed', derivationListener) + policy.subscribeDerivation('statusActive', derivationListener, 'multiTierStream:a') + + policy[Symbol.dispose]() + policy[Symbol.dispose]() + + expect(listenerCounts(recordingManagement, operatingMode, global)).toEqual(unbound) + expect(streamingEnabled.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(0) + + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + recordingManagement.updateCharacteristic(Characteristic.Active, true) + streamingEnabled.updateValue(false) + + expect(subscriber).not.toHaveBeenCalled() + expect(derivationListener).not.toHaveBeenCalled() + expect(changes).toEqual([]) + expect(saves).not.toHaveBeenCalled() + }) + + it('removes its listener from a streaming enabled its key is bound away from, which means a write to that one tells the key\'s derivation nothing', () => { + const statusActive = vi.fn() + const { policy } = camera() + const first = new Characteristic.StreamingEnabled() + const second = new Characteristic.StreamingEnabled() + first.updateValue(true) + second.updateValue(true) + policy.bindStreamingEnabled('multiTierStream:a', first) + policy.subscribeDerivation('statusActive', statusActive, 'multiTierStream:a') + + policy.bindStreamingEnabled('multiTierStream:a', second) + first.updateValue(false) + + expect(first.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(0) + expect(statusActive).not.toHaveBeenCalled() + expect(policy.statusActive('multiTierStream:a')).toBe(true) + + second.updateValue(false) + + expect(statusActive.mock.calls).toEqual([ + [false], + ]) + }) + + it('holds a global field a restore writes before its characteristic exists for serialize and the first bind alone, and drops it at a reset', () => { + const { policy, global, changes, saves } = camera() + policy.restore({ + ...PERSISTED_SLICE, + nightVision: true, + }) + const heard = changes.length + const saved = saves.mock.calls.length + + expect(policy.nightVision).toBe(false) + expect(policy.serialize()!.nightVision).toBe(true) + + const nightVision = global.getCharacteristic(Characteristic.NightVision) + + expect(nightVision.value).toBe(true) + expect(policy.nightVision).toBe(true) + expect(changes).toHaveLength(heard) + expect(saves).toHaveBeenCalledTimes(saved) + + const reset = camera() + reset.policy.restore({ + ...PERSISTED_SLICE, + nightVision: true, + }) + reset.policy.reset() + + expect(reset.policy.serialize()!.nightVision).toBe(false) + expect(reset.global.getCharacteristic(Characteristic.NightVision).value).toBe(false) + + const disabled = camera() + const streamingEnabled = new Characteristic.StreamingEnabled() + streamingEnabled.updateValue(true) + disabled.policy.bindStreamingEnabled('multiTierStream:a', streamingEnabled) + disabled.policy.restore({ + ...PERSISTED_SLICE, + manuallyDisabled: true, + }) + + expect(disabled.policy.statusActive('multiTierStream:a')).toBe(true) + + disabled.global.getCharacteristic(Characteristic.ManuallyDisabled) + + expect(disabled.policy.statusActive('multiTierStream:a')).toBe(false) + }) + + describe('motion enabled', () => { + it('reads motion enabled as on with the global service bound and no motion sensor, and serializes it last', () => { + const { policy } = camera() + + expect(policy.motionEnabled).toBe(true) + expect(Object.entries(policy.serialize()!).at(-1)).toEqual(['motionEnabled', true]) + }) + + it('adds motion enabled reading on to a motion sensor that lacks it and reports a hub write through it once, saving once', async () => { + const { policy, changes, saves } = camera() + const motionSensor = new Service.MotionSensor('', '') + + expect(motionSensor.testCharacteristic(Characteristic.MotionEnabled)).toBe(false) + + policy.bindMotionSensor(motionSensor) + const motionEnabled = motionSensor.getCharacteristic(Characteristic.MotionEnabled) + + expect(motionEnabled.value).toBe(true) + expect(changes).toEqual([]) + expect(saves).not.toHaveBeenCalled() + + await motionEnabled.handleSetRequest(false, HUB) + + expect(changes).toEqual([ + { field: 'motionEnabled', value: false, reason: 'write' }, + ]) + expect(policy.motionEnabled).toBe(false) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('keeps the value of a motion enabled the sensor already carries at the bind', () => { + const { policy } = camera() + const motionSensor = new Service.MotionSensor('', '') + motionSensor.getCharacteristic(Characteristic.MotionEnabled).updateValue(false) + + policy.bindMotionSensor(motionSensor) + + expect(motionSensor.getCharacteristic(Characteristic.MotionEnabled).value).toBe(false) + expect(policy.motionEnabled).toBe(false) + }) + + it('marks a motion enabled whose props carry no admin-only access admin-only at the bind', () => { + const { policy } = camera() + const motionSensor = new Service.MotionSensor('', '') + const motionEnabled = motionSensor.getCharacteristic(Characteristic.MotionEnabled) + motionEnabled.setProps({ adminOnlyAccess: null }) + + expect(motionEnabled.props.adminOnlyAccess).toBeUndefined() + + policy.bindMotionSensor(motionSensor) + + expect(motionEnabled.props.adminOnlyAccess).toEqual([Access.WRITE]) + }) + + it('holds a restored motion enabled for serialize and the motion sensor\'s bind alone, which seeds it, and drops it at a reset', () => { + const { policy, changes, saves } = camera() + policy.restore({ + ...PERSISTED_SLICE, + motionEnabled: false, + }) + const heard = changes.length + const saved = saves.mock.calls.length + + expect(policy.motionEnabled).toBe(true) + expect(policy.serialize()!.motionEnabled).toBe(false) + + const motionSensor = new Service.MotionSensor('', '') + policy.bindMotionSensor(motionSensor) + + expect(motionSensor.getCharacteristic(Characteristic.MotionEnabled).value).toBe(false) + expect(policy.motionEnabled).toBe(false) + expect(changes).toHaveLength(heard) + expect(saves).toHaveBeenCalledTimes(saved) + + const reset = camera() + reset.policy.restore({ + ...PERSISTED_SLICE, + motionEnabled: false, + }) + reset.policy.reset() + const later = new Service.MotionSensor('', '') + reset.policy.bindMotionSensor(later) + + expect(later.getCharacteristic(Characteristic.MotionEnabled).value).toBe(true) + expect(reset.policy.serialize()!.motionEnabled).toBe(true) + }) + + it('writes motion enabled after every other field at a restore and at a reset, each under its own reason', () => { + const { policy, changes } = camera(true, addEveryOptional) + policy.bindMotionSensor(new Service.MotionSensor('', '')) + const order = [ + 'recordingActive', + 'recordingAudioActive', + 'eventSnapshotsActive', + 'periodicSnapshotsActive', + 'homeKitCameraActive', + 'globalStreamingEnabled', + 'operatingModeIndicator', + 'manuallyDisabled', + 'nightVision', + 'thirdPartyCameraActive', + 'motionEnabled', + ] + + policy.restore({ + ...PERSISTED_SLICE, + globalStreamingEnabled: true, + operatingModeIndicator: true, + manuallyDisabled: false, + nightVision: false, + thirdPartyCameraActive: false, + motionEnabled: false, + }) + + expect(changes.map(({ field }) => field)).toEqual(order) + expect(changes.at(-1)).toEqual({ field: 'motionEnabled', value: false, reason: 'restore' }) + + changes.length = 0 + policy.reset() + + expect(changes.map(({ field }) => field)).toEqual(order) + expect(changes.at(-1)).toEqual({ field: 'motionEnabled', value: true, reason: 'reset' }) + }) + + it('carries a restored motion enabled untouched without the global service, and serializes a slice without it as before', () => { + const { policy } = camera(false) + const slice: OperatingModeState = { + ...PERSISTED_SLICE, + motionEnabled: false, + } + + policy.restore(slice) + + expect(policy.serialize()).toEqual(slice) + + policy.restore(PERSISTED_SLICE) + + expect(policy.serialize()).toEqual(PERSISTED_SLICE) + expect(Object.keys(policy.serialize()!)).toEqual(Object.keys(PERSISTED_SLICE)) + }) + + it('drops a motion enabled the plugin removes, reading the default, and binds one it adds again', async () => { + const { policy, changes } = camera() + const motionSensor = new Service.MotionSensor('', '') + policy.bindMotionSensor(motionSensor) + const removed = motionSensor.getCharacteristic(Characteristic.MotionEnabled) + removed.updateValue(false) + + expect(policy.motionEnabled).toBe(false) + + motionSensor.removeCharacteristic(removed) + + expect(policy.motionEnabled).toBe(true) + + changes.length = 0 + const added = motionSensor.getCharacteristic(Characteristic.MotionEnabled) + await added.handleSetRequest(true, HUB) + + expect(changes).toEqual([ + { field: 'motionEnabled', value: true, reason: 'write' }, + ]) + expect(policy.motionEnabled).toBe(true) + }) + }) +}) diff --git a/src/lib/camera/OperatingModePolicy.ts b/src/lib/camera/OperatingModePolicy.ts new file mode 100644 index 000000000..ce3918275 --- /dev/null +++ b/src/lib/camera/OperatingModePolicy.ts @@ -0,0 +1,1104 @@ +import type { WithUUID } from '../../types.js' +import type { CharacteristicChange } from '../Characteristic.js' +import type { StateChangeDelegate } from '../controller/index.js' +import type { + CameraCapabilities, + CameraGlobalOperatingMode, + CameraOperatingMode, + CameraRecordingManagement, + CameraRTPStreamManagement, + MotionSensor, +} from '../definitions/index.js' +import type { Service } from '../Service.js' + +import { Access, ChangeReason, Characteristic, CharacteristicEventTypes, Formats } from '../Characteristic.js' +import { ServiceEventTypes } from '../Service.js' +import { DisposableStack } from '../util/disposableStack.js' + +/** + * A camera's persisted operating mode, one boolean per field the operating-mode policy owns. The optional fields are the ones only a camera with the + * camera capabilities block projects, which a layout saved without the block carries none of. While more than one characteristic projects a field, a direct + * assignment to any one of them reaches no gate, because no change event carries it to the others, which is why a plugin writes a field through its characteristic's + * set path or `updateValue`. + */ +export interface OperatingModeState { + /** + * Service `CameraRecordingManagement`; Characteristic `Active` + */ + recordingActive: boolean + /** + * Service `CameraRecordingManagement`; Characteristic `RecordingAudioActive` + */ + recordingAudioActive: boolean + /** + * Service `CameraOperatingMode`; Characteristic `EventSnapshotsActive` + */ + eventSnapshotsActive: boolean + /** + * Services `CameraOperatingMode` and `CameraGlobalOperatingMode`; Characteristic `HomeKitCameraActive` + */ + homeKitCameraActive: boolean + /** + * Service `CameraOperatingMode`; Characteristic `PeriodicSnapshotsActive` + */ + periodicSnapshotsActive: boolean + /** + * Service `CameraGlobalOperatingMode`; Characteristic `StreamingEnabled` + */ + globalStreamingEnabled?: boolean + /** + * Services `CameraGlobalOperatingMode` and, when the plugin adds it, `CameraOperatingMode`; Characteristic `CameraOperatingModeIndicator` + */ + operatingModeIndicator?: boolean + /** + * Services `CameraGlobalOperatingMode`, `CameraCapabilities` and `CameraOperatingMode`, each when the plugin adds it; Characteristic `ManuallyDisabled` + */ + manuallyDisabled?: boolean + /** + * Services `CameraGlobalOperatingMode` and `CameraOperatingMode`, each when the plugin adds it; Characteristic `NightVision` + */ + nightVision?: boolean + /** + * Services `CameraGlobalOperatingMode` and `CameraOperatingMode`, each when the plugin adds it; Characteristic `ThirdPartyCameraActive` + */ + thirdPartyCameraActive?: boolean + /** + * Service `MotionSensor` on a camera with the camera capabilities block; Characteristic `MotionEnabled` + */ + motionEnabled?: boolean +} + +/** + * The name of one operating-mode field. + * + * @group Camera + */ +export type OperatingModeField = keyof OperatingModeState + +/** + * Why a piece of a camera's state changed, as an operating-mode field, a stream service's Streaming Enabled and a video sensor's motion zones each report it. + * + * - `'write'`: a HomeKit controller wrote a characteristic that holds the state, or the plugin called its `setValue`. + * - `'update'`: the plugin surfaced a value it holds: an `updateValue`, a get handler that returned a new value, or an event notification. + * - `'restore'`: the camera restored its persisted state. + * - `'reset'`: a factory reset gave the state its default. + * + * @group Camera + */ +export type CameraChangeReason = 'write' | 'update' | 'restore' | 'reset' + +/** + * One change of an operating-mode field, as the camera controller's operating-mode event reports it. + * + * @group Camera + */ +export interface OperatingModeChange { + /** + * The field that changed. + */ + readonly field: OperatingModeField + /** + * The field's value, which a write that leaves it unchanged reports again. + */ + readonly value: boolean + /** + * Why the field changed. + */ + readonly reason: CameraChangeReason +} + +/** + * One change of a multi-tier or WebRTC stream service's Streaming Enabled, as the camera controller's streaming-enabled event reports it. + * + * @group Camera + */ +export interface StreamingEnabledChange { + /** + * The video sensor whose service changed, in lowercase. + */ + readonly sensorUUID: string + /** + * Whether the change is for views at home, the sensor's Camera Multi-Tier RTP Stream Management changing, or for views from away, its Camera WebRTC + * Stream Management changing. + */ + readonly where: 'home' | 'away' + /** + * The value of Streaming Enabled, which a write that leaves it unchanged reports again. + */ + readonly value: boolean + /** + * Why it changed. + */ + readonly reason: CameraChangeReason +} + +/** + * What a camera's operating-mode policy is made with. A policy made without them announces no field change and reads its camera in service. + */ +export interface OperatingModePolicyOptions { + /** + * Called once for each change of a field, after its subscribers and before the state-change delegate. A restore and a reset store every field they + * write before the first call they make, and each call of theirs reads the camera's whole restored or reset state. + */ + readonly fieldChanged?: (change: OperatingModeChange) => void + /** + * Whether the camera's accessory is published, as the camera controller reads it from the context its accessory last handed it, read at each query of + * whether the camera is in service. Published by default. + */ + readonly published?: () => boolean + /** + * Whether the plugin has stated its camera's source away, as the camera controller holds it, read at each query of whether the camera is in service. + * Not away by default. + */ + readonly sourceAway?: () => boolean +} + +/** + * What a stream service's gate reads: `open` where the service may start a stream, `switched off` where the user's switch does not allow streaming or + * the service's own Streaming Enabled is off, and `out of service` where the user's switches allow it and the camera is out of service. The user's switch + * is read first: a camera switched off and out of service at once reads `switched off`. + */ +export type StreamGate = 'open' | 'switched off' | 'out of service' + +type OperatingModeSubscriber = (value: boolean) => void + +type DerivationListener = (value: boolean) => void + +// The derivations of the whole camera, in the order a recompute tells them: the user's switches alone first, then each together with the camera in +// service, which means going out of service tells the kept tiers, then the recordings, then each stream service, and last recording allowed together with the +// accessory published, which reads nothing of the source. A switch-off or an unpublish ends the recording before the clips. +const CAMERA_DERIVATIONS = [ + 'streamingAllowed', + 'recordingAllowed', + 'streamingInService', + 'recordingInService', + 'recordingPublished', +] as const + +type CameraDerivation = typeof CAMERA_DERIVATIONS[number] + +// The derivations of each stream service, by its key, in the order a recompute and a change of the service's own Streaming Enabled tell them, after the +// camera's own: whether the service may start or hold a stream before its Status Active. A switch-off ends a service's sessions before its Status Active +// is written. +const SERVICE_DERIVATIONS = [ + 'streamOpen', + 'statusActive', +] as const + +type ServiceDerivation = typeof SERVICE_DERIVATIONS[number] + +// A derivation keeps its listeners and the value they last heard: a recompute that leaves the value unmoved tells none of them. +interface Derivation { + readonly compute: () => boolean + readonly listeners: DerivationListener[] + last: boolean +} + +// A projection pairs the characteristic that projects a field with the service that carries it. A pass over that service can tell which of its projections it dropped. +interface Projection { + readonly characteristic: Characteristic + readonly service: Service +} + +// A stream service's bound Streaming Enabled and the policy's listener on it, kept together so a rebind of the key removes that listener at once. +interface StreamingEnabledBinding { + readonly characteristic: Characteristic + readonly listener: () => void +} + +type FieldCharacteristic = readonly [OperatingModeField, WithUUID<{ new (): Characteristic }>] + +// One field a restore or a reset writes and the value it writes there. +interface FieldWrite { + readonly field: OperatingModeField + readonly value: boolean +} + +// A field no characteristic projects holds the value a factory reset gives it. +const DEFAULTS: Readonly> = { + recordingActive: false, + recordingAudioActive: false, + eventSnapshotsActive: true, + homeKitCameraActive: true, + periodicSnapshotsActive: true, + globalStreamingEnabled: true, + operatingModeIndicator: true, + manuallyDisabled: false, + nightVision: false, + thirdPartyCameraActive: false, + motionEnabled: true, +} + +// These are the fields only a camera with the camera capabilities block projects, which a layout saved without the block lacks. +const CAPABILITY_BLOCK_FIELDS = [ + 'globalStreamingEnabled', + 'operatingModeIndicator', + 'manuallyDisabled', + 'nightVision', + 'thirdPartyCameraActive', + 'motionEnabled', +] as const + +// A restore and a reset store the fields in this order and then tell of them in it, the camera state the sensors mirror coming after the snapshot fields. +const WRITE_ORDER: readonly OperatingModeField[] = [ + 'recordingActive', + 'recordingAudioActive', + 'eventSnapshotsActive', + 'periodicSnapshotsActive', + 'homeKitCameraActive', + ...CAPABILITY_BLOCK_FIELDS, +] + +// Every projection of these fields takes admin-only write. A write through any projection, which the refresh carries to every other, needs an admin. +const ADMIN_ONLY_FIELDS: ReadonlySet = new Set([ + 'recordingActive', + 'eventSnapshotsActive', + 'periodicSnapshotsActive', + 'homeKitCameraActive', + 'operatingModeIndicator', + 'motionEnabled', +]) + +// Each of these lists the field characteristics one subscribed service can carry, read when a pass runs, after the definitions have populated the characteristic types. +function globalOperatingModeFields(): FieldCharacteristic[] { + return [ + ['homeKitCameraActive', Characteristic.HomeKitCameraActive], + ['globalStreamingEnabled', Characteristic.StreamingEnabled], + ['operatingModeIndicator', Characteristic.CameraOperatingModeIndicator], + ['manuallyDisabled', Characteristic.ManuallyDisabled], + ['nightVision', Characteristic.NightVision], + ['thirdPartyCameraActive', Characteristic.ThirdPartyCameraActive], + ] +} + +function cameraCapabilitiesFields(): FieldCharacteristic[] { + return [ + ['manuallyDisabled', Characteristic.ManuallyDisabled], + ] +} + +function motionSensorFields(): FieldCharacteristic[] { + return [ + ['motionEnabled', Characteristic.MotionEnabled], + ] +} + +function cameraOperatingModeFields(): FieldCharacteristic[] { + return [ + ['homeKitCameraActive', Characteristic.HomeKitCameraActive], + ['eventSnapshotsActive', Characteristic.EventSnapshotsActive], + ['periodicSnapshotsActive', Characteristic.PeriodicSnapshotsActive], + ['operatingModeIndicator', Characteristic.CameraOperatingModeIndicator], + ['manuallyDisabled', Characteristic.ManuallyDisabled], + ['nightVision', Characteristic.NightVision], + ['thirdPartyCameraActive', Characteristic.ThirdPartyCameraActive], + ] +} + +// A write from HomeKit or the plugin's setValue is a write, and every other change is the plugin surfacing a value it holds. A stream service's own +// Streaming Enabled reports its changes through the same mapping. +export function changeReason(reason: ChangeReason): CameraChangeReason { + return reason === ChangeReason.WRITE + ? 'write' + : 'update' +} + +// The refresh writes a field's value as its projection's format holds it: it writes what a HomeKit controller would. +function projectedValue(characteristic: Characteristic, value: boolean): boolean | number { + if (characteristic.props.format === Formats.BOOL) { + return value + } + + return value + ? 1 + : 0 +} + +/** + * The one owner of a camera's operating mode. Each characteristic that expresses a field is its projection, and how the policy holds the field follows the + * number of projections. With none, the field reads its default and a restore or a reset writes nothing: no value reaches a gate that no characteristic + * could change. A restore on a camera with the capabilities block, which the policy knows by the global service's bind, holds a field only the block projects + * instead, for `serialize` and for the field's first projection, which the bind seeds with it, and a reset drops it. With one, the policy reads the field + * through it, and every write that reaches the characteristic, a direct assignment of its value included, reaches the gates that query the policy. With two + * or more, the policy stores the field, seeded from the first projection when the second binds, and a write through any projection sets the stored value and + * refreshes every other one; a direct assignment to one projection then reaches no gate, because no change event carries it to the others. + * + * A write stores the field in its projections and then tells of it, in one order: the field's subscribers, the derivations, the field-change hook, then the + * state-change delegate. A change event's write tells as soon as it stores. A restore and a reset store every field they write before they tell of any. + * Each change they tell is read against the camera's whole restored or reset state, never one where a field they write still holds its earlier value, + * and a field a listener writes to another value while they tell stands, told by that write's own change and not again by them. A characteristic's own + * change event arrives as its field is stored, which means a write a listener of one makes while a restore or a reset still stores is a change event's write like + * any other: it is told at once, against the fields stored so far, and a field later in the write order then takes the restore's or the reset's value and + * is told again. The refresh writes each projection under a guard naming the field, and the change event it causes returns at the policy's own listener + * rather than running the write again. A binding or an unbinding moves the field only when the source of its reading changes, and runs no subscriber, hook + * or delegate. + * + * Beside the user's switches the policy answers whether the camera is in service: its accessory is published, which the camera controller reads from the + * context its accessory hands it, and the plugin has not stated its source away, which the controller holds, the policy reading each through its option + * at each query and storing neither. `streamingAllowed` and `recordingAllowed` keep the user's switches alone, and the library's own gates read each + * together with the camera in service, through `streamingInService` and `recordingInService`, and a stream service's gate, {@link streamGate}, reads + * streaming in service beside the service's own Streaming Enabled. A hub's clips read `recordingPublished`, recording allowed together with the accessory + * published and nothing of the source. A source stated away leaves a clip in flight to finish. The controller calls {@link serviceChanged} at each + * change of a cause, which recomputes every derivation. + */ +export class OperatingModePolicy implements Disposable { + private readonly projections = new Map() + private readonly stored = new Map() + private readonly subscribers = new Map() + private readonly streams: Characteristic[] = [] + private readonly streamingEnabled = new Map() + private readonly serviceDerivations: Readonly>> = { + statusActive: new Map(), + streamOpen: new Map(), + } + + private readonly cameraDerivations = new Map() + private readonly published: () => boolean + private readonly sourceAway: () => boolean + private fieldChanged?: (change: OperatingModeChange) => void + private stateChangeDelegate?: StateChangeDelegate + + /** + * The removal of every listener the policy adds to a characteristic or a service, run once at disposal. + */ + private readonly listeners = new DisposableStack() + + /** + * The capability block fields a restore wrote on a camera with the block while no characteristic projected them, each kept until its first projection + * binds. + */ + private readonly held = new Map() + + /** + * The camera's `CameraOperatingMode` service, kept from the recording bind so the global service's bind can reach its optional characteristics. + */ + private cameraOperatingMode?: CameraOperatingMode + + /** + * The camera's `CameraGlobalOperatingMode` service, while one projects the fields only it carries. Its bind also marks a camera with the capabilities + * block, which `restore` and `serialize` read to tell such a camera from one without the block. + */ + private globalOperatingMode?: CameraGlobalOperatingMode + + /** + * The field the refresh is writing. The change event each of its writes causes returns at the policy's listener. + */ + private refreshing?: OperatingModeField + + /** + * A restored slice that defines a field no service of this camera projects, carried untouched so `serialize` writes it back until a factory reset. + */ + private carried?: OperatingModeState + + /** + * @param options - The field-change hook and the readers of whether the camera's accessory is published, published by default, and whether its source + * is away, not away by default. + * @param options.fieldChanged - Called once for each change of a field, after its subscribers and before the state-change delegate, a restore and a + * reset storing every field they write before the first call they make. Each call of theirs reads the camera's whole restored or reset state. + * @param options.published - Whether the camera's accessory is published, read at each query of whether the camera is in service. + * @param options.sourceAway - Whether the camera's source is stated away, read at each query of whether the camera is in service. + */ + constructor({ fieldChanged, published = () => true, sourceAway = () => false }: OperatingModePolicyOptions = {}) { + this.fieldChanged = fieldChanged + this.published = published + this.sourceAway = sourceAway + } + + /** + * Whether recording is active, as `CameraRecordingManagement`'s `Active` projects it. + */ + get recordingActive(): boolean { + return this.read('recordingActive') + } + + /** + * Whether recordings carry audio, as `CameraRecordingManagement`'s `RecordingAudioActive` projects it. + */ + get recordingAudioActive(): boolean { + return this.read('recordingAudioActive') + } + + /** + * Whether event snapshots are allowed, as `CameraOperatingMode`'s `EventSnapshotsActive` projects it. + */ + get eventSnapshotsActive(): boolean { + return this.read('eventSnapshotsActive') + } + + /** + * Whether the camera is on, as each `HomeKitCameraActive` projects it. + */ + get homeKitCameraActive(): boolean { + return this.read('homeKitCameraActive') + } + + /** + * Whether periodic snapshots are allowed, as `CameraOperatingMode`'s `PeriodicSnapshotsActive` projects it. + */ + get periodicSnapshotsActive(): boolean { + return this.read('periodicSnapshotsActive') + } + + /** + * Whether the camera streams at all, as `CameraGlobalOperatingMode`'s `StreamingEnabled` projects it. + */ + get globalStreamingEnabled(): boolean { + return this.read('globalStreamingEnabled') + } + + /** + * Whether the camera's status light is on, as each `CameraOperatingModeIndicator` projects it. + */ + get operatingModeIndicator(): boolean { + return this.read('operatingModeIndicator') + } + + /** + * Whether the camera is manually disabled, as each `ManuallyDisabled` projects it. + */ + get manuallyDisabled(): boolean { + return this.read('manuallyDisabled') + } + + /** + * Whether night vision is on, as each `NightVision` projects it. + */ + get nightVision(): boolean { + return this.read('nightVision') + } + + /** + * Whether another ecosystem is using the camera, as each `ThirdPartyCameraActive` projects it. + */ + get thirdPartyCameraActive(): boolean { + return this.read('thirdPartyCameraActive') + } + + /** + * Whether motion detection is on, as the motion sensor's `MotionEnabled` projects it. + */ + get motionEnabled(): boolean { + return this.read('motionEnabled') + } + + /** + * Whether a legacy stream's `Active` is on. + * @param index - The stream's index. + * @returns The stream's `Active`. + */ + streamActive(index: number): boolean { + return !!this.streams[index].value + } + + /** + * The legacy streaming rule: a stream is disabled while its `Active`, the camera or streaming as a whole is off, or while the camera is manually disabled. + * @param index - The stream's index. + * @returns Whether the stream refuses to stream. + */ + legacyStreamingDisabled(index: number): boolean { + return !this.streamActive(index) || !this.homeKitCameraActive || !this.globalStreamingEnabled || this.manuallyDisabled + } + + /** + * Whether the camera lets any stream run: it is on, streaming as a whole is on, and it is not manually disabled. + * @returns Whether streaming is allowed. + */ + streamingAllowed(): boolean { + return this.homeKitCameraActive && this.globalStreamingEnabled && !this.manuallyDisabled + } + + /** + * Whether the camera lets a recording run: recording is active, the camera is on, and it is not manually disabled. + * @returns Whether recording is allowed. + */ + recordingAllowed(): boolean { + return this.recordingActive && this.homeKitCameraActive && !this.manuallyDisabled + } + + /** + * Whether the camera is in service: its accessory is published and its source is not stated away. + * @returns Whether the camera is in service. + */ + inService(): boolean { + return this.published() && !this.sourceAway() + } + + /** + * Whether the library's own streams may run: streaming is allowed and the camera is in service. + * @returns Whether streaming is allowed and the camera is in service. + */ + streamingInService(): boolean { + return this.streamingAllowed() && this.inService() + } + + /** + * Whether the library's own recordings may run: recording is allowed and the camera is in service. + * @returns Whether recording is allowed and the camera is in service. + */ + recordingInService(): boolean { + return this.recordingAllowed() && this.inService() + } + + /** + * Whether a hub's clips may run: recording is allowed and the camera's accessory is published, whatever the plugin states of the camera's source. A + * clip a hub uploads finishes with what its recording served while the source is away, and the user's switches and an unpublish still end it. + * @returns Whether recording is allowed and the accessory is published. + */ + recordingPublished(): boolean { + return this.recordingAllowed() && this.published() + } + + /** + * A stream service's Status Active: its gate is not switched off, which means it follows the user's switches and the service's own Streaming Enabled alone and + * stays on while the camera is out of service. + * @param serviceKey - The stream service's key in the camera's service map. + * @returns Whether the user's switches and the service's Streaming Enabled allow the service to stream. + */ + statusActive(serviceKey: string): boolean { + return this.streamGate(serviceKey) !== 'switched off' + } + + /** + * Whether a stream service may start or hold a stream: its gate is open, the user's switches and its own Streaming Enabled allowing it and the camera in + * service. + * @param serviceKey - The stream service's key in the camera's service map. + * @returns Whether the service may start or hold a stream. + */ + streamOpen(serviceKey: string): boolean { + return this.streamGate(serviceKey) === 'open' + } + + /** + * A stream service's gate: `switched off` while streaming is not allowed or the service's own `StreamingEnabled` is off, `out of service` while the + * user's switches allow it and the camera is out of service, and `open` otherwise. A service's Status Active reads it not switched off, a service starts + * or holds a stream where it reads open, and a Setup Endpoints or a Solicit Offer write fails with the communication failure where it reads out of + * service, a WebRTC service's Solicit Offer answering Privacy Mode Active where it reads switched off. + * @param serviceKey - The stream service's key in the camera's service map. + * @returns The service's gate. + */ + streamGate(serviceKey: string): StreamGate { + const streamingEnabled = this.streamingEnabled.get(serviceKey) + + if (!this.streamingAllowed() || ((streamingEnabled !== undefined) && !streamingEnabled.characteristic.value)) { + return 'switched off' + } + + return this.inService() + ? 'open' + : 'out of service' + } + + /** + * Recomputes every derivation after a cause of whether the camera is in service changed, telling each listener of a derivation that moved. + */ + serviceChanged(): void { + this.recomputeDerivations() + } + + /** + * Binds each field the recording services project to its characteristic and marks the admin-only ones. + * @param recordingManagement - The camera's `CameraRecordingManagement` service. + * @param operatingMode - The camera's `CameraOperatingMode` service. + */ + bindRecording(recordingManagement: CameraRecordingManagement, operatingMode: CameraOperatingMode): void { + this.cameraOperatingMode = operatingMode + + this.bind('recordingActive', recordingManagement.getCharacteristic(Characteristic.Active), recordingManagement) + this.bind('recordingAudioActive', recordingManagement.getCharacteristic(Characteristic.RecordingAudioActive), recordingManagement) + this.bind('homeKitCameraActive', operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive), operatingMode) + this.bind('eventSnapshotsActive', operatingMode.getCharacteristic(Characteristic.EventSnapshotsActive), operatingMode) + this.bind('periodicSnapshotsActive', operatingMode.getCharacteristic(Characteristic.PeriodicSnapshotsActive), operatingMode) + } + + /** + * Binds the fields `CameraGlobalOperatingMode` projects, then the optional characteristics of a recording camera's `CameraOperatingMode`, which only a + * camera with the global service projects, and follows each of the services' configuration changes. A field characteristic a plugin adds later is + * bound and one it removes is dropped. + * @param service - The camera's `CameraGlobalOperatingMode` service. + */ + bindGlobalOperatingMode(service: CameraGlobalOperatingMode): void { + this.globalOperatingMode = service + + this.bind('homeKitCameraActive', service.getCharacteristic(Characteristic.HomeKitCameraActive), service) + this.bind('globalStreamingEnabled', service.getCharacteristic(Characteristic.StreamingEnabled), service) + this.bind('operatingModeIndicator', service.getCharacteristic(Characteristic.CameraOperatingModeIndicator), service) + this.follow(service, globalOperatingModeFields) + + if (this.cameraOperatingMode) { + this.follow(this.cameraOperatingMode, cameraOperatingModeFields) + } + } + + /** + * Binds `CameraCapabilities`' `ManuallyDisabled` while the service carries it and follows the service's configuration changes, as the global service's + * bind does. + * @param service - The camera's `CameraCapabilities` service. + */ + bindCameraCapabilities(service: CameraCapabilities): void { + this.follow(service, cameraCapabilitiesFields) + } + + /** + * Binds the motion sensor's `MotionEnabled`, adding it when the service lacks it, and follows the service's configuration changes, as the global service's + * bind does. Only a camera with the capabilities block calls it. + * @param service - The camera's `MotionSensor` service. + */ + bindMotionSensor(service: MotionSensor): void { + const added = !service.testCharacteristic(Characteristic.MotionEnabled) + const characteristic = service.getCharacteristic(Characteristic.MotionEnabled) + + // A new boolean characteristic reads false, and the first projection becomes the field's source, which is why one this bind adds takes the field's reading first. + // A value a restore held reaches it at the bind. + if (added) { + characteristic.updateValue(this.read('motionEnabled')) + } + + this.follow(service, motionSensorFields) + } + + /** + * Binds a stream service's `StreamingEnabled`, which {@link streamGate} reads for the service's key. A change of it recomputes that key's derivations + * alone, whether it may stream and then its Status Active, because the stream service that owns it saves it in its own slice. Binding the key to another + * characteristic removes the policy's listener from the earlier one at once, and a write to that one tells the key's derivations nothing. + * @param serviceKey - The stream service's key in the camera's service map. + * @param characteristic - The service's `StreamingEnabled`. + */ + bindStreamingEnabled(serviceKey: string, characteristic: Characteristic): void { + const previous = this.streamingEnabled.get(serviceKey) + + if (previous?.characteristic === characteristic) { + return + } + + previous?.characteristic.removeListener(CharacteristicEventTypes.CHANGE, previous.listener) + + const listener = (): void => this.notifyService(serviceKey) + characteristic.on(CharacteristicEventTypes.CHANGE, listener) + this.listeners.defer(() => characteristic.removeListener(CharacteristicEventTypes.CHANGE, listener)) + this.streamingEnabled.set(serviceKey, { characteristic, listener }) + this.notifyService(serviceKey) + } + + /** + * Binds a legacy stream's `Active`, which {@link streamActive} and {@link legacyStreamingDisabled} read for the stream's index. + * @param index - The stream's index. + * @param service - The stream's `CameraRTPStreamManagement` service. + */ + bindStream(index: number, service: CameraRTPStreamManagement): void { + this.streams[index] = service.getCharacteristic(Characteristic.Active) + } + + /** + * Registers a side effect of a field, run once for each change of the field, before the state-change delegate. + * @param field - The field. + * @param subscriber - The side effect, given the field's new value. + */ + subscribe(field: OperatingModeField, subscriber: OperatingModeSubscriber): void { + const subscribers = this.subscribers.get(field) + if (subscribers) { + subscribers.push(subscriber) + } else { + this.subscribers.set(field, [subscriber]) + } + } + + /** + * Registers a listener of a derivation of the whole camera, told the new value each time it moves: `streamingAllowed` and `recordingAllowed`, the + * user's switches alone, `streamingInService` and `recordingInService`, each of those together with the camera in service, or `recordingPublished`, + * recording allowed together with the accessory published, which reads nothing of the source and is told after `recordingInService`. + * @param derivation - The derivation. + * @param listener - The listener. + */ + subscribeDerivation(derivation: CameraDerivation, listener: DerivationListener): void + /** + * Registers a listener of a stream service's derivation, told the new value each time it moves: `statusActive`, its Status Active, which the user's + * switches and its own Streaming Enabled move, or `streamOpen`, whether it may start or hold a stream, which the camera's service moves as well. Every + * key's `streamOpen` listeners are told before any key's `statusActive` listeners. + * @param derivation - `statusActive` or `streamOpen`. + * @param listener - The listener. + * @param serviceKey - The stream service's key in the camera's service map. + */ + subscribeDerivation(derivation: 'statusActive' | 'streamOpen', listener: DerivationListener, serviceKey: string): void + subscribeDerivation(derivation: CameraDerivation | ServiceDerivation, listener: DerivationListener, serviceKey = ''): void { + if ((derivation !== 'statusActive') && (derivation !== 'streamOpen')) { + let camera = this.cameraDerivations.get(derivation) + if (!camera) { + camera = this.derivation(() => this[derivation]()) + this.cameraDerivations.set(derivation, camera) + } + + camera.listeners.push(listener) + return + } + + const keyed = this.serviceDerivations[derivation] + let service = keyed.get(serviceKey) + if (!service) { + service = this.derivation(() => this[derivation](serviceKey)) + keyed.set(serviceKey, service) + } + + service.listeners.push(listener) + } + + /** + * Restores a persisted operating mode, writing each field the slice defines and leaving a field it lacks as the policy holds it. Every field it writes is + * stored before any is told: a subscriber, a derivation listener and the field-change hook each read the whole restored state at every change it + * tells, and a derivation it moves is told once, a write made from a characteristic's own change event while it stores apart, as the class comment + * states. On a camera without the capabilities block, which the policy knows by the absence of the global service's bind, a slice that defines a field + * only the block projects is carried for {@link serialize}. On a camera with the block, such a field none of the camera's characteristics projects is + * held for {@link serialize} and for its first projection, which the bind seeds with it, and reaches no gate meanwhile. + * @param state - The persisted operating mode. + */ + restore(state: Partial): void { + if (!this.globalOperatingMode) { + this.carried = CAPABILITY_BLOCK_FIELDS.some(field => state[field] !== undefined) + ? this.carry(state) + : undefined + } + + const writes: FieldWrite[] = [] + + for (const field of WRITE_ORDER) { + const value = state[field] + + if (value === undefined) { + continue + } + + if (this.globalOperatingMode && (this.projections.get(field) ?? []).length === 0 && (CAPABILITY_BLOCK_FIELDS as readonly OperatingModeField[]).includes(field)) { + this.held.set(field, value) + } else { + writes.push({ field, value }) + } + } + + this.writeAll(writes, 'restore') + } + + /** + * Gives every field its default and drops a carried slice and every held field, as a factory reset does. Every default is stored before any field is + * told, as at a restore, and each change reads the whole reset state. + */ + reset(): void { + this.carried = undefined + this.held.clear() + this.writeAll(WRITE_ORDER.map(field => ({ field, value: DEFAULTS[field] })), 'reset') + } + + /** + * The operating mode to persist: the fields while a characteristic projects any, a held field at the value a restore held for it, each field only a camera + * with the capabilities block projects taken from a carried slice on a camera without the block, and otherwise the carried slice. + * @returns The operating mode, or `undefined` when no characteristic projects it and no slice is carried. + */ + serialize(): OperatingModeState | undefined { + if (!this.projected()) { + return this.carried && { ...this.carried } + } + + const state: OperatingModeState = { + recordingActive: this.recordingActive, + recordingAudioActive: this.recordingAudioActive, + eventSnapshotsActive: this.eventSnapshotsActive, + homeKitCameraActive: this.homeKitCameraActive, + periodicSnapshotsActive: this.periodicSnapshotsActive, + } + + for (const field of CAPABILITY_BLOCK_FIELDS) { + const value = this.globalOperatingMode + ? this.held.get(field) ?? this.read(field) + : this.carried?.[field] + + if (value !== undefined) { + state[field] = value + } + } + + return state + } + + /** + * Sets the delegate each change of a field calls after the field's side effects, which is how the camera's state is saved. + * @param delegate - The delegate, or `undefined` to call none. + */ + setupStateChangeDelegate(delegate?: StateChangeDelegate): void { + this.stateChangeDelegate = delegate + } + + /** + * Removes every listener the policy added and drops every subscriber, every derivation listener, the field-change hook and the state-change delegate. + * No change reaches anyone afterward. It keeps answering reads through the characteristics it bound, because a stream a removed camera held still + * queries it. Safe to call more than once. + */ + [Symbol.dispose](): void { + this.listeners.dispose() + this.subscribers.clear() + this.cameraDerivations.clear() + + for (const name of SERVICE_DERIVATIONS) { + this.serviceDerivations[name].clear() + } + + this.fieldChanged = undefined + this.stateChangeDelegate = undefined + } + + private projected(): boolean { + for (const projections of this.projections.values()) { + if (projections.length > 0) { + return true + } + } + + return false + } + + private read(field: OperatingModeField): boolean { + const projections = this.projections.get(field) ?? [] + + switch (projections.length) { + case 0: + return DEFAULTS[field] + case 1: + return !!projections[0].characteristic.value + default: + return this.stored.get(field) ?? DEFAULTS[field] + } + } + + // A change event's path, which tells of the field as soon as it stores it. The event names its origin, which the store skips, since it holds the value + // already. + private write(field: OperatingModeField, value: boolean, reason: CameraChangeReason, origin?: Characteristic): void { + if (this.store(field, value, origin)) { + this.tell(field, value, reason) + } + } + + // A restore's and a reset's path. It stores every write and then tells of each stored field in the order it was handed: each change it tells is read + // against the camera's whole restored or reset state. A field that reads another value than the one stored here was written by a listener since, and + // that write told of it already, which is why the field is skipped. + private writeAll(writes: readonly FieldWrite[], reason: CameraChangeReason): void { + const stored: FieldWrite[] = [] + + for (const write of writes) { + if (this.store(write.field, write.value)) { + stored.push(write) + } + } + + for (const { field, value } of stored) { + if (this.read(field) === value) { + this.tell(field, value, reason) + } + } + } + + // Writes the value to the field's projections, every one but a change event's origin, and answers whether any characteristic projects the field, since + // a field none projects reads its default and has nothing to tell. + private store(field: OperatingModeField, value: boolean, origin?: Characteristic): boolean { + const projections = this.projections.get(field) ?? [] + + if (projections.length === 0) { + return false + } + + if (projections.length > 1) { + this.stored.set(field, value) + this.refresh(field, value, projections.filter(projection => projection.characteristic !== origin)) + } else if (!origin) { + this.refresh(field, value, projections) + } + + return true + } + + // Tells of a stored field in one order: its subscribers, the derivations, the field-change hook, then the state-change delegate. + private tell(field: OperatingModeField, value: boolean, reason: CameraChangeReason): void { + for (const subscriber of this.subscribers.get(field) ?? []) { + subscriber(value) + } + + this.recomputeDerivations() + this.fieldChanged?.({ field, value, reason }) + this.stateChangeDelegate?.() + } + + // Writes the value to each projection under the guard, put back afterward: the change event each write causes returns at the listener. + private refresh(field: OperatingModeField, value: boolean, projections: readonly Projection[]): void { + const previous = this.refreshing + this.refreshing = field + + try { + for (const { characteristic } of projections) { + characteristic.updateValue(projectedValue(characteristic, value)) + } + } finally { + this.refreshing = previous + } + } + + // Refreshes only the projections that read a value other than the field's, as a bind or an unbind does, and one that agrees fires no change event. + private align(field: OperatingModeField, value: boolean, projections: readonly Projection[]): void { + this.refresh(field, value, projections.filter(projection => !!projection.characteristic.value !== value)) + } + + private bind(field: OperatingModeField, characteristic: Characteristic, service: Service): void { + let projections = this.projections.get(field) + if (!projections) { + projections = [] + this.projections.set(field, projections) + } + + if (projections.some(projection => projection.characteristic === characteristic)) { + return + } + + projections.push({ characteristic, service }) + + const listener = (change: CharacteristicChange): void => { + if (this.refreshing !== field) { + this.write(field, !!change.newValue, changeReason(change.reason), characteristic) + } + } + characteristic.on(CharacteristicEventTypes.CHANGE, listener) + this.listeners.defer(() => characteristic.removeListener(CharacteristicEventTypes.CHANGE, listener)) + + // The first projection becomes the field's source, taking under the refresh guard a value a restore held for it, and the seed runs no write. The second + // seeds the stored value from the first, and a later one takes the stored value. + if (projections.length === 1) { + const held = this.held.get(field) + + if (held !== undefined) { + this.held.delete(field) + this.refresh(field, held, projections) + } + + this.recomputeDerivations() + } else { + if (projections.length === 2) { + this.stored.set(field, !!projections[0].characteristic.value) + } + + this.align(field, this.stored.get(field) ?? DEFAULTS[field], [projections[projections.length - 1]]) + } + + // The mark lands after the bind, and the configuration change its setProps emits finds the characteristic already held. + if (ADMIN_ONLY_FIELDS.has(field)) { + characteristic.setProps({ + adminOnlyAccess: [Access.WRITE], + }) + } + } + + // The listeners a removed characteristic carried went with it, and dropping it leaves only the field's source to settle. + private unbind(field: OperatingModeField, projection: Projection): void { + const projections = this.projections.get(field) ?? [] + projections.splice(projections.indexOf(projection), 1) + + if (projections.length === 0) { + this.recomputeDerivations() + } else if (projections.length === 1) { + const value = this.stored.get(field) ?? DEFAULTS[field] + this.stored.delete(field) + this.align(field, value, projections) + } + } + + // Runs one pass over the service at once and another at each of its configuration changes. A pass that finds the projections unchanged does nothing: a + // change that adds or removes no field characteristic, the admin-only mark's own setProps among them, costs nothing. + private follow(service: Service, fields: () => FieldCharacteristic[]): void { + this.reconcile(service, fields()) + + const listener = (): void => this.reconcile(service, fields()) + service.on(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE, listener) + this.listeners.defer(() => service.removeListener(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE, listener)) + } + + // Drops each projection whose characteristic the service has removed, then binds each field characteristic it carries that the policy does not hold, + // telling them apart by identity, which is why a characteristic a plugin replaces is dropped and its replacement bound. + private reconcile(service: Service, fields: readonly FieldCharacteristic[]): void { + for (const [field] of fields) { + const dropped = (this.projections.get(field) ?? []) + .filter(projection => projection.service === service && !service.characteristics.includes(projection.characteristic)) + + for (const projection of dropped) { + this.unbind(field, projection) + } + } + + for (const [field, type] of fields) { + const characteristic = service.characteristics.find(candidate => candidate.UUID === type.UUID) + + if (characteristic) { + this.bind(field, characteristic, service) + } + } + } + + private derivation(compute: () => boolean): Derivation { + return { + compute, + listeners: [], + last: compute(), + } + } + + // The camera's own derivations first, then every key's derivations of each kind in turn: every key's streamOpen listeners hear before any key's + // statusActive listeners. + private recomputeDerivations(): void { + for (const name of CAMERA_DERIVATIONS) { + this.notify(this.cameraDerivations.get(name)) + } + + for (const name of SERVICE_DERIVATIONS) { + for (const derivation of this.serviceDerivations[name].values()) { + this.notify(derivation) + } + } + } + + // One key's derivations, at a change of the service's own Streaming Enabled, which moves nothing of any other key. + private notifyService(serviceKey: string): void { + for (const name of SERVICE_DERIVATIONS) { + this.notify(this.serviceDerivations[name].get(serviceKey)) + } + } + + private notify(derivation?: Derivation): void { + if (!derivation) { + return + } + + const value = derivation.compute() + if (value === derivation.last) { + return + } + + derivation.last = value + for (const listener of derivation.listeners) { + listener(value) + } + } + + // A carried slice keeps every field the restored slice defines and fills a persisted field it lacks with the policy's reading. The slice serialize + // writes back is whole. + private carry(state: Partial): OperatingModeState { + const carried: OperatingModeState = { + recordingActive: state.recordingActive ?? this.recordingActive, + recordingAudioActive: state.recordingAudioActive ?? this.recordingAudioActive, + eventSnapshotsActive: state.eventSnapshotsActive ?? this.eventSnapshotsActive, + homeKitCameraActive: state.homeKitCameraActive ?? this.homeKitCameraActive, + periodicSnapshotsActive: state.periodicSnapshotsActive ?? this.periodicSnapshotsActive, + } + + for (const field of CAPABILITY_BLOCK_FIELDS) { + const value = state[field] + + if (value !== undefined) { + carried[field] = value + } + } + + return carried + } +} diff --git a/src/lib/camera/SensorRegistry.ts b/src/lib/camera/SensorRegistry.ts new file mode 100644 index 000000000..da135cb4c --- /dev/null +++ b/src/lib/camera/SensorRegistry.ts @@ -0,0 +1,119 @@ +import type { ControllerServiceMap } from '../controller/index.js' +import type { CameraCapabilities } from '../definitions/index.js' +import type { SensorConfiguration, SensorDimensions } from './capabilities/cameraSensors.js' + +import { Characteristic } from '../Characteristic.js' +import { Service } from '../Service.js' +import { + CAMERA_CAPABILITIES_DATA_VERSION, + CAMERA_SPECIFICATION_VERSION, + CameraSensorType, + encodeCameraCapabilities, + encodeSensorConfiguration, +} from './capabilities/cameraSensors.js' +import { CAPABILITY_KEY_PREFIX } from './capabilityKeys.js' +import { validateSensorUUIDs } from './StreamingOptions.js' + +/** + * The video sensors a plugin supplies, validated when the camera controller is constructed, and the Camera Capabilities value that advertises them. + */ +export class SensorRegistry { + /** + * The key the Camera Capabilities service carries in the camera's service map. + */ + static readonly SERVICE_KEY = `${CAPABILITY_KEY_PREFIX}cameraCapabilities` + + /** + * The sensor UUIDs, in lowercase, in the registry's order: every sensor labelled Primary first and the rest after, each group in the plugin's order. A + * controller shows the sensor that comes first, and the Primary sensor's picture leads whatever order the plugin lists its sensors in. + */ + readonly sensorUUIDs: readonly string[] + + /** + * The Camera Capabilities value, encoded once from the validated configurations and listing them in the registry's order. + */ + private readonly capabilities: string + + /** + * Each sensor's dimensions, a copy taken at construction and keyed by the sensor's UUID in lowercase. + */ + private readonly dimensions = new Map() + + /** + * Validates each sensor and encodes its Sensor Configuration in the plugin's order, then puts every sensor labelled Primary first and the rest after, each + * group in the plugin's order, because a controller shows the sensor that comes first; the UUIDs and the Camera Capabilities value take that order. + * It throws a `TypeError` for the first UUID fault in the plugin's order, a sensor UUID that is not a UUID or one that sensors share, through + * {@link validateSensorUUIDs}, and then for the first configuration in that order Camera Capabilities cannot encode. A UUID fault at a later index + * comes before an encode fault at an earlier one, and an index the error names is the sensor's index in the plugin's list. + * @param sensors - Each video sensor's configuration. + */ + constructor(sensors: readonly SensorConfiguration[]) { + const validated: { sensor: SensorConfiguration, sensorUUID: string }[] = [] + + validateSensorUUIDs(sensors.map(sensor => sensor.sensorUUID)) + + for (const sensor of sensors) { + const sensorUUID = sensor.sensorUUID.toLowerCase() + + try { + encodeSensorConfiguration(sensor) + } catch (error) { + throw new TypeError(`The video sensor "${sensorUUID}" has a configuration that Camera Capabilities cannot encode.`, { cause: error }) + } + + validated.push({ sensor, sensorUUID }) + this.dimensions.set(sensorUUID, { width: sensor.sensorDimensions.width, height: sensor.sensorDimensions.height }) + } + + // A stable partition rather than a sort: the Primary label alone moves a sensor and the plugin's order stands within each group. + const ordered = [ + ...validated.filter(({ sensor }) => sensor.sensorType === CameraSensorType.PRIMARY), + ...validated.filter(({ sensor }) => sensor.sensorType !== CameraSensorType.PRIMARY), + ] + this.sensorUUIDs = ordered.map(({ sensorUUID }) => sensorUUID) + this.capabilities = encodeCameraCapabilities({ + version: CAMERA_CAPABILITIES_DATA_VERSION, + cameraSensors: ordered.map(({ sensor }) => sensor), + }) + } + + /** + * Advertises the sensors on the Camera Capabilities service, writing its version and value each time. An adopted service's cached values never stand. + * @param service - The saved service, when the camera restores one. + * @returns The service, the saved one or a new one. + */ + advertise(service: CameraCapabilities = new Service.CameraCapabilities('', '')): CameraCapabilities { + service.setCharacteristic(Characteristic.Version, CAMERA_SPECIFICATION_VERSION) + service.setCharacteristic(Characteristic.CameraCapabilitiesData, this.capabilities) + return service + } + + /** + * Reconciles the advertisement in a restored service map: the saved Camera Capabilities service is adopted, its cached version and value overwritten, or a + * new one is created and inserted, and the advertised service is handed to the camera to bind to its operating-mode policy. + * @param serviceMap - The camera's service map, changed in place. + * @param bind - Binds the advertised service to the camera's operating-mode policy. + * @returns Whether the map changed. + */ + reconcile(serviceMap: ControllerServiceMap, bind: (service: CameraCapabilities) => void): boolean { + const saved = serviceMap[SensorRegistry.SERVICE_KEY] as CameraCapabilities | undefined + const service = this.advertise(saved) + bind(service) + + if (saved) { + return false + } + + serviceMap[SensorRegistry.SERVICE_KEY] = service + return true + } + + /** + * A sensor's dimensions as the plugin supplied them at construction. A later change to the plugin's configuration reaches no lookup. + * @param sensorUUID - The sensor's UUID, in either case. + * @returns The sensor's width and height, or `undefined` for a UUID the registry lacks. + */ + sensorDimensions(sensorUUID: string): SensorDimensions | undefined { + return this.dimensions.get(sensorUUID.toLowerCase()) + } +} diff --git a/src/lib/camera/StreamingOptions.ts b/src/lib/camera/StreamingOptions.ts index 268d76757..f9b51a0a2 100644 --- a/src/lib/camera/StreamingOptions.ts +++ b/src/lib/camera/StreamingOptions.ts @@ -1,3 +1,52 @@ +import type { Buffer } from 'node:buffer' + +import type { CameraSensorIntent, CameraVideoStreamCapabilities, SensorConfiguration, SensorDimensions } from './capabilities/cameraSensors.js' +import type { SupportedAudioStreamTiersPayload, SupportedVideoStreamTiersPayload, VideoStreamTier } from './capabilities/streamTiers.js' +import type { MotionZones } from './MotionZonesManagement.js' +import type { CameraChangeReason } from './OperatingModePolicy.js' + +import { counted } from '../util/counted.js' +import * as uuid from '../util/uuid.js' +import { CAMERA_SENSOR_INTENT_VALUES, CameraSensorType } from './capabilities/cameraSensors.js' +import { + CAMERA_VIDEO_QUALITY_VALUES, + CameraVideoQuality, + encodeSupportedAudioStreamTiers, + encodeSupportedVideoStreamTiers, + TieredAudioBitDepth, + TieredAudioCodecType, + TieredAudioSampleRate, + TieredVideoCodecType, +} from './capabilities/streamTiers.js' + +/** + * What a tier's stream has carried since its demand started, its picture and its sound together: the RTP packets the library sent the tier's RTP sessions, + * summed over them, and the consumers the tier serves. A consumer the library hands whole frames is counted among the consumers and in none of the packet + * counts. + * + * @group Camera + */ +export interface TierStreamStatistics { + /** + * The RTP packets the library cut from the stream's picture and sound and sent the tier's RTP sessions, one for each packet and session. + */ + readonly packets: number + /** + * The bytes of those packets, their RTP headers included. + */ + readonly bytes: number + /** + * Each sample of the stream the library refused, counted once, and each packet an RTP session's send refused under pressure, one for each packet and + * session. + */ + readonly drops: number + /** + * Every join of the tier's stream, of every kind: each RTP session once for each medium it takes, one whose Start is still waiting among them, each + * consumer it hands whole frames, and the library's own hold of the tier, which joins with no consumer. + */ + readonly consumers: number +} + /** * How a plugin registers what it makes on a handle the library gives it, for something whose life the library decides: the plugin registers each resource * as it makes it, and the library releases every registration once, where the handle's life ends, whichever way it ends, and the plugin releases none of @@ -35,3 +84,942 @@ export interface ResourceScope { */ defer(release: () => unknown): void } + +/** + * The handle a plugin writes one video tier's stream through, valid from the tier's `tierDemandStarted` to the demand's end, where the library releases + * what was registered on it, as {@link ResourceScope} sets out, after which a write is ignored. The stream carries its tier, the video tier its encoding is + * for, as the camera settled it. The stream is fragmented MP4, fMP4, the form an encoder or a camera's controller delivers: the initialization segment + * first, then fragments in the `default_base_moof` layout, whose runs place their data from their own `moof`. Its picture is the stream's first video track, HEVC + * under an `hvc1` or `hev1` sample entry whose samples write each NAL unit's length in four octets, and its sound is the stream's first Opus track. A + * stream without an Opus track is a tier without sound. Where the tier's sensor states its audio's {@link CameraAudioTier.source} `'shared'`, the library + * ignores the Opus track of every tier's stream but the sound's tier's, the one tier whose {@link TierStream.tier} reads `sound` true. A later initialization + * segment replaces everything read from the one before it. From ffmpeg, that is an fMP4 output with `-movflags empty_moov+default_base_moof`, each fragment + * 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. + * + * The library reads the stream as it arrives, with nothing decoded, and makes every RTP packet an RTP session is sent: it times the picture and the sound + * on one run of times, every tier of a video sensor on the sensor's one clock, puts the initialization segment's parameter sets in each picture keyframe + * it sends that holds fewer than each of HEVC's video, sequence and picture parameter sets, after its access unit delimiter or at its front, sends one + * that holds each of them as its sample's octets, and cuts each sample into the tier's packets and numbers them. A run opens at its first sample, picture + * or sound, from that sample's decode time, and places each sample at its presentation time's distance from that decode time, picture and sound each at + * its own rate, and the distance between them is the stream's own; a sound timed before that decode time is dropped and counted. A run ends at a + * discontinuity, at an initialization segment and at a sample timed more than a second ahead of where the one before it of its track and the time since + * that one arrived put it, with no discontinuity marked, and the next sample opens a later run for picture and sound alike. A viewer at home takes its + * sound from the tier it started where that tier's `sound` reads true, and otherwise from the sensor's sound tier, which it joins for its sound alone, + * and a viewer from away takes its sound from the sensor's sound tier, as {@link CameraAudioTier.source} sets out. + * + * The tier has one pacer for every viewer, at home and from away. The library keeps each sample in the tier's camera buffer as it arrives, and the pacer + * releases it at the moment it falls due on one schedule, read from the stream's own times and the moments its fragments arrived, as `write` sets out: to + * every viewer joined then, or to none, a picture to no viewer of the live pictures still waiting for a keyframe, as the paragraph below sets out. A + * fragment is paced from its last byte: the stream's fragment length sets the delay a viewer sees and how many frames the library holds while it paces + * them alike, and a plugin that wants a short delay writes short fragments, a frame's length the shortest. + * + * A view opens from the camera buffer. A viewer that joins a tier whose buffer keeps a picture keyframe the pacer has released is handed the pictures + * from the latest such keyframe on, on timestamps that begin past every timestamp the tier has sent and run at many times the stream's speed, lower for a + * stretch heavier than the specification's heaviest maximum so its burst stays that of a stream at the maximum, each as the live releases reach it and at + * home as fast as its session's sender has room, and then each picture the pacer releases, which is why its picture starts at once and is level with the live + * releases within a small fraction of the stretch where its sender has room, while its sound joins the live releases at once. + * A viewer that joins a tier whose buffer keeps no keyframe the pacer has released is sent each sound the pacer releases from its join on and no picture + * before the next keyframe the pacer releases, whether the buffer holds it already or the stream has yet to bring it, and its picture starts at that + * keyframe. Each run's opening holds every viewer of the live pictures the same way: after a restart a viewer is sent no picture before the run's first + * keyframe while its sound flows meanwhile, and a view opened from the camera buffer starts at a keyframe already. A viewer still opening when the + * buffer lets its keyframe go, at a restart, a ceiling or as the buffer moves on, carries on from the latest keyframe the pacer has released that the + * buffer keeps, its timestamps beginning afresh, and with none waits, sent nothing, and opens from the next keyframe as the pacer releases it, which means it is + * never sent a picture it cannot decode. + * + * A viewer's keyframe request, a report of a lost picture or an ask for a full intra frame, at home from its session and from away from its stream, opens + * the consumer it came through again from the latest keyframe the pacer has released, as a joining viewer opens, once for each keyframe: a lost + * picture comes back after a replay of a fraction of a second, and no other viewer is touched. A request during the viewer's own opening is passed by, + * since its opening sends it that stretch already. A request the buffer cannot answer, where it keeps no keyframe the pacer has released or its latest + * is the one the viewer was last answered from, since a replay that did not take is never sent again, opens nothing, and the viewer's picture comes back + * at the stream's next keyframe. + * + * A tier's stream is expected to stay within the bitrates its tier advertises, its {@link CameraVideoTier.bitrate} on average and its + * {@link CameraVideoTier.peakBitrate} at its peak. A heavier stream is accepted and never refused, but a view of it can start rough, its recovery from a + * lost picture can wait for the stream's next keyframe, and its picture can stand behind live. A view's opening and the replay that answers a keyframe + * request each send the stretch since the latest keyframe the pacer has released, and a replay's size is the stream's rate times the time since that + * keyframe. A stream that runs past twice its tier's peak over that stretch, read over a second at least, is told of once for its demand, a `stream-fault` + * problem on the camera's channel under the camera capabilities block's `strict` and a debug event under `HAP-NodeJS:Camera:Tier` otherwise, and a tier + * whose {@link CameraVideoTier.bitrate} is above the specification's maximum for its resolution is refused under `strict` and accepted with a debug event + * under `HAP-NodeJS:Camera:Controller` otherwise. + * + * @group Camera + */ +export interface TierStream extends ResourceScope { + /** + * The video tier the stream is for, its sensor's entry as the camera settled it and froze: its peak at its default where the entry gives none, its + * `keepRunning` and `recorded` marks as booleans, `recorded` true on the tier the camera records, its sensor's UUID in lowercase, and `sound`, true on a + * tier whose stream must carry the sensor's sound: every tier where the sensor's audio states its {@link CameraAudioTier.source} `'tier'` or states none, + * and the sound's tier alone where it states `'shared'`, which is how a plugin reads at a start whether to encode Opus for the stream. Every demand of one tier + * carries the same object. + */ + readonly tier: Readonly> & { readonly sensorUUID: string, readonly sound: boolean } + /** + * Writes the stream's next bytes, which may end anywhere in a box. The library keeps each sample in the tier's camera buffer as the write completes its + * octets and those of every sample the stream places before it, and the tier's one pacer sends it to every consumer of the tier later, a picture to none + * still waiting for a keyframe, in a turn of its own and never inside this call: a fragment once its last byte is written, its first picture held to the + * lateness the stream's recent fragments arrived at, by at most 200 milliseconds, and each later sample at its decode time's distance from that picture. + * A plugin writes each fragment as it has it and the library sends every viewer one steady schedule. A chunk belongs to the library once written: the + * plugin never changes or reuses it, since the library may keep a view of it. A sample whose octets the library cannot send, a picture whose lengths do + * not tile it or a sound of no octets, is dropped and counted and reaches no consumer. A sound too long for one packet is dropped and counted as it is + * cut for the sessions at home alone, and still reaches every other consumer. A picture keyframe whose sample and initialization segment lack HEVC's + * video, sequence or picture parameter set between them is sent as it stands, with one `stream-fault` problem for such a keyframe. Bytes the library + * cannot read, a sample whose decode time does not rise past the one before it in its track since the stream's last initialization segment or + * discontinuity, a stream whose initialization segment holds no video track, and a silence, no picture within the bounds + * {@link MultiTierStreamingDelegate.tierDemandStarted} sets out whatever sound is written, fail the tier with a `stream-failed` problem saying what was + * wrong, as {@link TierStream.fail} does, after which nothing more of the stream is sent and every chunk is ignored. A version 0 `tfdt`'s 32-bit decode + * time that wraps to zero past its last value is no step back: the stream's decode times carry on past the wrap. + * @param chunk - The bytes. + */ + 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. + */ + discontinuity(): void + /** + * Fails the tier with one `stream-failed` problem on the camera's channel: every consumer joined to the tier ends through its holder, one still waiting + * on the tier's start among them, and a controller whose session ends with it is answered nothing. From the failure on nothing more of the stream is + * sent, the samples the pacer had not yet sent among them, and every chunk written is ignored. A failure reported once the demand has ended does + * nothing, which is why a listener on an encoder's exit may report it: the exit the library's own kill brings arrives after that end. + * @param reason - Why the tier failed, which the problem's sentence names. + */ + fail(reason: string): void + /** + * What the stream has carried since its tier's demand started. + * @returns The stream's statistics. + */ + statistics(): TierStreamStatistics +} + +/** + * One talker's handle, which `talkbackStarted` is handed: the sensor's UUID, and what the plugin registers on it for the talker, such as its decoder, as + * {@link ResourceScope} sets out. The library releases every registration once where the talker's talkback ends: from away where the session stops holding + * its viewer's key, removed by the hub or dropped past the store's bound; at its session's teardown, at home and from away; at home inside a sink's own + * `write` that ends its session, by failing its tier's stream for one, before that `write` returns, and from away a turn later, at the session's teardown; + * and at every decline, after which no packet is written. A viewer whose key the hub removes in one update and writes again in a later one is a new + * talker, handed a handle of its own, and a key removed and written again within one update keeps its talker. + * + * @group Camera + */ +export interface Talker extends ResourceScope { + /** + * The UUID of the sensor whose stream the talker talks on, in lowercase. + */ + readonly sensorUUID: string +} + +/** + * The plugin's receiver of one talker's talkback, the audio a viewer sends while its user talks, from the talker's first talkback packet to the end of its + * talkback, on a multi-tier stream at home and on a WebRTC stream from a view away from home alike. Each talker takes a sink of its own, at home a + * controller's session and from away a viewer of the view: talkers at once never share one and a plugin decides who is heard on both paths alike. A + * plugin that plays one voice at a time takes a sink for every talker and chooses which to play: a decline lasts the talker's whole time in the view and + * the library asks no second time, which is why a plugin declines only a talker it will never play. + * + * A sink is an object with `write`, and the library asks nothing else of it. What the talker's talkback needs released at its end is registered on the + * {@link Talker}. A sink that carries a dispose method and is not registered on its talker is not disposed, and nothing is reported, since a plugin may + * share one decoder among talkers. A class with `write` and a dispose method is registered and answered in one line, since `use` answers its value. + * + * @example + * A decoder class whose instance is the sink, registered on its talker, which the library disposes where the talker's talkback ends: + * + * ```ts + * const delegate = { + * talkbackStarted: (talker: Talker): TalkbackSink => talker.use(new TalkbackDecoder(talker.sensorUUID)), + * } + * ``` + * + * @group Camera + */ +export interface TalkbackSink { + /** + * Takes one talkback packet: a plain RTP packet, header included, carrying {@link TALKBACK_PAYLOAD_TYPE}, the payload type of the sensor's audio, whose + * format it carries. At home it is the packet exactly as the controller sent it once unprotected, with the controller's SSRC, sequence numbers and + * timestamps. From away the library writes each packet's RTP header itself, with that payload type, one SSRC for the sink and sequence numbers and + * timestamps that run on, the timestamps the viewer's own clock, which is why time not written stays a gap. The payload is the viewer's own Opus packet, whose + * bandwidth and length may change from one packet to the next, a packet holding 40 milliseconds where one at home holds 20, which a decoder reads from + * each packet. Packets are written as they arrive, which from away can be in clumps well behind their timestamps: a sink that plays live paces by the + * timestamps. Each packet arrives in a buffer of its own, which the sink may keep, and the library holds no reference to it after the call. The call is + * synchronous and the library waits for nothing. A sink whose decoder is still starting buffers or drops inside the sink. A throw, or the rejection + * of a promise it returns, is a `plugin-failure` problem on the camera's channel, printed where nothing subscribes, and the session goes on. + * @param packet - The packet. + */ + write(packet: Buffer): void +} + +/** + * The encoder side of multi-tier streaming: the plugin starts and stops each video tier's encoding as consumers come and go, and writes each encoding's + * stream, picture and sound together, to the tier's {@link TierStream}. The library owns every session. The delegate never sees one, and the sensor's + * audio tier, which describes the sound the sensor's streams carry, raises no demand of its own. A rejection of the promise a method returns is a + * `plugin-failure` problem on the camera's channel, printed where nothing subscribes. + * + * A tier's joiners are the viewers at home and from away, which the tier's one pacer sends the stream to, and the library itself, which holds a tier + * with no viewer while the camera is in service, its accessory published and its source not stated away: the recorded tier while the user's switch + * allows recording, and each tier marked {@link CameraVideoTier.keepRunning} while the user's switch allows streaming. An opening needs the tier's stream + * already running, its frames since its latest keyframe kept in its camera buffer: a view starts at once on a tier the library holds, while the first + * viewer of any other tier waits for that tier's stream to start and bring its first keyframe. A plugin marks a tier `keepRunning` when its views + * should start at once, at the cost of that tier's encoding running while nobody watches, and leaves unmarked a tier whose encoding costs too much to run + * unwatched. + * + * Each tier's encoding is expected to stay within the bitrates the tier advertises. A heavier stream is accepted and never refused, at the cost + * {@link TierStream} sets out for the views on it. + * + * @group Camera + */ +export interface MultiTierStreamingDelegate { + /** + * Called when a video tier gains its first joiner, its demand carrying the tier's picture and the sound that comes in its stream. A consumer joins a tier + * in one step: one of the picture that finds a keyframe the tier's pacer has released in the tier's camera buffer is handed the pictures from the latest + * such keyframe on and then each picture the pacer releases, and any other is sent each sample the pacer releases from its join on, a picture from the + * next keyframe, as {@link TierStream} sets out. A stream written inside the call reaches every consumer joined by the time it is released, the one + * whose join raised the demand among them, an RTP session whose Start raised it too. A rejection of the promise refuses the demand: each join waiting on + * it is refused, an RTP session's Start as busy, the stream ignores every write and what the start registered on it is released. A start not settled + * within 30 seconds of its call, whoever joined the tier since, is withdrawn: its signal is aborted and every join waiting on it is refused, an RTP + * session's Start as busy, as at a rejection. + * + * A started stream is held to its silence bounds, whoever joined the tier: its first picture within 30 seconds of the start's settling, a picture written + * inside the call counting, and each later picture within 10 seconds of the one before. Sound counts for neither. A stream that misses a bound fails + * the tier as {@link TierStream.fail} does: every join ends, a view from away among them, which joins every video tier of its sensor, and the first + * join after the last release raises a fresh demand and calls this method again. The tier's silence is told by one `stream-failed` problem, and by none + * more until the tier hands over a picture again. A source stated reconnecting through {@link CameraController.updateSourceState} holds a running + * stream for 30 seconds from the statement, once, until its next picture. + * + * The start registers on its stream what it makes, as it makes it, through {@link ResourceScope.use} and {@link ResourceScope.defer}, and the library + * releases every registration once, where the demand ends, whichever way it ends: as the tier loses its last joiner, at a refused start and at a + * withdrawal, after which the stream ignores a write. The library ends every demand of a camera as the camera goes out of service, its accessory + * unpublished, destroyed or taken off its bridge or its source stated away, releasing what each start registered, which is why a plugin writes no shutdown code + * for it: Homebridge's shutdown unpublishes every accessory before its plugins hear the shutdown event. The start's answer is read for when it settles, + * and for nothing else: a settled value other than nothing is one `plugin-failure` problem, the delegate's failure, and nothing is released for it, + * since what a start makes is released through its registration alone. A later start of the same tier can arrive in the turn the last demand's cleanups + * were called, and the rest of an asynchronous cleanup can overlap it. + * + * The signal is aborted only where the library stops waiting on a start still pending, as it withdraws the demand at the start's bound, at a reset, at + * the camera's removal and as the camera goes out of service, and never once the library has read the start settled, which for a start that answers at + * once is a microtask after it returns: such a start may leave the signal unread, and one that awaits hands it to what it awaits. A start cut while it + * is pending has its signal aborted first and then what it registered released, while its own code may still be running: a start whose every wait takes + * the signal has stopped by then, and one that waits on something that takes no signal calls `signal.throwIfAborted()` after that wait, before it + * touches what it registered. A rejection that follows that abort raises no problem. A listener on the signal runs outside the library's guard: a + * throw from it is an uncaught exception that ends the process. A child process started with the signal raises an error when the signal aborts, + * which ends the process where the plugin listens for no `error` on that child process. + * + * @example + * A start that spawns the tier's encoder and registers the process, which the library kills at the demand's end through its `[Symbol.dispose]`, and + * that fails the tier where the encoder cannot start or ends by itself. A signal that stops the plugin's process can reach its encoders too, and an + * encoder's exit can then come before the library has ended its stream: a plugin that has begun its own stop fails no tier for an exit after that. + * + * ```ts + * const delegate = { + * tierDemandStarted: (stream: TierStream): void => { + * const encoder = stream.use(spawn('ffmpeg', argsFor(stream.tier))) + * + * encoder.on('error', (error: Error) => stream.fail(error.message)) + * encoder.on('exit', (code, signal) => stream.fail(`The encoder ended with ${signal ?? `code ${code}`}.`)) + * encoder.stdout.on('data', (chunk: Buffer) => stream.write(chunk)) + * }, + * } + * ``` + * @example + * A start that awaits a camera's feed, handing the wait its signal, and registers the feed's close once it has the feed: + * + * ```ts + * const delegate = { + * tierDemandStarted: async (stream: TierStream, signal: AbortSignal): Promise => { + * const feed = await camera.openFeed(stream.tier, { signal }) + * + * stream.defer(() => feed.close()) + * feed.on('segment', (segment: Buffer) => stream.write(segment)) + * }, + * } + * ``` + * @param stream - The handle the tier's stream is written through, which carries its tier and takes what the start registers. + * @param signal - Aborted where the library stops waiting on the start while it is pending. + * @returns Nothing, or a promise of nothing. + */ + tierDemandStarted(stream: TierStream, signal: AbortSignal): void | Promise + /** + * Called once for each talker, at home at a session's first talkback packet and from away at the first packet that says voice of each viewer the library + * follows, with the talker's {@link Talker}, and answers the sink that packet and every later one of that talker is written to, until the talker's + * talkback ends. At home that packet is the first that authenticates under the controller's audio key, and from away it is the first whose own Opus voice + * flag says voice, which a device sends as its talk goes on and before the first word. The silence a viewer sends as a view opens starts nothing. A + * viewer whose key the hub removes in one update and writes again in a later one is a new talker. While the camera's Speaker is muted the library writes + * no talkback packet to a sink and starts none, at home and from away: no packet starts a talker, and a sink already started stays started and is + * written again once the Speaker is unmuted. The call returns at once and takes no signal, since the library waits on nothing it answers. A plugin + * whose decoder takes time to start buffers or drops inside its sink. + * + * The call registers on its talker what it makes for the talker, as it makes it, through {@link ResourceScope.use} and {@link ResourceScope.defer}, and + * the library releases every registration once where the talker's talkback ends, as {@link Talker} sets out. It answers the sink itself, and every other + * answer declines talkback for that talker: an answer of nothing, `undefined` among them; a throw, and an answer whose `then` throws when read, each a + * `plugin-failure` problem on the camera's channel as the call's failure; a promise, reported as such a problem once, which the library never awaits and + * whose sink it never writes; and an answer with no `write` function, reported as such a problem once. Each decline releases what the call registered, + * and what a promise's function registers after it is released as it is registered. A declined talker's later talkback packets are dropped, and a + * decline lasts the talker's whole time in the view, at home its session and from away for as long as the session holds the viewer's key, a key replaced + * under its ID included, and the library asks no second time. A delegate without this method takes no talkback at all. A camera publishes its Speaker + * exactly when its delegate has this method: a controller at home offers talkback to that camera, and a plugin builds each camera's delegate with the + * method where the camera has a speaker and without it elsewhere. + * + * @example + * A delegate given the method only for a camera that has a speaker, which means a camera without one publishes no Speaker: + * + * ```ts + * const delegate: MultiTierStreamingDelegate = { + * tierDemandStarted: async (stream: TierStream, signal: AbortSignal): Promise => await device.openFeed(stream, { signal }), + * } + * + * if (device.hasSpeaker) { + * delegate.talkbackStarted = (talker: Talker): TalkbackSink => talker.use(new TalkbackDecoder(talker.sensorUUID)) + * } + * ``` + * @example + * A decoder class whose instance is the sink, registered on the talker and answered in one line: + * + * ```ts + * const delegate = { + * talkbackStarted: (talker: Talker): TalkbackSink => talker.use(new TalkbackDecoder(talker.sensorUUID)), + * } + * ``` + * @example + * A decoder with a stop of its own, registered on the talker, and a sink that writes to it: + * + * ```ts + * const delegate = { + * talkbackStarted: (talker: Talker): TalkbackSink => { + * const decoder = startDecoder(talker.sensorUUID) + * + * talker.defer(() => decoder.stop()) + * + * return { write: (packet: Buffer) => decoder.send(packet) } + * }, + * } + * ``` + * @param talker - The talker's handle, which carries the sensor's UUID and takes what the call registers. + * @returns The talker's sink, or `undefined` to decline. + */ + talkbackStarted?(talker: Talker): TalkbackSink | undefined +} + +/** + * One video tier of a video sensor, an encoding of the sensor's picture the plugin runs while the tier has a joiner and writes to the tier's + * {@link TierStream}. The library advertises it to a hub twice, as one of the sensor's stream tiers and as one of its capabilities in Camera + * Capabilities, both derived from these members. + * + * @group Camera + */ +export interface CameraVideoTier { + /** + * The tier's identifier, a whole number each tier of the sensor holds alone. The library derives the capability's UUID from it and the sensor's UUID, + * which is why a tier keeps its identifier for as long as it stays the same encoding. + */ + id: number + /** + * The width of the tier's picture, in pixels. + */ + width: number + /** + * The height of the tier's picture, in pixels. + */ + height: number + /** + * The frames a second the tier's picture runs at. + */ + frameRate: number + /** + * The tier's target average bitrate, in kbps. + */ + bitrate: number + /** + * The tier's quality, how a controller ranks it among the sensor's tiers. + */ + quality: CameraVideoQuality + /** + * The tier's peak bitrate, in kbps: by default the specification's maximum for the tier's resolution where the bitrate is at or under it, and the + * bitrate where the resolution is in no class the specification lists or the bitrate is above that maximum. The camera controller's constructor throws + * a `TypeError` for a peak below the bitrate. + */ + peakBitrate?: number + /** + * Whether the library holds the tier while the user's switch allows streaming and the camera is in service, its accessory published and its source + * not stated away, raising its demand through `tierDemandStarted` with no viewer and asking for it again after a failure, as it holds the recorded tier + * while the user's switch allows recording and the camera is in service. A tier left unmarked is raised only on demand. `false` by default. + */ + keepRunning?: boolean + /** + * Whether the camera records the tier from its camera buffer, for one tier of the camera at most: by default the first sensor's best tier, the one with + * the most pixels, the higher bitrate deciding between two of one size. `false` by default. The camera controller's constructor throws a `TypeError` for + * a second tier marked. + */ + recorded?: boolean +} + +/** + * The sound a video sensor's streams carry, Opus at 48 kHz with 16 bits a sample, which the library advertises as the sensor's audio tier and reads from + * each tier's stream, or from the sound's tier's stream alone, as {@link CameraAudioTier.source} states. + * + * @group Camera + */ +export interface CameraAudioTier { + /** + * The sound's target average bitrate, in kbps, the plugin's own encoder's. + */ + bitrate: number + /** + * The length of the sound in one packet, in milliseconds, 20 by default. + */ + packetTime?: number + /** + * The sound's channels, one by default. + */ + channels?: number + /** + * Where the sound of the sensor's views comes from. `'tier'`, the default, has each tier's stream carry its own sound as its first Opus track. `'shared'` + * has one tier's sound, the sound's tier, serve every view of the sensor: the camera's recorded tier where the sensor holds it, and the sensor's best tier + * otherwise. The Opus track of every other tier's stream is then ignored, and a recording of the recorded tier carries that tier's own sound. Sound and + * picture are in exact sync on the sound's tier's own pictures, and only approximate on another tier's pictures, the two lined up by the moment each + * tier's run opened and not by the media's own times. A view at home of another tier joins the sound's tier for its sound alone: it starts and runs on + * its own tier, its sound joining as the sound's tier runs, which runs for the view where nothing else holds it, and where the sound's tier is refused, + * cut or fails, a silence of its pictures among the failures, the view goes on silent until it is opened again, the failure told as that tier's own + * problem. A stream of the sound's tier that carries no Opus track raises one `stream-fault` problem for its demand, and no view of the sensor then has + * sound. + * + * A plugin that can hand Opus inside every tier's stream leaves the setting at `'tier'`, the better path, since each view's sound then comes from the + * stream of its own pictures. `'shared'` serves a plugin that cannot: it encodes sound for the sound's tier alone and writes every other tier's stream as + * it has it, reading `stream.tier.sound` at each `tierDemandStarted` to know which streams carry the sound, rather than working the choice out. The camera + * controller's constructor throws a `TypeError` for a value that is neither. + */ + source?: 'shared' | 'tier' +} + +/** + * One video sensor of a camera with the camera capabilities block, stated once: the library derives from it the sensor's Sensor Configuration in Camera + * Capabilities, the stream tiers its stream services advertise and, where it takes zones, its Camera Motion Zones service. The camera lists its sensors in + * the order the block gives them, the first labelled Primary and the rest Generic, in Camera Capabilities and in its stream services alike, because a + * controller shows the sensor that comes first. The library fills in each value only it chooses: each sensor's type, one capability for each tier, HEVC + * video, Opus audio and both payload types. + * + * @group Camera + */ +export interface CameraVideoSensor { + /** + * The sensor's UUID, its HomeKit identity, in any case. Derive it from stable device identity, such as a hardware address, and never generate it at + * startup. The camera controller's constructor throws a `TypeError` for a UUID that is not a UUID and for sensors that share one, the error naming the + * sensor's index in `videoSensors`. + */ + uuid: string + /** + * The sensor's width and height in pixels, which bound every vertex of its motion zones. The camera controller's constructor throws a `TypeError` for a + * sensor without them. + */ + dimensions: SensorDimensions + /** + * What the sensor watches, as Camera Capabilities advertises it. + */ + intent: CameraSensorIntent + /** + * The sensor's video tiers, at least one, each identifier once. The specification asks for at least three. The camera controller's constructor throws a + * `TypeError` for a tier that is not an object, the error naming the tier's index in `tiers`. + */ + tiers: CameraVideoTier[] + /** + * The sound the sensor's streams carry, in each tier's stream or in the sound's tier's alone, as its `source` states. + */ + audio: CameraAudioTier + /** + * Applies the zones a hub draws over the sensor to its motion detection, and gives the sensor a Camera Motion Zones service by being present. The + * library calls it as a plain function, with no receiver: it reads no `this`. + * + * It is called at each write of the sensor's Camera Zones or `Active`, a hub's or the plugin's own `setValue`, and awaited, one write at a time in the + * order the writes arrive. A rejection, or a call still unsettled at the bound the library sets on every awaited delegate call, fails the write and + * keeps the zones in force. The library also calls it with the zones in force at a restore and at a factory reset without awaiting it. A reset's + * call can arrive while a write's call is unsettled, and the library makes no call at a start with no saved zones, when `Active` is on and no zone is set. + * + * Each call is handed a signal of its own. A write's call's signal is aborted where the library stops waiting on that call: at the write's bound, at a + * factory reset and at the camera's removal, and at a reset before the reset's own call is made, which is why a plugin hears that a write is not wanted before it + * hears the defaults. A restore's or a reset's call is handed a signal that never aborts, and every rejection of such a call is a `plugin-failure` + * problem on the camera's channel. A plugin hands the signal to the work the call awaits and to nothing that outlives the call. A rejection that follows + * a write's abort raises no problem. A listener on the signal runs outside the library's guard: a throw from it is an uncaught exception that ends + * the process. A child process started with the signal raises an error when the signal aborts, which ends the process where the plugin listens for + * no `error` on that child process. + * @param zones - The zones in force once a write's call settles, or in force already at a restore or a reset. + * @param reason - `'write'` for a write, `'restore'` for a restore and `'reset'` for a factory reset. + * @param signal - For a write, aborted where the library stops waiting on the call; for a restore or a reset, never aborted. + */ + motionZones?: (zones: MotionZones, reason: CameraChangeReason, signal: AbortSignal) => Promise +} + +/** + * One video sensor's tier set, which the options boundary builds from the sensor's entry and the stream internals read: the stream tiers the sensor's + * services advertise, each video tier's entry as the boundary settled it, and whether the camera was given strict, which the camera keeps for its life + * with the set. + */ +export interface SensorStreamTiers { + /** + * The sensor's UUID, in lowercase. + */ + sensorUUID: string + /** + * The sensor's video stream tiers. + */ + videoStreamTiers: SupportedVideoStreamTiersPayload + /** + * The sensor's audio stream tier, exactly one. + */ + audioStreamTiers: SupportedAudioStreamTiersPayload + /** + * Where the sound of the sensor's views comes from, as its audio states it, `'tier'` where it states none. + */ + audioSource: 'shared' | 'tier' + /** + * The identifier of the sensor's sound tier, the tier a view from away takes its sound from: under `'shared'` the camera's recorded tier where the sensor + * holds it and the sensor's best tier otherwise, and under `'tier'` the sensor's best tier. + */ + soundTierId: number + /** + * Each video tier's entry by its identifier, settled and frozen: its peak at its default where none is given, `keepRunning` and `recorded` as booleans, + * `recorded` true on the tier the camera records whether marked or by default, the sensor's UUID in lowercase, and `sound`, true on a tier whose stream + * must carry the sensor's sound, every tier under `'tier'` and the sound's tier alone under `'shared'`. + */ + tiers: ReadonlyMap + /** + * Whether the camera was given strict, under which a tier's stream that runs past twice its tier's peak over the stretch a view opens on, + * read over a second at least, raises one `stream-fault` problem for its demand rather than writing a debug event. + */ + strict: boolean +} + +/** + * A camera's multi-tier streaming: one delegate for every tier of every video sensor, and the bound on each sensor's sessions. + * + * @group Camera + */ +export interface MultiTierStreamingOptions { + /** + * The delegate every sensor's tiers report their demand to. + */ + delegate: MultiTierStreamingDelegate + /** + * The most sessions each video sensor's service holds at once, prepared or streaming: a positive integer, 5 by default, the specification's floor. A + * value below the floor is taken as given, with a debug event under `HAP-NodeJS:Camera:Controller`, and refused under the camera capabilities block's + * `strict`. + */ + maxSessions?: number +} + +/** + * What the options boundary answers for a camera's video sensors, each sensor in the plugin's order. + */ +export interface ValidatedVideoSensors { + /** + * Each sensor's Sensor Configuration, the first Primary and the rest Generic, which the sensor registry encodes. + */ + readonly configurations: SensorConfiguration[] + /** + * Each sensor's tier set. + */ + readonly tierSets: SensorStreamTiers[] + /** + * Each zoned sensor's `motionZones` function, by the sensor's UUID in lowercase. + */ + readonly motionZones: ReadonlyMap> + /** + * The recorded sensor, by its UUID in lowercase, and its recorded tier: the tier marked recorded, or the first sensor's best tier. + */ + readonly recorded: { readonly sensorUUID: string, readonly tierId: number } + /** + * The most sessions each sensor's multi-tier service holds, the block's own or the specification's floor by default, which each management takes. + */ + readonly maxSessions: number + /** + * The sentence of each minimum of the specification the configuration falls below, in the order they are read, which the camera controller reads once + * every refusal of its options has passed. + */ + readonly minimums: readonly string[] +} + +/** + * The payload type of every talkback packet a {@link TalkbackSink} is written, and of the sound of every stream a video sensor's services send, from RFC + * 3551's dynamic range: the one payload type a plugin's talkback decoder states. + * + * @group Camera + */ +export const TALKBACK_PAYLOAD_TYPE = 110 + +// The payload type of every video tier's picture, from RFC 3551's dynamic range, and the identifier of each sensor's one audio tier. +const VIDEO_PAYLOAD_TYPE = 99 +const AUDIO_TIER_IDENTIFIER = 1 + +// A sensor's audio packet time in milliseconds and its channels, where its entry gives neither: the specification's own. +const DEFAULT_PACKET_TIME = 20 +const DEFAULT_CHANNELS = 1 + +// The specification's floor of simultaneous RTP sessions per video sensor, and the default capacity of each sensor's service. +export const MINIMUM_SESSIONS = 5 + +type ResolutionClass = '4K' | '2K' | '1080p' | '720p' | '360p or 240p' + +interface ResolutionLimit { + readonly resolutionClass: ResolutionClass + readonly maximumKbps: number +} + +// The resolution classes the specification lists, each with every resolution it names for the class and the class's maximum bitrate in kbps. A tier at a +// resolution outside them carries no class and no maximum. +const RESOLUTION_CLASSES: readonly (ResolutionLimit & { readonly resolutions: string })[] = [ + { resolutionClass: '4K', maximumKbps: 5000, resolutions: '3840x2160 2160x3840 2880x2160 2400x3200 2880x2880 3200x2400' }, + { resolutionClass: '2K', maximumKbps: 3000, resolutions: '2560x1440 1440x2560 2048x1536 1536x2048 1920x1920' }, + { resolutionClass: '1080p', maximumKbps: 1800, resolutions: '1920x1080 1080x1920 1600x1200 1200x1600 1440x1440' }, + { resolutionClass: '720p', maximumKbps: 800, resolutions: '1280x720 720x1280 1440x1080 960x1280 1080x1080' }, + { resolutionClass: '360p or 240p', maximumKbps: 190, resolutions: '640x360 360x640 640x480 480x640 480x480 480x360 427x240 320x240' }, +] + +const RESOLUTION_LIMITS: ReadonlyMap = new Map( + RESOLUTION_CLASSES.flatMap(limit => limit.resolutions.split(' ').map(resolution => [resolution, limit] as const)), +) + +function resolutionLimit(tier: Pick): ResolutionLimit | undefined { + return RESOLUTION_LIMITS.get(`${tier.width}x${tier.height}`) +} + +// A tier's peak where its entry gives none: its class's maximum where the bitrate is at or under it, and the bitrate where it has no class or exceeds it. +function defaultPeak(tier: CameraVideoTier): number { + const maximum = resolutionLimit(tier)?.maximumKbps + + return (maximum !== undefined) && (tier.bitrate <= maximum) + ? maximum + : tier.bitrate +} + +/* The refusals of one sensor's entry the stream tier codec cannot make for itself, each a TypeError naming its member: tiers missing or empty, audio or its + * bitrate missing, an audio source that is neither 'shared' nor 'tier', dimensions that are no object, a motionZones that is no function, an intent that is + * no sensor intent, a tier that is no object, named by its index, two tiers sharing an identifier, a quality that is no video quality, a keepRunning or a + * recorded that is no boolean and a peak below its bitrate. The sensor's UUID was refused already where it is no UUID, and each sentence names it in + * lowercase. + */ +function refuseSensor(sensor: CameraVideoSensor): void { + const sensorUUID = sensor.uuid.toLowerCase() + const { audio, dimensions, motionZones, tiers } = sensor + + if (!Array.isArray(tiers) || (tiers.length === 0)) { + throw new TypeError(`The tiers of the video sensor "${sensorUUID}" are missing or empty, but each sensor takes at least one.`) + } + + if ((typeof audio !== 'object') || (audio === null)) { + throw new TypeError(`The video sensor "${sensorUUID}" has no audio, which each sensor states with its bitrate.`) + } + + if (audio.bitrate === undefined) { + throw new TypeError(`The audio of the video sensor "${sensorUUID}" has no bitrate, which each sensor's audio states.`) + } + + if ((audio.source !== undefined) && (audio.source !== 'shared') && (audio.source !== 'tier')) { + throw new TypeError(`The audio of the video sensor "${sensorUUID}" takes a source of 'shared' or 'tier', but ${String(audio.source)} is neither.`) + } + + if ((typeof dimensions !== 'object') || (dimensions === null)) { + throw new TypeError(`The video sensor "${sensorUUID}" has no dimensions, which each sensor states with its width and height.`) + } + + if ((motionZones !== undefined) && (typeof motionZones !== 'function')) { + throw new TypeError(`The motionZones of the video sensor "${sensorUUID}" is not a function.`) + } + + if (!CAMERA_SENSOR_INTENT_VALUES.has(sensor.intent)) { + throw new TypeError(`The intent of the video sensor "${sensorUUID}", ${String(sensor.intent)}, is not a sensor intent.`) + } + + const identifiers = new Set() + + for (const [index, tier] of tiers.entries()) { + if ((typeof tier !== 'object') || (tier === null)) { + throw new TypeError(`The tiers of the video sensor "${sensorUUID}" hold an entry at index ${index} that is not an object.`) + } + + if (identifiers.has(tier.id)) { + throw new TypeError(`The video sensor "${sensorUUID}" has two tiers with the id ${tier.id}.`) + } + + identifiers.add(tier.id) + + if (!CAMERA_VIDEO_QUALITY_VALUES.has(tier.quality)) { + throw new TypeError(`The quality of the tier ${tier.id} of the video sensor "${sensorUUID}", ${String(tier.quality)}, is not a video quality.`) + } + + for (const mark of ['keepRunning', 'recorded'] as const) { + if ((tier[mark] !== undefined) && (typeof tier[mark] !== 'boolean')) { + throw new TypeError(`The ${mark} of the tier ${tier.id} of the video sensor "${sensorUUID}" is not a boolean.`) + } + } + + if ((tier.peakBitrate !== undefined) && (tier.peakBitrate < tier.bitrate)) { + throw new TypeError(`The peakBitrate of the tier ${tier.id} of the video sensor "${sensorUUID}", ${tier.peakBitrate} kbps, is below its bitrate of ` + + `${tier.bitrate} kbps.`) + } + } +} + +/** + * Refuses a list of video sensor UUIDs, each read as the plugin gave it, with a `TypeError` for an entry that is not a UUID, one that is no string among + * them, and for two that share one in any case, the first fault found in the plugin's order, an index the error names being the sensor's index in the + * plugin's list. The options boundary runs it before it reads a UUID, and the sensor registry's constructor runs it over its configurations. + * @param sensorUUIDs - Each video sensor's UUID, in the plugin's order. + */ +export function validateSensorUUIDs(sensorUUIDs: readonly string[]): void { + const indexes = new Map() + + for (const [index, given] of sensorUUIDs.entries()) { + if (!uuid.isValid(given)) { + throw new TypeError(`The video sensor at index ${index} has the sensor UUID "${given}", which is not a UUID.`) + } + + const sensorUUID = given.toLowerCase() + const first = indexes.get(sensorUUID) + if (first !== undefined) { + throw new TypeError(`The video sensors at index ${first} and index ${index} share the sensor UUID "${sensorUUID}", but each sensor needs its own.`) + } + indexes.set(sensorUUID, index) + } +} + +/** + * The best of a sensor's video tiers as they are advertised: the one with the most pixels, the higher target bitrate deciding between two of one size, and + * the earlier advertised between two alike in size and bitrate. It is the sensor's sound tier, which a view from away takes its sound from, unless the + * sensor's audio states its source `'shared'` and the sensor holds the camera's recorded tier, and a camera records the first sensor's unless its plugin + * marks a tier recorded. + * @param tiers - The sensor's video tiers, in the order they are advertised. + * @returns The best tier, or `undefined` for a sensor that offers none. + */ +export function bestStreamTier(tiers: Iterable): VideoStreamTier | undefined { + let best: VideoStreamTier | undefined + let bestPixels = 0 + + for (const tier of tiers) { + const { height, targetAverageBitrate, width } = tier + const pixels = width * height + + if ((best === undefined) || (pixels > bestPixels) || ((pixels === bestPixels) && (targetAverageBitrate > best.targetAverageBitrate))) { + best = tier + bestPixels = pixels + } + } + + return best +} + +/** + * Validates a camera's video sensors and builds from them what the camera advertises and streams: each sensor's Sensor Configuration, its tier set, which + * carries its sound's source and its sound tier, its `motionZones` function and the recorded tier, every value only the library chooses filled in. The + * recorded tier and each sound tier are chosen here alone, once for the camera's life. A rule that keeps the entries coherent throws a `TypeError` naming + * its member, and a minimum of the specification throws nothing here: its sentence is answered, read over the built tier sets once every rule has passed, + * and the camera controller writes it as a debug event, or throws the first as a `TypeError` under `strict`, once every refusal of its options has passed. + * Each entry is read as given and copied, never kept, and a later change to the plugin's objects reaches nothing the camera built. + * @param sensors - The block's video sensors, in the plugin's order. + * @param streaming - The block's multi-tier streaming, whose session bound is defaulted and validated here. + * @param strict - Whether the camera was given strict, which each tier set carries, which means a running stream past twice its tier's peak raises a `stream-fault` + * problem under it. Under it, the camera controller throws a specification minimum rather than writing a debug event. + * @returns The configurations, the tier sets, the zones functions, the recorded tier, the session bound and the sentence of each minimum the + * configuration falls below, each sensor in the plugin's order. + */ +export function validateVideoSensors(sensors: readonly CameraVideoSensor[], streaming: MultiTierStreamingOptions, strict: boolean): ValidatedVideoSensors { + // The block's shape is refused before any entry is read, since an untyped caller can give any value. A refusal names the member rather than a property + // read that fails on it. + if (!Array.isArray(sensors as unknown)) { + throw new TypeError('The camera capabilities block has no videoSensors list, which states each video sensor.') + } + + if ((typeof streaming !== 'object') || (streaming === null)) { + throw new TypeError('The camera capabilities block has no streaming member, which states the multi-tier streaming delegate.') + } + + if (typeof streaming.delegate?.tierDemandStarted !== 'function') { + throw new TypeError('The camera capabilities block\'s streaming delegate has no tierDemandStarted function, which starts each video tier\'s stream.') + } + + for (const [index, sensor] of sensors.entries()) { + if ((typeof sensor !== 'object') || (sensor === null)) { + throw new TypeError(`The video sensor at index ${index} is not an object.`) + } + } + + // The registry's refusals of a sensor's UUID run next, by the plugin's index: every sentence after them names a sensor by its UUID in lowercase. + validateSensorUUIDs(sensors.map(sensor => sensor.uuid)) + + if (sensors.length === 0) { + throw new TypeError('The camera capabilities block lists no video sensors, but it needs at least one.') + } + + const { maxSessions = MINIMUM_SESSIONS } = streaming + + if (!Number.isInteger(maxSessions) || (maxSessions < 1)) { + throw new TypeError(`The multi-tier streaming takes a maxSessions that is a positive integer, but ${maxSessions} is not one.`) + } + + const built = sensors.map((sensor) => { + refuseSensor(sensor) + + const sensorUUID = sensor.uuid.toLowerCase() + const videoStreamTiers: SupportedVideoStreamTiersPayload = { + codec: TieredVideoCodecType.H265, + payloadType: VIDEO_PAYLOAD_TYPE, + tiers: sensor.tiers.map(tier => ({ + identifier: tier.id, + quality: tier.quality, + targetAverageBitrate: tier.bitrate, + width: tier.width, + height: tier.height, + frameRate: tier.frameRate, + })), + } + const audioStreamTiers: SupportedAudioStreamTiersPayload = { + codec: TieredAudioCodecType.OPUS, + payloadType: TALKBACK_PAYLOAD_TYPE, + tiers: [ + { + identifier: AUDIO_TIER_IDENTIFIER, + targetAverageBitrate: sensor.audio.bitrate * 1000, + sampleRate: TieredAudioSampleRate.KHZ_48, + bitDepth: TieredAudioBitDepth.BITS_16, + packetTime: sensor.audio.packetTime ?? DEFAULT_PACKET_TIME, + numberOfChannels: sensor.audio.channels ?? DEFAULT_CHANNELS, + }, + ], + } + + try { + encodeSupportedVideoStreamTiers(videoStreamTiers) + encodeSupportedAudioStreamTiers(audioStreamTiers) + } catch (error) { + throw new TypeError(`The video sensor "${sensorUUID}" has tiers the stream tier codec cannot encode.`, { cause: error }) + } + + return { + audioStreamTiers, + sensor, + sensorUUID, + videoStreamTiers, + } + }) + + // One tier of the camera at most is marked recorded, and with none the first sensor's best tier is. + const marked = built.flatMap(({ sensor, sensorUUID }) => sensor.tiers.filter(tier => tier.recorded === true).map(tier => ({ sensorUUID, tierId: tier.id }))) + + if (marked.length > 1) { + const [first, second] = marked + + throw new TypeError(`The tier ${second.tierId} of the video sensor "${second.sensorUUID}" is marked recorded beside the tier ${first.tierId} of the ` + + `video sensor "${first.sensorUUID}", but a camera records one tier.`) + } + + const recorded = marked[0] ?? { sensorUUID: built[0].sensorUUID, tierId: bestStreamTier(built[0].videoStreamTiers.tiers)!.identifier } + const configurations: SensorConfiguration[] = [] + const tierSets: SensorStreamTiers[] = [] + const motionZones = new Map>() + + for (const [index, { audioStreamTiers, sensor, sensorUUID, videoStreamTiers }] of built.entries()) { + const capabilities: CameraVideoStreamCapabilities[] = [] + const tiers = new Map() + // The sensor's sound tier, which a view from away takes its sound from, chosen here once so no reader of the sound chooses it again: under a shared + // source the recorded tier where the sensor holds it, which means a recording reads its picture and its sound from one stream. + // Otherwise the sound tier is the best tier. + const audioSource = sensor.audio.source ?? 'tier' + const soundTierId = (audioSource === 'shared') && (sensorUUID === recorded.sensorUUID) + ? recorded.tierId + : bestStreamTier(videoStreamTiers.tiers)!.identifier + + for (const tier of sensor.tiers) { + const peakBitrate = tier.peakBitrate ?? defaultPeak(tier) + + capabilities.push({ + identifier: uuid.generate(`${sensorUUID}:${tier.id}`), + videoQuality: tier.quality, + width: tier.width, + height: tier.height, + framesPerSecond: tier.frameRate, + averageBitRate: tier.bitrate, + peakBitRate: peakBitrate, + }) + tiers.set(tier.id, Object.freeze({ + bitrate: tier.bitrate, + frameRate: tier.frameRate, + height: tier.height, + id: tier.id, + keepRunning: tier.keepRunning ?? false, + peakBitrate, + quality: tier.quality, + recorded: (sensorUUID === recorded.sensorUUID) && (tier.id === recorded.tierId), + sensorUUID, + sound: (audioSource === 'tier') || (tier.id === soundTierId), + width: tier.width, + })) + } + + configurations.push({ + sensorDimensions: { width: sensor.dimensions.width, height: sensor.dimensions.height }, + sensorUUID: sensor.uuid, + sensorType: index === 0 + ? CameraSensorType.PRIMARY + : CameraSensorType.GENERIC, + sensorIntent: sensor.intent, + videoStreamCapabilities: capabilities, + }) + tierSets.push({ + audioSource, + audioStreamTiers, + sensorUUID, + soundTierId, + strict, + tiers, + videoStreamTiers, + }) + + if (sensor.motionZones !== undefined) { + motionZones.set(sensorUUID, sensor.motionZones) + } + } + + /* A minimum is answered rather than thrown. A configuration below the specification still runs, a hub taking such a configuration and a plugin + * stating what its camera has, and the controller reads every minimum once its refusals have passed: it writes each as a debug event, and throws the first + * under strict. + */ + const minimums: string[] = [] + + if (maxSessions < MINIMUM_SESSIONS) { + minimums.push(`The multi-tier streaming holds at most ${counted(maxSessions, 'session')} per video sensor, but the specification requires at least five.`) + } + + for (const { sensorUUID, videoStreamTiers, audioStreamTiers } of tierSets) { + const videoTiers = videoStreamTiers.tiers + const [audioTier] = audioStreamTiers.tiers + + if (videoTiers.length < 3) { + minimums.push(`The video sensor "${sensorUUID}" offers ${counted(videoTiers.length, 'video stream tier')}, but the specification requires at least three.`) + } + + if ((audioTier.sampleRate !== TieredAudioSampleRate.KHZ_48) || (audioTier.packetTime !== 20) || (audioTier.numberOfChannels !== 1)) { + minimums.push(`The audio stream tier ${audioTier.identifier} of the video sensor "${sensorUUID}" is not at 48 kHz with a 20 ms packet time and one channel.`) + } + + const classes = new Set(videoTiers.map(tier => resolutionLimit(tier)?.resolutionClass)) + if (videoTiers.some(tier => tier.quality === CameraVideoQuality.HIGHEST) && !(classes.has('4K') && classes.has('2K'))) { + minimums.push(`The video sensor "${sensorUUID}" offers a Highest video stream tier without both a 4K and a 2K tier.`) + } + + for (const tier of videoTiers) { + const { identifier, targetAverageBitrate: bitrate } = tier + const maximum = resolutionLimit(tier)?.maximumKbps + + if ((maximum !== undefined) && (bitrate > maximum)) { + minimums.push(`The video stream tier ${identifier} of the video sensor "${sensorUUID}" targets ${bitrate} kbps, above the specification's maximum ` + + `of ${maximum} kbps.`) + } + } + } + + return { + configurations, + maxSessions, + minimums, + motionZones, + recorded, + tierSets, + } +} diff --git a/src/lib/camera/capabilityKeys.ts b/src/lib/camera/capabilityKeys.ts new file mode 100644 index 000000000..15a0f7314 --- /dev/null +++ b/src/lib/camera/capabilityKeys.ts @@ -0,0 +1,49 @@ +import type { ControllerServiceMap } from '../controller/index.js' +import type { Service } from '../Service.js' + +/** + * The prefix of every service-map key the camera capabilities block owns. A restore without the block can find and delete each one. + */ +export const CAPABILITY_KEY_PREFIX = 'cameraCapabilities:' + +/** + * The key a video sensor's service for one capability carries in the camera's service map and in the policy. + * @param capability - The capability's name in the key. + * @param sensorUUID - The video sensor's UUID. + * @returns The capability prefix, the capability's name and a colon, then the UUID in lowercase. + */ +export function sensorServiceKey(capability: string, sensorUUID: string): string { + return `${CAPABILITY_KEY_PREFIX}${capability}:${sensorUUID.toLowerCase()}` +} + +/** + * Reconciles every video sensor's service for one capability in a restored service map, in the order given: a sensor's saved service under its key is + * adopted, and a sensor without one gets a new service, inserted. The key of a sensor missing from the camera's inventory is left to the capability key sweep. + * @param serviceMap - The camera's service map, changed in place. + * @param sensors - Each video sensor's options, in the camera's order. + * @param keyOf - Answers the key of a sensor's service from its options. + * @param create - Builds a sensor's management over its saved service, or over a new one when it is given none, and answers the service it adopted or built. + * @returns Whether the map changed. + */ +export function reconcileSensorServices( + serviceMap: ControllerServiceMap, + sensors: readonly Options[], + keyOf: (options: Options) => string, + create: (options: Options, service?: S) => S, +): boolean { + let modified = false + + for (const options of sensors) { + const key = keyOf(options) + const saved = serviceMap[key] as S | undefined + + if (saved) { + create(options, saved) + } else { + serviceMap[key] = create(options) + modified = true + } + } + + return modified +} diff --git a/src/lib/camera/index.ts b/src/lib/camera/index.ts index bef3b58e1..133e28961 100644 --- a/src/lib/camera/index.ts +++ b/src/lib/camera/index.ts @@ -1,8 +1,20 @@ export * from './capabilities/index.js' export * from './diagnostics/problems.js' +export type { MotionZones, MotionZonesManagementState } from './MotionZonesManagement.js' +export type { CameraChangeReason, OperatingModeChange, OperatingModeField, OperatingModeState, StreamingEnabledChange } from './OperatingModePolicy.js' export * from './RecordingManagement.js' export * from './RTPProxy.js' export * from './RTPStreamManagement.js' export type { + CameraAudioTier, + CameraVideoSensor, + CameraVideoTier, + MultiTierStreamingDelegate, + MultiTierStreamingOptions, ResourceScope, + TalkbackSink, + Talker, + TierStream, + TierStreamStatistics, } from './StreamingOptions.js' +export { TALKBACK_PAYLOAD_TYPE } from './StreamingOptions.js' diff --git a/src/lib/util/valueGuard.ts b/src/lib/util/valueGuard.ts new file mode 100644 index 000000000..0817d15ee --- /dev/null +++ b/src/lib/util/valueGuard.ts @@ -0,0 +1,67 @@ +import type { CharacteristicValue, Nullable } from '../../types.js' +import type { Characteristic } from '../Characteristic.js' + +/* The library's guards on single characteristics, which only the library sets. A guard answers the value its one characteristic stores for each value + * the characteristic has cleaned up, which means a write it changes is an ordinary write of the value it answers. `Characteristic` lends the one install as it + * loads, which gives a characteristic a clean-up step of its own, and every path that stores or answers a value a plugin supplies runs that step first: + * `updateValue`, `setValue`, `sendEventNotification`, a read handler's answer, a plain read of the held value, a write response and `setProps`' + * correction. Outside a guard stand `Characteristic.deserialize` and a direct assignment of `value`, which store a value as written: a plain read still + * answers it through the step, and an accessory listing that asks no read handler answers it as stored. Outside it too stands a hub's own write, which + * `validateClientSuppliedValue` cleans and no guard sees. A guard stands only on a value no hub writes. + */ + +/** + * A characteristic's guard: it takes a value the characteristic has cleaned up and answers the value stored in its place. + */ +export type ValueGuard = (value: Nullable) => Nullable + +/** + * The install `Characteristic` lends: it gives the one characteristic a clean-up step that runs the class's and answers the guard's value for its result, + * and answers a disposable that takes that step away. + */ +export type GuardInstall = (characteristic: Characteristic, guard: ValueGuard) => Disposable + +// The install the class lent as it loaded, and each guarded characteristic's guard, held weakly so a characteristic that is collected takes its entry +// with it. +let install: GuardInstall | undefined +const guards = new WeakMap() + +/** + * Takes the install `Characteristic` lends from its static block as the class loads. + * @param lent - The install. + */ +export function lendGuardInstall(lent: GuardInstall): void { + install = lent +} + +/** + * Sets a guard on one characteristic that holds none. The install is lent as the class loads, and a caller imports the class first, which is why it is always + * lent here. + * @param characteristic - The characteristic. + * @param guard - The guard. + * @returns A disposable that takes the guard away, the characteristic storing every value as written again. + */ +export function guardValues(characteristic: Characteristic, guard: ValueGuard): Disposable { + const installed = install!(characteristic, guard) + + guards.set(characteristic, guard) + + return { + [Symbol.dispose]: () => { + guards.delete(characteristic) + installed[Symbol.dispose]() + }, + } +} + +/** + * Whether a characteristic stores a value as written: true for one with no guard, and for one with a guard, whether the guard answers the value as it is. + * @param characteristic - The characteristic. + * @param value - The value, as the characteristic would clean it up. + * @returns Whether the value is stored as written. + */ +export function admitsValue(characteristic: Characteristic, value: Nullable): boolean { + const guard = guards.get(characteristic) + + return (guard === undefined) || (guard(value) === value) +} From a5449335163ea4f70ad21f28284899b37890cf8c Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:48 -0600 Subject: [PATCH 10/16] feat(camera): add the media primitives: the fragmented MP4 reader and writer, the RTP clock, the frame cutter and SRTP --- src/lib/camera/StreamingOptions.ts | 39 + src/lib/camera/mp4/Mp4StreamReader.spec.ts | 1808 ++++++++++++++++++++ src/lib/camera/mp4/Mp4StreamReader.ts | 838 +++++++++ src/lib/camera/mp4/mp4Boxes.spec.ts | 1131 ++++++++++++ src/lib/camera/mp4/mp4Boxes.ts | 1215 +++++++++++++ src/lib/camera/mp4/mp4Writer.ts | 581 +++++++ src/lib/camera/rtp/FrameCutter.spec.ts | 246 +++ src/lib/camera/rtp/FrameCutter.ts | 357 ++++ src/lib/camera/rtp/RTPClock.spec.ts | 167 ++ src/lib/camera/rtp/RTPClock.ts | 220 +++ src/lib/camera/rtp/packetRules.spec.ts | 71 + src/lib/camera/rtp/packetRules.ts | 55 + src/lib/camera/srtp/SRTPContext.ts | 530 ++++++ src/lib/camera/srtp/keystream.ts | 81 + src/test-utils/mp4Fixtures.ts | 625 +++++++ src/test-utils/rtpVectors.ts | 248 +++ 16 files changed, 8212 insertions(+) create mode 100644 src/lib/camera/mp4/Mp4StreamReader.spec.ts create mode 100644 src/lib/camera/mp4/Mp4StreamReader.ts create mode 100644 src/lib/camera/mp4/mp4Boxes.spec.ts create mode 100644 src/lib/camera/mp4/mp4Boxes.ts create mode 100644 src/lib/camera/mp4/mp4Writer.ts create mode 100644 src/lib/camera/rtp/FrameCutter.spec.ts create mode 100644 src/lib/camera/rtp/FrameCutter.ts create mode 100644 src/lib/camera/rtp/RTPClock.spec.ts create mode 100644 src/lib/camera/rtp/RTPClock.ts create mode 100644 src/lib/camera/rtp/packetRules.spec.ts create mode 100644 src/lib/camera/rtp/packetRules.ts create mode 100644 src/lib/camera/srtp/SRTPContext.ts create mode 100644 src/lib/camera/srtp/keystream.ts create mode 100644 src/test-utils/mp4Fixtures.ts create mode 100644 src/test-utils/rtpVectors.ts diff --git a/src/lib/camera/StreamingOptions.ts b/src/lib/camera/StreamingOptions.ts index f9b51a0a2..b90a69d31 100644 --- a/src/lib/camera/StreamingOptions.ts +++ b/src/lib/camera/StreamingOptions.ts @@ -19,6 +19,11 @@ import { TieredVideoCodecType, } from './capabilities/streamTiers.js' +/** + * A medium of a tier's stream, its picture or its sound, which the library reads from the stream and sends on runs of its own. + */ +export type StreamTierMedium = 'audio' | 'video' + /** * What a tier's stream has carried since its demand started, its picture and its sound together: the RTP packets the library sent the tier's RTP sessions, * summed over them, and the consumers the tier serves. A consumer the library hands whole frames is counted among the consumers and in none of the packet @@ -47,6 +52,37 @@ export interface TierStreamStatistics { readonly consumers: number } +/** + * One encoded frame of a tier's stream, in the form the library sends it, read from one sample of the stream's picture or its sound. + */ +export interface TierFrame { + /** + * The frame's bytes. A video frame is its HEVC NAL units in decode order, each behind its length in four octets, big-endian, with a keyframe's parameter + * sets before its picture: a keyframe that holds each of HEVC's video, sequence and picture parameter sets is its sample's octets, and one that holds + * fewer takes its stream's whole block of them after its access unit delimiter or at its front. An audio frame is one Opus packet. A consumer reads the + * bytes before its call returns and never keeps them. + */ + readonly data: Buffer + /** + * The frame's presentation time, the moment its picture or sound was captured, in microseconds on its source's own clock, which picture and sound + * share: a frame is placed at its time's distance from its run's first, and the distance between a picture and a sound is their source's own, whenever + * the tier's pacer releases it. + */ + readonly time: number + /** + * Whether a video frame can be decoded with nothing before it. + */ + readonly keyframe?: boolean +} + +// The octets of the big-endian length each NAL unit of a video frame stands behind. +export const FRAME_LENGTH_SIZE = 4 + +// The octets of HEVC's NAL unit header, which every unit of a video frame opens with, and the mask of the unit's type, which the header's first octet +// carries in the six bits below its top bit (ITU-T H.265 7.3.1.2). +export const HEVC_HEADER_LENGTH = 2 +export const HEVC_TYPE_MASK = 0x3F + /** * How a plugin registers what it makes on a handle the library gives it, for something whose life the library decides: the plugin registers each resource * as it makes it, and the library releases every registration once, where the handle's life ends, whichever way it ends, and the plugin releases none of @@ -672,6 +708,9 @@ const RESOLUTION_CLASSES: readonly (ResolutionLimit & { readonly resolutions: st { resolutionClass: '360p or 240p', maximumKbps: 190, resolutions: '640x360 360x640 640x480 480x640 480x480 480x360 427x240 320x240' }, ] +// The specification's heaviest maximum, the highest any resolution class allows, in kbps: the rate an opening's burst is held to a multiple of. +export const HEAVIEST_MAXIMUM_KBPS = Math.max(...RESOLUTION_CLASSES.map(({ maximumKbps }) => maximumKbps)) + const RESOLUTION_LIMITS: ReadonlyMap = new Map( RESOLUTION_CLASSES.flatMap(limit => limit.resolutions.split(' ').map(resolution => [resolution, limit] as const)), ) diff --git a/src/lib/camera/mp4/Mp4StreamReader.spec.ts b/src/lib/camera/mp4/Mp4StreamReader.spec.ts new file mode 100644 index 000000000..94ff6830c --- /dev/null +++ b/src/lib/camera/mp4/Mp4StreamReader.spec.ts @@ -0,0 +1,1808 @@ +import type { SampleFixture, SampleRunFixture, TrackFixture } from '../../../test-utils/mp4Fixtures.js' +import type { StreamTierMedium, TierFrame } from '../StreamingOptions.js' +import type { Mp4StreamAudioTrack, Mp4StreamConsumer, Mp4StreamSample, Mp4StreamTracks, Mp4StreamVideoTrack } from './Mp4StreamReader.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + avcC, + box, + fullBox, + hvcC, + initializationSegment, + int32, + largeBox, + mp4aSampleEntry, + openBox, + opusSampleEntry, + sampleFragment, + uint32, + uint64, + visualSampleEntry, +} from '../../../test-utils/mp4Fixtures.js' +import { RTP_VECTORS, tierFrameData } from '../../../test-utils/rtpVectors.js' +import { walkBoxes } from './mp4Boxes.js' +import { frameOf, Mp4StreamReader } from './Mp4StreamReader.js' + +// One sample as the reader handed it: its track's medium, whether its track is the one the latest tracks handed on describe, its octets in hexadecimal and +// its fields. +interface HandedSample { + medium: StreamTierMedium + described: boolean + data: string + decodeTime: bigint + duration?: number + compositionOffset: number + sync: boolean +} + +// What a reader handed its consumer, in order: each initialization segment's tracks, each sample, each fragment's end and each failure. +type Handed = { tracks: Mp4StreamTracks } | { sample: HandedSample } | 'end' | { fail: string } + +// A consumer logging what it is handed, and the samples themselves. +function logging(): { consumer: Mp4StreamConsumer, handed: Handed[], samples: Mp4StreamSample[] } { + const handed: Handed[] = [] + const samples: Mp4StreamSample[] = [] + let latest: Mp4StreamTracks = {} + const consumer: Mp4StreamConsumer = { + fail: (reason) => { + handed.push({ fail: reason }) + }, + fragmentEnd: () => { + handed.push('end') + }, + sample: (sample) => { + const { compositionOffset, data, decodeTime, duration, sync, track } = sample + + samples.push(sample) + handed.push({ + sample: { + compositionOffset, + data: data.toString('hex'), + decodeTime, + described: track === latest[track.medium], + medium: track.medium, + sync, + ...(duration === undefined + ? {} + : { duration }), + }, + }) + }, + tracks: (tracks) => { + latest = tracks + handed.push({ tracks }) + }, + } + + return { consumer, handed, samples } +} + +// A reader logging what it hands on, written each chunk given in turn. +function read(...chunks: Buffer[]): { handed: Handed[], reader: Mp4StreamReader, samples: Mp4StreamSample[] } { + const { consumer, handed, samples } = logging() + const reader = new Mp4StreamReader(consumer) + + for (const chunk of chunks) { + reader.write(chunk) + } + + return { handed, reader, samples } +} + +// The vectors' frames, each its NAL units: a keyframe whose units open with its parameter sets, two frames after it and a second keyframe. +const HEVC = RTP_VECTORS.stream.frames.map(({ units }) => units.map(unit => Buffer.from(unit, 'hex'))) + +// The parameter sets the stream's keyframes open with, which an initialization segment carries in place of its samples. +const HEVC_SETS = HEVC[0].slice(0, 3) + +// HEVC's access unit delimiter, of type 35, naming the picture types the access unit may hold. +const HEVC_DELIMITER = Buffer.from('460150', 'hex') + +// The flags of a sync sample that depends on no other, and of a sample that is no sync sample and depends on one before it. +const SYNC = 0x02000000 +const NON_SYNC = 0x01010000 + +const VIDEO_ENTRY = visualSampleEntry('hvc1', 64, 36, hvcC(HEVC_SETS.map((unit, index) => ({ + type: 32 + index, + units: [unit], +})))) +const OPUS_ENTRY = opusSampleEntry() + +// A video track 1 at 90 kHz and an Opus track 2 at 48 kHz. +const VIDEO: TrackFixture = { + handler: 'vide', + id: 1, + sampleEntry: VIDEO_ENTRY, + timescale: 90000, +} +const OPUS: TrackFixture = { + handler: 'soun', + id: 2, + sampleEntry: OPUS_ENTRY, + timescale: 48000, +} + +const INITIALIZATION = initializationSegment(VIDEO, OPUS) + +// The tracks the reader describes from that segment. +const VIDEO_TRACK: Mp4StreamVideoTrack = { + height: 36, + id: 1, + medium: 'video', + parameterSets: tierFrameData(HEVC_SETS), + sampleEntry: VIDEO_ENTRY, + timescale: 90000, + width: 64, +} +const AUDIO_TRACK: Mp4StreamAudioTrack = { + id: 2, + medium: 'audio', + sampleEntry: OPUS_ENTRY, + timescale: 48000, +} + +// A picture sample of the units given, 6000 ticks long at 90 kHz, a sync sample when it is a keyframe. +function picture(units: Buffer[], keyframe = false): SampleFixture { + return { + data: tierFrameData(units), + duration: 6000, + flags: keyframe + ? SYNC + : NON_SYNC, + } +} + +// A sound sample of two octets, an Opus TOC and a tag, 960 ticks long at 48 kHz. +function sound(tag: number): SampleFixture { + return { + data: Buffer.from([0xFC, tag]), + duration: 960, + } +} + +// A fragment of track 1's video samples from a decode time. +function videoFragment(decodeTime: bigint | undefined, ...samples: SampleFixture[]): Buffer { + return sampleFragment({ decodeTime, samples, trackId: 1 }) +} + +// A fragment of the samples given of track 2's Opus, each of one octet and 960 ticks long at 48 kHz, from a decode time of zero. +function opusFragment(count: number): Buffer { + return sampleFragment({ + decodeTime: 0n, + samples: Array.from({ length: count }, () => ({ + data: Buffer.from([0xFC]), + duration: 960, + })), + trackId: 2, + }) +} + +// An initialization segment of a video track 1 at 90 kHz with the sample entry given, beside an Opus track 2 at 48 kHz. +function initialization(videoEntry: Buffer, audioEntry = OPUS_ENTRY): Buffer { + return initializationSegment( + { + ...VIDEO, + sampleEntry: videoEntry, + }, + { + ...OPUS, + sampleEntry: audioEntry, + }, + ) +} + +// A synthetic sequence and picture parameter set, which a well-formed avcC of an entry the reader refuses holds. +const AVC_SEQUENCE = Buffer.from('674d401f', 'hex') +const AVC_PICTURE = Buffer.from('68ebef20', 'hex') + +// The frame form of a sample of the units given at a time in microseconds. +function frame(units: Buffer[], time: number, keyframe = false): TierFrame { + return { + data: tierFrameData(units), + keyframe, + time, + } +} + +// A frame as a row keeps it, its bytes copied as it is handed, since they may be a view the reader reuses. +function kept(handed: TierFrame): TierFrame { + return { + ...handed, + data: Buffer.from(handed.data), + } +} + +// A stream reader handing the frame form of each sample of a medium's track to the call given, and keeping each reason it fails with. +function frameReader(medium: StreamTierMedium, take: (handed: TierFrame) => void): { reader: Mp4StreamReader, reasons: string[] } { + const reasons: string[] = [] + const reader = new Mp4StreamReader({ + fail: (reason) => { + reasons.push(reason) + }, + fragmentEnd: () => undefined, + sample: (sample) => { + if (sample.track.medium === medium) { + take(frameOf(sample)) + } + }, + tracks: () => undefined, + }) + + return { reader, reasons } +} + +// A frame reader of a medium keeping each frame it is handed, written each chunk given in turn. +function readFrames(medium: StreamTierMedium, ...chunks: Buffer[]): { frames: TierFrame[], reader: Mp4StreamReader, reasons: string[] } { + const frames: TierFrame[] = [] + const { reader, reasons } = frameReader(medium, handed => frames.push(kept(handed))) + + for (const chunk of chunks) { + reader.write(chunk) + } + + return { frames, reader, reasons } +} + +// A sample the reader hands on, of the medium and octets given, with its fields; a sample with no stated duration leaves it out. +function handedSample(medium: StreamTierMedium, data: Buffer, fields: Omit): { sample: HandedSample } { + return { + sample: { + data: data.toString('hex'), + described: true, + medium, + ...fields, + }, + } +} + +describe('mp4StreamReader', () => { + // A fragment whose sound run stands before its picture run, a picture sample with a composition offset among them. + const soundFirst = sampleFragment( + { + decodeTime: 48000n, + samples: [ + sound(1), + sound(2), + ], + trackId: 2, + }, + { + decodeTime: 0n, + samples: [ + { + ...picture(HEVC[0].slice(3), true), + compositionOffset: 6000, + }, + { + ...picture(HEVC[1]), + compositionOffset: 0, + }, + ], + trackId: 1, + }, + ) + // A fragment interleaving its tracks' runs, each track's second run continuing from its first, the last sound sample's duration stated nowhere. + const interleaved = sampleFragment( + { + decodeTime: 12000n, + samples: [ + picture(HEVC[2]), + ], + trackId: 1, + }, + { + decodeTime: 50880n, + samples: [ + sound(3), + ], + trackId: 2, + }, + { + samples: [ + picture(HEVC[3].slice(3), true), + ], + trackId: 1, + }, + { + samples: [ + { + data: Buffer.from([0xFC, 4]), + }, + ], + trackId: 2, + }, + ) + // A fragment after a discontinuity, its sound run with no decode time of its own. + const afterDiscontinuity = sampleFragment( + { + decodeTime: 90000n, + samples: [ + picture(HEVC[1]), + ], + trackId: 1, + }, + { + samples: [ + sound(5), + ], + trackId: 2, + }, + ) + // A fragment after a second initialization segment. + const afterInitialization = sampleFragment( + { + decodeTime: 0n, + samples: [ + picture(HEVC[0].slice(3), true), + ], + trackId: 1, + }, + { + decodeTime: 0n, + samples: [ + sound(6), + ], + trackId: 2, + }, + ) + // The stream before its discontinuity and after it. + const before = Buffer.concat([INITIALIZATION, soundFirst, interleaved]) + const after = Buffer.concat([afterDiscontinuity, INITIALIZATION, afterInitialization]) + const expected: Handed[] = [ + { + tracks: { audio: AUDIO_TRACK, video: VIDEO_TRACK }, + }, + handedSample('audio', Buffer.from([0xFC, 1]), { + compositionOffset: 0, + decodeTime: 48000n, + duration: 960, + sync: true, + }), + handedSample('audio', Buffer.from([0xFC, 2]), { + compositionOffset: 0, + decodeTime: 48960n, + duration: 960, + sync: true, + }), + handedSample('video', tierFrameData(HEVC[0].slice(3)), { + compositionOffset: 6000, + decodeTime: 0n, + duration: 6000, + sync: true, + }), + handedSample('video', tierFrameData(HEVC[1]), { + compositionOffset: 0, + decodeTime: 6000n, + duration: 6000, + sync: false, + }), + 'end', + handedSample('video', tierFrameData(HEVC[2]), { + compositionOffset: 0, + decodeTime: 12000n, + duration: 6000, + sync: false, + }), + handedSample('audio', Buffer.from([0xFC, 3]), { + compositionOffset: 0, + decodeTime: 50880n, + duration: 960, + sync: true, + }), + handedSample('video', tierFrameData(HEVC[3].slice(3)), { + compositionOffset: 0, + decodeTime: 18000n, + duration: 6000, + sync: true, + }), + handedSample('audio', Buffer.from([0xFC, 4]), { + compositionOffset: 0, + decodeTime: 51840n, + sync: true, + }), + 'end', + handedSample('video', tierFrameData(HEVC[1]), { + compositionOffset: 0, + decodeTime: 90000n, + duration: 6000, + sync: false, + }), + handedSample('audio', Buffer.from([0xFC, 5]), { + compositionOffset: 0, + decodeTime: 0n, + duration: 960, + sync: true, + }), + 'end', + { + tracks: { audio: AUDIO_TRACK, video: VIDEO_TRACK }, + }, + handedSample('video', tierFrameData(HEVC[0].slice(3)), { + compositionOffset: 0, + decodeTime: 0n, + duration: 6000, + sync: true, + }), + handedSample('audio', Buffer.from([0xFC, 6]), { + compositionOffset: 0, + decodeTime: 0n, + duration: 960, + sync: true, + }), + 'end', + ] + + // What a reader hands on written the stream's bytes before the discontinuity as the chunks given, then the discontinuity, then the rest as the chunks + // given. + function handedOf(first: Buffer[], second: Buffer[]): Handed[] { + const { handed, reader } = read(...first) + + reader.discontinuity() + + for (const chunk of second) { + reader.write(chunk) + } + + return handed + } + + // A stretch's top-level boxes, each a chunk of its own. + function boxesOf(bytes: Buffer): Buffer[] { + return walkBoxes(bytes).boxes.map(({ end, start }) => bytes.subarray(start, end)) + } + + // A stretch an octet at a time. + function octetsOf(bytes: Buffer): Buffer[] { + return Array.from(bytes, octet => Buffer.from([octet])) + } + + it('hands each sample of both tracks in the order the mdat places them, with its decode time, stated duration, composition offset and sync flag, beside ' + + 'each track\'s description and each fragment\'s end, from the bytes written whole, an octet at a time, at every box boundary and cut at every offset ' + + 'of a fragment', () => { + expect(handedOf([before], [after])).toEqual(expected) + expect(handedOf(boxesOf(before), boxesOf(after))).toEqual(expected) + expect(handedOf(octetsOf(before), octetsOf(after))).toEqual(expected) + + for (const fragment of [soundFirst, interleaved]) { + for (let cut = 1; cut < fragment.length; cut++) { + const chunks = [INITIALIZATION, soundFirst, interleaved].flatMap(part => part === fragment + ? [ + part.subarray(0, cut), + part.subarray(cut), + ] + : [part]) + + expect(handedOf(chunks, [after])).toEqual(expected) + } + } + }, 30000) + + it('reads a stream with no Opus track as picture alone and hands on a stream with no video track with the tracks it has, failing neither, and leaves ' + + 'the refusal of a stream that lacks a track to its consumer', () => { + const mp4a: TrackFixture = { + handler: 'soun', + id: 2, + sampleEntry: mp4aSampleEntry(2), + timescale: 16000, + } + const fragment = sampleFragment( + { + decodeTime: 0n, + samples: [ + picture(HEVC[0].slice(3), true), + ], + trackId: 1, + }, + { + decodeTime: 0n, + samples: [ + sound(1), + ], + trackId: 2, + }, + ) + const pictureAlone = read(initializationSegment(VIDEO, mp4a), fragment) + const soundAlone = read(initializationSegment(OPUS), fragment) + + expect(pictureAlone.handed).toEqual([ + { + tracks: { video: VIDEO_TRACK }, + }, + handedSample('video', tierFrameData(HEVC[0].slice(3)), { + compositionOffset: 0, + decodeTime: 0n, + duration: 6000, + sync: true, + }), + 'end', + ]) + expect(soundAlone.handed).toEqual([ + { + tracks: { audio: AUDIO_TRACK }, + }, + handedSample('audio', Buffer.from([0xFC, 1]), { + compositionOffset: 0, + decodeTime: 0n, + duration: 960, + sync: true, + }), + 'end', + ]) + expect(Object.keys((pictureAlone.handed[0] as { tracks: Mp4StreamTracks }).tracks)).toEqual(['video']) + expect(Object.keys((soundAlone.handed[0] as { tracks: Mp4StreamTracks }).tracks)).toEqual(['audio']) + }) + + it('makes each sample\'s frame form as the live path sends it: its time in microseconds from its decode time and composition offset, a keyframe\'s ' + + 'parameter sets first or after its delimiter, its keyframe flag', () => { + const otherSets = [ + Buffer.from('40010c02ff', 'hex'), + Buffer.from('42010102ff', 'hex'), + Buffer.from('440102ff', 'hex'), + ] + const otherInitialization = initializationSegment({ + ...VIDEO, + sampleEntry: visualSampleEntry('hev1', 64, 36, hvcC(otherSets.map((unit, index) => ({ + type: 32 + index, + units: [unit], + })))), + }, OPUS) + const wide = 2n ** 32n + 9000n + const { reader, samples } = read( + INITIALIZATION, + sampleFragment( + { + decodeTime: 48000n, + samples: [ + sound(1), + sound(2), + ], + trackId: 2, + }, + { + decodeTime: 0n, + samples: [ + picture(HEVC[0].slice(3), true), + picture(HEVC[1]), + picture(HEVC[2]), + ], + trackId: 1, + }, + ), + sampleFragment({ + decodeTime: 18000n, + samples: [ + picture([ + HEVC_DELIMITER, + ...HEVC[3].slice(3), + ], true), + ], + trackId: 1, + }), + sampleFragment({ + decodeTime: 90000n, + samples: [ + { + ...picture(HEVC[1]), + compositionOffset: 6000, + }, + ], + trackId: 1, + version: 0, + }), + sampleFragment({ + decodeTime: wide, + samples: [ + picture(HEVC[2]), + ], + trackId: 1, + }), + sampleFragment({ + samples: [ + picture(HEVC[1]), + ], + trackId: 1, + }), + ) + + reader.discontinuity() + reader.write(sampleFragment({ + samples: [ + picture(HEVC[2]), + ], + trackId: 1, + })) + reader.write(otherInitialization) + reader.write(sampleFragment({ + decodeTime: 0n, + samples: [ + picture(HEVC[3].slice(3), true), + ], + trackId: 1, + })) + + expect(samples.map(sample => frameOf(sample))).toEqual([ + { + data: Buffer.from([0xFC, 1]), + time: 1000000, + }, + { + data: Buffer.from([0xFC, 2]), + time: 1020000, + }, + frame(HEVC[0], 0, true), + frame(HEVC[1], 66666), + frame(HEVC[2], 133333), + frame([ + HEVC_DELIMITER, + ...HEVC_SETS, + ...HEVC[3].slice(3), + ], 200000, true), + frame(HEVC[1], 1066666), + frame(HEVC[2], Number(wide * 1000000n / 90000n)), + frame(HEVC[1], Number((wide + 6000n) * 1000000n / 90000n)), + frame(HEVC[2], 0), + frame([ + ...otherSets, + ...HEVC[3].slice(3), + ], 0, true), + ]) + }) + + it('hands a keyframe of a track that carries no parameter sets, and one that holds each of them, as the very octets its sample holds, and one holding ' + + 'fewer of a track that carries them as a copy with the track\'s whole block of sets before its first unit or after its access unit delimiter', () => { + // A stream that carries its parameter sets in its keyframes alone, and one that carries them in its initialization segment. + const { samples: [inBand] } = read(initialization(visualSampleEntry('hvc1', 64, 36, hvcC([]))), videoFragment(0n, picture(HEVC[0], true))) + const { samples: [described] } = read(INITIALIZATION, videoFragment(0n, picture(HEVC[0].slice(3), true))) + // On the track that carries the sets, keyframes holding each of them, alone and after an access unit delimiter, and keyframes holding its sequence and + // picture parameter sets without its video one before the keyframe's slice, alone and after a delimiter. + const slice = HEVC[0].slice(3) + const fewer = HEVC_SETS.slice(1) + const holding = [ + HEVC[0], + [ + HEVC_DELIMITER, + ...HEVC[0], + ], + ] + const lacking = [ + [ + ...fewer, + ...slice, + ], + [ + HEVC_DELIMITER, + ...fewer, + ...slice, + ], + ] + const keyframes = (runs: readonly Buffer[][]): Mp4StreamSample[] => runs.map((units) => { + const { samples: [sample] } = read(INITIALIZATION, videoFragment(0n, picture(units, true))) + + return sample + }) + // On a track that carries no sets, a keyframe holding a sequence and a picture parameter set without a video one, which the track has no block of + // sets to complete. + const { samples: [fewerInBand] } = read(initialization(visualSampleEntry('hvc1', 64, 36, hvcC([]))), videoFragment(0n, picture([ + ...fewer, + ...slice, + ], true))) + + expect(frameOf(inBand).data).toBe(inBand.data) + expect(frameOf(fewerInBand).data).toBe(fewerInBand.data) + expect(frameOf(inBand)).toEqual(frame(HEVC[0], 0, true)) + expect(frameOf(described).data).not.toBe(described.data) + expect(frameOf(described)).toEqual(frame(HEVC[0], 0, true)) + expect(keyframes(holding).map(sample => frameOf(sample).data === sample.data)).toEqual([true, true]) + expect(keyframes(lacking).map(sample => frameOf(sample))).toEqual([ + frame([ + ...HEVC_SETS, + ...fewer, + ...slice, + ], 0, true), + frame([ + HEVC_DELIMITER, + ...HEVC_SETS, + ...fewer, + ...slice, + ], 0, true), + ]) + }) + + // A fragment of a keyframe on track 1 at decode time zero beside the sound runs given, the picture run first in its mdat. + function pictureBeside(...sounds: SampleRunFixture[]): Buffer { + return sampleFragment( + { + decodeTime: 0n, + samples: [ + picture(HEVC[0].slice(3), true), + ], + trackId: 1, + }, + ...sounds, + ) + } + + // The keyframe that fragment hands on, the first of its track. + const besideKeyframe = handedSample('video', tierFrameData(HEVC[0].slice(3)), { + compositionOffset: 0, + decodeTime: 0n, + duration: 6000, + sync: true, + }) + + it('passes over an Opus track of timescale 0 beside a video track for a later Opus track, and reads a stream whose one Opus track has timescale 0 as ' + + 'picture alone', () => { + const untimed: TrackFixture = { + ...OPUS, + timescale: 0, + } + const later: TrackFixture = { + ...OPUS, + id: 3, + } + const fragment = pictureBeside( + { + decodeTime: 0n, + samples: [ + sound(1), + ], + trackId: 2, + }, + { + decodeTime: 48000n, + samples: [ + sound(2), + ], + trackId: 3, + }, + ) + const passed = read(initializationSegment(VIDEO, untimed, later), fragment) + const alone = read(initializationSegment(VIDEO, untimed), fragment) + + expect(passed.handed).toEqual([ + { + tracks: { + audio: { + ...AUDIO_TRACK, + id: 3, + }, + video: VIDEO_TRACK, + }, + }, + besideKeyframe, + handedSample('audio', Buffer.from([0xFC, 2]), { + compositionOffset: 0, + decodeTime: 48000n, + duration: 960, + sync: true, + }), + 'end', + ]) + expect(alone.handed).toEqual([ + { + tracks: { video: VIDEO_TRACK }, + }, + besideKeyframe, + 'end', + ]) + }) + + it('fails the stream once in the reader\'s sentence for a sound sample a fragment places outside its mdat, past its end or inside its header, handing ' + + 'on no sample of that fragment', () => { + const keyframeOctets = tierFrameData(HEVC[0].slice(3)).length + + // A sound sample placed one octet past the mdat's end, and one placed from the last octet of its header. + for (const moved of [1, -keyframeOctets - 1]) { + const fragment = Buffer.from(pictureBeside({ + decodeTime: 0n, + samples: [ + sound(1), + ], + trackId: 2, + })) + const [moof] = walkBoxes(fragment).boxes + const [, soundRun] = walkBoxes(fragment, moof.payload, moof.end).boxes.filter(({ type }) => type === 'traf') + const trun = walkBoxes(fragment, soundRun.payload, soundRun.end).boxes.find(({ type }) => type === 'trun')! + + // The sound run's data offset, after its version, flags and sample count, moved by the octets given. + fragment.writeInt32BE(fragment.readInt32BE(trun.payload + 8) + moved, trun.payload + 8) + + const { handed, reader } = read(INITIALIZATION, fragment) + + reader.write(pictureBeside()) + + expect(handed).toEqual([ + { + tracks: { audio: AUDIO_TRACK, video: VIDEO_TRACK }, + }, + { fail: 'The stream holds a sample outside its fragment\'s mdat box.' }, + ]) + } + }) + + it('continues a sound run with no decode time of its own from where its track\'s run ended in the fragment before it', () => { + const { handed, samples } = read( + INITIALIZATION, + pictureBeside({ + decodeTime: 48000n, + samples: [ + sound(1), + sound(2), + ], + trackId: 2, + }), + sampleFragment( + { + decodeTime: 6000n, + samples: [ + picture(HEVC[1]), + ], + trackId: 1, + }, + { + samples: [ + sound(3), + ], + trackId: 2, + }, + ), + ) + + expect(samples.filter(({ track }) => track.medium === 'audio').map(({ data, decodeTime }) => [data[1], decodeTime])).toEqual([ + [1, 48000n], + [2, 48960n], + [3, 49920n], + ]) + expect(handed.filter(entry => (typeof entry === 'object') && ('fail' in entry))).toEqual([]) + }) + + it('fails the stream once in the reader\'s sentence, handing on no sample of the fragment, for a picture or a sound repeating a decode time inside a ' + + 'fragment or across two, or stepping back, and takes a lower decode time after an initialization segment and after a discontinuity', () => { + // A fragment of one medium's samples from a decode time, each stating the duration given: a duration of 0 times the next sample at its own. + const run = (medium: StreamTierMedium, decodeTime: bigint, ...durations: number[]): Buffer => sampleFragment({ + decodeTime, + samples: durations.map(duration => ({ + ...(medium === 'video' + ? picture(HEVC[1]) + : sound(1)), + duration, + })), + trackId: medium === 'video' + ? 1 + : 2, + }) + const failures = (handed: Handed[]): Handed[] => handed.filter(entry => (typeof entry === 'object') && ('fail' in entry)) + + for (const medium of ['video', 'audio'] as const) { + // Each refused stream, after its initialization segment, with the samples handed on before the fragment that fails it: a sample stating 0 inside + // a fragment, a fragment repeating the last decode time before it, and one stepping back before it. + const refused: [Buffer[], number][] = [ + [ + [ + run(medium, 0n, 0, 10), + ], + 0, + ], + [ + [ + run(medium, 0n, 10, 10), + run(medium, 10n, 10), + ], + 2, + ], + [ + [ + run(medium, 0n, 10, 10), + run(medium, 5n, 10), + ], + 2, + ], + ] + + for (const [chunks, before] of refused) { + const { handed, reader, samples } = read(INITIALIZATION, ...chunks) + + reader.write(run(medium, 100n, 10)) + + expect([ + failures(handed), + samples.length, + ]).toEqual([ + [ + { fail: `The stream's ${medium} track's decode times do not rise: a sample is timed at or before the one before it.` }, + ], + before, + ]) + } + + // A lower decode time opens a new run after an initialization segment and after a discontinuity. + const renewed = read(INITIALIZATION, run(medium, 0n, 10, 10), INITIALIZATION, run(medium, 5n, 10)) + const marked = read(INITIALIZATION, run(medium, 0n, 10, 10)) + + marked.reader.discontinuity() + marked.reader.write(run(medium, 5n, 10)) + + for (const { handed, samples } of [renewed, marked]) { + expect([ + failures(handed), + samples.map(({ decodeTime }) => decodeTime), + ]).toEqual([ + [], + [0n, 10n, 5n], + ]) + } + } + }) + + it('carries a track\'s run on across the wrap of a version 0 tfdt\'s 32-bit decode time, and fails the stream for a smaller version 0 fall and for any ' + + 'version 1 step back', () => { + // The 32-bit counter's range, and a fragment of one picture from a decode time in a tfdt of the version given. + const range = 2n ** 32n + const at = (decodeTime: bigint, version: 0 | 1): Buffer => sampleFragment({ + decodeTime, + samples: [ + picture(HEVC[1]), + ], + trackId: 1, + version, + }) + const failures = (handed: Handed[]): Handed[] => handed.filter(entry => (typeof entry === 'object') && ('fail' in entry)) + const wrapped = read(INITIALIZATION, at(range - 12000n, 0), at(range - 6000n, 0), at(0n, 0), at(6000n, 0)) + + expect(failures(wrapped.handed)).toEqual([]) + expect(wrapped.samples.map(({ decodeTime }) => decodeTime)).toEqual([ + range - 12000n, + range - 6000n, + range, + range + 6000n, + ]) + + // A version 0 fall from the counter's upper half to its lower by less than half its range, one inside its lower half, and a version 1 fall of more. + for (const chunks of [ + [ + at(range / 4n * 3n, 0), + at(range / 4n + 6000n, 0), + ], + [ + at(90000n, 0), + at(60000n, 0), + ], + [ + at(range - 6000n, 1), + at(0n, 1), + ], + ]) { + const { handed, samples } = read(INITIALIZATION, ...chunks) + + expect([ + failures(handed), + samples.length, + ]).toEqual([ + [ + { fail: 'The stream\'s video track\'s decode times do not rise: a sample is timed at or before the one before it.' }, + ], + 1, + ]) + } + }) + + it('tells no end for a fragment a discontinuity cuts inside its mdat, and tells the next fragment\'s end', () => { + const fragment = sampleFragment( + { + decodeTime: 0n, + samples: [ + picture(HEVC[0].slice(3), true), + picture(HEVC[1]), + ], + trackId: 1, + }, + { + decodeTime: 0n, + samples: [ + sound(1), + ], + trackId: 2, + }, + ) + const [moof, mdat] = walkBoxes(fragment).boxes.map(({ end, start }) => fragment.subarray(start, end)) + const { handed, reader } = read(INITIALIZATION, moof, mdat.subarray(0, 8 + tierFrameData(HEVC[0].slice(3)).length)) + + reader.discontinuity() + reader.write(sampleFragment( + { + decodeTime: 90000n, + samples: [ + picture(HEVC[2]), + ], + trackId: 1, + }, + { + decodeTime: 48000n, + samples: [ + sound(2), + ], + trackId: 2, + }, + )) + + expect(handed).toEqual([ + { + tracks: { audio: AUDIO_TRACK, video: VIDEO_TRACK }, + }, + besideKeyframe, + handedSample('video', tierFrameData(HEVC[2]), { + compositionOffset: 0, + decodeTime: 90000n, + duration: 6000, + sync: false, + }), + handedSample('audio', Buffer.from([0xFC, 2]), { + compositionOffset: 0, + decodeTime: 48000n, + duration: 960, + sync: true, + }), + 'end', + ]) + }) +}) + +describe('the live path\'s frames', () => { + it('writes the frames an initialization segment\'s fragments hold, with their times and keyframe flags, a keyframe\'s parameter sets first, and after its ' + + 'delimiter when it opens with one', () => { + const hevc = readFrames( + 'video', + INITIALIZATION, + videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1]), picture(HEVC[2])), + videoFragment(18000n, picture(HEVC[3].slice(3), true)), + videoFragment(24000n, picture([ + HEVC_DELIMITER, + ...HEVC[3].slice(3), + ], true)), + ) + + expect(hevc.reasons).toEqual([]) + expect(hevc.frames).toEqual([ + frame(HEVC[0], 0, true), + frame(HEVC[1], 66666), + frame(HEVC[2], 133333), + frame([ + ...HEVC_SETS, + ...HEVC[3].slice(3), + ], 200000, true), + frame([ + HEVC_DELIMITER, + ...HEVC_SETS, + ...HEVC[3].slice(3), + ], 266666, true), + ]) + }) + + it('writes the same frames from the same bytes written one octet at a time, and cut at every offset of one fragment', () => { + const fragments = [ + videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1])), + // A box of a 64-bit size between fragments, which the reader passes over. + largeBox('free', Buffer.alloc(5)), + videoFragment(12000n, picture(HEVC[2]), picture([ + HEVC_DELIMITER, + ...HEVC[3].slice(3), + ], true)), + ] + const bytes = Buffer.concat([INITIALIZATION, ...fragments]) + const whole = readFrames('video', INITIALIZATION, ...fragments).frames + const octets = readFrames('video', ...Array.from(bytes, octet => Buffer.from([octet]))) + + expect(whole).toHaveLength(4) + expect(octets.reasons).toEqual([]) + expect(octets.frames).toEqual(whole) + + for (let cut = 1; cut < fragments[0].length; cut++) { + const { frames, reasons } = readFrames('video', INITIALIZATION, fragments[0].subarray(0, cut), fragments[0].subarray(cut), fragments[1], fragments[2]) + + expect(reasons).toEqual([]) + expect(frames).toEqual(whole) + } + }, 30000) + + it('writes a fragment\'s three video samples beside its audio run to a video reader, and its Opus samples alone to an audio reader', () => { + const opus = [ + Buffer.from('fc0102', 'hex'), + Buffer.from('fc03', 'hex'), + Buffer.from('fc040506', 'hex'), + ] + const fragment = sampleFragment( + { + decodeTime: 48000n, + samples: opus.map(data => ({ data, duration: 960 })), + trackId: 2, + }, + { + decodeTime: 0n, + samples: [ + picture(HEVC[0].slice(3), true), + picture(HEVC[1]), + picture(HEVC[2]), + ], + trackId: 1, + }, + ) + + expect(readFrames('video', INITIALIZATION, fragment).frames).toEqual([ + frame(HEVC[0], 0, true), + frame(HEVC[1], 66666), + frame(HEVC[2], 133333), + ]) + expect(readFrames('audio', INITIALIZATION, fragment).frames).toEqual([ + { data: opus[0], time: 1000000 }, + { data: opus[1], time: 1020000 }, + { data: opus[2], time: 1040000 }, + ]) + }) + + it('hands each medium the frames of its own track from one stream of an HEVC track and an Opus track', () => { + const opus = Buffer.from('fc0102', 'hex') + const bytes = Buffer.concat([ + INITIALIZATION, + sampleFragment( + { + decodeTime: 0n, + samples: [ + picture(HEVC[0].slice(3), true), + ], + trackId: 1, + }, + { + decodeTime: 0n, + samples: [ + { data: opus, duration: 960 }, + ], + trackId: 2, + }, + ), + ]) + + expect(readFrames('audio', bytes).frames).toEqual([ + { data: opus, time: 0 }, + ]) + expect(readFrames('video', bytes).frames).toEqual([ + frame(HEVC[0], 0, true), + ]) + }) + + it('writes an audio reader the Opus track\'s samples alone from an initialization segment carrying an mp4a track ahead of its Opus track', () => { + const opus = [ + Buffer.from('fc0102', 'hex'), + Buffer.from('fc03', 'hex'), + ] + const initialization = initializationSegment( + { + handler: 'vide', + id: 1, + sampleEntry: visualSampleEntry('hvc1', 64, 36, hvcC([])), + timescale: 90000, + }, + { + handler: 'soun', + id: 2, + sampleEntry: mp4aSampleEntry(2), + timescale: 16000, + }, + { + handler: 'soun', + id: 3, + sampleEntry: opusSampleEntry(), + timescale: 48000, + }, + ) + const fragment = sampleFragment( + { + decodeTime: 0n, + samples: [ + { + data: Buffer.from('2110', 'hex'), + duration: 1024, + }, + ], + trackId: 2, + }, + { + decodeTime: 48000n, + samples: opus.map(data => ({ data, duration: 960 })), + trackId: 3, + }, + ) + const { frames, reasons } = readFrames('audio', initialization, fragment) + + expect(reasons).toEqual([]) + expect(frames).toEqual([ + { data: opus[0], time: 1000000 }, + { data: opus[1], time: 1020000 }, + ]) + }) + + it('takes parameter sets of exactly the octets the reader puts in a keyframe and fails the stream for one octet more, and for a set shorter than HEVC\'s NAL ' + + 'unit header, each at the initialization segment', () => { + // An SEI of exactly a NAL unit header's two octets, which is taken. + const header = Buffer.from('4e01', 'hex') + // An initialization segment whose parameter sets take the octets given as a keyframe carries them, each behind its four-octet length: the stream's own + // sets, the SEI above and a second SEI of the length that makes up the rest. + const holding = (octets: number): Buffer => { + const held = [ + ...HEVC_SETS, + header, + ].reduce((total, unit) => total + 4 + unit.length, 0) + const filler = Buffer.concat([ + header, + Buffer.alloc(octets - held - 4 - header.length), + ]) + + return initialization(visualSampleEntry('hvc1', 64, 36, hvcC([ + ...HEVC_SETS.map((unit, index) => ({ + type: 32 + index, + units: [unit], + })), + { + type: 39, + units: [header, filler], + }, + ]))) + } + const largest = readFrames('video', holding(16384), videoFragment(0n, picture(HEVC[0].slice(3), true))) + const larger = readFrames('video', holding(16385)) + const short = readFrames('video', initialization(visualSampleEntry('hvc1', 64, 36, hvcC([ + { + type: 32, + units: [ + Buffer.from('40', 'hex'), + ], + }, + ])))) + + expect(largest.reasons).toEqual([]) + expect(largest.frames.map(({ data }) => data.length)).toEqual([16384 + tierFrameData(HEVC[0].slice(3)).length]) + expect(larger.reasons).toEqual(['An MP4 hvcC box holds parameter sets that take more than the 16384 octets its reader puts in a keyframe.']) + expect(short.reasons).toEqual(['The stream\'s video track holds a parameter set shorter than the 2 octets of HEVC\'s NAL unit header.']) + }) + + it('opens a new run at the first frame after a second initialization segment, its parameter sets replacing the first\'s, and drops a fragment the ' + + 'segment cut off from its media or a later moof replaced', () => { + // A second initialization segment of an hev1 entry, whose synthetic parameter sets the first segment does not carry. + const otherSets = [ + Buffer.from('40010c02ff', 'hex'), + Buffer.from('42010102ff', 'hex'), + Buffer.from('440102ff', 'hex'), + ] + const secondInitialization = initialization(visualSampleEntry('hev1', 64, 36, hvcC(otherSets.map((unit, index) => ({ + type: 32 + index, + units: [unit], + }))))) + const second = videoFragment(0n, picture(HEVC[3].slice(3), true), picture(HEVC[1])) + const [moof, mdat] = walkBoxes(second).boxes.map(({ end, start }) => second.subarray(start, end)) + // A moof of one sample, which the next fragment's moof replaces before any mdat arrives. + const stale = videoFragment(12000n, picture(HEVC[2])) + // The fragment that replaces the stale moof, one fragment after the second segment's own, which means its decode times rise past that fragment's. + const later = videoFragment(12000n, picture(HEVC[3].slice(3), true), picture(HEVC[1])) + const { frames, reasons } = readFrames( + 'video', + INITIALIZATION, + videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1])), + moof, + secondInitialization, + mdat, + second, + stale.subarray(0, walkBoxes(stale).boxes[0].end), + later, + ) + const keyframe = [ + ...otherSets, + ...HEVC[3].slice(3), + ] + + expect(reasons).toEqual([]) + expect(frames).toEqual([ + frame(HEVC[0], 0, true), + frame(HEVC[1], 66666), + frame(keyframe, 0, true), + frame(HEVC[1], 66666), + frame(keyframe, 133333, true), + frame(HEVC[1], 200000), + ]) + }) + + it('drops the box being read and a fragment waiting for its media at a discontinuity, keeps the track, and opens a new run at the next whole fragment\'s first frame', + () => { + const first = videoFragment(0n, picture(HEVC[0].slice(3), true)) + const cut = videoFragment(6000n, picture(HEVC[1])) + const next = videoFragment(90000n, picture(HEVC[2]), picture(HEVC[3].slice(3), true)) + const [moof, mdat] = walkBoxes(cut).boxes.map(({ end, start }) => cut.subarray(start, end)) + const { frames, reader, reasons } = readFrames('video', INITIALIZATION, first, cut.subarray(0, 20)) + + reader.discontinuity() + reader.write(next) + reader.write(moof) + reader.discontinuity() + reader.write(mdat) + reader.write(next) + + expect(reasons).toEqual([]) + expect(frames).toEqual([ + frame(HEVC[0], 0, true), + frame(HEVC[2], 1000000), + frame([ + ...HEVC_SETS, + ...HEVC[3].slice(3), + ], 1066666, true), + frame(HEVC[2], 1000000), + frame([ + ...HEVC_SETS, + ...HEVC[3].slice(3), + ], 1066666, true), + ]) + }) + + it('hands each frame of a fragment written its moof, its mdat\'s header and then each sample in a write of its own on at the write that completes it, in ' + + 'order', () => { + const fragment = videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1]), picture(HEVC[2])) + const [moof, mdat] = walkBoxes(fragment).boxes.map(({ end, start }) => fragment.subarray(start, end)) + const whole = readFrames('video', INITIALIZATION, fragment).frames + const { frames, reader, reasons } = readFrames('video', INITIALIZATION, moof, mdat.subarray(0, 8)) + const handed = [frames.length] + let at = 8 + + for (const units of [ + HEVC[0].slice(3), + HEVC[1], + HEVC[2], + ]) { + const size = tierFrameData(units).length + + reader.write(mdat.subarray(at, at + size)) + at += size + handed.push(frames.length) + } + + expect(reasons).toEqual([]) + expect(handed).toEqual([0, 1, 2, 3]) + expect(whole).toHaveLength(3) + expect(frames).toEqual(whole) + }) + + it('hands a frame cut across two writes at the second, its bytes whole, and a frame wholly inside one write at that write as a view of it', () => { + const fragment = videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1])) + const [moof, mdat] = walkBoxes(fragment).boxes.map(({ end, start }) => fragment.subarray(start, end)) + const whole = readFrames('video', INITIALIZATION, fragment).frames + const kept: TierFrame[] = [] + const { reader } = frameReader('video', frame => kept.push(frame)) + // The mdat's header and half the first sample in one write, and the first sample's rest and the whole second sample in the next. + const cut = 8 + (tierFrameData(HEVC[0].slice(3)).length >> 1) + const rest = mdat.subarray(cut) + + reader.write(INITIALIZATION) + reader.write(moof) + reader.write(mdat.subarray(0, cut)) + + expect(kept).toEqual([]) + + reader.write(rest) + + const second = kept[1].data + + expect(kept).toEqual(whole) + expect(second.buffer === rest.buffer && (second.byteOffset >= rest.byteOffset) && (second.byteOffset + second.length <= rest.byteOffset + rest.length)) + .toBe(true) + }) + + it('hands each frame that is no keyframe, its sample written whole in a write of its own, as a view of that write\'s chunk from its first octet', () => { + const fragment = videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1]), picture(HEVC[2])) + const [moof, mdat] = walkBoxes(fragment).boxes.map(({ end, start }) => fragment.subarray(start, end)) + const kept: TierFrame[] = [] + const chunks: Buffer[] = [] + const { reader } = frameReader('video', frame => kept.push(frame)) + let at = 8 + + reader.write(INITIALIZATION) + reader.write(moof) + reader.write(mdat.subarray(0, at)) + + for (const units of [ + HEVC[0].slice(3), + HEVC[1], + HEVC[2], + ]) { + const chunk = mdat.subarray(at, at + tierFrameData(units).length) + + reader.write(chunk) + chunks.push(chunk) + at += chunk.length + } + + expect(kept.map(({ keyframe }) => keyframe)).toEqual([true, false, false]) + expect([1, 2].map(index => [kept[index].data.buffer === chunks[index].buffer, kept[index].data.byteOffset, kept[index].data.length])) + .toEqual([1, 2].map(index => [true, chunks[index].byteOffset, chunks[index].length])) + }) + + it('fails the stream at the mdat\'s header for a fragment whose second sample lies past the mdat\'s end, written a frame at a time, handing nothing', () => { + const fragment = Buffer.from(videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1]))) + const [moof, mdat] = walkBoxes(fragment).boxes.map(({ end, start }) => fragment.subarray(start, end)) + const first = tierFrameData(HEVC[0].slice(3)).length + + // The mdat's header announces an extent one octet short of the second sample's end. + mdat.writeUInt32BE(mdat.length - 1, 0) + + const { frames, reader, reasons } = readFrames('video', INITIALIZATION, moof, mdat.subarray(0, 8)) + + expect(reasons).toEqual(['The stream holds a sample outside its fragment\'s mdat box.']) + + reader.write(mdat.subarray(8, 8 + first)) + reader.write(mdat.subarray(8 + first)) + + expect(frames).toEqual([]) + expect(reasons).toHaveLength(1) + }) + + it('keeps the frames a fragment handed on before a discontinuity inside its mdat, drops the rest, and reads the next fragment from its own first octet', + () => { + const fragment = videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1]), picture(HEVC[2])) + const [moof, mdat] = walkBoxes(fragment).boxes.map(({ end, start }) => fragment.subarray(start, end)) + const { frames, reader, reasons } = readFrames('video', INITIALIZATION, moof, mdat.subarray(0, 8 + tierFrameData(HEVC[0].slice(3)).length)) + + expect(frames).toEqual([ + frame(HEVC[0], 0, true), + ]) + + reader.discontinuity() + reader.write(videoFragment(90000n, picture(HEVC[2]))) + + expect(reasons).toEqual([]) + expect(frames).toEqual([ + frame(HEVC[0], 0, true), + frame(HEVC[2], 1000000), + ]) + }) + + it('rethrows a range error the consumer\'s own call throws from the reader\'s write, failing nothing', () => { + const { reader, reasons } = frameReader('video', () => { + throw new RangeError('The consumer refused the frame.') + }) + + reader.write(INITIALIZATION) + + expect(() => reader.write(videoFragment(0n, picture(HEVC[1])))).toThrow(new RangeError('The consumer refused the frame.')) + expect(reasons).toEqual([]) + }) + + it('hands a consumer that throws at a step\'s second frame the first frame and the second once each, and the step\'s rest at the next write', () => { + const first = videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1]), picture(HEVC[2])) + const second = videoFragment(18000n, picture(HEVC[3].slice(3), true)) + const [moof, mdat] = walkBoxes(second).boxes.map(({ end, start }) => second.subarray(start, end)) + const whole = readFrames('video', INITIALIZATION, first, second).frames + const frames: TierFrame[] = [] + const { reader, reasons } = frameReader('video', (frame) => { + frames.push(kept(frame)) + + if (frames.length === 2) { + throw new Error('The consumer refused the frame.') + } + }) + + reader.write(INITIALIZATION) + + // The whole fragment is one write, whose media completes every frame of the fragment in one step. + expect(() => reader.write(first)).toThrow(new Error('The consumer refused the frame.')) + expect(frames).toEqual(whole.slice(0, 2)) + + // The next write, a moof that completes no frame of its own, hands the step's third frame alone. + reader.write(moof) + + expect(frames).toEqual(whole.slice(0, 3)) + + reader.write(mdat) + + expect(whole).toHaveLength(4) + expect(frames).toEqual(whole) + expect(reasons).toEqual([]) + }) + + it('reads the whole chunk when a consumer throws on its first frame, the throw reaching the caller after, and hands every later frame in order at the ' + + 'next write', () => { + const first = videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1]), picture(HEVC[2])) + const second = videoFragment(18000n, picture(HEVC[3].slice(3), true)) + const third = videoFragment(36000n, picture(HEVC[1])) + const whole = readFrames('video', INITIALIZATION, first, second, third).frames + const frames: TierFrame[] = [] + const { reader, reasons } = frameReader('video', (frame) => { + frames.push(kept(frame)) + + if (frames.length === 1) { + throw new Error('The consumer refused the frame.') + } + }) + + reader.write(INITIALIZATION) + + // One chunk holds the first fragment and the second: the frame the consumer throws on is the first of the chunk's first step, and the second + // fragment is a later step. + expect(() => reader.write(Buffer.concat([first, second]))).toThrow(new Error('The consumer refused the frame.')) + expect(frames).toEqual(whole.slice(0, 1)) + + reader.write(third) + + expect(whole).toHaveLength(5) + expect(frames).toEqual(whole) + expect(reasons).toEqual([]) + }) + + it('reads a fragment whose runs count their data past a box between its moof and its mdat, and fails the stream for a sample past its mdat\'s end', () => { + const fragment = videoFragment(0n, picture(HEVC[0].slice(3), true), picture(HEVC[1])) + const [moof, mdat] = walkBoxes(fragment).boxes.map(({ end, start }) => Buffer.from(fragment.subarray(start, end))) + const between = box('free', Buffer.alloc(6)) + const traf = walkBoxes(moof, 8).boxes.find(({ type }) => type === 'traf')! + const trun = walkBoxes(moof, traf.payload, traf.end).boxes.find(({ type }) => type === 'trun')! + // A moof placing its one sample of 4 octets at a data offset from its first octet. + const placing = (dataOffset: number): Buffer => box('moof', box( + 'traf', + fullBox('tfhd', 0, 0x20000, uint32(1)), + fullBox('tfdt', 0, 0, uint32(0)), + fullBox('trun', 0, 0x301, uint32(1), int32(dataOffset), uint32(6000), uint32(4)), + )) + const media = placing(0).length + 8 + + // 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 moved = readFrames('video', INITIALIZATION, moof, between, mdat) + const last = readFrames('video', INITIALIZATION, placing(media), box('mdat', Buffer.alloc(4))) + const past = readFrames('video', INITIALIZATION, placing(media + 1), box('mdat', Buffer.alloc(4))) + + expect(moved.reasons).toEqual([]) + expect(moved.frames).toEqual([ + frame(HEVC[0], 0, true), + frame(HEVC[1], 66666), + ]) + expect(last.reasons).toEqual([]) + expect(last.frames).toHaveLength(1) + expect(past.reasons).toEqual(['The stream holds a sample outside its fragment\'s mdat box.']) + expect(past.frames).toEqual([]) + }) + + it('holds and reads through a box of the largest size the reader holds, and fails the stream for a box one octet larger', () => { + const largest = 16 * 1024 * 1024 + const header = (size: number): Buffer => Buffer.concat([ + uint32(size), + Buffer.from('mdat', 'latin1'), + ]) + // An mdat no moof describes, which the reader holds whole and passes over, before a fragment it reads. + const held = readFrames('video', INITIALIZATION, header(largest), Buffer.alloc(largest - 8), videoFragment(0n, picture(HEVC[0].slice(3), true))) + const larger = readFrames('video', INITIALIZATION, header(largest + 1)) + + expect(held.reasons).toEqual([]) + expect(held.frames).toEqual([ + frame(HEVC[0], 0, true), + ]) + expect(larger.reasons).toEqual(['The stream\'s mdat box of 16777217 octets is larger than the 16777216 octets the reader holds.']) + }) + + it('writes every frame of a fragment holding as many samples of its track as the reader takes from one fragment', () => { + const { frames, reasons } = readFrames('audio', INITIALIZATION, opusFragment(4096)) + + expect(reasons).toEqual([]) + expect(frames).toEqual(Array.from({ length: 4096 }, (_, index) => ({ + data: Buffer.from([0xFC]), + time: index * 20000, + }))) + }) + + // A run placing its one sample of 4 octets at the moof's first octet, outside the mdat after it. + const misplacedRun = fullBox('trun', 0, 0x301, uint32(1), int32(0), uint32(6000), uint32(4)) + const misplaced = box('traf', fullBox('tfhd', 0, 0x20000, uint32(1)), fullBox('tfdt', 0, 0, uint32(0)), misplacedRun) + // A moof of track 2's runs, each announcing more samples of no octets than the reader takes from one fragment, all at the data offset given, the first + // octet of the media past the header of the mdat after it. + const emptyRuns = (dataOffset: number): Buffer => box('moof', box( + 'traf', + fullBox('tfhd', 0, 0x20018, uint32(2), uint32(960), uint32(0)), + fullBox('tfdt', 0, 0, uint32(0)), + ...Array.from({ length: 4 }, () => fullBox('trun', 0, 0x1, uint32(100000), int32(dataOffset))), + )) + const limitReason = 'An MP4 fragment holds more samples of a track than the 4096 its reader takes from one fragment.' + + it.each([ + [ + 'a fragment before any initialization segment', + 'video', + [ + videoFragment(0n, picture(HEVC[1])), + ], + 'The stream holds a fragment before any initialization segment.', + ], + [ + 'a video track whose sample description holds no entry', + 'video', + [ + initialization(Buffer.alloc(0)), + ], + 'The stream\'s video track holds no sample entry.', + ], + [ + 'a video sample entry of another type', + 'video', + [ + initialization(visualSampleEntry('mp4v', 64, 36)), + ], + 'The stream\'s video track\'s sample entry is mp4v, which is neither hev1 nor hvc1.', + ], + [ + 'an avc1 video sample entry', + 'video', + [ + initialization(visualSampleEntry('avc1', 64, 36, avcC([AVC_SEQUENCE], [AVC_PICTURE]))), + ], + 'The stream\'s video track\'s sample entry is avc1, which is neither hev1 nor hvc1.', + ], + [ + 'an avc3 video sample entry', + 'video', + [ + initialization(visualSampleEntry('avc3', 64, 36, avcC([AVC_SEQUENCE], [AVC_PICTURE]))), + ], + 'The stream\'s video track\'s sample entry is avc3, which is neither hev1 nor hvc1.', + ], + [ + 'NAL unit lengths of one octet', + 'video', + [ + initialization(visualSampleEntry('hev1', 64, 36, hvcC([], 1))), + ], + 'The stream\'s video track writes each NAL unit\'s length in 1 octet, and the library takes a length of 4 octets.', + ], + [ + 'NAL unit lengths of two octets', + 'video', + [ + initialization(visualSampleEntry('hev1', 64, 36, hvcC([], 2))), + ], + 'The stream\'s video track writes each NAL unit\'s length in 2 octets, and the library takes a length of 4 octets.', + ], + [ + 'a malformed box', + 'video', + [ + INITIALIZATION, + Buffer.from('0000000466726565', 'hex'), + ], + 'The stream holds a malformed box, whose size is under its header\'s.', + ], + [ + 'a box the box reader refuses', + 'video', + [ + box('moov', Buffer.from('0000004074726166', 'hex')), + ], + 'An MP4 moov box holds a malformed box.', + ], + [ + 'a fragment placing its data by an absolute file offset', + 'video', + [ + INITIALIZATION, + box('moof', box('traf', fullBox('tfhd', 0, 0x1, uint32(1), uint64(4096n)), fullBox('trun', 0, 0x201, uint32(1), int32(0), uint32(4)))), + box('mdat', Buffer.alloc(4)), + ], + 'An MP4 fragment places its data by an absolute file offset, which a stream cannot follow, and ffmpeg writes the layout a stream needs under its ' + + 'default_base_moof muxer flag.', + ], + [ + 'a box that runs to the end of its file', + 'video', + [ + INITIALIZATION, + openBox('mdat', Buffer.alloc(4)), + ], + 'The stream holds a box that runs to the end of its file, and a stream has no end for it to run to.', + ], + [ + 'a box larger than the reader holds', + 'video', + [ + INITIALIZATION, + uint32(16 * 1024 * 1024 + 1), + Buffer.from('mdat', 'latin1'), + ], + 'The stream\'s mdat box of 16777217 octets is larger than the 16777216 octets the reader holds.', + ], + [ + 'a sample outside its mdat', + 'video', + [ + INITIALIZATION, + box('moof', misplaced), + box('mdat', Buffer.alloc(4)), + ], + 'The stream holds a sample outside its fragment\'s mdat box.', + ], + [ + 'a fragment holding one sample of its track more than the reader takes from one fragment', + 'audio', + [ + INITIALIZATION, + opusFragment(4097), + ], + limitReason, + ], + [ + 'a fragment of runs announcing samples of no octets past what the reader takes from one fragment', + 'audio', + [ + INITIALIZATION, + emptyRuns(emptyRuns(0).length + 8), + box('mdat'), + ], + limitReason, + ], + ] as [string, StreamTierMedium, Buffer[], string][])('fails the stream once for %s, throwing nothing and ignoring every later chunk', (_name, medium, chunks, + reason) => { + const { frames, reader, reasons } = readFrames(medium, ...chunks) + + expect(() => { + reader.write(INITIALIZATION) + reader.write(videoFragment(0n, picture(HEVC[0].slice(3), true))) + reader.discontinuity() + reader.write(videoFragment(0n, picture(HEVC[0].slice(3), true))) + }).not.toThrow() + expect(reasons).toEqual([reason]) + expect(frames).toEqual([]) + }) + + it('times frames by decode times of both tfdt versions and their composition offsets, a run with no tfdt continuing from the last, and from zero after a ' + + 'discontinuity', () => { + const offsetSamples = [ + { + ...picture(HEVC[0].slice(3), true), + compositionOffset: 6000, + }, + { + ...picture(HEVC[1]), + compositionOffset: 0, + }, + ] + const wide = 2n ** 32n + 9000n + const { frames, reader, reasons } = readFrames( + 'video', + INITIALIZATION, + sampleFragment({ + decodeTime: 90000n, + samples: offsetSamples, + trackId: 1, + version: 0, + }), + sampleFragment({ + decodeTime: wide, + samples: [ + picture(HEVC[2]), + ], + trackId: 1, + version: 1, + }), + videoFragment(undefined, picture(HEVC[1])), + ) + + reader.discontinuity() + reader.write(videoFragment(undefined, picture(HEVC[2]), picture(HEVC[1]))) + + expect(reasons).toEqual([]) + expect(frames.map(({ time }) => ({ time }))).toEqual([ + { time: 1066666 }, + { time: 1066666 }, + { + time: Number(wide * 1000000n / 90000n), + }, + { + time: Number((wide + 6000n) * 1000000n / 90000n), + }, + { time: 0 }, + { time: 66666 }, + ]) + }) +}) diff --git a/src/lib/camera/mp4/Mp4StreamReader.ts b/src/lib/camera/mp4/Mp4StreamReader.ts new file mode 100644 index 000000000..a26cbdecf --- /dev/null +++ b/src/lib/camera/mp4/Mp4StreamReader.ts @@ -0,0 +1,838 @@ +import type { TierFrame } from '../StreamingOptions.js' +import type { Mp4Box, Mp4BoxHeader, Mp4Sample, Mp4SampleDefaults, Mp4TrackBox } from './mp4Boxes.js' + +import { Buffer } from 'node:buffer' + +import { counted } from '../../util/counted.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, + readSampleDefaults, + readTrackBoxEntry, + readTrackBoxEntryBytes, + readTrackBoxes, + readTrackBoxParameterSets, + readTrackSamples, + readVideoTrackBox, +} from './mp4Boxes.js' + +// The largest box the reader holds, the most samples of each track it takes from one fragment and the most octets of parameter sets a video track may +// carry, which together bound what a corrupt stream can make it keep: a box's octets, a sample for each sample of a fragment's tracks, and the parameter +// sets each keyframe's frame copies. +const LARGEST_BOX = 16 * 1024 * 1024 +const LARGEST_FRAGMENT_SAMPLES = 4096 +const LARGEST_PARAMETER_SETS = 16 * 1024 + +// The microseconds of a second, which a frame's time counts in. +const MICROSECONDS = 1000000n + +// The range of a version 0 tfdt's 32-bit decode time, which wraps to zero past its last value, and the fall past half of it that reads as that wrap. +const COUNTER_RANGE = 0x100000000n +const COUNTER_FALL = COUNTER_RANGE / 2n + +// HEVC's access unit delimiter's NAL unit type. +const HEVC_DELIMITER = 35 + +/** + * What an initialization segment says of a track the stream reader reads. + */ +interface Mp4StreamTrackFields { + /** + * The track's identifier, which its fragments' runs name. + */ + readonly id: number + /** + * The track's timescale in units per second, never 0. + */ + readonly timescale: number + /** + * The track's first sample entry whole, its header, its fields and the boxes it holds, as a view of the initialization segment. + */ + readonly sampleEntry: Buffer +} + +/** + * The stream's picture: its first video track, HEVC under an `hev1` or `hvc1` sample entry whose samples write each NAL unit's length in four octets. + */ +export interface Mp4StreamVideoTrack extends Mp4StreamTrackFields { + readonly medium: 'video' + /** + * The picture's width in pixels, from the sample entry. + */ + readonly width: number + /** + * The picture's height in pixels, from the sample entry. + */ + readonly height: number + /** + * The parameter sets of the entry's `hvcC`, in the record's order, each behind its four-octet length as a keyframe carries them, and no octets when the + * record holds none. + */ + readonly parameterSets: Buffer +} + +/** + * The stream's sound: its first track whose sample entry is `Opus`. + */ +export interface Mp4StreamAudioTrack extends Mp4StreamTrackFields { + readonly medium: 'audio' +} + +/** + * A track the stream reader reads, tagged by its medium. + */ +export type Mp4StreamTrack = Mp4StreamVideoTrack | Mp4StreamAudioTrack + +/** + * The tracks an initialization segment holds of those the stream reader reads, each absent when the segment holds none. + */ +export interface Mp4StreamTracks { + readonly video?: Mp4StreamVideoTrack + readonly audio?: Mp4StreamAudioTrack +} + +/** + * One sample of a track the stream reader reads, with its times as the stream states them in its track's timescale. + */ +export interface Mp4StreamSample { + /** + * The track the sample belongs to, as the initialization segment the sample follows describes it. + */ + readonly track: Mp4StreamTrack + /** + * The sample's octets: a view of the one chunk holding them all, or the reader's own copy when they span chunks. + */ + readonly data: Buffer + /** + * The sample's decode time. + */ + readonly decodeTime: bigint + /** + * The sample's duration, absent when the stream states none. + */ + readonly duration?: number + /** + * The time from the sample's decode time to its presentation. + */ + readonly compositionOffset: number + /** + * Whether the sample is a sync sample, one decoded with nothing before it. + */ + readonly sync: boolean +} + +/** + * What the stream reader hands what it reads to, each call in the stream's order, outside the reading. + */ +export interface Mp4StreamConsumer { + /** + * Takes the tracks an initialization segment holds, before any sample of the fragments after it. + * @param tracks - The tracks. + */ + tracks(tracks: Mp4StreamTracks): void + /** + * Takes one sample whose octets have arrived with those of every sample the stream places before it. + * @param sample - The sample. + */ + sample(sample: Mp4StreamSample): void + /** + * Marks the end of a fragment, once its `mdat` box is whole and each of its samples is handed on. + */ + fragmentEnd(): void + /** + * Takes the reason the stream failed, once, after which nothing more is handed on. + * @param reason - Why the stream failed. + */ + fail(reason: string): void +} + +/** + * What a stream reader reads of its stream beside its picture. + */ +export interface Mp4StreamReaderOptions { + /** + * Whether the reader reads the stream's sound, its first Opus track, `true` by default. A reader made with `false` reads that track as none: none of + * its samples is read, and a stream whose sound comes from another stream meets no fault of a track it never reads. + */ + readonly sound?: boolean +} + +// A track the reader reads, as the latest initialization segment describes it, with the decode time its next run with no tfdt continues from, absent when +// its last run ends at a sample with no duration, the decode time of the last sample it took in its run, which the next must rise past, a run opening at +// an initialization segment and at a discontinuity, and the range its version 0 decode times have wrapped past in that run. +interface ReaderTrack { + readonly description: Mp4StreamTrack + decodeTime?: bigint + last?: bigint + wrapped: bigint +} + +// The tracks the latest initialization segment gives the reader, picture first, and each track's sample defaults, which place its fragments' samples. +interface ReaderMovie { + readonly tracks: readonly ReaderTrack[] + 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. +interface PendingFragment { + data: Buffer + moof: Mp4Box + end: number +} + +// One track's samples a fragment places in its mdat, each checked to lie inside it, and the next to hand on. +interface ArrivingRun { + readonly track: ReaderTrack + readonly samples: Mp4Sample[] + 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. +interface ArrivingMedia { + readonly runs: readonly ArrivingRun[] + readonly base: number +} + +// What one step of the reading hands on, in the stream's order, once the step is done. +type ReaderEvent = { readonly kind: 'tracks', readonly tracks: Mp4StreamTracks } + | { readonly kind: 'sample', readonly sample: Mp4StreamSample } + | { readonly kind: 'end' } + +const FRAGMENT_END: ReaderEvent = { kind: 'end' } + +/** + * Reads an fMP4 stream, the fragmented MP4 an encoder or a camera's controller delivers, from its bytes cut anywhere, with nothing decoded: its picture, the + * first video track, and its sound, the first Opus track where the reader reads sound, read together in one pass. Each initialization segment's tracks are + * handed on as it is read, and each sample as its octets complete, in the order the stream's `mdat` places them across the tracks, each track's samples in + * its own order. No sample goes out ahead of one placed before it. A fragment's end is told once its `mdat` is whole. + * + * The bytes are the initialization segment first and then fragments in the `default_base_moof` layout, whose runs count their data from their own `moof`. + * A later initialization segment replaces everything read from the one before it, and each track's first sample after it, or after a discontinuity, opens + * a new run, inside which the track's decode times rise: a fragment holding a sample timed at or before the one before it in its track fails the stream + * before any of its samples is handed on. A version 0 `tfdt` holds its decode time in a 32-bit counter, which wraps to zero past its last + * 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. + */ +export class Mp4StreamReader { + private readonly consumer: Mp4StreamConsumer + // Whether the reader reads the stream's first Opus track, which a reader made to read no sound reads as none. + private readonly sound: boolean + // The octets of a box header spanning chunks, copied together to be read. + private readonly header = Buffer.alloc(LARGE_HEADER_SIZE) + // What one step of the reading completes, handed to the consumer once the step is done. + private readonly events: ReaderEvent[] = [] + // The chunks holding the box being read from its first octet, each beside the box's offset it starts at, the octets they hold, and the box's size, + // header length and type once its header is read. + private parts: Buffer[] = [] + private starts: number[] = [] + private held = 0 + private size = 0 + private headerLength = 0 + private type = '' + private movie?: ReaderMovie + private pending?: PendingFragment + private media?: ArrivingMedia + private failed = false + + /** + * Makes a reader handing what it reads to a consumer. + * @param consumer - The consumer. + * @param options - What the reader reads beside the picture, its sound by default. + * @param options.sound - Whether the reader reads the stream's first Opus track. + */ + constructor(consumer: Mp4StreamConsumer, { sound = true }: Mp4StreamReaderOptions = {}) { + this.consumer = consumer + this.sound = sound + } + + /** + * Reads the stream's next bytes, which may end anywhere in a box, and hands the consumer what the chunk completes, in the stream's order. What the reader + * cannot read fails the stream rather than throwing, and a chunk written after it failed is ignored. When the consumer throws, the reader hands it nothing + * more in that call, reads the chunk to its end, keeping what it reads in order, and then lets that first throw reach the caller; what was kept goes out + * first at the next call unless the stream fails before it, which drops it. Nothing is handed twice. + * @param chunk - The bytes, which the reader leaves unchanged and its caller never changes or reuses once written, since a sample's octets may be a + * view of them. + */ + write(chunk: Buffer): void { + if (this.failed) { + return + } + + let thrown = this.handOn() + let at = 0 + + while (!this.failed && (at < chunk.length)) { + try { + at = this.size === 0 + ? this.readHeader(chunk, at) + : this.readBox(chunk, at) + } catch (error) { + if (!(error instanceof RangeError)) { + throw error + } + + this.fail(error.message) + + break + } + + thrown ??= this.handOn() + } + + if (thrown) { + throw thrown.error + } + } + + /** + * 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. + */ + discontinuity(): void { + this.release() + this.pending = undefined + + for (const track of this.movie?.tracks ?? []) { + track.decodeTime = 0n + track.last = undefined + track.wrapped = 0n + } + } + + /** + * Fails the stream once with a reason: everything held and not yet handed on is dropped, the consumer's `fail` is called, and every later chunk is + * ignored. A consumer refuses a stream it cannot take this way, and the reader its own unreadable bytes. A no-op on repeat. + * @param reason - Why the stream failed. + */ + fail(reason: string): void { + if (this.failed) { + return + } + + this.failed = true + this.release() + this.pending = undefined + this.events.length = 0 + this.consumer.fail(reason) + } + + /* Hands the consumer what the reading completed, in order, outside the reading, which is why the consumer's own work is never taken for the stream's. The reader stops + * at the first call that throws, answering that throw. Each event leaves the list as it is handed on: the one the consumer threw on is never handed again + * and the events after it stay for the next call. + */ + private handOn(): { error: unknown } | undefined { + const { consumer, events } = this + + for (let event = events.shift(); event !== undefined; event = events.shift()) { + try { + switch (event.kind) { + case 'tracks': + consumer.tracks(event.tracks) + break + + case 'sample': + consumer.sample(event.sample) + break + + case 'end': + consumer.fragmentEnd() + break + } + } catch (error) { + return { error } + } + } + + return undefined + } + + // Reads a box's header, wholly in the chunk or spanning the chunks before it, and holds what is read of a header the chunk ends inside. An mdat's header + // starts the media of the moof waiting for it. + private readHeader(chunk: Buffer, at: number): number { + const header = this.held === 0 + ? readBoxHeader(chunk, at) + : this.spanningHeader(chunk, at) + + if (header === undefined) { + this.keep(chunk.subarray(at)) + + return chunk.length + } + + const { length, size, type } = header + + if (size === undefined) { + throw new RangeError('The stream holds a box that runs to the end of its file, and a stream has no end for it to run to.') + } + + if (size < length) { + throw new RangeError('The stream holds a malformed box, whose size is under its header\'s.') + } + + if (size > LARGEST_BOX) { + throw new RangeError(`The stream's ${type} box of ${size} octets is larger than the ${LARGEST_BOX} octets the reader holds.`) + } + + this.size = size + this.headerLength = length + this.type = type + + if (type === 'mdat') { + this.startMedia() + } + + return at + } + + // A header spanning chunks, read from its octets held so far, which never reach a large header's, and the chunk's first octets copied together. + private spanningHeader(chunk: Buffer, at: number): Mp4BoxHeader | undefined { + let copied = 0 + + for (const part of this.parts) { + copied += part.copy(this.header, copied) + } + + copied += chunk.copy(this.header, copied, at, at + LARGE_HEADER_SIZE - copied) + + return readBoxHeader(this.header, 0, copied) + } + + /* Reads the rest of the box whose header is read. A fragment's media is read as its octets arrive, each sample they complete handed on in turn, and its + * end told as its last octet arrives. Any other box is read whole, in place when the chunk holds it whole, else joined once from its chunks when its last + * arrives. + */ + private readBox(chunk: Buffer, at: number): number { + const end = Math.min(chunk.length, at + this.size - this.held) + const { headerLength, type } = this + + if (this.media !== undefined) { + this.keep(chunk.subarray(at, end)) + this.readArrived(this.media) + + // Every sample lies inside the mdat, which means each is handed on by the time its last octet arrives. + if (this.held === this.size) { + this.events.push(FRAGMENT_END) + this.release() + } + + return end + } + + if ((this.held === 0) && (end - at === this.size)) { + this.release() + this.readWhole(chunk.subarray(at, end), type, headerLength) + + return end + } + + this.keep(chunk.subarray(at, end)) + + if (this.held === this.size) { + const box = Buffer.concat(this.parts, this.size) + + this.release() + this.readWhole(box, type, headerLength) + } + + 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. + private readWhole(box: Buffer, type: string, headerLength: number): void { + switch (type) { + case 'moov': + this.readMovie(box, { + end: box.length, + payload: headerLength, + start: 0, + type, + }) + break + + case 'moof': + if (this.movie === undefined) { + throw new RangeError('The stream holds a fragment before any initialization segment.') + } + + // A moof arriving while another waits for its mdat replaces it. + this.pending = { + data: box, + end: box.length, + moof: { + end: box.length, + payload: headerLength, + start: 0, + type, + }, + } + 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. + if (this.pending !== undefined) { + this.pending.end += box.length + } + } + } + + /* Reads the tracks an initialization segment holds, which replace everything read from the segment before it. The moov's tracks are read once, and each + * track's entry from its own trak: a track sharing an earlier track's identifier reads as itself. The picture is the first video track, refused when it + * is no HEVC the reader can put in a keyframe, and the sound the first Opus track, which a reader made to read no sound reads as none, and no fragment's + * samples of it are read. A track of timescale 0 times nothing, which is why an Opus track of it reads as none, as the box reader reads a video track of it. + */ + private readMovie(data: Buffer, moov: Mp4Box): void { + const trackBoxes = readTrackBoxes(data, moov) + const videoBox = readVideoTrackBox(trackBoxes) + const video = videoBox === undefined + ? undefined + : videoOf(data, videoBox) + const audioBox = this.sound + ? trackBoxes.find(trackBox => (trackBox.track.timescale > 0) && (readTrackBoxEntry(data, trackBox)?.type === 'Opus')) + : undefined + const audio = audioBox === undefined + ? undefined + : audioOf(data, audioBox) + const defaults = readSampleDefaults(data, moov) + const tracks: { video?: Mp4StreamVideoTrack, audio?: Mp4StreamAudioTrack } = {} + const read: ReaderTrack[] = [] + + if (video !== undefined) { + tracks.video = video + read.push({ + decodeTime: 0n, + description: video, + wrapped: 0n, + }) + } + + if (audio !== undefined) { + tracks.audio = audio + read.push({ + decodeTime: 0n, + description: audio, + wrapped: 0n, + }) + } + + this.movie = { defaults, tracks: read } + this.pending = 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. + */ + private startMedia(): void { + const { headerLength, movie, pending } = this + + if ((pending === undefined) || (movie === undefined)) { + return + } + + this.pending = undefined + + const media = pending.end + headerLength + const dataEnd = pending.end + this.size + const read = movie.tracks.map(track => ({ + track, + ...readTrackSamples(pending.data, pending.moof, { + counter: value => carried(track, value), + decodeTime: track.decodeTime, + defaults: movie.defaults, + limit: LARGEST_FRAGMENT_SAMPLES, + trackId: track.description.id, + }), + })) + + if (read.some(({ samples }) => samples.some(({ offset, size }) => (offset < media) || (offset + size > dataEnd)))) { + throw new RangeError('The stream holds a sample outside its fragment\'s mdat box.') + } + + const unrisen = read.find(({ samples, track }) => !rises(samples, track.last)) + + if (unrisen !== undefined) { + throw new RangeError(`The stream's ${unrisen.track.description.medium} track's decode times do not rise: a sample is timed at or before the one before it.`) + } + + for (const { decodeTime, samples, track } of read) { + track.decodeTime = decodeTime + track.last = samples.at(-1)?.decodeTime ?? track.last + } + + this.media = { + base: pending.end, + runs: read.map(({ samples, track }) => ({ next: 0, samples, track })), + } + } + + /* 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 { + for (let run = nextRun(runs); run !== undefined; run = nextRun(runs)) { + const sample = run.samples[run.next] + const start = sample.offset - base + const end = start + sample.size + + if (end > this.held) { + return + } + + run.next++ + this.events.push({ + kind: 'sample', + sample: sampleOf(this.octets(start, end), sample, run.track), + }) + } + } + + // The octets of the box being read from one offset to another, all of which have arrived: a view of the one chunk holding them all, or joined once from + // the chunks they span. + private octets(start: number, end: number): Buffer { + const { parts, starts } = this + let first = 0 + + // The last part starting at or before the first octet, found by halving, since a box read an octet at a time holds a part for each. + for (let last = parts.length - 1; first < last;) { + const middle = (first + last + 1) >>> 1 + + if (starts[middle] <= start) { + first = middle + } else { + last = middle - 1 + } + } + + if (end <= starts[first] + parts[first].length) { + return parts[first].subarray(start - starts[first], end - starts[first]) + } + + const joined = Buffer.allocUnsafe(end - start) + let copied = 0 + + for (let index = first; copied < joined.length; index++) { + copied += parts[index].copy(joined, copied, Math.max(start - starts[index], 0), Math.min(parts[index].length, end - starts[index])) + } + + return joined + } + + // Holds one more of the chunks the box being read spans, beside the box's offset it starts at. + private keep(part: Buffer): void { + this.parts.push(part) + this.starts.push(this.held) + this.held += part.length + } + + // Drops the box being read, its chunks, its header and the media it was handing on. + private release(): void { + this.parts = [] + this.starts = [] + this.held = 0 + this.size = 0 + this.media = undefined + } +} + +/** + * The fields of a sample its time and its frame are read from, which a sample the reader hands on carries, as does one the camera buffer keeps. The + * live path reads a kept sample as it stands. + */ +export type Mp4TimedSample = Pick + +/** + * A sample's presentation time in whole microseconds, from its decode time and composition offset at its track's timescale, which the live path places it + * by. + * @param sample - The sample. + * @returns The time. + */ +export function timeOf(sample: Mp4TimedSample): number { + const { compositionOffset, decodeTime, track } = sample + + return Number((decodeTime + BigInt(compositionOffset)) * MICROSECONDS / BigInt(track.timescale)) +} + +/** + * The frame the live path takes for one sample: its time in whole microseconds from its decode time and composition offset, and for a picture its keyframe + * flag. A sync sample that holds fewer than all of HEVC's video, sequence and picture parameter sets, of a track that carries them, is handed as a copy + * with the track's whole block of them put in, after its access unit delimiter or at its front, and every other sample is handed as the very octets it + * holds: a keyframe that holds the sets itself, one of a track that carries none, whose stream puts them in its keyframes, a picture that is no keyframe + * and a sound. The sets a keyframe holds are read through its units' headers once, which allocates nothing. + * @param sample - The sample. + * @param time - The sample's time, for a caller that has read it already. + * @returns The frame. + */ +export function frameOf(sample: Mp4TimedSample, time: number = timeOf(sample)): TierFrame { + const { data, sync, track } = sample + + if (track.medium === 'audio') { + return { data, time } + } + + return { + data: sync && (track.parameterSets.length > 0) && (parameterSetsIn(data) !== HEVC_PARAMETER_SETS) + ? keyframeOf(data, track.parameterSets) + : data, + keyframe: sync, + time, + } +} + +// The run whose next sample the mdat places first, the earlier run on a tie, or undefined once every run's samples are handed on. +function nextRun(runs: readonly ArrivingRun[]): ArrivingRun | undefined { + let next: ArrivingRun | undefined + + for (const run of runs) { + if ((run.next < run.samples.length) && ((next === undefined) || (run.samples[run.next].offset < next.samples[next.next].offset))) { + next = run + } + } + + return next +} + +/* A version 0 tfdt's 32-bit decode time on its track's run: past the range the counter has wrapped past in the run, and past one more range where it + * falls from the counter's upper half to its lower by more than half the range below the last decode time the track took, which is the counter wrapping, + * and the run's decode times rise on across it. Any smaller fall is a step back, which the run refuses. + */ +function carried(track: ReaderTrack, value: bigint): bigint { + const read = value + track.wrapped + + if ((track.last === undefined) || (track.last - read <= COUNTER_FALL)) { + return read + } + + track.wrapped += COUNTER_RANGE + + return read + COUNTER_RANGE +} + +// Whether a run's samples each rise past the decode time before them, the first past the last its track took in its run, when it took one. +function rises(samples: readonly Mp4Sample[], last: bigint | undefined): boolean { + let before = last + + for (const { decodeTime } of samples) { + if ((before !== undefined) && (decodeTime <= before)) { + return false + } + + before = decodeTime + } + + 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 { + return duration === undefined + ? { + compositionOffset, + data, + decodeTime, + sync, + track: description, + } + : { + compositionOffset, + data, + decodeTime, + duration, + sync, + track: description, + } +} + +/* A video track's description, its parameter sets each behind the four-octet length a frame's units stand behind, as every keyframe carries them. Sets a + * keyframe would carry more octets of than the reader takes are refused by the box reader as it reads them, and a set shorter than HEVC's NAL unit header, + * which is no NAL unit, is refused here, each at the initialization segment, before any keyframe copies them. + */ +function videoOf(data: Buffer, trackBox: Mp4TrackBox): Mp4StreamVideoTrack { + const sets = readTrackBoxParameterSets(data, trackBox, { lengthSize: FRAME_LENGTH_SIZE, limit: LARGEST_PARAMETER_SETS }) + const entry = readTrackBoxEntry(data, trackBox) + const sampleEntry = readTrackBoxEntryBytes(data, trackBox) + + // A track whose entry holds no HEVC parameter sets is refused, its entry naming why. + if ((sets === undefined) || (entry === undefined) || (sampleEntry === undefined)) { + throw new RangeError(entry === undefined + ? 'The stream\'s video track holds no sample entry.' + : `The stream's video track's sample entry is ${entry.type}, which is neither hev1 nor hvc1.`) + } + + const { nalLengthSize, units } = sets + + if (nalLengthSize !== FRAME_LENGTH_SIZE) { + throw new RangeError(`The stream's video track writes each NAL unit's length in ${counted(nalLengthSize, 'octet')}, and the library takes a length of ` + + `${counted(FRAME_LENGTH_SIZE, 'octet')}.`) + } + + if (units.some(unit => unit.length < HEVC_HEADER_LENGTH)) { + throw new RangeError(`The stream's video track holds a parameter set shorter than the ${HEVC_HEADER_LENGTH} octets of HEVC's NAL unit header.`) + } + + const { id, timescale } = trackBox.track + + // A video track's entry always states the picture's size, which the box reader reads from every entry of a video track. + return { + height: entry.height!, + id, + medium: 'video', + parameterSets: Buffer.concat(units.flatMap((unit) => { + const length = Buffer.alloc(FRAME_LENGTH_SIZE) + length.writeUInt32BE(unit.length) + + return [length, unit] + })), + sampleEntry, + timescale, + width: entry.width!, + } +} + +// An Opus track's description, its entry found by its type. The entry is there to read whole. +function audioOf(data: Buffer, trackBox: Mp4TrackBox): Mp4StreamAudioTrack { + const { id, timescale } = trackBox.track + + return { + id, + medium: 'audio', + sampleEntry: readTrackBoxEntryBytes(data, trackBox)!, + timescale, + } +} + +/* A keyframe's bytes: the sample with its track's parameter sets put before its first unit, or after that unit when it is an access unit delimiter, which + * opens its access unit. + */ +function keyframeOf(sample: Buffer, parameterSets: Buffer): Buffer { + const split = delimiterEnd(sample) + + return Buffer.concat([ + sample.subarray(0, split), + parameterSets, + sample.subarray(split), + ]) +} + +// The offset past a sample's first unit when that unit is an access unit delimiter, and 0 for a sample opening with any other unit or with none it holds. +function delimiterEnd(sample: Buffer): number { + const end = sample.length > FRAME_LENGTH_SIZE + ? FRAME_LENGTH_SIZE + sample.readUInt32BE(0) + : 0 + + if ((end <= FRAME_LENGTH_SIZE) || (end > sample.length)) { + return 0 + } + + return ((sample[FRAME_LENGTH_SIZE] >> 1) & HEVC_TYPE_MASK) === HEVC_DELIMITER + ? end + : 0 +} diff --git a/src/lib/camera/mp4/mp4Boxes.spec.ts b/src/lib/camera/mp4/mp4Boxes.spec.ts new file mode 100644 index 000000000..93729bfbc --- /dev/null +++ b/src/lib/camera/mp4/mp4Boxes.spec.ts @@ -0,0 +1,1131 @@ +import type { Mp4SampleOptions, Mp4TrackSamples } from './mp4Boxes.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + audioSampleEntry, + avc1SampleEntry, + avcC, + box, + fullBox, + hvc1SampleEntry, + hvcC, + initializationSegment, + int32, + largeBox, + mediaFragment, + mp4aSampleEntry, + openBox, + sampleFragment, + skeletonPackets, + trun, + uint32, + uint64, + visualSampleEntry, +} from '../../../test-utils/mp4Fixtures.js' +import { + readSampleDefaults, + readTrackBoxEntry, + readTrackBoxEntryBytes, + readTrackBoxes, + readTrackBoxParameterSets, + readTrackDefaults, + readTrackFragments, + readTrackSamples, + readVideoTrackBox, + walkBoxes, +} from './mp4Boxes.js' + +function types(packet: Buffer): string[] { + return walkBoxes(packet).boxes.map(({ type }) => type) +} + +// The one top-level box of a type a packet holds. +function only(packet: Buffer, type: string): ReturnType['boxes'][number] { + return walkBoxes(packet).boxes.find(candidate => candidate.type === type)! +} + +describe('mp4Boxes', () => { + describe('walkBoxes', () => { + it('reads a 32-bit size, a 64-bit size after the type, and a size of 0 that runs to the end', () => { + const packet = Buffer.concat([ + box('styp', Buffer.alloc(4)), + largeBox('moof', Buffer.alloc(8)), + openBox('mdat', Buffer.alloc(5)), + ]) + + expect(walkBoxes(packet)).toEqual({ + boxes: [ + { + end: 12, + payload: 8, + start: 0, + type: 'styp', + }, + { + end: 36, + payload: 28, + start: 12, + type: 'moof', + }, + { + end: 49, + payload: 44, + start: 36, + type: 'mdat', + }, + ], + complete: true, + }) + }) + + it('reads an empty packet as complete and holding no box', () => { + expect(walkBoxes(Buffer.alloc(0))).toEqual({ boxes: [], complete: true }) + }) + + it.each([ + [ + 'a size under its header\'s', + Buffer.concat([ + box('free'), + Buffer.from('0000000466726565', 'hex'), + ]), + ], + [ + 'a 64-bit size under its header\'s', + Buffer.concat([ + box('free'), + Buffer.from('000000016672656500000000000000000f', 'hex'), + ]), + ], + [ + 'a size running past the packet', + Buffer.concat([ + box('free'), + Buffer.from('0000004066726565', 'hex'), + ]), + ], + [ + 'a 64-bit size running past the packet', + Buffer.concat([ + box('free'), + Buffer.from('00000001667265650000000000000040', 'hex'), + ]), + ], + [ + 'a trailing fragment of a header', + Buffer.concat([ + box('free'), + Buffer.from('000000', 'hex'), + ]), + ], + [ + 'a trailing fragment of a 64-bit header', + Buffer.concat([ + box('free'), + Buffer.from('000000016672656500', 'hex'), + ]), + ], + ])('ends the walk short at %s, keeping the boxes before it', (_name, packet) => { + expect(walkBoxes(packet)).toEqual({ + boxes: [ + { + end: 8, + payload: 8, + start: 0, + type: 'free', + }, + ], + complete: false, + }) + }) + + it('reads the one-byte end marker as no box', () => { + expect(walkBoxes(Buffer.alloc(1))).toEqual({ boxes: [], complete: false }) + }) + + it('walks one stretch of a buffer', () => { + const packet = box('moof', box('mfhd', Buffer.alloc(8)), box('traf')) + const moof = only(packet, 'moof') + + expect(walkBoxes(packet, moof.payload, moof.end).boxes.map(({ type }) => type)).toEqual(['mfhd', 'traf']) + }) + }) + + describe('tracks', () => { + it('reads each track\'s identifier, timescale and handler, in versions 0 and 1', () => { + const packet = initializationSegment( + { handler: 'soun', id: 1, timescale: 16000 }, + { + handler: 'vide', + id: 2, + timescale: 90000, + version: 1, + }, + ) + + expect(readTrackBoxes(packet, only(packet, 'moov')).map(({ track }) => track)).toEqual([ + { handler: 'soun', id: 1, timescale: 16000 }, + { handler: 'vide', id: 2, timescale: 90000 }, + ]) + }) + + it('reads the first video track as the video track', () => { + const packet = initializationSegment( + { handler: 'soun', id: 1, timescale: 16000 }, + { handler: 'vide', id: 2, timescale: 90000 }, + { handler: 'vide', id: 3, timescale: 15360 }, + ) + + const trackBoxes = readTrackBoxes(packet, only(packet, 'moov')) + + expect(readVideoTrackBox(trackBoxes)).toBe(trackBoxes[1]) + expect(trackBoxes[1].track).toEqual({ handler: 'vide', id: 2, timescale: 90000 }) + }) + + it('reads no video track from a movie of audio alone, or from a video track of timescale 0', () => { + const audio = initializationSegment({ handler: 'soun', id: 1, timescale: 16000 }) + const stopped = initializationSegment({ handler: 'vide', id: 1, timescale: 0 }) + + expect(readVideoTrackBox(readTrackBoxes(audio, only(audio, 'moov')))).toBeUndefined() + expect(readVideoTrackBox(readTrackBoxes(stopped, only(stopped, 'moov')))).toBeUndefined() + }) + + it.each([ + [ + 'a track with no header', + box('moov', box('trak', box('mdia'))), + ], + [ + 'a track header of version 2', + box('moov', box('trak', fullBox('tkhd', 2, 0, Buffer.alloc(20)))), + ], + [ + 'a malformed box inside the movie', + box('moov', Buffer.from('0000004074726166', 'hex')), + ], + ])('refuses %s', (_name, packet) => { + expect(() => readTrackBoxes(packet, only(packet, 'moov'))).toThrow(RangeError) + }) + + // A track header with its two times and no identifier, followed inside the track by its media box. A read past the header would land in that box. + it('refuses a track header too short for its identifier', () => { + const mdia = box( + 'mdia', + fullBox('mdhd', 0, 0, Buffer.alloc(8), Buffer.from('00003a98', 'hex'), Buffer.alloc(4)), + fullBox('hdlr', 0, 0, Buffer.alloc(4), Buffer.from('vide', 'latin1'), Buffer.alloc(12)), + ) + const packet = box('moov', box('trak', fullBox('tkhd', 0, 0, Buffer.alloc(8)), mdia)) + + expect(() => readTrackBoxes(packet, only(packet, 'moov'))).toThrow(new RangeError('An MP4 tkhd box is too short for its fields.')) + }) + }) + + describe('track fragments', () => { + it('reads each run\'s track and decode time, from 32 bits in version 0 and 64 bits in version 1, and a run with no decode time', () => { + const packet = mediaFragment( + { decodeTime: 4294967295n, trackId: 1, version: 0 }, + { decodeTime: 2n ** 64n - 1n, trackId: 2 }, + { trackId: 3 }, + ) + + expect(readTrackFragments(packet, only(packet, 'moof'))).toEqual([ + { baseMediaDecodeTime: 4294967295n, trackId: 1 }, + { baseMediaDecodeTime: 2n ** 64n - 1n, trackId: 2 }, + { trackId: 3 }, + ]) + }) + + it.each([ + [ + 'a run with no header', + box('moof', box('traf')), + ], + [ + 'a decode time of version 2', + box('moof', box('traf', fullBox('tfhd', 0, 0, Buffer.alloc(4)), fullBox('tfdt', 2, 0, Buffer.alloc(8)))), + ], + [ + 'a malformed box inside the run', + box('moof', box('traf', Buffer.from('0000000474666864', 'hex'))), + ], + ])('refuses %s', (_name, packet) => { + expect(() => readTrackFragments(packet, only(packet, 'moof'))).toThrow(RangeError) + }) + + // A version 1 decode time of 32 bits, followed in the fragment by another run. A 64-bit read would take its low half from that run's header. + it('refuses a version 1 decode time of 32 bits', () => { + const packet = box( + 'moof', + box('traf', fullBox('tfhd', 0, 0, Buffer.alloc(4)), fullBox('tfdt', 1, 0, Buffer.alloc(4))), + box('traf', fullBox('tfhd', 0, 0, Buffer.from('00000002', 'hex'))), + ) + + expect(() => readTrackFragments(packet, only(packet, 'moof'))).toThrow(new RangeError('An MP4 tfdt box is too short for its fields.')) + }) + }) + + describe('durations', () => { + const NO_DEFAULTS = new Map() + + it('sums a run\'s own sample durations across its truns whether or not the caller passes track defaults, and reads none for a run with no trun', () => { + const packet = box('moof', box('traf', fullBox('tfhd', 0, 0x20008, Buffer.from('0000000100000001', 'hex')), trun([3000, 3003]), trun([2997]))) + const bare = mediaFragment({ trackId: 1 }) + + expect(readTrackFragments(packet, only(packet, 'moof'), NO_DEFAULTS)).toEqual([ + { duration: 9000n, trackId: 1 }, + ]) + expect(readTrackFragments(bare, only(bare, 'moof'), NO_DEFAULTS)).toStrictEqual([ + { trackId: 1 }, + ]) + expect(readTrackFragments(packet, only(packet, 'moof'))).toStrictEqual([ + { duration: 9000n, trackId: 1 }, + ]) + }) + + it('reads a run\'s duration from its tfhd default with no track defaults passed, and none for a run whose samples have neither source then', () => { + const packet = mediaFragment({ defaultDuration: 3000, samples: 5, trackId: 1 }, { samples: 4, trackId: 2 }) + + expect(readTrackFragments(packet, only(packet, 'moof'))).toStrictEqual([ + { duration: 15000n, trackId: 1 }, + { trackId: 2 }, + ]) + }) + + it('takes a run\'s default sample duration from its tfhd before its track\'s default', () => { + const packet = mediaFragment({ defaultDuration: 3000, samples: 5, trackId: 1 }) + + expect(readTrackFragments(packet, only(packet, 'moof'), new Map([ + [1, 1], + ]))).toEqual([ + { duration: 15000n, trackId: 1 }, + ]) + }) + + it('takes a track\'s default sample duration from its trex, and reads none for a run whose samples have no duration anywhere', () => { + const initialization = initializationSegment( + { + defaultDuration: 3000, + handler: 'vide', + id: 1, + timescale: 90000, + }, + { handler: 'soun', id: 2, timescale: 16000 }, + ) + const packet = mediaFragment({ samples: 4, trackId: 1 }, { samples: 4, trackId: 2 }) + const defaults = readTrackDefaults(initialization, only(initialization, 'moov')) + + expect(defaults).toEqual(new Map([ + [1, 3000], + ])) + expect(readTrackFragments(packet, only(packet, 'moof'), defaults)).toStrictEqual([ + { duration: 12000n, trackId: 1 }, + { trackId: 2 }, + ]) + }) + + it('reads each run\'s duration past a tfhd\'s base data offset and description index, and past a trun\'s first sample flags and composition offsets', () => { + // The tfhd names a base data offset, a sample description index and a default duration; the trun a data offset, first sample flags and, for each + // sample, its duration, size and composition offset. + const described = fullBox('tfhd', 0, 0x0B, uint32(1), uint64(8n), uint32(1), uint32(3000)) + const offsets = fullBox('trun', 0, 0xB05, uint32(2), uint32(0), uint32(0x02000000), uint32(3000), uint32(16), uint32(0), uint32(3003), uint32(16), uint32(1000)) + const packet = box('moof', box('traf', described, trun(5)), box('traf', fullBox('tfhd', 0, 0x20000, uint32(2)), offsets)) + + expect(readTrackFragments(packet, only(packet, 'moof'), NO_DEFAULTS).map(({ duration }) => duration)).toEqual([15000n, 6003n]) + }) + + it.each([ + [ + 'a trun whose sample count runs past its box', + box('moof', box('traf', fullBox('tfhd', 0, 0, Buffer.alloc(4)), fullBox('trun', 0, 0x100, Buffer.from('00000003', 'hex'), Buffer.alloc(8)))), + 'An MP4 trun box is too short for its fields.', + ], + [ + 'a tfhd whose flags name a default duration it does not hold', + box('moof', box('traf', fullBox('tfhd', 0, 0x8, Buffer.alloc(4)), trun(1))), + 'An MP4 tfhd box is too short for its fields.', + ], + ])('refuses %s', (_name, packet, message) => { + expect(() => readTrackFragments(packet, only(packet, 'moof'), NO_DEFAULTS)).toThrow(new RangeError(message)) + }) + + it('refuses a trex too short for its default duration', () => { + const packet = box('moov', box('mvex', fullBox('trex', 0, 0, Buffer.alloc(8)))) + + expect(() => readTrackDefaults(packet, only(packet, 'moov'))).toThrow(new RangeError('An MP4 trex box is too short for its fields.')) + }) + }) + + describe('sample entries', () => { + function entryOf(sampleEntry: Buffer, handler = 'vide'): ReturnType { + const packet = initializationSegment({ + handler, + id: 7, + sampleEntry, + timescale: 90000, + }) + const [trackBox] = readTrackBoxes(packet, only(packet, 'moov')) + + return readTrackBoxEntry(packet, trackBox) + } + + it('reads an avc1 entry\'s size and its codec from its avcC', () => { + expect(entryOf(avc1SampleEntry(1920, 1080, 0x4D, 0x00, 0x28))).toStrictEqual({ + codec: 'avc1.4d0028', + height: 1080, + type: 'avc1', + width: 1920, + }) + }) + + it('reads an hvc1 entry\'s size and its codec from its hvcC', () => { + expect(entryOf(hvc1SampleEntry(1920, 1080))).toStrictEqual({ + codec: 'hvc1.1.6.L120.90', + height: 1080, + type: 'hvc1', + width: 1920, + }) + }) + + it('reads an hev1 entry\'s codec from its hvcC as it reads an hvc1 entry\'s, under the entry\'s own type', () => { + expect(entryOf(visualSampleEntry('hev1', 1920, 1080, box('hvcC', Buffer.from('01016000000090000000000078', 'hex'))))).toStrictEqual({ + codec: 'hev1.1.6.L120.90', + height: 1080, + type: 'hev1', + width: 1920, + }) + }) + + // The records libx265 and VideoToolbox wrote for test patterns, each beside the label FFmpeg derives from the same bytes: the high tier, the Main 10 + // profile and a constraint byte written with a letter among them. + it.each([ + ['01216000000090000000000078', 'hvc1.1.6.H120.90'], + ['0122200000009000000000007b', 'hvc1.2.4.H123.90'], + ['01216000000090000000000099', 'hvc1.1.6.H153.90'], + ['010160000000b0000000000078', 'hvc1.1.6.L120.b0'], + ['010220000000b0000000000078', 'hvc1.2.4.L120.b0'], + ])('reads an hvcC opening %s as %s', (head, codec) => { + expect(entryOf(hvc1SampleEntry(1920, 1080, Buffer.from(head, 'hex')))?.codec).toBe(codec) + }) + + it('reads an mp4a entry\'s codec from its esds, an escaped audio object type among them', () => { + expect(entryOf(mp4aSampleEntry(2), 'soun')).toStrictEqual({ codec: 'mp4a.40.2', type: 'mp4a' }) + expect(entryOf(mp4aSampleEntry(42), 'soun')).toStrictEqual({ codec: 'mp4a.40.42', type: 'mp4a' }) + }) + + it('reads an mp4a entry\'s codec past its ES descriptor\'s dependency, URL and OCR stream fields', () => { + // The flags name all three: a dependency's ES ID, a URL of three bytes after its length and an OCR ES ID. + const flagged = Buffer.concat([ + Buffer.from([0xE0, 0, 2, 3]), + Buffer.from('abc', 'latin1'), + Buffer.from([0, 3]), + ]) + + expect(entryOf(mp4aSampleEntry(2, flagged), 'soun')).toStrictEqual({ codec: 'mp4a.40.2', type: 'mp4a' }) + }) + + it('reads an Opus entry\'s codec as the entry\'s own type', () => { + // An Opus Specific Box: its version, channel count, pre-skip, input sample rate, output gain and channel mapping family. + const opus = audioSampleEntry('Opus', box('dOps', Buffer.from([0, 1, 0x01, 0x38]), uint32(16000), Buffer.from([0, 0, 0]))) + + expect(entryOf(opus, 'soun')).toStrictEqual({ codec: 'Opus', type: 'Opus' }) + }) + + it('reads an entry of another type with its size and no codec', () => { + const hevc = visualSampleEntry('hvc1', 1920, 1080, box('hvcC', Buffer.alloc(23))) + + expect(entryOf(hevc)).toStrictEqual({ height: 1080, type: 'hvc1', width: 1920 }) + }) + + it('reads a track\'s first sample entry whole as a view of the segment, and none from a track holding no entry', () => { + const sampleEntry = hvc1SampleEntry(1920, 1080) + const packet = initializationSegment( + { + handler: 'vide', + id: 1, + sampleEntry, + timescale: 90000, + }, + { + handler: 'soun', + id: 2, + sampleEntry: Buffer.alloc(0), + timescale: 48000, + }, + ) + const [video, empty] = readTrackBoxes(packet, only(packet, 'moov')) + const bytes = readTrackBoxEntryBytes(packet, video) + + expect(bytes).toEqual(sampleEntry) + expect(bytes?.buffer).toBe(packet.buffer) + expect(readTrackBoxEntryBytes(packet, empty)).toBeUndefined() + }) + + it.each([ + [ + 'a video entry too short for its fields', + box('avc1', Buffer.alloc(40)), + 'vide', + 'An MP4 avc1 box is too short for its fields.', + ], + [ + 'an avcC too short for its level', + visualSampleEntry('avc1', 64, 36, box('avcC', Buffer.from([1, 0x4D]))), + 'vide', + 'An MP4 avcC box is too short for its fields.', + ], + [ + 'an hvcC too short for its level', + visualSampleEntry('hvc1', 64, 36, box('hvcC', Buffer.from([1, 0x01, 0x60]))), + 'vide', + 'An MP4 hvcC box is too short for its fields.', + ], + [ + 'an esds cut inside its decoder config', + audioSampleEntry('mp4a', fullBox('esds', 0, 0, Buffer.from([0x03, 0x05, 0, 1, 0, 0x04, 0x0D]))), + 'soun', + 'An MP4 esds box is too short for its fields.', + ], + ])('refuses %s', (_name, sampleEntry, handler, message) => { + expect(() => entryOf(sampleEntry, handler)).toThrow(new RangeError(message)) + }) + }) + + describe('parameter sets', () => { + const VPS = Buffer.from('40010c01ffff016000000300', 'hex') + const SPS = Buffer.from('420101016000000300900000', 'hex') + const PPS = Buffer.from('4401c172b462', 'hex') + const SEI = Buffer.from('4e01050a', 'hex') + + // A synthetic H.264 sequence and picture parameter set, which a well-formed avcC holds. + const AVC_SEQUENCE = Buffer.from('674d401f', 'hex') + const AVC_PICTURE = Buffer.from('68ebef20', 'hex') + + // The bound the stream reader hands the box reader: each set behind a four-octet length, in at most 16 KiB. + const BOUND = { lengthSize: 4, limit: 16 * 1024 } + + function setsOf(sampleEntry: Buffer): ReturnType { + const packet = initializationSegment({ + handler: 'vide', + id: 7, + sampleEntry, + timescale: 90000, + }) + const [trackBox] = readTrackBoxes(packet, only(packet, 'moov')) + + return readTrackBoxParameterSets(packet, trackBox, BOUND) + } + + it('reads an hvcC\'s units array by array with each length size, and no parameter sets from an entry of another type, the skeleton\'s avc1 among them, ' + + 'and refuses a record too short for what it announces', () => { + const arrays = [ + { + type: 32, + units: [VPS], + }, + { + type: 33, + units: [SPS], + }, + { + type: 34, + units: [ + PPS, + PPS.subarray(0, 4), + ], + }, + { + type: 39, + units: [SEI], + }, + ] + const [initialization] = skeletonPackets() + const skeletonTracks = readTrackBoxes(initialization, only(initialization, 'moov')) + + // An hvcC announcing two arrays and holding one, one whose array announces two units and holds one, one whose unit's length runs past its record, + // and one of version 0, each written over a record of one array. + const twoArrays = hvcC(arrays.slice(0, 1)) + const twoUnits = hvcC(arrays.slice(0, 1)) + const longUnit = hvcC(arrays.slice(0, 1)) + const versionZero = hvcC(arrays.slice(0, 1)) + + twoArrays.writeUInt8(2, 30) + twoUnits.writeUInt16BE(2, 32) + longUnit.writeUInt16BE(VPS.length + 1, 34) + versionZero.writeUInt8(0, 8) + + // The hvcC records above, and an entry holding no record. + const refusals: [string, Buffer[], string][] = [ + [ + 'hvc1', + [twoArrays], + 'An MP4 hvcC box is too short for the parameter sets it announces.', + ], + [ + 'hvc1', + [twoUnits], + 'An MP4 hvcC box is too short for the parameter sets it announces.', + ], + [ + 'hev1', + [longUnit], + 'An MP4 hvcC box is too short for the parameter sets it announces.', + ], + [ + 'hvc1', + [versionZero], + 'An MP4 hvcC box has version 0, which the library does not read.', + ], + ['hvc1', [], 'An MP4 hvc1 box holds no hvcC box.'], + ] + + expect(setsOf(visualSampleEntry('hvc1', 64, 36, hvcC(arrays)))).toEqual({ + nalLengthSize: 4, + units: [ + VPS, + SPS, + PPS, + PPS.subarray(0, 4), + SEI, + ], + }) + expect(setsOf(visualSampleEntry('hev1', 64, 36, hvcC(arrays.slice(0, 1), 2)))).toEqual({ + nalLengthSize: 2, + units: [VPS], + }) + // An avc3 entry carrying a well-formed avcC holds no HEVC parameter sets. + expect(setsOf(visualSampleEntry('avc3', 64, 36, avcC([AVC_SEQUENCE], [AVC_PICTURE])))).toBeUndefined() + // The skeleton's video entry is avc1, whose avcC the box reader reads for its codec alone, and its audio track is AAC, whose entry holds no parameter + // sets. + expect(skeletonTracks.map(trackBox => readTrackBoxParameterSets(initialization, trackBox, BOUND))).toEqual([undefined, undefined]) + + for (const [type, boxes, message] of refusals) { + expect(() => setsOf(visualSampleEntry(type, 64, 36, ...boxes))).toThrow(new RangeError(message)) + } + }) + + it('refuses an hvcC whose sets pass the reader\'s bound at the set that passes it, though the record runs out before the sets it announces', () => { + // One array announcing 10,000 units of no octets and holding 4,100: the bound's 16 KiB take 4,096 of them behind their four-octet lengths, and the + // 4,097th passes it while the record still holds it, where a walk reading every unit first meets the record's end at the 4,101st. + const record = hvcC([ + { + type: 39, + units: Array.from({ length: 4100 }, () => Buffer.alloc(0)), + }, + ]) + + record.writeUInt16BE(10000, 32) + + expect(() => setsOf(visualSampleEntry('hvc1', 64, 36, record))) + .toThrow(new RangeError('An MP4 hvcC box holds parameter sets that take more than the 16384 octets its reader puts in a keyframe.')) + }) + + // A version 1 record one octet short of its fixed fields, its entry's last box, which means a read past its end meets the buffer's end. + it('refuses an hvcC too short for its fixed fields with the box module\'s message', () => { + const sampleEntry = visualSampleEntry('hvc1', 64, 36, box('hvcC', Buffer.from('01016000000090000000000078f000fcfdf8f800000f', 'hex'))) + + expect(() => setsOf(sampleEntry)).toThrow(new RangeError('An MP4 hvcC box is too short for its fields.')) + }) + }) + + describe('samples', () => { + // A limit far past the samples of the track any row's fragment holds, but for the rows refusing a fragment past it. + const LIMIT = 4096 + + // A fragment's samples for track 1. + function samplesIn(packet: Buffer, options: Partial = {}): Mp4TrackSamples { + return readTrackSamples(packet, only(packet, 'moof'), { limit: LIMIT, trackId: 1, ...options }) + } + + // The flags of a sync sample that depends on no other, and of a sample that is no sync sample and depends on one before it. + const SYNC = 0x02000000 + const NON_SYNC = 0x01010000 + + it('takes a sample\'s size, duration and flags from its trun, else its tfhd, else its trex, a run\'s first sample flags over every other, flags with no ' + + 'source as zero, and a version 1 trun\'s signed composition offset, refusing a size or a needed duration with no source', () => { + const own = sampleFragment({ + decodeTime: 9000n, + samples: [ + { + compositionOffset: 6000, + data: Buffer.alloc(4, 1), + duration: 3000, + flags: SYNC, + }, + { + data: Buffer.alloc(2, 2), + duration: 3003, + flags: NON_SYNC, + }, + ], + trackId: 1, + }) + const offset = own.length - 6 + const runDefaults = box('moof', box( + 'traf', + fullBox('tfhd', 0, 0x20038, uint32(1), uint32(3000), uint32(5), uint32(NON_SYNC)), + fullBox('tfdt', 1, 0, uint64(0n)), + fullBox('trun', 0, 0x1, uint32(2), int32(100)), + )) + const trex = box('moov', box('mvex', fullBox('trex', 0, 0, uint32(1), uint32(1), uint32(1024), uint32(7), uint32(NON_SYNC)))) + const trackDefaults = readSampleDefaults(trex, only(trex, 'moov')) + const bare = box('moof', box('traf', fullBox('tfhd', 0, 0x20000, uint32(1)), fullBox('tfdt', 0, 0, uint32(0)), fullBox('trun', 0, 0x1, uint32(2), int32(100)))) + // A trun naming its first sample flags and each sample's size and flags, and a tfhd whose default flags name no sync sample. + const first = box('moof', box( + 'traf', + fullBox('tfhd', 0, 0x20028, uint32(1), uint32(3000), uint32(NON_SYNC)), + fullBox('tfdt', 0, 0, uint32(0)), + fullBox('trun', 0, 0x605, uint32(2), int32(100), uint32(SYNC), uint32(3), uint32(NON_SYNC), uint32(3), uint32(NON_SYNC)), + )) + const unflagged = box('moof', box('traf', fullBox('tfhd', 0, 0x20018, uint32(1), uint32(3000), uint32(4)), fullBox('trun', 0, 0, uint32(2)))) + const [, skeleton] = skeletonPackets() + + expect(samplesIn(own)).toStrictEqual({ + decodeTime: 15003n, + samples: [ + { + compositionOffset: 6000, + decodeTime: 9000n, + duration: 3000, + offset, + size: 4, + sync: true, + }, + { + compositionOffset: 0, + decodeTime: 12000n, + duration: 3003, + offset: offset + 4, + size: 2, + sync: false, + }, + ], + }) + expect(samplesIn(runDefaults, { + defaults: new Map([ + [ + 1, + { duration: 1, flags: 0, size: 1 }, + ], + ]), + })).toStrictEqual({ + decodeTime: 6000n, + samples: [ + { + compositionOffset: 0, + decodeTime: 0n, + duration: 3000, + offset: 100, + size: 5, + sync: false, + }, + { + compositionOffset: 0, + decodeTime: 3000n, + duration: 3000, + offset: 105, + size: 5, + sync: false, + }, + ], + }) + expect(trackDefaults).toEqual(new Map([ + [ + 1, + { duration: 1024, flags: NON_SYNC, size: 7 }, + ], + ])) + expect(samplesIn(bare, { defaults: trackDefaults })).toStrictEqual({ + decodeTime: 2048n, + samples: [ + { + compositionOffset: 0, + decodeTime: 0n, + duration: 1024, + offset: 100, + size: 7, + sync: false, + }, + { + compositionOffset: 0, + decodeTime: 1024n, + duration: 1024, + offset: 107, + size: 7, + sync: false, + }, + ], + }) + expect(samplesIn(first).samples.map(({ sync }) => sync)).toEqual([true, false]) + // The skeleton's video run names its first sample flags, a sync sample's, over its tfhd's default flags, which name no sync sample. + expect(readTrackSamples(skeleton, only(skeleton, 'moof'), { limit: LIMIT, trackId: 1 }).samples.slice(0, 3).map(({ sync }) => sync)) + .toEqual([true, false, false]) + expect(samplesIn(unflagged, { decodeTime: 90000n })).toStrictEqual({ + decodeTime: 96000n, + samples: [ + { + compositionOffset: 0, + decodeTime: 90000n, + duration: 3000, + offset: 0, + size: 4, + sync: true, + }, + { + compositionOffset: 0, + decodeTime: 93000n, + duration: 3000, + offset: 4, + size: 4, + sync: true, + }, + ], + }) + + // A composition offset of -3003 reads signed from a version 1 trun and unsigned from a version 0 one. + const negative = (trunVersion: 0 | 1): Buffer => sampleFragment({ + decodeTime: 3003n, + samples: [ + { + compositionOffset: -3003, + data: Buffer.alloc(1), + }, + ], + trackId: 1, + trunVersion, + }) + + expect(samplesIn(negative(1)).samples[0].compositionOffset).toBe(-3003) + expect(samplesIn(negative(0)).samples[0].compositionOffset).toBe(2 ** 32 - 3003) + + // A trex too short for its default size and flags names neither, and a run it sizes has no size. + const short = box('moov', box('mvex', fullBox('trex', 0, 0, uint32(1), uint32(1), uint32(1024)))) + + expect(readSampleDefaults(short, only(short, 'moov'))).toStrictEqual(new Map([ + [ + 1, + { duration: 1024 }, + ], + ])) + expect(() => samplesIn(bare)).toThrow(new RangeError('An MP4 trun box holds a sample with no size.')) + expect(() => samplesIn(bare, { + defaults: readSampleDefaults(short, only(short, 'moov')), + })).toThrow(new RangeError('An MP4 trun box holds a sample with no size.')) + + // Two samples with no duration anywhere: the second's decode time has no source, and a run of one sample ends with no decode time. + const untimed = box('moof', box('traf', fullBox('tfhd', 0, 0x20010, uint32(1), uint32(4)), fullBox('tfdt', 0, 0, uint32(0)), fullBox('trun', 0, 0, uint32(2)))) + const single = box('moof', box('traf', fullBox('tfhd', 0, 0x20010, uint32(1), uint32(4)), fullBox('tfdt', 0, 0, uint32(0)), fullBox('trun', 0, 0, uint32(1)))) + + expect(() => samplesIn(untimed)).toThrow(new RangeError('An MP4 fragment holds a sample whose decode time has no source, neither a tfdt box nor the duration ' + + 'of the sample before it.')) + expect(samplesIn(single)).toStrictEqual({ + samples: [ + { + compositionOffset: 0, + decodeTime: 0n, + offset: 0, + size: 4, + sync: true, + }, + ], + }) + expect(() => samplesIn(unflagged)).toThrow(RangeError) + }) + + it('reads a sample\'s size, duration and flags from a trun carrying each beside a tfhd naming other defaults', () => { + // A tfhd naming a default duration of 3000, size of 5 and flags of no sync sample, and a trun naming each sample's own duration, size and flags. + const packet = box('moof', box( + 'traf', + fullBox('tfhd', 0, 0x20038, uint32(1), uint32(3000), uint32(5), uint32(NON_SYNC)), + fullBox('tfdt', 0, 0, uint32(0)), + fullBox('trun', 0, 0x701, uint32(2), int32(100), uint32(1000), uint32(3), uint32(SYNC), uint32(2000), uint32(6), uint32(SYNC)), + )) + + expect(samplesIn(packet)).toStrictEqual({ + decodeTime: 3000n, + samples: [ + { + compositionOffset: 0, + decodeTime: 0n, + duration: 1000, + offset: 100, + size: 3, + sync: true, + }, + { + compositionOffset: 0, + decodeTime: 1000n, + duration: 2000, + offset: 103, + size: 6, + sync: true, + }, + ], + }) + }) + + it('reads a sample whose flags set the dependency on another sample alone as a sync sample, and one whose flags set the non-sync bit alone as none', () => { + const packet = box('moof', box( + 'traf', + fullBox('tfhd', 0, 0x20018, uint32(1), uint32(1), uint32(4)), + fullBox('tfdt', 0, 0, uint32(0)), + fullBox('trun', 0, 0x401, uint32(2), int32(0), uint32(0x01000000), uint32(0x00010000)), + )) + + expect(samplesIn(packet).samples.map(({ sync }) => sync)).toEqual([true, false]) + }) + + it('reads a sample whose duration has no source with none, and one whose trun states a duration of zero with that duration', () => { + // One sample sized 4 by its tfhd, its duration in neither its trun, its tfhd nor a trex. + const unstated = box('moof', box('traf', fullBox('tfhd', 0, 0x20010, uint32(1), uint32(4)), fullBox('tfdt', 0, 0, uint32(0)), fullBox('trun', 0, 0, uint32(1)))) + // One sample whose trun states its duration as zero and its size as 4. + const zero = box('moof', box('traf', fullBox('tfhd', 0, 0x20000, uint32(1)), fullBox('tfdt', 0, 0, uint32(0)), fullBox('trun', 0, 0x300, uint32(1), uint32(0), + uint32(4)))) + const [none] = samplesIn(unstated).samples + const [stated] = samplesIn(zero).samples + + expect(none).not.toHaveProperty('duration') + expect(stated).toHaveProperty('duration', 0) + }) + + it('continues a traf of the track with no tfdt from the decode time handed in, though another track\'s traf before it carries one', () => { + const packet = box( + 'moof', + box('traf', fullBox('tfhd', 0, 0x20000, uint32(2)), fullBox('tfdt', 0, 0, uint32(5000))), + box('traf', fullBox('tfhd', 0, 0x20018, uint32(1), uint32(1), uint32(4)), fullBox('trun', 0, 0, uint32(2))), + ) + + expect(samplesIn(packet, { decodeTime: 90000n })).toStrictEqual({ + decodeTime: 90002n, + samples: [ + { + compositionOffset: 0, + decodeTime: 90000n, + duration: 1, + offset: 0, + size: 4, + sync: true, + }, + { + compositionOffset: 0, + decodeTime: 90001n, + duration: 1, + offset: 4, + size: 4, + sync: true, + }, + ], + }) + }) + + it('reads a trex holding a default size and no default flags as naming that size, which sizes a run', () => { + const sized = box('moov', box('mvex', fullBox('trex', 0, 0, uint32(1), uint32(1), uint32(1024), uint32(7)))) + const defaults = readSampleDefaults(sized, only(sized, 'moov')) + const bare = box('moof', box('traf', fullBox('tfhd', 0, 0x20000, uint32(1)), fullBox('tfdt', 0, 0, uint32(0)), fullBox('trun', 0, 0x1, uint32(2), int32(100)))) + + expect(defaults).toStrictEqual(new Map([ + [ + 1, + { duration: 1024, size: 7 }, + ], + ])) + expect(samplesIn(bare, { defaults }).samples.map(({ offset, size }) => [offset, size])).toEqual([ + [100, 7], + [107, 7], + ]) + }) + + it('counts a trun\'s data from its data offset past the moof, a trun with none after the one before it, a traf after the one before it, and refuses a ' + + 'tfhd naming a base data offset of its own with the muxer flag that writes the layout a stream needs', () => { + const placed = sampleFragment({ + decodeTime: 0n, + samples: [ + { + data: Buffer.from('aabbcc', 'hex'), + duration: 1, + }, + { + data: Buffer.from('dd', 'hex'), + duration: 1, + }, + ], + trackId: 1, + }) + const decodeTime = fullBox('tfdt', 0, 0, uint32(0)) + // Track 1's tfhd naming a default duration of 1 and size of 4, counting its runs' data from the moof or from where the traf before it ends. + const fromMoofHeader = fullBox('tfhd', 0, 0x20018, uint32(1), uint32(1), uint32(4)) + const followingHeader = fullBox('tfhd', 0, 0x18, uint32(1), uint32(1), uint32(4)) + // Track 2's run of three samples of 10 octets from 300, then track 1's runs, counted from where track 2's data ends unless their tfhd says otherwise. + const other = box('traf', fullBox('tfhd', 0, 0x20010, uint32(2), uint32(10)), fullBox('trun', 0, 0x1, uint32(3), int32(300))) + const unsizedOther = box('traf', fullBox('tfhd', 0, 0, uint32(2)), fullBox('trun', 0, 0x1, uint32(3), int32(300))) + const runs = [ + decodeTime, + fullBox('trun', 0, 0x1, uint32(2), int32(6)), + fullBox('trun', 0, 0, uint32(1)), + ] + const following = box('moof', other, box('traf', followingHeader, ...runs)) + const fromMoof = box('moof', other, box('traf', fromMoofHeader, ...runs)) + const first = box('moof', box('traf', followingHeader, decodeTime, fullBox('trun', 0, 0, uint32(2)))) + const unsized = box('moof', unsizedOther, box('traf', followingHeader, ...runs)) + const absoluteHeader = fullBox('tfhd', 0, 0x1, uint32(1), uint64(4096n)) + const absolute = box('moof', box('traf', absoluteHeader, decodeTime, fullBox('trun', 0, 0x201, uint32(1), int32(0), uint32(4)))) + const offsets = (packet: Buffer): number[] => samplesIn(packet).samples.map(({ offset }) => offset) + + expect(samplesIn(placed).samples.map(({ offset, size }) => placed.subarray(offset, offset + size).toString('hex'))).toEqual(['aabbcc', 'dd']) + expect(offsets(following)).toEqual([336, 340, 344]) + expect(offsets(fromMoof)).toEqual([6, 10, 14]) + expect(offsets(first)).toEqual([0, 4]) + expect(() => offsets(unsized)).toThrow(new RangeError('An MP4 traf box follows a run whose sample sizes have no source.')) + expect(readTrackSamples(unsized, only(unsized, 'moof'), { limit: LIMIT, trackId: 3 })).toStrictEqual({ samples: [] }) + expect(() => offsets(absolute)).toThrow(new RangeError('An MP4 fragment places its data by an absolute file offset, which a stream cannot follow, and ffmpeg ' + + 'writes the layout a stream needs under its default_base_moof muxer flag.')) + expect(() => offsets(absolute)).toThrow(/default_base_moof/) + }) + + describe('refuses a sample count past a trun\'s fields or past the limit across its fragment, and places another track\'s run of one sample size with no ' + + 'walk', () => { + const decodeTime = fullBox('tfdt', 0, 0, uint32(0)) + // Track 1's tfhd naming a default duration of 1 and size of 4, counting its runs' data from where the traf before it ends. + const followingHeader = fullBox('tfhd', 0, 0x18, uint32(1), uint32(1), uint32(4)) + + // A trun of the samples given, carrying no fields. + function run(count: number): Buffer { + return fullBox('trun', 0, 0, uint32(count)) + } + + // Track 2's traf of one run of the samples given, carrying a data offset and no per-sample fields, its data from 300 and each sample of the size its + // tfhd gives. + function otherTraf(count: number, size: number): Buffer { + return box('traf', fullBox('tfhd', 0, 0x20010, uint32(2), uint32(size)), fullBox('trun', 0, 0x1, uint32(count), int32(300))) + } + + // The refusal of a fragment holding more samples of the track than the limit, which it names. + function limitError(limit: number): RangeError { + return new RangeError(`An MP4 fragment holds more samples of a track than the ${limit} its reader takes from one fragment.`) + } + + it('refuses a run whose per-sample fields claim more samples than its box holds', () => { + // A trun announcing more sizes than it holds. + const fields = box('moof', box('traf', fullBox('tfhd', 0, 0x20000, uint32(1)), decodeTime, fullBox('trun', 0, 0x200, uint32(3), uint32(4), uint32(4)))) + + expect(() => samplesIn(fields)).toThrow(new RangeError('An MP4 trun box is too short for its fields.')) + }) + + it('reads runs of the track holding as many samples as the limit and refuses one sample more, in one traf and across two', () => { + const oneTraf = (first: number, second: number): Buffer => box('moof', box('traf', followingHeader, decodeTime, run(first), run(second))) + const twoTrafs = (first: number, second: number): Buffer => box('moof', box('traf', followingHeader, decodeTime, run(first)), box('traf', followingHeader, + run(second))) + const times = (packet: Buffer): bigint[] => samplesIn(packet, { limit: 4 }).samples.map(sample => sample.decodeTime) + + expect(times(oneTraf(2, 2))).toEqual([0n, 1n, 2n, 3n]) + expect(times(twoTrafs(2, 2))).toEqual([0n, 1n, 2n, 3n]) + expect(() => times(oneTraf(2, 3))).toThrow(limitError(4)) + expect(() => times(twoTrafs(2, 3))).toThrow(limitError(4)) + }) + + it('refuses a run of the track announcing more samples than the limit, though its samples hold no octets', () => { + // Samples far past the limit, each sized 0 by their tfhd, which a fragment of any length holds. + const emptyHeader = fullBox('tfhd', 0, 0x20018, uint32(1), uint32(1), uint32(0)) + const empty = box('moof', box('traf', emptyHeader, decodeTime, run(1000000))) + // One sample past the limit, then a trun announcing three sizes and holding one, which only a walk of the first run's samples would reach: the + // limit's refusal says the run was refused before any of its samples was read. + const beforeWalk = box('moof', box('traf', emptyHeader, decodeTime, run(LIMIT + 1), fullBox('trun', 0, 0x200, uint32(3), uint32(4)))) + + expect(() => samplesIn(empty)).toThrow(limitError(LIMIT)) + expect(() => samplesIn(beforeWalk)).toThrow(limitError(LIMIT)) + }) + + it('places the track\'s samples where another track\'s run of the most samples a count holds begins, its samples holding no octets, without walking ' + + 'it', () => { + const packet = box('moof', otherTraf(0xFFFFFFFF, 0), box('traf', followingHeader, decodeTime, run(2))) + + expect(samplesIn(packet).samples.map(({ offset }) => offset)).toEqual([300, 304]) + }) + + it('places the track\'s traf after another track\'s run carrying no sizes at its count times the size its tfhd gives', () => { + const packet = box('moof', otherTraf(3, 5), box('traf', followingHeader, decodeTime, run(2))) + // The offsets of the track's samples in a traf following another track's traf given. + const offsets = (other: Buffer, options: Partial = {}): number[] => { + const fragment = box('moof', other, box('traf', followingHeader, decodeTime, run(2))) + + return samplesIn(fragment, options).samples.map(({ offset }) => offset) + } + // Another track's run carrying sizes of 7 and 9 over a tfhd default of 5, which is walked by its own sizes. + const sized = box('traf', fullBox('tfhd', 0, 0x20010, uint32(2), uint32(5)), fullBox('trun', 0, 0x201, uint32(2), int32(300), uint32(7), uint32(9))) + // Another track's run of no samples and no size source, which moves nothing. + const none = box('traf', fullBox('tfhd', 0, 0x20000, uint32(2)), fullBox('trun', 0, 0x1, uint32(0), int32(300))) + // Another track's run of three samples sized 5 by its trex alone. + const unsized = box('traf', fullBox('tfhd', 0, 0x20000, uint32(2)), fullBox('trun', 0, 0x1, uint32(3), int32(300))) + + expect(samplesIn(packet).samples.map(({ offset }) => offset)).toEqual([315, 319]) + expect(offsets(sized)).toEqual([316, 320]) + expect(offsets(none)).toEqual([300, 304]) + expect(offsets(unsized, { + defaults: new Map([ + [ + 2, + { duration: 1, size: 5 }, + ], + ]), + })).toEqual([315, 319]) + }) + }) + }) + + describe('a real muxer\'s boxes', () => { + it('walks the skeleton\'s packets and reads its tracks, their decode times and the muxer\'s own boxes', () => { + const [initialization, first, second] = skeletonPackets() + + expect([initialization, first, second].map(types)).toEqual([ + ['ftyp', 'moov', 'prft'], + ['moof', 'mdat'], + ['prft', 'moof', 'mdat'], + ]) + expect(readTrackBoxes(initialization, only(initialization, 'moov')).map(({ track }) => track)).toEqual([ + { handler: 'vide', id: 1, timescale: 15360 }, + { handler: 'soun', id: 2, timescale: 16000 }, + ]) + expect(readTrackFragments(first, only(first, 'moof'))).toEqual([ + { baseMediaDecodeTime: 0n, duration: 62424n, trackId: 1 }, + { baseMediaDecodeTime: 0n, duration: 65536n, trackId: 2 }, + ]) + expect(readTrackFragments(second, only(second, 'moof'))).toEqual([ + { baseMediaDecodeTime: 62424n, duration: 60n * 1024n, trackId: 1 }, + { baseMediaDecodeTime: 65536n, duration: 62n * 1024n, trackId: 2 }, + ]) + + for (const packet of [initialization, second]) { + const muxerBox = only(packet, 'prft') + + expect(muxerBox.end - muxerBox.start).toBe(32) + expect(packet.readUInt32BE(muxerBox.payload)).toBe(0x01000018) + expect(packet.readUInt32BE(muxerBox.payload + 4)).toBe(1) + } + }) + + // A run's duration carries its track to the next run's decode time, which the muxer wrote on its own. + it('reads the skeleton\'s runs\' durations, each first run ending at the next run\'s decode time, and its sample entries', () => { + const [initialization, first, second] = skeletonPackets() + const moov = only(initialization, 'moov') + const defaults = readTrackDefaults(initialization, moov) + + expect(readTrackFragments(first, only(first, 'moof'), defaults)).toEqual([ + { baseMediaDecodeTime: 0n, duration: 62424n, trackId: 1 }, + { baseMediaDecodeTime: 0n, duration: 65536n, trackId: 2 }, + ]) + // The last runs have no next decode time: sixty video samples and sixty-two AAC frames, each at the 1024 its tfhd gives. + expect(readTrackFragments(second, only(second, 'moof'), defaults).map(({ duration }) => duration)).toEqual([60n * 1024n, 62n * 1024n]) + const [video, audio] = readTrackBoxes(initialization, moov) + + expect(readTrackBoxEntry(initialization, video)).toStrictEqual({ + codec: 'avc1.4d400a', + height: 36, + type: 'avc1', + width: 64, + }) + expect(readTrackBoxEntry(initialization, audio)).toStrictEqual({ codec: 'mp4a.40.2', type: 'mp4a' }) + }) + }) +}) diff --git a/src/lib/camera/mp4/mp4Boxes.ts b/src/lib/camera/mp4/mp4Boxes.ts new file mode 100644 index 000000000..83ff381e8 --- /dev/null +++ b/src/lib/camera/mp4/mp4Boxes.ts @@ -0,0 +1,1215 @@ +import type { Buffer } from 'node:buffer' + +// A box header: a 32-bit size and a four-character type, then, when the size reads 1, the size as 64 bits. +const HEADER_SIZE = 8 +export const LARGE_HEADER_SIZE = 16 + +/** + * One box of a buffer, read in place: its type and where it starts, where its payload starts and where it ends, each an offset into that buffer. + */ +export interface Mp4Box { + /** + * The box's four-character type. + */ + type: string + /** + * The offset of the box's first byte. + */ + start: number + /** + * The offset of the box's payload, past its header. + */ + payload: number + /** + * The offset just past the box's last byte. + */ + end: number +} + +/** + * A box's header, as its first octets give it before the rest of the box is read. + */ +export interface Mp4BoxHeader { + /** + * The box's four-character type. + */ + type: string + /** + * The octets the header takes: 16 when a 64-bit size follows the type, else 8. + */ + length: number + /** + * The size the header declares, its own octets included, absent for a box whose 32-bit size of 0 runs it to the end of what holds it. A 64-bit size reads + * exactly below 2^53 and, above it, still past any buffer's length. Every comparison with a length reads as the 64-bit size would. + */ + size?: number +} + +/** + * The boxes one walk read in order, and whether they span every byte the walk was given. + */ +export interface Mp4BoxWalk { + /** + * Each box read before the walk ended. + */ + boxes: Mp4Box[] + /** + * Whether every byte was read as a box. A size under its header's, a box running past the end, or a trailing fragment of a header ends the walk short. + */ + complete: boolean +} + +/** + * A track of an initialization segment, as its `trak` box describes it. + */ +export interface Mp4Track { + /** + * The track's identifier, from its `tkhd` box. + */ + id: number + /** + * The track's timescale in units per second, from its `mdhd` box. + */ + timescale: number + /** + * The track's handler type from its `hdlr` box, `vide` for video and `soun` for audio. + */ + handler: string +} + +/** + * A track of an initialization segment beside the `trak` box it was read from, which its sample entry and parameter sets are read from. + */ +export interface Mp4TrackBox { + /** + * The track, as its `trak` box describes it. + */ + track: Mp4Track + /** + * The `trak` box the track was read from. + */ + trak: Mp4Box +} + +/** + * A track's run of a media fragment, as its `traf` box describes it. + */ +export interface Mp4TrackFragment { + /** + * The identifier of the track the run belongs to, from its `tfhd` box. + */ + trackId: number + /** + * The decode time of the run's first sample in the track's timescale, from its `tfdt` box, when it has one. + */ + baseMediaDecodeTime?: bigint + /** + * The run's duration in the track's timescale, the sum of its samples' durations across its `trun` boxes, read whenever every sample's duration has a + * source: the sample's own, else the run's default from `tfhd`, else the track's default from `trex` when the caller passes the initialization + * segment's track defaults. + */ + duration?: bigint +} + +/** + * A track's first sample entry, as its `stsd` box describes it. + */ +export interface Mp4SampleEntry { + /** + * The entry's four-character type, like `avc1` or `mp4a`. + */ + type: string + /** + * A video entry's width in pixels. + */ + width?: number + /** + * A video entry's height in pixels. + */ + height?: number + /** + * The entry's codec as an RFC 6381 codecs parameter names it: an `avc1` entry's profile, compatibility and level from its `avcC` box, an `hvc1` or + * `hev1` entry's profile, compatibility, tier, level and constraints from its `hvcC` box as ISO/IEC 14496-15 writes them, an `mp4a` entry's MPEG-4 + * audio object type from its `esds` box, or an `Opus` entry's own type, which carries no parameters. Any other entry has none. + */ + codec?: string +} + +/** + * A sample's defaults, as a `trex` box gives them for every sample of its track or a `tfhd` box for every sample of its run, each absent where the box + * names none. + */ +export interface Mp4SampleDefaults { + /** + * The sample's duration in the track's timescale. + */ + duration?: number + /** + * The sample's size in octets. + */ + size?: number + /** + * The sample's flags, whose non-sync bit marks a sample that is no sync sample. + */ + flags?: number +} + +/** + * An HEVC sample entry's parameter sets, as its `hvcC` decoder configuration record holds them, and the octets each NAL unit's length takes in its samples. + */ +export interface Mp4ParameterSets { + /** + * The octets each NAL unit's length takes before the unit in a sample, from the record's length size field. + */ + nalLengthSize: number + /** + * The parameter sets in the record's order, each a view of the buffer holding the box: each array's units of an `hvcC` box. + */ + units: Buffer[] +} + +/** + * One sample of a track's run, as a fragment's `trun` box and the defaults behind it describe it. + */ +export interface Mp4Sample { + /** + * The offset of the sample's first octet from the first octet of the `moof` box describing it. + */ + offset: number + /** + * The sample's size in octets. + */ + size: number + /** + * The sample's decode time in the track's timescale. + */ + decodeTime: bigint + /** + * The sample's duration in the track's timescale, its own in its `trun`, else its run's default in `tfhd`, else its track's in `trex`, absent when none + * of them states one. + */ + duration?: number + /** + * The time from the sample's decode time to its presentation in the track's timescale, unsigned in a version 0 `trun` and signed in version 1. + */ + compositionOffset: number + /** + * Whether the sample is a sync sample, one decoded with nothing before it: its flags' non-sync bit is clear. + */ + sync: boolean +} + +/** + * What the sample reader takes beside a `moof` box: the track whose samples it reads, the defaults its initialization segment gives, the decode time its + * fragments so far end at, and the most of the track's samples one fragment may hold. + */ +export interface Mp4SampleOptions { + /** + * The identifier of the track whose samples are read. + */ + trackId: number + /** + * Each track's defaults, as {@link readSampleDefaults} reads them, the last source of a sample's size, duration and flags, after the sample's own and the + * run's `tfhd` default. Another track's sizes place a run that follows its data. + */ + defaults?: ReadonlyMap + /** + * The decode time the track's last run ended at, which a `traf` with no `tfdt` continues from. + */ + decodeTime?: bigint + /** + * Reads a version 0 `tfdt`'s decode time, a 32-bit counter, on the track's own timeline, for a caller that carries the counter on across its wrap. A + * version 1 `tfdt`'s 64 bits are read as they stand, and without this a version 0 one's are too. + */ + counter?: (value: bigint) => bigint + /** + * The most samples of the track one fragment may hold, counted across every `traf` and `trun` of the track in the box. A run that would take the + * track's samples past it is refused before any of its samples is read. + */ + limit: number +} + +/** + * What the parameter set reader takes beside a track's `trak` box: the octets its caller puts before each set and the most octets the sets may take with their lengths, + * the bound the caller puts on what it copies the sets into. + */ +export interface Mp4ParameterSetOptions { + /** + * The octets of the length the caller puts before each set. + */ + lengthSize: number + /** + * The most octets the sets may take, each behind its length. A record whose sets pass it is refused as the set that passes it is read, before any set + * after it is. + */ + limit: number +} + +/** + * A track's samples in one `moof` box, and the decode time they end at. + */ +export interface Mp4TrackSamples { + /** + * The track's samples in the box's order. + */ + samples: Mp4Sample[] + /** + * The decode time the track's last sample ends at, which the next fragment's runs continue from: the decode time handed in for a box holding none of + * the track's samples, and absent when the last sample's duration has no source. + */ + decodeTime?: bigint +} + +// The trun flags of the fields a run carries before its samples, and of each field a sample carries, in the order a sample holds them. +const TRUN_DATA_OFFSET = 0x1 +const TRUN_FIRST_SAMPLE_FLAGS = 0x4 +const TRUN_SAMPLE_DURATION = 0x100 +const TRUN_SAMPLE_SIZE = 0x200 +const TRUN_SAMPLE_FLAGS = 0x400 +const TRUN_SAMPLE_COMPOSITION_OFFSET = 0x800 +const TRUN_SAMPLE_FIELDS = [ + TRUN_SAMPLE_DURATION, + TRUN_SAMPLE_SIZE, + TRUN_SAMPLE_FLAGS, + TRUN_SAMPLE_COMPOSITION_OFFSET, +] as const + +// The tfhd flags of the fields after its track ID, each beside the octets it takes, in the order the box holds them, and of the base its runs count from. +const TFHD_BASE_DATA_OFFSET = 0x1 +const TFHD_SAMPLE_DESCRIPTION_INDEX = 0x2 +const TFHD_DEFAULT_SAMPLE_DURATION = 0x8 +const TFHD_DEFAULT_SAMPLE_SIZE = 0x10 +const TFHD_DEFAULT_SAMPLE_FLAGS = 0x20 +const TFHD_FIELDS = [ + [TFHD_BASE_DATA_OFFSET, 8], + [TFHD_SAMPLE_DESCRIPTION_INDEX, 4], + [TFHD_DEFAULT_SAMPLE_DURATION, 4], + [TFHD_DEFAULT_SAMPLE_SIZE, 4], + [TFHD_DEFAULT_SAMPLE_FLAGS, 4], +] as const +const TFHD_DEFAULT_BASE_IS_MOOF = 0x20000 + +// The bit of a sample's flags that marks it as no sync sample, which ISO/IEC 14496-12 calls sample_is_non_sync_sample. +const SAMPLE_IS_NON_SYNC = 0x10000 + +// The refusal of a fragment whose runs count their data from an absolute place in a file, which a stream's reader has no file offsets to resolve. +const ABSOLUTE_DATA_OFFSET = 'An MP4 fragment places its data by an absolute file offset, which a stream cannot follow, and ffmpeg writes the layout a ' + + 'stream needs under its default_base_moof muxer flag.' + +// The octets an hvcC record holds before its parameter sets, through its count of arrays, as ISO/IEC 14496-15 lays them out. +const HVCC_FIXED_FIELDS = 23 + +// The fixed fields of a video and of an audio sample entry, before the boxes it holds. +const VISUAL_ENTRY_FIELDS = 78 +const AUDIO_ENTRY_FIELDS = 28 + +// The sample entry types an hvcC box describes, the bytes of a version 1 hvcC through its level, and the letter each profile space writes before its profile. +const HEVC_ENTRY_TYPES: ReadonlySet = new Set(['hev1', 'hvc1']) +const HVCC_CODEC_FIELDS = 13 +const HEVC_PROFILE_SPACES = ['', 'A', 'B', 'C'] as const + +// The esds descriptor tags the audio object type is read through, and the object type indication of MPEG-4 audio. +const ES_DESCRIPTOR = 0x03 +const DECODER_CONFIG_DESCRIPTOR = 0x04 +const DECODER_SPECIFIC_INFO = 0x05 +const MPEG4_AUDIO = 0x40 + +/** + * Walks the boxes laid end to end in a buffer, or in one stretch of it. + * @param data - The buffer. + * @param start - The offset the walk starts at. + * @param end - The offset the walk ends at. + * @returns The boxes read, and whether they span the stretch. + */ +export function walkBoxes(data: Buffer, start = 0, end = data.length): Mp4BoxWalk { + const boxes: Mp4Box[] = [] + let offset = start + + while (offset < end) { + const remaining = end - offset + const header = readBoxHeader(data, offset, end) + + if (header === undefined) { + return { boxes, complete: false } + } + + const size = header.size ?? remaining + + if (size < header.length || size > remaining) { + return { boxes, complete: false } + } + + boxes.push({ + end: offset + size, + payload: offset + header.length, + start: offset, + type: header.type, + }) + offset += size + } + + return { boxes, complete: true } +} + +/** + * Reads the header of the box at an offset, before the rest of the box is read: a 32-bit size and a four-character type, then, when the size reads 1, the + * size as 64 bits. + * @param data - The buffer. + * @param start - The offset of the box's first octet. + * @param end - The offset past the last octet the buffer holds of it. + * @returns The header, or `undefined` when the stretch ends inside it. + */ +export function readBoxHeader(data: Buffer, start = 0, end = data.length): Mp4BoxHeader | undefined { + if (end - start < HEADER_SIZE) { + return undefined + } + + const declared = data.readUInt32BE(start) + const type = data.toString('latin1', start + 4, start + HEADER_SIZE) + + switch (declared) { + case 0: + return { length: HEADER_SIZE, type } + + case 1: + return end - start < LARGE_HEADER_SIZE + ? undefined + : { + length: LARGE_HEADER_SIZE, + size: Number(data.readBigUInt64BE(start + HEADER_SIZE)), + type, + } + + default: + return { length: HEADER_SIZE, size: declared, type } + } +} + +// The child boxes of a box, which must span its payload. +function childrenOf(data: Buffer, box: Mp4Box): Mp4Box[] { + const walk = walkBoxes(data, box.payload, box.end) + + if (!walk.complete) { + throw new RangeError(`An MP4 ${box.type} box holds a malformed box.`) + } + + return walk.boxes +} + +// The one child of a type a box must hold. +function childOf(data: Buffer, box: Mp4Box, type: string, children = childrenOf(data, box)): Mp4Box { + const child = children.find(candidate => candidate.type === type) + + if (child === undefined) { + throw new RangeError(`An MP4 ${box.type} box holds no ${type} box.`) + } + + 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 } { + if (box.end - box.payload < 4) { + throw new RangeError(`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.`) + } + + if (box.end - box.payload - 4 < lengths[version]) { + throw new RangeError(`An MP4 ${box.type} box is too short for its fields.`) + } + + return { offset: box.payload + 4, version } +} + +// 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) +} + +// The offset past a full box's creation and modification times, 32 bits each in version 0 and 64 bits each in version 1. +function pastTimes({ offset, version }: { offset: number, version: 0 | 1 }): number { + return version === 1 + ? offset + 16 + : offset + 8 +} + +// A track's identifier, timescale and handler type, from its trak's tkhd, mdia/mdhd and mdia/hdlr. +function readTrack(data: Buffer, trak: Mp4Box): Mp4Track { + // A tkhd's track ID and an mdhd's timescale each follow the box's two times. + const tkhd = fieldsOf(data, childOf(data, trak, 'tkhd'), [12, 20]) + const mdia = childOf(data, trak, 'mdia') + const mdhd = fieldsOf(data, childOf(data, mdia, 'mdhd'), [12, 20]) + // An hdlr's handler type follows 32 bits of pre-definition, the same in either version. + const hdlr = fieldsOf(data, childOf(data, mdia, 'hdlr'), [8, 8]) + + return { + handler: data.toString('latin1', hdlr.offset + 4, hdlr.offset + 8), + id: data.readUInt32BE(pastTimes(tkhd)), + timescale: data.readUInt32BE(pastTimes(mdhd)), + } +} + +/** + * Reads each track of a `moov` box once, its identifier, timescale and handler type from `tkhd`, `mdia`/`mdhd` and `mdia`/`hdlr`, versions 0 and 1, beside + * the `trak` box it came from: its sample entry and parameter sets are read from that box alone, a track whose identifier an earlier track carries among + * them. + * @param data - The buffer holding the box. + * @param moov - The `moov` box. + * @returns The tracks and their `trak` boxes in order. + * @throws RangeError for a malformed box, a box missing or a version past 1. + */ +export function readTrackBoxes(data: Buffer, moov: Mp4Box): Mp4TrackBox[] { + return childrenOf(data, moov).filter(box => box.type === 'trak').map(trak => ({ + track: readTrack(data, trak), + trak, + })) +} + +/** + * Reads each track's default sample duration from a `moov` box's `mvex`/`trex` boxes, which a fragmented file's runs fall back on. + * @param data - The buffer holding the box. + * @param moov - The `moov` box. + * @returns Each default sample duration by track identifier, none when the box holds no `mvex`. + * @throws RangeError for a malformed box or a `trex` too short for its fields. + */ +export function readTrackDefaults(data: Buffer, moov: Mp4Box): Map { + return new Map(Array.from(trackExtendsOf(data, moov), ([trackId, { duration }]) => [trackId, duration])) +} + +/** + * Reads each track's sample defaults from a `moov` box's `mvex`/`trex` boxes, which a fragmented file's samples fall back on: the default duration, and + * the default size and flags a `trex` long enough for them holds. + * @param data - The buffer holding the box. + * @param moov - The `moov` box. + * @returns Each track's defaults by track identifier, none when the box holds no `mvex`. + * @throws RangeError for a malformed box or a `trex` too short for its default duration. + */ +export function readSampleDefaults(data: Buffer, moov: Mp4Box): Map { + return trackExtendsOf(data, moov) +} + +// A track's defaults as its trex gives them, every trex holding a default duration. +type TrackExtends = Mp4SampleDefaults & { duration: number } + +/* Each trex of a moov's mvex, by track identifier: the one parse of the box, which every reader of the track defaults answers from. A trex holds the track + * ID and the default sample description index before the default sample duration, size and flags. One too short for its duration is refused, and one too + * short for its size or its flags names none. + */ +function trackExtendsOf(data: Buffer, moov: Mp4Box): Map { + const defaults = new Map() + const mvex = childrenOf(data, moov).find(box => box.type === 'mvex') + + if (mvex === undefined) { + return defaults + } + + for (const trex of childrenOf(data, mvex).filter(box => box.type === 'trex')) { + const { offset } = fieldsOf(data, trex, [12, 12]) + const track: TrackExtends = { + duration: data.readUInt32BE(offset + 8), + } + + if (trex.end - offset >= 16) { + track.size = data.readUInt32BE(offset + 12) + } + + if (trex.end - offset >= 20) { + track.flags = data.readUInt32BE(offset + 16) + } + + defaults.set(data.readUInt32BE(offset), track) + } + + return defaults +} + +// One byte of an esds box, refused at or past the end of the descriptor holding it. +function esdsByte(data: Buffer, at: number, end: number): number { + if (at >= end) { + throw new RangeError('An MP4 esds box is too short for its fields.') + } + + return data.readUInt8(at) +} + +// One descriptor of an esds box: its tag, then its length in up to four bytes of seven bits each, a set high bit saying another byte follows. +function readDescriptor(data: Buffer, start: number, end: number): Mp4Box & { tag: number } { + const tag = esdsByte(data, start, end) + let cursor = start + 1 + let length = 0 + + for (let read = 0; read < 4; read++) { + const byte = esdsByte(data, cursor++, end) + + length = (length << 7) | (byte & 0x7F) + + if ((byte & 0x80) === 0) { + break + } + } + + if (cursor + length > end) { + throw new RangeError('An MP4 esds box is too short for its fields.') + } + + return { + end: cursor + length, + payload: cursor, + start, + tag, + type: 'esds', + } +} + +/* An mp4a entry's codec from its esds box. The ES descriptor holds its flags' optional fields, then the decoder config descriptor, whose object type + * indication names MPEG-4 audio and whose decoder specific info opens with the audio object type: five bits, or 32 plus the next six when those read 31. + */ +function audioCodecOf(data: Buffer, esds: Mp4Box): string | undefined { + const { offset } = fieldsOf(data, esds, [0, 0]) + const es = readDescriptor(data, offset, esds.end) + + if (es.tag !== ES_DESCRIPTOR) { + return undefined + } + + // The ES ID, then the flags naming a dependency's ES ID, a URL and an OCR ES ID. + const flags = esdsByte(data, es.payload + 2, es.end) + let cursor = es.payload + 3 + + cursor += (flags & 0x80) === 0 + ? 0 + : 2 + cursor += (flags & 0x40) === 0 + ? 0 + : 1 + esdsByte(data, cursor, es.end) + cursor += (flags & 0x20) === 0 + ? 0 + : 2 + + const config = readDescriptor(data, cursor, es.end) + + // The object type indication, then the stream type, buffer size and two bitrates, before the decoder specific info. + if (config.tag !== DECODER_CONFIG_DESCRIPTOR || esdsByte(data, config.payload, config.end) !== MPEG4_AUDIO) { + return undefined + } + + const info = readDescriptor(data, config.payload + 13, config.end) + + if (info.tag !== DECODER_SPECIFIC_INFO) { + return undefined + } + + const audioObjectType = esdsByte(data, info.payload, info.end) >> 3 + + if (audioObjectType !== 31) { + return `mp4a.40.${audioObjectType}` + } + + const word = (esdsByte(data, info.payload, info.end) << 8) | esdsByte(data, info.payload + 1, info.end) + + return `mp4a.40.${32 + ((word >> 5) & 0x3F)}` +} + +// A codec's byte as the two lowercase hexadecimal digits RFC 6381 writes. +function hexByte(value: number): string { + return value.toString(16).padStart(2, '0') +} + +/* An hvc1 or hev1 entry's codec from its hvcC box, as ISO/IEC 14496-15 Annex E.3 writes it: the entry's type; the profile space's letter, none for space 0, + * before the profile in decimal; the 32 compatibility flags in reversed bit order, in hexadecimal with leading zeros dropped; L for the main tier or H for + * the high one before the level in decimal; and each constraint byte in hexadecimal, trailing zero bytes dropped. A version 1 record holds the + * configuration version, then one byte of profile space, tier and profile, four of compatibility flags, six of constraints and one of level. A record of + * another version has a layout this reader does not know, which is why it names no codec. + */ +function hevcCodecOf(data: Buffer, hvcC: Mp4Box, type: string): string | undefined { + const length = hvcC.end - hvcC.payload + + if (length > 0 && data.readUInt8(hvcC.payload) !== 1) { + return undefined + } + + if (length < HVCC_CODEC_FIELDS) { + throw new RangeError('An MP4 hvcC box is too short for its fields.') + } + + const profile = data.readUInt8(hvcC.payload + 1) + const compatibility = data.readUInt32BE(hvcC.payload + 2) + const tier = (profile & 0x20) === 0 + ? 'L' + : 'H' + const constraints = Array.from(data.subarray(hvcC.payload + 6, hvcC.payload + 12)) + let reversed = 0 + + for (let bit = 0; bit < 32; bit++) { + reversed = (reversed << 1) | ((compatibility >>> bit) & 1) + } + + while (constraints.at(-1) === 0) { + constraints.pop() + } + + return [ + type, + `${HEVC_PROFILE_SPACES[profile >> 6]}${profile & 0x1F}`, + (reversed >>> 0).toString(16), + `${tier}${data.readUInt8(hvcC.payload + 12)}`, + ...constraints.map(hexByte), + ].join('.') +} + +/** + * Reads one track's first sample entry from its own `trak` box's `mdia`/`minf`/`stbl`/`stsd`: its type, a video entry's size, and an `avc1`, `hvc1`, + * `hev1`, `mp4a` or `Opus` entry's codec. + * @param data - The buffer holding the box. + * @param trackBox - The track and its `trak` box, as {@link readTrackBoxes} reads them. + * @returns The entry, or `undefined` when the track holds no entry. + * @throws RangeError for a malformed box, a box missing, a version past 1 or an entry too short for its fields. + */ +export function readTrackBoxEntry(data: Buffer, trackBox: Mp4TrackBox): Mp4SampleEntry | undefined { + const found = sampleEntryOf(data, trackBox) + + if (found === undefined) { + return undefined + } + + const { children, entry, handler } = found + const sampleEntry: Mp4SampleEntry = { type: entry.type } + + // A video entry's width and height follow its eight bytes of sample entry and sixteen of pre-definition. + if (handler === 'vide') { + sampleEntry.width = data.readUInt16BE(entry.payload + 24) + sampleEntry.height = data.readUInt16BE(entry.payload + 26) + } + + const avcC = entry.type === 'avc1' + ? children.find(box => box.type === 'avcC') + : undefined + const hvcC = HEVC_ENTRY_TYPES.has(entry.type) + ? children.find(box => box.type === 'hvcC') + : undefined + const esds = entry.type === 'mp4a' + ? children.find(box => box.type === 'esds') + : undefined + + // An avcC's configuration version comes before its profile, compatibility and level. + if (avcC !== undefined) { + if (avcC.end - avcC.payload < 4) { + throw new RangeError('An MP4 avcC box is too short for its fields.') + } + + sampleEntry.codec = `avc1.${[1, 2, 3].map(at => hexByte(data.readUInt8(avcC.payload + at))).join('')}` + } + + if (hvcC !== undefined) { + const codec = hevcCodecOf(data, hvcC, entry.type) + + if (codec !== undefined) { + sampleEntry.codec = codec + } + } + + if (esds !== undefined) { + const codec = audioCodecOf(data, esds) + + if (codec !== undefined) { + sampleEntry.codec = codec + } + } + + // An Opus entry's codec is its four-character type, the name the MP4 registration authority gives it and RFC 6381 reads case sensitively. + if (entry.type === 'Opus') { + sampleEntry.codec = entry.type + } + + return sampleEntry +} + +/** + * Reads one track's first sample entry whole from its own `trak` box's `mdia`/`minf`/`stbl`/`stsd`: the entry box's octets, its header, its fields and the + * boxes it holds, as a view of the buffer holding the box. + * @param data - The buffer holding the box. + * @param trackBox - The track and its `trak` box, as {@link readTrackBoxes} reads them. + * @returns The entry's octets, or `undefined` when the track holds no entry. + * @throws RangeError for a malformed box, a box missing, a version past 1 or an entry too short for its fields. + */ +export function readTrackBoxEntryBytes(data: Buffer, trackBox: Mp4TrackBox): Buffer | undefined { + const found = sampleEntryOf(data, trackBox) + + return found === undefined + ? undefined + : data.subarray(found.entry.start, found.entry.end) +} + +/** + * The boxes a sample entry holds past its fields, a picture's `hvcC` or a sound's `dOps` among them, read from an entry {@link readTrackBoxEntryBytes} + * answered, whose header and fields it has read whole. + * @param entry - The sample entry whole, its header, its fields and the boxes it holds. + * @param medium - The entry's medium, which sets its fields: a visual entry's for a picture and an audio entry's for a sound. + * @returns The boxes the entry holds, each placed in the entry. + */ +export function readSampleEntryBoxes(entry: Buffer, medium: 'audio' | 'video'): Mp4Box[] { + const fields = medium === 'video' + ? VISUAL_ENTRY_FIELDS + : AUDIO_ENTRY_FIELDS + + return walkBoxes(entry, readBoxHeader(entry)!.length + fields).boxes +} + +// A track's first sample entry from its trak's mdia/minf/stbl/stsd, its track's handler type, which sets the entry's fields, and the boxes the entry holds +// past them, or undefined when the track holds no entry. +function sampleEntryOf(data: Buffer, { trak, track: { handler } }: Mp4TrackBox): { children: Mp4Box[], entry: Mp4Box, handler: string } | undefined { + const stbl = childOf(data, childOf(data, childOf(data, trak, 'mdia'), 'minf'), 'stbl') + const stsdBox = childOf(data, stbl, 'stsd') + // An stsd's entry count comes before its entries. + const stsd = fieldsOf(data, stsdBox, [4, 4]) + const [entry] = childrenOf(data, { ...stsdBox, payload: stsd.offset + 4 }) + + if (entry === undefined) { + return undefined + } + + const fields = handler === 'vide' + ? VISUAL_ENTRY_FIELDS + : AUDIO_ENTRY_FIELDS + + if (entry.end - entry.payload < fields) { + throw new RangeError(`An MP4 ${entry.type} box is too short for its fields.`) + } + + return { + children: childrenOf(data, { ...entry, payload: entry.payload + fields }), + entry, + handler, + } +} + +// The parameter sets a record's walk has read so far, the octets they take behind the caller's lengths, and the caller's bound on those octets. +interface ParameterSetWalk { + readonly options: Mp4ParameterSetOptions + readonly units: Buffer[] + taken: number +} + +/* A decoder configuration record's NAL units from a cursor on, each behind its 16-bit length, refused when the record ends before the units it announces. + * Each unit's octets behind the caller's length count against the caller's bound as its length is read. A record past the bound is refused at the unit + * that passes it, before any unit after it is built, however many more it announces. + */ +function parameterSetsOf(data: Buffer, record: Mp4Box, cursor: number, count: number, walk: ParameterSetWalk): number { + const { options: { lengthSize, limit }, units } = walk + let at = cursor + + for (let unit = 0; unit < count; unit++) { + if (at + 2 > record.end) { + throw new RangeError(`An MP4 ${record.type} box is too short for the parameter sets it announces.`) + } + + const length = data.readUInt16BE(at) + + walk.taken += lengthSize + length + + if (walk.taken > limit) { + throw new RangeError(`An MP4 ${record.type} box holds parameter sets that take more than the ${limit} octets its reader puts in a keyframe.`) + } + + if (at + 2 + length > record.end) { + throw new RangeError(`An MP4 ${record.type} box is too short for the parameter sets it announces.`) + } + + units.push(data.subarray(at + 2, at + 2 + length)) + at += 2 + length + } + + return at +} + +// An hvcC record's fixed fields, refused when it is too short for them, and its configuration version, which comes first, refused when it is not 1, the +// one version whose layout ISO/IEC 14496-15 defines. +function checkRecord(data: Buffer, record: Mp4Box): void { + if (record.end - record.payload < HVCC_FIXED_FIELDS) { + throw new RangeError(`An MP4 ${record.type} box is too short for its fields.`) + } + + const version = data.readUInt8(record.payload) + + if (version !== 1) { + throw new RangeError(`An MP4 ${record.type} box has version ${version}, which the library does not read.`) + } +} + +/* An hvcC's parameter sets. Its fixed fields end in a byte whose low two bits hold the length size less one and a byte counting its arrays, and each array + * opens with a byte naming its NAL unit type and two counting its units. + */ +function hevcParameterSetsOf(data: Buffer, hvcC: Mp4Box, options: Mp4ParameterSetOptions): Mp4ParameterSets { + checkRecord(data, hvcC) + + const walk: ParameterSetWalk = { options, taken: 0, units: [] } + let cursor = hvcC.payload + HVCC_FIXED_FIELDS + + for (let array = 0, arrays = data.readUInt8(hvcC.payload + 22); array < arrays; array++) { + if (cursor + 3 > hvcC.end) { + throw new RangeError('An MP4 hvcC box is too short for the parameter sets it announces.') + } + + cursor = parameterSetsOf(data, hvcC, cursor + 3, data.readUInt16BE(cursor + 1), walk) + } + + return { nalLengthSize: (data.readUInt8(hvcC.payload + 21) & 0x03) + 1, units: walk.units } +} + +/** + * Reads one HEVC video track's parameter sets and NAL length size from its own `trak` box's first sample entry, an `hvc1` or `hev1` entry's `hvcC`, each + * array's units in the record's order, within the caller's bound on the octets they take behind its lengths. + * @param data - The buffer holding the box. + * @param trackBox - The track and its `trak` box, as {@link readTrackBoxes} reads them. + * @param options - The length the caller puts before each set, and the most octets the sets may take behind it. + * @returns The parameter sets, or `undefined` when the track holds no entry or an entry of any other type than `hvc1` and `hev1`, an `avc1` entry's + * among them. + * @throws RangeError for a malformed box, a box missing, a record of a version other than 1, a record too short for its fields or for the parameter sets + * it announces, or a record whose sets pass the caller's bound. + */ +export function readTrackBoxParameterSets(data: Buffer, trackBox: Mp4TrackBox, options: Mp4ParameterSetOptions): Mp4ParameterSets | undefined { + const found = sampleEntryOf(data, trackBox) + + if ((found === undefined) || !HEVC_ENTRY_TYPES.has(found.entry.type)) { + return undefined + } + + const { children, entry } = found + + return hevcParameterSetsOf(data, childOf(data, entry, 'hvcC', children), options) +} + +/** + * Picks the video track of a `moov` box's tracks: the first track whose handler is `vide`, read as no video track when its timescale is 0, which times + * nothing. + * @param trackBoxes - The tracks and their `trak` boxes, as {@link readTrackBoxes} reads them. + * @returns The video track and its `trak` box, or `undefined` when the tracks hold none. + */ +export function readVideoTrackBox(trackBoxes: readonly Mp4TrackBox[]): Mp4TrackBox | undefined { + const video = trackBoxes.find(({ track }) => track.handler === 'vide') + + return video?.track.timescale === 0 + ? undefined + : video +} + +// A tfhd's 32-bit default its flags name, after the track ID and each field before it the flags name, refused when the box is too short for it, or +// undefined when the flags name none. +function runDefault(data: Buffer, tfhd: Mp4Box, field: number): number | undefined { + const flags = flagsOf(data, tfhd) + + if ((flags & field) === 0) { + return undefined + } + + let before = 4 + + for (const [flag, octets] of TFHD_FIELDS) { + if (flag === field) { + break + } + + if ((flags & flag) !== 0) { + before += octets + } + } + + const { offset } = fieldsOf(data, tfhd, [before + 4, before + 4]) + + return data.readUInt32BE(offset + before) +} + +// A tfdt's base decode time, 64 bits in version 1, and in version 0 a 32-bit counter, read on a caller's timeline where it gives one. +function decodeTimeOf(data: Buffer, tfdtBox: Mp4Box, counter?: (value: bigint) => bigint): bigint { + const tfdt = fieldsOf(data, tfdtBox, [4, 8]) + + if (tfdt.version === 1) { + return data.readBigUInt64BE(tfdt.offset) + } + + const value = BigInt(data.readUInt32BE(tfdt.offset)) + + return counter?.(value) ?? value +} + +// A trun's samples as its fields lay them out: their count, the data offset and first sample flags the run carries, where the first sample's fields start, +// the octets each sample's fields take, and where among them each field the samples carry sits, by its flag. +interface TrackRun { + count: number + dataOffset?: number + firstSampleFlags?: number + samples: number + stride: number + fields: ReadonlyMap + version: 0 | 1 +} + +/* The one walk of a trun's fields, which every reader of a run's samples takes. A run is read only once its length is known to hold the sample count its + * fields say: a count no box can hold is refused before any sample is read. The data offset is signed, as ISO/IEC 14496-12 writes it. + */ +function trackRunOf(data: Buffer, trun: Mp4Box): TrackRun { + const { offset, version } = fieldsOf(data, trun, [4, 4]) + const flags = flagsOf(data, trun) + const count = data.readUInt32BE(offset) + const leading = ((flags & TRUN_DATA_OFFSET) === 0 + ? 0 + : 4) + ((flags & TRUN_FIRST_SAMPLE_FLAGS) === 0 + ? 0 + : 4) + const fields = new Map() + let stride = 0 + + for (const field of TRUN_SAMPLE_FIELDS) { + if ((flags & field) !== 0) { + fields.set(field, stride) + stride += 4 + } + } + + fieldsOf(data, trun, [4 + leading + count * stride, 4 + leading + count * stride]) + + const run: TrackRun = { + count, + fields, + samples: offset + 4 + leading, + stride, + version, + } + let cursor = offset + 4 + + if ((flags & TRUN_DATA_OFFSET) !== 0) { + run.dataOffset = data.readInt32BE(cursor) + cursor += 4 + } + + if ((flags & TRUN_FIRST_SAMPLE_FLAGS) !== 0) { + run.firstSampleFlags = data.readUInt32BE(cursor) + } + + return run +} + +// A field of one of a run's samples, or undefined when the run's samples carry no such field. A composition offset is unsigned in a version 0 trun and +// signed in version 1. +function sampleField(data: Buffer, run: TrackRun, sample: number, field: (typeof TRUN_SAMPLE_FIELDS)[number]): number | undefined { + const at = run.fields.get(field) + + if (at === undefined) { + return undefined + } + + const offset = run.samples + (sample * run.stride) + at + + return (field === TRUN_SAMPLE_COMPOSITION_OFFSET) && (run.version === 1) + ? data.readInt32BE(offset) + : data.readUInt32BE(offset) +} + +/* A run's duration: the sum of its samples' durations across its trun boxes, each sample's own when a trun carries them, else the default the run or its + * track gives. A run with no trun, or a sample whose duration has no source, has none. + */ +function runDuration(data: Buffer, children: readonly Mp4Box[], tfhd: Mp4Box, trackDefault: number | undefined): bigint | undefined { + const truns = children.filter(box => box.type === 'trun') + + if (truns.length === 0) { + return undefined + } + + const fallback = runDefault(data, tfhd, TFHD_DEFAULT_SAMPLE_DURATION) ?? trackDefault + let duration = 0n + + for (const trun of truns) { + const run = trackRunOf(data, trun) + + if (run.fields.has(TRUN_SAMPLE_DURATION)) { + for (let sample = 0; sample < run.count; sample++) { + duration += BigInt(sampleField(data, run, sample, TRUN_SAMPLE_DURATION)!) + } + } else if (fallback === undefined) { + return undefined + } else { + duration += BigInt(run.count) * BigInt(fallback) + } + } + + return duration +} + +/** + * Reads each track's run of a `moof` box: its track identifier from `tfhd`, its base decode time from `tfdt`, versions 0 and 1, and its duration from its + * `trun` boxes wherever its samples' durations have a source. + * @param data - The buffer holding the box. + * @param moof - The `moof` box. + * @param trackDefaults - Each track's default sample duration, as {@link readTrackDefaults} reads them, the last source of a sample's duration, after the + * sample's own and the run's `tfhd` default; without them a run whose samples carry neither has no duration. + * @returns The runs in order. + * @throws RangeError for a malformed box, a `traf` without `tfhd`, a version past 1 or a box too short for its fields. + */ +export function readTrackFragments(data: Buffer, moof: Mp4Box, trackDefaults?: ReadonlyMap): Mp4TrackFragment[] { + return childrenOf(data, moof).filter(box => box.type === 'traf').map((traf) => { + const children = childrenOf(data, traf) + const tfhdBox = childOf(data, traf, 'tfhd', children) + const tfhd = fieldsOf(data, tfhdBox, [4, 4]) + const run: Mp4TrackFragment = { + trackId: data.readUInt32BE(tfhd.offset), + } + const tfdtBox = children.find(box => box.type === 'tfdt') + + if (tfdtBox !== undefined) { + run.baseMediaDecodeTime = decodeTimeOf(data, tfdtBox) + } + + const duration = runDuration(data, children, tfhdBox, trackDefaults?.get(run.trackId)) + + if (duration !== undefined) { + run.duration = duration + } + + return run + }) +} + +/** + * 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 + * the track's in `trex`, and a run's first sample takes its `trun`'s first sample flags when the run carries them. Flags with no source read as zero, and + * a sample is a sync sample when their non-sync bit is clear. + * + * A `traf` counts its data from the `moof` box's first octet when its `tfhd` says so or it is the box's first, and otherwise from where the previous + * `traf`'s data ends, which another track's sizes place. A `trun` starts its data at its data offset from that base, and one with no data offset follows + * the `trun` before it, or starts at the base when it is the first. A `traf` with a `tfdt` starts its decode times there, a version 0 one's 32-bit counter + * read on the caller's timeline where it gives one, and one with none continues from the track's previous run, in the box or before it. + * @param data - The buffer holding the box. + * @param moof - The `moof` box. + * @param options - The track, its defaults, the decode time it continues from, the reading of a 32-bit decode time, and the most of its samples one + * fragment may hold. + * @returns The track's samples in order, and the decode time they end at. + * @throws RangeError for a malformed box, a `traf` without `tfhd`, a version past 1, a box too short for its fields, a `tfhd` naming a base data offset of + * its own, a sample with no size, a sample whose decode time has no source, or more samples of the track than the limit. + */ +export function readTrackSamples(data: Buffer, moof: Mp4Box, options: Mp4SampleOptions): Mp4TrackSamples { + const { defaults, limit, trackId } = options + const samples: Mp4Sample[] = [] + // The decode time the track's next sample takes, undefined while it has no source. + let time = options.decodeTime + // Where the previous traf's data ends, from the moof's first octet, undefined when a size placing it has no source. It starts at the moof's first octet, + // which the first traf counts from. + let previousEnd: number | undefined = 0 + + for (const traf of childrenOf(data, moof).filter(box => box.type === 'traf')) { + const children = childrenOf(data, traf) + const tfhd = childOf(data, traf, 'tfhd', children) + const { offset } = fieldsOf(data, tfhd, [4, 4]) + const flags = flagsOf(data, tfhd) + + if ((flags & TFHD_BASE_DATA_OFFSET) !== 0) { + throw new RangeError(ABSOLUTE_DATA_OFFSET) + } + + const id = data.readUInt32BE(offset) + const own = id === trackId + const base: number | undefined = (flags & TFHD_DEFAULT_BASE_IS_MOOF) !== 0 + ? 0 + : previousEnd + + // A traf whose base follows data no size places has no place of its own, which only the track's own samples need. + if (base === undefined) { + if (own) { + throw new RangeError('An MP4 traf box follows a run whose sample sizes have no source.') + } + + continue + } + + const tfdt = children.find(box => box.type === 'tfdt') + + if (own && (tfdt !== undefined)) { + time = decodeTimeOf(data, tfdt, options.counter) + } + + const runDefaults: Mp4SampleDefaults = { + duration: runDefault(data, tfhd, TFHD_DEFAULT_SAMPLE_DURATION), + flags: runDefault(data, tfhd, TFHD_DEFAULT_SAMPLE_FLAGS), + size: runDefault(data, tfhd, TFHD_DEFAULT_SAMPLE_SIZE), + } + const trackDefaults = defaults?.get(id) + let position: number | undefined = base + + for (const trun of children.filter(box => box.type === 'trun')) { + const layout = trackRunOf(data, trun) + + if (own && ((samples.length + layout.count) > limit)) { + throw new RangeError(`An MP4 fragment holds more samples of a track than the ${limit} its reader takes from one fragment.`) + } + + if (layout.dataOffset !== undefined) { + position = base + layout.dataOffset + } + + // Another track's run whose samples carry no size of their own gives each the one size its tfhd or its track's trex gives: its data is its count + // times that size, placed with no walk. A run holding samples whose size has no source leaves what follows it unplaced, and a run of none holds no data. + if (!own && !layout.fields.has(TRUN_SAMPLE_SIZE)) { + const size = runDefaults.size ?? trackDefaults?.size + + if ((position !== undefined) && (layout.count > 0)) { + position = size === undefined + ? undefined + : position + (layout.count * size) + } + + continue + } + + for (let sample = 0; (sample < layout.count) && (position !== undefined); sample++) { + const size = sampleField(data, layout, sample, TRUN_SAMPLE_SIZE) ?? runDefaults.size ?? trackDefaults?.size + + if (size === undefined) { + throw new RangeError('An MP4 trun box holds a sample with no size.') + } + + if (own) { + if (time === undefined) { + throw new RangeError('An MP4 fragment holds a sample whose decode time has no source, neither a tfdt box nor the duration of the sample before it.') + } + + // A run's first sample takes the run's first sample flags over every other source of its flags. + const first = sample === 0 + ? layout.firstSampleFlags + : undefined + const duration = sampleField(data, layout, sample, TRUN_SAMPLE_DURATION) ?? runDefaults.duration ?? trackDefaults?.duration + const sampleFlags = first ?? sampleField(data, layout, sample, TRUN_SAMPLE_FLAGS) ?? runDefaults.flags ?? trackDefaults?.flags ?? 0 + const read: Mp4Sample = { + compositionOffset: sampleField(data, layout, sample, TRUN_SAMPLE_COMPOSITION_OFFSET) ?? 0, + decodeTime: time, + offset: position, + size, + sync: (sampleFlags & SAMPLE_IS_NON_SYNC) === 0, + } + + // A duration with no source stays absent rather than reading as zero, which is why a sample the stream times is told apart from one it does not. + if (duration !== undefined) { + read.duration = duration + } + + samples.push(read) + time = duration === undefined + ? undefined + : time + BigInt(duration) + } + + position += size + } + } + + previousEnd = position + } + + return time === undefined + ? { samples } + : { decodeTime: time, samples } +} diff --git a/src/lib/camera/mp4/mp4Writer.ts b/src/lib/camera/mp4/mp4Writer.ts new file mode 100644 index 000000000..913131c3a --- /dev/null +++ b/src/lib/camera/mp4/mp4Writer.ts @@ -0,0 +1,581 @@ +import type { Mp4StreamAudioTrack, Mp4StreamVideoTrack } from './Mp4StreamReader.js' + +import { Buffer } from 'node:buffer' + +import { parameterSetUnits } from '../rtp/FrameCutter.js' +import { FRAME_LENGTH_SIZE, HEVC_TYPE_MASK } from '../StreamingOptions.js' +import { readBoxHeader, walkBoxes } from './mp4Boxes.js' + +/** + * What an initialization segment is written from: the stream's picture and sound as the stream reader describes them, and the parameter sets a caller read + * from the stream's video for a picture whose description holds none. + */ +export interface InitializationSegmentOptions { + /** + * The sound's description, absent for a segment of picture alone. + */ + audio?: Mp4StreamAudioTrack + /** + * Parameter sets for the picture's `hvcC`, each behind its four-octet length as a keyframe carries them, read only when the picture's description holds + * none. + */ + parameterSets?: Buffer + /** + * The picture's description. + */ + video: Mp4StreamVideoTrack +} + +/** + * One sample a segment carries, with its times in its track's timescale. + */ +export interface SegmentSample { + /** + * The sample's octets, copied once into the segment. + */ + readonly data: Buffer + /** + * The sample's duration. + */ + readonly duration: number + /** + * The time from the sample's decode time to its presentation, which a version 1 `trun` writes signed. + */ + readonly compositionOffset: number + /** + * Whether a picture sample is a sync sample. Every sound sample is written as one. + */ + readonly sync: boolean +} + +/** + * One track's samples in a segment, in decode order, and the decode time of the first. + */ +export interface SegmentRun { + /** + * The first sample's decode time in the track's timescale. + */ + readonly decodeTime: bigint + /** + * The samples. + */ + readonly samples: readonly SegmentSample[] +} + +/** + * What a segment is written from: its sequence number and each track's run. + */ +export interface SegmentOptions { + /** + * The sound's run, absent or of no samples for a segment without sound. + */ + audio?: SegmentRun + /** + * The segment's sequence number, written in its `mfhd`. + */ + sequenceNumber: number + /** + * The picture's run, absent or of no samples for a segment without picture. + */ + video?: SegmentRun +} + +// The track identifiers the writer gives the picture and the sound, the same in every initialization segment and segment it writes. +const VIDEO_TRACK_ID = 1 +const AUDIO_TRACK_ID = 2 + +// The brands ffmpeg writes in a fragmented MP4's ftyp: iso5, which default_base_moof needs, as the major brand at minor version 512, then iso5, iso6 and +// mp41 as the compatible brands. +const MAJOR_BRAND = 'iso5' +const MINOR_VERSION = 512 +const COMPATIBLE_BRANDS = ['iso5', 'iso6', 'mp41'] as const + +/* The movie fields ffmpeg writes for a movie whose moov holds no sample: a timescale of 1000, or 48000 once the movie holds a sound track, which no field + * counts in since the movie's duration is zero, and a next track identifier of 2, its value for a movie written before any of its samples. + */ +const MOVIE_TIMESCALE = 1000 +const SOUND_MOVIE_TIMESCALE = 48000 +const NEXT_TRACK_ID = 2 + +// The identity matrix of mvhd and tkhd, in 16.16 and 2.30 fixed point as ISO/IEC 14496-12 writes it. +const MATRIX = [ + 0x00010000, + 0, + 0, + 0, + 0x00010000, + 0, + 0, + 0, + 0x40000000, +] as const + +// The language code of a track whose language is undetermined, ISO 639-2's und packed as three five-bit letters. +const UNDETERMINED_LANGUAGE = 0x55C4 + +// A track header's flags marking it enabled and in the movie. +const TRACK_ENABLED_IN_MOVIE = 0x3 + +// A data reference's flag marking the media in the same file. +const SELF_CONTAINED = 0x1 + +// A video media header's flag, which ISO/IEC 14496-12 sets to 1. +const VIDEO_MEDIA_HEADER_FLAGS = 0x1 + +// The fixed fields of a video sample entry before the boxes it holds, and the octets an hvcC record holds before its count of arrays. +const VISUAL_ENTRY_FIELDS = 78 +const HVCC_ARRAYS_AT = 22 + +// HEVC's parameter set NAL unit types, the video, sequence and picture parameter sets from the first to the last, whose arrays an hvc1 entry marks complete +// by the top bit of the octet naming an array's type. +const HEVC_VPS = 32 +const HEVC_PPS = 34 +const ARRAY_COMPLETE = 0x80 + +// The tfhd flag counting a run's data from its moof, and the trun flags of the data offset and of each field every sample carries. +const TFHD_DEFAULT_BASE_IS_MOOF = 0x20000 +const TRUN_FIELDS = 0x1 | 0x100 | 0x200 | 0x400 | 0x800 + +// The flags of a sync sample, which depends on no other, and of any other picture sample, which depends on one before it and is no sync sample. +const SYNC_SAMPLE_FLAGS = 0x02000000 +const NON_SYNC_SAMPLE_FLAGS = 0x01010000 + +// The octets of a box header, of a full box's version and flags, and of each part of a segment's moof that does not grow with its samples. +const HEADER = 8 +const FULL_HEADER = 12 +const MFHD = FULL_HEADER + 4 +const TFHD = FULL_HEADER + 4 +const TFDT = FULL_HEADER + 8 +const TRUN = FULL_HEADER + 8 +const TRUN_SAMPLE = 16 + +// A box of a type holding the parts given in order. +function box(type: string, ...parts: readonly Uint8Array[]): Buffer { + const size = parts.reduce((total, part) => total + part.length, HEADER) + const bytes = Buffer.alloc(size) + let at = HEADER + + bytes.writeUInt32BE(size, 0) + bytes.write(type, 4, 'latin1') + + for (const part of parts) { + bytes.set(part, at) + at += part.length + } + + return bytes +} + +// A full box of a type, its version and flags, holding the parts given in order. +function fullBox(type: string, version: number, flags: number, ...parts: readonly Uint8Array[]): Buffer { + const versionAndFlags = Buffer.alloc(4) + + versionAndFlags.writeUInt32BE((version << 24) | flags) + + return box(type, versionAndFlags, ...parts) +} + +// The 32-bit words given, big-endian. +function words(...values: readonly number[]): Buffer { + const bytes = Buffer.alloc(values.length * 4) + + for (const [index, value] of values.entries()) { + bytes.writeUInt32BE(value, index * 4) + } + + return bytes +} + +// The movie header: no creation or modification time, the movie's timescale, no duration, a rate of 1.0 and full volume, the identity matrix and the next +// track identifier. +function movieHeader(timescale: number): Buffer { + const fields = Buffer.alloc(96) + + fields.writeUInt32BE(timescale, 8) + fields.writeUInt32BE(0x00010000, 16) + fields.writeUInt16BE(0x0100, 20) + words(...MATRIX).copy(fields, 32) + fields.writeUInt32BE(NEXT_TRACK_ID, 92) + + return fullBox('mvhd', 0, 0, fields) +} + +/* A track header: no creation or modification time, the track's identifier, no duration, the identity matrix, and for a picture its width and height in + * 16.16 fixed point, or for sound the alternate group 1 and full volume. + */ +function trackHeader(id: number, video?: Mp4StreamVideoTrack): Buffer { + const fields = Buffer.alloc(80) + + fields.writeUInt32BE(id, 8) + + if (video === undefined) { + fields.writeUInt16BE(1, 30) + fields.writeUInt16BE(0x0100, 32) + } + + words(...MATRIX).copy(fields, 36) + + if (video !== undefined) { + fields.writeUInt32BE(video.width * 0x10000, 72) + fields.writeUInt32BE(video.height * 0x10000, 76) + } + + return fullBox('tkhd', 0, TRACK_ENABLED_IN_MOVIE, fields) +} + +// A media header: no creation or modification time, the track's timescale, no duration and an undetermined language. +function mediaHeader(timescale: number): Buffer { + const fields = Buffer.alloc(20) + + fields.writeUInt32BE(timescale, 8) + fields.writeUInt16BE(UNDETERMINED_LANGUAGE, 16) + + return fullBox('mdhd', 0, 0, fields) +} + +// A handler: its type after 32 bits of pre-definition, twelve reserved octets, and its name ending in a zero octet. +function handler(type: 'soun' | 'vide', name: string): Buffer { + return fullBox('hdlr', 0, 0, Buffer.alloc(4), Buffer.from(type, 'latin1'), Buffer.alloc(12), Buffer.from(`${name}\0`, 'latin1')) +} + +/* One track's trak: its header, then its media of a media header, a handler, a media information box of the medium's header, a data information box + * naming the media as this file's own, and a sample table describing the one sample entry and holding no sample, every sample being in a fragment. + */ +function track(id: number, timescale: number, sampleEntry: Uint8Array, video?: Mp4StreamVideoTrack): Buffer { + const mediaInformation = video === undefined + ? fullBox('smhd', 0, 0, Buffer.alloc(4)) + : fullBox('vmhd', 0, VIDEO_MEDIA_HEADER_FLAGS, Buffer.alloc(8)) + + return box( + 'trak', + trackHeader(id, video), + box( + 'mdia', + mediaHeader(timescale), + video === undefined + ? handler('soun', 'SoundHandler') + : handler('vide', 'VideoHandler'), + box( + 'minf', + mediaInformation, + box('dinf', fullBox('dref', 0, 0, words(1), fullBox('url ', 0, SELF_CONTAINED))), + box( + 'stbl', + fullBox('stsd', 0, 0, words(1), sampleEntry), + fullBox('stts', 0, 0, words(0)), + fullBox('stsc', 0, 0, words(0)), + fullBox('stsz', 0, 0, words(0, 0)), + fullBox('stco', 0, 0, words(0)), + ), + ), + ), + ) +} + +// The NAL units of parameter sets in the form a keyframe carries them, each behind its four-octet length. +function unitsOf(parameterSets: Buffer): Buffer[] { + const units: Buffer[] = [] + + for (let at = 0; at + FRAME_LENGTH_SIZE <= parameterSets.length;) { + const end = at + FRAME_LENGTH_SIZE + parameterSets.readUInt32BE(at) + + units.push(parameterSets.subarray(at + FRAME_LENGTH_SIZE, end)) + at = end + } + + return units +} + +// Whether an hvc1 entry marks an hvcC array of a NAL unit type complete: an array of parameter sets, as ffmpeg marks them, and no other. +function marksComplete(type: number): boolean { + return (type >= HEVC_VPS) && (type <= HEVC_PPS) +} + +/* The stream's own hvcC as an hvc1 entry carries it, each parameter set array marked complete as ffmpeg marks it in an hvc1 entry, where an hev1 entry's + * record may leave it unmarked. The stream reader read the record whole: each array is there to walk. + */ +function markedRecord(hvcC: Buffer, payload: number): Buffer { + const record = Buffer.from(hvcC) + let at = payload + HVCC_ARRAYS_AT + 1 + + for (let array = 0; array < record[payload + HVCC_ARRAYS_AT]; array++) { + const count = record.readUInt16BE(at + 1) + + if (marksComplete(record[at] & HEVC_TYPE_MASK)) { + record[at] |= ARRAY_COMPLETE + } + + at += 3 + + for (let unit = 0; unit < count; unit++) { + at += 2 + record.readUInt16BE(at) + } + } + + return record +} + +/* An hvcC holding the stream's own record's fields through its length size and arrays of the parameter sets given, one array for each NAL unit type in the + * order of their types, each unit behind its 16-bit length and each parameter set array marked complete. + */ +function recordWith(record: Buffer, parameterSets: Buffer): Buffer { + const arrays = new Map() + + for (const unit of unitsOf(parameterSets)) { + const type = (unit[0] >> 1) & HEVC_TYPE_MASK + const units = arrays.get(type) + + if (units === undefined) { + arrays.set(type, [unit]) + } else { + units.push(unit) + } + } + + const parts = [...arrays].sort(([left], [right]) => left - right).flatMap(([type, units]) => { + const head = Buffer.alloc(3) + const completeness = marksComplete(type) + ? ARRAY_COMPLETE + : 0 + + head.writeUInt8(completeness | type, 0) + head.writeUInt16BE(units.length, 1) + + return [ + head, + ...units.flatMap((unit) => { + const length = Buffer.alloc(2) + + length.writeUInt16BE(unit.length) + + return [length, unit] + }), + ] + }) + + return box('hvcC', record.subarray(0, HVCC_ARRAYS_AT), Buffer.from([arrays.size]), ...parts) +} + +/* The picture's sample entry as hvc1: the stream's own entry's fields and boxes, its hvcC among them with its parameter set arrays marked complete, or + * with its arrays written from the parameter sets given when the stream's record holds none. + */ +function videoEntry(video: Mp4StreamVideoTrack, parameterSets: Buffer | undefined): Buffer { + const { sampleEntry } = video + // The stream reader read the entry whole: its header and fields are there to read. + const headerLength = readBoxHeader(sampleEntry)!.length + const boxes = walkBoxes(sampleEntry, headerLength + VISUAL_ENTRY_FIELDS).boxes.map(({ end, payload, start, type }) => { + if (type !== 'hvcC') { + return sampleEntry.subarray(start, end) + } + + return parameterSets === undefined + ? markedRecord(sampleEntry.subarray(start, end), payload - start) + : recordWith(sampleEntry.subarray(payload, end), parameterSets) + }) + + return box('hvc1', sampleEntry.subarray(headerLength, headerLength + VISUAL_ENTRY_FIELDS), ...boxes) +} + +/** + * Writes an initialization segment of the stream's picture and, when given, its sound, holding the boxes ffmpeg writes for the same tracks under + * `empty_moov+default_base_moof`: an `ftyp` of ffmpeg's brands and a `moov` of an `mvhd`, a `trak` for each track and an `mvex` of a `trex` for each. The + * picture is track 1, its entry written as `hvc1` with the stream's own entry's fields and boxes, and the sound is track 2, its Opus entry the stream's own + * whole, each track at its stream's timescale and holding no sample. + * @param options - The tracks, and the parameter sets for a picture whose description holds none. + * @returns The segment's octets. + * @throws RangeError for a picture whose description holds no parameter sets when none are given, since an `hvc1` entry cannot be decoded without them. + */ +export function writeInitializationSegment(options: InitializationSegmentOptions): Buffer { + const { audio, parameterSets, video } = options + const own = video.parameterSets.length > 0 + + if (!own && ((parameterSets === undefined) || (parameterSets.length === 0))) { + throw new RangeError('The stream\'s video track carries no parameter sets in its sample entry and none were given, and an hvc1 sample entry cannot be ' + + 'decoded without them.') + } + + const movieTimescale = audio === undefined + ? MOVIE_TIMESCALE + : SOUND_MOVIE_TIMESCALE + const tracks = [ + track(VIDEO_TRACK_ID, video.timescale, videoEntry(video, own ? undefined : parameterSets), video), + ] + // Each track's trex names its first sample entry and no default, since every sample of a segment states its own fields. + const trackExtends = [ + fullBox('trex', 0, 0, words(VIDEO_TRACK_ID, 1, 0, 0, 0)), + ] + + if (audio !== undefined) { + tracks.push(track(AUDIO_TRACK_ID, audio.timescale, audio.sampleEntry)) + trackExtends.push(fullBox('trex', 0, 0, words(AUDIO_TRACK_ID, 1, 0, 0, 0))) + } + + return Buffer.concat([ + box('ftyp', Buffer.from(MAJOR_BRAND, 'latin1'), words(MINOR_VERSION), Buffer.from(COMPATIBLE_BRANDS.join(''), 'latin1')), + box('moov', movieHeader(movieTimescale), ...tracks, box('mvex', ...trackExtends)), + ]) +} + +/** + * Writes the initialization segment of a run that opens on a keyframe: the picture's parameter sets come from its description, or, for a stream that + * carries them in its keyframes alone, from the keyframe's own units. + * @param options - The tracks and the keyframe. + * @param options.audio - The sound's description, absent for a segment of picture alone. + * @param options.keyframe - The keyframe the run opens on, each of its NAL units behind its four-octet length. + * @param options.video - The picture's description. + * @returns The segment's octets. + * @throws RangeError where neither the picture's description nor the keyframe holds parameter sets, as {@link writeInitializationSegment} throws. + */ +export function writeKeyframeInitializationSegment(options: { audio?: Mp4StreamAudioTrack, keyframe: Buffer, video: Mp4StreamVideoTrack }): Buffer { + const { audio, keyframe, video } = options + const parameterSets = video.parameterSets.length === 0 + ? parameterSetUnits(keyframe) + : undefined + + return writeInitializationSegment({ audio, parameterSets, video }) +} + +/** + * Writes a movie of one picture: the initialization segment {@link writeKeyframeInitializationSegment} writes for the picture alone, then one segment of + * sequence number 1 holding the keyframe as its one sample, sync, at decode time 0 with a composition offset of 0 and the duration given. + * @param options - The sample's duration, the keyframe and the picture's description. + * @param options.duration - The duration of the movie's one sample, in the picture's timescale. + * @param options.keyframe - The keyframe, each of its NAL units behind its four-octet length. + * @param options.video - The picture's description. + * @returns The movie's octets. + * @throws RangeError where neither the picture's description nor the keyframe holds parameter sets. + */ +export function writeKeyframeMovie(options: { duration: number, keyframe: Buffer, video: Mp4StreamVideoTrack }): Buffer { + const { duration, keyframe, video } = options + + return Buffer.concat([ + writeKeyframeInitializationSegment({ keyframe, video }), + writeSegment({ + sequenceNumber: 1, + video: { + decodeTime: 0n, + samples: [ + { + compositionOffset: 0, + data: keyframe, + duration, + sync: true, + }, + ], + }, + }), + ]) +} + +/** + * A track's share of a segment: how many samples it carries and their octets. + */ +export interface SegmentTrackLength { + /** + * The track's samples in the segment. + */ + readonly samples: number + /** + * The octets of those samples. + */ + readonly octets: number +} + +// The octets of a track's traf: its headers and a trun entry for each sample. +function trackFragmentLength(samples: number): number { + return HEADER + TFHD + TFDT + TRUN + (samples * TRUN_SAMPLE) +} + +/** + * The octets of the segment {@link writeSegment} writes for tracks of these lengths, its `moof` and its `mdat`, which is how a caller reads a segment's size before + * it writes one. A track of no samples adds nothing, as it gets no `traf`. + * @param tracks - Each track's samples and octets. + * @returns The segment's octets. + */ +export function segmentLength(tracks: readonly SegmentTrackLength[]): number { + return tracks.reduce((total, { octets, samples }) => samples === 0 + ? total + : total + trackFragmentLength(samples) + octets, HEADER + MFHD + HEADER) +} + +/** + * Writes one segment: a `moof` of an `mfhd` and a `traf` for each track with samples, picture first, then one `mdat` holding their samples in that order. + * Each `traf` holds a `tfhd` counting its data from the `moof`, a version 1 `tfdt` of its first sample's decode time, and a version 1 `trun` stating its + * data offset and each sample's duration, size, flags and signed composition offset. A picture's sync samples are flagged sync and its other samples not, + * and every sound sample is flagged sync. Each sample's octets are copied once, into the segment. + * @param options - The sequence number and each track's run. + * @returns The segment's octets. + */ +export function writeSegment(options: SegmentOptions): Buffer { + const { audio, sequenceNumber, video } = options + + // Each track with samples, picture first, beside its identifier. + const runs: { id: number, run: SegmentRun }[] = [] + + for (const [id, run] of [ + [VIDEO_TRACK_ID, video], + [AUDIO_TRACK_ID, audio], + ] as const) { + if ((run !== undefined) && (run.samples.length > 0)) { + runs.push({ id, run }) + } + } + + const moof = HEADER + MFHD + runs.reduce((total, { run }) => total + trackFragmentLength(run.samples.length), 0) + const media = runs.reduce((total, { run }) => total + run.samples.reduce((sum, { data }) => sum + data.length, 0), 0) + const segment = Buffer.alloc(moof + HEADER + media) + // Where the next box is written in the moof, and where the next sample's octets go in the mdat, counted from the moof's first octet. + let at = 0 + let data = moof + HEADER + + const header = (type: string, size: number, versionAndFlags?: number): void => { + segment.writeUInt32BE(size, at) + segment.write(type, at + 4, 'latin1') + + if (versionAndFlags !== undefined) { + segment.writeUInt32BE(versionAndFlags, at + HEADER) + } + + at += versionAndFlags === undefined + ? HEADER + : FULL_HEADER + } + + header('moof', moof) + header('mfhd', MFHD, 0) + segment.writeUInt32BE(sequenceNumber, at) + at += 4 + + for (const { id, run } of runs) { + const sound = id === AUDIO_TRACK_ID + + header('traf', trackFragmentLength(run.samples.length)) + header('tfhd', TFHD, TFHD_DEFAULT_BASE_IS_MOOF) + segment.writeUInt32BE(id, at) + at += 4 + header('tfdt', TFDT, 1 << 24) + segment.writeBigUInt64BE(run.decodeTime, at) + at += 8 + header('trun', TRUN + (run.samples.length * TRUN_SAMPLE), (1 << 24) | TRUN_FIELDS) + segment.writeUInt32BE(run.samples.length, at) + segment.writeInt32BE(data, at + 4) + at += 8 + + for (const sample of run.samples) { + const flags = (sound || sample.sync) + ? SYNC_SAMPLE_FLAGS + : NON_SYNC_SAMPLE_FLAGS + + segment.writeUInt32BE(sample.duration, at) + segment.writeUInt32BE(sample.data.length, at + 4) + segment.writeUInt32BE(flags, at + 8) + segment.writeInt32BE(sample.compositionOffset, at + 12) + at += TRUN_SAMPLE + data += sample.data.copy(segment, data) + } + } + + header('mdat', HEADER + media) + + return segment +} diff --git a/src/lib/camera/rtp/FrameCutter.spec.ts b/src/lib/camera/rtp/FrameCutter.spec.ts new file mode 100644 index 000000000..b3c6a9b41 --- /dev/null +++ b/src/lib/camera/rtp/FrameCutter.spec.ts @@ -0,0 +1,246 @@ +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { TIER_STREAM_PARAMETER_SETS } from '../../../test-utils/mp4Fixtures.js' +import { nalUnit, RTP_VECTORS, tierFrameData, vectorFrameData } from '../../../test-utils/rtpVectors.js' +import { decodable, FrameCutter, wellFormedFrame } from './FrameCutter.js' + +// The packet sizes the vectors were cut at, and the small one the boundary rows cut at, whose payload holds 188 octets. +const PACKET_SIZES = [1228, 200] as const +const SMALL_PACKET = 200 +const SMALL_PAYLOAD = SMALL_PACKET - 12 + +// The NAL unit header of an HEVC picture slice, TRAIL_R in the lowest temporal sub-layer, which a row's own units open with. +const HEADER = Buffer.from([0x02, 0x01]) + +// A packet's type, from its payload header's first octet. +function typeOf(packet: Buffer): number { + return (packet[12] >> 1) & 0x3F +} + +// Every packet of a frame, each copied out of the cutter's buffer before the next is made. +function cutAll(cutter: FrameCutter, frame: Buffer, timestamp = 0, opensRun = false): Buffer[] { + const packets: Buffer[] = [] + + cutter.cut(frame, timestamp, opensRun) + + for (let packet = cutter.next(); packet !== undefined; packet = cutter.next()) { + packets.push(Buffer.from(packet)) + } + + return packets +} + +function payloads(packets: readonly Buffer[]): string[] { + return packets.map(packet => packet.subarray(12).toString('hex')) +} + +function markers(packets: readonly Buffer[]): boolean[] { + return packets.map(packet => (packet[1] & 0x80) !== 0) +} + +// The frame's one marker on its last packet. +function lastMarked(count: number): boolean[] { + return Array.from({ length: count }, (_marker, index) => index === count - 1) +} + +describe('frameCutter', () => { + it('cuts every HEVC vector at both packet sizes octet for octet, the marker on each frame\'s last packet alone', () => { + const hevc = RTP_VECTORS.stream + + for (const size of PACKET_SIZES) { + const cutter = new FrameCutter('video', Buffer.alloc(size)) + + for (const [index, frame] of hevc.frames.entries()) { + const packets = cutAll(cutter, vectorFrameData(frame)) + + expect({ + size, + index, + payloads: payloads(packets), + }).toEqual({ size, index, payloads: frame.cuts[size] }) + expect(markers(packets)).toEqual(lastMarked(packets.length)) + } + } + }) + + it('sends a unit of exactly a payload single and fragments one an octet longer in two, and aggregates units that fill a payload exactly and no more', () => { + const cutter = new FrameCutter('video', Buffer.alloc(SMALL_PACKET)) + const whole = nalUnit(HEADER, SMALL_PAYLOAD) + const longer = nalUnit(HEADER, SMALL_PAYLOAD + 1) + + expect(payloads(cutAll(cutter, tierFrameData([whole])))).toEqual([ + whole.toString('hex'), + ]) + expect(cutAll(cutter, tierFrameData([longer])).map(typeOf)).toEqual([49, 49]) + + // The aggregation header and each unit's length of two octets leave the rest of the payload to the units. + const first = nalUnit(HEADER, 40) + const filling = nalUnit(HEADER, SMALL_PAYLOAD - HEADER.length - 4 - first.length) + const exact = cutAll(cutter, tierFrameData([first, filling])) + const over = cutAll(cutter, tierFrameData([ + first, + nalUnit(HEADER, filling.length + 1), + ])) + + expect(exact.map(packet => packet.length - 12)).toEqual([SMALL_PAYLOAD]) + expect(exact.map(typeOf)).toEqual([48]) + expect(payloads(over)).toEqual([ + first.toString('hex'), + nalUnit(HEADER, filling.length + 1).toString('hex'), + ]) + }) + + it('numbers no packet, leaving each consumer to number its own, each packet carrying its frame\'s timestamp in the fixed header across frames', () => { + const hevc = RTP_VECTORS.stream + const cutter = new FrameCutter('video', Buffer.alloc(SMALL_PACKET)) + const keyframe = cutAll(cutter, vectorFrameData(hevc.frames[0]), 0x100000000 + 3000) + const next = cutAll(cutter, vectorFrameData(hevc.frames[1]), 0x100000000 + 6000) + + expect(keyframe.map(packet => packet.readUInt32BE(4))).toEqual(Array.from({ length: 6 }).fill(3000)) + expect(next.map(packet => packet.readUInt32BE(4))).toEqual([6000]) + + for (const packet of [ + ...keyframe, + ...next, + ]) { + expect([ + packet[0], + packet[1] & 0x7F, + packet.readUInt16BE(2), + packet.readUInt32BE(8), + ]).toEqual([0x80, 0, 0, 0]) + } + }) + + it('refuses a video frame with a length past its end, trailing octets, a unit shorter than its header or no octets, and takes a whole one', () => { + const unit = tierFrameData([ + nalUnit(HEADER, 10), + ]) + const pastEnd = Buffer.from(unit) + pastEnd.writeUInt32BE(11) + // A unit exactly its header long, as HEVC's end of bitstream is. + const headerOnly = Buffer.from('4a01', 'hex') + + expect({ + whole: wellFormedFrame('video', tierFrameData([ + nalUnit(HEADER, 10), + nalUnit(HEADER, 300), + ])), + headerOnly: wellFormedFrame('video', tierFrameData([ + nalUnit(HEADER, 10), + headerOnly, + ])), + pastEnd: wellFormedFrame('video', pastEnd), + trailing: wellFormedFrame('video', Buffer.concat([ + unit, + Buffer.alloc(3), + ])), + short: wellFormedFrame('video', tierFrameData([ + nalUnit(HEADER, 10), + HEADER.subarray(0, HEADER.length - 1), + ])), + empty: wellFormedFrame('video', Buffer.alloc(0)), + }).toEqual({ + whole: true, + headerOnly: true, + pastEnd: false, + trailing: false, + short: false, + empty: false, + }) + }) + + it('cuts an audio frame into one packet of its bytes, marked only when it opens a run, and refuses an empty one and one larger than a payload', () => { + const cutter = new FrameCutter('audio', Buffer.alloc(SMALL_PACKET)) + const opus = nalUnit(Buffer.from([0x78]), 160) + const opening = cutAll(cutter, opus, 48000, true) + const following = cutAll(cutter, opus, 48960, false) + + expect(payloads([ + ...opening, + ...following, + ])).toEqual([ + opus.toString('hex'), + opus.toString('hex'), + ]) + expect(markers([ + ...opening, + ...following, + ])).toEqual([true, false]) + expect([ + wellFormedFrame('audio', Buffer.alloc(0)), + cutter.cut(Buffer.alloc(SMALL_PAYLOAD), 49920, false), + cutter.cut(Buffer.alloc(SMALL_PAYLOAD + 1), 50880, false), + ]).toEqual([false, true, false]) + }) + + it('aggregates HEVC units of temporal identifier fields 2 and 1 under 1, and carries a fragmented unit\'s field of 2 in every fragment', () => { + const cutter = new FrameCutter('video', Buffer.alloc(SMALL_PACKET)) + const [aggregation] = cutAll(cutter, tierFrameData([ + nalUnit(Buffer.from([0x02, 0x02]), 20), + nalUnit(Buffer.from([0x02, 0x01]), 20), + ])) + const fragments = cutAll(cutter, tierFrameData([ + nalUnit(Buffer.from([0x02, 0x02]), 600), + ])) + + expect(aggregation.subarray(12, 14).toString('hex')).toBe('6001') + expect(fragments.map(packet => packet.subarray(12, 15).toString('hex'))).toEqual(['620281', '620201', '620201', '620241']) + + // The lowest identifier last and first alike: units of 1 then 2 aggregate under 1 too. + const [ascending] = cutAll(cutter, tierFrameData([ + nalUnit(Buffer.from([0x02, 0x01]), 20), + nalUnit(Buffer.from([0x02, 0x02]), 20), + ])) + + expect(ascending.subarray(12, 14).toString('hex')).toBe('6001') + }) + + it('aggregates HEVC units under their joined F bits and lowest layer identifier, and carries a fragmented unit\'s F bit and layer in every fragment', () => { + const cutter = new FrameCutter('video', Buffer.alloc(SMALL_PACKET)) + + // A unit of layer 34 with no F bit, then one of layer 33 with it, each a TRAIL_R slice of temporal identifier 1: the layer's high bit closes the first + // octet and its low five bits open the second. + const [aggregation] = cutAll(cutter, tierFrameData([ + nalUnit(Buffer.from([0x03, 0x11]), 20), + nalUnit(Buffer.from([0x83, 0x09]), 20), + ])) + const fragments = cutAll(cutter, tierFrameData([ + nalUnit(Buffer.from([0x83, 0x09]), 600), + ])) + + expect(aggregation.subarray(12, 14).toString('hex')).toBe('e109') + expect(fragments.map(packet => packet.subarray(12, 15).toString('hex'))).toEqual(['e30981', 'e30901', 'e30901', 'e30941']) + }) +}) + +describe('decodable', () => { + // HEVC's video, sequence and picture parameter sets, which a reading hands a keyframe and its track's description some of each. + const [VPS, SPS, PPS] = TIER_STREAM_PARAMETER_SETS + + // The IDR slice every keyframe ends with, after the parameter sets it carries in band. + const SLICE = nalUnit(Buffer.from([0x26, 0x01]), 20) + + // Whether a keyframe carrying the sets given in band before its slice is decodable beside a description holding the sets given. + function read(inBand: readonly Buffer[], described: readonly Buffer[]): boolean { + return decodable(tierFrameData([...inBand, SLICE]), tierFrameData(described)) + } + + it('reads a keyframe as decodable where its units and its track\'s description hold every HEVC parameter set between them, and nowhere else', () => { + expect({ + describedAlone: read([], [VPS, SPS, PPS]), + inBandAlone: read([VPS, SPS, PPS], []), + neither: read([], []), + sequenceAndPictureDescribed: read([], [SPS, PPS]), + videoDescribedOthersInBand: read([SPS, PPS], [VPS]), + }).toEqual({ + describedAlone: true, + inBandAlone: true, + neither: false, + sequenceAndPictureDescribed: false, + videoDescribedOthersInBand: true, + }) + }) +}) diff --git a/src/lib/camera/rtp/FrameCutter.ts b/src/lib/camera/rtp/FrameCutter.ts new file mode 100644 index 000000000..d57603669 --- /dev/null +++ b/src/lib/camera/rtp/FrameCutter.ts @@ -0,0 +1,357 @@ +import type { StreamTierMedium } from '../StreamingOptions.js' + +import { Buffer } from 'node:buffer' + +import { FRAME_LENGTH_SIZE, HEVC_HEADER_LENGTH, HEVC_TYPE_MASK } from '../StreamingOptions.js' +import { marksPacket, RTP_HEADER_LENGTH, wireTimestamp } from './packetRules.js' + +/* Cuts the encoded frames of a tier's stream into RTP packets in the payload formats a viewer at home reads: HEVC by RFC 7798 and Opus by RFC 7587. + * A video frame is its NAL units in decode order, each behind its length in four octets, big-endian, and an audio frame is one Opus packet. Each packet is + * made in the one buffer the cutter's owner hands it and handed out as a view of that buffer, which the caller reads before it asks for the next. The + * cutting allocates nothing in our own JavaScript beyond those views. A packet carries RFC 3550 5.1's fixed header with a payload type and an SSRC of zero + * and no sequence number, which each consumer writes as its own. + */ + +// RFC 3550 5.1's first octet for version 2 with no padding, no extension and no CSRC, and the marker bit atop the second octet. +const VERSION_OCTET = 0x80 +const MARKER_BIT = 0x80 + +// The octets of the fixed header that carry the timestamp and the SSRC (RFC 3550 5.1). +const TIMESTAMP_OFFSET = 4 +const SSRC_OFFSET = 8 + +// The length each unit stands behind inside an aggregation packet (RFC 7798 4.4.2). An aggregation packet's header and a fragmentation unit's payload +// header are each as long as HEVC's NAL unit header (RFC 7798 1.1.4). +const AGGREGATED_LENGTH_SIZE = 2 + +// The packet types of HEVC's aggregation packet and fragmentation unit (RFC 7798 4.4.2 and 4.4.3). +const HEVC_AGGREGATION = 48 +const HEVC_FRAGMENT = 49 + +// The fields of HEVC's NAL unit header (RFC 7798 1.1.4) beside the type, which the frame contract's mask reads: the F bit atop it, the layer identifier +// across the first octet's last bit and the second octet's top five, and the temporal identifier in the second's last three. +const FORBIDDEN_BIT = 0x80 +const HEVC_LAYER_HIGH_BIT = 0x01 +const HEVC_LAYER_MAXIMUM = 0x3F +const HEVC_TEMPORAL_MASK = 0x07 + +// A fragmentation unit's header marks its unit's first fragment with the start bit and its last with the end bit (RFC 7798 4.4.3). +const START_BIT = 0x80 +const END_BIT = 0x40 + +// The NAL unit types of HEVC's video, sequence and picture parameter sets, consecutive from the first (ITU-T H.265 7.4.2.2). +const HEVC_VIDEO_PARAMETER_SET = 32 +const HEVC_PICTURE_PARAMETER_SET = 34 + +/** + * The mask {@link parameterSetsIn} answers for a picture whose units hold each of HEVC's video, sequence and picture parameter sets, one bit a type, which + * a viewer needs to decode a keyframe. + */ +export const HEVC_PARAMETER_SETS = 0b111 + +/** + * Whether a frame is well formed for its medium, whoever reads it: a video frame holds at least one unit, its lengths tile it exactly, and each unit is at + * least as long as HEVC's NAL unit header, and an audio frame holds at least one octet. Whether an audio frame fits one packet is the cutter's own question, + * asked at the cut. + * @param medium - The frame's medium. + * @param frame - The frame's bytes. + * @returns Whether the frame is well formed. + */ +export function wellFormedFrame(medium: StreamTierMedium, frame: Buffer): boolean { + if (frame.length === 0) { + return false + } + + if (medium === 'audio') { + return true + } + + for (let offset = 0; offset < frame.length;) { + if (frame.length - offset < FRAME_LENGTH_SIZE) { + return false + } + + const length = frame.readUInt32BE(offset) + + if ((length < HEVC_HEADER_LENGTH) || (length > frame.length - offset - FRAME_LENGTH_SIZE)) { + return false + } + + offset += FRAME_LENGTH_SIZE + length + } + + return true +} + +/** + * The bits of HEVC's video, sequence and picture parameter sets a well-formed run of units holds, each unit read through its header, which reads whole as + * {@link HEVC_PARAMETER_SETS}. The walk allocates nothing. + * @param units - The units, each behind its four-octet length. + * @returns The bits held. + */ +export function parameterSetsIn(units: Buffer): number { + let held = 0 + + for (let offset = 0; offset < units.length; offset += FRAME_LENGTH_SIZE + units.readUInt32BE(offset)) { + const type = (units[offset + FRAME_LENGTH_SIZE] >> 1) & HEVC_TYPE_MASK + + if ((type >= HEVC_VIDEO_PARAMETER_SET) && (type <= HEVC_PICTURE_PARAMETER_SET)) { + held |= 1 << (type - HEVC_VIDEO_PARAMETER_SET) + } + } + + return held +} + +/** + * Whether a decoder can read a keyframe: its own units and its track's description hold between them each of HEVC's video, sequence and picture parameter + * sets. The camera buffer's readiness, the recorder's declined sentence, the demand's warning of a stream and the keyframe lookup each read it, and its + * walks allocate nothing. + * @param keyframe - The keyframe's units, each behind its four-octet length. + * @param parameterSets - The parameter sets its track's description carries, each behind its four-octet length. + * @returns Whether a decoder can read the keyframe. + */ +export function decodable(keyframe: Buffer, parameterSets: Buffer): boolean { + return (parameterSetsIn(parameterSets) | parameterSetsIn(keyframe)) === HEVC_PARAMETER_SETS +} + +/** + * The units of HEVC's video, sequence and picture parameter sets a well-formed run of units holds, in their order, each behind its four-octet length, as a + * keyframe carries them in band, which lets a recording's header take the sets a stream carries in its keyframes alone. + * @param units - The units, each behind its four-octet length. + * @returns The parameter set units, each behind its length, and no octets when the run holds none. + */ +export function parameterSetUnits(units: Buffer): Buffer { + const sets: Buffer[] = [] + + for (let offset = 0; offset < units.length; offset += FRAME_LENGTH_SIZE + units.readUInt32BE(offset)) { + const type = (units[offset + FRAME_LENGTH_SIZE] >> 1) & HEVC_TYPE_MASK + + if ((type >= HEVC_VIDEO_PARAMETER_SET) && (type <= HEVC_PICTURE_PARAMETER_SET)) { + sets.push(units.subarray(offset, offset + FRAME_LENGTH_SIZE + units.readUInt32BE(offset))) + } + } + + return Buffer.concat(sets) +} + +/** + * Cuts the frames of one medium of a tier's stream into RTP packets, which it leaves unnumbered, since each consumer numbers the packets it sends from a + * start of its own. A caller checks a frame with {@link wellFormedFrame}, hands it to {@link cut} with its timestamp, which refuses an audio frame longer + * than one payload, and calls {@link next} until it answers `undefined`, reading each packet before the next call, because every packet is made in the + * same buffer. + * + * A video frame's units go out in their order: consecutive units that fit one payload together go in one aggregation packet, a unit that fits a payload + * and shares it with no neighbor goes as a single NAL unit packet, and a unit larger than a payload is cut into fragmentation units, every one full but + * the last. The marker is on the frame's last packet alone. An audio frame makes one packet, marked when its frame opens a run of times. + */ +export class FrameCutter { + private readonly packet: Buffer + private readonly maxPayload: number + private readonly video: boolean + // The frame being cut, with its timestamp as the wire writes it and whether it opens a run. A video frame is released at the call that answers its end, + // and an audio frame at the call that makes its one packet. + private frame?: Buffer + private timestamp = 0 + private opensRun = false + // The offset of the frame's next unit, and while a unit is fragmented the offset of its header, of the next fragment's first octet and of its end. + private offset = 0 + private unitHeader = 0 + private fragment = 0 + private unitEnd = 0 + + /** + * Makes a cutter over the buffer its packets are made in. + * @param medium - The tier's medium: HEVC video or Opus audio. + * @param packet - The buffer, as long as the largest packet the tier sends, header included. + */ + constructor(medium: StreamTierMedium, packet: Buffer) { + this.packet = packet + this.maxPayload = packet.length - RTP_HEADER_LENGTH + this.video = medium === 'video' + + // The version octet and the SSRC are the same in every packet, which is why they are written once. + packet[0] = VERSION_OCTET + packet.writeUInt32BE(0, SSRC_OFFSET) + } + + /** + * Starts cutting a well-formed frame, whose packets {@link next} then makes, and answers whether it can: an audio frame longer than one payload is refused, + * and the cutter then holds no frame. A frame cut while another still has packets left replaces it. + * @param frame - The frame's bytes, which the cutter reads until its last packet is made. A video frame is released at the call that answers its end. + * @param timestamp - The frame's timestamp, kept whole by its caller and written modulo 2^32. + * @param opensRun - Whether the frame opens a run of times, which marks an audio frame's packet (RFC 7587 4.1). + * @returns Whether the cutter took the frame. + */ + cut(frame: Buffer, timestamp: number, opensRun: boolean): boolean { + if (!this.fits(frame)) { + this.frame = undefined + + return false + } + + this.frame = frame + this.timestamp = wireTimestamp(timestamp) + this.opensRun = opensRun + this.offset = 0 + this.fragment = 0 + this.unitEnd = 0 + + return true + } + + /** + * Counts the packets a well-formed frame cuts into, by cutting it in the cutter's buffer: the count follows the cut's own rules, an audio frame the + * cut refuses making none. The cutter then holds no frame, which is why a caller counts a frame before it cuts one to send, never while a frame has packets left. + * @param frame - The frame's bytes. + * @returns The packets the frame cuts into. + */ + count(frame: Buffer): number { + let packets = 0 + + if (this.cut(frame, 0, false)) { + while (this.next() !== undefined) { + packets++ + } + } + + return packets + } + + /** + * Makes the frame's next packet in the cutter's buffer. + * @returns A view of the packet, valid until the next call, or `undefined` once the frame's last packet is made. + */ + next(): Buffer | undefined { + const frame = this.frame + + if (frame === undefined) { + return undefined + } + + if (!this.video) { + this.frame = undefined + frame.copy(this.packet, RTP_HEADER_LENGTH) + + return this.finish(true, frame.length) + } + + if (this.fragment < this.unitEnd) { + return this.nextFragment(frame) + } + + if (this.offset === frame.length) { + this.frame = undefined + + return undefined + } + + const length = frame.readUInt32BE(this.offset) + const start = this.offset + FRAME_LENGTH_SIZE + const end = start + length + + if (length > this.maxPayload) { + this.unitHeader = start + this.fragment = start + HEVC_HEADER_LENGTH + this.unitEnd = end + this.offset = end + + return this.nextFragment(frame) + } + + // The units after this one join it while they fit one payload together, the aggregation header and each unit's two-octet length included. + let size = HEVC_HEADER_LENGTH + AGGREGATED_LENGTH_SIZE + length + let last = end + + while (last < frame.length) { + const following = frame.readUInt32BE(last) + + if (size + AGGREGATED_LENGTH_SIZE + following > this.maxPayload) { + break + } + + size += AGGREGATED_LENGTH_SIZE + following + last += FRAME_LENGTH_SIZE + following + } + + if (last === end) { + frame.copy(this.packet, RTP_HEADER_LENGTH, start, end) + this.offset = end + + return this.finish(end === frame.length, length) + } + + this.aggregate(frame, last) + this.offset = last + + return this.finish(last === frame.length, size) + } + + /* Writes an aggregation packet's payload of the units from the frame's next one to an end. Its header joins the units' F bits and carries their lowest + * layer and temporal identifiers (RFC 7798 4.4.2). + */ + private aggregate(frame: Buffer, end: number): void { + const packet = this.packet + let position = RTP_HEADER_LENGTH + HEVC_HEADER_LENGTH + let forbidden = 0 + let layer = HEVC_LAYER_MAXIMUM + let temporal = HEVC_TEMPORAL_MASK + + for (let offset = this.offset; offset < end;) { + const length = frame.readUInt32BE(offset) + const start = offset + FRAME_LENGTH_SIZE + + forbidden |= frame[start] & FORBIDDEN_BIT + layer = Math.min(layer, ((frame[start] & HEVC_LAYER_HIGH_BIT) << 5) | (frame[start + 1] >> 3)) + temporal = Math.min(temporal, frame[start + 1] & HEVC_TEMPORAL_MASK) + packet.writeUInt16BE(length, position) + frame.copy(packet, position + AGGREGATED_LENGTH_SIZE, start, start + length) + position += AGGREGATED_LENGTH_SIZE + length + offset = start + length + } + + packet[RTP_HEADER_LENGTH] = forbidden | (HEVC_AGGREGATION << 1) | (layer >> 5) + packet[RTP_HEADER_LENGTH + 1] = ((layer & 0x1F) << 3) | temporal + } + + /* Makes the fragmented unit's next fragmentation unit, which drops the unit's own header for a payload header carrying the unit's F bit, layer and + * temporal identifiers under type 49, followed by an octet of the start bit, the end bit and the unit's type (RFC 7798 4.4.3). + */ + private nextFragment(frame: Buffer): Buffer { + const packet = this.packet + const header = this.unitHeader + const first = this.fragment === header + HEVC_HEADER_LENGTH + const from = this.fragment + const to = Math.min(from + this.maxPayload - HEVC_HEADER_LENGTH - 1, this.unitEnd) + const edges = (first + ? START_BIT + : 0) | (to === this.unitEnd + ? END_BIT + : 0) + + packet[RTP_HEADER_LENGTH] = (frame[header] & (FORBIDDEN_BIT | HEVC_LAYER_HIGH_BIT)) | (HEVC_FRAGMENT << 1) + packet[RTP_HEADER_LENGTH + 1] = frame[header + 1] + packet[RTP_HEADER_LENGTH + 2] = edges | ((frame[header] >> 1) & HEVC_TYPE_MASK) + frame.copy(packet, RTP_HEADER_LENGTH + HEVC_HEADER_LENGTH + 1, from, to) + this.fragment = to + + return this.finish((to === this.unitEnd) && (this.offset === frame.length), HEVC_HEADER_LENGTH + 1 + to - from) + } + + // Whether a frame fits the cutter's packets: any video frame, whose units are fragmented as they need, and an audio frame within one payload. + private fits(frame: Buffer): boolean { + return this.video || (frame.length <= this.maxPayload) + } + + // Writes the marker and the timestamp of the packet whose payload is made, its frame's last or not, and answers a view of the packet. + private finish(last: boolean, payloadLength: number): Buffer { + const packet = this.packet + + packet[1] = marksPacket(this.video, last, this.opensRun) + ? MARKER_BIT + : 0 + packet.writeUInt32BE(this.timestamp, TIMESTAMP_OFFSET) + + return packet.subarray(0, RTP_HEADER_LENGTH + payloadLength) + } +} diff --git a/src/lib/camera/rtp/RTPClock.spec.ts b/src/lib/camera/rtp/RTPClock.spec.ts new file mode 100644 index 000000000..3073d897e --- /dev/null +++ b/src/lib/camera/rtp/RTPClock.spec.ts @@ -0,0 +1,167 @@ +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { FrameCutter } from './FrameCutter.js' +import { ClockRun, RTPClock } from './RTPClock.js' + +// A frame's time n frames after a source's first at 30 frames a second, rounded to the microsecond as a source's clock gives it. +function frameTime(base: number, frame: number): number { + return base + Math.round(frame * 1000000 / 30) +} + +// Places a picture frame on a run as the frame entry does: a mark ends the run where the picture has placed a sample in it, which an open run has here, +// since the helper places a picture in each run it opens, and a frame that finds the run ended opens it at its own time, a frame carrying no decode time. +function placeFrame(run: ClockRun, time: number, discontinuity: boolean, moment: number): number | undefined { + if (discontinuity && run.open) { + run.end() + } + + if (!run.open) { + run.openAt(time, moment) + } + + return run.place('video', time) +} + +describe('rtpClock', () => { + it('places a run\'s first frame at its moment and each later one by its time\'s distance from the first, 3000 ticks a frame with no drift', () => { + const clock = new RTPClock(1000, 7) + const run = new ClockRun(clock) + const base = 5000000 + const timestamps = [ + placeFrame(run, base, false, 2000)!, + ] + + // Each later frame arrives at a moment of its own, a little late or early, which placement never reads. + for (let frame = 1; frame <= 1000; frame++) { + timestamps.push(placeFrame(run, frameTime(base, frame), false, 2000 + frame * 33 + (frame % 7))!) + } + + expect(timestamps[0]).toBe(clock.timestamp('video', 2000)) + expect(timestamps[0]).toBe(7 + 90000) + expect(timestamps.slice(1).every((timestamp, index) => timestamp - timestamps[index] === 3000)).toBe(true) + expect(timestamps[1000] - timestamps[0]).toBe(3000000) + }) + + it('places frames 33,339 microseconds apart by each one\'s distance from the run\'s first, 3000.51 ticks a frame, and never by summing rounded steps', () => { + const run = new ClockRun(new RTPClock(0, 0)) + const timestamps = Array.from({ length: 1001 }, (_timestamp, frame) => placeFrame(run, frame * 33339, false, frame * 33)) + + // Steps rounded one at a time would land the thousandth frame at 3,001,000, where its own distance rounded once lands it at 3,000,510. + expect(timestamps.every((timestamp, frame) => timestamp === Math.round(frame * 33339 * 90000 / 1000000))).toBe(true) + expect(timestamps[1000]).toBe(3000510) + }) + + it('places a discontinuity at its moment, and one tick after the highest timestamp given when its moment is not past it', () => { + const clock = new RTPClock(0, 0) + const run = new ClockRun(clock) + + expect(placeFrame(run, 0, false, 1000)).toBe(90000) + expect(placeFrame(run, 0, true, 6000)).toBe(540000) + expect(run.opened).toBe(true) + + // Ten seconds of the source's time arrive over ten seconds of the clock, which keeps the run, and a discontinuity at that same moment finds its + // moment's timestamp no later than the highest the run placed. + expect(placeFrame(run, 10000000, false, 16000)).toBe(540000 + 900000) + expect(run.opened).toBe(false) + expect(placeFrame(run, 0, true, 16000)).toBe(540000 + 900000 + 1) + expect(run.opened).toBe(true) + }) + + it('keeps the run of a source that pauses ten seconds and resumes on its own time', () => { + const run = new ClockRun(new RTPClock(0, 0)) + + placeFrame(run, 0, false, 0) + placeFrame(run, 33333, false, 33) + + expect(placeFrame(run, 33333 + 10000000, false, 10033)).toBe(3000 + 900000) + expect(run.opened).toBe(false) + }) + + it('keeps timestamps whole across 2^32: the wire wraps them with their steps kept and a later run never lands behind them', () => { + const run = new ClockRun(new RTPClock(0, 0x100000000 - 4000)) + const cutter = new FrameCutter('video', Buffer.alloc(200)) + const frame = Buffer.from('0000000302011e', 'hex') + const written = (timestamp: number): number => { + cutter.cut(frame, timestamp, false) + + return cutter.next()!.readUInt32BE(4) + } + const timestamps = [0, 1, 2].map(index => placeFrame(run, frameTime(0, index), false, index * 33)!) + + expect(timestamps).toEqual([0x100000000 - 4000, 0x100000000 - 1000, 0x100000000 + 2000]) + expect(timestamps.map(written)).toEqual([0xFFFFFFFF - 3999, 0xFFFFFFFF - 999, 2000]) + expect(placeFrame(run, 0, true, 0)).toBe(0x100000000 + 2001) + expect(written(0x100000000 + 2001)).toBe(2001) + }) + + it('places a frame arriving at one moment on a video run and an audio run of one clock at that moment\'s timestamp, each at its own rate', () => { + const clock = new RTPClock(0, 1000) + const video = new ClockRun(clock) + const audio = new ClockRun(clock) + + video.openAt(123456789, 500) + audio.openAt(987, 500) + + expect(video.place('video', 123456789)).toBe(1000 + 45000) + expect(audio.place('audio', 987)).toBe(1000 + 24000) + }) + + it('places a picture and a sound of one run at their presentation times\' distance from its origin, the decode time of its first sample, each at ' + + 'its own rate, and marks each medium\'s first sample of the run', () => { + const clock = new RTPClock(0, 0) + const run = new ClockRun(clock) + const placed: [number | undefined, boolean][] = [] + const place = (medium: 'audio' | 'video', time: number): void => { + placed.push([ + run.place(medium, time), + run.opened, + ]) + } + + // A keyframe decoded at 2 s and presented 66,667 microseconds after, which opens the run at 1 s, then a sound at 2.5 s and a picture at 2.1 s. + run.openAt(2000000, 1000) + place('video', 2066667) + place('audio', 2500000) + place('video', 2100000) + place('audio', 2520000) + + expect(placed).toEqual([ + [90000 + 6000, true], + [48000 + 24000, true], + [90000 + 9000, false], + [48000 + 24960, false], + ]) + }) + + it('opens a later run at the least moment whose timestamps pass each medium\'s highest, one moment for both media, lets a sound timed before its ' + + 'origin go and places a picture timed before it at the opening', () => { + const clock = new RTPClock(0, 0) + const run = new ClockRun(clock) + + // A run opened at 1 s whose picture stands two seconds of its ticks on and whose sound stands a second of its own on. + run.openAt(0, 1000) + run.place('video', 2000000) + run.place('audio', 1000000) + run.end() + + // A later run opened at the same moment: the picture's highest, 270,000, binds. The run opens at the moment whose picture timestamp is 270,001, + // and the sound opens at that one moment's own timestamp, past its highest of 96,000. + run.openAt(5000000, 1000) + + const opening = clock.momentOf('video', 270001) + + expect([ + run.place('audio', 4990000), + run.place('video', 4990000), + run.place('audio', 5000000), + ]).toEqual([ + undefined, + 270001, + clock.timestamp('audio', opening), + ]) + expect(clock.timestamp('audio', opening)).toBeGreaterThan(96000) + expect(opening).toBeCloseTo(3000 + 1 / 90) + }) +}) diff --git a/src/lib/camera/rtp/RTPClock.ts b/src/lib/camera/rtp/RTPClock.ts new file mode 100644 index 000000000..b916de0b8 --- /dev/null +++ b/src/lib/camera/rtp/RTPClock.ts @@ -0,0 +1,220 @@ +import type { StreamTierMedium } from '../StreamingOptions.js' + +import crypto from 'node:crypto' + +import { HEAVIEST_MAXIMUM_KBPS } from '../StreamingOptions.js' + +/* The RTP clock of one video sensor's tiers and the runs of times each tier's frames are placed on. Every tier of the sensor reads the one clock: a + * frame captured at one moment carries the same moment on each tier, at its medium's rate. A view that opens from the camera buffer is handed its + * stretch on timestamps of its own, which begin past every timestamp its tier's picture has been placed at and run at the opening's speed, read from the + * stretch's own rate, each handed once the live edge reaches it, which is why no picture of an opening stands behind the moment it is sent and the live pictures + * after it stand above them all. The clock reads no time of its own: every moment it reads is handed in, in milliseconds of a steady clock that a + * correction of the time of day never moves, and every frame time in microseconds. Timestamps are kept and compared whole, as Numbers that stay exact far + * beyond any process's life at these rates, and only the wire writes them modulo 2^32. + */ + +/** + * The RTP clock rates of the tiers' codecs: 90 kHz for HEVC video (RFC 7798) and 48 kHz for Opus audio (RFC 7587). + */ +export const CLOCK_RATES: Readonly> = { audio: 48000, video: 90000 } + +// The timestamp's 32-bit range, which a clock's offset is drawn from (RFC 3550 5.1). +const TIMESTAMP_RANGE = 0x100000000 + +const MILLISECONDS_PER_SECOND = 1000 +const MICROSECONDS_PER_SECOND = 1000000 + +// The speed an opening replays a stretch at, as a multiple of the stream's own, for a stretch at or under the specification's heaviest maximum: one speed +// for every such opening, at home and from away, and no option. A heavier stretch replays slower: its burst holds at this multiple of that maximum. +const OPENING_SPEED = 50 + +// The step an opening's first timestamp stands past the highest its tier's picture has been placed at, in milliseconds, which a viewer takes as later than +// every picture it was sent, where a picture at that highest timestamp itself is not taken. +const OPENING_STEP = 1 + +// The media a run places, each at its own rate. +const MEDIA: readonly StreamTierMedium[] = ['video', 'audio'] + +/** + * The speed an opening replays a stretch at, as a multiple of the stream's own, from the stretch's rate: the opening speed for a stretch at or under the + * specification's heaviest maximum, and for a heavier one the speed that holds its burst to the opening speed times that maximum. The replay of a + * stream past the specification sends no faster than the heaviest stream within it does. + * @param rate - The stretch's rate, in kilobits a second. + * @returns The speed. + */ +export function openingSpeed(rate: number): number { + return (rate <= HEAVIEST_MAXIMUM_KBPS) + ? OPENING_SPEED + : OPENING_SPEED * HEAVIEST_MAXIMUM_KBPS / rate +} + +/** + * One sensor's RTP clock: a moment's timestamp is the clock's offset plus the time from the clock's making to that moment, at the medium's rate. + */ +export class RTPClock { + private readonly origin: number + private readonly offset: number + + /** + * Makes a clock. + * @param origin - The moment the clock is made at, in milliseconds. + * @param offset - The timestamp of that moment, drawn at random unless one is handed in. + */ + constructor(origin: number, offset = crypto.randomInt(TIMESTAMP_RANGE)) { + this.origin = origin + this.offset = offset + } + + /** + * A moment's timestamp at a medium's rate, whole. + * @param medium - The medium. + * @param moment - The moment, in milliseconds. + * @returns The timestamp. + */ + timestamp(medium: StreamTierMedium, moment: number): number { + return this.offset + Math.round((moment - this.origin) * CLOCK_RATES[medium] / MILLISECONDS_PER_SECOND) + } + + /** + * The moment whose timestamp at a medium's rate is a given one, the inverse of {@link timestamp}. + * @param medium - The medium. + * @param timestamp - The timestamp, whole. + * @returns The moment, in milliseconds. + */ + momentOf(medium: StreamTierMedium, timestamp: number): number { + return this.origin + (timestamp - this.offset) * MILLISECONDS_PER_SECOND / CLOCK_RATES[medium] + } +} + +/** + * One demand's run of times on its sensor's clock, picture and sound together. The run opens at its first sample, picture or sound: its origin is that + * sample's decode time, which stands at the timestamp of the moment the run opens on each medium's rate, and each sample of the run is placed at that + * timestamp plus its presentation time's distance from the origin, to the nearest tick. The placement never drifts the way added steps would and the + * distance between a picture and a sound is the stream's own. A sound timed before the origin is not placed, and a picture timed before it, which only a + * run a sound opened brings, is placed at the opening. The run ends where its demand reads an end, and the next sample opens a later run at its moment, or, + * where a medium's timestamp there would not pass the highest placed for that medium, at the least later moment at which each medium's timestamp reaches + * one tick past its highest: one moment for picture and sound, which is why the distance between them holds across the opening and no run starts behind a + * timestamp a viewer already has. + * + * A view's opening from the camera buffer stands on the same highest picture timestamp. Its first picture stands the opening's step past it, at the + * picture's rate, and each later picture at its presentation time's distance from its keyframe's presentation time divided by the opening's own speed, + * which {@link openingSpeed} reads from its stretch's rate as it takes its start. The stretch replays faster than the stream runs, and a picture is + * handed once the live edge has reached its timestamp, the highest picture placed standing at or above it. The rule is the picture's alone, since only the + * picture opens. + */ +export class ClockRun { + private readonly clock: RTPClock + // Whether the run is open, its origin in microseconds of the stream's times, and each medium's timestamp at its opening. + private running = false + private origin = 0 + private readonly openings: Record = { audio: 0, video: 0 } + // Each medium's highest timestamp placed across every run, which a later run and an opening start past, and whether it has placed a sample in the open + // run. + private readonly highest: Record = { audio: Number.NEGATIVE_INFINITY, video: Number.NEGATIVE_INFINITY } + private readonly placedIn: Record = { audio: false, video: false } + private opening = false + + /** + * Makes a run, which opens at its first sample. + * @param clock - The sensor's clock. + */ + constructor(clock: RTPClock) { + this.clock = clock + } + + /** + * Whether the run is open: a sample opened it and no end has been read since. + */ + get open(): boolean { + return this.running + } + + /** + * Whether the latest sample placed was its medium's first of the run, which carries the run's opening for that medium. + */ + get opened(): boolean { + return this.opening + } + + /** + * Opens the run at its first sample, at the moment of the release that sends it or the least later moment at which each medium's timestamp reaches one + * tick past its highest. + * @param origin - The sample's decode time, in microseconds on its stream's clock. + * @param moment - The moment of the tier pacer's release that sends the sample, in milliseconds of a steady clock. + */ + openAt(origin: number, moment: number): void { + let at = moment + + for (const medium of MEDIA) { + at = Math.max(at, this.clock.momentOf(medium, this.highest[medium] + 1)) + } + + for (const medium of MEDIA) { + this.openings[medium] = this.clock.timestamp(medium, at) + this.placedIn[medium] = false + } + + this.origin = origin + this.running = true + } + + /** + * Where an opening's timestamps start: the opening's step past the highest timestamp the run has placed a picture at, across every run its demand opened, + * at the picture's rate. A tier's pacer reads it in its turn, after the turn's releases have placed the opening's keyframe: a picture stands placed. + * @returns The timestamp the opening's keyframe stands at, whole. + */ + openingStart(): number { + return this.highest.video + OPENING_STEP * CLOCK_RATES.video / MILLISECONDS_PER_SECOND + } + + /** + * The timestamp a picture of an opening stands at: the opening's start plus the picture's presentation time's distance from its keyframe's, divided by + * the opening's speed, at the picture's rate to the nearest tick. A picture presented before its keyframe stands at the start, never below it. + * @param start - The opening's start, as {@link openingStart} read it as the opening took its keyframe. + * @param distance - The picture's presentation time less its keyframe's, in microseconds on its stream's clock. + * @param speed - The opening's speed, as {@link openingSpeed} read it from the opening's stretch as the opening took its start. + * @returns The picture's timestamp, whole. + */ + openingTimestamp(start: number, distance: number, speed: number): number { + return start + Math.round(Math.max(distance, 0) * CLOCK_RATES.video / MICROSECONDS_PER_SECOND / speed) + } + + /** + * Whether the live edge has reached a picture timestamp: the highest picture the run has placed stands at or above it, which means a picture of an opening + * handed at it stands at or below every live picture sent from then on. + * @param timestamp - The picture timestamp, whole. + * @returns Whether the edge has reached it. + */ + reached(timestamp: number): boolean { + return this.highest.video >= timestamp + } + + /** + * Ends the run, and the next sample opens a later one. + */ + end(): void { + this.running = false + } + + /** + * Places a sample of the open run. + * @param medium - The sample's medium. + * @param time - The sample's presentation time, in microseconds on its stream's clock. + * @returns The sample's timestamp, whole, or `undefined` for a sound timed before the run's origin, which is not placed. + */ + place(medium: StreamTierMedium, time: number): number | undefined { + const distance = time - this.origin + + if ((distance < 0) && (medium === 'audio')) { + return undefined + } + + const timestamp = this.openings[medium] + Math.round(Math.max(distance, 0) * CLOCK_RATES[medium] / MICROSECONDS_PER_SECOND) + + this.opening = !this.placedIn[medium] + this.placedIn[medium] = true + this.highest[medium] = Math.max(this.highest[medium], timestamp) + + return timestamp + } +} diff --git a/src/lib/camera/rtp/packetRules.spec.ts b/src/lib/camera/rtp/packetRules.spec.ts new file mode 100644 index 000000000..0d3cd19a4 --- /dev/null +++ b/src/lib/camera/rtp/packetRules.spec.ts @@ -0,0 +1,71 @@ +import type * as nodeCrypto from 'node:crypto' + +import { randomInt } from 'node:crypto' + +import { describe, expect, it, vi } from 'vitest' + +import { firstSequence, marksPacket, nextSequence, SEQUENCE_RANGE, wireTimestamp } from './packetRules.js' + +/* The suite's setup file imports the camera controller, whose graph evaluates these rules over node:crypto before this file's mock is in place. The module + * registry is reset first, which is why this file's import evaluates them over the mock. + */ +vi.hoisted(() => vi.resetModules()) + +// node:crypto as it is, its integer draw recorded, which lets a row read what the draw was asked and answered. +vi.mock('node:crypto', async (importOriginal) => { + const actual = await importOriginal() + + return { + ...actual, + randomInt: vi.fn(actual.randomInt), + } +}) + +describe('packetRules', () => { + it('draws a stream\'s first sequence number from the 16-bit range, answering the draw itself', () => { + const draw = vi.mocked(randomInt as (max: number) => number) + + draw.mockReturnValueOnce(0xBEEF) + + expect(firstSequence()).toBe(0xBEEF) + expect(draw).toHaveBeenLastCalledWith(0x10000) + + const drawn = Array.from({ length: 1000 }, () => firstSequence()) + + expect(drawn.every(sequence => Number.isInteger(sequence) && (sequence >= 0) && (sequence < 0x10000))).toBe(true) + expect(new Set(drawn).size).toBeGreaterThan(1) + }) + + it('numbers the packet after one a step on, wrapping from the range\'s last sequence number to zero', () => { + expect([0, 1, 0x7FFF, 0xFFFE, 0xFFFF].map(nextSequence)).toEqual([1, 2, 0x8000, 0xFFFF, 0]) + expect(nextSequence(SEQUENCE_RANGE - 1)).toBe(0) + }) + + it('marks a picture\'s last packet whether or not its frame opens a run, and a sound\'s one packet only when its frame opens one', () => { + const table = [ + [true, true, true, true], + [true, true, false, true], + [true, false, true, false], + [true, false, false, false], + [false, true, true, true], + [false, true, false, false], + [false, false, true, false], + [false, false, false, false], + ] as const + + expect(table.map(([video, last, opensRun]) => marksPacket(video, last, opensRun))).toEqual(table.map(([, , , marked]) => marked)) + }) + + it('writes a timestamp past 2^32 modulo 2^32 and one under it unchanged', () => { + const timestamps = [ + 0, + 7, + 0xFFFFFFFF, + 2 ** 32, + 2 ** 32 + 7, + 3 * 2 ** 32 + 0x1234, + ] + + expect(timestamps.map(wireTimestamp)).toEqual([0, 7, 0xFFFFFFFF, 0, 7, 0x1234]) + }) +}) diff --git a/src/lib/camera/rtp/packetRules.ts b/src/lib/camera/rtp/packetRules.ts new file mode 100644 index 000000000..775577b37 --- /dev/null +++ b/src/lib/camera/rtp/packetRules.ts @@ -0,0 +1,55 @@ +import { randomInt } from 'node:crypto' + +/* The rules of RFC 3550 5.1's fixed RTP header that every packet the library sends follows, whatever its payload: the header's length, the sequence + * number's range with its random start and its wrap, the timestamp as the wire writes it, and the marker. The at-home cutter writes its packets' octets for + * SRTP and the WebRTC engine builds werift's packets from sealed frames, and each packetizer reads these rules. Every packet the library sends is + * numbered, timed and marked alike. + */ + +/** + * The length of RFC 3550 5.1's fixed RTP header, which every RTP packet carries before any CSRC list or header extension. + */ +export const RTP_HEADER_LENGTH = 12 + +/** + * The range of an RTP sequence number, a 16-bit field, which a stream's first sequence number is drawn from and every later one wraps within. + */ +export const SEQUENCE_RANGE = 0x10000 + +/** + * A stream's first sequence number, drawn at random from the range, as RFC 3550 5.1 asks of a stream's start. + * @returns The sequence number. + */ +export function firstSequence(): number { + return randomInt(SEQUENCE_RANGE) +} + +/** + * The sequence number of the packet after one, which wraps from the range's last to zero. + * @param sequence - The packet's sequence number. + * @returns The next packet's. + */ +export function nextSequence(sequence: number): number { + return (sequence + 1) % SEQUENCE_RANGE +} + +/** + * A timestamp as the wire writes it: kept whole by its caller and written modulo 2^32. + * @param timestamp - The timestamp, whole. + * @returns The timestamp modulo 2^32. + */ +export function wireTimestamp(timestamp: number): number { + return timestamp >>> 0 +} + +/** + * Whether a packet carries the marker: a picture's last packet alone (RFC 7798 4.1), and a sound's one packet when its frame opens a run of times (RFC 7587 + * 4.1). + * @param video - Whether the packet carries a picture. + * @param last - Whether the packet is its frame's last, as a sound's one packet is. + * @param opensRun - Whether the packet's frame opens a run of times. + * @returns Whether the packet is marked. + */ +export function marksPacket(video: boolean, last: boolean, opensRun: boolean): boolean { + return last && (video || opensRun) +} diff --git a/src/lib/camera/srtp/SRTPContext.ts b/src/lib/camera/srtp/SRTPContext.ts new file mode 100644 index 000000000..8470890c4 --- /dev/null +++ b/src/lib/camera/srtp/SRTPContext.ts @@ -0,0 +1,530 @@ +import type { Cipheriv } from 'node:crypto' + +import { Buffer } from 'node:buffer' +import crypto from 'node:crypto' + +import { counted } from '../../util/counted.js' +import { RTP_HEADER_LENGTH, SEQUENCE_RANGE } from '../rtp/packetRules.js' +import { applyKeystream, createKeystreamCipher, deriveSessionKey } from './keystream.js' + +/* The SRTP context of one session and direction, carrying one stream: AES_CM_128_HMAC_SHA1_80 alone, no MKI, a ten-octet tag, and the session values RFC + * 3711 4.3.1 derives at a key derivation rate of zero. The 48-bit packet index is carried as its rollover counter and sequence number, each a Number and + * each written into the IV where the index lands. The packet path stays in Number arithmetic, and the packet methods allocate nothing in our own JavaScript + * beyond subarray views: the keystream cipher's update output and the tag's two SHA-1 digests are node:crypto's. A context takes a plain packet of at most + * 1500 octets, one Ethernet payload, which with its ROC or SRTCP index fills its tag work buffer, and refuses a longer one: no work buffer ever grows. + */ + +const MASTER_KEY_LENGTH = 16 +const MASTER_SALT_LENGTH = 14 +const SESSION_KEY_LENGTH = 16 +const SESSION_SALT_LENGTH = 14 +const AUTH_KEY_LENGTH = 20 +const TAG_LENGTH = 10 +const RTCP_HEADER_LENGTH = 8 +const SRTCP_INDEX_LENGTH = 4 + +/** + * The longest plain packet a context protects or unprotects, one Ethernet payload. A reader that hands a context what it received holds the same bound, + * and no packet the reader kept is too long for the context. + */ +export const PLAIN_PACKET_LIMIT = 1500 + +// The longest message a tag covers: the longest plain packet and the ROC or SRTCP index after it. +const TAG_MESSAGE_LIMIT = PLAIN_PACKET_LIMIT + SRTCP_INDEX_LENGTH + +// HMAC-SHA1 (RFC 2104): SHA-1's block and digest lengths, and the pads the authentication key is XORed with for the inner and the outer hash. +const SHA1_BLOCK_LENGTH = 64 +const SHA1_DIGEST_LENGTH = 20 +const INNER_PAD = 0x36 +const OUTER_PAD = 0x5C + +// The counter blocks one keystream update encrypts, enough for a 1378-octet feed payload in one update. +const COUNTER_BLOCKS = 96 + +// The labels RFC 3711 4.3.1 derives each session value under. +const RTP_ENCRYPTION_LABEL = 0 +const RTP_AUTH_LABEL = 1 +const RTP_SALT_LABEL = 2 +const RTCP_ENCRYPTION_LABEL = 3 +const RTCP_AUTH_LABEL = 4 +const RTCP_SALT_LABEL = 5 + +// The distance RFC 3711 3.3.1 reads a sequence number as a wrap or a reordering beyond, half the sequence number's range, whose wraps the rollover +// counter counts in the packet index, and the rollover counter's 32-bit range. +const SEQUENCE_HALF = SEQUENCE_RANGE / 2 +const ROC_RANGE = 0x100000000 + +// The SRTCP index's range, and the E flag that marks an encrypted SRTCP packet. +const SRTCP_INDEX_RANGE = 0x80000000 +const SRTCP_E_FLAG = 0x80000000 + +// The replay window RFC 3711 3.3.2 sets as its minimum: an index this many or more behind the highest one accepted is refused. +const REPLAY_WINDOW = 64 + +/** + * The length of an RTP packet's header: twelve octets, its CSRCs, and the extension its X bit announces, whose length word is read only when the packet holds + * the extension's four-octet header. + * @param packet - The RTP packet. + * @returns The header's length, or `undefined` for a packet shorter than twelve octets or than the header it announces. + */ +export function rtpHeaderLength(packet: Buffer): number | undefined { + if (packet.length < RTP_HEADER_LENGTH) { + return undefined + } + + let length = RTP_HEADER_LENGTH + (packet[0] & 0x0F) * 4 + + if (packet[0] & 0x10) { + if (packet.length < length + 4) { + return undefined + } + + length += 4 + packet.readUInt16BE(length + 2) * 4 + } + + return packet.length < length + ? undefined + : length +} + +/* The replay window RFC 3711 3.3.2 keeps over one stream's packet index: the highest index accepted, unset before the first, and the window behind it as a + * bit field of two words, allocated once, where bit n, counting from the first word's lowest bit, records whether the index n behind the highest was + * accepted. A context keeps one over the RTP index of the packets it unprotects and one over the SRTCP index, each apart from the other. + */ +class ReplayWindow implements Disposable { + private highest?: number + private readonly words = new Uint32Array(REPLAY_WINDOW / 32) + + // Whether the window admits an index: one ahead of the highest accepted always, and one behind it while it sits inside the window unseen. + unseen(index: number): boolean { + const highest = this.highest + + if (highest === undefined || index > highest) { + return true + } + + const behind = highest - index + + return behind < REPLAY_WINDOW && (this.words[behind >>> 5] & (1 << (behind & 31))) === 0 + } + + /* Records an index the window admitted. An index ahead of the highest shifts the window by the distance between them, the bits that pass its far end + * falling away, and becomes the highest at bit zero; an index behind the highest sets its own bit. Each word is a 32-bit lane, and the shift carries the + * first word's top bits into the second. + */ + accept(index: number): void { + const highest = this.highest + const words = this.words + + if (highest !== undefined && index <= highest) { + const behind = highest - index + words[behind >>> 5] |= 1 << (behind & 31) + return + } + + const distance = highest === undefined + ? REPLAY_WINDOW + : index - highest + + if (distance >= REPLAY_WINDOW) { + words[0] = 0 + words[1] = 0 + } else if (distance >= 32) { + words[1] = words[0] << (distance - 32) + words[0] = 0 + } else { + words[1] = (words[1] << distance) | (words[0] >>> (32 - distance)) + words[0] = words[0] << distance + } + + words[0] |= 1 + this.highest = index + } + + // Zeroes the window and forgets the highest index, as the context that holds it is disposed. + [Symbol.dispose](): void { + this.words.fill(0) + this.highest = undefined + } +} + +/** + * The SRTP context of one session and direction. A context keeps one RTP index, its rollover counter and highest sequence number: it either protects one + * stream's RTP packets or unprotects them, never both. Each stream a session sends takes a context of its own, which protects its RTP and SRTCP packets and + * keeps the SRTCP index, and a context under the peer's master key and salt unprotects the RTP and SRTCP packets of a stream the session receives, keeping + * a replay window over the RTP index and another over the SRTCP index, which is why each received stream takes one too. + */ +export class SRTPContext implements Disposable { + private readonly rtpCipher: Cipheriv + private readonly rtpSalt: Buffer + private readonly rtcpCipher: Cipheriv + private readonly rtcpSalt: Buffer + + // Each stream's tag work buffers, built once from its authentication key: the inner one holds the key XOR the inner pad, with room behind it for the + // longest message a tag covers, and the outer one the key XOR the outer pad, with room for the inner digest. + private readonly rtpInner: Buffer + private readonly rtpOuter: Buffer + private readonly rtcpInner: Buffer + private readonly rtcpOuter: Buffer + + // The work buffers, allocated once: the IV block, the counter blocks the keystream is generated from, and the ROC word the tag authenticates. + private readonly iv = Buffer.alloc(16) + private readonly counters = Buffer.alloc(COUNTER_BLOCKS * 16) + private readonly roc = Buffer.alloc(4) + + // The context's one RTP index: the highest sequence number protected or unprotected, unset before the first packet, and the rollover counter beside it. + // Protect and unprotect estimate and advance the same index: a context that did both would read one stream's packets against the other's. + private highestSequence?: number + private rolloverCounter = 0 + private srtcpIndex = 0 + private disposed = false + + // The replay windows of the packets the context unprotects, one over the RTP index and one over the SRTCP index. + private readonly rtpWindow = new ReplayWindow() + private readonly rtcpWindow = new ReplayWindow() + + /** + * Derives the session values of the RTP and SRTCP streams from the master key and salt. + * @param masterKey - The 16-octet master key. + * @param masterSalt - The 14-octet master salt. + */ + constructor(masterKey: Buffer, masterSalt: Buffer) { + if (masterKey.length !== MASTER_KEY_LENGTH) { + throw new TypeError(`The SRTP context takes a ${MASTER_KEY_LENGTH}-octet master key, but the key has ${counted(masterKey.length, 'octet')}.`) + } + + if (masterSalt.length !== MASTER_SALT_LENGTH) { + throw new TypeError(`The SRTP context takes a ${MASTER_SALT_LENGTH}-octet master salt, but the salt has ${counted(masterSalt.length, 'octet')}.`) + } + + const rtpAuthKey = deriveSessionKey(masterKey, masterSalt, RTP_AUTH_LABEL, AUTH_KEY_LENGTH) + const rtcpAuthKey = deriveSessionKey(masterKey, masterSalt, RTCP_AUTH_LABEL, AUTH_KEY_LENGTH) + + this.rtpCipher = SRTPContext.cipherOf(deriveSessionKey(masterKey, masterSalt, RTP_ENCRYPTION_LABEL, SESSION_KEY_LENGTH)) + this.rtpSalt = deriveSessionKey(masterKey, masterSalt, RTP_SALT_LABEL, SESSION_SALT_LENGTH) + this.rtpInner = SRTPContext.padded(rtpAuthKey, INNER_PAD, TAG_MESSAGE_LIMIT) + this.rtpOuter = SRTPContext.padded(rtpAuthKey, OUTER_PAD, SHA1_DIGEST_LENGTH) + this.rtcpCipher = SRTPContext.cipherOf(deriveSessionKey(masterKey, masterSalt, RTCP_ENCRYPTION_LABEL, SESSION_KEY_LENGTH)) + this.rtcpSalt = deriveSessionKey(masterKey, masterSalt, RTCP_SALT_LABEL, SESSION_SALT_LENGTH) + this.rtcpInner = SRTPContext.padded(rtcpAuthKey, INNER_PAD, TAG_MESSAGE_LIMIT) + this.rtcpOuter = SRTPContext.padded(rtcpAuthKey, OUTER_PAD, SHA1_DIGEST_LENGTH) + + // Each authentication key lives on only in its pads, which is why it is zeroed once its pads are built, as an encryption key is once its cipher holds it. + rtpAuthKey.fill(0) + rtcpAuthKey.fill(0) + } + + /** + * Protects an RTP packet into `output`: its payload, padding included, encrypted and the authentication tag appended. A packet shorter than the header it + * announces, or longer than 1500 octets, one Ethernet payload, is refused with a `RangeError`. + * @param packet - The RTP packet. + * @param output - The buffer the SRTP packet is written to, at least ten octets longer than the packet. + * @returns The SRTP packet's length. + */ + protect(packet: Buffer, output: Buffer): number { + this.assertLive() + + const headerLength = rtpHeaderLength(packet) + + if (headerLength === undefined) { + throw new RangeError(`The RTP packet holds ${counted(packet.length, 'octet')}, fewer than the header it announces.`) + } + + if (output.length < packet.length + TAG_LENGTH) { + throw new RangeError(`The SRTP output holds ${counted(output.length, 'octet')}, but the packet needs ${packet.length + TAG_LENGTH}.`) + } + + if (packet.length > PLAIN_PACKET_LIMIT) { + throw new RangeError(`The RTP packet holds ${packet.length} octets, more than the ${PLAIN_PACKET_LIMIT} a context protects.`) + } + + const sequence = packet.readUInt16BE(2) + const roc = this.estimateRolloverCounter(sequence) + + this.writeRTPIV(packet, roc) + packet.copy(output, 0, 0, packet.length) + applyKeystream(this.rtpCipher, this.iv, output.subarray(headerLength, packet.length), this.counters) + + // The tag is the first ten octets of HMAC-SHA1 over the packet, then the ROC. + SRTPContext.tag(this.rtpInner, this.rtpOuter, output.subarray(0, packet.length), this.roc).copy(output, packet.length, 0, TAG_LENGTH) + + this.advance(sequence, roc) + + return packet.length + TAG_LENGTH + } + + /** + * Protects an RTCP packet into `output`: everything after its first eight octets encrypted, the E flag and the SRTCP index appended, then the tag. A + * packet shorter than its header, or longer than 1500 octets, one Ethernet payload, is refused with a `RangeError`. + * @param packet - The RTCP packet, a compound packet included. + * @param output - The buffer the SRTCP packet is written to, at least fourteen octets longer than the packet. + * @returns The SRTCP packet's length. + */ + protectRTCP(packet: Buffer, output: Buffer): number { + this.assertLive() + + if (packet.length < RTCP_HEADER_LENGTH) { + throw new RangeError(`The RTCP packet holds ${counted(packet.length, 'octet')}, fewer than the ${RTCP_HEADER_LENGTH} of its header.`) + } + + const length = packet.length + SRTCP_INDEX_LENGTH + TAG_LENGTH + + if (output.length < length) { + throw new RangeError(`The SRTCP output holds ${counted(output.length, 'octet')}, but the packet needs ${length}.`) + } + + if (packet.length > PLAIN_PACKET_LIMIT) { + throw new RangeError(`The RTCP packet holds ${packet.length} octets, more than the ${PLAIN_PACKET_LIMIT} a context protects.`) + } + + this.writeRTCPIV(packet, this.srtcpIndex) + packet.copy(output, 0, 0, packet.length) + applyKeystream(this.rtcpCipher, this.iv, output.subarray(RTCP_HEADER_LENGTH, packet.length), this.counters) + output.writeUInt32BE((SRTCP_E_FLAG | this.srtcpIndex) >>> 0, packet.length) + + const authenticated = packet.length + SRTCP_INDEX_LENGTH + SRTPContext.tag(this.rtcpInner, this.rtcpOuter, output.subarray(0, authenticated)).copy(output, authenticated, 0, TAG_LENGTH) + + this.srtcpIndex = (this.srtcpIndex + 1) % SRTCP_INDEX_RANGE + + return length + } + + /** + * Unprotects an SRTP packet into `output` (RFC 3711 3.3 and 3.3.2): the rollover counter is estimated from the highest index accepted, an index the replay + * window has seen or one 64 or more behind the highest accepted is refused, the tag is checked over the packet and that counter, and the payload past the + * header is decrypted, after which the index advances. A refused packet advances nothing. The output may be the packet's own buffer, which then holds the + * RTP packet in place with the tag behind it, because the tag is read before the keystream runs. + * @param packet - The SRTP packet. + * @param output - The buffer the RTP packet is written to, at least as long as the packet less its ten-octet tag, the packet's own buffer among them. + * @returns The RTP packet's length, or `undefined` for a packet too short to carry the header it announces and a tag, one whose RTP packet is longer than + * 1500 octets, one whose tag fails, or a replay. + */ + unprotect(packet: Buffer, output: Buffer): number | undefined { + this.assertLive() + + if (packet.length < RTP_HEADER_LENGTH + TAG_LENGTH) { + return undefined + } + + const length = packet.length - TAG_LENGTH + const headerLength = rtpHeaderLength(packet.subarray(0, length)) + + if (headerLength === undefined || length > PLAIN_PACKET_LIMIT) { + return undefined + } + + if (output.length < length) { + throw new RangeError(`The RTP output holds ${counted(output.length, 'octet')}, but the packet needs ${length}.`) + } + + const sequence = packet.readUInt16BE(2) + const roc = this.estimateRolloverCounter(sequence) + const index = roc * SEQUENCE_RANGE + sequence + + if (!this.rtpWindow.unseen(index)) { + return undefined + } + + this.writeRTPIV(packet, roc) + + const digest = SRTPContext.tag(this.rtpInner, this.rtpOuter, packet.subarray(0, length), this.roc) + + if (!crypto.timingSafeEqual(digest.subarray(0, TAG_LENGTH), packet.subarray(length))) { + return undefined + } + + packet.copy(output, 0, 0, length) + applyKeystream(this.rtpCipher, this.iv, output.subarray(headerLength, length), this.counters) + + this.advance(sequence, roc) + this.rtpWindow.accept(index) + + return length + } + + /** + * Unprotects an SRTCP packet into `output` (RFC 3711 3.4 and 3.3.2): the tag is checked over the packet and its E flag and index, an index the replay + * window has seen or one 64 or more behind the highest accepted is refused, and the packet is decrypted after its first eight octets when its E flag is + * set and copied as it is when the flag is clear. A refused packet advances nothing. + * @param packet - The SRTCP packet, a compound packet included. + * @param output - The buffer the RTCP packet is written to, at least as long as the packet less its fourteen trailing octets. + * @returns The RTCP packet's length, or `undefined` for a packet too short to carry a header, an index and a tag, one whose RTCP packet is longer than + * 1500 octets, one whose tag fails, or a replay. + */ + unprotectRTCP(packet: Buffer, output: Buffer): number | undefined { + this.assertLive() + + if (packet.length < RTCP_HEADER_LENGTH + SRTCP_INDEX_LENGTH + TAG_LENGTH) { + return undefined + } + + const length = packet.length - SRTCP_INDEX_LENGTH - TAG_LENGTH + + if (length > PLAIN_PACKET_LIMIT) { + return undefined + } + + if (output.length < length) { + throw new RangeError(`The RTCP output holds ${counted(output.length, 'octet')}, but the packet needs ${length}.`) + } + + const trailer = packet.readUInt32BE(length) + const index = trailer % SRTCP_INDEX_RANGE + + if (!this.rtcpWindow.unseen(index)) { + return undefined + } + + const digest = SRTPContext.tag(this.rtcpInner, this.rtcpOuter, packet.subarray(0, length + SRTCP_INDEX_LENGTH)) + + if (!crypto.timingSafeEqual(digest.subarray(0, TAG_LENGTH), packet.subarray(length + SRTCP_INDEX_LENGTH))) { + return undefined + } + + packet.copy(output, 0, 0, length) + + if (trailer >= SRTCP_E_FLAG) { + this.writeRTCPIV(packet, index) + applyKeystream(this.rtcpCipher, this.iv, output.subarray(RTCP_HEADER_LENGTH, length), this.counters) + } + + this.rtcpWindow.accept(index) + + return length + } + + /** + * Zeroes every key, salt, work buffer and replay window the context holds, after which the packet methods throw a `ReferenceError`; a second call does + * nothing. Each keystream cipher keeps its key inside node:crypto until it is collected, which no call here can reach. + */ + [Symbol.dispose](): void { + if (this.disposed) { + return + } + + this.disposed = true + + for (const buffer of [ + this.rtpInner, + this.rtpOuter, + this.rtpSalt, + this.rtcpInner, + this.rtcpOuter, + this.rtcpSalt, + this.iv, + this.counters, + this.roc, + ]) { + buffer.fill(0) + } + + this.rtpWindow[Symbol.dispose]() + this.rtcpWindow[Symbol.dispose]() + } + + // The keystream cipher of a derived encryption key, which is zeroed once node:crypto holds its copy: the context keeps no copy of its own. + private static cipherOf(key: Buffer): Cipheriv { + const cipher = createKeystreamCipher(key) + key.fill(0) + + return cipher + } + + // A tag work buffer (RFC 2104): the authentication key, zero-padded to one SHA-1 block, XOR the pad, with room behind the block for what the hash covers next. + private static padded(key: Buffer, pad: number, room: number): Buffer { + const buffer = Buffer.alloc(SHA1_BLOCK_LENGTH + room) + buffer.fill(pad, 0, SHA1_BLOCK_LENGTH) + + for (let octet = 0; octet < key.length; octet++) { + buffer[octet] ^= key[octet] + } + + return buffer + } + + /* The HMAC-SHA1 digest whose first ten octets are a tag, over the message and, for RTP, the ROC after it, as two one-shot hashes over a stream's work + * buffers: the message goes in behind the inner pad and is hashed, and that digest goes in behind the outer pad and is hashed in turn. No Hmac object is + * created per packet. Each caller keeps its message within TAG_MESSAGE_LIMIT, which means every copy here is whole. The two digests are node:crypto's. + */ + private static tag(inner: Buffer, outer: Buffer, message: Buffer, roc?: Buffer): Buffer { + let end = SHA1_BLOCK_LENGTH + message.copy(inner, SHA1_BLOCK_LENGTH) + + if (roc) { + end += roc.copy(inner, end) + } + + crypto.hash('sha1', inner.subarray(0, end), 'buffer').copy(outer, SHA1_BLOCK_LENGTH) + + return crypto.hash('sha1', outer, 'buffer') + } + + /* The packet's rollover counter by RFC 3711 3.3.1: a sequence number more than half the range behind the highest one protected belongs to the next ROC + * when the highest sits in the range's upper half, and one more than half ahead belongs to the previous ROC when it sits in the lower half. A wrap + * and a reordering across it each keep their index. The counter is a 32-bit value, and the previous ROC of ROC zero wraps to its top. + */ + private estimateRolloverCounter(sequence: number): number { + const highest = this.highestSequence + + if (highest === undefined) { + return this.rolloverCounter + } + + if (highest < SEQUENCE_HALF) { + return sequence - highest > SEQUENCE_HALF + ? (this.rolloverCounter + ROC_RANGE - 1) % ROC_RANGE + : this.rolloverCounter + } + + return highest - SEQUENCE_HALF > sequence + ? (this.rolloverCounter + 1) % ROC_RANGE + : this.rolloverCounter + } + + // Advances the context's RTP index, as RFC 3711 3.3.1 updates it: a packet of the next ROC, or of this ROC beyond the highest sequence number, moves it, + // and a reordered packet leaves the state where it was. Protect advances it for every packet, and unprotect only for one whose tag holds. + private advance(sequence: number, roc: number): void { + const highest = this.highestSequence + + if (highest === undefined || roc === (this.rolloverCounter + 1) % ROC_RANGE || (roc === this.rolloverCounter && sequence > highest)) { + this.highestSequence = sequence + this.rolloverCounter = roc + } + } + + /* The RTP IV, (salt x 2^16) XOR (SSRC x 2^64) XOR (index x 2^16): the SSRC lands in octets 4 to 7 and the index, the ROC then the sequence number, in + * octets 8 to 13, the last two octets staying zero for the block count. The ROC word it writes is the one the packet's tag then covers. + */ + private writeRTPIV(packet: Buffer, roc: number): void { + this.rtpSalt.copy(this.iv, 0) + this.iv.writeUInt16BE(0, SESSION_SALT_LENGTH) + for (let octet = 0; octet < 4; octet++) { + this.iv[4 + octet] ^= packet[8 + octet] + } + this.roc.writeUInt32BE(roc, 0) + for (let octet = 0; octet < 4; octet++) { + this.iv[8 + octet] ^= this.roc[octet] + } + this.iv[12] ^= packet[2] + this.iv[13] ^= packet[3] + } + + // The SRTCP IV takes the SRTCP index where the RTP IV takes the packet index, and the index lands in octets 10 to 13 beside the sender's SSRC in 4 to 7. + private writeRTCPIV(packet: Buffer, index: number): void { + this.rtcpSalt.copy(this.iv, 0) + this.iv.writeUInt16BE(0, SESSION_SALT_LENGTH) + for (let octet = 0; octet < 4; octet++) { + this.iv[4 + octet] ^= packet[4 + octet] + } + this.roc.writeUInt32BE(index, 0) + for (let octet = 0; octet < 4; octet++) { + this.iv[10 + octet] ^= this.roc[octet] + } + } + + private assertLive(): void { + if (this.disposed) { + throw new ReferenceError('The SRTP context has been disposed.') + } + } +} diff --git a/src/lib/camera/srtp/keystream.ts b/src/lib/camera/srtp/keystream.ts new file mode 100644 index 000000000..407b89d7c --- /dev/null +++ b/src/lib/camera/srtp/keystream.ts @@ -0,0 +1,81 @@ +import type { Cipheriv } from 'node:crypto' + +import { Buffer } from 'node:buffer' +import crypto from 'node:crypto' + +/* The AES counter-mode primitives of SRTP (RFC 3711 4.1.1 and 4.3.1). The keystream comes from one long-lived AES-128-ECB cipher per key encrypting counter + * blocks, rather than from a fresh AES-128-CTR cipher per packet: ECB carries no state between blocks, which means one cipher serves every packet a context + * protects, and the packet path creates no cipher. A packet's counter blocks are its IV with the block number in the last two octets, which RFC 3711 keeps + * zero in the IV. The count never carries into the IV's other octets. + */ + +// The AES block size in octets. +const BLOCK_LENGTH = 16 + +/** + * Creates the long-lived cipher that turns counter blocks into keystream under one key. + * @param key - The AES-128 key. + * @returns The cipher, padding off: every update returns exactly the blocks it was given. + */ +export function createKeystreamCipher(key: Buffer): Cipheriv { + const cipher = crypto.createCipheriv('aes-128-ecb', key, null) + cipher.setAutoPadding(false) + + return cipher +} + +/** + * XORs into `data`, in place, the AES-CM keystream of the counter blocks that count up from `iv`: block `j` is `iv` with `j` in its last two octets, + * big-endian. The blocks are encrypted as many at a time as `counters` holds, looping until `data` is covered, and a payload of any length takes the same + * path a feed packet takes in one update. + * @param cipher - The keystream cipher, from {@link createKeystreamCipher}. + * @param iv - The packet's IV, its last two octets zero. + * @param data - The octets to encrypt or decrypt. + * @param counters - The work buffer the counter blocks are written to, a whole number of blocks long. + */ +export function applyKeystream(cipher: Cipheriv, iv: Buffer, data: Buffer, counters: Buffer): void { + const capacity = Math.floor(counters.length / BLOCK_LENGTH) + let block = 0 + + for (let offset = 0; offset < data.length; offset += capacity * BLOCK_LENGTH) { + const blocks = Math.min(capacity, Math.ceil((data.length - offset) / BLOCK_LENGTH)) + + // One fill writes the IV into every counter block the update needs, one native call where a copy per block would make one for each block, and each + // block's number then takes its last two octets. + counters.fill(iv, 0, blocks * BLOCK_LENGTH) + + for (let index = 0; index < blocks; index++) { + counters.writeUInt16BE(block + index, index * BLOCK_LENGTH + BLOCK_LENGTH - 2) + } + + // The update's output is node:crypto's allocation, the one the packet path accepts. + const keystream = cipher.update(counters.subarray(0, blocks * BLOCK_LENGTH)) + const end = Math.min(data.length, offset + blocks * BLOCK_LENGTH) + + for (let position = offset; position < end; position++) { + data[position] ^= keystream[position - offset] + } + + block += blocks + } +} + +/** + * Derives one session value from the master key and salt, RFC 3711 4.3.1 at a key derivation rate of zero: the master salt with `label` XORed into its + * eighth octet and two zero octets appended is the IV of the keystream the master key generates, and the value is the first `length` octets of it. + * @param masterKey - The 16-octet master key. + * @param masterSalt - The 14-octet master salt. + * @param label - The value's label: 0, 1 and 2 for the RTP encryption key, authentication key and salt, 3, 4 and 5 for SRTCP's. + * @param length - The value's length in octets. + * @returns The session value. + */ +export function deriveSessionKey(masterKey: Buffer, masterSalt: Buffer, label: number, length: number): Buffer { + const iv = Buffer.alloc(BLOCK_LENGTH) + masterSalt.copy(iv, 0, 0, BLOCK_LENGTH - 2) + iv[7] ^= label + + const value = Buffer.alloc(length) + applyKeystream(createKeystreamCipher(masterKey), iv, value, Buffer.alloc(Math.ceil(length / BLOCK_LENGTH) * BLOCK_LENGTH)) + + return value +} diff --git a/src/test-utils/mp4Fixtures.ts b/src/test-utils/mp4Fixtures.ts new file mode 100644 index 000000000..9246f7ac3 --- /dev/null +++ b/src/test-utils/mp4Fixtures.ts @@ -0,0 +1,625 @@ +/* The MP4 boxes the box reader's, the stream reader's and the producer reference time writer's suites share, and the tier streams the suites of a tier's + * stream write. Boxes built by hand reach every edge deterministically: each size form, each version, audio as track 1, two fragments in a packet, a + * segment type or a segment index before a fragment, decoder configuration records holding parameter sets, and fragments whose media data carries each + * sample's own bytes. The skeleton beside them proves + * the reader on a real muxer's box set, with what no hand-built box carries: its user data, and a track fragment header that names a default sample size + * and default sample flags beside its default duration. + */ +import type { StreamTierMedium, TierFrame, TierStream } from '../lib/camera/StreamingOptions.js' + +import { Buffer } from 'node:buffer' + +export function uint16(value: number): Buffer { + const buffer = Buffer.alloc(2) + + buffer.writeUInt16BE(value) + + return buffer +} + +export function int32(value: number): Buffer { + const buffer = Buffer.alloc(4) + + buffer.writeInt32BE(value) + + return buffer +} + +export function uint32(value: number): Buffer { + const buffer = Buffer.alloc(4) + + buffer.writeUInt32BE(value) + + return buffer +} + +export function uint64(value: bigint): Buffer { + const buffer = Buffer.alloc(8) + + buffer.writeBigUInt64BE(value) + + return buffer +} + +// A box with a 32-bit size. +export function box(type: string, ...payload: Uint8Array[]): Buffer { + const body = Buffer.concat(payload) + + return Buffer.concat([ + uint32(8 + body.length), + Buffer.from(type, 'latin1'), + body, + ]) +} + +// A box whose size is 1 and whose 64-bit size follows its type. +export function largeBox(type: string, ...payload: Uint8Array[]): Buffer { + const body = Buffer.concat(payload) + + return Buffer.concat([ + uint32(1), + Buffer.from(type, 'latin1'), + uint64(BigInt(16 + body.length)), + body, + ]) +} + +// A box whose size is 0: it runs to the end of what holds it. +export function openBox(type: string, ...payload: Uint8Array[]): Buffer { + return Buffer.concat([ + uint32(0), + Buffer.from(type, 'latin1'), + ...payload, + ]) +} + +// A box with a version and 24 bits of flags before its fields. +export function fullBox(type: string, version: number, flags: number, ...fields: Uint8Array[]): Buffer { + return box(type, uint32((version << 24) | flags), ...fields) +} + +export interface TrackFixture { + // The track's default sample duration, written in a trex box of the segment's mvex. + defaultDuration?: number + handler: string + id: number + // The track's one sample entry, written in its stsd box. + sampleEntry?: Buffer + timescale: number + version?: 0 | 1 +} + +// A video sample entry: eight bytes of sample entry, sixteen of pre-definition, its width and height, and the rest of its 78 bytes of fields, then its boxes. +export function visualSampleEntry(type: string, width: number, height: number, ...boxes: Buffer[]): Buffer { + const fields = Buffer.alloc(78) + + fields.writeUInt16BE(1, 6) + fields.writeUInt16BE(width, 24) + fields.writeUInt16BE(height, 26) + fields.writeUInt32BE(0x00480000, 28) + fields.writeUInt32BE(0x00480000, 32) + fields.writeUInt16BE(1, 40) + fields.writeUInt16BE(0x18, 74) + fields.writeInt16BE(-1, 76) + + return box(type, fields, ...boxes) +} + +// An audio sample entry of 28 bytes of fields, one channel of 16-bit samples at 16 kHz, then its boxes. +export function audioSampleEntry(type: string, ...boxes: Buffer[]): Buffer { + const fields = Buffer.alloc(28) + + fields.writeUInt16BE(1, 6) + fields.writeUInt16BE(1, 16) + fields.writeUInt16BE(16, 18) + fields.writeUInt32BE(16000 * 65536, 24) + + return box(type, fields, ...boxes) +} + +// An Opus entry whose Opus Specific Box names one channel, no pre-skip, an input rate of 48 kHz, no output gain and channel mapping family 0. +export function opusSampleEntry(): Buffer { + return audioSampleEntry('Opus', box('dOps', Buffer.from([0, 1, 0, 0]), uint32(48000), Buffer.from([0, 0, 0]))) +} + +// An avc1 entry whose avcC carries the profile, compatibility and level given. +export function avc1SampleEntry(width: number, height: number, profile: number, compatibility: number, level: number): Buffer { + return visualSampleEntry('avc1', width, height, box('avcC', Buffer.from([ + 1, + profile, + compatibility, + level, + 0xFF, + 0xE0, + ]))) +} + +// An hvc1 entry whose hvcC opens with the thirteen bytes given, its configuration version, profile, compatibility, constraint and level fields, then the +// rest of a record's fixed fields for 8-bit 4:2:0 video with no parameter set arrays. The default names the Main profile at the main tier and level 4.0. +export function hvc1SampleEntry(width: number, height: number, head: Buffer = Buffer.from('01016000000090000000000078', 'hex')): Buffer { + return visualSampleEntry('hvc1', width, height, box('hvcC', head, Buffer.from('f000fcfdf8f800000f00', 'hex'))) +} + +// A decoder configuration record's NAL units, each behind its 16-bit length. +function lengthPrefixed(units: Buffer[]): Buffer[] { + return units.flatMap(unit => [ + uint16(unit.length), + unit, + ]) +} + +// An avcC of the Main profile at level 3.1 holding the sequence and picture parameter sets given, its samples' NAL unit lengths in the octets given. +export function avcC(sequence: Buffer[], picture: Buffer[], nalLengthSize = 4): Buffer { + return box( + 'avcC', + Buffer.from([ + 1, + 0x4D, + 0x40, + 0x1F, + 0xFC | (nalLengthSize - 1), + 0xE0 | sequence.length, + ]), + ...lengthPrefixed(sequence), + Buffer.from([picture.length]), + ...lengthPrefixed(picture), + ) +} + +// One array of an hvcC: the type of its NAL units, the units, and whether the array is marked complete, as it is unless it says otherwise. +export interface NalUnitArray { + complete?: boolean + type: number + units: Buffer[] +} + +// An hvcC of the Main profile at the main tier and level 4.0 holding the arrays given in order, each marked complete unless it says otherwise, its samples' +// NAL unit lengths in the octets given: the fixed fields of hvc1SampleEntry's default record, then its byte of frame rate, temporal layers and length size, +// and its count of arrays. +export function hvcC(arrays: NalUnitArray[], nalLengthSize = 4): Buffer { + return box( + 'hvcC', + Buffer.from('01016000000090000000000078f000fcfdf8f80000', 'hex'), + Buffer.from([0x0C | (nalLengthSize - 1), arrays.length]), + ...arrays.flatMap(({ complete = true, type, units }) => [ + Buffer.from([(complete ? 0x80 : 0) | type]), + uint16(units.length), + ...lengthPrefixed(units), + ]), + ) +} + +// One esds descriptor, its length written in four bytes of seven bits each as muxers write it. +function descriptor(tag: number, ...payload: Buffer[]): Buffer { + const body = Buffer.concat(payload) + + return Buffer.concat([ + Buffer.from([tag, 0x80, 0x80, 0x80, body.length]), + body, + ]) +} + +// An mp4a entry whose esds names MPEG-4 audio and an audio specific config opening with the audio object type given, escaped past 30 as the format does. +// Its ES descriptor carries the flags given after its ES ID, with the optional fields they name, and none by default. +export function mp4aSampleEntry(audioObjectType: number, flagged: Buffer = Buffer.from([0])): Buffer { + const config = audioObjectType < 31 + ? Buffer.from([(audioObjectType << 3) | 0x04, 0x08]) + : Buffer.from([0xF8 | ((audioObjectType - 32) >> 3), ((audioObjectType - 32) & 0x07) << 5]) + const decoderConfig = Buffer.concat([ + Buffer.from([0x40, 0x15, 0, 0, 0]), + uint32(64000), + uint32(64000), + ]) + + return audioSampleEntry('mp4a', fullBox('esds', 0, 0, descriptor(0x03, Buffer.from([0, 1]), flagged, descriptor(0x04, decoderConfig, descriptor(0x05, config))))) +} + +// A track: its header with its identifier, then its media with its header's timescale and its handler type, the identifier and the timescale each following +// creation and modification times of its version's width, and, when it has a sample entry, its sample table's description of it. +export function trak({ handler, id, sampleEntry, timescale, version = 0 }: TrackFixture): Buffer { + const times = Buffer.alloc(version === 1 + ? 16 + : 8) + const media = [ + fullBox('mdhd', version, 0, times, uint32(timescale), uint32(0)), + fullBox('hdlr', 0, 0, Buffer.alloc(4), Buffer.from(handler, 'latin1'), Buffer.alloc(12)), + ] + + if (sampleEntry !== undefined) { + media.push(box('minf', box('stbl', fullBox('stsd', 0, 0, uint32(1), sampleEntry)))) + } + + return box('trak', fullBox('tkhd', version, 3, times, uint32(id), Buffer.alloc(4)), box('mdia', ...media)) +} + +// A track's default sample duration as a movie extends box holds it. +export function trex(trackId: number, defaultDuration: number): Buffer { + return fullBox('trex', 0, 0, uint32(trackId), uint32(1), uint32(defaultDuration), uint32(0), uint32(0)) +} + +// An initialization segment of the tracks given, in their order, with a movie extends box when a track has a default sample duration. +export function initializationSegment(...tracks: TrackFixture[]): Buffer { + const defaults = tracks.filter(({ defaultDuration }) => defaultDuration !== undefined).map(({ defaultDuration, id }) => trex(id, defaultDuration!)) + + return Buffer.concat([ + box('ftyp', Buffer.from('iso5', 'latin1'), uint32(512)), + box('moov', ...tracks.map(trak), ...(defaults.length === 0 + ? [] + : [ + box('mvex', ...defaults), + ])), + ]) +} + +export interface TrackFragmentFixture { + decodeTime?: bigint + // The run's default sample duration, written in its tfhd. + defaultDuration?: number + // A trun of this many samples carrying no duration, or of samples carrying these durations. + samples?: number | number[] + trackId: number + version?: 0 | 1 +} + +// A run's samples: a data offset, then each sample's size, beside its duration when the durations are given. +export function trun(samples: number | number[]): Buffer { + if (typeof samples === 'number') { + return fullBox('trun', 0, 0x201, uint32(samples), uint32(0), ...Array.from({ length: samples }, () => uint32(16))) + } + + return fullBox('trun', 0, 0x301, uint32(samples.length), uint32(0), ...samples.flatMap(duration => [ + uint32(duration), + uint32(16), + ])) +} + +// A track's run: its header with the track's identifier and any default duration, then, when it has them, its decode time in the width of its version +// and its samples. +export function traf({ decodeTime, defaultDuration, samples, trackId, version = 1 }: TrackFragmentFixture): Buffer { + const parts = [ + defaultDuration === undefined + ? fullBox('tfhd', 0, 0x20000, uint32(trackId)) + : fullBox('tfhd', 0, 0x20008, uint32(trackId), uint32(defaultDuration)), + ] + + if (decodeTime !== undefined) { + parts.push(fullBox('tfdt', version, 0, version === 1 + ? uint64(decodeTime) + : uint32(Number(decodeTime)))) + } + + if (samples !== undefined) { + parts.push(trun(samples)) + } + + return box('traf', ...parts) +} + +// A fragment of the runs given and its media data. +export function mediaFragment(...runs: TrackFragmentFixture[]): Buffer { + return Buffer.concat([ + box('moof', fullBox('mfhd', 0, 0, uint32(1)), ...runs.map(traf)), + box('mdat', Buffer.alloc(16, 0xA5)), + ]) +} + +export interface SampleFixture { + // The sample's bytes, which the fragment's media data carries. + data: Buffer + compositionOffset?: number + duration?: number + flags?: number +} + +export interface SampleRunFixture { + // The run's decode time, written in a tfdt of its version. + decodeTime?: bigint + samples: SampleFixture[] + trackId: number + // The trun's version, whose composition offsets are signed in version 1. + trunVersion?: 0 | 1 + version?: 0 | 1 +} + +/* A track's run carrying its samples: a tfhd counting the run's data from the moof, its decode time when it has one, and a trun naming the data offset + * given and each sample's size, with each sample's duration, flags and composition offset wherever one of the run's samples has one, 0 for the others. + */ +function sampleTraf({ decodeTime, samples, trackId, trunVersion = 0, version = 1 }: SampleRunFixture, dataOffset: number): Buffer { + const present = { + compositionOffset: samples.some(sample => sample.compositionOffset !== undefined), + duration: samples.some(sample => sample.duration !== undefined), + flags: samples.some(sample => sample.flags !== undefined), + } + let flags = 0x201 + const fields: Buffer[] = [] + + flags |= present.duration ? 0x100 : 0 + flags |= present.flags ? 0x400 : 0 + flags |= present.compositionOffset ? 0x800 : 0 + + for (const { compositionOffset = 0, data, duration = 0, flags: sampleFlags = 0 } of samples) { + if (present.duration) { + fields.push(uint32(duration)) + } + + fields.push(uint32(data.length)) + + if (present.flags) { + fields.push(uint32(sampleFlags)) + } + + if (present.compositionOffset) { + fields.push(int32(compositionOffset)) + } + } + + const parts = [ + fullBox('tfhd', 0, 0x20000, uint32(trackId)), + ] + + if (decodeTime !== undefined) { + parts.push(fullBox('tfdt', version, 0, version === 1 + ? uint64(decodeTime) + : uint32(Number(decodeTime)))) + } + + parts.push(fullBox('trun', trunVersion, flags, uint32(samples.length), int32(dataOffset), ...fields)) + + return box('traf', ...parts) +} + +// A fragment of the runs given and a media data box of their samples' bytes in order, each run's data offset counted from the moof to its first sample. +export function sampleFragment(...runs: SampleRunFixture[]): Buffer { + const moofOf = (offsets: number[]): Buffer => box('moof', fullBox('mfhd', 0, 0, uint32(1)), ...runs.map((run, index) => sampleTraf(run, offsets[index]))) + const sampleBytes = runs.map(({ samples }) => Buffer.concat(samples.map(({ data }) => data))) + const media = moofOf(runs.map(() => 0)).length + 8 + const offsets = sampleBytes.map((_, index) => media + sampleBytes.slice(0, index).reduce((sum, bytes) => sum + bytes.length, 0)) + + return Buffer.concat([ + moofOf(offsets), + box('mdat', ...sampleBytes), + ]) +} + +// The flags of a sync sample that depends on no other, and of a sample that is no sync sample and depends on one before it. +const SYNC_SAMPLE = 0x02000000 +const DEPENDENT_SAMPLE = 0x01010000 + +// A tier's stream as a plugin writes it to its TierStream: its picture on track 1 at 90 kHz and its sound on track 2 at 48 kHz. +export const TIER_STREAM_PICTURE = 1 +export const TIER_STREAM_SOUND = 2 + +/* A tier's stream's initialization segment: an hvc1 picture track whose hvcC holds the parameter sets given, each its NAL unit with its header, in an array + * of its own type, beside an Opus sound track unless the stream has none. + */ +export function tierStreamInitialization({ parameterSets = [], sound = true }: { parameterSets?: readonly Buffer[], sound?: boolean } = {}): Buffer { + const tracks: TrackFixture[] = [ + { + handler: 'vide', + id: TIER_STREAM_PICTURE, + sampleEntry: visualSampleEntry('hvc1', 64, 36, hvcC(parameterSets.map(unit => ({ + type: (unit[0] >> 1) & 0x3F, + units: [unit], + })))), + timescale: 90000, + }, + ] + + if (sound) { + tracks.push({ + handler: 'soun', + id: TIER_STREAM_SOUND, + sampleEntry: opusSampleEntry(), + timescale: 48000, + }) + } + + return initializationSegment(...tracks) +} + +// A picture sample of a tier's stream: a frame's bytes, each NAL unit behind its four-octet length, 3000 ticks long at 90 kHz, a sync sample when it is a +// keyframe. +export function pictureSample(data: Buffer, keyframe = false): SampleFixture { + return { + data, + duration: 3000, + flags: keyframe + ? SYNC_SAMPLE + : DEPENDENT_SAMPLE, + } +} + +// A sound sample of a tier's stream: one Opus packet, 960 ticks long at 48 kHz. +export function soundSample(data: Buffer): SampleFixture { + return { + data, + duration: 960, + } +} + +// HEVC's video, sequence and picture parameter sets, each a NAL unit of 12 octets with its header, which a tier's stream carries in its hvcC or in band. +export const TIER_STREAM_PARAMETER_SETS: readonly Buffer[] = [32, 33, 34].map(type => Buffer.concat([ + Buffer.from([type << 1, 0x01]), + Buffer.alloc(10, type), +])) + +// A frame's units, each behind its four-octet length, after those parameter sets in band, as a keyframe that opens a viewer's pictures carries them. +export function withParameterSets(units: Buffer): Buffer { + return Buffer.concat([ + ...TIER_STREAM_PARAMETER_SETS.flatMap(unit => [ + uint32(unit.length), + unit, + ]), + units, + ]) +} + +export interface TierPictureFixture { + // A sync sample, its picture an IDR slice, carrying in band before its slice each of the parameter sets where asked, or those listed alone. + inBand?: boolean | readonly Buffer[] + keyframe?: boolean + // The sample's octets, 100 by default. + octets?: number + // A sample that states no duration of its own. + untimed?: boolean +} + +/* A picture sample of a tier's stream of the octets given, each NAL unit behind its four-octet length: a keyframe's IDR slice, after the parameter sets + * when it carries them in band, or a later picture's TRAIL_R slice, each slice in the lowest temporal sub-layer. + */ +export function tierPicture({ inBand = false, keyframe = false, octets = 100, untimed = false }: TierPictureFixture = {}): SampleFixture { + const carried = inBand === true + ? TIER_STREAM_PARAMETER_SETS + : inBand || [] + const units = keyframe + ? [...carried] + : [] + const used = units.reduce((sum, unit) => sum + 4 + unit.length, 0) + + units.push(Buffer.concat([ + Buffer.from(keyframe + ? [0x26, 0x01] + : [0x02, 0x01]), + Buffer.alloc(octets - used - 6, 0xA5), + ])) + + const { data, duration, flags } = pictureSample(Buffer.concat(units.flatMap(unit => [ + uint32(unit.length), + unit, + ])), keyframe) + + return untimed + ? { data, flags } + : { data, duration, flags } +} + +// A fragment of a tier's stream: its picture samples from one decode time and its sound samples from another, each run only when it has samples, picture +// first. +export function tierStreamFragment({ picture = [], pictureTime = 0n, sound = [], soundTime = 0n }: { + picture?: SampleFixture[] + pictureTime?: bigint + sound?: SampleFixture[] + soundTime?: bigint +}): Buffer { + const runs: SampleRunFixture[] = [] + + if (picture.length > 0) { + runs.push({ decodeTime: pictureTime, samples: picture, trackId: TIER_STREAM_PICTURE }) + } + + if (sound.length > 0) { + runs.push({ decodeTime: soundTime, samples: sound, trackId: TIER_STREAM_SOUND }) + } + + return sampleFragment(...runs) +} + +// The initialization segment a suite's frames are written after: an hvc1 picture whose hvcC holds no parameter set beside an Opus sound, each track +// counting microseconds, which means a frame's time is its sample's decode time exactly. +const MICROSECOND_TRACKS = initializationSegment({ + handler: 'vide', + id: TIER_STREAM_PICTURE, + sampleEntry: visualSampleEntry('hvc1', 64, 36, hvcC([])), + timescale: 1000000, +}, { + handler: 'soun', + id: TIER_STREAM_SOUND, + sampleEntry: opusSampleEntry(), + timescale: 1000000, +}) + +// The streams a suite has written that initialization segment to: a frame it writes follows one. +const described = new WeakSet() + +// A frame a row writes to a tier's stream, in the form the live path sends it, and whether the plugin marks a discontinuity before it. +export interface WrittenFrame extends TierFrame { + readonly discontinuity?: boolean +} + +/* Writes one frame of a medium to a tier's stream as a plugin writes fMP4: the stream's initialization segment first, the first time a suite writes the + * stream, then a fragment of the frame's one sample, its decode time the frame's time, a picture a sync sample for a keyframe, and a discontinuity marked + * before it for a frame that asks for one. The tier's pacer releases it in a later turn. + */ +export function writeTierFrame(stream: TierStream, medium: StreamTierMedium, frame: WrittenFrame): void { + if (!described.has(stream)) { + described.add(stream) + stream.write(MICROSECOND_TRACKS) + } + + if (frame.discontinuity === true) { + stream.discontinuity() + } + + const decodeTime = BigInt(frame.time) + + stream.write(medium === 'video' + ? tierStreamFragment({ + picture: [ + pictureSample(frame.data, frame.keyframe === true), + ], + pictureTime: decodeTime, + }) + : tierStreamFragment({ + sound: [ + soundSample(frame.data), + ], + soundTime: decodeTime, + })) +} + +// 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)) +} + +export const STYP = box('styp', Buffer.from('msdh', 'latin1'), uint32(0), Buffer.from('msdhmsix', 'latin1')) + +/* The box skeleton of an eight second test pattern ffmpeg generated, a 64 by 36 picture at 15 frames per second as H.264 Main beside a 440 Hz tone as + * AAC, fragmented at each keyframe with ffmpeg's own producer reference time boxes. Each media data box is cut to 16 bytes, and the file is split as a + * plugin's assembler splits a recording: the initialization segment ends at the first fragment, and each later packet ends after its media data. The + * first packet holds ftyp, moov and ffmpeg's trailing prft, the second moof and mdat, the third prft, moof and mdat. + */ +const SKELETON_BASE64 = [ + 'AAAAHGZ0eXBpc281AAACAGlzbzVpc282bXA0MQAABKRtb292AAAAbG12aGQAAAAAAAAAAAAAAAAAALuAAAAAAAABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAE', + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAB7HRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAA', + 'AAAAAAAAAEAAAAAAQAAAACQAAAAAAYhtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAADwAAAAAAFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAEzbWluZg', + 'AAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAAA83N0YmwAAACnc3RzZAAAAAAAAAABAAAAl2F2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAA', + 'QAAkAEgAAABIAAAAAAAAAAEMTGF2YyBsaWJ4MjY0AAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAAxYXZjQwFNQAr/4QAYZ01ACtkEf58BEAAAAwAQAAADAeDxImSAAQAGaOvAZSyAAAAAEHBhc3AAAA', + 'ABAAAAAQAAABBzdHRzAAAAAAAAAAAAAAAQc3RzYwAAAAAAAAAAAAAAFHN0c3oAAAAAAAAAAAAAAAAAAAAQc3RjbwAAAAAAAAAAAAABv3RyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAIAAAAAAAAA', + 'AAAAAAAAAAAAAAAAAQEAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAVttZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAD6AAAAAAFXEAAAAAAAtaGRscgAAAA', + 'AAAAAAc291bgAAAAAAAAAAAAAAAFNvdW5kSGFuZGxlcgAAAAEGbWluZgAAABBzbWhkAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAADKc3RibAAAAH5zdHNkAAAA', + 'AAAAAAEAAABubXA0YQAAAAAAAAABAAAAAAAAAAAAAQAQAAAAAD6AAAAAAAA2ZXNkcwAAAAADgICAJQACAASAgIAXQBUAAAAAAD6AAAA+gAWAgIAFFAhW5QAGgICAAQIAAAAUYnRydAAAAAAAAD6AAA', + 'A+gAAAABBzdHRzAAAAAAAAAAAAAAAQc3RzYwAAAAAAAAAAAAAAFHN0c3oAAAAAAAAAAAAAAAAAAAAQc3RjbwAAAAAAAAAAAAAASG12ZXgAAAAgdHJleAAAAAAAAAABAAAAAQAAAAAAAAAAAAAAAAAA', + 'ACB0cmV4AAAAAAAAAAIAAAABAAAAAAAAAAAAAAAAAAAAPXVkdGEAAAA1bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAIaWxzdAAAACBwcmZ0AQAAGAAAAAHuodGGZ2', + 'yLQwAAAAAAAAPYAAADlG1vb2YAAAAQbWZoZAAAAAAAAAABAAACMHRyYWYAAAAcdGZoZAACADgAAAABAAAH2AAAAwwBAQAAAAAAFHRmZHQBAAAAAAAAAAAAAAAAAAH4dHJ1bgAAAwUAAAA8AAADnAIA', + 'AAAAAAfYAAADDAAABAAAAAANAAAEAAAAACEAAAQAAAAAGAAABAAAAAAQAAAEAAAAABMAAAQAAAAAEAAABAAAAAATAAAEAAAAAA8AAAQAAAAAFAAABAAAAAAPAAAEAAAAAA8AAAQAAAAADwAABAAAAA', + 'APAAAEAAAAABgAAAQAAAAAFQAABAAAAAASAAAEAAAAAA8AAAQAAAAAEgAABAAAAAAPAAAEAAAAAA8AAAQAAAAADwAABAAAAAAPAAAEAAAAAA8AAAQAAAAADwAABAAAAAAPAAAEAAAAAA8AAAQAAAAA', + 'EgAABAAAAAARAAAEAAAAABEAAAQAAAAAEQAABAAAAAARAAAEAAAAABEAAAQAAAAAFAAABAAAAAAPAAAEAAAAAA8AAAQAAAAAFQAABAAAAAAPAAAEAAAAAA8AAAQAAAAAFAAABAAAAAATAAAEAAAAAA', + '8AAAQAAAAAEQAABAAAAAAPAAAEAAAAAA8AAAQAAAAAEQAABAAAAAATAAAEAAAAAA8AAAQAAAAAEQAABAAAAAAPAAAEAAAAAA8AAAQAAAAADwAABAAAAAAPAAAEAAAAAA8AAAQAAAAADwAABAAAAAAP', + 'AAAEAAAAAA8AAAQAAAAADwAABAAAAAAPAAAEAAAAAA8AAAFMdHJhZgAAABx0ZmhkAAIAOAAAAAIAAAQAAAAArgIAAAAAAAAUdGZkdAEAAAAAAAAAAAAAAAAAARR0cnVuAAACAQAAAEAAAAqFAAAArg', + 'AAALEAAACnAAAAhQAAAIQAAAB6AAAAfwAAAHwAAACGAAAAgwAAAHkAAACAAAAAgwAAAIkAAAB9AAAAhwAAAHYAAACAAAAAhQAAAH0AAACNAAAAhAAAAHQAAACHAAAAfAAAAH8AAACBAAAAgQAAAHwA', + 'AACEAAAAfwAAAIAAAAB/AAAAjgAAAH4AAAB2AAAAhwAAAIkAAAB7AAAAdwAAAIkAAAB+AAAAhAAAAIkAAAB+AAAAhwAAAIAAAAB0AAAAgQAAAHwAAAB+AAAAhAAAAH0AAAB7AAAAhAAAAIUAAAB6AA', + 'AAfwAAAIgAAACEAAAAiAAAAIEAAAB6AAAAggAAABhtZGF0AAACbwYF//9r3EXpvebZSAAAACBwcmZ0AQAAGAAAAAHuodGGaj1wowAAAAAAAPPYAAACnG1vb2YAAAAQbWZoZAAAAAAAAAACAAABQHRy', + 'YWYAAAAcdGZoZAACADgAAAABAAAEAAAAAMEBAQAAAAAAFHRmZHQBAAAAAAAAAAAA89gAAAEIdHJ1bgAAAgUAAAA8AAACpAIAAAAAAADBAAAACgAAAA4AAAAPAAAADwAAAA8AAAAPAAAADwAAAA8AAA', + 'APAAAADwAAAA8AAAAPAAAADwAAAA8AAAAPAAAADwAAABEAAAAPAAAADwAAABEAAAAPAAAADwAAAA8AAAAPAAAADwAAAA8AAAAPAAAADwAAAA8AAAAYAAAADwAAAA8AAAAPAAAADwAAAA8AAAAPAAAA', + 'DwAAABEAAAASAAAADwAAAA8AAAAPAAAADwAAAA8AAAAWAAAADwAAAA8AAAAPAAAAEgAAAA8AAAAPAAAAEQAAAA8AAAAPAAAADwAAAA8AAAAPAAAAFQAAABAAAAFEdHJhZgAAABx0ZmhkAAIAOAAAAA', + 'IAAAQAAAAAegIAAAAAAAAUdGZkdAEAAAAAAAAAAAEAAAAAAQx0cnVuAAACAQAAAD4AAAb5AAAAegAAAIIAAACBAAAAhwAAAIUAAAB+AAAAhwAAAIEAAACAAAAAdwAAAH0AAAB7AAAAgAAAAIAAAACF', + 'AAAAgwAAAH0AAAB9AAAAiQAAAIQAAAB/AAAAewAAAIcAAAB/AAAAewAAAH0AAACKAAAAegAAAIcAAACBAAAAfgAAAH8AAAB/AAAAgAAAAIYAAACBAAAAfgAAAH4AAAB8AAAAfQAAAIoAAAB8AAAAhw', + 'AAAH8AAACGAAAAgQAAAIMAAACBAAAAfgAAAIQAAAB9AAAAgwAAAHUAAAB9AAAAhgAAAH0AAACKAAAAhAAAAIIAAACCAAAAfQAAAIEAAAAYbWRhdAAAAL1liIIE/x/sK8k+TQY=', +].join('') + +const SKELETON_PACKET_LENGTHS = [1248, 940, 724] + +// The skeleton's packets, in the order a recording yields them. +export function skeletonPackets(): Buffer[] { + const skeleton = Buffer.from(SKELETON_BASE64, 'base64') + let offset = 0 + + return SKELETON_PACKET_LENGTHS.map((length) => { + const packet = skeleton.subarray(offset, offset + length) + + offset += length + + return packet + }) +} diff --git a/src/test-utils/rtpVectors.ts b/src/test-utils/rtpVectors.ts new file mode 100644 index 000000000..95c780e4a --- /dev/null +++ b/src/test-utils/rtpVectors.ts @@ -0,0 +1,248 @@ +/* The RTP cutting vectors the suites hold the library's frame cutting to: an HEVC stream of a generated test pattern of a 64 by 36 picture, a keyframe, + * the frames after it and a second keyframe, as the source below names them. Each frame carries its NAL units in order, each as hex with no start code and + * no length, and for each packet size the RTP payloads ffmpeg's own RTP muxer cut that frame into, in order, each as hex with no RTP header, the frame's + * one marker on the last. + */ +import { Buffer } from 'node:buffer' + +// One frame: its NAL units, and the payloads it was cut into at each packet size. +export interface RTPVectorFrame { + readonly cuts: Readonly> + readonly units: readonly string[] +} + +// The vectors' one stream: its frames, in order. +export interface RTPVectorStream { + readonly frames: readonly RTPVectorFrame[] +} + +// The encoder and the source the vectors were made with, beside the stream. +export interface RTPVectorSet { + readonly ffmpeg: string + readonly source: string + readonly stream: RTPVectorStream +} + +export const RTP_VECTORS: RTPVectorSet = { + ffmpeg: 'ffmpeg version 9.0.2', + source: 'testsrc2=size=64x36:rate=15, 4 frames, a keyframe every third', + stream: { + frames: [ + { + cuts: { + 200: [ + [ + '6001001840010c01ffff01600000030090000003000003001eba0240002842010101600000030090000003000003001ea020831f3e5ba4a4c2f0168080000003', + '00800000078400064401c0718112', + ].join(''), + [ + '620194ade0670293e467112792951c9809d14c7002ccaa7e4af41dc745164039f747670db73c711788c7ff11967225fc2c53a9b91694529b7d48783ad723939c', + '9a7103ff86997c618c81c683a45a1cac210bc8d53c2adae9f5d7bb4364034a66f20be70f2412f762721d77fa7db1c794b0b4743acbfdd677682732effff3c4a5', + '8ef09ccb21b2d50c7675850fb557158ca4d8f7d3a19e02ea7cb89db042c4ffe2f9f1f40be198eece9db60434f42612d09fdc59b154c38a41aa1d98c1', + ].join(''), + [ + '620114ea6ae3205b056c0f2c735c51f020ecd263210afc6f1bdd99ad109c7d97f32f3969f6db886c443c9cb49f84b54b86313b47bb0c25517b61fa115ccafb5c', + 'aa9302276ee6851c4c12a2e7d5efef4fc39a050a34ae1721214716a54552161bf409bbb83d5b787ef16f2886c41f24681ef5a8ead2b623844523b0429083735c', + '1492ad1c2b10bbaedfcd9978b3d647becaa0a28618f0125f291963b1b480a04c50d4c53ccf36d41dcca1ffc9486e5e806e9de2d757fefa0719d55059', + ].join(''), + [ + '6201146a0ba39dec1f447193d89e7903cdf3969f2bf14e37901c66c5b4ce6c726772d0dd575ef511bd5b3ba3c0793e792de0af87fed7692963cac662ec05f4cf', + '0e1f266f8d66fe2f2c62377ef79212fcfb495af98f485aefed7a9a81cef837bfaa88619d41d5ed1957688d9e128b59615dd60c1509c748ce4d7b1423f99f7812', + 'cd1cf489b2498eac335c55864d228f00f03d90774d094df74381d8edf2a5dd7862fda0b9eb33e3c10f5bdc1d2dfc6f99f53cc624b8cf32a0a79d4a43', + ].join(''), + [ + '620114fcca08ad7e27e0ec01fc98215496acbceeaa4513e080c293846e4bf83596fe81eb26995b51f4ee6f21fe88c57d7b0bef499c09cc02e7e526018ffafc64', + 'f20908ccf1fc4177b25e0b98c3466529e9b098aec4e8342a5b8e2e82270a3a002cbb958ad8517a080f0bab78e57336359c428c270da4df8bb19f03c51246aa6c', + '194f91029d55704f0acd42b2d5a84d157d9a17b17286f9b0362d5a9206b5e221dfc2da1d90d389527570e86245758c712262679cfce3133056ca406a', + ].join(''), + [ + '620154f0aaca0084d92256f87d6f9931cc8644269005935bf561baccea607cbc4e538136addfd7387bfcf1ea9eb134ca8a70228080340b750ed2c677dc154764', + 'e56c702dfb8252ac71af42156414ce756e4ad3013aef67', + ].join(''), + ], + 1228: [ + [ + '6001001840010c01ffff01600000030090000003000003001eba0240002842010101600000030090000003000003001ea020831f3e5ba4a4c2f0168080000003', + '00800000078400064401c0718112033a2801ade0670293e467112792951c9809d14c7002ccaa7e4af41dc745164039f747670db73c711788c7ff11967225fc2c', + '53a9b91694529b7d48783ad723939c9a7103ff86997c618c81c683a45a1cac210bc8d53c2adae9f5d7bb4364034a66f20be70f2412f762721d77fa7db1c794b0', + 'b4743acbfdd677682732effff3c4a58ef09ccb21b2d50c7675850fb557158ca4d8f7d3a19e02ea7cb89db042c4ffe2f9f1f40be198eece9db60434f42612d09f', + 'dc59b154c38a41aa1d98c1ea6ae3205b056c0f2c735c51f020ecd263210afc6f1bdd99ad109c7d97f32f3969f6db886c443c9cb49f84b54b86313b47bb0c2551', + '7b61fa115ccafb5caa9302276ee6851c4c12a2e7d5efef4fc39a050a34ae1721214716a54552161bf409bbb83d5b787ef16f2886c41f24681ef5a8ead2b62384', + '4523b0429083735c1492ad1c2b10bbaedfcd9978b3d647becaa0a28618f0125f291963b1b480a04c50d4c53ccf36d41dcca1ffc9486e5e806e9de2d757fefa07', + '19d550596a0ba39dec1f447193d89e7903cdf3969f2bf14e37901c66c5b4ce6c726772d0dd575ef511bd5b3ba3c0793e792de0af87fed7692963cac662ec05f4', + 'cf0e1f266f8d66fe2f2c62377ef79212fcfb495af98f485aefed7a9a81cef837bfaa88619d41d5ed1957688d9e128b59615dd60c1509c748ce4d7b1423f99f78', + '12cd1cf489b2498eac335c55864d228f00f03d90774d094df74381d8edf2a5dd7862fda0b9eb33e3c10f5bdc1d2dfc6f99f53cc624b8cf32a0a79d4a43fcca08', + 'ad7e27e0ec01fc98215496acbceeaa4513e080c293846e4bf83596fe81eb26995b51f4ee6f21fe88c57d7b0bef499c09cc02e7e526018ffafc64f20908ccf1fc', + '4177b25e0b98c3466529e9b098aec4e8342a5b8e2e82270a3a002cbb958ad8517a080f0bab78e57336359c428c270da4df8bb19f03c51246aa6c194f91029d55', + '704f0acd42b2d5a84d157d9a17b17286f9b0362d5a9206b5e221dfc2da1d90d389527570e86245758c712262679cfce3133056ca406af0aaca0084d92256f87d', + '6f9931cc8644269005935bf561baccea607cbc4e538136addfd7387bfcf1ea9eb134ca8a70228080340b750ed2c677dc154764e56c702dfb8252ac71af421564', + '14ce756e4ad3013aef67', + ].join(''), + ], + }, + units: [ + '40010c01ffff01600000030090000003000003001eba0240', + '42010101600000030090000003000003001ea020831f3e5ba4a4c2f0168080000003008000000784', + '4401c0718112', + [ + '2801ade0670293e467112792951c9809d14c7002ccaa7e4af41dc745164039f747670db73c711788c7ff11967225fc2c53a9b91694529b7d48783ad723939c9a', + '7103ff86997c618c81c683a45a1cac210bc8d53c2adae9f5d7bb4364034a66f20be70f2412f762721d77fa7db1c794b0b4743acbfdd677682732effff3c4a58e', + 'f09ccb21b2d50c7675850fb557158ca4d8f7d3a19e02ea7cb89db042c4ffe2f9f1f40be198eece9db60434f42612d09fdc59b154c38a41aa1d98c1ea6ae3205b', + '056c0f2c735c51f020ecd263210afc6f1bdd99ad109c7d97f32f3969f6db886c443c9cb49f84b54b86313b47bb0c25517b61fa115ccafb5caa9302276ee6851c', + '4c12a2e7d5efef4fc39a050a34ae1721214716a54552161bf409bbb83d5b787ef16f2886c41f24681ef5a8ead2b623844523b0429083735c1492ad1c2b10bbae', + 'dfcd9978b3d647becaa0a28618f0125f291963b1b480a04c50d4c53ccf36d41dcca1ffc9486e5e806e9de2d757fefa0719d550596a0ba39dec1f447193d89e79', + '03cdf3969f2bf14e37901c66c5b4ce6c726772d0dd575ef511bd5b3ba3c0793e792de0af87fed7692963cac662ec05f4cf0e1f266f8d66fe2f2c62377ef79212', + 'fcfb495af98f485aefed7a9a81cef837bfaa88619d41d5ed1957688d9e128b59615dd60c1509c748ce4d7b1423f99f7812cd1cf489b2498eac335c55864d228f', + '00f03d90774d094df74381d8edf2a5dd7862fda0b9eb33e3c10f5bdc1d2dfc6f99f53cc624b8cf32a0a79d4a43fcca08ad7e27e0ec01fc98215496acbceeaa45', + '13e080c293846e4bf83596fe81eb26995b51f4ee6f21fe88c57d7b0bef499c09cc02e7e526018ffafc64f20908ccf1fc4177b25e0b98c3466529e9b098aec4e8', + '342a5b8e2e82270a3a002cbb958ad8517a080f0bab78e57336359c428c270da4df8bb19f03c51246aa6c194f91029d55704f0acd42b2d5a84d157d9a17b17286', + 'f9b0362d5a9206b5e221dfc2da1d90d389527570e86245758c712262679cfce3133056ca406af0aaca0084d92256f87d6f9931cc8644269005935bf561baccea', + '607cbc4e538136addfd7387bfcf1ea9eb134ca8a70228080340b750ed2c677dc154764e56c702dfb8252ac71af42156414ce756e4ad3013aef67', + ].join(''), + ], + }, + { + cuts: { + 200: [ + '0201d009788f9ceb', + ], + 1228: [ + '0201d009788f9ceb', + ], + }, + units: [ + '0201d009788f9ceb', + ], + }, + { + cuts: { + 200: [ + [ + '0201d011fe2094cc6b2f903dc2ef857b67ec839a02b9aae6cca6b12ebc8ebff6b3edc1b7243811cce6c8a026f70503576062ac2454961aa36d1e0c35261aa2cd', + '6307deff35352bd1c964a0657d674d25f640150ecd85ad6eb0a584b34e4ee5d3e2403594bb9a6c2a5f3af8646f81227da1f4924e20', + ].join(''), + ], + 1228: [ + [ + '0201d011fe2094cc6b2f903dc2ef857b67ec839a02b9aae6cca6b12ebc8ebff6b3edc1b7243811cce6c8a026f70503576062ac2454961aa36d1e0c35261aa2cd', + '6307deff35352bd1c964a0657d674d25f640150ecd85ad6eb0a584b34e4ee5d3e2403594bb9a6c2a5f3af8646f81227da1f4924e20', + ].join(''), + ], + }, + units: [ + [ + '0201d011fe2094cc6b2f903dc2ef857b67ec839a02b9aae6cca6b12ebc8ebff6b3edc1b7243811cce6c8a026f70503576062ac2454961aa36d1e0c35261aa2cd', + '6307deff35352bd1c964a0657d674d25f640150ecd85ad6eb0a584b34e4ee5d3e2403594bb9a6c2a5f3af8646f81227da1f4924e20', + ].join(''), + ], + }, + { + cuts: { + 200: [ + [ + '6001001840010c01ffff01600000030090000003000003001eba0240002842010101600000030090000003000003001ea020831f3e5ba4a4c2f0168080000003', + '00800000078400064401c0718112', + ].join(''), + [ + '620195ac0cf512806d8485fabe1fab3e95d51c227b584f826471d9de42a56289e77f04a7725d247b4787f2fd0bd467a676f1f7d63917a74b4095137c403eeaec', + '6439f118045580e2e79cc691e141a95bf77550f124353aa0924ed5679dd2774a5b01d0b6eb97f27d45d89d41ffa921b01020e4b0628165b037c2d489140d70cd', + '60a04c69c3283a122a6930b1b3d4ffaaa655fffc6478645b600682be21a8cef51a2a591b16120f1ddeaa414c5448930b5c00eb43b973267efac81050', + ].join(''), + [ + '620115df86db53a5f3c0ba7e31c5edd15255118d7827fcc251fc935ac98888c081566a9f2850a477f5ec01085df131c1a67e606ac6a9b83353e87047b597e1c0', + 'd4d38a3a6c498eaa41059a4a2c86336652e9e8a9d772d87ea826a6a04f186b22808b754baf946d93d4f4f132500b28bfa56543374343a43196f6373cde22f426', + 'c54692c5af52f4c0ab20baa778f67aeca74dc7527d3e7fe0ea03363db6999d9a75100f402a1c40fbec7898e6eb860efedba1a6887e411207a6cd06e9', + ].join(''), + [ + '6201150b9cbfe4aad36ea72283545f8b983c54ad22218dd7727e0e372be573065eb888ddd0275affaf7dd942178a873e4c09fb9153c9abe9303b6102e8e315e7', + '1ea4a7cb328fd7d700f1a1c592837e22dbf2b99ed0377f6eecca90e05d98f096f1d3fdfff8fd84dafc90bc24d4fd10091aa309194ec5897d9341a281bfbe97d5', + '594fbc62dd6832fcb7c72aa5a0a630891c07a95b57381189d3b55cdaf1750179a977c150309f8b10b66ae9135c6aa19bdda8f7ece45fa57055337361', + ].join(''), + [ + '62011520699686ba7d22df7b1d36bd4d3a732964fe798320266bce19548708c25e6355f79df7f0008801c0638c804c4c58e932665000cc3c4be3b67fab839316', + '805d66d8924914bccccfb9231e67a876a77416a0800b6a45c5be54a0485b27bed5ac2e13fb5bdf732e80d4146f0278b00e30e33fa230842883afda675b732c4c', + '7ca1d49a63e1857f6aee3ca587ea421c4cba4d7e0fc9761752a7d8ad4a9339e9c096f7c80b62af22c1282b4fc9dce7bdc17926bd1fac7c7f2a57157f', + ].join(''), + [ + '620115176ef04999ac38bf4f2a55dae0080f217d4ffc3123676d5e05785673d5d751ac3a4e8f9d0a99c2b1d15f7ebe3919c007647d3e2f1c990a313e1c651f04', + '3f25282990f75077daf0220bde99f8c3d90ebe01fbd5c4ad1bae674639c54195dc1827480c69b4b9c387a18b2dc37cdace0abc759cc82daaa5fdbc61f103b481', + '2049602891b2b540713a93c433c77ad05d21c04f9b2935b33369f746db2a5cf787f29ef1870a90384a0ed2d5af98119cbfd9a70a9c595e720246dd05', + ].join(''), + '62015596b3d300a6a932f543b0642fa45916e044e8998e6878965ce2f4e0', + ], + 1228: [ + [ + '6001001840010c01ffff01600000030090000003000003001eba0240002842010101600000030090000003000003001ea020831f3e5ba4a4c2f0168080000003', + '00800000078400064401c071811203ba2a01ac0cf512806d8485fabe1fab3e95d51c227b584f826471d9de42a56289e77f04a7725d247b4787f2fd0bd467a676', + 'f1f7d63917a74b4095137c403eeaec6439f118045580e2e79cc691e141a95bf77550f124353aa0924ed5679dd2774a5b01d0b6eb97f27d45d89d41ffa921b010', + '20e4b0628165b037c2d489140d70cd60a04c69c3283a122a6930b1b3d4ffaaa655fffc6478645b600682be21a8cef51a2a591b16120f1ddeaa414c5448930b5c', + '00eb43b973267efac81050df86db53a5f3c0ba7e31c5edd15255118d7827fcc251fc935ac98888c081566a9f2850a477f5ec01085df131c1a67e606ac6a9b833', + '53e87047b597e1c0d4d38a3a6c498eaa41059a4a2c86336652e9e8a9d772d87ea826a6a04f186b22808b754baf946d93d4f4f132500b28bfa56543374343a431', + '96f6373cde22f426c54692c5af52f4c0ab20baa778f67aeca74dc7527d3e7fe0ea03363db6999d9a75100f402a1c40fbec7898e6eb860efedba1a6887e411207', + 'a6cd06e90b9cbfe4aad36ea72283545f8b983c54ad22218dd7727e0e372be573065eb888ddd0275affaf7dd942178a873e4c09fb9153c9abe9303b6102e8e315', + 'e71ea4a7cb328fd7d700f1a1c592837e22dbf2b99ed0377f6eecca90e05d98f096f1d3fdfff8fd84dafc90bc24d4fd10091aa309194ec5897d9341a281bfbe97', + 'd5594fbc62dd6832fcb7c72aa5a0a630891c07a95b57381189d3b55cdaf1750179a977c150309f8b10b66ae9135c6aa19bdda8f7ece45fa57055337361206996', + '86ba7d22df7b1d36bd4d3a732964fe798320266bce19548708c25e6355f79df7f0008801c0638c804c4c58e932665000cc3c4be3b67fab839316805d66d89249', + '14bccccfb9231e67a876a77416a0800b6a45c5be54a0485b27bed5ac2e13fb5bdf732e80d4146f0278b00e30e33fa230842883afda675b732c4c7ca1d49a63e1', + '857f6aee3ca587ea421c4cba4d7e0fc9761752a7d8ad4a9339e9c096f7c80b62af22c1282b4fc9dce7bdc17926bd1fac7c7f2a57157f176ef04999ac38bf4f2a', + '55dae0080f217d4ffc3123676d5e05785673d5d751ac3a4e8f9d0a99c2b1d15f7ebe3919c007647d3e2f1c990a313e1c651f043f25282990f75077daf0220bde', + '99f8c3d90ebe01fbd5c4ad1bae674639c54195dc1827480c69b4b9c387a18b2dc37cdace0abc759cc82daaa5fdbc61f103b4812049602891b2b540713a93c433', + 'c77ad05d21c04f9b2935b33369f746db2a5cf787f29ef1870a90384a0ed2d5af98119cbfd9a70a9c595e720246dd0596b3d300a6a932f543b0642fa45916e044', + 'e8998e6878965ce2f4e0', + ].join(''), + ], + }, + units: [ + '40010c01ffff01600000030090000003000003001eba0240', + '42010101600000030090000003000003001ea020831f3e5ba4a4c2f0168080000003008000000784', + '4401c0718112', + [ + '2a01ac0cf512806d8485fabe1fab3e95d51c227b584f826471d9de42a56289e77f04a7725d247b4787f2fd0bd467a676f1f7d63917a74b4095137c403eeaec64', + '39f118045580e2e79cc691e141a95bf77550f124353aa0924ed5679dd2774a5b01d0b6eb97f27d45d89d41ffa921b01020e4b0628165b037c2d489140d70cd60', + 'a04c69c3283a122a6930b1b3d4ffaaa655fffc6478645b600682be21a8cef51a2a591b16120f1ddeaa414c5448930b5c00eb43b973267efac81050df86db53a5', + 'f3c0ba7e31c5edd15255118d7827fcc251fc935ac98888c081566a9f2850a477f5ec01085df131c1a67e606ac6a9b83353e87047b597e1c0d4d38a3a6c498eaa', + '41059a4a2c86336652e9e8a9d772d87ea826a6a04f186b22808b754baf946d93d4f4f132500b28bfa56543374343a43196f6373cde22f426c54692c5af52f4c0', + 'ab20baa778f67aeca74dc7527d3e7fe0ea03363db6999d9a75100f402a1c40fbec7898e6eb860efedba1a6887e411207a6cd06e90b9cbfe4aad36ea72283545f', + '8b983c54ad22218dd7727e0e372be573065eb888ddd0275affaf7dd942178a873e4c09fb9153c9abe9303b6102e8e315e71ea4a7cb328fd7d700f1a1c592837e', + '22dbf2b99ed0377f6eecca90e05d98f096f1d3fdfff8fd84dafc90bc24d4fd10091aa309194ec5897d9341a281bfbe97d5594fbc62dd6832fcb7c72aa5a0a630', + '891c07a95b57381189d3b55cdaf1750179a977c150309f8b10b66ae9135c6aa19bdda8f7ece45fa5705533736120699686ba7d22df7b1d36bd4d3a732964fe79', + '8320266bce19548708c25e6355f79df7f0008801c0638c804c4c58e932665000cc3c4be3b67fab839316805d66d8924914bccccfb9231e67a876a77416a0800b', + '6a45c5be54a0485b27bed5ac2e13fb5bdf732e80d4146f0278b00e30e33fa230842883afda675b732c4c7ca1d49a63e1857f6aee3ca587ea421c4cba4d7e0fc9', + '761752a7d8ad4a9339e9c096f7c80b62af22c1282b4fc9dce7bdc17926bd1fac7c7f2a57157f176ef04999ac38bf4f2a55dae0080f217d4ffc3123676d5e0578', + '5673d5d751ac3a4e8f9d0a99c2b1d15f7ebe3919c007647d3e2f1c990a313e1c651f043f25282990f75077daf0220bde99f8c3d90ebe01fbd5c4ad1bae674639', + 'c54195dc1827480c69b4b9c387a18b2dc37cdace0abc759cc82daaa5fdbc61f103b4812049602891b2b540713a93c433c77ad05d21c04f9b2935b33369f746db', + '2a5cf787f29ef1870a90384a0ed2d5af98119cbfd9a70a9c595e720246dd0596b3d300a6a932f543b0642fa45916e044e8998e6878965ce2f4e0', + ].join(''), + ], + }, + ], + }, +} + +// A frame's bytes as the live path sends them, the vectors' units or a row's own: each unit behind its length in four octets, big-endian. +export function tierFrameData(units: readonly Uint8Array[]): Buffer { + return Buffer.concat(units.flatMap((unit) => { + const length = Buffer.alloc(4) + length.writeUInt32BE(unit.length) + + return [length, unit] + })) +} + +// A vector frame's bytes as the live path sends them. +export function vectorFrameData(frame: RTPVectorFrame): Buffer { + return tierFrameData(frame.units.map(unit => Buffer.from(unit, 'hex'))) +} + +// A NAL unit of a given length for a row's own frame, opening with the NAL unit header given, its other octets counting up. +export function nalUnit(header: Uint8Array, length: number): Buffer { + const unit = Buffer.alloc(length) + + unit.set(header) + + for (let octet = header.length; octet < length; octet++) { + unit[octet] = octet & 0xFF + } + + return unit +} From 3cc99e791c13cc3eb8e0145712f1d3162dc620ad Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:49 -0600 Subject: [PATCH 11/16] feat(camera): add the recording that provisions a camera and uploads each clip a hub commands, packaged over CMAF and sealed under the Camera Key --- src/hap.ts | 9 +- src/lib/Accessory.ts | 43 + src/lib/camera/mp4/mp4Writer.spec.ts | 569 +++++ .../recording/CMAFRecordingManagement.ts | 1838 +++++++++++++++++ .../camera/recording/CameraEventQueue.spec.ts | 159 ++ src/lib/camera/recording/CameraEventQueue.ts | 182 ++ .../camera/recording/IngestSession.spec.ts | 756 +++++++ src/lib/camera/recording/IngestSession.ts | 769 +++++++ .../ProducerReferenceTimeWriter.spec.ts | 433 ++++ .../recording/ProducerReferenceTimeWriter.ts | 276 +++ .../camera/recording/ServedRecording.spec.ts | 564 +++++ src/lib/camera/recording/ServedRecording.ts | 772 +++++++ .../camera/recording/clipPackaging.spec.ts | 193 ++ src/lib/camera/recording/clipPackaging.ts | 263 +++ src/lib/camera/recording/clipSealing.spec.ts | 66 + src/lib/camera/recording/clipSealing.ts | 83 + .../camera/recording/signingRequest.spec.ts | 111 + src/lib/camera/recording/signingRequest.ts | 72 + src/lib/model/RecordingProvisioning.spec.ts | 363 ++++ src/lib/model/RecordingProvisioning.ts | 399 ++++ src/lib/util/der.spec.ts | 63 + src/lib/util/der.ts | 158 ++ src/lib/util/libraryVersion.ts | 12 + src/lib/util/ntp.spec.ts | 74 + src/lib/util/ntp.ts | 17 + src/test-utils/MockIngestServer.ts | 238 +++ src/test-utils/ingest/client.key | 5 + src/test-utils/ingest/client.pem | 9 + src/test-utils/ingest/hub-ca.pem | 10 + src/test-utils/ingest/server-ca.pem | 11 + src/test-utils/ingest/server.key | 5 + src/test-utils/ingest/server.pem | 10 + src/test-utils/ingest/stranger-ca.pem | 10 + src/test-utils/ingest/stranger.key | 5 + src/test-utils/ingest/stranger.pem | 10 + 35 files changed, 8550 insertions(+), 7 deletions(-) create mode 100644 src/lib/camera/mp4/mp4Writer.spec.ts create mode 100644 src/lib/camera/recording/CMAFRecordingManagement.ts create mode 100644 src/lib/camera/recording/CameraEventQueue.spec.ts create mode 100644 src/lib/camera/recording/CameraEventQueue.ts create mode 100644 src/lib/camera/recording/IngestSession.spec.ts create mode 100644 src/lib/camera/recording/IngestSession.ts create mode 100644 src/lib/camera/recording/ProducerReferenceTimeWriter.spec.ts create mode 100644 src/lib/camera/recording/ProducerReferenceTimeWriter.ts create mode 100644 src/lib/camera/recording/ServedRecording.spec.ts create mode 100644 src/lib/camera/recording/ServedRecording.ts create mode 100644 src/lib/camera/recording/clipPackaging.spec.ts create mode 100644 src/lib/camera/recording/clipPackaging.ts create mode 100644 src/lib/camera/recording/clipSealing.spec.ts create mode 100644 src/lib/camera/recording/clipSealing.ts create mode 100644 src/lib/camera/recording/signingRequest.spec.ts create mode 100644 src/lib/camera/recording/signingRequest.ts create mode 100644 src/lib/model/RecordingProvisioning.spec.ts create mode 100644 src/lib/model/RecordingProvisioning.ts create mode 100644 src/lib/util/der.spec.ts create mode 100644 src/lib/util/der.ts create mode 100644 src/lib/util/libraryVersion.ts create mode 100644 src/lib/util/ntp.spec.ts create mode 100644 src/lib/util/ntp.ts create mode 100644 src/test-utils/MockIngestServer.ts create mode 100644 src/test-utils/ingest/client.key create mode 100644 src/test-utils/ingest/client.pem create mode 100644 src/test-utils/ingest/hub-ca.pem create mode 100644 src/test-utils/ingest/server-ca.pem create mode 100644 src/test-utils/ingest/server.key create mode 100644 src/test-utils/ingest/server.pem create mode 100644 src/test-utils/ingest/stranger-ca.pem create mode 100644 src/test-utils/ingest/stranger.key create mode 100644 src/test-utils/ingest/stranger.pem diff --git a/src/hap.ts b/src/hap.ts index aa85b8d12..24de3517e 100644 --- a/src/hap.ts +++ b/src/hap.ts @@ -1,10 +1,9 @@ -import { readFileSync } from 'node:fs' - import createDebug from 'debug' // only used as types, for the documentation namespace at the end of this file. The definitions themselves are loaded by the import of definitions/index.js below import * as Characteristics from './lib/definitions/CharacteristicDefinitions.js' import * as Services from './lib/definitions/ServiceDefinitions.js' +import { libraryVersion } from './lib/util/libraryVersion.js' import 'source-map-support/register.js' // registering node-source-map-support for typescript stack traces import './lib/definitions/index.js' @@ -62,8 +61,6 @@ export * from './types.js' const debug = createDebug('HAP-NodeJS:Init') -let libraryVersion: string | undefined - /** * This method can be used to retrieve the current running library version of the HAP-NodeJS framework. * @returns The SemVer version string. @@ -71,9 +68,7 @@ let libraryVersion: string | undefined * @group Utils */ export function HAPLibraryVersion(): string { - // the version cannot change while the process runs, so the file is read only once - libraryVersion ??= JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8')).version as string - return libraryVersion + return libraryVersion() } function printInit() { diff --git a/src/lib/Accessory.ts b/src/lib/Accessory.ts index 9f49f65a0..f9a1f8602 100644 --- a/src/lib/Accessory.ts +++ b/src/lib/Accessory.ts @@ -79,6 +79,7 @@ import { import { AccessoryInfo, PermissionTypes } from './model/AccessoryInfo.js' import { ControllerStorage } from './model/ControllerStorage.js' import { IdentifierCache } from './model/IdentifierCache.js' +import { RecordingProvisioning } from './model/RecordingProvisioning.js' import { Service, ServiceEventTypes } from './Service.js' import { checkName } from './util/checkName.js' import { clone } from './util/clone.js' @@ -466,6 +467,13 @@ export class Accessory extends EventEmitter { private serializedControllers?: Record // store uninitialized controller data after an Accessory.deserialize call private activeCameraController?: CameraController + /** + * The UUIDs of the bridged accessories removed while this accessory has no username. The first publish learns the username their recording provisioning + * entries are stored under and clears each entry to its marks. A removal after a destroy needs no clear, because the destroy removed that username's + * whole record. + */ + private readonly unpublishedRemovals = new Set() + /** * @private */ @@ -810,6 +818,17 @@ export class Accessory extends EventEmitter { this.controllerStorage.unlinkAccessory(accessory) accessory.handAccessoryContext() + // A camera that leaves its bridge has its recording provisioning cleared to its marks, as at an unpairing, because the service keeps its session folders + // and a plugin may add the same camera back. Homebridge removes the cached accessories a plugin no longer has before it publishes the bridge. A + // removal made before the username is known is carried out at the first publish. + const username = this._accessoryInfo?.username + + if (username === undefined) { + this.unpublishedRemovals.add(accessory.UUID) + } else { + this.writeRecordingProvisioning(() => RecordingProvisioning.clearProvisioning(username, accessory.UUID)) + } + if (!deferUpdate) { this.enqueueConfigurationUpdate() } @@ -1033,6 +1052,16 @@ export class Accessory extends EventEmitter { } } + // A write of the recording provisioning record that fails keeps what the store held and is logged. An unpairing, a bridged accessory's removal or a + // publish carries on whatever the disk does. + private writeRecordingProvisioning(write: () => void): void { + try { + write() + } catch (error) { + console.warn(`[${this.displayName}] The recording provisioning record could not be written: ${errorMessage(error)}`) + } + } + private handleAccessoryUnpairedForControllers(): void { for (const context of Object.values(this.controllers)) { const controller = context.controller @@ -1444,6 +1473,14 @@ export class Accessory extends EventEmitter { if (!this.initialized) { // controller storage is only loaded from disk the first time we publish! this.controllerStorage.load(info.username) // initializing controller data + + // Each bridged accessory removed before this first publish has its recording provisioning entry cleared to its marks here, the outcome its removal + // after the publish would have had. + for (const accessoryUUID of this.unpublishedRemovals) { + this.writeRecordingProvisioning(() => RecordingProvisioning.clearProvisioning(info.username, accessoryUUID)) + } + + this.unpublishedRemovals.clear() } // The accessory's controllers and every bridged accessory's learn the username they are published under, after the first publish's restore above. @@ -1754,6 +1791,11 @@ export class Accessory extends EventEmitter { } this.emit(AccessoryEventTypes.UNPAIRED) + // What the hubs provisioned on every camera stored under this username is cleared before any controller resets: each reset reads the cleared + // record, and every number the cameras used is kept. + const { username: accessoryUsername } = this._accessoryInfo + this.writeRecordingProvisioning(() => RecordingProvisioning.clearProvisioning(accessoryUsername)) + this.handleAccessoryUnpairedForControllers() for (const accessory of this.bridgedAccessories) { accessory.handleAccessoryUnpairedForControllers() @@ -2426,6 +2468,7 @@ export class Accessory extends EventEmitter { IdentifierCache.remove(username) AccessoryInfo.remove(username) ControllerStorage.remove(username) + RecordingProvisioning.remove(username) } private static serializeServiceMap(serviceMap: ControllerServiceMap): SerializedServiceMap { diff --git a/src/lib/camera/mp4/mp4Writer.spec.ts b/src/lib/camera/mp4/mp4Writer.spec.ts new file mode 100644 index 000000000..74892b3b6 --- /dev/null +++ b/src/lib/camera/mp4/mp4Writer.spec.ts @@ -0,0 +1,569 @@ +import type { Mp4Box, Mp4Sample } from './mp4Boxes.js' +import type { Mp4StreamSample, Mp4StreamTracks } from './Mp4StreamReader.js' +import type { SegmentRun } from './mp4Writer.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { box, hvcC, initializationSegment, opusSampleEntry, uint32, visualSampleEntry } from '../../../test-utils/mp4Fixtures.js' +import { detachedReporter } from '../../../test-utils/reporterFixtures.js' +import { RTP_VECTORS, tierFrameData } from '../../../test-utils/rtpVectors.js' +import { ProducerReferenceTimeWriter } from '../recording/ProducerReferenceTimeWriter.js' +import { ServedRecordings } from '../recording/ServedRecording.js' +import { + readSampleDefaults, + readTrackBoxEntry, + readTrackBoxEntryBytes, + readTrackBoxes, + readTrackBoxParameterSets, + readTrackFragments, + readTrackSamples, + readVideoTrackBox, + walkBoxes, +} from './mp4Boxes.js' +import { Mp4StreamReader } from './Mp4StreamReader.js' +import { writeInitializationSegment, writeKeyframeInitializationSegment, writeKeyframeMovie, writeSegment } from './mp4Writer.js' + +// The boxes whose children the tree below descends into, and the full boxes whose version and flags it reads. +const CONTAINERS = new Set([ + 'dinf', + 'mdia', + 'minf', + 'moov', + 'mvex', + 'stbl', + 'trak', +]) +const FULL_BOXES = new Set([ + 'dref', + 'hdlr', + 'mdhd', + 'mvhd', + 'smhd', + 'stco', + 'stsc', + 'stsd', + 'stsz', + 'stts', + 'tkhd', + 'trex', + 'url ', + 'vmhd', +]) + +// A box's type, its version and flags when it is a full box, and its children when it is a container, a data reference's entries among them. +interface BoxTree { + type: string + versionAndFlags?: number + children?: BoxTree[] +} + +// The tree of the boxes in a stretch of a buffer. +function treeOf(data: Buffer, start = 0, end = data.length): BoxTree[] { + return walkBoxes(data, start, end).boxes.map(({ end, payload, type }) => { + const node: BoxTree = { type } + + if (FULL_BOXES.has(type)) { + node.versionAndFlags = data.readUInt32BE(payload) + } + + if (CONTAINERS.has(type)) { + node.children = treeOf(data, payload, end) + } + + if (type === 'dref') { + node.children = treeOf(data, payload + 8, end) + } + + return node + }) +} + +// The one top-level box of a type a buffer holds. +function only(data: Buffer, type: string): Mp4Box { + return walkBoxes(data).boxes.find(candidate => candidate.type === type)! +} + +// Each sample of a track a segment holds as the box reader reads it, its octets read at its offset in place of the offset. +function samplesOf(data: Buffer, trackId: number): (Omit & { data: Buffer })[] { + const { samples } = readTrackSamples(data, only(data, 'moof'), { limit: 4096, trackId }) + + return samples.map(({ offset, size, ...sample }) => ({ + ...sample, + data: data.subarray(offset, offset + size), + size, + })) +} + +// The tracks a stream reader reads from an initialization segment. +function tracksOf(initialization: Buffer): Mp4StreamTracks { + let read: Mp4StreamTracks = {} + + new Mp4StreamReader({ + fail: (reason) => { + throw new Error(reason) + }, + fragmentEnd: () => undefined, + sample: () => undefined, + tracks: (tracks) => { + read = tracks + }, + }).write(initialization) + + return read +} + +// What a stream reader reads from a whole movie: its tracks and every sample, in order. +function readMovie(movie: Buffer): { samples: Mp4StreamSample[], tracks: Mp4StreamTracks } { + const samples: Mp4StreamSample[] = [] + let tracks: Mp4StreamTracks = {} + + new Mp4StreamReader({ + fail: (reason) => { + throw new Error(reason) + }, + fragmentEnd: () => undefined, + sample: (sample) => { + samples.push(sample) + }, + tracks: (read) => { + tracks = read + }, + }).write(movie) + + return { samples, tracks } +} + +// The vectors' frames, each its NAL units: a keyframe whose units open with its parameter sets, two frames after it and a second keyframe. +const HEVC = RTP_VECTORS.stream.frames.map(({ units }) => units.map(unit => Buffer.from(unit, 'hex'))) + +// The parameter sets the stream's keyframes open with, and an SEI of exactly a NAL unit header's two octets. +const HEVC_SETS = HEVC[0].slice(0, 3) +const SEI = Buffer.from('4e01', 'hex') + +// A stream's picture under an hev1 entry whose hvcC holds the parameter sets in arrays left unmarked, as ffmpeg writes an hev1 entry's, a pixel aspect +// ratio box after it, and its sound as Opus. +const PASP = box('pasp', uint32(1), uint32(1)) +const STREAM_VIDEO_ENTRY = visualSampleEntry('hev1', 64, 36, hvcC(HEVC_SETS.map((unit, index) => ({ + complete: false, + type: 32 + index, + units: [unit], +}))), PASP) +const OPUS_ENTRY = opusSampleEntry() +const STREAM = tracksOf(initializationSegment( + { + handler: 'vide', + id: 3, + sampleEntry: STREAM_VIDEO_ENTRY, + timescale: 90000, + }, + { + handler: 'soun', + id: 5, + sampleEntry: OPUS_ENTRY, + timescale: 48000, + }, +)) + +// A stream whose picture's hvcC holds no parameter sets. +const BARE = tracksOf(initializationSegment({ + handler: 'vide', + id: 1, + sampleEntry: visualSampleEntry('hvc1', 64, 36, hvcC([])), + timescale: 90000, +})) + +// The tree of an initialization segment's track, its media information header given. +function trakTree(mediaInformation: BoxTree): BoxTree { + return { + children: [ + { type: 'tkhd', versionAndFlags: 3 }, + { + children: [ + { type: 'mdhd', versionAndFlags: 0 }, + { type: 'hdlr', versionAndFlags: 0 }, + { + children: [ + mediaInformation, + { + children: [ + { + children: [ + { type: 'url ', versionAndFlags: 1 }, + ], + type: 'dref', + versionAndFlags: 0, + }, + ], + type: 'dinf', + }, + { + children: [ + { type: 'stsd', versionAndFlags: 0 }, + { type: 'stts', versionAndFlags: 0 }, + { type: 'stsc', versionAndFlags: 0 }, + { type: 'stsz', versionAndFlags: 0 }, + { type: 'stco', versionAndFlags: 0 }, + ], + type: 'stbl', + }, + ], + type: 'minf', + }, + ], + type: 'mdia', + }, + ], + type: 'trak', + } +} + +// Each array of an hvcC's record: the octet naming its completeness and NAL unit type, and its count of units. +function arraysOf(entry: Buffer): [number, number][] { + const record = walkBoxes(entry, 8 + 78).boxes.find(({ type }) => type === 'hvcC')! + const arrays: [number, number][] = [] + let at = record.payload + 23 + + for (let array = 0; array < entry.readUInt8(record.payload + 22); array++) { + const count = entry.readUInt16BE(at + 1) + + arrays.push([ + entry.readUInt8(at), + count, + ]) + at += 3 + + for (let unit = 0; unit < count; unit++) { + at += 2 + entry.readUInt16BE(at) + } + } + + return arrays +} + +describe('mp4Writer', () => { + it('writes an initialization segment of ffmpeg\'s boxes and brands that reads back through the box readers, the picture under hvc1 with the stream\'s ' + + 'own fields, boxes and codec, its parameter set arrays marked complete, and the sound under the stream\'s own Opus entry, one of picture alone, and ' + + 'one of a picture whose record holds no parameter sets with the sets handed in beside it, refusing it when given none', () => { + const segment = writeInitializationSegment({ audio: STREAM.audio, video: STREAM.video! }) + const moov = only(segment, 'moov') + const trackBoxes = readTrackBoxes(segment, moov) + const [video, audio] = trackBoxes + const written = readTrackBoxEntryBytes(segment, video)! + + expect(walkBoxes(segment).complete).toBe(true) + expect(treeOf(segment)).toEqual([ + { type: 'ftyp' }, + { + children: [ + { type: 'mvhd', versionAndFlags: 0 }, + trakTree({ type: 'vmhd', versionAndFlags: 1 }), + trakTree({ type: 'smhd', versionAndFlags: 0 }), + { + children: [ + { type: 'trex', versionAndFlags: 0 }, + { type: 'trex', versionAndFlags: 0 }, + ], + type: 'mvex', + }, + ], + type: 'moov', + }, + ]) + + const ftyp = only(segment, 'ftyp') + + expect(segment.subarray(ftyp.payload, ftyp.end)).toEqual(Buffer.concat([ + Buffer.from('iso5', 'latin1'), + uint32(512), + Buffer.from('iso5iso6mp41', 'latin1'), + ])) + expect(trackBoxes.map(({ track }) => track)).toEqual([ + { handler: 'vide', id: 1, timescale: 90000 }, + { handler: 'soun', id: 2, timescale: 48000 }, + ]) + expect(readVideoTrackBox(trackBoxes)).toBe(video) + expect(readTrackBoxEntry(segment, video)).toStrictEqual({ + codec: 'hvc1.1.6.L120.90', + height: 36, + type: 'hvc1', + width: 64, + }) + expect(readTrackBoxEntry(segment, audio)).toStrictEqual({ codec: 'Opus', type: 'Opus' }) + expect(readTrackBoxEntryBytes(segment, audio)).toEqual(OPUS_ENTRY) + // The written entry holds the stream's fields and boxes, its hvcC's parameter set arrays marked complete where the stream's are not, and every other + // octet as the stream wrote it. + expect(written.subarray(8, 8 + 78)).toEqual(STREAM_VIDEO_ENTRY.subarray(8, 8 + 78)) + expect(arraysOf(STREAM_VIDEO_ENTRY)).toEqual([ + [32, 1], + [33, 1], + [34, 1], + ]) + expect(arraysOf(written)).toEqual([ + [0x80 | 32, 1], + [0x80 | 33, 1], + [0x80 | 34, 1], + ]) + expect(Array.from(written.subarray(8 + 78)).filter((octet, at) => octet !== STREAM_VIDEO_ENTRY[8 + 78 + at])).toEqual([0x80 | 32, 0x80 | 33, 0x80 | 34]) + expect(written).toHaveLength(STREAM_VIDEO_ENTRY.length) + expect(readTrackBoxParameterSets(segment, video, { lengthSize: 4, limit: 16384 })?.units).toEqual(HEVC_SETS) + expect(readSampleDefaults(segment, moov)).toEqual(new Map([ + [ + 1, + { duration: 0, flags: 0, size: 0 }, + ], + [ + 2, + { duration: 0, flags: 0, size: 0 }, + ], + ])) + + const pictureAlone = writeInitializationSegment({ video: STREAM.video! }) + const aloneMoov = only(pictureAlone, 'moov') + + expect(readTrackBoxes(pictureAlone, aloneMoov).map(({ track }) => track)).toEqual([ + { handler: 'vide', id: 1, timescale: 90000 }, + ]) + expect(treeOf(pictureAlone)[1].children!.map(({ type }) => type)).toEqual(['mvhd', 'trak', 'mvex']) + expect(readSampleDefaults(pictureAlone, aloneMoov).size).toBe(1) + + // The parameter sets handed in out of their types' order, an SEI among them. + const handed = writeInitializationSegment({ + parameterSets: tierFrameData([ + SEI, + HEVC_SETS[1], + HEVC_SETS[0], + HEVC_SETS[2], + ]), + video: BARE.video!, + }) + const [handedVideo] = readTrackBoxes(handed, only(handed, 'moov')) + + expect(BARE.video?.parameterSets).toHaveLength(0) + expect(readTrackBoxParameterSets(handed, handedVideo, { lengthSize: 4, limit: 16384 })?.units).toEqual([...HEVC_SETS, SEI]) + expect(arraysOf(readTrackBoxEntryBytes(handed, handedVideo)!)).toEqual([ + [0x80 | 32, 1], + [0x80 | 33, 1], + [0x80 | 34, 1], + [39, 1], + ]) + expect(() => writeInitializationSegment({ video: BARE.video! })).toThrow(new RangeError('The stream\'s video track carries no parameter sets in its ' + + 'sample entry and none were given, and an hvc1 sample entry cannot be decoded without them.')) + }) + + it('writes a movie of one keyframe that reads back as one picture track holding that keyframe alone, sync, at decode time 0 with the duration given, ' + + 'under the description\'s parameter sets', () => { + const keyframe = tierFrameData(HEVC[0]) + const movie = writeKeyframeMovie({ duration: 3000, keyframe, video: STREAM.video! }) + const { samples, tracks } = readMovie(movie) + + expect(tracks.audio).toBeUndefined() + expect(tracks.video).toMatchObject({ height: 36, timescale: 90000, width: 64 }) + expect(tracks.video!.parameterSets).toEqual(STREAM.video!.parameterSets) + expect(samples).toEqual([ + { + compositionOffset: 0, + data: keyframe, + decodeTime: 0n, + duration: 3000, + sync: true, + track: tracks.video, + }, + ]) + expect(movie.subarray(0, writeKeyframeInitializationSegment({ keyframe, video: STREAM.video! }).length)) + .toEqual(writeInitializationSegment({ video: STREAM.video! })) + }) + + it('writes a keyframe\'s initialization segment and movie under the keyframe\'s own parameter sets for a picture whose description holds none, and ' + + 'throws the initialization segment\'s RangeError where neither holds them', () => { + const keyframe = tierFrameData(HEVC[0]) + const { samples, tracks } = readMovie(writeKeyframeMovie({ duration: 1500, keyframe, video: BARE.video! })) + + expect(BARE.video!.parameterSets).toHaveLength(0) + expect(tracks.video!.parameterSets).toEqual(tierFrameData(HEVC_SETS)) + expect(samples.map(({ data, duration }) => [data, duration])).toEqual([ + [keyframe, 1500], + ]) + expect(writeKeyframeInitializationSegment({ audio: STREAM.audio, keyframe, video: BARE.video! })) + .toEqual(writeInitializationSegment({ + audio: STREAM.audio, + parameterSets: tierFrameData(HEVC_SETS), + video: BARE.video!, + })) + + // A frame after the keyframe carries no parameter set, which means a picture whose description holds none has none at all. + const bare = tierFrameData(HEVC[1]) + const refusal = new RangeError('The stream\'s video track carries no parameter sets in its sample entry and none were given, and an hvc1 sample entry ' + + 'cannot be decoded without them.') + + expect(() => writeKeyframeInitializationSegment({ keyframe: bare, video: BARE.video! })).toThrow(refusal) + expect(() => writeKeyframeMovie({ duration: 1500, keyframe: bare, video: BARE.video! })).toThrow(refusal) + }) + + it('writes the header fields ffmpeg writes: the sound track header\'s alternate group 1 and full volume, the picture\'s width and height in 16.16 fixed ' + + 'point, and a movie timescale of 48000 with a sound track and 1000 without', () => { + // A child box of a box, and a track header's fields from its version and flags on: the alternate group, the volume, the width and the height. + const childOf = (data: Buffer, parent: Mp4Box, type: string): Mp4Box => walkBoxes(data, parent.payload, parent.end).boxes.find(child => child.type === type)! + const headerOf = (data: Buffer, trak: Mp4Box): number[] => { + const { payload } = childOf(data, trak, 'tkhd') + + return [ + data.readUInt16BE(payload + 34), + data.readUInt16BE(payload + 36), + data.readUInt32BE(payload + 76), + data.readUInt32BE(payload + 80), + ] + } + // A movie header's timescale, from its version and flags on. + const movieTimescaleOf = (data: Buffer): number => data.readUInt32BE(childOf(data, only(data, 'moov'), 'mvhd').payload + 12) + const segment = writeInitializationSegment({ audio: STREAM.audio, video: STREAM.video! }) + const pictureAlone = writeInitializationSegment({ video: STREAM.video! }) + const traks = walkBoxes(segment, only(segment, 'moov').payload, only(segment, 'moov').end).boxes.filter(({ type }) => type === 'trak') + + expect(traks.map(trak => headerOf(segment, trak))).toEqual([ + [0, 0, 64 * 0x10000, 36 * 0x10000], + [1, 0x0100, 0, 0], + ]) + expect(headerOf(pictureAlone, childOf(pictureAlone, only(pictureAlone, 'moov'), 'trak'))).toEqual([0, 0, 64 * 0x10000, 36 * 0x10000]) + expect(movieTimescaleOf(segment)).toBe(48000) + expect(movieTimescaleOf(pictureAlone)).toBe(1000) + }) + + it('writes a segment whose every sample reads back through the box readers with its octets, decode time past 2^32, duration, size, sync flag and signed ' + + 'composition offset, no traf for a track with no samples, and an initialization segment and a segment the producer reference time writer passes ' + + 'and a served recording places', () => { + const video: SegmentRun = { + decodeTime: 2n ** 32n + 3000n, + samples: [ + { + compositionOffset: 6000, + data: tierFrameData(HEVC[0].slice(3)), + duration: 3000, + sync: true, + }, + { + compositionOffset: -3003, + data: tierFrameData(HEVC[1]), + duration: 3003, + sync: false, + }, + { + compositionOffset: 0, + data: tierFrameData(HEVC[2]), + duration: 3000, + sync: false, + }, + ], + } + const audio: SegmentRun = { + decodeTime: 96000n, + samples: [ + { + compositionOffset: 0, + data: Buffer.from([0xFC, 1]), + duration: 960, + sync: false, + }, + { + compositionOffset: 0, + data: Buffer.from([0xFC, 2, 3]), + duration: 960, + sync: false, + }, + ], + } + const segment = writeSegment({ audio, sequenceNumber: 7, video }) + const moof = only(segment, 'moof') + const mdat = only(segment, 'mdat') + + expect(walkBoxes(segment)).toMatchObject({ complete: true }) + expect(walkBoxes(segment).boxes.map(({ type }) => type)).toEqual(['moof', 'mdat']) + expect(walkBoxes(segment, moof.payload, moof.end).boxes.map(({ type }) => type)).toEqual(['mfhd', 'traf', 'traf']) + expect(segment.readUInt32BE(moof.payload + 12)).toBe(7) + expect(mdat.end - mdat.payload).toBe([ + ...video.samples, + ...audio.samples, + ].reduce((total, { data }) => total + data.length, 0)) + expect(readTrackFragments(segment, moof)).toEqual([ + { baseMediaDecodeTime: 2n ** 32n + 3000n, duration: 9003n, trackId: 1 }, + { baseMediaDecodeTime: 96000n, duration: 1920n, trackId: 2 }, + ]) + expect(samplesOf(segment, 1)).toEqual([ + { + compositionOffset: 6000, + data: video.samples[0].data, + decodeTime: 2n ** 32n + 3000n, + duration: 3000, + size: video.samples[0].data.length, + sync: true, + }, + { + compositionOffset: -3003, + data: video.samples[1].data, + decodeTime: 2n ** 32n + 6000n, + duration: 3003, + size: video.samples[1].data.length, + sync: false, + }, + { + compositionOffset: 0, + data: video.samples[2].data, + decodeTime: 2n ** 32n + 9003n, + duration: 3000, + size: video.samples[2].data.length, + sync: false, + }, + ]) + expect(samplesOf(segment, 2)).toEqual([ + { + compositionOffset: 0, + data: audio.samples[0].data, + decodeTime: 96000n, + duration: 960, + size: 2, + sync: true, + }, + { + compositionOffset: 0, + data: audio.samples[1].data, + decodeTime: 96960n, + duration: 960, + size: 3, + sync: true, + }, + ]) + + for (const silent of [ + writeSegment({ + audio: { decodeTime: 0n, samples: [] }, + sequenceNumber: 8, + video, + }), + writeSegment({ sequenceNumber: 9, video }), + ]) { + expect(readTrackFragments(silent, only(silent, 'moof')).map(({ trackId }) => trackId)).toEqual([1]) + expect(samplesOf(silent, 1).map(({ data }) => data)).toEqual(video.samples.map(({ data }) => data)) + } + + const writer = new ProducerReferenceTimeWriter() + const recordings = new ServedRecordings({ + reporter: detachedReporter(), + sensorUUID: 'a1b2c3d4-0000-4000-8000-00000000000a', + }) + const recording = recordings.begin() + const initialization = writer.writePacket(writeInitializationSegment({ audio: STREAM.audio, video: STREAM.video! }), 0) + const fragment = writer.writePacket(segment, 1000) + + recording.add(initialization) + recording.add(fragment) + + expect(initialization.initialization?.video).toEqual({ handler: 'vide', id: 1, timescale: 90000 }) + expect(fragment.fragments).toHaveLength(1) + expect(fragment.fragments[0].runs.map(({ duration }) => duration)).toEqual([9003n, 1920n]) + expect(recording.closed).toBe(false) + expect(recording.length).toBe(1) + expect(recording.fragment(0)?.timescaleDuration).toBe(9003n) + recordings[Symbol.dispose]() + }) +}) diff --git a/src/lib/camera/recording/CMAFRecordingManagement.ts b/src/lib/camera/recording/CMAFRecordingManagement.ts new file mode 100644 index 000000000..37b5790b3 --- /dev/null +++ b/src/lib/camera/recording/CMAFRecordingManagement.ts @@ -0,0 +1,1838 @@ +import type { Buffer } from 'node:buffer' +import type { KeyObject } from 'node:crypto' + +import type { ControllerAccessoryContext, ControllerServiceMap } from '../../controller/index.js' +import type { AccessoryInformation, CameraBufferManagement, CameraClientCertificateManagement, CameraKeyManagement } from '../../definitions/index.js' +import type { RecordingProvisioningEntry } from '../../model/RecordingProvisioning.js' +import type { + BufferActivityCommandRequest, + BufferEventCommandRequest, + BufferEventCommandResponse, + BufferUploadCommandRequest, + BufferUploadCommandResponse, + CameraRecordingPublishingPointPayload, +} from '../capabilities/cameraBuffer.js' +import type { CameraClientCertificateRequest, CameraClientCSRRequest, CameraClientCSRResponse, CameraKeyPayload } from '../capabilities/provisioning.js' +import type { CameraReporter, DebugWriter } from '../diagnostics/CameraReporter.js' +import type { OperatingModePolicy } from '../OperatingModePolicy.js' +import type { CameraBufferEventInput } from './CameraEventQueue.js' +import type { PlaylistSegment } from './clipPackaging.js' +import type { ContentKey } from './clipSealing.js' +import type { ServedFragment, ServedReader, ServedRecording, ServedRecordings, ServedRun } from './ServedRecording.js' + +import { X509Certificate } from 'node:crypto' +import { setTimeout as sleep } from 'node:timers/promises' + +import { Access, Characteristic } from '../../Characteristic.js' +import { HAPStatus } from '../../HAPServer.js' +import { RecordingProvisioning } from '../../model/RecordingProvisioning.js' +import { Service } from '../../Service.js' +import { counted } from '../../util/counted.js' +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 { + BufferActivity, + BufferEventCommandType, + BufferUploadCommandType, + BufferUploadStopAction, + CameraBufferEventType, + CMAFError, + decodeBufferActivityCommandRequest, + decodeBufferEventCommandRequest, + decodeBufferUploadCommandRequest, + decodeCameraRecordingPublishingPoint, + encodeBufferEventCommandResponse, + encodeBufferUploadCommandResponse, + encodeCameraRecordingPublishingPoint, +} from '../capabilities/cameraBuffer.js' +import { + decodeCameraClientCertificateRequest, + decodeCameraClientCSRRequest, + decodeCameraKey, + encodeCameraClientCertificateRequest, + encodeCameraClientCertificateStatus, + encodeCameraClientCSRResponse, + encodeCameraKeyID, +} from '../capabilities/provisioning.js' +import { CAPABILITY_KEY_PREFIX } from '../capabilityKeys.js' +import { debugChannel } from '../diagnostics/debugChannels.js' +import { CommandQueue } from '../session/CommandQueue.js' +import { wireControlPoint } from '../session/controlPoint.js' +import { CameraEventQueue, SKIP_AHEAD } from './CameraEventQueue.js' +import { + bandwidthsOf, + closingMediaPlaylist, + codecsOf, + CONTENT_TYPES, + EXTINF_DURATION_HEADER, + extinfDuration, + FIRST_SEGMENT, + initializationPath, + MEDIA_PLAYLIST, + MULTIVARIANT_PLAYLIST, + multivariantPlaylist, + openingMediaPlaylist, + segmentPath, + sessionFolder, +} from './clipPackaging.js' +import { contentKeyOf, keyAttributes, seal, SEALING_OVERHEAD } from './clipSealing.js' +import { IngestError, IngestSession, parsePublishingPointURL } from './IngestSession.js' +import { distance, SERVED_RECORDING_GRACE } from './ServedRecording.js' +import { createSigningRequest } from './signingRequest.js' + +const CMAF_RECORDING_DEBUG = debugChannel('HAP-NodeJS:Camera:CMAFRecording') +const PROVISIONING_DEBUG = debugChannel('HAP-NodeJS:RecordingProvisioning') + +// A certificate counts as needing an update from this long before its end, and the status is checked again this often while the camera runs. +const RENEWAL_WINDOW = 7 * 24 * 60 * 60 * 1000 +const DAILY = 24 * 60 * 60 * 1000 + +// A camera that cannot encrypt a clip raises an upload-refused problem at its first refused Start and again only once this long has passed since its last. +const REFUSAL_WARNING_INTERVAL = 60 * 60 * 1000 + +// A restored sequence mark at or past this reads as absent, and a queue built from it cannot wrap past 2^64. +const MARK_LIMIT = 2n ** 64n - 2n * SKIP_AHEAD + +// A clip mark restored when the accessory hands its context is raised by this margin. A number whose save was lost is not used again. +const CLIP_MARK_MARGIN = 16n + +// A clip repeats an object, in a new ingest session, at most this often and this long after its failure, and only for a failure a repeat can cure: a +// 4xx or a refused credential will not change on a repeat. +const MAX_REPEATS = 2 +const REPEAT_DELAY = 1000 +const REPEATED_ERRORS: ReadonlySet = new Set([ + CMAFError.HTTP_INTERNAL_SERVER_ERROR, + CMAFError.HTTP_SERVICE_UNAVAILABLE, + CMAFError.REQUIRES_RETRY, + CMAFError.NO_RESPONSE, + CMAFError.TIMEOUT, + CMAFError.CONNECTION_FAILED, +]) + +// The answer to an object the folder already holds. +const ALREADY_REPORTED = 208 + +// An ended clip's Session ID answers its Clip ID this long, and a hub's late Stop or repeated Start is answered as the clip was. +const ENDED_TAIL = 60 * 1000 + +// A hub clears a part of the package by writing no bytes to its characteristic. +const CLEAR = Symbol('clear') + +/** + * The services of the HKSV3 recording management, as a camera's service map holds them. + * @private + */ +export interface CMAFRecordingServices { + /** + * The Camera Buffer Management service. + */ + buffer: CameraBufferManagement + /** + * The Camera Key Management service. + */ + key: CameraKeyManagement + /** + * The Camera Client Certificate Management service. + */ + certificate: CameraClientCertificateManagement +} + +// The services in the order they are built and a camera's service map holds them. +const SERVICE_PARTS = ['buffer', 'key', 'certificate'] as const satisfies readonly (keyof CMAFRecordingServices)[] + +/** + * What a camera hands its HKSV3 recording management beside its services. + * @private + */ +export interface CMAFRecordingManagementOptions { + /** + * The recordings the camera's recording stream serves, which its clips upload from. + */ + feed: ServedRecordings + /** + * The camera's operating-mode policy, whose recording published, the user's switches allowing recording and the camera's accessory published, gates a + * clip's Start and ends every clip once it turns false. + */ + policy: OperatingModePolicy + /** + * The camera's reporter, through which a clip's failed upload, a Start refused for want of a usable Camera Key and a failed write of the camera's + * recording provisioning record are the camera's problems. + */ + reporter: CameraReporter +} + +// The identity a context names, which the management holds the package of. +interface Identity { + accessoryUUID: string + username: string +} + +// The status's parts the hubs read: the entry is whole when it holds a credential, a Camera Key and a publishing point. +function isWhole(entry: RecordingProvisioningEntry): boolean { + return entry.credential !== undefined && entry.cameraKey !== undefined && entry.publishingPoint !== undefined +} + +// What a clip takes when it opens and keeps for its life, which means a clear or a replacement under it changes nothing it sends. +interface ClipIdentity { + readonly contentKey: ContentKey + readonly credential: NonNullable + readonly point: CameraRecordingPublishingPointPayload + readonly userAgent: string +} + +// Whether the held entry lets the camera upload: what a clip takes from it when it opens, or why the camera cannot upload, which is holding no credential +// or no publishing point, holding no Camera Key, or holding a Camera Key no content key derives from, with the sentence its derivation refused it with. +type UploadReadiness + = | Omit & { kind: 'ready' } + | { kind: 'unprovisioned' } + | { kind: 'keyless' } + | { kind: 'unusable', reason: string } + +// The readiness an entry gives, its content key derived once here rather than at each clip's open. +function readinessOf({ cameraKey, credential, publishingPoint }: RecordingProvisioningEntry): UploadReadiness { + if (credential === undefined || publishingPoint === undefined) { + return { kind: 'unprovisioned' } + } + + if (cameraKey === undefined) { + return { kind: 'keyless' } + } + + try { + return { + contentKey: contentKeyOf(cameraKey), + credential, + kind: 'ready', + point: publishingPoint, + } + } catch (error) { + return { + kind: 'unusable', + reason: errorMessage(error), + } + } +} + +// 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. +interface ClipContext { + readonly allocate: () => bigint + readonly debug: DebugWriter + readonly enqueue: (event: CameraBufferEventInput) => void + readonly ended: (clip: ClipSession) => void + readonly fail: (failure: string) => void + readonly reporter: CameraReporter +} + +// One fragment a clip read, with the reader and recording it came from, its run and its duration in seconds. +interface ReadFragment { + readonly fragment: ServedFragment & { readonly bytes: Buffer } + readonly reader: ServedReader + readonly recording: ServedRecording + readonly run: ServedRun + readonly seconds: number +} + +// The objects a clip sends, in the order it sends them: the multivariant playlist, the opening media playlist, each run's initialization segment before its +// first segment, each segment, and the closing media playlist. +type ClipObject + = | { kind: 'multivariant' } + | { kind: 'opening' } + | { kind: 'initialization', read: ReadFragment } + | { kind: 'segment', read: ReadFragment } + | { kind: 'closing' } + +// How one send of an object went: answered with a 2xx status, its session ended idle with every object it sent answered, or its session failed. +type Attempt + = | { kind: 'answered', status: number } + | { kind: 'idle' } + | { error: unknown, kind: 'failed' } + +type ClipState = 'uploading' | 'paused' | 'ended' + +// Why a session a clip could not send on ended: idle, with none of its objects lost, or with its one failure, which finish rejects with. +async function sessionEnd(session: IngestSession): Promise { + try { + await session.finish() + + return { kind: 'idle' } + } catch (error) { + return { error, kind: 'failed' } + } +} + +// A field of the User-Agent's comment: printable ASCII with the comment's own syntax spaced out, runs of spaces collapsed, and `Unknown` when nothing is left. +function userAgentField(value: unknown): string { + const field = String(value ?? '').replace(/[^\x20-\x7E]|[();]/g, ' ').replace(/ {2,}/g, ' ').trim() + + return field === '' + ? 'Unknown' + : field +} + +/* One clip session: the span of a served recording a hub commanded, keyed by the hub's Session ID and uploaded as an HLS session folder under the clip + * number the camera allocated. The clip reads fragments from its reader as they arrive, before it knows which it will send: it notices its recording's + * end, its unusability, a released fragment or its reader's end even while it waits on a verdict. It requests a fragment it read only once that fragment + * is known to lie inside its window: the fragment its Start names at once, a later one once a Should Record verdict on it or on a fragment after it + * arrives, or once a Stop puts it inside. A Should Not Record verdict on a fragment of its recording holds the clip at the fragment before that one, and + * until its Stop it sends nothing past the hold whatever later verdicts read; a later rejection only lowers the hold, and a Stop that reaches past it sends + * what it includes. A stop, once set, bounds the clip whatever later verdicts read. Every fragment requested is sent, in order, one object answered before + * the next, which means the folder holds exactly the segments its closing playlist lists. + * + * A clip's end is one routine guarded by its first step, which every path that ends it runs: a finalize, a failure, a disallow or an unpublish, a reset + * and a removal. + */ +class ClipSession { + readonly sessionID: bigint + + readonly clipID: bigint + + private readonly identity: ClipIdentity + + private readonly context: ClipContext + + private readonly controller = new AbortController() + + // The fragments read and not yet requested, and those requested and not yet answered, each in order. + private readonly pending: ReadFragment[] = [] + + private readonly requested: ReadFragment[] = [] + + // Each segment the folder holds, in the order it was answered, for the closing playlist. + private readonly segments: PlaylistSegment[] = [] + + private readonly readings: Promise[] = [] + + private readonly uploading: Promise + + private clipState: ClipState = 'uploading' + + // The folder the clip sends under: its Clip ID until a 208 on its multivariant playlist moves it to a number no clip has used. + private folder: bigint + + // The reader, its recording, and the index of the fragment its Start named, which goes at once. + private reader?: ServedReader + + private recording: ServedRecording + + private readerStart: number + + // Whether the reader's iterator has ended on its own, at its recording's end, its unusability or a released fragment. + private readEnded = false + + private lastRead?: number + + private lastRequested?: number + + // The stop, a fragment index on the reader's recording, or the place of a Stop whose fragment end is not yet served, and what the Stop does there. + private stop?: number + + private stopPlace?: bigint + + private action?: BufferUploadStopAction + + // The hold, a fragment index on the reader's recording past which the clip sends nothing while no stop is set, lowered by each Should Not Record verdict + // on that recording and ended by a Stop or a resume. + private hold?: number + + private grace?: ReturnType + + private session?: IngestSession + + private repeats = 0 + + private multivariantSent = false + + private openingSent = false + + // The run whose initialization segment the folder holds last, and how many initialization segments it holds. + private sentRun?: ServedRun + + private initializations = 0 + + private wakeup?: () => void + + constructor({ clipID, context, from, identity, recording, sessionID }: { + clipID: bigint + context: ClipContext + from: number + identity: ClipIdentity + recording: ServedRecording + sessionID: bigint + }) { + this.sessionID = sessionID + this.clipID = clipID + this.folder = clipID + this.identity = identity + this.context = context + this.recording = recording + this.readerStart = from + + // The reader opens in the Start's own turn, before any object is sent, because until a reader holds it the fragment is kept only until the next verdict. + this.reader = recording.read(from, this.controller.signal) + this.readings.push(this.read(this.reader, recording)) + this.uploading = this.upload() + } + + /** + * Whether the clip is uploading, paused or ended. + */ + get state(): ClipState { + return this.clipState + } + + /** + * A Start with a paused clip's Session ID: the Pause's stop, a Stop place kept with it and any hold cleared, and a new reader opened at the fragment the + * Start names. + * @param recording - The recording holding the fragment. + * @param from - The fragment's index. + */ + resume(recording: ServedRecording, from: number): void { + this.clipState = 'uploading' + this.stop = undefined + this.stopPlace = undefined + this.action = undefined + this.hold = undefined + this.recording = recording + this.readerStart = from + this.readEnded = false + this.lastRead = undefined + this.lastRequested = undefined + this.reader = recording.read(from, this.controller.signal) + this.readings.push(this.read(this.reader, recording)) + this.context.debug('clip-resumed', () => ({ + clipID: String(this.clipID), + sentence: `Clip ${this.clipID} resumes.`, + })) + this.wake() + } + + /** + * A Stop. On a running clip it ends the hold and sets the stop at the fragment end the place matches, or at the latest fragment requested when the place + * ends before it, a place past an ended recording's last fragment clamping to it and one past the fragments served kept until a fragment's end matches + * it. On a paused clip a Finalize closes the folder and a Pause changes nothing. + * @param place - The Stop's place on the hub's timeline. + * @param action - What the clip does once it has drained to its stop. + */ + stopAt(place: bigint, action: BufferUploadStopAction): void { + if (this.clipState === 'ended') { + return + } + + if (this.clipState === 'paused') { + if (action === BufferUploadStopAction.FINALIZE) { + this.action = action + this.clipState = 'uploading' + this.wake() + } + + return + } + + this.action = action + this.hold = undefined + clearTimeout(this.grace) + this.grace = undefined + + const matched = this.recording.fragmentAt(place, 'end') + + if (matched !== undefined) { + this.setStop(matched.index) + } else if (!this.pastLastFragment(place)) { + this.setStop(this.lastRequested ?? this.readerStart) + } else if (this.recording.closed) { + this.setStop(this.recording.length - 1) + } else if (this.readEnded) { + this.setStop(this.lastRead ?? this.readerStart) + } else { + this.stop = undefined + this.stopPlace = place + } + + this.reconsider() + } + + /** + * A Should Not Record verdict on a fragment: on the clip's own recording it lowers the hold to the fragment before the one the verdict names, never + * raising it. + * @param recording - The recording the verdict names. + * @param index - The index of the fragment the verdict names. + */ + holdBefore(recording: ServedRecording, index: number): void { + if (this.clipState === 'ended' || recording !== this.recording) { + return + } + + this.hold = Math.min(this.hold ?? Number.POSITIVE_INFINITY, index - 1) + } + + /** + * Reads the window again, after a verdict or any change to the clip: a kept Stop place resolved, each fragment read that the window lets in requested, + * and the upload woken. + */ + reconsider(): void { + if (this.clipState === 'ended') { + return + } + + this.resolveStopPlace() + + while (this.pending.length > 0 && this.inside(this.pending[0].fragment.index)) { + const read = this.pending.shift()! + + this.requested.push(read) + this.lastRequested = read.fragment.index + } + + this.wake() + } + + /** + * Ends the clip, queuing Session Stop when it finalized and the CMAF error that ended it otherwise, ends its reader and cancels its upload. A clip a + * failure ends raises its upload-failed problem here, once, because the camera's user reads no debug output. Safe to call more than once. + * @param cmafError - The error that ended the clip, or none when it finalized. + * @param failure - The sentence naming the failure that ended the clip, or none when the clip finalized or was canceled. + */ + end(cmafError?: CMAFError, failure?: string): void { + if (this.clipState === 'ended') { + return + } + + this.clipState = 'ended' + clearTimeout(this.grace) + this.grace = undefined + + if (failure !== undefined) { + this.context.fail(failure) + } + + this.context.enqueue(cmafError === undefined + ? { cmafSessionID: this.clipID, type: CameraBufferEventType.CMAF_SESSION_STOP } + : { cmafError, cmafSessionID: this.clipID, type: CameraBufferEventType.CMAF_ERROR }) + + // The abort ends the reader, cancels the session's request in flight and cuts a repeat's wait. + this.controller.abort() + this.reader = undefined + this.pending.length = 0 + this.requested.length = 0 + this.context.ended(this) + this.wake() + } + + /** + * Waits for the clip's upload and readings to settle, its ingest session closed. + * @returns A promise that resolves once nothing of the clip runs. + */ + async settled(): Promise { + await this.uploading + await Promise.all(this.readings) + } + + // Reads a reader's fragments as they arrive, requesting each the window lets in. An iterator that ends on its own, rather than at the clip's end of its + // reader, starts the grace. Nothing observes a reading, which is why a throw here ends the clip rather than rejecting. + private async read(reader: ServedReader, recording: ServedRecording): Promise { + try { + for await (const fragment of reader) { + const { run } = recording + + if (this.reader !== reader || run === undefined) { + break + } + + this.pending.push({ + fragment, + reader, + recording, + run, + seconds: Number(fragment.timescaleDuration) / run.video.timescale, + }) + this.lastRead = fragment.index + this.reconsider() + } + + if (this.reader === reader && this.clipState === 'uploading') { + this.readerFinished() + } + } catch (error) { + this.failed(error) + } + } + + /* The reader's iterator ended with the clip running: a kept Stop place resolves at the last fragment read, and a stop past it clamps to it. With no Stop, + * the clip finalizes once the served recording's grace has run from this end, never from the arrival of the last fragment it read, unless the hub's + * Stop comes first. It then sends what the window holds at that moment, bounded by its hold, and nothing past it. + */ + private readerFinished(): void { + this.readEnded = true + + if (this.stop !== undefined) { + this.setStop(this.stop) + } + + this.reconsider() + + if (this.stop !== undefined || this.clipState !== 'uploading') { + return + } + + this.grace = setTimeout(() => { + this.grace = undefined + this.action = BufferUploadStopAction.FINALIZE + this.setStop(this.lastRequested ?? this.readerStart) + this.context.debug('clip-finalizing', () => ({ + clipID: String(this.clipID), + sentence: `Clip ${this.clipID} finalizes at the end of its grace.`, + })) + this.reconsider() + }, SERVED_RECORDING_GRACE) + this.grace.unref() + } + + // Whether a fragment lies inside the window: the Start's fragment always, then every fragment at or before the stop once one is set, and otherwise every + // fragment at or before the latest one the hub judged Should Record and at or before the hold. + private inside(index: number): boolean { + if (index === this.readerStart) { + return true + } + + if (this.stop !== undefined) { + return index <= this.stop + } + + const latest = this.recording.latestShouldRecord + + return latest !== undefined && index <= latest && (this.hold === undefined || index <= this.hold) + } + + // Sets the stop at a fragment, never before the latest fragment requested and never past the last one a finished reader read. + private setStop(index: number): void { + const stop = Math.max(index, this.lastRequested ?? this.readerStart) + + this.stop = this.readEnded && this.lastRead !== undefined + ? Math.min(stop, this.lastRead) + : stop + this.stopPlace = undefined + } + + // A kept Stop place sets the stop once a fragment's end matches it, or at the last fragment read once the reader has finished. + private resolveStopPlace(): void { + if (this.stopPlace === undefined) { + return + } + + const matched = this.recording.fragmentAt(this.stopPlace, 'end') + + if (matched !== undefined) { + this.setStop(matched.index) + } else if (this.readEnded) { + this.setStop(this.lastRead ?? this.readerStart) + } + } + + // Whether a place lies past the end of the recording's last fragment, by serial arithmetic modulo 2^64. + private pastLastFragment(place: bigint): boolean { + const last = this.recording.fragment(this.recording.length - 1) + + return last !== undefined && distance(last.place + last.duration, place) > 0n + } + + // Whether the clip has sent every fragment through its stop. + private drained(): boolean { + return this.stop !== undefined && this.lastRequested === this.stop && this.requested.length === 0 + } + + // The next object to send, or none while the clip waits on a fragment, a verdict or a command. + private next(): ClipObject | undefined { + if (this.clipState !== 'uploading') { + return undefined + } + + if (!this.multivariantSent) { + return this.requested.length === 0 + ? undefined + : { kind: 'multivariant' } + } + + if (!this.openingSent) { + return { kind: 'opening' } + } + + const [read] = this.requested + + if (read !== undefined) { + return read.run === this.sentRun + ? { kind: 'segment', read } + : { kind: 'initialization', read } + } + + return this.drained() && this.action === BufferUploadStopAction.FINALIZE + ? { kind: 'closing' } + : undefined + } + + // Sends each object in turn until the clip ends, pausing once it has drained to a Pause's stop. Its ingest session is closed whatever ends it. Nothing + // observes the upload until a destroy waits for it, which is why a throw here ends the clip rather than rejecting. + private async upload(): Promise { + try { + while (this.clipState !== 'ended') { + if (this.clipState === 'uploading' && this.drained() && this.action === BufferUploadStopAction.PAUSE) { + this.pause() + } + + const object = this.next() + + if (object === undefined) { + await this.change() + continue + } + + await this.send(object) + } + } catch (error) { + this.failed(error) + } + + await this.discardSession().catch(error => this.failed(error)) + } + + /* Sends one object until a 2xx answers it. A session that ended idle is opened again without spending a repeat; a failure a repeat can cure is repeated + * in a new session after the repeat delay, within the repeats a clip has, and any other ends the clip with its CMAF error. A 208 on the multivariant playlist, always + * its folder's first object, means another clip used the folder's number. The clip takes the next number from the mark and sends under it. + */ + private async send(object: ClipObject): Promise { + const { signal } = this.controller + + for (;;) { + const attempt = await this.attempt(object) + + // The clip's end aborts its signal, and an attempt it cut short is no failure of the upload's. + if (signal.aborted) { + return + } + + if (attempt.kind === 'answered') { + if (attempt.status === ALREADY_REPORTED && object.kind === 'multivariant') { + if (!this.advance()) { + return + } + + continue + } + + // The closing playlist's answer is the folder's last: the session finishes before the clip ends and closes as finished. A session that fails as + // it finishes has had every object answered, which is why the clip finalizes all the same. + if (object.kind === 'closing') { + await this.session?.finish().catch(() => undefined) + + if (signal.aborted) { + return + } + } + + this.answered(object) + + return + } + + await this.discardSession() + + if (signal.aborted) { + return + } + + if (attempt.kind === 'idle') { + continue + } + + const { error } = attempt + const failure = error instanceof IngestError + ? error + : undefined + const cmafError = failure?.cmafError ?? CMAFError.UNKNOWN + + // An ingest failure is named by its message, its CMAF error and its status alone, never its cause or its body. + this.context.debug('object-send-failed', () => { + const message = failure?.message ?? String(error) + const status = failure?.status + + return { + clipID: String(this.clipID), + cmafError, + message, + sentence: `Clip ${this.clipID} failed to send an object: ${message} (CMAF error ${cmafError}, status ${status}).`, + status, + } + }) + + if (!REPEATED_ERRORS.has(cmafError) || this.repeats >= MAX_REPEATS) { + this.end(cmafError, `${failure?.message ?? String(error)}${failure?.status === undefined + ? '' + : ` Its answer was status ${failure.status}.`}`) + + return + } + + this.repeats++ + await sleep(REPEAT_DELAY, undefined, { ref: false, signal }).catch(() => undefined) + + if (signal.aborted) { + return + } + } + } + + // One send of an object on the clip's session, opened when it has none. A put refused before its request went out, or an answer the session's failure + // left unread, is read from how the session ended. + private async attempt(object: ClipObject): Promise { + const { body, contentType, headers, path } = this.payload(object) + let session = this.session + + if (session === undefined) { + try { + session = await IngestSession.open({ + clientCA: this.identity.credential.ca, + clientCertificate: this.identity.credential.certificate, + privateKey: this.identity.credential.privateKey, + reporter: this.context.reporter, + serverCAs: this.identity.point.serverCACertificates.map(({ certificate }) => certificate), + signal: this.controller.signal, + url: this.identity.point.url, + userAgent: this.identity.userAgent, + }) + } catch (error) { + return { error, kind: 'failed' } + } + + this.session = session + } + + try { + const status = await (await session.put(`${sessionFolder(this.folder)}${path}`, contentType, body, headers)).answer + + if (status !== undefined) { + return { kind: 'answered', status } + } + } catch { + // The session ended before the request went out, which how it ended tells apart from a failure. + } + + 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. + private payload(object: ClipObject): { body: Uint8Array, contentType: string, headers?: Record, path: string } { + const { contentKey } = this.identity + + switch (object.kind) { + case 'multivariant': { + const reads = [ + ...this.requested, + ...this.pending, + ] + const { 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 }))) + + return { + body: new TextEncoder().encode(multivariantPlaylist({ + average, + codecs: codecsOf(run.sampleEntries.values()), + keyAttributes: keyAttributes(contentKey), + peak, + resolution: video?.width === undefined || video.height === undefined + ? undefined + : { height: video.height, width: video.width }, + })), + contentType: CONTENT_TYPES.playlist, + path: MULTIVARIANT_PLAYLIST, + } + } + + case 'opening': + return { + body: new TextEncoder().encode(openingMediaPlaylist({ + keyAttributes: keyAttributes(contentKey), + targetDuration: Math.ceil(Math.max(...[ + ...this.requested, + ...this.pending, + ].map(({ seconds }) => seconds))), + })), + contentType: CONTENT_TYPES.playlist, + path: MEDIA_PLAYLIST, + } + + case 'initialization': + return { + body: object.read.run.initialization, + contentType: CONTENT_TYPES.initialization, + path: initializationPath(this.initializations + 1), + } + + case 'segment': + return { + body: seal(contentKey, object.read.fragment.bytes), + contentType: CONTENT_TYPES.segment, + headers: { + [EXTINF_DURATION_HEADER]: extinfDuration(object.read.seconds), + }, + path: segmentPath(FIRST_SEGMENT + this.segments.length), + } + + case 'closing': + return { + body: new TextEncoder().encode(closingMediaPlaylist({ + keyAttributes: keyAttributes(contentKey), + segments: this.segments, + })), + contentType: CONTENT_TYPES.playlist, + path: MEDIA_PLAYLIST, + } + } + } + + // Takes what a 2xx answer settles: each segment reported sent to its reader, and the closing playlist's answer finalizing the clip. + private answered(object: ClipObject): void { + switch (object.kind) { + case 'multivariant': + this.multivariantSent = true + break + + case 'opening': + this.openingSent = true + break + + case 'initialization': + this.sentRun = object.read.run + this.initializations++ + break + + case 'segment': + this.requested.shift() + this.segments.push({ initialization: this.initializations, seconds: object.read.seconds }) + object.read.reader.sent(object.read.fragment.index) + break + + case 'closing': + // The clip's length is the durations its media playlist states for the segments it uploaded, summed. + this.context.debug('clip-finalized', () => { + const { length } = this.segments + const seconds = this.segments.reduce((sum, segment) => sum + segment.seconds, 0) + + return { + clipID: String(this.clipID), + seconds, + segments: length, + sentence: `Clip ${this.clipID} finalized with ${counted(length, 'segment')}, ${seconds.toFixed(3)} seconds long.`, + } + }) + this.end() + break + } + } + + // Moves the folder to the next clip number from the mark, saved before the resend so an overlapping clip's number is never taken. A save that fails + // ends the clip with CMAF Error Unknown, because no CMAF error names a failed save more closely. + private advance(): boolean { + try { + this.folder = this.context.allocate() + } catch (error) { + this.context.debug('clip-number-unsaved', () => ({ + clipID: String(this.clipID), + message: errorMessage(error), + sentence: `Clip ${this.clipID} could not save the next clip number: ${errorMessage(error)}`, + })) + this.end(CMAFError.UNKNOWN, `The next clip number could not be saved: ${errorMessage(error)}`) + + return false + } + + this.context.debug('clip-folder-moved', () => ({ + clipID: String(this.clipID), + folder: String(this.folder), + sentence: `Clip ${this.clipID} finds its folder used and sends under folder ${this.folder}.`, + })) + + return true + } + + // Ends the clip with CMAF Error Unknown at a throw its upload or a reading does not answer. No promise the clip starts can reject. + private failed(error: unknown): void { + const message = error instanceof Error + ? error.message + : String(error) + + this.context.debug('clip-failed', () => ({ + clipID: String(this.clipID), + message, + sentence: `Clip ${this.clipID} ends on a failure of its own: ${message}`, + })) + this.end(CMAFError.UNKNOWN, `The library met a failure of its own: ${message}`) + } + + // Pauses at the stop: the reader ends, the playlists stay open, and the clip waits for a resume or a Finalize. + private pause(): void { + this.clipState = 'paused' + this.pending.length = 0 + this.reader?.end() + this.reader = undefined + this.context.debug('clip-paused', () => ({ + clipID: String(this.clipID), + sentence: `Clip ${this.clipID} paused.`, + })) + } + + private async discardSession(): Promise { + const session = this.session + + this.session = undefined + await session?.[Symbol.asyncDispose]() + } + + private async change(): Promise { + await new Promise((resolve) => { + this.wakeup = resolve + }) + } + + private wake(): void { + const wakeup = this.wakeup + + this.wakeup = undefined + wakeup?.() + } +} + +/* The HKSV3 recording management of a camera with the capabilities block: the Camera Buffer Management, Camera Key Management and Camera Client + * Certificate Management services, and the recording provisioning package a hub writes through them, kept in the record under the camera's publishing + * username and accessory UUID. HKSV3 is Apple's own name for the iOS 27 camera features, of which this is the recording part, and its public guide does + * not use the name: the Home app's log calls a clip uploaded this way an HKSV3 recording, and each upload's User-Agent opens with `HKSV/3.0`. + * + * A hub provisions a camera by writing Camera Client CSR, Camera Client Certificate, Camera Key and Camera Recording Publishing Point, and it decides + * whether to do so from Camera Client Certificate Status alone: Needs Update reads true while the package is not whole, and from the start of the renewal + * window before the held certificate's end. A renewal is that whole provisioning again, each write replacing what it names, and no write ever touches the + * package's marks, because the service keeps a camera's session folders across provisionings. A write of no bytes to the certificate or the publishing point is the hub's + * clear. Each write saves the whole entry the management holds: a write the record cannot save is answered with a failure the hub repeats, and the + * entry in memory stays as the record has it. + * + * A hub's verdicts reach the served recordings through Buffer Activity Command, a Should Not Record verdict holding each clip on its recording at the + * fragment before the one it names until that clip's Stop, and its Buffer Upload Command opens, stops, pauses and resumes clip sessions keyed by its + * Session ID, never by its connection, each uploading the span of a served recording the hub names. A Start is answered a Clip ID saved as the clip mark + * before the answer. The clips' gate reads the user's switches and the accessory being published and nothing of the camera's source: while recording is + * 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. 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 { + /** + * The key of each service in a camera's service map. + * @private + */ + static readonly SERVICE_KEYS = Object.freeze({ + buffer: `${CAPABILITY_KEY_PREFIX}cameraBufferManagement`, + certificate: `${CAPABILITY_KEY_PREFIX}cameraClientCertificateManagement`, + key: `${CAPABILITY_KEY_PREFIX}cameraKeyManagement`, + }) + + /** + * Each service's key in the order the services are built and a camera's service map holds them. + * @private + */ + static readonly SERVICE_KEY_ORDER: readonly string[] = Object.freeze(SERVICE_PARTS.map(part => CMAFRecordingManagement.SERVICE_KEYS[part])) + + /** + * The management's services. + * @private + */ + readonly services: CMAFRecordingServices + + private readonly feed: ServedRecordings + + private readonly policy: OperatingModePolicy + + private readonly reporter: CameraReporter + + // The camera's reporter's debug events on the management's debug name, which each clip and every control point write through as well. + private readonly debug: DebugWriter + + private readonly queue = new CommandQueue() + + private readonly stack = new DisposableStack() + + // Each clip by the hub's Session ID, an ended one kept for its tail, and the timer that forgets each ended one. + private readonly clips = new Map() + + private readonly tails = new Map>() + + private readonly clipContext: ClipContext + + private identity?: Identity + + // The camera's Accessory Information, which a clip's User-Agent names. + private accessoryInformation?: AccessoryInformation + + private entry: RecordingProvisioningEntry = {} + + // The camera event queue of the identity held, built at its context from the record's sequence mark. + private events?: CameraEventQueue + + // The key a signing request asked a hub to certify, kept until its certificate arrives, another request replaces it or the identity changes. + private pendingKey?: KeyObject + + // The held certificate's end, read once as the credential is set. + private certificateEnd?: number + + // Whether the held entry lets the camera upload, read once as the entry is set. + private readiness: UploadReadiness = { kind: 'unprovisioned' } + + // When the camera last warned of a Start it refused for want of a usable Camera Key, and how many such Starts it has refused since, each cleared when + // the reason it cannot upload turns. + private refusalWarnedAt?: number + + private refusalsSinceWarning = 0 + + // The last Camera Key ID and status the characteristics carry, which means each is updated, and notified, only when it changes. + private servedKeyID?: string + + private servedNeedsUpdate?: boolean + + private destroyed = false + + /** + * 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 services - The saved services to adopt, each built new when absent. + */ + constructor(options: CMAFRecordingManagementOptions, services: Partial = {}) { + this.feed = options.feed + this.policy = options.policy + this.reporter = options.reporter + this.debug = options.reporter.writer(CMAF_RECORDING_DEBUG) + this.clipContext = { + allocate: () => this.allocate(), + debug: this.debug, + enqueue: event => this.enqueue(event), + 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, + } + this.services = { + buffer: services.buffer ?? new Service.CameraBufferManagement('', ''), + certificate: services.certificate ?? new Service.CameraClientCertificateManagement('', ''), + key: services.key ?? new Service.CameraKeyManagement('', ''), + } + + this.bind() + + // The status turns at the start of the renewal window before the certificate's end with no write to mark it: a daily check notifies it while the + // camera runs. + const check = setInterval(() => this.publish(), DAILY) + + check.unref() + this.stack.defer(() => clearInterval(check)) + this.publish() + + this.policy.subscribeDerivation('recordingPublished', (allowed) => { + if (!allowed) { + this.cancelClips() + } + }) + } + + /** + * Reconciles each service in a restored service map: each saved service under its key is adopted, and a missing one is built and inserted. + * @param serviceMap - The camera's service map, changed in place. + * @param create - Builds the management over the saved services. + * @returns Whether the map changed. + * @private + */ + static reconcile(serviceMap: ControllerServiceMap, create: (services: Partial) => CMAFRecordingManagement): boolean { + const keys = CMAFRecordingManagement.SERVICE_KEYS + const saved: Partial = { + buffer: serviceMap[keys.buffer] as CameraBufferManagement | undefined, + certificate: serviceMap[keys.certificate] as CameraClientCertificateManagement | undefined, + key: serviceMap[keys.key] as CameraKeyManagement | undefined, + } + const { services } = create(saved) + let changed = false + + for (const part of SERVICE_PARTS) { + if (saved[part] === undefined) { + serviceMap[keys[part]] = services[part] + changed = true + } + } + + return changed + } + + /** + * Takes the camera's accessory context. A context naming the identity held changes nothing; one with no username drops the package in memory, the event + * queue, every clip session and the pending key; one naming another identity drops them, loads that identity's package from the record, its clip mark + * passed by a margin, and builds its event queue. + * @param context - The camera's accessory context. + * @private + */ + handleAccessoryContext(context: ControllerAccessoryContext): void { + const { accessoryInformation, accessoryUUID, username } = context + + if (this.identity?.username === username && this.identity?.accessoryUUID === accessoryUUID) { + return + } + + if (username === undefined && this.identity === undefined) { + return + } + + // The queue goes before the clips end: their events, which no hub of the identity held will read, save no mark under it, and a context with no + // username, which an accessory's destroy hands once its data is removed, writes nothing to the record. + this.events = undefined + this.cancelClips() + this.forgetClips() + this.identity = username === undefined + ? undefined + : { accessoryUUID, username } + this.accessoryInformation = accessoryInformation + this.pendingKey = undefined + + const loaded = this.loadEntry() + + // The raised clip mark is saved with the sequence mark the event queue's build saves, before any Clip ID is answered. + this.setEntry(loaded.clipMark === undefined + ? loaded + : { ...loaded, clipMark: loaded.clipMark + CLIP_MARK_MARGIN }) + + if (this.identity !== undefined) { + this.buildEvents() + } + } + + /** + * Drops the pending key, reads the package again from the record, ends every clip, each queuing its CMAF error, and empties the event queue keeping its + * counter. A second run in the same removal finds nothing changed and changes nothing. + */ + handleFactoryReset(): void { + this.pendingKey = undefined + + // The record is read before any clip ends: the entry held while the clips end, and their events save the sequence mark, is the one the accessory + // left, an unpairing's clear among them. + this.setEntry(this.loadEntry()) + this.cancelClips() + this.events?.acknowledge(this.events.sequenceNumber) + } + + /** + * Queues a Motion event at each edge of the camera's motion sensor's Motion Detected, which carries no motion while Motion Enabled reads off. + * @param detected - Whether motion is detected. + * @private + */ + motionChanged(detected: boolean): void { + this.enqueue({ active: detected, type: CameraBufferEventType.MOTION }) + } + + // The identity's stored entry, empty without an identity, each part the record leaves out written as a debug event under the record's debug name. + private loadEntry(): RecordingProvisioningEntry { + if (this.identity === undefined) { + return {} + } + + return RecordingProvisioning.load(this.identity.username, this.identity.accessoryUUID, part => this.reporter.debug(PROVISIONING_DEBUG, 'part-unreadable', () => ({ + part, + sentence: `A stored recording provisioning entry holds an unreadable ${part}, which is left out.`, + }))) ?? {} + } + + /* Builds the identity's event queue from the record's sequence mark, sets Buffer Event Sequence Number to it at once and saves the queue's counter as the + * mark at once, which is why no number is used twice across a crash. A restored mark within two skip-aheads of 2^64 reads as absent, and the counter cannot wrap. + */ + private buildEvents(): void { + let restoredMark = this.entry.sequenceMark + + if (restoredMark !== undefined && restoredMark >= MARK_LIMIT) { + this.debug('sequence-mark-dropped', () => ({ + sentence: 'A restored event sequence mark lies within two skip-aheads of 2^64. The event queue starts as if none was stored.', + })) + restoredMark = undefined + } + + this.events = new CameraEventQueue({ reporter: this.reporter, restoredMark }) + this.services.buffer.updateCharacteristic(Characteristic.BufferEventSequenceNumber, this.events.characteristicValue) + this.saveMark() + } + + // Queues an event, sets Buffer Event Sequence Number to the queue's counter, and saves the counter as the mark once it passes the saved one by half a + // skip-ahead. + private enqueue(event: CameraBufferEventInput): void { + const events = this.events + + if (events === undefined || this.destroyed) { + return + } + + events.enqueue(event) + this.services.buffer.updateCharacteristic(Characteristic.BufferEventSequenceNumber, events.characteristicValue) + + if (events.sequenceNumber - (this.entry.sequenceMark ?? 0n) >= SKIP_AHEAD / 2n) { + this.saveMark() + } + } + + // Saves the queue's counter as the sequence mark, beside the held clip mark, into the record as it stands, and the save writes back no part of the + // package the record does not hold. The mark moves outside any write a hub makes: a save that fails is a storage-failed problem naming the failure, + // the camera serving from memory, and every later event saves again until one succeeds. + private saveMark(): void { + const identity = this.identity + + if (this.events === undefined || identity === undefined || this.destroyed) { + return + } + + const sequenceMark = this.events.sequenceNumber + + try { + RecordingProvisioning.saveMarks(identity.username, identity.accessoryUUID, { clipMark: this.entry.clipMark, sequenceMark }) + this.entry = { ...this.entry, sequenceMark } + } catch (error) { + this.storageFailed(`The camera's recording provisioning record could not be written: ${errorMessage(error)}`, error) + } + } + + // Takes the next clip number, the held clip mark plus one, saved as the mark beside the held sequence mark into the record as it stands before it is + // used, which is why no number is used again, across a crash or by another clip, and no part of the package the record does not hold is written back. It + // throws when the record cannot save it, and after the management's destroy has started. No unsaved number is used. + private allocate(): bigint { + const { accessoryUUID, username } = this.served() + const clipMark = (this.entry.clipMark ?? 0n) + 1n + + RecordingProvisioning.saveMarks(username, accessoryUUID, { clipMark, sequenceMark: this.entry.sequenceMark }) + this.entry = { ...this.entry, clipMark } + + return clipMark + } + + private async eventCommand({ command, limit, sequenceNumber }: BufferEventCommandRequest): Promise { + this.served() + + const events = this.events! + + if (command === BufferEventCommandType.QUERY) { + return { + events: events.query(sequenceNumber, limit), + } + } + + events.acknowledge(sequenceNumber) + + return { events: [] } + } + + // Hands the feed a hub's verdict on the fragment its Start names, holds each clip at a Should Not Record verdict on the fragment the feed found, and lets + // each clip read its window again. + private async activityCommand({ activity, start }: BufferActivityCommandRequest): Promise { + const record = activity === BufferActivity.SHOULD_RECORD + + this.debug('fragment-judged', () => { + const verdict = record + ? 'Should Record' + : 'Should Not Record' + + return { + sentence: `Buffer Activity Command judges the fragment at ${start} ${verdict}.`, + start: String(start), + verdict, + } + }) + + const judged = this.feed.judged(start, record) + + for (const clip of this.clips.values()) { + if (!record && judged !== undefined) { + clip.holdBefore(judged.recording, judged.index) + } + + clip.reconsider() + } + + return {} + } + + /* Buffer Upload Command, keyed by the hub's Session ID. A Start with a new Session ID opens a clip, with a paused one's resumes it, and with any other + * known one answers its Clip ID; a Stop stops the clip it names, and StartAndStop opens a clip and stops it. An ended clip's Session ID answers its Clip + * ID for the tail. + */ + private async uploadCommand(request: BufferUploadCommandRequest): Promise { + this.served() + + const { command, sessionID, start } = request + const clip = this.clips.get(sessionID) + + if (command === BufferUploadCommandType.STOP) { + const { action, place } = stopOf(request, this.debug) + + if (clip === undefined) { + this.debug('stop-refused-no-session', () => ({ sentence: 'Buffer Upload Command refuses a Stop naming no session.' })) + throw new HapStatusError(HAPStatus.RESOURCE_DOES_NOT_EXIST) + } + + clip.stopAt(place, action) + + return { clipID: clip.clipID } + } + + // The codec requires none of the optional fields, which is why a Start without its place, or a StartAndStop without its Stop, is refused before it changes anything. + if (start === undefined) { + this.debug('start-refused-no-place', () => ({ sentence: 'Buffer Upload Command refuses a Start without its place.' })) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + const bound = command === BufferUploadCommandType.START_AND_STOP + ? stopOf(request, this.debug) + : undefined + + if (clip?.state === 'paused') { + this.resume(clip, start) + } + + const opened = clip ?? this.open(sessionID, start) + + if (bound !== undefined) { + opened.stopAt(bound.place, bound.action) + } + + return { clipID: opened.clipID } + } + + /* Opens a clip at the fragment a Start names. It is refused while the camera holds no credential or no publishing point, while recording is disallowed + * or the accessory is unpublished, whatever the plugin states of the camera's source, while the camera holds no Camera Key a content key derives from, a + * refusal that also raises the problem refusalWarning states, and with no recording to draw on: a place that matches no fragment start within half a + * fragment across every recording the feed keeps, or one whose bytes are released. Its Clip ID is saved before the answer, and a save that fails opens + * and queues nothing. The clip's reader opens in this same turn as the check that found the fragment's bytes. + */ + private open(sessionID: bigint, start: bigint): ClipSession { + const { readiness } = this + + if (readiness.kind === 'unprovisioned' || !this.policy.recordingPublished()) { + this.debug('start-refused-not-ready', () => ({ + sentence: 'Buffer Upload Command refuses a Start while the camera holds no credential or no publishing point, recording is disallowed or the ' + + 'accessory is unpublished.', + })) + throw new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + // A camera that cannot encrypt a clip's video and audio refuses before any fragment is read, any clip number spent or any event queued. + if (readiness.kind !== 'ready') { + this.debug('start-refused-keyless', () => ({ + sentence: 'Buffer Upload Command refuses a Start while the camera holds no Camera Key it can encrypt a clip\'s video and audio with.', + })) + this.refusalWarning(readiness) + throw new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + const found = this.feed.fragmentAt(start, 'start') + + if (found?.fragment.bytes === undefined) { + this.debug('start-refused-no-recording', () => ({ sentence: 'Buffer Upload Command refuses a Start with no recording to draw on.' })) + throw new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + let clipID: bigint + + try { + clipID = this.allocate() + } catch (error) { + this.storageFailed(`Buffer Upload Command could not save the clip number: ${errorMessage(error)}`, error) + throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + this.enqueue({ cmafSessionID: clipID, type: CameraBufferEventType.CMAF_SESSION_START }) + + const { contentKey, credential, point } = readiness + const clip = new ClipSession({ + clipID, + context: this.clipContext, + from: found.fragment.index, + identity: { + contentKey, + credential, + point, + userAgent: this.userAgent(), + }, + recording: found.recording, + sessionID, + }) + + this.clips.set(sessionID, clip) + this.debug('clip-opened', () => ({ + clipID: String(clipID), + fragment: found.fragment.index, + sentence: `Clip ${clipID} opens at fragment ${found.fragment.index}.`, + })) + + return clip + } + + /* Raises an upload-refused problem for a Start refused for want of a Camera Key the camera can encrypt a clip with: at the first such refusal since the + * reason it cannot upload last turned, and after it only once the interval has passed on the clock since the last such problem, then naming how many + * Starts the camera has refused since that problem, this one among them. A hub that repeats a refused Start cannot flood the camera's channel or the + * console, and a camera that goes on refusing is never quiet for longer than the interval, a clock set back reading as the interval passed. Each refusal + * reads the clock itself, and no timer is armed. + */ + private refusalWarning(readiness: Extract): void { + const now = Date.now() + + this.refusalsSinceWarning++ + + if (this.refusalWarnedAt !== undefined && now >= this.refusalWarnedAt && now - this.refusalWarnedAt < REFUSAL_WARNING_INTERVAL) { + return + } + + const reason = readiness.kind === 'keyless' + ? 'the camera holds no Camera Key to encrypt its video and audio with.' + : `the camera cannot encrypt its video and audio with the Camera Key it holds: ${readiness.reason}` + const since = this.refusalWarnedAt === undefined + ? '' + : ` The camera has refused ${counted(this.refusalsSinceWarning, 'request')} for a clip since the last warning.` + + this.reporter.problem({ kind: 'upload-refused', level: 'warning', sentence: `No clip is uploaded, because ${reason}${since}` }) + this.refusalWarnedAt = now + this.refusalsSinceWarning = 0 + } + + // Resumes a paused clip at the fragment a Start names, refusing while that fragment's bytes are gone, the clip staying paused with its stop. + private resume(clip: ClipSession, start: bigint): void { + const found = this.feed.fragmentAt(start, 'start') + + if (found?.fragment.bytes === undefined) { + this.debug('resume-refused-no-recording', () => ({ sentence: 'Buffer Upload Command refuses a resume with no recording to draw on.' })) + throw new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + clip.resume(found.recording, found.fragment.index) + } + + // Ends every open or paused clip with CMAF Error CANCELED, each queuing its event as any ended clip does. + private cancelClips(): void { + for (const clip of this.clips.values()) { + clip.end(CMAFError.CANCELED) + } + } + + // Keeps an ended clip's Session ID answering its Clip ID for the tail, on an unreferenced timer. + private clipEnded({ sessionID }: ClipSession): void { + const tail = setTimeout(() => { + this.tails.delete(sessionID) + this.clips.delete(sessionID) + }, ENDED_TAIL) + + tail.unref() + this.tails.set(sessionID, tail) + } + + // Forgets every clip and releases each tail's timer. + private forgetClips(): void { + for (const tail of this.tails.values()) { + clearTimeout(tail) + } + + this.tails.clear() + this.clips.clear() + } + + // The User-Agent of a clip's requests, from the camera's Accessory Information as it reads when the clip opens. + private userAgent(): string { + const information = this.accessoryInformation + const field = (type: typeof Characteristic.Manufacturer): string => userAgentField(information?.getCharacteristic(type).value) + + return `HKSV/3.0 HAP-NodeJS/${libraryVersion()} (${field(Characteristic.Manufacturer)}; ${field(Characteristic.Model)}; ${field(Characteristic.FirmwareRevision)})` + } + + // Reports a write of the camera's recording provisioning record that failed as the camera's storage-failed problem, at the level `warning`, the sentence + // naming the failure and the thrown value carried as thrown. + private storageFailed(sentence: string, error: unknown): void { + this.reporter.problem({ + error, + kind: 'storage-failed', + level: 'warning', + sentence, + }) + } + + /** + * Releases everything the management holds, each clip ended and its upload closed; from the moment it starts the management writes nothing to the record. + */ + async destroy(): Promise { + this.destroyed = true + this.pendingKey = undefined + + const clips = [ + ...this.clips.values(), + ] + + this.cancelClips() + this.forgetClips() + this.events = undefined + this.stack.dispose() + await Promise.all(clips.map(async clip => clip.settled())) + } + + private bind(): void { + const point = this.services.buffer.getCharacteristic(Characteristic.CameraRecordingPublishingPoint) + const certificate = this.services.certificate.getCharacteristic(Characteristic.CameraClientCertificate) + const cameraKey = this.services.key.getCharacteristic(Characteristic.CameraKey) + + // The publishing point carries a hub's token in its URL, which is why it is kept out of the characteristic's value and the accessory cache, and with the Camera + // Key and the client certificate it is written, and read, by an admin alone. + point.setProps({ + adminOnlyAccess: [Access.READ, Access.WRITE], + sensitive: true, + transient: true, + }) + certificate.setProps({ + adminOnlyAccess: [Access.READ, Access.WRITE], + }) + cameraKey.setProps({ + adminOnlyAccess: [Access.WRITE], + }) + this.services.buffer.getCharacteristic(Characteristic.BufferActivityCommand).setProps({ transient: true }) + + point.onGet(() => this.entry.publishingPoint === undefined + ? '' + : encodeCameraRecordingPublishingPoint(this.entry.publishingPoint)) + certificate.onGet(() => this.entry.credential === undefined + ? '' + : encodeCameraClientCertificateRequest({ ca: this.entry.credential.ca, clientCertificate: this.entry.credential.certificate })) + this.services.key.getCharacteristic(Characteristic.CameraKeyID).onGet(() => this.publish().keyID) + this.services.certificate.getCharacteristic(Characteristic.CameraClientCertificateStatus).onGet(() => this.publish().status) + + wireControlPoint( + this.services.certificate.getCharacteristic(Characteristic.CameraClientCSR), + this.queue, + this.debug, + decodeCameraClientCSRRequest, + this.signingRequest.bind(this), + encodeCameraClientCSRResponse, + ) + wireControlPoint( + this.services.buffer.getCharacteristic(Characteristic.BufferEventCommand), + this.queue, + this.debug, + decodeBufferEventCommandRequest, + this.eventCommand.bind(this), + encodeBufferEventCommandResponse, + ) + wireControlPoint( + this.services.buffer.getCharacteristic(Characteristic.BufferUploadCommand), + this.queue, + this.debug, + decodeBufferUploadCommandRequest, + this.uploadCommand.bind(this), + encodeBufferUploadCommandResponse, + ) + wireControlPoint( + this.services.buffer.getCharacteristic(Characteristic.BufferActivityCommand), + this.queue, + this.debug, + decodeBufferActivityCommandRequest, + this.activityCommand.bind(this), + () => undefined, + ) + wireControlPoint(certificate, this.queue, this.debug, clearable(decodeCameraClientCertificateRequest), this.clientCertificate.bind(this), () => undefined) + wireControlPoint(cameraKey, this.queue, this.debug, decodeCameraKey, this.cameraKey.bind(this), () => undefined) + wireControlPoint(point, this.queue, this.debug, clearable(decodeCameraRecordingPublishingPoint), this.publishingPoint.bind(this), () => undefined) + } + + // A provisioning write is served while the management stands and knows the identity it provisions; any other is refused before it changes anything. + private served(): Identity { + if (this.destroyed || this.identity === undefined) { + throw new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + return this.identity + } + + private async signingRequest({ nonce }: CameraClientCSRRequest): Promise { + const { username } = this.served() + let request: Awaited> + + try { + request = await createSigningRequest(nonce, username) + } catch (error) { + this.debug('nonce-refused', () => ({ + message: errorMessage(error), + sentence: `Camera Client CSR refuses a nonce it cannot sign: ${errorMessage(error)}`, + })) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + this.pendingKey = request.privateKey + + return { csr: request.csr, nonceSignature: request.nonceSignature } + } + + private async clientCertificate(request: CameraClientCertificateRequest | typeof CLEAR): Promise { + this.served() + + if (request === CLEAR) { + this.save({ ...this.entry, cameraKey: undefined, credential: undefined }) + + return {} + } + + const privateKey = this.pendingKey + + try { + const certificate = new X509Certificate(request.clientCertificate) + const ca = new X509Certificate(request.ca) + + if (privateKey === undefined || !certificate.checkPrivateKey(privateKey) || !certificate.verify(ca.publicKey)) { + throw new Error('The certificate does not certify the pending key under its CA.') + } + } catch (error) { + this.debug('certificate-refused', () => ({ + message: errorMessage(error), + sentence: `Camera Client Certificate refuses a certificate: ${errorMessage(error)}`, + })) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + this.save({ + ...this.entry, + credential: { ca: request.ca, certificate: request.clientCertificate, privateKey }, + }) + this.pendingKey = undefined + + return {} + } + + private async cameraKey(cameraKey: CameraKeyPayload): Promise { + this.served() + this.save({ ...this.entry, cameraKey }) + + return {} + } + + private async publishingPoint(point: CameraRecordingPublishingPointPayload | typeof CLEAR): Promise { + this.served() + + if (point === CLEAR) { + this.save({ ...this.entry, publishingPoint: undefined }) + + return {} + } + + try { + parsePublishingPointURL(point.url) + } catch (error) { + this.debug('point-refused', () => ({ + message: errorMessage(error), + sentence: `Camera Recording Publishing Point refuses a point: ${errorMessage(error)}`, + })) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + if (point.serverCACertificates.length === 0) { + this.debug('point-refused-no-server-ca', () => ({ sentence: 'Camera Recording Publishing Point refuses a point with no server CA.' })) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + this.save({ ...this.entry, publishingPoint: point }) + + return {} + } + + // Saves the whole entry, its marks with it, and takes it as the one held once the record has it. A save that fails leaves the entry held as it was and + // answers the write with a failure the hub repeats; a save that would leave the record as it is writes nothing. + private save(entry: RecordingProvisioningEntry): void { + const { accessoryUUID, username } = this.served() + + try { + RecordingProvisioning.save(username, accessoryUUID, entry) + } catch (error) { + this.storageFailed(`The recording provisioning record could not be saved: ${errorMessage(error)}`, error) + throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + this.setEntry(entry) + } + + // Takes an entry as the one held: the certificate's end read, whether the camera can upload read, the feed holding while it can, which is what + // provisioned for uploads means, and the characteristics published. The refusal warning's state is cleared only when the reason the camera cannot upload + // turns: a write that leaves it refusing for the same reason, a hub writing the same key again among them, brings no warning sooner than the interval. + private setEntry(entry: RecordingProvisioningEntry): void { + const previous = this.readiness + + this.entry = entry + this.certificateEnd = undefined + this.readiness = readinessOf(entry) + + if (previous.kind !== this.readiness.kind || (previous.kind === 'unusable' && this.readiness.kind === 'unusable' && previous.reason !== this.readiness.reason)) { + this.refusalWarnedAt = undefined + this.refusalsSinceWarning = 0 + } + + this.feed.holding = this.readiness.kind === 'ready' + + if (entry.credential !== undefined) { + try { + this.certificateEnd = new X509Certificate(entry.credential.certificate).validToDate.getTime() + } catch { + // A stored certificate that does not parse has no end, and the status reads Needs Update until a hub writes another. + this.certificateEnd = Number.NEGATIVE_INFINITY + } + } + + this.publish() + } + + // Computes Camera Key ID and the status from the entry and the clock, and updates each characteristic only when its value turns, which notifies it. + private publish(): { keyID: string, status: string } { + const keyID = this.entry.cameraKey === undefined + ? '' + : encodeCameraKeyID({ keyID: this.entry.cameraKey.keyNumber }) + const needsUpdate = !isWhole(this.entry) || (this.certificateEnd ?? 0) - RENEWAL_WINDOW <= Date.now() + const status = encodeCameraClientCertificateStatus({ needsUpdate }) + + if (this.destroyed) { + return { keyID, status } + } + + if (keyID !== this.servedKeyID) { + this.servedKeyID = keyID + this.services.key.updateCharacteristic(Characteristic.CameraKeyID, keyID) + } + + if (needsUpdate !== this.servedNeedsUpdate) { + this.servedNeedsUpdate = needsUpdate + this.services.certificate.updateCharacteristic(Characteristic.CameraClientCertificateStatus, status) + } + + return { keyID, status } + } +} + +// A command's Stop and what it does there, refusing a command that lacks its place or its action as malformed, its debug event through the writer given. +function stopOf({ stop, stopAction }: BufferUploadCommandRequest, debug: DebugWriter): { action: BufferUploadStopAction, place: bigint } { + if (stop === undefined || stopAction === undefined) { + debug('stop-refused-no-place', () => ({ sentence: 'Buffer Upload Command refuses a Stop without its place and its action.' })) + throw new HapStatusError(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + return { action: stopAction, place: stop } +} + +// A decoder that reads a write of no bytes as the hub's clear, and every other write through the codec. +function clearable(decode: (value: string) => Request): (value: string) => Request | typeof CLEAR { + return value => value === '' + ? CLEAR + : decode(value) +} diff --git a/src/lib/camera/recording/CameraEventQueue.spec.ts b/src/lib/camera/recording/CameraEventQueue.spec.ts new file mode 100644 index 000000000..95793c0d8 --- /dev/null +++ b/src/lib/camera/recording/CameraEventQueue.spec.ts @@ -0,0 +1,159 @@ +import type { CameraBufferEvent } from '../capabilities/cameraBuffer.js' + +import { describe, expect, it } from 'vitest' + +import { detachedReporter } from '../../../test-utils/reporterFixtures.js' +import { CameraBufferEventType, CMAFError } from '../capabilities/cameraBuffer.js' +import { CameraEventQueue, SKIP_AHEAD } from './CameraEventQueue.js' + +const MOTION = { active: true, type: CameraBufferEventType.MOTION } as const + +// The reporter of no camera every queue of the spec writes its debug events through. +const reporter = detachedReporter() + +function numbers(events: CameraBufferEvent[]): bigint[] { + return events.map(event => event.sequenceNumber) +} + +function errors(events: CameraBufferEvent[]): CameraBufferEvent[] { + return events.filter(event => event.type === CameraBufferEventType.CMAF_ERROR) +} + +describe('cameraEventQueue', () => { + it('starts empty at sequence number 0', () => { + const queue = new CameraEventQueue({ reporter }) + + expect(queue.sequenceNumber).toBe(0n) + expect(queue.characteristicValue).toBe(0) + expect(queue.query(0n)).toEqual([]) + }) + + it('numbers events and answers queries inclusively, limited and repeated, removing nothing', () => { + const queue = new CameraEventQueue({ reporter }) + + expect(queue.enqueue(MOTION)).toBe(1n) + expect(queue.enqueue({ active: false, type: CameraBufferEventType.MOTION })).toBe(2n) + expect(queue.characteristicValue).toBe(2) + expect(numbers(queue.query(1n))).toEqual([1n, 2n]) + expect(numbers(queue.query(2n))).toEqual([2n]) + expect(numbers(queue.query(1n, 1n))).toEqual([1n]) + expect(numbers(queue.query(1n, 0n))).toEqual([1n, 2n]) + expect(numbers(queue.query(1n))).toEqual([1n, 2n]) + expect(queue.query(1n)[1]).toEqual({ active: false, sequenceNumber: 2n, type: CameraBufferEventType.MOTION }) + expect(queue.query(1n).every(event => Object.isFrozen(event))).toBe(true) + }) + + it('removes the events an acknowledgement covers and keeps counting', () => { + const queue = new CameraEventQueue({ reporter }) + + queue.enqueue(MOTION) + queue.enqueue(MOTION) + queue.acknowledge(1n) + + expect(numbers(queue.query(0n))).toEqual([2n]) + + queue.acknowledge(9n) + + expect(queue.query(0n)).toEqual([]) + expect(queue.enqueue(MOTION)).toBe(3n) + }) + + it('starts past a restored mark by the skip-ahead margin', () => { + const queue = new CameraEventQueue({ reporter, restoredMark: 10n }) + + expect(queue.sequenceNumber).toBe(10n + SKIP_AHEAD) + expect(queue.enqueue(MOTION)).toBe(11n + SKIP_AHEAD) + }) + + it('keeps the order of events across the characteristic\'s wrap', () => { + const queue = new CameraEventQueue({ reporter, restoredMark: 2n ** 32n - 2n - SKIP_AHEAD }) + const shown: number[] = [] + const numbered: bigint[] = [] + + for (let index = 0; index < 4; index++) { + numbered.push(queue.enqueue(MOTION)) + shown.push(queue.characteristicValue) + } + + expect(numbered).toEqual([ + 2n ** 32n - 1n, + 2n ** 32n, + 2n ** 32n + 1n, + 2n ** 32n + 2n, + ]) + expect(shown).toEqual([4294967295, 0, 1, 2]) + expect(numbers(queue.query(1n))).toEqual([2n ** 32n + 1n, 2n ** 32n + 2n]) + expect(numbers(queue.query(4294967295n))).toEqual(numbered) + expect(queue.query(5n)).toEqual([]) + + queue.acknowledge(0n) + + expect(numbers(queue.query(0n))).toEqual([2n ** 32n + 1n, 2n ** 32n + 2n]) + expect(numbers(queue.query(2n ** 32n + 2n))).toEqual([2n ** 32n + 2n]) + }) + + it('drops the oldest events on overflow and surfaces each episode as one Out of Resources error', () => { + const queue = new CameraEventQueue({ capacity: 3, reporter }) + + queue.enqueue(MOTION) + queue.enqueue(MOTION) + queue.enqueue(MOTION) + + expect(queue.enqueue(MOTION)).toBe(5n) + expect(numbers(queue.query(0n))).toEqual([3n, 4n, 5n]) + expect(queue.query(0n)[1]).toEqual({ + cmafError: CMAFError.OUT_OF_RESOURCES, + cmafSessionID: 0n, + sequenceNumber: 4n, + type: CameraBufferEventType.CMAF_ERROR, + }) + expect(queue.enqueue(MOTION)).toBe(6n) + expect(numbers(queue.query(0n))).toEqual([4n, 5n, 6n]) + expect(errors(queue.query(0n))).toHaveLength(1) + + queue.acknowledge(4n) + + expect(queue.enqueue(MOTION)).toBe(7n) + expect(numbers(queue.query(0n))).toEqual([5n, 6n, 7n]) + expect(errors(queue.query(0n))).toEqual([]) + expect(queue.enqueue(MOTION)).toBe(9n) + expect(numbers(queue.query(0n))).toEqual([7n, 8n, 9n]) + expect(numbers(errors(queue.query(0n)))).toEqual([8n]) + }) + + it('keeps an episode\'s error through every later drop while its episode is open', () => { + const queue = new CameraEventQueue({ capacity: 3, reporter }) + + for (let index = 0; index < 5; index++) { + queue.enqueue(MOTION) + } + + expect(queue.enqueue(MOTION)).toBe(7n) + expect(numbers(queue.query(0n))).toEqual([4n, 6n, 7n]) + expect(numbers(errors(queue.query(0n)))).toEqual([4n]) + }) + + it('closes an episode at an acknowledgement short of its error, and the next overflow opens another', () => { + const queue = new CameraEventQueue({ capacity: 3, reporter }) + + for (let index = 0; index < 4; index++) { + queue.enqueue(MOTION) + } + + expect(numbers(queue.query(0n))).toEqual([3n, 4n, 5n]) + expect(numbers(errors(queue.query(0n)))).toEqual([4n]) + + queue.acknowledge(3n) + queue.enqueue(MOTION) + queue.enqueue(MOTION) + + expect(numbers(queue.query(0n))).toEqual([6n, 7n, 8n]) + expect(numbers(errors(queue.query(0n)))).toEqual([7n]) + }) + + it('refuses a capacity of 1, a fractional capacity and a negative restored mark', () => { + expect(() => new CameraEventQueue({ capacity: 1, reporter })).toThrow(RangeError) + expect(() => new CameraEventQueue({ capacity: 2.5, reporter })).toThrow(RangeError) + expect(() => new CameraEventQueue({ reporter, restoredMark: -1n })).toThrow(RangeError) + }) +}) diff --git a/src/lib/camera/recording/CameraEventQueue.ts b/src/lib/camera/recording/CameraEventQueue.ts new file mode 100644 index 000000000..9205c6c87 --- /dev/null +++ b/src/lib/camera/recording/CameraEventQueue.ts @@ -0,0 +1,182 @@ +import type { CameraBufferEvent } from '../capabilities/cameraBuffer.js' +import type { CameraReporter } from '../diagnostics/CameraReporter.js' + +import { CameraBufferEventType, CMAFError } from '../capabilities/cameraBuffer.js' +import { debugChannel } from '../diagnostics/debugChannels.js' + +const RECORDING_DEBUG = debugChannel('HAP-NodeJS:Camera:Recording') + +/** + * The most events the queue holds before it drops the oldest. + */ +export const EVENT_QUEUE_CAPACITY = 256 + +/** + * How far past a restored high-water mark the counter starts, which is why a crash between saves of the mark never reuses a sequence number. + */ +export const SKIP_AHEAD = 2n ** 16n + +// The serial-number space of Buffer Event Sequence Number, a uint32 characteristic. +const CHARACTERISTIC_BITS = 32 +const CHARACTERISTIC_RANGE = 2n ** 32n + +// Each member of a union with its sequence number left out. An input keeps the union's tag on the event's type. +type WithoutSequenceNumber = Event extends unknown ? Omit : never + +/** + * An event as it is handed to the queue, which numbers it. + */ +export type CameraBufferEventInput = WithoutSequenceNumber + +/** + * The camera event queue: in memory, bounded, and delivered at least once. One bigint counter numbers every event, the uint32 characteristic shows its low 32 + * bits, and a sequence number read from the characteristic is lifted back to the counter's range by serial-number arithmetic. A wrap never reorders + * events. A query never removes an event, only an acknowledgement covering its number does, and a query is inclusive, because a hub deduplicates by sequence + * number and a duplicate is always preferred over a loss. + * + * When the queue is full it drops the oldest events and surfaces the loss as one Out of Resources CMAF error per overflow episode, kept while its + * episode is open, rather than a problem: a hub may never read the queue, and overflow is a working camera's normal state. The queue does no storage + * and no notification: its owner persists {@link sequenceNumber} as the high-water mark, hands it back as the restored mark, and notifies the + * characteristic with {@link characteristicValue}. + */ +export class CameraEventQueue { + private readonly capacity: number + + private readonly reporter: CameraReporter + + private counter: bigint + + // The queued events in ascending sequence order, each frozen when it is numbered. + private readonly events: CameraBufferEvent[] = [] + + // The open overflow episode's error event, which no later drop removes, or undefined when no episode is open. + private episodeError?: CameraBufferEvent + + /** + * @param options - The queue's capacity, {@link EVENT_QUEUE_CAPACITY} by default, its camera's reporter, and the high-water mark its owner restored, if any. + * @param options.capacity - The most events the queue holds, an integer of at least 2. + * @param options.reporter - The camera's reporter, through which an overflow writes its debug event. + * @param options.restoredMark - The counter's last persisted value. + */ + constructor({ capacity = EVENT_QUEUE_CAPACITY, reporter, restoredMark }: { capacity?: number, reporter: CameraReporter, restoredMark?: bigint }) { + // An overflow keeps room for its error event and the event that caused it. + if (!Number.isInteger(capacity) || capacity < 2) { + throw new RangeError(`The camera event queue's capacity must be an integer of at least 2, got ${capacity}.`) + } + + if (restoredMark !== undefined && restoredMark < 0n) { + throw new RangeError(`The camera event queue's restored mark must not be negative, got ${restoredMark}.`) + } + + this.capacity = capacity + this.reporter = reporter + this.counter = restoredMark === undefined + ? 0n + : restoredMark + SKIP_AHEAD + } + + /** + * The sequence number of the latest event, the high-water mark the queue's owner persists. + */ + get sequenceNumber(): bigint { + return this.counter + } + + /** + * The value of Buffer Event Sequence Number: the counter's low 32 bits. + */ + get characteristicValue(): number { + return Number(BigInt.asUintN(CHARACTERISTIC_BITS, this.counter)) + } + + /** + * Numbers an event and queues it, dropping the oldest events when the queue is full. + * @param event - The event. + * @returns The event's sequence number. + */ + enqueue(event: CameraBufferEventInput): bigint { + if (this.events.length >= this.capacity) { + this.overflow() + } + + return this.store(event).sequenceNumber + } + + /** + * The queued events numbered at or after a sequence number, in order. Nothing is removed. + * @param sequenceNumber - The first sequence number wanted, as read from the event TLVs or the characteristic. + * @param limit - The most events answered, or 0 for every one. + * @returns The events, each frozen. + */ + query(sequenceNumber: bigint, limit = 0n): CameraBufferEvent[] { + const from = this.lift(sequenceNumber) + const found = this.events.filter(event => event.sequenceNumber >= from) + + return limit > 0n && limit < BigInt(found.length) + ? found.slice(0, Number(limit)) + : found + } + + /** + * Removes the queued events numbered at or before a sequence number, which closes an open overflow episode once the queue has room again. + * @param sequenceNumber - The last sequence number acknowledged. + */ + acknowledge(sequenceNumber: bigint): void { + const through = this.lift(sequenceNumber) + const kept = this.events.findIndex(event => event.sequenceNumber > through) + + this.events.splice(0, kept === -1 + ? this.events.length + : kept) + + if (this.episodeError !== undefined && this.events.length < this.capacity) { + this.episodeError = undefined + } + } + + // Makes room for one more event in a full queue. An episode opens by dropping the oldest events until there is room for its error event and the event + // that overflowed, and queuing the error; within an open episode the oldest event other than that error drops. + private overflow(): void { + if (this.episodeError !== undefined) { + this.events.splice(this.events[0] === this.episodeError + ? 1 + : 0, 1) + + return + } + + const dropped = this.events.length - (this.capacity - 2) + + this.events.splice(0, dropped) + this.episodeError = this.store({ cmafError: CMAFError.OUT_OF_RESOURCES, cmafSessionID: 0n, type: CameraBufferEventType.CMAF_ERROR }) + this.reporter.debug(RECORDING_DEBUG, 'queue-overflowed', () => { + const sequenceNumber = String(this.counter) + + return { + dropped, + sentence: `The camera event queue was full: it dropped its ${dropped} oldest events and queued Out of Resources as event ${sequenceNumber}.`, + sequenceNumber, + } + }) + } + + private store(event: CameraBufferEventInput): CameraBufferEvent { + this.counter++ + + const numbered = Object.freeze({ ...event, sequenceNumber: this.counter } as CameraBufferEvent) + + this.events.push(numbered) + + return numbered + } + + // The full sequence number a value names. A value of 2^32 or more is a full number already, and below 2^32 on a counter that has not wrapped it is one + // too; otherwise it is the characteristic's low 32 bits, read as the number nearest the counter with those bits, RFC 1982 serial arithmetic. + private lift(sequenceNumber: bigint): bigint { + if (sequenceNumber >= CHARACTERISTIC_RANGE || this.counter < CHARACTERISTIC_RANGE) { + return sequenceNumber + } + + return this.counter + BigInt.asIntN(CHARACTERISTIC_BITS, sequenceNumber - BigInt.asUintN(CHARACTERISTIC_BITS, this.counter)) + } +} diff --git a/src/lib/camera/recording/IngestSession.spec.ts b/src/lib/camera/recording/IngestSession.spec.ts new file mode 100644 index 000000000..e781ce417 --- /dev/null +++ b/src/lib/camera/recording/IngestSession.spec.ts @@ -0,0 +1,756 @@ +import type { ClientHttp2Session, SecureClientSessionOptions } from 'node:http2' +import type { AddressInfo, Socket } from 'node:net' + +import type { IngestSessionOptions } from './IngestSession.js' + +import { Buffer } from 'node:buffer' +import { createPrivateKey, X509Certificate } from 'node:crypto' +import { getEventListeners } from 'node:events' +import http2 from 'node:http2' +import net from 'node:net' +import process from 'node:process' +import { setTimeout as delay } from 'node:timers/promises' + +import { describe, expect, it, vi } from 'vitest' + +import { INGEST_CERTIFICATES, MockIngestServer } from '../../../test-utils/MockIngestServer.js' +import { detachedReporter } from '../../../test-utils/reporterFixtures.js' +import { CMAFError } from '../capabilities/cameraBuffer.js' +import { IngestError, IngestSession } from './IngestSession.js' + +const PLAYLIST = 'session_1/index.m3u8' +const PLAYLIST_TYPE = 'application/vnd.apple.mpegurl' +const SEGMENT_TYPE = 'video/iso.segment' +const BODY = Buffer.from('#EXTM3U\n#EXT-X-VERSION:7\n') +const USER_AGENT = 'HKSV/3.0 HAP-NodeJS-Test (HAP-NodeJS; Test Camera; 1.0.0)' + +// Each option an ingest session refuses before it connects, by what is wrong with it. +const REFUSED_OPTIONS: Record> = { + 'a URL that does not parse': { url: 'publishing point' }, + 'a URL that is not https': { url: 'http://localhost/point/' }, + 'a URL without a trailing slash': { url: 'https://localhost/point' }, + 'a URL with a query': { url: 'https://localhost/point/?token=1' }, + 'a URL with a fragment': { url: 'https://localhost/point/#token' }, + 'a URL with credentials': { url: 'https://user:secret@localhost/point/' }, + 'no server CA': { serverCAs: [] }, + 'an empty user agent': { userAgent: '' }, + 'a window of 0': { window: 0 }, + 'a fractional window': { window: 1.5 }, + 'a connect timeout of 0': { connectTimeout: 0 }, + 'a negative response timeout': { responseTimeout: -1 }, +} + +function der(pem: string): Buffer { + return new X509Certificate(pem).raw +} + +function sessionOptions(url: string, overrides: Partial = {}): IngestSessionOptions { + return { + clientCA: der(INGEST_CERTIFICATES.hubCA), + clientCertificate: der(INGEST_CERTIFICATES.clientCertificate), + privateKey: createPrivateKey(INGEST_CERTIFICATES.clientKey), + reporter: detachedReporter(), + serverCAs: [ + der(INGEST_CERTIFICATES.serverCA), + ], + url, + userAgent: USER_AGENT, + ...overrides, + } +} + +// The error a promise rejects with, which a row then reads field by field. +async function rejectionOf(pending: Promise): Promise { + return pending.then(() => undefined, (error: unknown) => error) +} + +// A TCP listener that accepts connections and never speaks: a TLS handshake against it waits forever. +async function silentListener(): Promise { + const sockets = new Set() + const server = net.createServer((socket) => { + sockets.add(socket) + socket.on('close', () => sockets.delete(socket)) + }) + + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + + return { + async [Symbol.asyncDispose]() { + for (const socket of sockets) { + socket.destroy() + } + + await new Promise(resolve => server.close(() => resolve())) + }, + port: (server.address() as AddressInfo).port, + } +} + +// A loopback port nothing listens on: one the system handed out and that was closed again. +async function closedPort(): Promise { + const server = net.createServer() + + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + + const { port } = server.address() as AddressInfo + + await new Promise(resolve => server.close(() => resolve())) + + return port +} + +describe('ingestSession', () => { + describe('uploads', () => { + it('puts an object beneath the publishing point with its type, length and user agent', async () => { + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + await session.finish() + + expect(mock.requests).toHaveLength(1) + expect(mock.requests[0].method).toBe('PUT') + expect(mock.requests[0].path).toBe('/point/session_1/index.m3u8') + expect(mock.requests[0].headers['content-type']).toBe(PLAYLIST_TYPE) + expect(mock.requests[0].headers['content-length']).toBe(String(BODY.length)) + expect(mock.requests[0].headers['user-agent']).toBe(USER_AGENT) + expect(mock.requests[0].body).toEqual(BODY) + }) + + it('sends the next object of a window of one only after the publishing point answered the last', async () => { + const DELAY = 100 + const order: string[] = [] + + await using mock = await MockIngestServer.start({ + answer: (request) => { + order.push(`received ${request.path}`) + + if (request.path.endsWith('first.m4s')) { + // The mock answers on a timer of the same delay set just after this one: the marker runs immediately before the answer is sent. + setTimeout(() => order.push('answered first'), DELAY) + + return { delay: DELAY, status: 201 } + } + + return { status: 201 } + }, + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put('clip/first.m4s', SEGMENT_TYPE, BODY) + await session.put('clip/second.m4s', SEGMENT_TYPE, BODY).then(() => order.push('second put resolved')) + await session.finish() + + expect(order.slice(0, 2)).toEqual(['received /point/clip/first.m4s', 'answered first']) + expect(order.slice(2).sort()).toEqual(['received /point/clip/second.m4s', 'second put resolved']) + }) + + it('sends the next object of a window of two while the last one\'s answer is held', async () => { + await using mock = await MockIngestServer.start({ + answer: (request) => { + if (request.path.endsWith('first.m4s')) { + return { hold: true } + } + + return { status: 201 } + }, + }) + await using session = await IngestSession.open(sessionOptions(mock.url, { window: 2 })) + + await session.put('clip/first.m4s', SEGMENT_TYPE, BODY) + await session.put('clip/second.m4s', SEGMENT_TYPE, BODY) + + await vi.waitFor(() => expect(mock.requests).toHaveLength(2)) + expect(mock.requests.map(request => request.path)).toEqual(['/point/clip/first.m4s', '/point/clip/second.m4s']) + }) + + it('completes a slow but moving upload that lasts well past its response bound', async () => { + const RESPONSE_TIMEOUT = 500 + const segment = Buffer.alloc(1024 * 1024, 0x2A) + + await using mock = await MockIngestServer.start({ drainDelay: 20 }) + await using session = await IngestSession.open(sessionOptions(mock.url, { responseTimeout: RESPONSE_TIMEOUT })) + + const started = performance.now() + + await session.put('clip/segment_1.m4s', SEGMENT_TYPE, segment) + await session.finish() + + expect(performance.now() - started).toBeGreaterThan(2 * RESPONSE_TIMEOUT) + expect(mock.requests[0].body).toEqual(segment) + }) + + it('gives back the slot of a request refused as it is made, and the next object is sent', async () => { + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url)) + + // A content type given as an array is a header HTTP/2 refuses as the request is made. + const refused = await rejectionOf(session.put('clip/first.m4s', [SEGMENT_TYPE, PLAYLIST_TYPE] as unknown as string, BODY)) + + expect(refused).toBeInstanceOf(Error) + + await session.put('clip/second.m4s', SEGMENT_TYPE, BODY) + await session.finish() + + expect(mock.requests.map(request => request.path)).toEqual(['/point/clip/second.m4s']) + }) + + it('sends an object\'s extra headers on its request alone, beside the session\'s own, which they do not replace', async () => { + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put('clip/segment_1001.m4s', SEGMENT_TYPE, BODY, { + 'user-agent': 'Another Agent', + 'x-extinf-duration': '4.00000', + }) + await session.put('clip/segment_1002.m4s', SEGMENT_TYPE, BODY) + await session.finish() + + expect(mock.requests.map(({ headers }) => headers['x-extinf-duration'])).toEqual(['4.00000', undefined]) + + for (const { headers } of mock.requests) { + expect(headers['content-type']).toBe(SEGMENT_TYPE) + expect(headers['content-length']).toBe(String(BODY.length)) + expect(headers['user-agent']).toBe(USER_AGENT) + } + }) + }) + + describe('trust', () => { + it('refuses a publishing point under a CA the hub did not name', async () => { + await using mock = await MockIngestServer.start() + + const error = await rejectionOf(IngestSession.open(sessionOptions(mock.url, { + serverCAs: [ + der(INGEST_CERTIFICATES.strangerCA), + ], + }))) + + expect(error).toBeInstanceOf(IngestError) + expect((error as IngestError).cmafError).toBe(CMAFError.CERT_CONNECTION_FAILURE) + }) + + it('refuses a publishing point whose certificate does not name the host connected to', async () => { + await using mock = await MockIngestServer.start() + + const error = await rejectionOf(IngestSession.open(sessionOptions(mock.url.replace('localhost', '127.0.0.1')))) + + expect(error).toBeInstanceOf(IngestError) + expect((error as IngestError).cmafError).toBe(CMAFError.CERT_CONNECTION_FAILURE) + }) + + it('fails on a publishing point that refuses the client certificate, and succeeds where none is required', async () => { + await using refusing = await MockIngestServer.start({ clientCAs: INGEST_CERTIFICATES.strangerCA }) + await using lenient = await MockIngestServer.start({ clientCAs: INGEST_CERTIFICATES.strangerCA, requireClientCertificate: false }) + + // TLS 1.3 finishes client authentication after the session connects. The refusal reaches the first request, as an alert or a reset the + // platform chooses between. + const error = await rejectionOf((async () => { + await using session = await IngestSession.open(sessionOptions(refusing.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + await session.finish() + })()) + + expect(error).toBeInstanceOf(IngestError) + expect([CMAFError.CERT_CONNECTION_FAILURE, CMAFError.CONNECTION_FAILED]).toContain((error as IngestError).cmafError) + + await using session = await IngestSession.open(sessionOptions(lenient.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + await session.finish() + + expect(lenient.requests).toHaveLength(1) + }) + + it('trusts exactly the CAs the hub named, in their order, with nothing that changes how the chain is verified', async () => { + const serverCAs = [ + der(INGEST_CERTIFICATES.serverCA), + der(INGEST_CERTIFICATES.strangerCA), + ] + const connect = vi.spyOn(http2, 'connect') + + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url, { serverCAs })) + + const options = connect.mock.calls[0][1] as SecureClientSessionOptions + + connect.mockRestore() + + expect(options.ca).toEqual([ + new X509Certificate(INGEST_CERTIFICATES.serverCA).toString(), + new X509Certificate(INGEST_CERTIFICATES.strangerCA).toString(), + ]) + expect(options).not.toHaveProperty('rejectUnauthorized') + expect(options).not.toHaveProperty('checkServerIdentity') + expect(options).not.toHaveProperty('secureContext') + + await session.finish() + }) + }) + + describe('answers', () => { + it.each([ + [400, CMAFError.HTTP_BAD_REQUEST], + [401, CMAFError.HTTP_INVALID_TOKEN], + [403, CMAFError.HTTP_BLOCKED], + [404, CMAFError.HTTP_NOT_FOUND], + [415, CMAFError.HTTP_UNSUPPORTED_MEDIA_TYPE], + [429, CMAFError.REQUIRES_RETRY], + [418, CMAFError.HTTP_BAD_REQUEST], + [500, CMAFError.HTTP_INTERNAL_SERVER_ERROR], + [502, CMAFError.HTTP_SERVICE_UNAVAILABLE], + [503, CMAFError.HTTP_SERVICE_UNAVAILABLE], + [504, CMAFError.HTTP_SERVICE_UNAVAILABLE], + [599, CMAFError.HTTP_INTERNAL_SERVER_ERROR], + ])('maps an answer of %i to CMAF error %i', async (status, cmafError) => { + await using mock = await MockIngestServer.start({ + answer: () => ({ status }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + + const error = await rejectionOf(session.finish()) + + expect(error).toBeInstanceOf(IngestError) + expect((error as IngestError).cmafError).toBe(cmafError) + expect((error as IngestError).status).toBe(status) + }) + + it('never follows a redirect', async () => { + await using elsewhere = await MockIngestServer.start() + await using mock = await MockIngestServer.start({ + answer: () => ({ location: `${elsewhere.url}${PLAYLIST}`, status: 307 }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + + const error = await rejectionOf(session.finish()) + + expect((error as IngestError).cmafError).toBe(CMAFError.UNKNOWN) + expect((error as IngestError).status).toBe(307) + expect(elsewhere.requests).toEqual([]) + }) + + it('keeps the first 4 KiB of a refusal\'s body', async () => { + await using mock = await MockIngestServer.start({ + answer: () => ({ + body: 'x'.repeat(10000), + status: 400, + }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + + const error = await rejectionOf(session.finish()) + + expect((error as IngestError).body).toBe('x'.repeat(4096)) + }) + + it('asks for a retry when the publishing point refuses the stream', async () => { + await using mock = await MockIngestServer.start({ + answer: () => ({ reset: http2.constants.NGHTTP2_REFUSED_STREAM }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + + const error = await rejectionOf(session.finish()) + + expect((error as IngestError).cmafError).toBe(CMAFError.REQUIRES_RETRY) + }) + + it('fails the connection when the publishing point sends GOAWAY while an answer is held', async () => { + await using mock = await MockIngestServer.start({ + answer: () => ({ hold: true }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + await vi.waitFor(() => expect(mock.requests).toHaveLength(1)) + mock.goaway() + + const error = await rejectionOf(session.finish()) + + expect((error as IngestError).cmafError).toBe(CMAFError.CONNECTION_FAILED) + }) + + it('finishes a session the publishing point ends with GOAWAY once every object is answered, and fails a later put', async () => { + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url)) + + const object = await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + + await expect(object.answer).resolves.toBe(201) + mock.goaway() + + // The mock keeps its side of a session the client closed, and the client's held failure is what says the GOAWAY arrived. + await vi.waitFor(() => { + // @ts-expect-error: private access + expect(session.failure).toBeDefined() + }) + + const failure = await rejectionOf(session.put('clip/segment_1001.m4s', SEGMENT_TYPE, BODY)) + + expect((failure as IngestError).cmafError).toBe(CMAFError.CONNECTION_FAILED) + await expect(session.finish()).resolves.toBeUndefined() + expect(mock.requests).toHaveLength(1) + }) + + it('never reads a GOAWAY with an answer held as an idle end, which means finish called once it arrived still rejects', async () => { + await using mock = await MockIngestServer.start({ + answer: () => ({ hold: true }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + const object = await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + + await vi.waitFor(() => expect(mock.requests).toHaveLength(1)) + mock.goaway() + await vi.waitFor(() => { + // @ts-expect-error: private access + expect(session.failure).toBeDefined() + }) + + await expect(object.answer).resolves.toBeUndefined() + expect((await rejectionOf(session.finish()) as IngestError).cmafError).toBe(CMAFError.CONNECTION_FAILED) + }) + + it('never reads a cancel by the caller\'s signal or by disposal as an idle end, which means finish rejects after either', async () => { + await using mock = await MockIngestServer.start() + const controller = new AbortController() + await using signaled = await IngestSession.open(sessionOptions(mock.url, { signal: controller.signal })) + + await (await signaled.put(PLAYLIST, PLAYLIST_TYPE, BODY)).answer + controller.abort() + + expect((await rejectionOf(signaled.finish()) as IngestError).cmafError).toBe(CMAFError.CANCELED) + + const disposed = await IngestSession.open(sessionOptions(mock.url)) + + await (await disposed.put(PLAYLIST, PLAYLIST_TYPE, BODY)).answer + await disposed[Symbol.asyncDispose]() + + expect((await rejectionOf(disposed.finish()) as IngestError).cmafError).toBe(CMAFError.CANCELED) + }) + + it('holds the first failure and hands it to every later call without sending again', async () => { + await using mock = await MockIngestServer.start({ + answer: () => ({ status: 400 }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put('clip/first.m4s', SEGMENT_TYPE, BODY) + + const failure = await rejectionOf(session.put('clip/second.m4s', SEGMENT_TYPE, BODY)) + + expect((failure as IngestError).cmafError).toBe(CMAFError.HTTP_BAD_REQUEST) + await expect(session.put('clip/third.m4s', SEGMENT_TYPE, BODY)).rejects.toBe(failure) + await expect(session.finish()).rejects.toBe(failure) + expect(mock.requests.map(request => request.path)).toEqual(['/point/clip/first.m4s']) + }) + + it.each([201, 208])('answers an object the publishing point answered %i with that status', async (status) => { + await using mock = await MockIngestServer.start({ + answer: () => ({ status }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + const object = await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + + await expect(object.answer).resolves.toBe(status) + await session.finish() + }) + + it('answers none for an object held when the session fails and for the object that failed it, rejecting nothing unhandled', async () => { + const unhandled: unknown[] = [] + const onUnhandled = (reason: unknown): void => { + unhandled.push(reason) + } + + process.on('unhandledRejection', onUnhandled) + + try { + await using mock = await MockIngestServer.start({ + answer: request => request.path.endsWith('first.m4s') + ? { hold: true } + : { status: 400 }, + }) + await using session = await IngestSession.open(sessionOptions(mock.url, { window: 2 })) + + const first = await session.put('clip/first.m4s', SEGMENT_TYPE, BODY) + const second = await session.put('clip/second.m4s', SEGMENT_TYPE, BODY) + + await expect(second.answer).resolves.toBeUndefined() + await expect(first.answer).resolves.toBeUndefined() + expect((await rejectionOf(session.finish()) as IngestError).cmafError).toBe(CMAFError.HTTP_BAD_REQUEST) + + // A held answer no caller reads, ended by the session's disposal. + await using held = await MockIngestServer.start({ + answer: () => ({ hold: true }), + }) + const disposed = await IngestSession.open(sessionOptions(held.url)) + + await disposed.put(PLAYLIST, PLAYLIST_TYPE, BODY) + await vi.waitFor(() => expect(held.requests).toHaveLength(1)) + await disposed[Symbol.asyncDispose]() + await delay(50) + } finally { + process.off('unhandledRejection', onUnhandled) + } + + expect(unhandled).toEqual([]) + }) + }) + + describe('bounds and cancellation', () => { + it('times out a connection that never completes its handshake', async () => { + await using listener = await silentListener() + + const error = await rejectionOf(IngestSession.open(sessionOptions(`https://127.0.0.1:${listener.port}/point/`, { connectTimeout: 50 }))) + + expect((error as IngestError).cmafError).toBe(CMAFError.TIMEOUT) + }) + + it('bounds a request whose answer never comes', async () => { + await using mock = await MockIngestServer.start({ + answer: () => ({ hold: true }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url, { responseTimeout: 50 })) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + + const error = await rejectionOf(session.finish()) + + expect((error as IngestError).cmafError).toBe(CMAFError.NO_RESPONSE) + }) + + it('cancels an object in flight when the caller\'s signal aborts', async () => { + const controller = new AbortController() + + await using mock = await MockIngestServer.start({ + answer: () => ({ hold: true }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url, { signal: controller.signal })) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + controller.abort() + + const error = await rejectionOf(session.finish()) + + expect((error as IngestError).cmafError).toBe(CMAFError.CANCELED) + }) + + it('refuses the first object once the caller\'s signal aborted after the session opened', async () => { + const controller = new AbortController() + + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url, { signal: controller.signal })) + + controller.abort() + + const error = await rejectionOf(session.put(PLAYLIST, PLAYLIST_TYPE, BODY)) + + expect((error as IngestError).cmafError).toBe(CMAFError.CANCELED) + expect(mock.requests).toEqual([]) + }) + + it('cancels a put waiting on the window when the session is disposed', async () => { + await using mock = await MockIngestServer.start({ + answer: () => ({ hold: true }), + }) + await using session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put('clip/first.m4s', SEGMENT_TYPE, BODY) + + const waiting = rejectionOf(session.put('clip/second.m4s', SEGMENT_TYPE, BODY)) + + await session[Symbol.asyncDispose]() + + expect(((await waiting) as IngestError).cmafError).toBe(CMAFError.CANCELED) + }) + + it('fails the connection to a closed port', async () => { + const error = await rejectionOf(IngestSession.open(sessionOptions(`https://127.0.0.1:${await closedPort()}/point/`))) + + expect((error as IngestError).cmafError).toBe(CMAFError.CONNECTION_FAILED) + }) + + it('fails with Cannot Find Host for a host whose name does not resolve', async () => { + const error = await rejectionOf(IngestSession.open(sessionOptions('https://ingest.invalid/point/'))) + + expect((error as IngestError).cmafError).toBe(CMAFError.CANNOT_FIND_HOST) + }) + + it('fails with Cannot Certify for a key the client certificate does not certify', async () => { + await using mock = await MockIngestServer.start() + + const error = await rejectionOf(IngestSession.open(sessionOptions(mock.url, { + privateKey: createPrivateKey(INGEST_CERTIFICATES.strangerKey), + }))) + + expect((error as IngestError).cmafError).toBe(CMAFError.CANNOT_CERTIFY) + }) + + it('fails a put on a session destroyed before its own event says so, sending nothing', async () => { + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url)) + + // No public call reaches a session destroyed before its own close event sets the failure, which is why the row destroys the session the client holds. + const held = (session as unknown as { session: ClientHttp2Session }).session + + held.destroy() + + const error = await rejectionOf(session.put(PLAYLIST, PLAYLIST_TYPE, BODY)) + + await delay(100) + + expect(error).toBeInstanceOf(IngestError) + expect((error as IngestError).cmafError).toBe(CMAFError.CONNECTION_FAILED) + expect(mock.requests).toEqual([]) + }) + + it('reads an abort in the same turn as a put that took a free slot, sending nothing', async () => { + const controller = new AbortController() + + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url, { signal: controller.signal })) + + const put = rejectionOf(session.put(PLAYLIST, PLAYLIST_TYPE, BODY)) + + controller.abort() + + expect(((await put) as IngestError).cmafError).toBe(CMAFError.CANCELED) + expect(((await rejectionOf(session.finish())) as IngestError).cmafError).toBe(CMAFError.CANCELED) + + await delay(200) + + expect(mock.requests).toEqual([]) + }) + + it('reads a disposal in the same turn as a put that took a free slot, sending nothing', async () => { + await using mock = await MockIngestServer.start() + + const session = await IngestSession.open(sessionOptions(mock.url)) + const put = rejectionOf(session.put(PLAYLIST, PLAYLIST_TYPE, BODY)) + + await session[Symbol.asyncDispose]() + + const error = await put + + await delay(200) + + expect(error).toBeInstanceOf(IngestError) + expect((error as IngestError).cmafError).toBe(CMAFError.CANCELED) + expect(mock.requests).toEqual([]) + }) + + it('reads the caller\'s abort during the connect wait as a cancel, not a timeout', async () => { + const controller = new AbortController() + + await using listener = await silentListener() + + const opening = rejectionOf(IngestSession.open(sessionOptions(`https://127.0.0.1:${listener.port}/point/`, { + connectTimeout: 5000, + signal: controller.signal, + }))) + + await delay(50) + controller.abort() + + expect(((await opening) as IngestError).cmafError).toBe(CMAFError.CANCELED) + }) + + it('refuses to open with a signal already aborted', async () => { + await using mock = await MockIngestServer.start() + + const signal = AbortSignal.abort() + const error = await rejectionOf(IngestSession.open(sessionOptions(mock.url, { signal }))) + + expect((error as IngestError).cmafError).toBe(CMAFError.CANCELED) + }) + + it('times out a connect bound shorter than the handshake and leaves no session open at the publishing point', async () => { + await using mock = await MockIngestServer.start() + + const error = await rejectionOf(IngestSession.open(sessionOptions(mock.url, { connectTimeout: 1 }))) + + expect((error as IngestError).cmafError).toBe(CMAFError.TIMEOUT) + + await delay(300) + + expect(mock.openSessions).toBe(0) + }) + }) + + describe('refusals and disposal', () => { + it.each(Object.entries(REFUSED_OPTIONS))('refuses %s', async (_name, overrides) => { + await expect(IngestSession.open(sessionOptions('https://localhost/point/', overrides))).rejects.toThrow(TypeError) + }) + + it('refuses an object path that leaves the publishing point, and any object once finishing', async () => { + await using mock = await MockIngestServer.start() + await using session = await IngestSession.open(sessionOptions(mock.url)) + + for (const path of ['../x', '/x', 'a//b', 'a/./b', '']) { + await expect(session.put(path, SEGMENT_TYPE, BODY)).rejects.toThrow(TypeError) + } + + await session.finish() + await expect(session.put(PLAYLIST, PLAYLIST_TYPE, BODY)).rejects.toThrow(TypeError) + expect(mock.requests).toEqual([]) + }) + + it('closes its session on disposal, and a second disposal does nothing', async () => { + await using mock = await MockIngestServer.start() + + const session = await IngestSession.open(sessionOptions(mock.url)) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + await session.finish() + await vi.waitFor(() => expect(mock.openSessions).toBe(1)) + await session[Symbol.asyncDispose]() + await vi.waitFor(() => expect(mock.openSessions).toBe(0)) + await expect(session[Symbol.asyncDispose]()).resolves.toBeUndefined() + }) + + it('holds one abort listener on the caller\'s signal while open and none after disposal', async () => { + const controller = new AbortController() + + await using mock = await MockIngestServer.start() + + const session = await IngestSession.open(sessionOptions(mock.url, { signal: controller.signal })) + + expect(getEventListeners(controller.signal, 'abort')).toHaveLength(1) + + await session[Symbol.asyncDispose]() + + expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0) + }) + + it('closes at once on disposal after an abort cancelled the stream whose answer was held', async () => { + const controller = new AbortController() + + await using mock = await MockIngestServer.start({ + answer: () => ({ hold: true }), + }) + + const session = await IngestSession.open(sessionOptions(mock.url, { signal: controller.signal })) + + await session.put(PLAYLIST, PLAYLIST_TYPE, BODY) + controller.abort() + + expect(((await rejectionOf(session.finish())) as IngestError).cmafError).toBe(CMAFError.CANCELED) + + const started = performance.now() + + await session[Symbol.asyncDispose]() + + // Disposal asks the session to close and waits for it up to CLOSE_TIMEOUT. A close that is never asked for takes the whole bound. + expect(performance.now() - started).toBeLessThan(1000) + }) + }) +}) diff --git a/src/lib/camera/recording/IngestSession.ts b/src/lib/camera/recording/IngestSession.ts new file mode 100644 index 000000000..1985f5adb --- /dev/null +++ b/src/lib/camera/recording/IngestSession.ts @@ -0,0 +1,769 @@ +import type { KeyObject } from 'node:crypto' +import type { ClientHttp2Session, ClientHttp2Stream } from 'node:http2' + +import type { CameraReporter } from '../diagnostics/CameraReporter.js' + +import { Buffer } from 'node:buffer' +import { X509Certificate } from 'node:crypto' +import http2 from 'node:http2' + +import { AsyncDisposableStack } from '../../util/asyncDisposableStack.js' +import { CMAFError } from '../capabilities/cameraBuffer.js' +import { debugChannel } from '../diagnostics/debugChannels.js' +import { settleWithin } from '../session/settleWithin.js' + +const INGEST_DEBUG = debugChannel('HAP-NodeJS:Camera:Ingest') + +// The default window is one object in flight at a time, which means a slow uplink slows the clip rather than growing the heap. The default response bound is long enough +// for a slow uplink to stall between writes without failing the object. +const DEFAULT_WINDOW = 1 +const DEFAULT_CONNECT_TIMEOUT = 10 * 1000 +const DEFAULT_RESPONSE_TIMEOUT = 30 * 1000 + +/** + * How long disposal waits for the session to close before it destroys it. + */ +export const CLOSE_TIMEOUT = 5 * 1000 + +// The most of an answer's body the client reads, and keeps as a failure's excerpt. +const BODY_EXCERPT_LENGTH = 4 * 1024 + +// An object's path beneath the publishing point: segments of word characters, dots and hyphens joined by slashes, none of them a dot segment. +const OBJECT_PATH = /^[\w.-]+(?:\/[\w.-]+)*$/ +const DOT_SEGMENTS: ReadonlySet = new Set(['.', '..']) + +// The codes of a failed name resolution and of a failed socket, read from an error's code before the session connects. +const NAME_RESOLUTION_CODES: ReadonlySet = new Set(['EAI_AGAIN', 'ENOTFOUND']) +const SOCKET_CODES: ReadonlySet = new Set([ + 'ECONNREFUSED', + 'ECONNRESET', + 'EHOSTUNREACH', + 'ENETUNREACH', + 'EPIPE', + 'ETIMEDOUT', +]) + +/** + * The options of an ingest session. + */ +export interface IngestSessionOptions { + /** + * The publishing point's URL, which must be https and end in a slash. + */ + url: string + /** + * The CA certificates the hub wrote for the publishing point, each in DER format. They are the only certificates the session trusts. + */ + serverCAs: readonly Uint8Array[] + /** + * The client certificate the hub issued, in DER format. + */ + clientCertificate: Uint8Array + /** + * The CA the client certificate was issued under, in DER format, sent with it as its chain. + */ + clientCA: Uint8Array + /** + * The private key the client certificate certifies. + */ + privateKey: KeyObject + /** + * The User-Agent every request carries. + */ + userAgent: string + /** + * A signal that cancels the session at any point of its life. + */ + signal?: AbortSignal + /** + * The most objects in flight at once, 1 by default. + */ + window?: number + /** + * How long the session waits to connect, in milliseconds. + */ + connectTimeout?: number + /** + * How long a request's stream may stay idle before its answer is read, in milliseconds. + */ + responseTimeout?: number + /** + * The camera's reporter, through which the session writes its debug events. + */ + reporter: CameraReporter +} + +/** + * One object an ingest session sent. + */ +export interface IngestObject { + /** + * Resolves with the 2xx status the publishing point answered the object with, or with `undefined` once the session failed before that answer. It + * never rejects: an answer no caller reads cannot reject unhandled. + */ + readonly answer: Promise +} + +/** + * The one failure of an ingest session, carrying the CMAF error a camera reports for it. + */ +export class IngestError extends Error { + /** + * The CMAF error the failure maps to. + */ + readonly cmafError: CMAFError + /** + * The status the publishing point answered, when it answered. + */ + readonly status?: number + /** + * The start of the answer's body, decoded as UTF-8, when the publishing point answered. + */ + readonly body?: string + + constructor(message: string, { body, cause, cmafError, status }: { body?: string, cause?: unknown, cmafError: CMAFError, status?: number }) { + super(message, { cause }) + + this.name = 'IngestError' + this.cmafError = cmafError + this.status = status + this.body = body + } +} + +// What the client saw end a connection, a request or the session short of the answer it wanted, the input of the one CMAF error mapping. +type Observation + = | { kind: 'canceled' } + | { code?: string, kind: 'connect' } + | { kind: 'connectTimeout' } + | { kind: 'credential' } + | { code?: string, kind: 'ended', rstCode?: number } + | { kind: 'responseTimeout' } + | { kind: 'status', status: number } + +// The CMAF error of each answer the spec names a value for; any other status takes its class's value. +const STATUS_ERRORS: ReadonlyMap = new Map([ + [400, CMAFError.HTTP_BAD_REQUEST], + [401, CMAFError.HTTP_INVALID_TOKEN], + [403, CMAFError.HTTP_BLOCKED], + [404, CMAFError.HTTP_NOT_FOUND], + [415, CMAFError.HTTP_UNSUPPORTED_MEDIA_TYPE], + [429, CMAFError.REQUIRES_RETRY], + [500, CMAFError.HTTP_INTERNAL_SERVER_ERROR], + [502, CMAFError.HTTP_SERVICE_UNAVAILABLE], + [503, CMAFError.HTTP_SERVICE_UNAVAILABLE], + [504, CMAFError.HTTP_SERVICE_UNAVAILABLE], +]) + +/* The one mapping from what the client observes to the CMAF error it reports. It reads an error's code and a stream's reset code, never an error's class, + * because a refused connection to a name with several addresses surfaces as an AggregateError carrying the same code as a plain one. The publishing point's + * service documents none of its answers: each value is the spec's name that matches what the client saw, kept in this one function so the mapping + * changes in one place. + */ +function cmafErrorOf(observation: Observation): CMAFError { + switch (observation.kind) { + case 'canceled': + return CMAFError.CANCELED + + case 'connect': + if (observation.code !== undefined && NAME_RESOLUTION_CODES.has(observation.code)) { + return CMAFError.CANNOT_FIND_HOST + } + + // Anything else before the session connects is the handshake: a chain not under the hub's CAs, a name that does not match, a refused handshake. + return observation.code !== undefined && SOCKET_CODES.has(observation.code) + ? CMAFError.CONNECTION_FAILED + : CMAFError.CERT_CONNECTION_FAILURE + + case 'connectTimeout': + return CMAFError.TIMEOUT + + case 'credential': + return CMAFError.CANNOT_CERTIFY + + case 'ended': + // TLS 1.3 finishes client authentication after the session connects. A refused client certificate arrives as an alert on the first request. + if (observation.code?.startsWith('ERR_SSL_')) { + return CMAFError.CERT_CONNECTION_FAILURE + } + + return observation.rstCode === http2.constants.NGHTTP2_REFUSED_STREAM + ? CMAFError.REQUIRES_RETRY + : CMAFError.CONNECTION_FAILED + + case 'responseTimeout': + return CMAFError.NO_RESPONSE + + case 'status': { + const { status } = observation + const named = STATUS_ERRORS.get(status) + + if (named !== undefined) { + return named + } + + if (status >= 400 && status < 500) { + return CMAFError.HTTP_BAD_REQUEST + } + + return status >= 500 && status < 600 + ? CMAFError.HTTP_INTERNAL_SERVER_ERROR + : CMAFError.UNKNOWN + } + } +} + +// The sentence each kind of failure is reported with, naming no URL, path, key or certificate, because users paste their logs and debug output into +// public issues. +const FAILURE_MESSAGES: Record = { + canceled: 'The ingest session was canceled.', + connect: 'The ingest session could not connect to the publishing point.', + connectTimeout: 'The ingest session timed out connecting to the publishing point.', + credential: 'The ingest session could not use its credential to connect.', + ended: 'The connection to the publishing point ended without an answer.', + responseTimeout: 'The publishing point did not answer an object in time.', + status: 'The publishing point did not accept an object.', +} + +function failureOf(observation: Observation, { body, cause }: { body?: string, cause?: unknown } = {}): IngestError { + return new IngestError(FAILURE_MESSAGES[observation.kind], { + body, + cause, + cmafError: cmafErrorOf(observation), + status: observation.kind === 'status' + ? observation.status + : undefined, + }) +} + +function codeOf(error: unknown): string | undefined { + return typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string' + ? error.code + : undefined +} + +/** + * Reads a publishing point's URL as the spec has it: well formed, https, ending in a slash, and carrying no query, fragment or credentials. Every + * object's path sits beneath it. + * @param url - The URL a hub wrote. + * @returns The parsed URL. + */ +export function parsePublishingPointURL(url: string): URL { + if (!URL.canParse(url)) { + throw new TypeError('The publishing point\'s URL is not a URL.') + } + + const parsed = new URL(url) + + if (parsed.protocol !== 'https:') { + throw new TypeError('The publishing point\'s URL must use https.') + } + + if (!parsed.pathname.endsWith('/')) { + throw new TypeError('The publishing point\'s URL must end in a slash.') + } + + if (parsed.search !== '' || parsed.hash !== '' || parsed.username !== '' || parsed.password !== '') { + throw new TypeError('The publishing point\'s URL must carry no query, fragment or credentials.') + } + + return parsed +} + +/* Waits for the session to connect, answering undefined once it has, or what ended the wait: an error, a close, the connect bound or the caller's signal. + * Its error listener stays for the session's life and does nothing once the wait is over: an error emitted before the session's own listener is + * attached, or by a session destroyed after a failed wait, still finds one. + */ +async function connected(session: ClientHttp2Session, signal: AbortSignal, bound: AbortSignal): Promise<{ cause?: unknown, observation: Observation } | undefined> { + return new Promise((resolve) => { + function end(outcome?: { cause?: unknown, observation: Observation }): void { + session.off('connect', onConnect) + session.off('close', onClose) + signal.removeEventListener('abort', onAbort) + resolve(outcome) + } + + function onConnect(): void { + end() + } + + function onError(error: unknown): void { + end({ + cause: error, + observation: { + code: codeOf(error), + kind: 'connect', + }, + }) + } + + function onClose(): void { + end({ + observation: { kind: 'connect' }, + }) + } + + // A caller's own AbortSignal.timeout aborts with the same reason name as the connect bound, which is why the bound's own signal tells the two apart. + function onAbort(): void { + end({ + observation: { + kind: bound.aborted ? 'connectTimeout' : 'canceled', + }, + }) + } + + session.once('connect', onConnect) + session.on('error', onError) + session.once('close', onClose) + signal.addEventListener('abort', onAbort, { once: true }) + }) +} + +// Closes a session, waiting for the close up to CLOSE_TIMEOUT and destroying it past that. A session a TLS alert destroyed never emits close, and it is +// not waited for. +async function closeSession(session: ClientHttp2Session, reporter: CameraReporter): Promise { + if (session.destroyed) { + return + } + + const closed = new Promise(resolve => session.once('close', () => resolve())) + + session.close() + + if (await settleWithin(closed, AbortSignal.timeout(CLOSE_TIMEOUT)) === undefined) { + reporter.debug(INGEST_DEBUG, 'session-destroyed', () => ({ sentence: 'The ingest session did not close in time, and it is destroyed.' })) + session.destroy() + } +} + +interface Waiter { + reject: (error: IngestError) => void + resolve: () => void +} + +/** + * One HTTP/2 session with mutual TLS to a publishing point, carrying the objects of one clip. It knows no playlist and no path of its own: its caller names + * every object's path beneath the point. The hub's server CAs replace Node's bundled roots for the session, hostname verification applies as usual, a + * redirect is never followed, and at most a window of objects is in flight. A caller that awaits each {@link put} sends no faster than the uplink + * drains. Each put answers the object it sent, whose answer tells the caller when the publishing point accepted that object without waiting for + * {@link finish}. + * + * The session holds at most one failure, set by whatever ends it first: an answer other than 2xx, a request's stream ending without one, a request idle + * past its response bound, the session's own GOAWAY, close or error, the caller's signal, or disposal. The failure is kept as a value and handed to every + * waiting and later {@link put} and {@link finish}, and it cancels every stream still in flight. A failure after {@link finish} resolved is a debug event + * and nothing more. + * + * One failure leaves {@link finish} resolving: the session's own GOAWAY, close or error while no object is in flight and none waits. Such a session ended + * idle, with every object it sent answered 2xx: its objects are whole at the publishing point, and only a later put fails. A cancel by the caller's + * signal or by disposal is never idle, because the caller ended the session rather than the publishing point. + */ +export class IngestSession implements AsyncDisposable { + private readonly session: ClientHttp2Session + + // The publishing point's path, which every object's path extends. + private readonly base: string + + private readonly userAgent: string + + private readonly window: number + + private readonly responseTimeout: number + + private readonly reporter: CameraReporter + + private readonly stack = new AsyncDisposableStack() + + // Each request in flight with the resolver of its object's answer. + private readonly inFlight = new Map void>() + + // The puts waiting for a slot in the window, and the finishes waiting for every object to be answered. + private readonly waiting: Waiter[] = [] + private readonly draining: Waiter[] = [] + + // The slots in use: each request holds one from its send to its outcome, and a put woken for a slot holds it from the moment it is handed over. + private held = 0 + + private failure?: IngestError + + // Whether the failure is the session's own end while it was idle, which finish reads as every object answered. + private endedIdle = false + + private finishing = false + + private finished = false + + private disposed = false + + private constructor(session: ClientHttp2Session, base: string, { reporter, responseTimeout, signal, userAgent, window }: { + reporter: CameraReporter + responseTimeout: number + signal?: AbortSignal + userAgent: string + window: number + }) { + this.session = session + this.base = base + this.userAgent = userAgent + this.window = window + this.responseTimeout = responseTimeout + this.reporter = reporter + + session.on('goaway', () => this.end()) + session.on('close', () => this.end()) + session.on('error', error => this.end(error)) + + this.stack.adopt(session, session => closeSession(session, reporter)) + + if (signal === undefined) { + return + } + + const onAbort = (): void => this.fail(failureOf({ kind: 'canceled' })) + + if (signal.aborted) { + onAbort() + + return + } + + signal.addEventListener('abort', onAbort, { once: true }) + this.stack.defer(() => signal.removeEventListener('abort', onAbort)) + } + + /** + * Connects to a publishing point with the hub-issued credential. + * @param options - The session's options. + * @returns The connected session. + */ + static async open(options: IngestSessionOptions): Promise { + const { + clientCA, + clientCertificate, + connectTimeout = DEFAULT_CONNECT_TIMEOUT, + privateKey, + reporter, + responseTimeout = DEFAULT_RESPONSE_TIMEOUT, + serverCAs, + signal, + url, + userAgent, + window = DEFAULT_WINDOW, + } = options + const point = parsePublishingPointURL(url) + + if (serverCAs.length === 0) { + throw new TypeError('An ingest session needs at least one server CA certificate.') + } + + if (userAgent === '') { + throw new TypeError('An ingest session needs a user agent.') + } + + if (!Number.isInteger(window) || window < 1) { + throw new TypeError('An ingest session\'s window must be a positive integer.') + } + + if (!(connectTimeout > 0) || !(responseTimeout > 0)) { + throw new TypeError('An ingest session\'s timeouts must be positive.') + } + + const bound = AbortSignal.timeout(connectTimeout) + const connecting = AbortSignal.any(signal === undefined + ? [bound] + : [bound, signal]) + + if (connecting.aborted) { + throw failureOf({ kind: 'canceled' }) + } + + let session: ClientHttp2Session + + // Node reads a CA or a certificate given as DER as no certificate at all: each goes to TLS as PEM, the client certificate's chain one string. + try { + session = http2.connect(point.origin, { + ca: serverCAs.map(certificate => new X509Certificate(certificate).toString()), + cert: new X509Certificate(clientCertificate).toString() + new X509Certificate(clientCA).toString(), + key: privateKey.export({ format: 'pem', type: 'pkcs8' }), + }) + } catch (error) { + throw failureOf({ kind: 'credential' }, { cause: error }) + } + + const ended = await connected(session, connecting, bound) + + if (ended !== undefined) { + session.destroy() + + throw failureOf(ended.observation, { cause: ended.cause }) + } + + reporter.debug(INGEST_DEBUG, 'session-connected', () => ({ sentence: 'The ingest session connected.' })) + + return new IngestSession(session, point.pathname, { + reporter, + responseTimeout, + signal, + userAgent, + window, + }) + } + + /** + * Sends one object once a slot in the window is free. + * @param path - The object's path beneath the publishing point. + * @param contentType - The object's content type. + * @param body - The object. + * @param headers - Headers for this object's request alone, each a name and its value, sent beside the session's own. + * @returns A promise that resolves with the object once its request is in flight. + */ + async put(path: string, contentType: string, body: Uint8Array, headers: Readonly> = {}): Promise { + if (this.finishing) { + throw new TypeError('An ingest session takes no object once it is finishing.') + } + + if (!OBJECT_PATH.test(path) || path.split('/').some(segment => DOT_SEGMENTS.has(segment))) { + throw new TypeError('An object\'s path must be relative segments of letters, digits, underscores, dots and hyphens, none of them a dot segment.') + } + + await this.acquire() + + // A session that ended without an event to say so fails here, and a failure set since the slot was taken, an abort or a disposal in the same turn + // as this put, is read here too. A request is only ever made on a live session and a failed put gives its slot back. + if (this.failure === undefined && (this.session.closed || this.session.destroyed)) { + this.fail(failureOf({ kind: 'ended' })) + } + + if (this.failure !== undefined) { + this.release() + + throw this.failure + } + + return this.send(path, contentType, body, headers) + } + + /** + * Waits for every object sent to be answered. + * @returns A promise that resolves once every object is answered 2xx, a session that ended idle among them, and rejects with the session's failure. + */ + async finish(): Promise { + this.finishing = true + + if (this.failure !== undefined && !this.endedIdle) { + throw this.failure + } + + if (this.held > 0) { + await new Promise((resolve, reject) => this.draining.push({ reject, resolve })) + } + + this.finished = true + this.reporter.debug(INGEST_DEBUG, 'objects-accepted', () => ({ sentence: 'The publishing point accepted every object of the ingest session.' })) + } + + /** + * Cancels whatever is in flight and closes the session. + */ + async [Symbol.asyncDispose](): Promise { + if (this.disposed) { + return + } + + this.disposed = true + this.fail(failureOf({ kind: 'canceled' })) + await this.stack.disposeAsync() + } + + // Takes a slot in the window, waiting in turn for one when the window is full. + private async acquire(): Promise { + if (this.failure !== undefined) { + throw this.failure + } + + if (this.held < this.window) { + this.held++ + } else { + await new Promise((resolve, reject) => this.waiting.push({ reject, resolve })) + } + } + + // Hands a freed slot to the next waiting put, or gives it up and wakes the finishes once no slot is held. + private release(): void { + const next = this.waiting.shift() + + if (next !== undefined) { + next.resolve() + + return + } + + this.held-- + + if (this.held === 0) { + for (const waiter of this.draining.splice(0)) { + waiter.resolve() + } + } + } + + private send(path: string, contentType: string, body: Uint8Array, headers: Readonly>): IngestObject { + let stream: ClientHttp2Stream + + // A request refused as it is made, a header it cannot carry among them, gives its slot back at once; any later outcome gives it back as it settles. + // The session's own headers come after the caller's, which is why a caller's header of the same name never replaces one of them. + try { + stream = this.session.request({ + ...headers, + ':method': 'PUT', + ':path': `${this.base}${path}`, + 'content-length': body.byteLength, + 'content-type': contentType, + 'user-agent': this.userAgent, + }) + } catch (error) { + this.release() + + throw error + } + + const excerpt: Buffer[] = [] + let read = 0 + let status: number | undefined + let streamError: unknown + let settled = false + let answerWith!: (status: number | undefined) => void + const objectAnswer = new Promise((resolve) => { + answerWith = resolve + }) + + // A request's outcome frees its slot whatever it is: an answer, an error, a cancel or the bound. Its object's answer is the status of a 2xx alone. + const settle = (failure?: IngestError): void => { + if (settled) { + return + } + + settled = true + this.inFlight.delete(stream) + answerWith(failure === undefined + ? status + : undefined) + + if (failure === undefined) { + this.reporter.debug(INGEST_DEBUG, 'object-accepted', () => ({ + path, + sentence: `The publishing point accepted ${path}.`, + })) + } else { + this.reporter.debug(INGEST_DEBUG, 'object-refused', () => ({ + message: failure.message, + path, + sentence: `The publishing point did not accept ${path}: ${failure.message}`, + })) + this.fail(failure) + } + + this.release() + } + + // An answer's outcome is its status, its excerpt the start of its body. + const answered = (answer: number): IngestError | undefined => answer >= 200 && answer < 300 + ? undefined + : failureOf({ kind: 'status', status: answer }, { + body: Buffer.concat(excerpt).subarray(0, BODY_EXCERPT_LENGTH).toString('utf8'), + }) + + this.inFlight.set(stream, answerWith) + + // The bound is on inactivity from the request until its answer is read, and a slow but moving upload never trips it. + stream.setTimeout(this.responseTimeout, () => { + settle(status === undefined + ? failureOf({ kind: 'responseTimeout' }) + : answered(status)) + stream.close(http2.constants.NGHTTP2_CANCEL) + }) + + stream.on('response', (headers) => { + status = Number(headers[':status']) + }) + + stream.on('data', (chunk: Buffer) => { + if (read >= BODY_EXCERPT_LENGTH) { + return + } + + excerpt.push(chunk) + read += chunk.length + + if (read >= BODY_EXCERPT_LENGTH) { + stream.close(http2.constants.NGHTTP2_CANCEL) + } + }) + + stream.on('error', (error) => { + streamError = error + }) + + stream.on('close', () => { + settle(status === undefined + ? failureOf({ + code: codeOf(streamError), + kind: 'ended', + rstCode: stream.rstCode, + }, { cause: streamError }) + : answered(status)) + }) + + stream.end(body) + + return { answer: objectAnswer } + } + + // The session's own GOAWAY, close or error, which ends an idle session when it sets the failure while no slot is held: no object is in flight then, and + // no put waits, because a put waits only on a full window. + private end(error?: unknown): void { + if (this.failure === undefined && !this.finished) { + this.endedIdle = this.held === 0 + } + + this.fail(failureOf({ + code: codeOf(error), + kind: 'ended', + }, { cause: error })) + } + + // Sets the session's one failure, answers every object in flight with none and cancels its stream, and rejects every waiting put and finish. + private fail(failure: IngestError): void { + if (this.failure !== undefined) { + return + } + + if (this.finished) { + if (!this.disposed) { + this.reporter.debug(INGEST_DEBUG, 'failed-after-finish', () => ({ + message: failure.message, + sentence: `The ingest session ended after it finished: ${failure.message}`, + })) + } + + return + } + + this.failure = failure + this.reporter.debug(INGEST_DEBUG, 'session-failed', () => ({ + message: failure.message, + sentence: `The ingest session failed: ${failure.message}`, + })) + + for (const [stream, answerWith] of this.inFlight) { + answerWith(undefined) + stream.close(http2.constants.NGHTTP2_CANCEL) + } + + for (const waiter of [ + ...this.waiting.splice(0), + ...this.draining.splice(0), + ]) { + waiter.reject(failure) + } + } +} diff --git a/src/lib/camera/recording/ProducerReferenceTimeWriter.spec.ts b/src/lib/camera/recording/ProducerReferenceTimeWriter.spec.ts new file mode 100644 index 000000000..8ba4353fa --- /dev/null +++ b/src/lib/camera/recording/ProducerReferenceTimeWriter.spec.ts @@ -0,0 +1,433 @@ +import type { TrackFixture } from '../../../test-utils/mp4Fixtures.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + box, + initializationSegment, + mediaFragment, + mp4aSampleEntry, + opusSampleEntry, + prft, + skeletonPackets, + STYP, + visualSampleEntry, +} from '../../../test-utils/mp4Fixtures.js' +import { walkBoxes } from '../mp4/mp4Boxes.js' +import { ProducerReferenceTimeWriter } from './ProducerReferenceTimeWriter.js' + +const WALL_CLOCK = Date.parse('2026-11-12T00:00:00.000Z') +const VIDEO: TrackFixture = { handler: 'vide', id: 1, timescale: 90000 } + +const BEFORE_INITIALIZATION = 'The recording yielded a media fragment before any initialization segment.' +const NO_VIDEO_TRACK = 'The recording yielded an initialization segment with no video track.' +const UNREADABLE = 'The recording yielded a packet whose boxes cannot be read.' +const UNTIMEABLE = 'The recording yielded a media fragment with no decode time for its video track.' + +// A writer that has read an initialization segment of the tracks given. +function initialized(...tracks: TrackFixture[]): ProducerReferenceTimeWriter { + const writer = new ProducerReferenceTimeWriter() + + writer.write(initializationSegment(...tracks), WALL_CLOCK) + + return writer +} + +// The fields of the box written at an offset of a packet. +function written(packet: Buffer, offset = 0): { media: bigint, ntp: bigint, track: number, type: string, versionAndFlags: number } { + return { + media: packet.readBigUInt64BE(offset + 24), + ntp: packet.readBigUInt64BE(offset + 16), + track: packet.readUInt32BE(offset + 12), + type: packet.toString('latin1', offset + 4, offset + 8), + versionAndFlags: packet.readUInt32BE(offset + 8), + } +} + +describe('producerReferenceTimeWriter', () => { + describe('packets it passes as they came', () => { + it('passes a packet holding no boxes, the one-byte end marker among them', () => { + const writer = initialized(VIDEO) + + for (const packet of [ + Buffer.alloc(1), + Buffer.alloc(0), + Buffer.from('00000004', 'hex'), + ]) { + expect(writer.write(packet, WALL_CLOCK)).toBe(packet) + } + }) + + it('passes boxes holding neither an initialization segment nor a fragment, a producer reference time box among them kept', () => { + const writer = initialized(VIDEO) + + for (const packet of [ + Buffer.concat([ + box('free'), + prft(), + ]), + prft(), + STYP, + ]) { + expect(writer.write(packet, WALL_CLOCK)).toBe(packet) + } + }) + }) + + describe('initialization segments', () => { + it('reads a fresh initialization segment\'s track and timescale, keeping the stream\'s anchor', () => { + const writer = initialized(VIDEO) + const first = writer.write(mediaFragment({ decodeTime: 0n, trackId: 1 }), WALL_CLOCK) + + writer.write(initializationSegment({ handler: 'vide', id: 2, timescale: 15360 }), WALL_CLOCK + 60000) + + const later = writer.write(mediaFragment({ decodeTime: 15360n, trackId: 2 }), WALL_CLOCK + 60000) + + expect(written(later)).toMatchObject({ media: 15360n, ntp: written(first).ntp + 2n ** 32n, track: 2 }) + }) + + it('times the video track when audio is track 1', () => { + const writer = initialized({ handler: 'soun', id: 1, timescale: 16000 }, { handler: 'vide', id: 2, timescale: 90000 }) + const packet = writer.write(mediaFragment({ decodeTime: 32000n, trackId: 1 }, { decodeTime: 180000n, trackId: 2 }), WALL_CLOCK) + + expect(written(packet)).toMatchObject({ media: 180000n, ntp: 0xEE9F800000000000n, track: 2 }) + }) + + it('times the first of two video tracks, and refuses a video track of timescale 0 or a movie of audio alone as no video track', () => { + const writer = initialized(VIDEO, { handler: 'vide', id: 2, timescale: 15360 }) + + expect(written(writer.write(mediaFragment({ decodeTime: 0n, trackId: 1 }, { decodeTime: 0n, trackId: 2 }), WALL_CLOCK)).track).toBe(1) + + for (const track of [ + { ...VIDEO, timescale: 0 }, + { handler: 'soun', id: 1, timescale: 16000 }, + ]) { + expect(() => new ProducerReferenceTimeWriter().write(initializationSegment(track), WALL_CLOCK)).toThrow(NO_VIDEO_TRACK) + } + }) + }) + + describe('fragments', () => { + it('writes a version 1 box with flags 24 immediately before a fragment, carrying the video track, the clock and the decode time', () => { + const fragment = mediaFragment({ decodeTime: 0n, trackId: 1 }) + const packet = initialized(VIDEO).write(fragment, WALL_CLOCK) + + expect(packet).toHaveLength(32 + fragment.length) + expect(packet.readUInt32BE(0)).toBe(32) + expect(written(packet)).toEqual({ + media: 0n, + ntp: 0xEE9F800000000000n, + track: 1, + type: 'prft', + versionAndFlags: 0x01000018, + }) + expect(packet.subarray(32)).toEqual(fragment) + }) + + it('reads a decode time of version 0', () => { + const packet = initialized(VIDEO).write(mediaFragment({ decodeTime: 360000n, trackId: 1, version: 0 }), WALL_CLOCK) + + expect(written(packet).media).toBe(360000n) + }) + + it('writes a box before each of two fragments in one packet', () => { + const first = mediaFragment({ decodeTime: 0n, trackId: 1 }) + const second = mediaFragment({ decodeTime: 90000n, trackId: 1 }) + const packet = initialized(VIDEO).write(Buffer.concat([first, second]), WALL_CLOCK) + + expect(packet.subarray(32, 32 + first.length)).toEqual(first) + expect(packet.subarray(64 + first.length)).toEqual(second) + expect(written(packet, 32 + first.length)).toMatchObject({ media: 90000n, ntp: written(packet).ntp + 2n ** 32n }) + }) + + it('reads an initialization segment and stamps the fragment that follows it in one packet', () => { + const initialization = initializationSegment(VIDEO) + const fragment = mediaFragment({ decodeTime: 0n, trackId: 1 }) + const packet = new ProducerReferenceTimeWriter().write(Buffer.concat([initialization, fragment]), WALL_CLOCK) + + expect(packet.subarray(0, initialization.length)).toEqual(initialization) + expect(written(packet, initialization.length).track).toBe(1) + expect(packet.subarray(initialization.length + 32)).toEqual(fragment) + }) + + it('writes the box after a segment type box, immediately before the fragment', () => { + const fragment = mediaFragment({ decodeTime: 0n, trackId: 1 }) + const packet = initialized(VIDEO).write(Buffer.concat([STYP, fragment]), WALL_CLOCK) + + expect(packet.subarray(0, STYP.length)).toEqual(STYP) + expect(written(packet, STYP.length).type).toBe('prft') + expect(packet.subarray(STYP.length + 32)).toEqual(fragment) + }) + }) + + describe('contract errors', () => { + it('refuses a fragment before any initialization segment, first or after the end marker', () => { + const fragment = mediaFragment({ decodeTime: 0n, trackId: 1 }) + const afterMarker = new ProducerReferenceTimeWriter() + + afterMarker.write(Buffer.alloc(1), WALL_CLOCK) + + expect(() => new ProducerReferenceTimeWriter().write(fragment, WALL_CLOCK)).toThrow(BEFORE_INITIALIZATION) + expect(() => afterMarker.write(fragment, WALL_CLOCK)).toThrow(BEFORE_INITIALIZATION) + }) + + it('refuses a fragment with no run of the video track, or a video run with no decode time', () => { + const writer = initialized(VIDEO) + + expect(() => writer.write(mediaFragment({ decodeTime: 0n, trackId: 2 }), WALL_CLOCK)).toThrow(UNTIMEABLE) + expect(() => writer.write(mediaFragment({ trackId: 1 }), WALL_CLOCK)).toThrow(UNTIMEABLE) + }) + + it('refuses a fragment followed by a box running past the packet', () => { + const packet = Buffer.concat([ + mediaFragment({ decodeTime: 0n, trackId: 1 }), + Buffer.from('0000004066726565', 'hex'), + ]) + + expect(() => initialized(VIDEO).write(packet, WALL_CLOCK)).toThrow(UNREADABLE) + }) + + it('refuses an initialization segment followed by a box running past the packet', () => { + const packet = Buffer.concat([ + initializationSegment(VIDEO), + Buffer.from('0000004066726565', 'hex'), + ]) + + expect(() => new ProducerReferenceTimeWriter().write(packet, WALL_CLOCK)).toThrow(UNREADABLE) + }) + + it('refuses a malformed box inside an initialization segment and inside a fragment', () => { + const movie = box('moov', Buffer.from('0000004074726166', 'hex')) + const fragment = box('moof', box('traf', Buffer.from('0000000474666864', 'hex'))) + + expect(() => new ProducerReferenceTimeWriter().write(movie, WALL_CLOCK)).toThrow(UNREADABLE) + expect(() => initialized(VIDEO).write(fragment, WALL_CLOCK)).toThrow(UNREADABLE) + }) + }) + + describe('the clock', () => { + it.each([ + [ + 'at whole seconds', + '2026-11-12T00:00:00.000Z', + VIDEO, + [0n, 360000n], + ['00000020707266740100001800000001ee9f8000000000000000000000000000', '00000020707266740100001800000001ee9f8004000000000000000000057e40'], + ], + [ + 'from a first fragment past its track\'s start', + '2026-11-12T00:00:00.250Z', + { handler: 'vide', id: 2, timescale: 15360 }, + [61440n, 122880n], + ['00000020707266740100001800000002ee9f800040000000000000000000f000', '00000020707266740100001800000002ee9f800440000000000000000001e000'], + ], + [ + 'across the NTP era\'s wrap', + '2036-02-07T06:28:16.000Z', + VIDEO, + [0n, 360000n], + ['0000002070726674010000180000000100000000000000000000000000000000', '0000002070726674010000180000000100000004000000000000000000057e40'], + ], + [ + 'with a 64-bit decode time', + '2026-11-12T00:00:00.000Z', + VIDEO, + [4295057296n], + ['00000020707266740100001800000001ee9f8000000000000000000100015f90'], + ], + [ + 'flooring each fraction, as one anchor plus each decode time', + '2026-11-12T00:00:00.003Z', + VIDEO, + [1n, 3001n], + ['00000020707266740100001800000001ee9f800000c49ba50000000000000001', '00000020707266740100001800000001ee9f8000094d242e0000000000000bb9'], + ], + ] as const)('writes the clock %s', (_name, wallClock, track, decodeTimes, boxes) => { + const writer = initialized(track) + const start = Date.parse(wallClock) + + // Every later fragment is written at a later wall clock, which the box never reads. + const written = decodeTimes.map((decodeTime, index) => writer.write(mediaFragment({ decodeTime, trackId: track.id }), start + index * 7000)) + + expect(written.map(packet => packet.subarray(0, 32).toString('hex'))).toEqual(boxes) + }) + }) + + describe('readings', () => { + it('reads the skeleton in the bytes it writes: each fragment from its box to its mdat\'s end at its box\'s time with its runs\' durations', () => { + const [muxed, first, muxedSecond] = skeletonPackets() + // The skeleton's packets without the muxer's own producer reference time boxes, as the library's recorder writes none. + const initialization = muxed.subarray(0, muxed.length - 32) + const second = muxedSecond.subarray(32) + const writer = new ProducerReferenceTimeWriter() + const written = writer.writePacket(initialization, WALL_CLOCK) + + expect(written.fragments).toEqual([]) + expect(written.initialization?.bytes).toEqual(initialization) + expect(written.initialization?.video).toEqual({ handler: 'vide', id: 1, timescale: 15360 }) + expect([ + ...written.initialization!.sampleEntries.values(), + ].map(entry => entry?.codec)).toEqual(['avc1.4d400a', 'mp4a.40.2']) + + for (const [packet, duration] of [ + [first, 62424n], + [second, 61440n], + ] as const) { + const { bytes, fragments } = writer.writePacket(packet, WALL_CLOCK) + + expect(fragments).toHaveLength(1) + expect(fragments[0].bytes).toEqual(bytes) + expect(walkBoxes(fragments[0].bytes).boxes.map(({ type }) => type)).toEqual(['prft', 'moof', 'mdat']) + expect(fragments[0].ntpTime).toBe(bytes.readBigUInt64BE(16)) + expect(fragments[0].runs.find(({ trackId }) => trackId === 1)?.duration).toBe(duration) + } + }) + + it('reads each fragment of a packet from its own box, leaving out the segment type before it, and no reading from the end marker', () => { + const writer = initialized(VIDEO) + const packet = Buffer.concat([ + STYP, + mediaFragment({ + decodeTime: 0n, + samples: [3000], + trackId: 1, + }), + STYP, + mediaFragment({ + decodeTime: 3000n, + samples: [3000], + trackId: 1, + }), + ]) + const { bytes, fragments } = writer.writePacket(packet, WALL_CLOCK) + const fragmentLength = (bytes.length - 2 * STYP.length) / 2 + + expect(fragments.map(fragment => fragment.bytes)).toEqual([ + bytes.subarray(STYP.length, STYP.length + fragmentLength), + bytes.subarray(2 * STYP.length + fragmentLength), + ]) + expect(fragments.map(({ ntpTime }) => ntpTime)).toEqual([0xEE9F800000000000n, 0xEE9F800000000000n + (3000n << 32n) / 90000n]) + expect(writer.writePacket(Buffer.alloc(1), WALL_CLOCK)).toEqual({ + bytes: Buffer.alloc(1), + fragments: [], + }) + }) + + it('keys every track of an initialization segment, a video track whose avcC is too short holding no entry beside its audio track\'s entry', () => { + const shortVideo = visualSampleEntry('avc1', 64, 36, box('avcC', Buffer.from([1, 0x4D]))) + const audio: TrackFixture = { + handler: 'soun', + id: 2, + sampleEntry: mp4aSampleEntry(2), + timescale: 16000, + } + const { initialization } = new ProducerReferenceTimeWriter().writePacket(initializationSegment({ ...VIDEO, sampleEntry: shortVideo }, audio), WALL_CLOCK) + + expect(initialization?.sampleEntries).toEqual(new Map([ + [1, undefined], + [ + 2, + { codec: 'mp4a.40.2', type: 'mp4a' }, + ], + ])) + }) + + it('keys every track of an initialization segment of many tracks, a video track first, reading each track once', () => { + const tracks: TrackFixture[] = [ + VIDEO, + ...Array.from({ length: 6000 }, (_, index) => ({ + handler: 'soun', + id: index + 2, + sampleEntry: mp4aSampleEntry(2), + timescale: 16000, + })), + ] + const { initialization } = new ProducerReferenceTimeWriter().writePacket(initializationSegment(...tracks), WALL_CLOCK) + + expect(initialization?.sampleEntries.size).toBe(6001) + expect(Array.from(initialization!.sampleEntries.keys())).toEqual(tracks.map(({ id }) => id)) + expect(initialization?.sampleEntries.get(6001)).toEqual({ codec: 'mp4a.40.2', type: 'mp4a' }) + }, 2000) + + it('keys an identifier an mp4a track and a later Opus track share with the mp4a track\'s entry', () => { + const tracks: TrackFixture[] = [ + VIDEO, + { + handler: 'soun', + id: 2, + sampleEntry: mp4aSampleEntry(2), + timescale: 16000, + }, + { + handler: 'soun', + id: 2, + sampleEntry: opusSampleEntry(), + timescale: 48000, + }, + ] + const { initialization } = new ProducerReferenceTimeWriter().writePacket(initializationSegment(...tracks), WALL_CLOCK) + + expect(initialization?.sampleEntries).toEqual(new Map([ + [1, undefined], + [ + 2, + { codec: 'mp4a.40.2', type: 'mp4a' }, + ], + ])) + }) + + it('writes with write exactly the bytes writePacket answers, for every packet of the clock\'s vectors and the skeleton', () => { + const vectors: { decodeTimes: bigint[], track: TrackFixture, wallClock: string }[] = [ + { + decodeTimes: [0n, 360000n], + track: VIDEO, + wallClock: '2026-11-12T00:00:00.000Z', + }, + { + decodeTimes: [61440n, 122880n], + track: { handler: 'vide', id: 2, timescale: 15360 }, + wallClock: '2026-11-12T00:00:00.250Z', + }, + { + decodeTimes: [0n, 360000n], + track: VIDEO, + wallClock: '2036-02-07T06:28:16.000Z', + }, + { + decodeTimes: [4295057296n], + track: VIDEO, + wallClock: '2026-11-12T00:00:00.000Z', + }, + { + decodeTimes: [1n, 3001n], + track: VIDEO, + wallClock: '2026-11-12T00:00:00.003Z', + }, + ] + const sequences = [ + ...vectors.map(({ decodeTimes, track, wallClock }) => ({ + packets: [ + initializationSegment(track), + ...decodeTimes.map(decodeTime => mediaFragment({ decodeTime, trackId: track.id })), + ], + wallClock: Date.parse(wallClock), + })), + { + packets: skeletonPackets(), + wallClock: WALL_CLOCK, + }, + ] + + for (const { packets, wallClock } of sequences) { + const writer = new ProducerReferenceTimeWriter() + const reader = new ProducerReferenceTimeWriter() + + for (const [index, packet] of packets.entries()) { + expect(writer.write(packet, wallClock + index * 7000)).toEqual(reader.writePacket(packet, wallClock + index * 7000).bytes) + } + } + }) + }) +}) diff --git a/src/lib/camera/recording/ProducerReferenceTimeWriter.ts b/src/lib/camera/recording/ProducerReferenceTimeWriter.ts new file mode 100644 index 000000000..5686f730f --- /dev/null +++ b/src/lib/camera/recording/ProducerReferenceTimeWriter.ts @@ -0,0 +1,276 @@ +import type { Mp4Box, Mp4SampleEntry, Mp4Track, Mp4TrackBox, Mp4TrackFragment } from '../mp4/mp4Boxes.js' + +import { Buffer } from 'node:buffer' + +import { NTP_FRACTION_BITS, ntpTime } from '../../util/ntp.js' +import { readTrackBoxEntry, readTrackBoxes, readTrackDefaults, readTrackFragments, readVideoTrackBox, walkBoxes } from '../mp4/mp4Boxes.js' + +/** + * What the writer read of an initialization segment in the walk that wrote it. + */ +export interface WrittenInitialization { + /** + * The segment's bytes in the written packet, every box up to and including its `moov`. + */ + bytes: Buffer + /** + * The video track the writer times. + */ + video: Mp4Track + /** + * Each track's default sample duration, by track identifier. + */ + trackDefaults: ReadonlyMap + /** + * Each track's first sample entry, by track identifier, every track of the segment keyed and one whose entry is absent or does not read holding none. + */ + sampleEntries: ReadonlyMap +} + +/** + * What the writer read of a media fragment in the walk that wrote it. + */ +export interface WrittenFragment { + /** + * The fragment's bytes in the written packet, from the `prft` box written before it to the end of its `mdat`. + */ + bytes: Buffer + /** + * The NTP time the written `prft` box carries, reduced modulo 2^64. + */ + ntpTime: bigint + /** + * The fragment's runs, each with its duration when its samples give one. + */ + runs: Mp4TrackFragment[] +} + +/** + * A packet as the writer wrote it, with what its one walk read. + */ +export interface WrittenPacket { + /** + * The bytes to send. + */ + bytes: Buffer + /** + * The initialization segment the packet holds, when it holds one. + */ + initialization?: WrittenInitialization + /** + * Each fragment the packet holds, in order, none for a packet passed as it came. + */ + fragments: WrittenFragment[] +} + +// The box written before each fragment: version 1 with flags 24, then the video track's identifier, the NTP time and the media time, 32 bytes in all. +const PRFT_SIZE = 32 +const PRFT_VERSION_AND_FLAGS = 0x01000018 + +// The contract each refused packet breaks. A fragment the writer cannot time would break the clock a hub counts from the recording's first box onward. +const CONTRACT_ERRORS = { + beforeInitialization: 'The recording yielded a media fragment before any initialization segment.', + noVideoTrack: 'The recording yielded an initialization segment with no video track.', + unreadable: 'The recording yielded a packet whose boxes cannot be read.', + untimeable: 'The recording yielded a media fragment with no decode time for its video track.', +} as const + +// Reads boxes through the box reader, whose refusal of a malformed box is the unreadable packet's contract error. +function readable(read: () => T): T { + try { + return read() + } catch (error) { + throw new Error(CONTRACT_ERRORS.unreadable, { cause: error }) + } +} + +// A track's sample entry informs a playlist and times nothing: a track that describes none, or an entry the box reader refuses, holds none rather than +// refusing the recording a hub pulls. Every track is keyed from the one read of the moov's tracks the video track is taken from. A playlist names each +// track's codec or none of them, and a track whose identifier an earlier track carries keeps the earlier track's entry. +function sampleEntriesOf(packet: Buffer, trackBoxes: readonly Mp4TrackBox[]): Map { + const entries = new Map() + + for (const trackBox of trackBoxes) { + const { id } = trackBox.track + + if (entries.has(id)) { + continue + } + + let entry: Mp4SampleEntry | undefined + + try { + entry = readTrackBoxEntry(packet, trackBox) + } catch { + // An entry the box reader refuses leaves the track holding none. + } + + entries.set(id, entry) + } + + return entries +} + +/** + * 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. + * + * 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. + * + * The walk that writes a packet is the only walk of it on the stream, which is why it also answers what it read, for the served recording a camera keeps for its + * clips: each initialization segment's tracks and each fragment's place in the written bytes, its time and its runs' durations. + */ +export class ProducerReferenceTimeWriter { + private video?: { id: number, timescale: bigint } + + private trackDefaults: ReadonlyMap = new Map() + + private anchor?: bigint + + /** + * 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. + * @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. + */ + write(packet: Buffer, wallClock: number): Buffer { + return this.writePacket(packet, wallClock).bytes + } + + /** + * 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. + * @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. + */ + writePacket(packet: Buffer, wallClock: number): WrittenPacket { + const walk = walkBoxes(packet) + const fragment = walk.boxes.some(box => box.type === 'moof') + const moov = walk.boxes.find(box => box.type === 'moov') + + // A walk that read an initialization segment or a fragment and then ended short is refused here, because passing it would leave the stream's next + // fragment refused as one before any initialization segment, a contract the plugin did not break. + if (!walk.complete) { + if (fragment || moov !== undefined) { + throw new Error(CONTRACT_ERRORS.unreadable) + } + + return { bytes: packet, fragments: [] } + } + + if (moov === undefined && !fragment) { + return { bytes: packet, fragments: [] } + } + + let initialization: Omit | undefined + + if (moov !== undefined) { + const trackBoxes = readable(() => readTrackBoxes(packet, moov)) + const video = readVideoTrackBox(trackBoxes)?.track + + if (video === undefined) { + throw new Error(CONTRACT_ERRORS.noVideoTrack) + } + + this.video = { + id: video.id, + timescale: BigInt(video.timescale), + } + this.trackDefaults = readable(() => readTrackDefaults(packet, moov)) + initialization = { + sampleEntries: sampleEntriesOf(packet, trackBoxes), + trackDefaults: this.trackDefaults, + video, + } + } + + // Each part written and where the readings lie in the written bytes: the initialization segment's end, and each fragment from its box to its mdat. + const parts: Buffer[] = [] + const stamped: { end: number, ntpTime: bigint, runs: Mp4TrackFragment[], start: number }[] = [] + let length = 0 + let initializationEnd = 0 + let open: (typeof stamped)[number] | undefined + + for (const box of walk.boxes) { + if (box.type === 'moof') { + const { bytes, ntpTime, runs } = this.stamp(packet, box, wallClock) + + open = { end: 0, ntpTime, runs, start: length } + stamped.push(open) + parts.push(bytes) + length += bytes.length + } + + parts.push(packet.subarray(box.start, box.end)) + length += box.end - box.start + + if (box.type === 'moov') { + initializationEnd = length + } + + // A fragment's bytes run to the end of its moof, and on to the end of the first mdat that follows it. + if (open !== undefined && (box.type === 'moof' || box.type === 'mdat')) { + open.end = length + open = box.type === 'mdat' + ? undefined + : open + } + } + + const bytes = Buffer.concat(parts, length) + + return { + bytes, + fragments: stamped.map(({ end, ntpTime, runs, start }) => ({ + bytes: bytes.subarray(start, end), + ntpTime, + runs, + })), + initialization: initialization === undefined + ? undefined + : { + ...initialization, + bytes: bytes.subarray(0, initializationEnd), + }, + } + } + + // The box for one fragment, the anchor set at the stream's first, with the time it carries and the fragment's runs. Each 64-bit word is written modulo + // 2^64: the NTP time wraps with its era. + private stamp(packet: Buffer, moof: Mp4Box, wallClock: number): { bytes: Buffer, ntpTime: bigint, runs: Mp4TrackFragment[] } { + const video = this.video + + if (video === undefined) { + throw new Error(CONTRACT_ERRORS.beforeInitialization) + } + + const runs = readable(() => readTrackFragments(packet, moof, this.trackDefaults)) + const decodeTime = runs.find(run => run.trackId === video.id)?.baseMediaDecodeTime + + if (decodeTime === undefined) { + throw new Error(CONTRACT_ERRORS.untimeable) + } + + const elapsed = (decodeTime << NTP_FRACTION_BITS) / video.timescale + + this.anchor ??= ntpTime(wallClock) - elapsed + + const time = BigInt.asUintN(64, this.anchor + elapsed) + const box = Buffer.alloc(PRFT_SIZE) + + box.writeUInt32BE(PRFT_SIZE, 0) + box.write('prft', 4, 'latin1') + box.writeUInt32BE(PRFT_VERSION_AND_FLAGS, 8) + box.writeUInt32BE(video.id, 12) + box.writeBigUInt64BE(time, 16) + box.writeBigUInt64BE(BigInt.asUintN(64, decodeTime), 24) + + return { bytes: box, ntpTime: time, runs } + } +} diff --git a/src/lib/camera/recording/ServedRecording.spec.ts b/src/lib/camera/recording/ServedRecording.spec.ts new file mode 100644 index 000000000..3ee10b45c --- /dev/null +++ b/src/lib/camera/recording/ServedRecording.spec.ts @@ -0,0 +1,564 @@ +import type { TrackFixture } from '../../../test-utils/mp4Fixtures.js' +import type { CameraProblem } from '../diagnostics/problems.js' +import type { WrittenPacket } from './ProducerReferenceTimeWriter.js' +import type { ServedFragment, ServedReader, ServedRecording } from './ServedRecording.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { initializationSegment, mediaFragment, skeletonPackets, STYP } from '../../../test-utils/mp4Fixtures.js' +import { detachedReporter, problemsOf } from '../../../test-utils/reporterFixtures.js' +import { settle } from '../../../test-utils/settle.js' +import * as uuid from '../../util/uuid.js' +import { ProducerReferenceTimeWriter } from './ProducerReferenceTimeWriter.js' +import { SERVED_RECORDING_GRACE, SERVED_RECORDINGS_CEILING, ServedRecordings } from './ServedRecording.js' + +const VIDEO: TrackFixture = { handler: 'vide', id: 1, timescale: 90000 } +const WALL_CLOCK = Date.parse('2026-11-12T00:00:00.000Z') +const SENSOR = '1a2b3c4d-0000-4000-8000-00000000000a' + +// The synthetic camera whose channel a feed that raises its problems is heard on. +const CAMERA = uuid.generate('served recordings spec camera') + +// One block every large fragment's bytes view, a quarter of the store's ceiling. A few fragments reach the ceiling without the memory for each. +const QUARTER = Buffer.alloc(SERVED_RECORDINGS_CEILING / 4) +const STORE_FULL = `The camera that records the video sensor "${SENSOR}" held more than the ceiling of 100000000 octets in the recordings it served: the ` + + 'library released their oldest bytes, and an upload that reaches them ends at its last whole segment.' + +// Each fragment's samples sum to FRAGMENT_TICKS at 90 kHz, a whole number of seconds, and its NTP duration D is those seconds in 32.32. +const SAMPLES = 120 +const SAMPLE_DURATION = 3000 +const FRAGMENT_TICKS = 360000n +const D = 4n << 32n +const P0 = 0xEE9F800000000000n + +// A recording stream's packets as a writer wrote them: its initialization segment, then fragments whose decode times count on from the first given. +function stream(count: number, { decodeStart = 0n, wallClock = WALL_CLOCK, writer = new ProducerReferenceTimeWriter() } = {}): WrittenPacket[] { + return [ + writer.writePacket(initializationSegment(VIDEO), wallClock), + ...Array.from({ length: count }, (_, index) => writer.writePacket(mediaFragment({ + decodeTime: decodeStart + BigInt(index) * FRAGMENT_TICKS, + defaultDuration: SAMPLE_DURATION, + samples: SAMPLES, + trackId: 1, + }), wallClock)), + ] +} + +// A stream's packets as `stream` writes them, each fragment's bytes the quarter block. +function largeStream(count: number, options?: Parameters[1]): WrittenPacket[] { + return stream(count, options).map(packet => ({ + ...packet, + fragments: packet.fragments.map(fragment => ({ ...fragment, bytes: QUARTER })), + })) +} + +// A feed whose problems a row does not read, its reporter of no camera. +function quietFeed(): ServedRecordings { + return new ServedRecordings({ + reporter: detachedReporter(), + sensorUUID: SENSOR, + }) +} + +// A feed that holds, raising its problems for the synthetic camera, and the problems heard on that camera's channel. +function alertingFeed(): { alerts: CameraProblem[], feed: ServedRecordings } { + const { problems, reporter } = problemsOf(CAMERA) + + return { + alerts: problems, + feed: Object.assign(new ServedRecordings({ reporter, sensorUUID: SENSOR }), { holding: true }), + } +} + +// A recording of a feed that holds, with the packets given added. +function recorded(packets: WrittenPacket[], feed = Object.assign(quietFeed(), { holding: true })): ServedRecording { + const recording = feed.begin() + + for (const packet of packets) { + recording.add(packet) + } + + return recording +} + +// Which of a recording's fragments still hold their bytes. +function held(recording: ServedRecording): boolean[] { + return Array.from({ length: recording.length }, (_, index) => recording.fragment(index)?.bytes !== undefined) +} + +// Every fragment a reader yields until it ends. +async function drain(reader: ServedReader): Promise { + const indexes: number[] = [] + + for await (const { index } of reader) { + indexes.push(index) + } + + return indexes +} + +function placeOf(fragment: ServedFragment | undefined): bigint | undefined { + return fragment?.place +} + +describe('servedRecording', () => { + afterEach(() => { + vi.useRealTimers() + }) + + describe('the timeline', () => { + it('places the first fragment at its prft time and each later one at the end of the one before, with its bytes, durations and initialization segment', () => { + const packets = stream(3) + const recording = recorded(packets) + + expect(recording.length).toBe(3) + + for (let index = 0; index < 3; index++) { + expect(recording.fragment(index)).toEqual({ + bytes: packets[index + 1].fragments[0].bytes, + duration: D, + index, + place: P0 + BigInt(index) * D, + timescaleDuration: FRAGMENT_TICKS, + }) + } + + expect(recording.run?.initialization).toEqual(packets[0].initialization?.bytes) + }) + + it('finds a fragment start within half a fragment of a place, inclusive, the earlier when two are, and none outside', () => { + const recording = recorded(stream(3)) + + expect(placeOf(recording.fragmentAt(P0 + D + D / 2n, 'start'))).toBe(P0 + D) + expect(placeOf(recording.fragmentAt(P0 + D + D / 2n + 1n, 'start'))).toBe(P0 + 2n * D) + expect(placeOf(recording.fragmentAt(P0 - D / 2n, 'start'))).toBe(P0) + expect(recording.fragmentAt(P0 - D / 2n - 1n, 'start')).toBeUndefined() + expect(recording.fragmentAt(P0 + 2n * D + D / 2n + 1n, 'start')).toBeUndefined() + }) + + it('finds a fragment end within half a fragment of a place, and none past the last end\'s reach', () => { + const recording = recorded(stream(3)) + + expect(placeOf(recording.fragmentAt(P0 + D - 10n, 'end'))).toBe(P0) + expect(placeOf(recording.fragmentAt(P0 + 3n * D + D / 2n, 'end'))).toBe(P0 + 2n * D) + expect(recording.fragmentAt(P0 + 3n * D + D / 2n + 1n, 'end')).toBeUndefined() + }) + + it('places fragments and finds them across the NTP era\'s wrap', () => { + const recording = recorded(stream(2, { + wallClock: Date.parse('2036-02-07T06:28:15.000Z'), + })) + const first = 0xFFFFFFFF00000000n + + expect(recording.fragment(0)?.place).toBe(first) + expect(recording.fragment(1)?.place).toBe(0x300000000n) + expect(placeOf(recording.fragmentAt(0x300000000n - 1000n, 'start'))).toBe(0x300000000n) + expect(placeOf(recording.fragmentAt(2n ** 64n - 1n, 'start'))).toBe(first) + expect(placeOf(recording.fragmentAt(0x300000000n, 'end'))).toBe(first) + }) + + // Half a fragment past the first fragment's start lies past the wrap, where the place restarts from zero. + it('finds a fragment that starts before the NTP era\'s wrap from a place past it', () => { + const recording = recorded(stream(2, { + wallClock: Date.parse('2036-02-07T06:28:15.000Z'), + })) + + expect(placeOf(recording.fragmentAt(0x100000000n, 'start'))).toBe(0xFFFFFFFF00000000n) + }) + + it('follows a recording live from a fragment and ends at the recording\'s end', async () => { + const packets = stream(4) + const recording = recorded(packets.slice(0, 2)) + const reading = drain(recording.read(0)) + + await settle() + recording.add(packets[2]) + await settle() + recording.add(packets[3]) + recording.end() + recording.add(stream(1)[1]) + + await expect(reading).resolves.toEqual([0, 1, 2]) + expect(recording.length).toBe(3) + }) + }) + + describe('what a recording holds', () => { + it('keeps every fragment until the first verdict, then from the one before the latest judged, never moving back', () => { + const recording = recorded(stream(6)) + + expect(held(recording)).toEqual([true, true, true, true, true, true]) + expect(recording.judged(P0 + 2n * D, true)).toBe(true) + expect(held(recording)).toEqual([false, true, true, true, true, true]) + expect(recording.judged(P0 + 3n * D, false)).toBe(true) + expect(held(recording)).toEqual([false, false, true, true, true, true]) + expect(recording.judged(P0 + D, true)).toBe(true) + expect(held(recording)).toEqual([false, false, true, true, true, true]) + expect(recording.latestShouldRecord).toBe(2) + expect(recording.judged(P0 + 5n * D + D / 2n + 1n, true)).toBe(false) + expect(recording.latestShouldRecord).toBe(2) + expect(recording.fragmentAt(P0, 'start')).toEqual({ + duration: D, + index: 0, + place: P0, + timescaleDuration: FRAGMENT_TICKS, + }) + }) + + it('skips a packet with no reading or with neither initialization nor fragment, and turns unusable at a fragment it cannot place, never throwing', async () => { + const writer = new ProducerReferenceTimeWriter() + const packets = stream(2, { writer }) + const recording = recorded(packets) + const reading = drain(recording.read(0)) + + recording.add(writer.writePacket(Buffer.alloc(1), WALL_CLOCK)) + recording.add(writer.writePacket(STYP, WALL_CLOCK)) + + expect(recording.closed).toBe(false) + + // A fragment whose video run has no samples has no duration. + expect(() => recording.add(writer.writePacket(mediaFragment({ decodeTime: 2n * FRAGMENT_TICKS, trackId: 1 }), WALL_CLOCK))).not.toThrow() + expect(recording.closed).toBe(true) + await expect(reading).resolves.toEqual([0, 1]) + + const orphan = recorded([packets[1]]) + + expect(orphan.closed).toBe(true) + expect(orphan.length).toBe(0) + }) + + it('turns unusable at a fragment whose video run\'s samples sum to no time, reading it as closed, never throwing', async () => { + const writer = new ProducerReferenceTimeWriter() + const recording = recorded(stream(2, { writer })) + const reading = drain(recording.read(0)) + const zeroLength = mediaFragment({ + decodeTime: 2n * FRAGMENT_TICKS, + defaultDuration: 0, + samples: SAMPLES, + trackId: 1, + }) + + expect(() => recording.add(writer.writePacket(zeroLength, WALL_CLOCK))).not.toThrow() + expect(recording.closed).toBe(true) + expect(recording.length).toBe(2) + await expect(reading).resolves.toEqual([0, 1]) + }) + + it('keeps every fragment a reader has not reported sent, releasing a sent one once the verdicts pass it, and all it kept once it ends', async () => { + const packets = stream(6) + const recording = recorded(packets.slice(0, 1)) + const reader = recording.read(0) + + for (let index = 0; index < 6; index++) { + recording.add(packets[index + 1]) + recording.judged(P0 + BigInt(index) * D, true) + } + + expect(held(recording)).toEqual([true, true, true, true, true, true]) + + reader.sent(0) + reader.sent(1) + reader.sent(4) + + expect(held(recording)).toEqual([false, false, true, true, true, true]) + + reader.end() + + expect(held(recording)).toEqual([false, false, false, false, true, true]) + await expect(drain(reader)).resolves.toEqual([]) + }) + + it('ends a reader at a fragment whose next one another reader reported sent and released', async () => { + const feed = quietFeed() + const packets = stream(3) + const recording = recorded(packets.slice(0, 1), feed) + const first = recording.read(1) + + recording.add(packets[1]) + recording.add(packets[2]) + recording.add(packets[3]) + first.sent(2) + + expect(held(recording)).toEqual([false, true, false]) + await expect(drain(recording.read(1))).resolves.toEqual([1]) + first.end() + }) + + it('keeps no fragment\'s bytes with no reader while the feed does not hold, and keeps them from the moment it holds', () => { + const feed = quietFeed() + const packets = stream(5) + const recording = recorded(packets.slice(0, 2), feed) + + expect(held(recording)).toEqual([false]) + + const reader = recording.read(1) + + recording.add(packets[2]) + recording.add(packets[3]) + + expect(held(recording)).toEqual([false, true, true]) + + reader.sent(1) + + expect(held(recording)).toEqual([false, false, true]) + + feed.holding = true + recording.add(packets[4]) + reader.end() + + expect(held(recording)).toEqual([false, false, true, true]) + + feed.holding = false + + expect(held(recording)).toEqual([false, false, false, false]) + }) + }) + + describe('the feed', () => { + it('begins a recording per stream, finds a start and takes a verdict in an older one a reader reads, and drops every one at a clear', async () => { + const feed = Object.assign(quietFeed(), { holding: true }) + const older = recorded(stream(2), feed) + const newer = recorded(stream(2, { wallClock: WALL_CLOCK + 60000 }), feed) + const reader = older.read(0) + const reading = drain(reader) + + older.end() + + expect(feed.fragmentAt(P0 + D, 'start')).toEqual({ + fragment: older.fragment(1), + recording: older, + }) + expect(feed.judged(P0 + D, true)).toEqual({ index: 1, recording: older }) + expect(older.latestShouldRecord).toBe(1) + expect(newer.latestShouldRecord).toBeUndefined() + expect(feed.judged(P0 - D, true)).toBeUndefined() + await expect(reading).resolves.toEqual([0, 1]) + + // The iterator ended with its recording, and the reader keeps what it needs until the clear ends it. + expect(reader.done).toBe(false) + + feed.clear() + + expect(reader.done).toBe(true) + expect(feed.fragmentAt(P0 + D, 'start')).toBeUndefined() + expect([older.closed, newer.closed]).toEqual([true, true]) + + newer.add(stream(1)[1]) + + expect(newer.length).toBe(0) + + { + using disposed = Object.assign(quietFeed(), { holding: true }) + + recorded(stream(1), disposed).read(0) + } + }) + + it('finds a start and takes a verdict in the newer of two recordings that hold the same place', () => { + const feed = Object.assign(quietFeed(), { holding: true }) + const older = recorded(stream(2), feed) + const newer = recorded(stream(2), feed) + + expect(feed.fragmentAt(P0 + D, 'start')?.recording).toBe(newer) + expect(feed.judged(P0 + D, true)).toEqual({ index: 1, recording: newer }) + expect([older.latestShouldRecord, newer.latestShouldRecord]).toEqual([undefined, 1]) + }) + }) + + describe('the ceiling', () => { + it('releases the oldest bytes past the ceiling, the older recording\'s first, needed or not, with one alert, and a reader reaching them ends', async () => { + const { alerts, feed } = alertingFeed() + const newerPackets = largeStream(5, { wallClock: WALL_CLOCK + 60000 }) + const older = recorded(largeStream(2), feed) + const iterator = older.read(0)[Symbol.asyncIterator]() + const newer = recorded(newerPackets.slice(0, 3), feed) + + await expect(iterator.next()).resolves.toMatchObject({ + done: false, + value: { index: 0 }, + }) + + // Four quarters stand at the ceiling, which the store may hold. + expect([ + held(older), + held(newer), + ]).toEqual([ + [true, true], + [true, true], + ]) + expect(alerts).toEqual([]) + + newer.add(newerPackets[3]) + + expect([ + held(older), + held(newer), + ]).toEqual([ + [false, true], + [true, true, true], + ]) + + newer.add(newerPackets[4]) + + expect([ + held(older), + held(newer), + ]).toEqual([ + [false, false], + [true, true, true, true], + ]) + + newer.add(newerPackets[5]) + + expect([ + held(older), + held(newer), + ]).toEqual([ + [false, false], + [false, true, true, true, true], + ]) + expect(alerts).toEqual([ + { + accessoryUUID: CAMERA, + kind: 'store-full', + level: 'warning', + sensorUUID: SENSOR, + sentence: STORE_FULL, + }, + ]) + + // The reader had yielded the first fragment, and ends at the second, whose bytes the ceiling released. + await expect(iterator.next()).resolves.toEqual({ done: true, value: undefined }) + }) + + it('keeps an episode open while the rules keep the bytes it released, ends it once they keep the store under the ceiling, and alerts the next', () => { + const { alerts, feed } = alertingFeed() + const packets = largeStream(9) + const recording = recorded(packets.slice(0, 6), feed) + const reader = recording.read(0) + + expect(held(recording)).toEqual([false, true, true, true, true]) + expect(alerts).toHaveLength(1) + + // A reading that releases nothing leaves the episode open while the reader still needs the fragment the ceiling released. + expect(recording.judged(P0, true)).toBe(true) + recording.add(packets[6]) + + expect(held(recording)).toEqual([false, false, true, true, true, true]) + expect(alerts).toHaveLength(1) + + // With the reader gone and the verdicts past them, the rules keep none of what the ceiling released, and three quarters stand under it. + expect(recording.judged(P0 + 4n * D, true)).toBe(true) + reader.end() + + expect(held(recording)).toEqual([false, false, false, true, true, true]) + + recording.add(packets[7]) + + expect(alerts).toHaveLength(1) + + recording.add(packets[8]) + + expect(held(recording)).toEqual([ + false, + false, + false, + false, + true, + true, + true, + true, + ]) + expect(alerts).toHaveLength(2) + }) + + it('ends an episode at a clear, the next store past the ceiling raising its own problem', () => { + const { alerts, feed } = alertingFeed() + + recorded(largeStream(5), feed) + feed.clear() + recorded(largeStream(5), feed) + + expect(alerts).toHaveLength(2) + }) + }) + + describe('the grace', () => { + it('keeps an ended recording for the grace, a reader holding it until the grace after its end, the last of two readers arming it', () => { + vi.useFakeTimers() + + const feed = Object.assign(quietFeed(), { holding: true }) + const recording = recorded(stream(2), feed) + + recording.end() + vi.advanceTimersByTime(SERVED_RECORDING_GRACE - 1) + + expect(feed.fragmentAt(P0 + D, 'start')?.recording).toBe(recording) + expect(feed.judged(P0 + D, true)).toEqual({ index: 1, recording }) + + const first = recording.read(1) + const second = recording.read(1) + + vi.advanceTimersByTime(SERVED_RECORDING_GRACE) + first.end() + + expect(vi.getTimerCount()).toBe(0) + + second.end() + vi.advanceTimersByTime(SERVED_RECORDING_GRACE - 1) + + expect(feed.fragmentAt(P0 + D, 'start')?.recording).toBe(recording) + + vi.advanceTimersByTime(1) + + expect(feed.fragmentAt(P0 + D, 'start')).toBeUndefined() + expect(recording.length).toBe(0) + }) + + it('leaves no timer after a clear with a reader open on an ended recording, or after disposal', () => { + vi.useFakeTimers() + + const feed = Object.assign(quietFeed(), { holding: true }) + const read = recorded(stream(1), feed) + + read.read(0) + read.end() + recorded(stream(1), feed).end() + + expect(vi.getTimerCount()).toBe(1) + + feed.clear() + + expect(vi.getTimerCount()).toBe(0) + + { + using disposed = quietFeed() + + recorded(stream(1), disposed).end() + + expect(vi.getTimerCount()).toBe(1) + } + + expect(vi.getTimerCount()).toBe(0) + }) + }) + + describe('a real muxer\'s boxes', () => { + it('places the skeleton\'s fragments by their durations from the first fragment\'s box', () => { + const writer = new ProducerReferenceTimeWriter() + const recording = recorded(skeletonPackets().map(packet => writer.writePacket(packet, WALL_CLOCK))) + + expect(recording.length).toBe(2) + expect(recording.fragment(0)?.place).toBe(P0) + expect(recording.fragment(1)?.place).toBe(P0 + (62424n << 32n) / 15360n) + expect(recording.run?.sampleEntries.get(1)).toEqual({ + codec: 'avc1.4d400a', + height: 36, + type: 'avc1', + width: 64, + }) + }) + }) +}) diff --git a/src/lib/camera/recording/ServedRecording.ts b/src/lib/camera/recording/ServedRecording.ts new file mode 100644 index 000000000..72e7d281c --- /dev/null +++ b/src/lib/camera/recording/ServedRecording.ts @@ -0,0 +1,772 @@ +import type { Buffer } from 'node:buffer' + +import type { CameraReporter, DebugWriter } from '../diagnostics/CameraReporter.js' +import type { Mp4SampleEntry, Mp4Track } from '../mp4/mp4Boxes.js' +import type { WrittenPacket } from './ProducerReferenceTimeWriter.js' + +import { NTP_FRACTION_BITS } from '../../util/ntp.js' +import { debugChannel } from '../diagnostics/debugChannels.js' + +const SERVED_RECORDING_DEBUG = debugChannel('HAP-NodeJS:Camera:ServedRecording') + +/** + * How long a recording is kept once its stream has ended and no reader reads it, in milliseconds. The hubs close a recording a few milliseconds before they + * write its last verdict: a Start that verdict draws arrives after the recording's end. A clip whose reader ends with no Stop finalizes the same span + * after that end. + */ +export const SERVED_RECORDING_GRACE = 15 * 1000 + +/** + * The most octets a camera's served recordings hold across every recording, counted on each fragment's bytes: 100 MB, read as 100,000,000 octets. + */ +export const SERVED_RECORDINGS_CEILING = 100 * 1000 * 1000 + +/** + * What a camera's served recordings raise their problem through: the camera's reporter, and the sensor the problem names. + */ +export interface ServedRecordingsOptions { + /** + * The camera's reporter, through which the recordings raise the `store-full` problem on the camera's channel, once for each episode past the ceiling. + */ + readonly reporter: CameraReporter + /** + * The camera's recorded sensor, in lowercase: the sensor its camera buffer records. + */ + readonly sensorUUID: string +} + +/** + * The initialization segment of a served recording, which the fragments after it follow. + */ +export interface ServedRun { + /** + * The initialization segment's bytes as the stream sent them. + */ + readonly initialization: Buffer + /** + * The video track the run's fragments are placed by. + */ + readonly video: Mp4Track + /** + * Each track's first sample entry, by track identifier, every track of the segment keyed and one whose entry is absent or does not read holding none. + */ + readonly sampleEntries: ReadonlyMap +} + +/** + * One fragment of a served recording, placed on the hub's timeline. + */ +export interface ServedFragment { + /** + * The fragment's index in its recording, from 0. + */ + readonly index: number + /** + * Where the fragment starts on the hub's timeline, an NTP time reduced modulo 2^64. + */ + readonly place: bigint + /** + * The fragment's duration as an NTP time span. + */ + readonly duration: bigint + /** + * The fragment's duration in its video track's timescale. + */ + readonly timescaleDuration: bigint + /** + * The fragment's bytes as the stream sent them, from its `prft` box to the end of its `mdat`, absent once they are released. + */ + 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. + */ +export class ServedReader implements AsyncIterable, Disposable { + private readonly recording: ServedRecording + + private readonly from: number + + private readonly signal?: AbortSignal + + private readonly reported = new Set() + + private ended = false + + constructor(recording: ServedRecording, from: number, signal?: AbortSignal) { + this.recording = recording + this.from = from + this.signal = signal + signal?.addEventListener('abort', this.end, { once: true }) + } + + /** + * Whether the reader has ended. + */ + get done(): boolean { + return this.ended + } + + /** + * Whether the reader still needs a fragment's bytes. + * @param index - The fragment's index. + * @returns Whether the fragment is at or past the reader's start and not yet reported sent, while the reader runs. + */ + needs(index: number): boolean { + return !this.ended && index >= this.from && !this.reported.has(index) + } + + /** + * Reports a fragment sent: its clip's object carrying it was answered, and the reader stops keeping it. + * @param index - The index the iterator yielded with the fragment. + */ + sent(index: number): void { + if (this.ended || this.reported.has(index)) { + return + } + + this.reported.add(index) + this.recording.reconcile() + } + + /** + * Ends the reader: its iterator ends and it keeps no fragment. Safe to call more than once. + */ + readonly end = (): void => { + if (this.ended) { + return + } + + this.ended = true + this.signal?.removeEventListener('abort', this.end) + this.recording.readerEnded(this) + } + + [Symbol.dispose](): void { + this.end() + } + + async* [Symbol.asyncIterator](): AsyncGenerator { + let index = this.from + + while (!this.ended) { + const fragment = this.recording.fragment(index) + + if (fragment !== undefined) { + // A fragment whose bytes are gone ends the reader's run, as its recording's end does. + if (fragment.bytes === undefined) { + return + } + + yield Object.freeze({ ...fragment, bytes: fragment.bytes }) + index++ + + continue + } + + if (this.recording.closed) { + return + } + + await this.recording.changed(this.signal) + } + } +} + +/* One recording as a camera's recording stream served it, kept for the clips a hub commands on it: the one initialization segment its stream sends + * first, and the fragments after it, placed on the hub's timeline, the first at the time its own prft box carries and each later one at the end of the + * one before, by the video track's sample durations. + * + * What it keeps follows the hub's own verdicts. Each fragment keeps its place and duration for the recording's life, and its bytes only while something + * can still ask for them: a reader that needs it, or the hub's next Start. Every Start a hub writes names the fragment a verdict just judged or + * the one before it: while the feed holds, a recording keeps every fragment until its first verdict and, after it, every fragment from the one before + * its latest judged fragment onward. No count of fragments or figure of bytes enters the rule, which is read again at each change that could move it. The + * feed's ceiling stands over it, releasing the oldest bytes of every recording past that ceiling whoever needs them. + */ +export class ServedRecording { + private readonly feed: ServedRecordings + + private servedRun?: ServedRun + + private readonly fragments: (ServedFragment & { bytes?: Buffer })[] = [] + + private readonly readers = new Set() + + private readonly waiters = new Set<() => void>() + + // The octets of each fragment the feed's ceiling released, by index, while the release rule still keeps it. + private readonly cut = new Map() + + // Where the next fragment starts on the hub's timeline, once the first has set it. + private next?: bigint + + // The lowest index whose bytes may still be held, every fragment below it released. + private lowestHeld = 0 + + private latestJudged?: number + + private latestRecorded?: number + + private ended = false + + private unusable = false + + private dropped = false + + private grace?: ReturnType + + constructor(feed: ServedRecordings) { + this.feed = feed + } + + /** + * Whether the recording takes no more fragments: its stream ended, it turned unusable, or the feed dropped it. + */ + get closed(): boolean { + return this.ended || this.unusable || this.dropped + } + + /** + * The index of the latest fragment the hub has judged Should Record, which bounds what a clip on the recording may upload while no stop is set, a + * clip's own hold at a Should Not Record verdict bounding it further. + */ + get latestShouldRecord(): number | undefined { + return this.latestRecorded + } + + /** + * The number of fragments the recording has placed. + */ + get length(): number { + return this.fragments.length + } + + /** + * The recording's initialization segment, once its stream has sent it. + */ + get run(): ServedRun | undefined { + return this.servedRun + } + + /** + * A fragment of the recording. + * @param index - The fragment's index. + * @returns The fragment, its bytes absent once released. + */ + fragment(index: number): ServedFragment | undefined { + return this.fragments[index] + } + + /** + * Records what the writer read of one packet. A packet with no reading is skipped, the end marker among them. A fragment before any initialization + * segment, or one whose video run has no duration, marks the recording unusable, which takes no more fragments. Never throws. + * @param written - The packet as the writer wrote it. + */ + add(written: WrittenPacket): void { + if (this.closed || (written.initialization === undefined && written.fragments.length === 0)) { + return + } + + if (written.initialization !== undefined) { + const { bytes, sampleEntries, video } = written.initialization + + this.servedRun = { initialization: bytes, sampleEntries, video } + } + + for (const { bytes, ntpTime, runs } of written.fragments) { + const video = this.servedRun?.video + const timescaleDuration = runs.find(({ trackId }) => trackId === video?.id)?.duration + + // A run whose samples sum to no time has no duration, as a run with no samples has none, and no fragment is placed lasting zero seconds. + if (video === undefined || timescaleDuration === undefined || timescaleDuration === 0n) { + const cause = (video === undefined) + ? 'no initialization segment before it' + : 'no duration for its video run' + + this.unusable = true + this.feed.debug('recording-unusable', () => ({ + cause, + sentence: `A served recording turned unusable at a fragment it cannot place: ${cause}.`, + })) + + break + } + + const place = this.next ?? ntpTime + const duration = (timescaleDuration << NTP_FRACTION_BITS) / BigInt(video.timescale) + + this.fragments.push({ + bytes, + duration, + index: this.fragments.length, + place, + timescaleDuration, + }) + this.feed.tally(bytes.length) + this.next = BigInt.asUintN(64, place + duration) + } + + this.reconcile() + } + + /** + * Marks the recording's stream ended, and it takes no more fragments. Safe to call more than once. + */ + end(): void { + if (this.ended) { + return + } + + this.ended = true + this.reconcile() + } + + /** + * Finds the fragment whose start or end lies within half that fragment's duration of a place, inclusive, the earlier answering when two do. + * @param place - An NTP time on the hub's timeline. + * @param edge - Whether the place names a fragment's start or its end. + * @returns The fragment, with no bytes when they are released, or `undefined` when no boundary lies within reach. + */ + fragmentAt(place: bigint, edge: 'start' | 'end'): ServedFragment | undefined { + if (this.dropped) { + return undefined + } + + return this.fragments.find((fragment) => { + const boundary = edge === 'start' + ? fragment.place + : BigInt.asUintN(64, fragment.place + fragment.duration) + const apart = distance(boundary, place) + + return (apart < 0n + ? -apart + : apart) * 2n <= fragment.duration + }) + } + + /** + * Records the hub's verdict on the fragment a Start would name at a place, moving the latest judged fragment forward and never back, and the latest + * fragment judged Should Record with it when the verdict says so. + * @param place - The verdict's place on the hub's timeline. + * @param record - Whether the verdict reads Should Record. + * @returns Whether a fragment's start lay within reach of the place. + */ + judged(place: bigint, record: boolean): boolean { + const fragment = this.fragmentAt(place, 'start') + + if (fragment === undefined) { + this.feed.debug('verdict-unplaced', () => ({ sentence: 'A verdict names no fragment of a served recording.' })) + + return false + } + + if (this.latestJudged === undefined || fragment.index >= this.latestJudged) { + this.latestJudged = fragment.index + + if (record) { + this.latestRecorded = fragment.index + } + } + + this.reconcile() + + return true + } + + /** + * Opens a reader at a fragment. A reader opened on a dropped recording has already ended. + * @param from - The index of the reader's first fragment. + * @param signal - A signal that ends the reader. + * @returns The reader. + */ + read(from: number, signal?: AbortSignal): ServedReader { + const reader = new ServedReader(this, from, signal) + + if (this.dropped || signal?.aborted) { + reader.end() + + return reader + } + + this.readers.add(reader) + clearTimeout(this.grace) + this.grace = undefined + + return reader + } + + /** + * Waits for the recording to change: every wait wakes at each reading of its release rule and at its drop. + * @param signal - A signal that ends the wait. + * @returns A promise that resolves at the next change, or once the signal aborts. + */ + async changed(signal?: AbortSignal): Promise { + if (signal?.aborted) { + return + } + + await new Promise((resolve) => { + const wake = (): void => { + this.waiters.delete(wake) + signal?.removeEventListener('abort', wake) + resolve() + } + + this.waiters.add(wake) + signal?.addEventListener('abort', wake, { once: true }) + }) + } + + /** + * Reads the release rule again, then the feed's ceiling, and wakes every wait. The feed calls it when its holding changes, and a reader when it reports a + * fragment sent. + */ + reconcile(): void { + for (let index = this.lowestHeld; index < this.fragments.length; index++) { + const fragment = this.fragments[index] + + if (fragment.bytes !== undefined && !this.keeps(index)) { + this.release(fragment) + } + } + + this.feed.bound() + this.passReleased() + this.armGrace() + + for (const wake of [...this.waiters]) { + wake() + } + } + + /** + * Releases the bytes of the recording's lowest fragment that holds them, whoever needs them, for the feed's ceiling. + * @returns Whether a fragment's bytes were released, `false` for a recording that holds none. + */ + releaseOldest(): boolean { + this.passReleased() + + const fragment = this.fragments.at(this.lowestHeld) + + if (fragment === undefined) { + return false + } + + this.cut.set(fragment.index, this.release(fragment)) + this.passReleased() + + return true + } + + /** + * The octets the ceiling released that the release rule would still keep, which the feed adds to the octets held to read whether its store stands at or + * under the ceiling by the rule alone. A fragment the rule no longer keeps is forgotten. + * @returns The octets. + */ + owed(): number { + let octets = 0 + + for (const [index, length] of this.cut) { + if (this.keeps(index)) { + octets += length + } else { + this.cut.delete(index) + } + } + + return octets + } + + /** + * Leaves a reader that ended: it keeps no fragment and the grace may start. + * @param reader - The reader. + */ + readerEnded(reader: ServedReader): void { + if (this.readers.delete(reader)) { + this.reconcile() + } + } + + /** + * Drops the recording whole, verdicts and all: it ends every reader, takes no more fragments, releases its timer and arms none again. The feed calls it. + */ + drop(): void { + if (this.dropped) { + return + } + + this.dropped = true + + for (const reader of [...this.readers]) { + reader.end() + } + + clearTimeout(this.grace) + this.grace = undefined + + for (let index = this.lowestHeld; index < this.fragments.length; index++) { + this.release(this.fragments[index]) + } + + this.cut.clear() + this.fragments.length = 0 + this.servedRun = undefined + this.lowestHeld = 0 + this.latestJudged = undefined + this.latestRecorded = undefined + + for (const wake of [...this.waiters]) { + wake() + } + } + + // Whether the release rule keeps a fragment's bytes: while the feed holds, every fragment from the one before the latest judged on, and every one a + // reader still needs. + private keeps(index: number): boolean { + const floor = this.latestJudged === undefined + ? 0 + : this.latestJudged - 1 + + if (this.feed.holding && index >= floor) { + return true + } + + for (const reader of this.readers) { + if (reader.needs(index)) { + return true + } + } + + return false + } + + // Releases a fragment's bytes, which the feed stops counting. + private release(fragment: ServedFragment & { bytes?: Buffer }): number { + const length = fragment.bytes?.length ?? 0 + + fragment.bytes = undefined + this.feed.tally(-length) + + return length + } + + // Moves the lowest index that may hold bytes past every fragment released. + private passReleased(): void { + while (this.lowestHeld < this.fragments.length && this.fragments[this.lowestHeld].bytes === undefined) { + this.lowestHeld++ + } + } + + // The grace starts once the stream has ended and no reader reads, on one unreferenced timer, and ends by dropping the recording if no reader opened. + private armGrace(): void { + if (!this.ended || this.dropped || this.readers.size > 0 || this.grace !== undefined) { + return + } + + this.grace = setTimeout(() => { + this.grace = undefined + this.feed.dropRecording(this) + }, SERVED_RECORDING_GRACE) + this.grace.unref() + } +} + +/** + * The recordings one camera's recording stream served, kept for its clips: one begun at each stream's start, each kept while its stream runs or a reader + * reads it and for {@link SERVED_RECORDING_GRACE} after its stream has ended and no reader reads it. A Start and a verdict find their fragment across + * every recording kept, newest first. While the feed does not hold, which it does not until the camera is provisioned for uploads, a recording keeps no + * fragment's bytes but those a reader needs. + * + * The bytes every recording holds stay at or under {@link SERVED_RECORDINGS_CEILING}, read again at each reading of a recording's release rule and at each + * drop. Past it the oldest bytes held go, the oldest recording's lowest fragment first, whoever needs them, and the episode raises one `store-full` + * problem. The episode ends at a reading that releases nothing once the bytes the release rules keep, those the ceiling released among them, stand at or + * under the ceiling again, which is why a store the rules keep full is told of once however many fragments it releases. Under the ceiling every release is the rule's. + */ +export class ServedRecordings implements Disposable { + // Every recording kept, oldest first. + private readonly recordings: ServedRecording[] = [] + + /** + * The camera's reporter's debug events on the served recordings' debug name, which each recording of the feed writes through as well. + */ + readonly debug: DebugWriter + + private readonly options: ServedRecordingsOptions + + private held = false + + // The octets of every fragment's bytes the recordings hold. + private octets = 0 + + // Whether an episode past the ceiling is open, its problem raised. + private full = false + + /** + * Makes a camera's served recordings. + * @param options - The camera's reporter and the sensor the problem names. + */ + constructor(options: ServedRecordingsOptions) { + this.options = options + this.debug = options.reporter.writer(SERVED_RECORDING_DEBUG) + } + + /** + * Whether the camera is provisioned for uploads, which means its recordings keep fragments for the hub's next Start. + */ + get holding(): boolean { + return this.held + } + + set holding(holding: boolean) { + if (holding === this.held) { + return + } + + this.held = holding + + for (const recording of this.recordings) { + recording.reconcile() + } + } + + /** + * Begins the recording of one recording stream. + * @returns The recording, which the stream adds each written packet to and ends at its close. + */ + begin(): ServedRecording { + const recording = new ServedRecording(this) + + this.recordings.push(recording) + + return recording + } + + /** + * Finds a fragment by a place across every recording kept, newest first. + * @param place - An NTP time on the hub's timeline. + * @param edge - Whether the place names a fragment's start or its end. + * @returns The fragment and its recording, or `undefined` when no recording holds a boundary within reach. + */ + fragmentAt(place: bigint, edge: 'start' | 'end'): { fragment: ServedFragment, recording: ServedRecording } | undefined { + for (const recording of this.recordings.toReversed()) { + const fragment = recording.fragmentAt(place, edge) + + if (fragment !== undefined) { + return { fragment, recording } + } + } + + return undefined + } + + /** + * Records a hub's verdict on the newest recording holding a fragment that starts within reach of its place. + * @param place - The verdict's place on the hub's timeline. + * @param record - Whether the verdict reads Should Record. + * @returns The recording and the index of the fragment the verdict names, or `undefined` when no recording holds a fragment start within reach. + */ + judged(place: bigint, record: boolean): { index: number, recording: ServedRecording } | undefined { + const found = this.fragmentAt(place, 'start') + + if (found === undefined) { + this.debug('verdict-unplaced-anywhere', () => ({ sentence: 'A verdict names no fragment of any served recording.' })) + + return undefined + } + + found.recording.judged(place, record) + + return { index: found.fragment.index, recording: found.recording } + } + + /** + * Ends and drops every recording, each drop ending its readers and releasing its timer. A stream still running adds nothing to its dropped recording. + */ + clear(): void { + for (const recording of this.recordings.splice(0)) { + recording.end() + recording.drop() + } + + this.bound() + } + + /** + * Leaves a recording whose grace ended, dropping it. + * @param recording - The recording. + */ + dropRecording(recording: ServedRecording): void { + const index = this.recordings.indexOf(recording) + + if (index !== -1) { + this.recordings.splice(index, 1) + } + + recording.drop() + this.bound() + } + + /** + * Counts the octets a recording takes or releases. + * @param octets - The octets, negative for bytes released. + */ + tally(octets: number): void { + this.octets += octets + } + + /** + * Reads the ceiling again: past it the oldest bytes held go, oldest recording first, raising the episode's one problem, and an open episode ends at a + * reading that releases nothing once the bytes the release rules keep stand at or under the ceiling. + */ + bound(): void { + let released = false + + for (const recording of this.recordings) { + while (this.octets > SERVED_RECORDINGS_CEILING && recording.releaseOldest()) { + released = true + } + } + + if (released) { + if (!this.full) { + this.full = true + this.raise() + } + + return + } + + if (this.full && this.octets + this.recordings.reduce((owed, recording) => owed + recording.owed(), 0) <= SERVED_RECORDINGS_CEILING) { + this.full = false + } + } + + [Symbol.dispose](): void { + this.clear() + } + + // Raises the problem of an episode past the ceiling, naming the camera's recorded sensor. + private raise(): void { + const { reporter, sensorUUID } = this.options + + reporter.problem({ + kind: 'store-full', + level: 'warning', + sensorUUID, + sentence: `The camera that records the video sensor "${sensorUUID}" held more than the ceiling of ${SERVED_RECORDINGS_CEILING} octets in the recordings ` + + 'it served: the library released their oldest bytes, and an upload that reaches them ends at its last whole segment.', + }) + } +} diff --git a/src/lib/camera/recording/clipPackaging.spec.ts b/src/lib/camera/recording/clipPackaging.spec.ts new file mode 100644 index 000000000..0b65ffcbb --- /dev/null +++ b/src/lib/camera/recording/clipPackaging.spec.ts @@ -0,0 +1,193 @@ +import { describe, expect, it } from 'vitest' + +import { hvc1SampleEntry, initializationSegment, mp4aSampleEntry } from '../../../test-utils/mp4Fixtures.js' +import { + bandwidthsOf, + closingMediaPlaylist, + codecsOf, + CONTENT_TYPES, + extinfDuration, + initializationPath, + MEDIA_PLAYLIST, + MULTIVARIANT_PLAYLIST, + multivariantPlaylist, + openingMediaPlaylist, + segmentPath, + sessionFolder, +} from './clipPackaging.js' +import { ProducerReferenceTimeWriter } from './ProducerReferenceTimeWriter.js' + +const KEY = 'METHOD=AES-256-GCM,URI="hksv3:10004000.key"' + +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', () => { + const [named, partial] = [ + multivariantPlaylist({ + average: 400000, + codecs: 'avc1.4d0028,mp4a.40.2', + keyAttributes: KEY, + peak: 450000, + resolution: { height: 1080, width: 1920 }, + }), + multivariantPlaylist({ average: 1, keyAttributes: KEY, peak: 2 }), + ] + const header = [ + '#EXTM3U', + '#EXT-X-VERSION:7', + '#EXT-X-INDEPENDENT-SEGMENTS', + `#EXT-X-SESSION-KEY:${KEY}`, + '', + ] + + expect(named).toBe([ + ...header, + '#EXT-X-STREAM-INF:BANDWIDTH=450000,AVERAGE-BANDWIDTH=400000,RESOLUTION=1920x1080,CODECS="avc1.4d0028,mp4a.40.2"', + 'high/index.m3u8', + '', + ].join('\n')) + expect(partial).toBe([ + ...header, + '#EXT-X-STREAM-INF:BANDWIDTH=2,AVERAGE-BANDWIDTH=1', + 'high/index.m3u8', + '', + ].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', () => { + expect(openingMediaPlaylist({ keyAttributes: KEY, targetDuration: 4 })).toBe([ + '#EXTM3U', + '#EXT-X-VERSION:7', + '#EXT-X-TARGETDURATION:4', + '#EXT-X-MEDIA-SEQUENCE:1001', + '#EXT-X-PLAYLIST-TYPE:EVENT', + '#EXT-X-INDEPENDENT-SEGMENTS', + '#EXT-X-MAP:URI="high.init"', + `#EXT-X-KEY:${KEY}`, + '', + ].join('\n')) + }) + + it('writes the closing media playlist listing every segment at six decimals, its target the longest rounded up, and its end', () => { + expect(closingMediaPlaylist({ + keyAttributes: KEY, + segments: [ + { initialization: 1, seconds: 4 }, + { initialization: 1, seconds: 3.9666666 }, + { initialization: 1, seconds: 4.1 }, + ], + })).toBe([ + '#EXTM3U', + '#EXT-X-VERSION:7', + '#EXT-X-TARGETDURATION:5', + '#EXT-X-MEDIA-SEQUENCE:1001', + '#EXT-X-PLAYLIST-TYPE:EVENT', + '#EXT-X-INDEPENDENT-SEGMENTS', + '#EXT-X-MAP:URI="high.init"', + `#EXT-X-KEY:${KEY}`, + '#EXTINF:4.000000,', + 'segment_1001.m4s', + '#EXTINF:3.966667,', + 'segment_1002.m4s', + '#EXTINF:4.100000,', + 'segment_1003.m4s', + '#EXT-X-ENDLIST', + '', + ].join('\n')) + }) + + it('opens a discontinuity with the later initialization segment\'s map named by its order, and its key line', () => { + expect(closingMediaPlaylist({ + keyAttributes: KEY, + segments: [ + { initialization: 1, seconds: 4 }, + { initialization: 2, seconds: 4 }, + { initialization: 2, seconds: 2.5 }, + ], + })).toBe([ + '#EXTM3U', + '#EXT-X-VERSION:7', + '#EXT-X-TARGETDURATION:4', + '#EXT-X-MEDIA-SEQUENCE:1001', + '#EXT-X-PLAYLIST-TYPE:EVENT', + '#EXT-X-INDEPENDENT-SEGMENTS', + '#EXT-X-MAP:URI="high.init"', + `#EXT-X-KEY:${KEY}`, + '#EXTINF:4.000000,', + 'segment_1001.m4s', + '#EXT-X-DISCONTINUITY', + '#EXT-X-MAP:URI="high_2.init"', + `#EXT-X-KEY:${KEY}`, + '#EXTINF:4.000000,', + 'segment_1002.m4s', + '#EXTINF:2.500000,', + 'segment_1003.m4s', + '#EXT-X-ENDLIST', + '', + ].join('\n')) + }) + + it('names every path and type, a segment\'s duration header at five decimals, and the codecs and bit rates read from the media', () => { + expect(sessionFolder(17n)).toBe('session_17/') + expect([ + MULTIVARIANT_PLAYLIST, + MEDIA_PLAYLIST, + initializationPath(1), + initializationPath(2), + segmentPath(1001), + ]).toEqual([ + 'index.m3u8', + 'high/index.m3u8', + 'high/high.init', + 'high/high_2.init', + 'high/segment_1001.m4s', + ]) + expect(CONTENT_TYPES).toEqual({ initialization: 'video/mp4', playlist: 'application/vnd.apple.mpegurl', segment: 'video/iso.segment' }) + expect([ + extinfDuration(4), + extinfDuration(3.9666666), + ]).toEqual(['4.00000', '3.96667']) + expect(codecsOf([ + { codec: 'avc1.4d0028', type: 'avc1' }, + { codec: 'mp4a.40.2', type: 'mp4a' }, + ])).toBe('avc1.4d0028,mp4a.40.2') + expect(codecsOf([ + { codec: 'avc1.4d0028', type: 'avc1' }, + { type: 'opus' }, + ])).toBeUndefined() + expect(bandwidthsOf([ + { bytes: 200000, seconds: 4 }, + { bytes: 100000, seconds: 3 }, + ])).toEqual({ average: 342858, peak: 400000 }) + }) + + it('names an HEVC rendition\'s codecs in the multivariant playlist as its initialization segment\'s sample entries read', () => { + const { initialization } = new ProducerReferenceTimeWriter().writePacket(initializationSegment( + { + handler: 'vide', + id: 1, + sampleEntry: hvc1SampleEntry(1920, 1080), + timescale: 90000, + }, + { + handler: 'soun', + id: 2, + sampleEntry: mp4aSampleEntry(2), + timescale: 16000, + }, + ), Date.parse('2026-11-12T00:00:00.000Z')) + + expect(multivariantPlaylist({ + average: 400000, + codecs: codecsOf(initialization!.sampleEntries.values()), + keyAttributes: KEY, + peak: 450000, + })).toContain('#EXT-X-STREAM-INF:BANDWIDTH=450000,AVERAGE-BANDWIDTH=400000,CODECS="hvc1.1.6.L120.90,mp4a.40.2"\n') + }) + + it('leaves the codecs out when a track holds no sample entry beside one with a codec', () => { + expect(codecsOf([ + undefined, + { codec: 'mp4a.40.2', type: 'mp4a' }, + ])).toBeUndefined() + }) +}) diff --git a/src/lib/camera/recording/clipPackaging.ts b/src/lib/camera/recording/clipPackaging.ts new file mode 100644 index 000000000..7a2ea5d1e --- /dev/null +++ b/src/lib/camera/recording/clipPackaging.ts @@ -0,0 +1,263 @@ +/* A clip's packaging as an HLS session folder over CMAF: its paths beneath the publishing point, the content type of each object, and the text of its + * playlists. Every function is pure. The forms are those of a clip the service accepts and plays back: HLS version 7, one rendition + * named `high` holding the recording's tracks as the camera served them, segments numbered from 1001, `#EXT-X-PLAYLIST-TYPE:EVENT` in each media playlist + * and each segment's duration in an `x-extinf-duration` header. A later initialization segment, after a discontinuity, is named by its order in the clip. + */ +import type { Mp4SampleEntry } from '../mp4/mp4Boxes.js' + +/** + * The one rendition of a clip. + */ +export const RENDITION = 'high' + +/** + * The number of a clip's first segment. + */ +export const FIRST_SEGMENT = 1001 + +/** + * The content type of each kind of object a clip uploads. + */ +export const CONTENT_TYPES = Object.freeze({ + initialization: 'video/mp4', + playlist: 'application/vnd.apple.mpegurl', + segment: 'video/iso.segment', +}) + +/** + * The multivariant playlist's path within a session folder. + */ +export const MULTIVARIANT_PLAYLIST = 'index.m3u8' + +/** + * The media playlist's path within a session folder. + */ +export const MEDIA_PLAYLIST = `${RENDITION}/index.m3u8` + +/** + * The header carrying a segment's duration. + */ +export const EXTINF_DURATION_HEADER = 'x-extinf-duration' + +/** + * One segment as the closing media playlist lists it. + */ +export interface PlaylistSegment { + /** + * The segment's duration in seconds. + */ + seconds: number + /** + * The order in the clip of the initialization segment the segment follows, from 1. + */ + initialization: number +} + +/** + * A clip's session folder beneath the publishing point. + * @param clip - The clip's number. + * @returns The folder, ending in a slash. + */ +export function sessionFolder(clip: bigint): string { + return `session_${clip}/` +} + +/** + * An initialization segment's name within the rendition, as its media playlist names it. + * @param order - The segment's order in the clip, from 1. + * @returns `high.init` for the first, `high_.init` for the k-th from the second. + */ +export function initializationName(order: number): string { + return order === 1 + ? `${RENDITION}.init` + : `${RENDITION}_${order}.init` +} + +/** + * An initialization segment's path within a session folder. + * @param order - The segment's order in the clip, from 1. + * @returns The path. + */ +export function initializationPath(order: number): string { + return `${RENDITION}/${initializationName(order)}` +} + +/** + * A segment's name within the rendition, as its media playlist names it. + * @param sequence - The segment's number, from {@link FIRST_SEGMENT}. + * @returns The name. + */ +export function segmentName(sequence: number): string { + return `segment_${sequence}.m4s` +} + +/** + * A segment's path within a session folder. + * @param sequence - The segment's number, from {@link FIRST_SEGMENT}. + * @returns The path. + */ +export function segmentPath(sequence: number): string { + return `${RENDITION}/${segmentName(sequence)}` +} + +/** + * A segment's `x-extinf-duration` value. + * @param seconds - The segment's duration in seconds. + * @returns The duration at five decimals. + */ +export function extinfDuration(seconds: number): string { + return seconds.toFixed(5) +} + +/** + * The rendition's codecs as the multivariant playlist's `CODECS` attribute names them, read from the initialization segment's sample entries. + * @param entries - Each track's sample entry, or none for a track whose entry is absent or does not read. + * @returns Every entry's codec, or `undefined` when a track holds no entry or an entry has no codec, which means the attribute is left out rather than naming the + * rendition in part. + */ +export function codecsOf(entries: Iterable): string | undefined { + const codecs: string[] = [] + + for (const entry of entries) { + if (entry?.codec === undefined) { + return undefined + } + + codecs.push(entry.codec) + } + + return codecs.length === 0 + ? undefined + : codecs.join(',') +} + +/** + * A rendition's peak and average bit rates over segments, as the multivariant playlist's `BANDWIDTH` and `AVERAGE-BANDWIDTH` state them. + * @param segments - Each segment's size in bytes and duration in seconds. + * @returns The peak, the largest of each segment's size over its duration, and the average, the total size over the total duration, each in bits per + * second rounded up. + */ +export function bandwidthsOf(segments: Iterable<{ bytes: number, seconds: number }>): { average: number, peak: number } { + let peak = 0 + let bytes = 0 + let seconds = 0 + + for (const segment of segments) { + peak = Math.max(peak, (segment.bytes * 8) / segment.seconds) + bytes += segment.bytes + seconds += segment.seconds + } + + return { + average: seconds === 0 + ? 0 + : Math.ceil((bytes * 8) / seconds), + peak: Math.ceil(peak), + } +} + +/** + * The multivariant playlist, naming the one rendition. + * @param options - The rendition's attributes. + * @param options.average - Its average bit rate. + * @param options.codecs - Its codecs, left out when absent. + * @param options.keyAttributes - The key's attributes, which the session key line after `#EXT-X-INDEPENDENT-SEGMENTS` carries. + * @param options.peak - Its peak bit rate. + * @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. + * @returns The playlist, every line ending in a newline. + */ +export function multivariantPlaylist({ average, codecs, keyAttributes, peak, resolution }: { + average: number + codecs?: string + keyAttributes: string + peak: number + resolution?: { height: number, width: number } +}): string { + const attributes = [ + `BANDWIDTH=${peak}`, + `AVERAGE-BANDWIDTH=${average}`, + ...(resolution === undefined + ? [] + : [`RESOLUTION=${resolution.width}x${resolution.height}`]), + ...(codecs === undefined + ? [] + : [`CODECS="${codecs}"`]), + ] + + return lines([ + '#EXTM3U', + '#EXT-X-VERSION:7', + '#EXT-X-INDEPENDENT-SEGMENTS', + `#EXT-X-SESSION-KEY:${keyAttributes}`, + '', + `#EXT-X-STREAM-INF:${attributes.join(',')}`, + MEDIA_PLAYLIST, + ]) +} + +/** + * The media playlist's opening form, sent before any segment: its header and its first initialization segment's map and key line. + * @param options - The playlist's attributes. + * @param options.keyAttributes - The key's attributes, which the key line after the map carries. + * @param options.targetDuration - The longest segment the clip expects, in whole seconds. + * @returns The playlist, every line ending in a newline. + */ +export function openingMediaPlaylist({ keyAttributes, targetDuration }: { keyAttributes: string, targetDuration: number }): string { + return lines(mediaHeader(targetDuration, keyAttributes)) +} + +/** + * 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. + * @param options - The playlist's attributes. + * @param options.keyAttributes - The key's attributes, which the key line after each map carries. + * @param options.segments - Each segment the clip sent, in order. + * @returns The playlist, every line ending in a newline. + */ +export function closingMediaPlaylist({ keyAttributes, segments }: { keyAttributes: string, segments: readonly PlaylistSegment[] }): string { + const body: string[] = [] + let initialization = 1 + + for (const [index, segment] of segments.entries()) { + if (segment.initialization !== initialization) { + initialization = segment.initialization + body.push('#EXT-X-DISCONTINUITY', ...mapLines(initialization, keyAttributes)) + } + + body.push(`#EXTINF:${segment.seconds.toFixed(6)},`, segmentName(FIRST_SEGMENT + index)) + } + + return lines([ + ...mediaHeader(Math.ceil(Math.max(0, ...segments.map(({ seconds }) => seconds))), keyAttributes), + ...body, + '#EXT-X-ENDLIST', + ]) +} + +// A media playlist's header, through its first initialization segment's map and key line. +function mediaHeader(targetDuration: number, keyAttributes: string): string[] { + return [ + '#EXTM3U', + '#EXT-X-VERSION:7', + `#EXT-X-TARGETDURATION:${targetDuration}`, + `#EXT-X-MEDIA-SEQUENCE:${FIRST_SEGMENT}`, + '#EXT-X-PLAYLIST-TYPE:EVENT', + '#EXT-X-INDEPENDENT-SEGMENTS', + ...mapLines(1, keyAttributes), + ] +} + +// An initialization segment's map, then the key line. +function mapLines(order: number, keyAttributes: string): string[] { + return [ + `#EXT-X-MAP:URI="${initializationName(order)}"`, + `#EXT-X-KEY:${keyAttributes}`, + ] +} + +// A playlist's text: every line ends in a newline. +function lines(text: readonly string[]): string { + return `${text.join('\n')}\n` +} diff --git a/src/lib/camera/recording/clipSealing.spec.ts b/src/lib/camera/recording/clipSealing.spec.ts new file mode 100644 index 000000000..b5c095e45 --- /dev/null +++ b/src/lib/camera/recording/clipSealing.spec.ts @@ -0,0 +1,66 @@ +import { Buffer } from 'node:buffer' +import { createDecipheriv } from 'node:crypto' + +import { describe, expect, it } from 'vitest' + +import { contentKeyOf, keyAttributes, seal } 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 = { + key: Buffer.from(Array.from({ length: 32 }, (_, index) => index)), + keyNumber: 0x1000n, +} +const CONTENT_KEY = 'bc6ca5e67f07754fd51de3d56c9e9af2f8343636248ae1f1cd74fe09df84a317' + +describe('clipSealing', () => { + it('derives the content key and its identifier from the Camera Key and its number', () => { + const contentKey = contentKeyOf(CAMERA_KEY) + + expect(contentKey.key.toString('hex')).toBe(CONTENT_KEY) + expect(contentKey.identifier).toBe(0x10004000n) + expect(keyAttributes(contentKey)).toBe('METHOD=AES-256-GCM,URI="hksv3:10004000.key"') + }) + + it('seals a segment whole as a 16-byte IV, its ciphertext and a 16-byte tag, which decrypts with no additional data', () => { + const contentKey = contentKeyOf(CAMERA_KEY) + const segment = Buffer.from('a media segment, prft, moof and mdat') + const sealed = seal(contentKey, segment) + const decipher = createDecipheriv('aes-256-gcm', contentKey.key, sealed.subarray(0, 16), { authTagLength: 16 }) + + decipher.setAuthTag(sealed.subarray(-16)) + + expect(sealed).toHaveLength(segment.length + 32) + expect(Buffer.concat([ + decipher.update(sealed.subarray(16, -16)), + decipher.final(), + ])).toEqual(segment) + }) + + it('takes a fresh IV for every seal', () => { + const contentKey = contentKeyOf(CAMERA_KEY) + const segment = Buffer.alloc(64, 0x2A) + + expect(seal(contentKey, segment).subarray(0, 16)).not.toEqual(seal(contentKey, segment).subarray(0, 16)) + }) + + it.each([ + [ + 'a key of 31 bytes', + { + key: Buffer.alloc(31), + keyNumber: 1n, + }, + 'A Camera Key must be thirty-two bytes long.', + ], + [ + 'a key number that does not fit in 48 bits', + { + key: Buffer.alloc(32), + keyNumber: 2n ** 48n, + }, + 'A Camera Key\'s number must fit in 48 bits.', + ], + ])('refuses %s', (_name, cameraKey, message) => { + expect(() => contentKeyOf(cameraKey)).toThrow(new RangeError(message)) + }) +}) diff --git a/src/lib/camera/recording/clipSealing.ts b/src/lib/camera/recording/clipSealing.ts new file mode 100644 index 000000000..62db64eff --- /dev/null +++ b/src/lib/camera/recording/clipSealing.ts @@ -0,0 +1,83 @@ +import type { CameraKeyPayload } from '../capabilities/provisioning.js' + +import { Buffer } from 'node:buffer' +import { createCipheriv, hkdfSync, randomBytes } from 'node:crypto' + +// The content key's derivation from the Camera Key, and the length of each part of a sealed segment. +const CONTENT_KEY_INFO = 'HomeKit 1.0 CMAF Content' +const KEY_LENGTH = 32 +const IV_LENGTH = 16 +const TAG_LENGTH = 16 + +// A key number takes the identifier's bits above its low 16, which carry the content key's tag, and must fit in 48 bits. +const KEY_NUMBER_LIMIT = 2n ** 48n +const CONTENT_KEY_TAG = 0x4000n + +/** + * 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. + */ +export interface ContentKey { + /** + * The AES-256-GCM key, thirty-two bytes. + */ + readonly key: Buffer + /** + * The key's identifier: the Camera Key's number shifted above 16 bits with the content key's tag set. + */ + readonly identifier: bigint +} + +/** + * Derives a clip's content key from the Camera Key a hub wrote: HKDF-SHA256 over the key with an empty salt and the content info, thirty-two bytes. + * @param cameraKey - The Camera Key and its number. + * @returns The content key and its identifier. + * @throws RangeError for a key that is not thirty-two bytes long or a key number of 48 bits or more. + */ +export function contentKeyOf(cameraKey: CameraKeyPayload): ContentKey { + const { key, keyNumber } = cameraKey + + if (key.length !== KEY_LENGTH) { + throw new RangeError('A Camera Key must be thirty-two bytes long.') + } + + if (keyNumber < 0n || keyNumber >= KEY_NUMBER_LIMIT) { + throw new RangeError('A Camera Key\'s number must fit in 48 bits.') + } + + return { + identifier: (keyNumber << 16n) | CONTENT_KEY_TAG, + key: Buffer.from(hkdfSync('sha256', key, Buffer.alloc(0), CONTENT_KEY_INFO, KEY_LENGTH)), + } +} + +/** + * The attributes of the key lines a clip's playlists carry, naming the key its media segments are sealed under. + * @param contentKey - The clip's content key. + * @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"` +} + +/** + * Seals one media segment whole under a clip's content key. + * @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. + */ +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 }) + + return Buffer.concat([ + iv, + cipher.update(segment), + cipher.final(), + cipher.getAuthTag(), + ]) +} diff --git a/src/lib/camera/recording/signingRequest.spec.ts b/src/lib/camera/recording/signingRequest.spec.ts new file mode 100644 index 000000000..0c816ce0b --- /dev/null +++ b/src/lib/camera/recording/signingRequest.spec.ts @@ -0,0 +1,111 @@ +import type { KeyObject } from 'node:crypto' + +import { Buffer } from 'node:buffer' +import { spawnSync } from 'node:child_process' +import { createPublicKey, randomBytes, verify } from 'node:crypto' + +import { describe, expect, it } from 'vitest' + +import { createSigningRequest, NONCE_LENGTH } from './signingRequest.js' + +const SUBJECT = '0E:AE:FC:45:7B:91' +const NONCE = Buffer.from('202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f', 'hex') + +// The request info's fixed opening for SUBJECT, through its subject, and the opening every P-256 SubjectPublicKeyInfo shares. +const INFO_OPENING = '307e020100301c311a301806035504030c1130453a41453a46433a34353a37423a3931' +const SPKI_OPENING = '3059301306072a8648ce3d020106082a8648ce3d03010703420004' +const SIGNATURE_ALGORITHM = '300a06082a8648ce3d040302' + +// Whether a signature over the data verifies under the public half of the key, ECDSA over SHA-256 in the given form. +function signedBy(privateKey: KeyObject, data: Uint8Array, signature: Uint8Array, dsaEncoding: 'der' | 'ieee-p1363'): boolean { + const key = createPublicKey(privateKey) + + return verify( + 'sha256', + data, + { dsaEncoding, key }, + signature, + ) +} + +/* Runs openssl's own verification of a request. The row is required in every run, and a missing binary fails it with that requirement named rather than + * skipping it. LibreSSL prints a failed verification yet exits 0, which is why the answer is read from openssl's words as well as its exit status. + */ +function opensslVerify(csr: Buffer): { output: string, status: number | null } { + const result = spawnSync('openssl', [ + 'req', + '-inform', + 'DER', + '-verify', + '-noout', + ], { encoding: 'utf8', input: csr }) + + if (result.error) { + throw new Error(`The openssl command is required to verify the signing request, and it could not run: ${result.error.message}`) + } + + return { output: result.stdout + result.stderr, status: result.status } +} + +describe('createSigningRequest', () => { + it.each([0, 31, 33])('refuses a nonce of %i bytes', async (length) => { + await expect(createSigningRequest(Buffer.alloc(length), SUBJECT)).rejects.toThrow(RangeError) + }) + + it('refuses an empty subject', async () => { + await expect(createSigningRequest(NONCE, '')).rejects.toThrow(RangeError) + }) + + it('builds the request the hubs accept, signed over its info by the key it certifies', async () => { + const { csr, privateKey } = await createSigningRequest(NONCE, SUBJECT) + const spki = createPublicKey(privateKey).export({ format: 'der', type: 'spki' }) + const info = csr.subarray(3, 131) + + expect(NONCE_LENGTH).toBe(32) + expect(csr.subarray(0, 2).toString('hex')).toBe('3081') + expect(csr[2]).toBe(csr.length - 3) + expect(spki.subarray(0, 27).toString('hex')).toBe(SPKI_OPENING) + expect(info.toString('hex')).toBe(`${INFO_OPENING}${spki.toString('hex')}a000`) + expect(csr.subarray(131, 143).toString('hex')).toBe(SIGNATURE_ALGORITHM) + expect(csr[143]).toBe(0x03) + expect(csr[144]).toBe(csr.length - 145) + expect(csr[145]).toBe(0) + expect(signedBy(privateKey, info, csr.subarray(146), 'der')).toBe(true) + }) + + it('writes the info\'s long-form length for a 40-character subject and still signs it', async () => { + const { csr, privateKey } = await createSigningRequest(NONCE, 'a'.repeat(40)) + const info = csr.subarray(3, 3 + 3 + 0x95) + const end = 3 + info.length + + expect(info.subarray(0, 3).toString('hex')).toBe('308195') + expect(csr.subarray(end, end + 12).toString('hex')).toBe(SIGNATURE_ALGORITHM) + expect(signedBy(privateKey, info, csr.subarray(end + 15), 'der')).toBe(true) + }) + + it('signs the nonce in the fixed-width form with a key made for each call', async () => { + const first = await createSigningRequest(NONCE, SUBJECT) + const second = await createSigningRequest(randomBytes(NONCE_LENGTH), SUBJECT) + + expect(first.nonceSignature).toHaveLength(64) + expect(signedBy(first.privateKey, NONCE, first.nonceSignature, 'ieee-p1363')).toBe(true) + expect(first.privateKey.equals(second.privateKey)).toBe(false) + }) + + it('passes openssl\'s verification, which a request with a changed subject fails', async () => { + const { csr } = await createSigningRequest(NONCE, SUBJECT) + const changed = Buffer.from(csr) + const subjectAt = changed.indexOf(SUBJECT) + + // The subject's first byte becomes another digit, which is why the UTF8String stays valid and openssl reaches the signature check. + changed[subjectAt] = '1'.charCodeAt(0) + + const verified = opensslVerify(csr) + const refused = opensslVerify(changed) + + expect(changed[subjectAt - 1]).toBe(SUBJECT.length) + expect(verified.status).toBe(0) + expect(verified.output).toContain('verify OK') + expect(refused.output).not.toContain('verify OK') + }) +}) diff --git a/src/lib/camera/recording/signingRequest.ts b/src/lib/camera/recording/signingRequest.ts new file mode 100644 index 000000000..216c0ff73 --- /dev/null +++ b/src/lib/camera/recording/signingRequest.ts @@ -0,0 +1,72 @@ +import type { Buffer } from 'node:buffer' +import type { KeyObject } from 'node:crypto' + +import { createPublicKey, generateKeyPair, sign } from 'node:crypto' +import { promisify } from 'node:util' + +import * as der from '../../util/der.js' + +/** + * The length of the nonce a hub writes to Camera Client CSR, in bytes. + */ +export const NONCE_LENGTH = 32 + +// The common name attribute of a subject, and ECDSA with SHA-256 with its parameters absent, RFC 5758 section 3.2. +const COMMON_NAME = '2.5.4.3' +const ECDSA_WITH_SHA256 = '1.2.840.10045.4.3.2' + +const generateKeyPairAsync = promisify(generateKeyPair) + +/** + * A certificate signing request with the signature of the nonce it answers, and the key that signed them. + */ +export interface SigningRequest { + /** + * The request, in DER format. + */ + csr: Buffer + /** + * The nonce's signature, ECDSA over SHA-256 of the nonce in the fixed-width 64-byte form. + */ + nonceSignature: Buffer + /** + * The private key the request asks a hub to certify, made for this request alone. + */ + privateKey: KeyObject +} + +/** + * Builds the RFC 2986 certificate signing request a hub certifies, in the shape the hubs accept: version 0, a subject of one common name, the key's + * SubjectPublicKeyInfo, an empty attribute set, and the request signed with ECDSA and SHA-256 in the DER form X.509 carries. Each call makes a fresh P-256 + * key: the key signs exactly its own request and the one nonce of the call that made it, and never anything a caller chooses later. + * @param nonce - The nonce the hub wrote, which must be {@link NONCE_LENGTH} bytes long. + * @param subject - The common name of the request's subject. + * @returns The request, the nonce's signature and the private key. + */ +export async function createSigningRequest(nonce: Uint8Array, subject: string): Promise { + if (nonce.length !== NONCE_LENGTH) { + throw new RangeError(`A signing request's nonce must be ${NONCE_LENGTH} bytes long, got ${nonce.length}.`) + } + + if (subject === '') { + throw new RangeError('A signing request needs a subject, got an empty string.') + } + + const { privateKey } = await generateKeyPairAsync('ec', { namedCurve: 'P-256' }) + const info = der.sequence( + der.integer(0n), + der.sequence(der.set(der.sequence(der.objectIdentifier(COMMON_NAME), der.utf8String(subject)))), + createPublicKey(privateKey).export({ format: 'der', type: 'spki' }), + der.context(0), + ) + const csr = der.sequence( + info, + der.sequence(der.objectIdentifier(ECDSA_WITH_SHA256)), + der.bitString(sign('sha256', info, { dsaEncoding: 'der', key: privateKey })), + ) + + // The hubs verify the nonce's signature in the fixed-width r and s form of IEEE P1363 and refuse the DER form. + const nonceSignature = sign('sha256', nonce, { dsaEncoding: 'ieee-p1363', key: privateKey }) + + return { csr, nonceSignature, privateKey } +} diff --git a/src/lib/model/RecordingProvisioning.spec.ts b/src/lib/model/RecordingProvisioning.spec.ts new file mode 100644 index 000000000..67c9cd483 --- /dev/null +++ b/src/lib/model/RecordingProvisioning.spec.ts @@ -0,0 +1,363 @@ +import type { RecordingProvisioningEntry } from './RecordingProvisioning.js' + +import { Buffer } from 'node:buffer' +import { generateKeyPairSync } from 'node:crypto' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { Accessory } from '../Accessory.js' +import { HAPStorage } from './HAPStorage.js' +import { RecordingProvisioning } from './RecordingProvisioning.js' + +const USERNAME = '0E:AE:FC:45:7B:91' +const KEY = RecordingProvisioning.persistKey(USERNAME) +const FIRST_CAMERA = 'a1b2c3d4-0000-4000-8000-000000000001' +const SECOND_CAMERA = 'a1b2c3d4-0000-4000-8000-000000000002' +const MAX64 = 2n ** 64n - 1n + +function fullEntry(): RecordingProvisioningEntry { + return { + cameraKey: { + key: Buffer.alloc(32, 0x5A), + keyNumber: MAX64, + }, + clipMark: MAX64, + credential: { + ca: Buffer.from('3082ca', 'hex'), + certificate: Buffer.from('3082ce', 'hex'), + privateKey: generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey, + }, + publishingPoint: { + serverCACertificates: ['3082a1', '3082a2'].map(hex => ({ + certificate: Buffer.from(hex, 'hex'), + })), + url: 'https://ingest.example/v1/token/', + }, + sequenceMark: MAX64, + } +} + +// Every value a stored record holds, nested or not, which lets a row see that only strings reach the store. +function leaves(value: unknown): unknown[] { + return typeof value === 'object' && value !== null + ? Object.values(value).flatMap(leaves) + : [value] +} + +describe('recordingProvisioning', () => { + beforeEach(() => { + RecordingProvisioning.remove(USERNAME) + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('keys a username\'s record as AccessoryInfo keys its own', () => { + expect(KEY).toBe('RecordingProvisioning.0EAEFC457B91.json') + }) + + it('round trips a full entry exactly, storing strings only', () => { + const entry = fullEntry() + + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, entry) + + const stored = HAPStorage.storage().getItem(KEY) + const loaded = RecordingProvisioning.load(USERNAME, FIRST_CAMERA) + + expect(leaves(stored).every(leaf => typeof leaf === 'string')).toBe(true) + expect(stored.accessories[FIRST_CAMERA]).toMatchObject({ + clipMark: '18446744073709551615', + keyNumber: '18446744073709551615', + sequenceMark: '18446744073709551615', + }) + expect(loaded?.credential?.ca).toEqual(entry.credential?.ca) + expect(loaded?.credential?.certificate).toEqual(entry.credential?.certificate) + expect(loaded?.credential?.privateKey.equals(entry.credential!.privateKey)).toBe(true) + expect(loaded?.cameraKey).toEqual(entry.cameraKey) + expect(loaded?.publishingPoint).toEqual(entry.publishingPoint) + expect(loaded?.sequenceMark).toBe(MAX64) + expect(loaded?.clipMark).toBe(MAX64) + }) + + it('round trips partial entries as given', () => { + const { credential } = fullEntry() + + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { clipMark: 7n, sequenceMark: 0n }) + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, { credential }) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ clipMark: 7n, sequenceMark: 0n }) + expect(Object.keys(RecordingProvisioning.load(USERNAME, SECOND_CAMERA)!)).toEqual(['credential']) + }) + + it('writes nothing for a save or removal that would leave the record as it is', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, fullEntry()) + + const entry = fullEntry() + + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, entry) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + const removeItemSync = vi.spyOn(HAPStorage.storage(), 'removeItemSync') + + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, entry) + RecordingProvisioning.save(USERNAME, 'a1b2c3d4-0000-4000-8000-000000000009', {}) + RecordingProvisioning.removeEntry(USERNAME, 'a1b2c3d4-0000-4000-8000-000000000009') + + expect(setItemSync).not.toHaveBeenCalled() + expect(removeItemSync).not.toHaveBeenCalled() + }) + + it('removes the file when an empty entry is saved for the only stored camera', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + const removeItemSync = vi.spyOn(HAPStorage.storage(), 'removeItemSync') + + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, {}) + + expect(setItemSync).not.toHaveBeenCalled() + expect(removeItemSync).toHaveBeenCalledExactlyOnceWith(KEY) + expect(HAPStorage.storage().getItem(KEY)).toBeUndefined() + }) + + it('writes again after a failed write, the store\'s own copy left as it was', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementationOnce(() => { + throw new Error('The disk is full.') + }) + + expect(() => RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 2n })).toThrow('The disk is full.') + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ sequenceMark: 1n }) + + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 2n }) + + expect(setItemSync).toHaveBeenCalledTimes(2) + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ sequenceMark: 2n }) + }) + + it('removes an entry again after a failed removal, the store\'s own copy left as it was', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, { sequenceMark: 2n }) + + vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementationOnce(() => { + throw new Error('The disk is full.') + }) + + expect(() => RecordingProvisioning.removeEntry(USERNAME, FIRST_CAMERA)).toThrow('The disk is full.') + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ sequenceMark: 1n }) + + RecordingProvisioning.removeEntry(USERNAME, FIRST_CAMERA) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toBeUndefined() + expect(RecordingProvisioning.load(USERNAME, SECOND_CAMERA)).toStrictEqual({ sequenceMark: 2n }) + }) + + it('writes a camera\'s marks into its stored entry as it stands, every other part left as stored, an unreadable one among them', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, fullEntry()) + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, { clipMark: 3n }) + + const { accessories } = HAPStorage.storage().getItem(KEY) + const unreadable = { ...accessories[FIRST_CAMERA], privateKey: 'not a key' } + + HAPStorage.storage().setItemSync(KEY, { + accessories: { + ...accessories, + [FIRST_CAMERA]: unreadable, + }, + }) + RecordingProvisioning.saveMarks(USERNAME, FIRST_CAMERA, { clipMark: 4n, sequenceMark: 5n }) + + expect(HAPStorage.storage().getItem(KEY).accessories).toStrictEqual({ + [FIRST_CAMERA]: { ...unreadable, clipMark: '4', sequenceMark: '5' }, + [SECOND_CAMERA]: { clipMark: '3' }, + }) + }) + + it('writes a marks-only entry for a camera with none, keeps a stored mark it is not given, and writes nothing when the marks are as stored', () => { + RecordingProvisioning.saveMarks(USERNAME, FIRST_CAMERA, { clipMark: 2n, sequenceMark: 1n }) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ clipMark: 2n, sequenceMark: 1n }) + + RecordingProvisioning.saveMarks(USERNAME, FIRST_CAMERA, { sequenceMark: 6n }) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ clipMark: 2n, sequenceMark: 6n }) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + + RecordingProvisioning.saveMarks(USERNAME, FIRST_CAMERA, { clipMark: 2n, sequenceMark: 6n }) + RecordingProvisioning.saveMarks(USERNAME, SECOND_CAMERA, {}) + + expect(setItemSync).not.toHaveBeenCalled() + expect(RecordingProvisioning.load(USERNAME, SECOND_CAMERA)).toBeUndefined() + }) + + it('throws at a mark write that fails, the store\'s own copy left as it was', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementationOnce(() => { + throw new Error('The disk is full.') + }) + + expect(() => RecordingProvisioning.saveMarks(USERNAME, FIRST_CAMERA, { sequenceMark: 2n })).toThrow('The disk is full.') + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ sequenceMark: 1n }) + }) + + it('keeps two cameras of one username in one file and removes them one at a time', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, { sequenceMark: 2n }) + + expect(Object.keys(HAPStorage.storage().getItem(KEY).accessories)).toEqual([FIRST_CAMERA, SECOND_CAMERA]) + + RecordingProvisioning.removeEntry(USERNAME, FIRST_CAMERA) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toBeUndefined() + expect(RecordingProvisioning.load(USERNAME, SECOND_CAMERA)).toStrictEqual({ sequenceMark: 2n }) + + RecordingProvisioning.removeEntry(USERNAME, SECOND_CAMERA) + + expect(HAPStorage.storage().getItem(KEY)).toBeUndefined() + }) + + it('clears every camera\'s entry under a username to its marks', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, fullEntry()) + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, { + ...fullEntry(), + clipMark: 7n, + sequenceMark: undefined, + }) + + RecordingProvisioning.clearProvisioning(USERNAME) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ clipMark: MAX64, sequenceMark: MAX64 }) + expect(RecordingProvisioning.load(USERNAME, SECOND_CAMERA)).toStrictEqual({ clipMark: 7n }) + }) + + it('clears one camera\'s entry to its marks and leaves another camera\'s whole', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, fullEntry()) + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, fullEntry()) + const neighbor = structuredClone(HAPStorage.storage().getItem(KEY).accessories[SECOND_CAMERA]) + + RecordingProvisioning.clearProvisioning(USERNAME, FIRST_CAMERA) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ clipMark: MAX64, sequenceMark: MAX64 }) + expect(HAPStorage.storage().getItem(KEY).accessories[SECOND_CAMERA]).toStrictEqual(neighbor) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + + RecordingProvisioning.clearProvisioning(USERNAME, FIRST_CAMERA) + RecordingProvisioning.clearProvisioning(USERNAME, 'a1b2c3d4-0000-4000-8000-000000000003') + + expect(setItemSync).not.toHaveBeenCalled() + }) + + it('writes nothing for a clear that leaves the record as it is', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { clipMark: 1n, sequenceMark: 2n }) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + const removeItemSync = vi.spyOn(HAPStorage.storage(), 'removeItemSync') + + RecordingProvisioning.clearProvisioning(USERNAME) + RecordingProvisioning.clearProvisioning('0E:AE:FC:45:7B:99') + + expect(setItemSync).not.toHaveBeenCalled() + expect(removeItemSync).not.toHaveBeenCalled() + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ clipMark: 1n, sequenceMark: 2n }) + }) + + it('removes an entry a clear leaves with no mark, and the file once no entry is left', () => { + const { cameraKey, credential, publishingPoint } = fullEntry() + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { cameraKey, credential, publishingPoint }) + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, { publishingPoint, sequenceMark: 3n }) + + RecordingProvisioning.clearProvisioning(USERNAME) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toBeUndefined() + expect(Object.keys(HAPStorage.storage().getItem(KEY).accessories)).toEqual([SECOND_CAMERA]) + + RecordingProvisioning.save(USERNAME, SECOND_CAMERA, { publishingPoint }) + const removeItemSync = vi.spyOn(HAPStorage.storage(), 'removeItemSync') + + RecordingProvisioning.clearProvisioning(USERNAME) + + expect(removeItemSync).toHaveBeenCalledExactlyOnceWith(KEY) + expect(HAPStorage.storage().getItem(KEY)).toBeUndefined() + }) + + it('is removed by username, through its own removal and with the accessory\'s data', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + RecordingProvisioning.remove(USERNAME) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toBeUndefined() + + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + Accessory.cleanupAccessoryData(USERNAME) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toBeUndefined() + }) + + it('loads a missing username or camera as undefined', () => { + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + + expect(RecordingProvisioning.load('0E:AE:FC:45:7B:92', FIRST_CAMERA)).toBeUndefined() + expect(RecordingProvisioning.load(USERNAME, SECOND_CAMERA)).toBeUndefined() + }) + + it('leaves out each unreadable part and never throws on stored data', () => { + const entry = fullEntry() + + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, entry) + + const stored = HAPStorage.storage().getItem(KEY).accessories[FIRST_CAMERA] + + HAPStorage.storage().setItemSync(KEY, { + accessories: { + 'a1b2c3d4-0000-4000-8000-000000000003': { ...stored, privateKey: '00' }, + 'a1b2c3d4-0000-4000-8000-000000000004': { privateKey: '00' }, + 'a1b2c3d4-0000-4000-8000-000000000005': { ...stored, sequenceMark: '-5' }, + 'a1b2c3d4-0000-4000-8000-000000000006': { ...stored, ca: 'zz' }, + }, + }) + + const unreadableKey = RecordingProvisioning.load(USERNAME, 'a1b2c3d4-0000-4000-8000-000000000003') + const negativeMark = RecordingProvisioning.load(USERNAME, 'a1b2c3d4-0000-4000-8000-000000000005') + const malformedCA = RecordingProvisioning.load(USERNAME, 'a1b2c3d4-0000-4000-8000-000000000006') + + expect(Object.keys(unreadableKey!).sort()).toEqual([ + 'cameraKey', + 'clipMark', + 'publishingPoint', + 'sequenceMark', + ]) + expect(RecordingProvisioning.load(USERNAME, 'a1b2c3d4-0000-4000-8000-000000000004')).toBeUndefined() + expect(negativeMark?.sequenceMark).toBeUndefined() + expect(negativeMark?.clipMark).toBe(MAX64) + expect(malformedCA?.credential).toBeUndefined() + expect(malformedCA?.sequenceMark).toBe(MAX64) + }) + + it('leaves out a stored number past the uint64 range', () => { + HAPStorage.storage().setItemSync(KEY, { + accessories: { + [FIRST_CAMERA]: { + clipMark: '18446744073709551615', + sequenceMark: '18446744073709551616', + }, + }, + }) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ clipMark: MAX64 }) + }) + + it('reads a stored value without an accessories object as an empty record in every method', () => { + HAPStorage.storage().setItemSync(KEY, { accessories: 'unreadable' }) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toBeUndefined() + expect(() => RecordingProvisioning.removeEntry(USERNAME, FIRST_CAMERA)).not.toThrow() + + RecordingProvisioning.save(USERNAME, FIRST_CAMERA, { sequenceMark: 1n }) + + expect(RecordingProvisioning.load(USERNAME, FIRST_CAMERA)).toStrictEqual({ sequenceMark: 1n }) + expect(Object.keys(HAPStorage.storage().getItem(KEY).accessories)).toEqual([FIRST_CAMERA]) + }) +}) diff --git a/src/lib/model/RecordingProvisioning.ts b/src/lib/model/RecordingProvisioning.ts new file mode 100644 index 000000000..99ab13dd0 --- /dev/null +++ b/src/lib/model/RecordingProvisioning.ts @@ -0,0 +1,399 @@ +import type { KeyObject } from 'node:crypto' + +import type { MacAddress } from '../../types.js' +import type { CameraRecordingPublishingPointPayload } from '../camera/capabilities/cameraBuffer.js' +import type { CameraKeyPayload } from '../camera/capabilities/provisioning.js' + +import { Buffer } from 'node:buffer' +import { createPrivateKey } from 'node:crypto' +import { format, isDeepStrictEqual } from 'node:util' + +import { HAPStorage } from './HAPStorage.js' + +// A stored number is a decimal with no sign or leading zero, read only within uint64, because BigInt reads '', '-5' and '0x10' without complaint. +const DECIMAL = /^(?:0|[1-9]\d*)$/ +const UINT64_MAX = 2n ** 64n - 1n + +// Stored bytes are lowercase hex of whole octets, because Buffer.from reads malformed hex without complaint, as a shorter buffer. +const HEX = /^(?:[0-9a-f]{2})+$/ + +/** + * One camera's recording provisioning package. Every part is optional, because a hub provisions in steps and clears at any moment. + */ +export interface RecordingProvisioningEntry { + /** + * The client certificate a hub issued, the CA it was issued under and the private key it certifies, all three or none, each certificate in DER format. + */ + credential?: { ca: Buffer, certificate: Buffer, privateKey: KeyObject } + /** + * The Camera Key a hub wrote and its key number. + */ + cameraKey?: CameraKeyPayload + /** + * The publishing point clips are uploaded to, as a hub wrote it. + */ + publishingPoint?: CameraRecordingPublishingPointPayload + /** + * The camera event queue's high-water mark. + */ + sequenceMark?: bigint + /** + * The last clip number used. + */ + clipMark?: bigint +} + +// An entry as it is stored: strings only, bytes as hex, the key as PKCS8 DER and every number as a decimal string. A uint64 keeps every bit in JSON. +interface StoredEntry { + ca?: string + certificate?: string + privateKey?: string + cameraKey?: string + keyNumber?: string + url?: string + serverCAs?: string[] + sequenceMark?: string + clipMark?: string +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/* The stored entries of one username's file, keyed by accessory UUID, as the store holds them. This is the store's own object, served by reference, which is why no + * method changes it: a write builds a new map, which keeps a failed write from changing what the store holds. A stored value that is not an object + * holding an accessories object reads as an empty map. + */ +function storedAccessories(key: string): Record { + const stored: unknown = HAPStorage.storage().getItem(key) + + return isRecord(stored) && isRecord(stored.accessories) + ? stored.accessories + : {} +} + +// Writes one camera's stored entry into its username's file beside every other camera's, writing nothing when the file already holds it. +function writeEntry(key: string, accessories: Record, accessoryUUID: string, stored: object): void { + if (isDeepStrictEqual(accessories[accessoryUUID], stored)) { + return + } + + HAPStorage.storage().setItemSync(key, { + accessories: { + ...accessories, + [accessoryUUID]: stored, + }, + }) +} + +function serialize(entry: RecordingProvisioningEntry): StoredEntry { + const stored: StoredEntry = {} + + if (entry.credential) { + stored.ca = entry.credential.ca.toString('hex') + stored.certificate = entry.credential.certificate.toString('hex') + stored.privateKey = entry.credential.privateKey.export({ format: 'der', type: 'pkcs8' }).toString('hex') + } + + if (entry.cameraKey) { + stored.cameraKey = entry.cameraKey.key.toString('hex') + stored.keyNumber = entry.cameraKey.keyNumber.toString() + } + + if (entry.publishingPoint) { + stored.url = entry.publishingPoint.url + stored.serverCAs = entry.publishingPoint.serverCACertificates.map(({ certificate }) => certificate.toString('hex')) + } + + if (entry.sequenceMark !== undefined) { + stored.sequenceMark = entry.sequenceMark.toString() + } + + if (entry.clipMark !== undefined) { + stored.clipMark = entry.clipMark.toString() + } + + return stored +} + +// The high-water marks of a stored entry, as stored, which a clear keeps so no number is used twice. +function marksOf(stored: unknown): StoredEntry { + const marks: StoredEntry = {} + + if (!isRecord(stored)) { + return marks + } + + if (typeof stored.sequenceMark === 'string') { + marks.sequenceMark = stored.sequenceMark + } + + if (typeof stored.clipMark === 'string') { + marks.clipMark = stored.clipMark + } + + return marks +} + +function readBytes(value: unknown): Buffer | undefined { + return typeof value === 'string' && HEX.test(value) + ? Buffer.from(value, 'hex') + : undefined +} + +function readNumber(value: unknown): bigint | undefined { + if (typeof value !== 'string' || !DECIMAL.test(value)) { + return undefined + } + + const number = BigInt(value) + + return number <= UINT64_MAX + ? number + : undefined +} + +function readPrivateKey(value: unknown): KeyObject | undefined { + const key = readBytes(value) + + if (key === undefined) { + return undefined + } + + try { + return createPrivateKey({ format: 'der', key, type: 'pkcs8' }) + } catch { + return undefined + } +} + +function readCredential(stored: Record): RecordingProvisioningEntry['credential'] { + const ca = readBytes(stored.ca) + const certificate = readBytes(stored.certificate) + const privateKey = readPrivateKey(stored.privateKey) + + return ca && certificate && privateKey + ? { ca, certificate, privateKey } + : undefined +} + +function readCameraKey(stored: Record): CameraKeyPayload | undefined { + const key = readBytes(stored.cameraKey) + const keyNumber = readNumber(stored.keyNumber) + + return key && keyNumber !== undefined + ? { key, keyNumber } + : undefined +} + +function readPublishingPoint(stored: Record): CameraRecordingPublishingPointPayload | undefined { + const { serverCAs, url } = stored + + if (typeof url !== 'string' || !Array.isArray(serverCAs)) { + return undefined + } + + const certificates = serverCAs.map(readBytes) + + if (!certificates.every(certificate => certificate !== undefined)) { + return undefined + } + + return { + serverCACertificates: certificates.map(certificate => ({ certificate })), + url, + } +} + +/* Reads one part of a stored entry into the entry being loaded. A part whose fields are all absent is simply not there; a part missing a field or holding + * one that does not read is left out, the caller's function told the part's name alone, because the stored values are key material and a hub's token. + */ +function readPart( + entry: RecordingProvisioningEntry, + stored: Record, + part: Part, + fields: readonly (keyof StoredEntry)[], + read: (stored: Record) => RecordingProvisioningEntry[Part] | undefined, + unreadable?: (part: keyof RecordingProvisioningEntry) => void, +): void { + if (!fields.some(field => Object.hasOwn(stored, field))) { + return + } + + const value = read(stored) + + if (value === undefined) { + unreadable?.(part) + + return + } + + entry[part] = value +} + +/** + * The synchronous record of each camera's recording provisioning package: the hub-issued credential, the Camera Key, the publishing point, and the + * high-water marks of the event sequence counter and the clip number. Losing the hub-issued identity keeps recording dark until the Home app provisions + * again, which is why it is written as soon as it changes, never postponed, and it outlives any controller. It is removed only with its accessory's data or its own + * entry, and cleared to its marks at an unpairing, when its camera leaves its bridge and when its camera starts without the camera capabilities block: + * its credentials and its Camera Key go and its marks stay. + * + * One file per publishing username, as `AccessoryInfo` keys its record, holds every camera's entry by accessory UUID, because bridged cameras share their + * bridge's username. A write that would leave the file as it is writes nothing, because a hub repeats an empty clear about every half minute on a camera + * whose recording is off. Stored data never makes a read throw: a part that does not read is left out. + */ +export class RecordingProvisioning { + /** + * The storage key of a username's record, like "RecordingProvisioning.CC223DE3CEF3.json". + * @param username - The publishing username. + * @returns The key. + */ + static persistKey(username: MacAddress): string { + return format('RecordingProvisioning.%s.json', username.replace(/:/g, '').toUpperCase()) + } + + /** + * Reads a camera's stored entry, each part on its own. + * @param username - The publishing username. + * @param accessoryUUID - The camera's accessory UUID. + * @param unreadable - Told the name of each part the entry holds and leaves out, since it does not read, and never its values. + * @returns The entry's readable parts, or `undefined` when none reads. + */ + static load(username: MacAddress, accessoryUUID: string, unreadable?: (part: keyof RecordingProvisioningEntry) => void): RecordingProvisioningEntry | undefined { + const stored = storedAccessories(RecordingProvisioning.persistKey(username))[accessoryUUID] + + if (!isRecord(stored)) { + return undefined + } + + const entry: RecordingProvisioningEntry = {} + + readPart(entry, stored, 'credential', ['ca', 'certificate', 'privateKey'], readCredential, unreadable) + readPart(entry, stored, 'cameraKey', ['cameraKey', 'keyNumber'], readCameraKey, unreadable) + readPart(entry, stored, 'publishingPoint', ['url', 'serverCAs'], readPublishingPoint, unreadable) + readPart(entry, stored, 'sequenceMark', ['sequenceMark'], ({ sequenceMark }) => readNumber(sequenceMark), unreadable) + readPart(entry, stored, 'clipMark', ['clipMark'], ({ clipMark }) => readNumber(clipMark), unreadable) + + return Object.keys(entry).length === 0 + ? undefined + : entry + } + + /** + * Replaces a camera's stored entry and writes it at once. An entry with no part removes the camera's entry as {@link removeEntry} does. + * @param username - The publishing username. + * @param accessoryUUID - The camera's accessory UUID. + * @param entry - The whole entry. + */ + static save(username: MacAddress, accessoryUUID: string, entry: RecordingProvisioningEntry): void { + const serialized = serialize(entry) + + if (Object.keys(serialized).length === 0) { + RecordingProvisioning.removeEntry(username, accessoryUUID) + + return + } + + const key = RecordingProvisioning.persistKey(username) + + writeEntry(key, storedAccessories(key), accessoryUUID, serialized) + } + + /** + * Writes a camera's high-water marks into its stored entry as it stands and at once, every other part left as stored and none of them read. A mark + * that moves outside a hub's write never writes back a part the record does not hold. A mark not given leaves the stored one as it is, and a write + * that would leave the record as it is writes nothing. + * @param username - The publishing username. + * @param accessoryUUID - The camera's accessory UUID. + * @param marks - The sequence mark and the clip mark. + */ + static saveMarks(username: MacAddress, accessoryUUID: string, marks: Pick): void { + const key = RecordingProvisioning.persistKey(username) + const accessories = storedAccessories(key) + const stored = accessories[accessoryUUID] + const entry = { + ...(isRecord(stored) + ? stored + : {}), + ...serialize(marks), + } + + if (Object.keys(entry).length === 0) { + return + } + + writeEntry(key, accessories, accessoryUUID, entry) + } + + /** + * Removes a camera's stored entry, and the username's file once it holds no entry. + * @param username - The publishing username. + * @param accessoryUUID - The camera's accessory UUID. + */ + static removeEntry(username: MacAddress, accessoryUUID: string): void { + const key = RecordingProvisioning.persistKey(username) + const accessories = storedAccessories(key) + + if (!Object.hasOwn(accessories, accessoryUUID)) { + return + } + + const remaining = Object.fromEntries(Object.entries(accessories).filter(([uuid]) => uuid !== accessoryUUID)) + + if (Object.keys(remaining).length === 0) { + HAPStorage.storage().removeItemSync(key) + + return + } + + HAPStorage.storage().setItemSync(key, { accessories: remaining }) + } + + /** + * Strips a camera's entry, or every camera's entry under a username when no camera is named, to its high-water marks, as an unpairing, a camera + * leaving its bridge and a camera starting without the camera capabilities block each clear what the hubs provisioned, its credentials and its Camera + * Key going. The marks stay so no number is used twice, because the service keeps a camera's session folders and a plugin may add the same camera back. + * An entry left with no mark is removed, and the file once it holds no entry. A clear that changes nothing writes nothing. + * @param username - The publishing username. + * @param accessoryUUID - The camera's accessory UUID, leaving every other camera's entry as it is. + */ + static clearProvisioning(username: MacAddress, accessoryUUID?: string): void { + const key = RecordingProvisioning.persistKey(username) + const accessories = storedAccessories(key) + const cleared: Record = {} + + for (const [uuid, stored] of Object.entries(accessories)) { + if ((accessoryUUID !== undefined) && (uuid !== accessoryUUID)) { + cleared[uuid] = stored + + continue + } + + const marks = marksOf(stored) + + if (Object.keys(marks).length > 0) { + cleared[uuid] = marks + } + } + + if (isDeepStrictEqual(cleared, accessories)) { + return + } + + if (Object.keys(cleared).length === 0) { + HAPStorage.storage().removeItemSync(key) + + return + } + + HAPStorage.storage().setItemSync(key, { accessories: cleared }) + } + + /** + * Removes a username's whole record, every camera's entry with it. + * @param username - The publishing username. + */ + static remove(username: MacAddress): void { + HAPStorage.storage().removeItemSync(RecordingProvisioning.persistKey(username)) + } +} diff --git a/src/lib/util/der.spec.ts b/src/lib/util/der.spec.ts new file mode 100644 index 000000000..72ce061ef --- /dev/null +++ b/src/lib/util/der.spec.ts @@ -0,0 +1,63 @@ +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import * as der from './der.js' + +// Each vector is the DER encoding X.690 gives its value, the header's tag and length octets included. +describe('der', () => { + it('writes an INTEGER in the fewest octets, a leading zero octet keeping a set high bit positive', () => { + expect(der.integer(0n).toString('hex')).toBe('020100') + expect(der.integer(127n).toString('hex')).toBe('02017f') + expect(der.integer(128n).toString('hex')).toBe('02020080') + expect(der.integer(256n).toString('hex')).toBe('02020100') + expect(der.integer(2n ** 64n - 1n).toString('hex')).toBe('020900ffffffffffffffff') + }) + + it('writes an OBJECT IDENTIFIER, the first two arcs combined and every arc in base 128', () => { + expect(der.objectIdentifier('2.5.4.3').toString('hex')).toBe('0603550403') + expect(der.objectIdentifier('2.999.3').toString('hex')).toBe('0603883703') + expect(der.objectIdentifier('1.2.840.10045.4.3.2').toString('hex')).toBe('06082a8648ce3d040302') + }) + + it('writes a UTF8String and a BIT STRING of whole octets', () => { + expect(der.utf8String('é').toString('hex')).toBe('0c02c3a9') + expect(der.bitString(Buffer.from([1, 2])).toString('hex')).toBe('0303000102') + }) + + it('writes a context-specific element and a SEQUENCE, empty or holding elements', () => { + expect(der.context(0).toString('hex')).toBe('a000') + expect(der.context(1, der.sequence()).toString('hex')).toBe('a1023000') + expect(der.sequence().toString('hex')).toBe('3000') + }) + + it('writes a SET OF its elements sorted by their encodings', () => { + expect(der.set(der.integer(5n), der.utf8String('a'), der.integer(1n)).toString('hex')).toBe('31090201010201050c0161') + }) + + it.each([ + [127, '0c7f'], + [128, '0c8180'], + [255, '0c81ff'], + [256, '0c820100'], + [65535, '0c82ffff'], + [65536, '0c83010000'], + ])('writes the header of a UTF8String of %i octets in the shortest length form', (length, header) => { + const written = der.utf8String('a'.repeat(length)) + + expect(written.subarray(0, header.length / 2).toString('hex')).toBe(header) + expect(written.length).toBe(header.length / 2 + length) + }) + + it('refuses a negative integer', () => { + expect(() => der.integer(-1n)).toThrow(RangeError) + }) + + it.each(['1', '1..2', '1.0x10', '3.1', '1.40'])('refuses the object identifier \'%s\'', (dotted) => { + expect(() => der.objectIdentifier(dotted)).toThrow(RangeError) + }) + + it('refuses a context tag number past the single-octet form', () => { + expect(() => der.context(31)).toThrow(RangeError) + }) +}) diff --git a/src/lib/util/der.ts b/src/lib/util/der.ts new file mode 100644 index 000000000..5d01de98b --- /dev/null +++ b/src/lib/util/der.ts @@ -0,0 +1,158 @@ +import { Buffer } from 'node:buffer' + +/* X.690 DER writing for the grammar a fixed-shape certificate signing request needs, and writing only: the certificates the recording path receives are + * parsed by crypto.X509Certificate, never here. Each function answers one whole element, its identifier, length and contents. A structure is built by + * passing elements to the constructed forms. An INTEGER is taken as a bigint, and no value loses precision on its way to the wire. + */ + +// The identifier octets of the universal types the grammar uses, and the base of a constructed context-specific element. +const INTEGER = 0x02 +const BIT_STRING = 0x03 +const OBJECT_IDENTIFIER = 0x06 +const UTF8_STRING = 0x0C +const SEQUENCE = 0x30 +const SET = 0x31 +const CONTEXT_CONSTRUCTED = 0xA0 + +// The highest tag number a single identifier octet carries, X.690 8.1.2. +const LAST_LOW_TAG_NUMBER = 30 + +// An arc is a decimal number with no sign, space, prefix or leading zero, because BigInt reads '', ' 7 ', '0x10' and '-5' without complaint. +const ARC = /^(?:0|[1-9]\d*)$/ + +// The fewest big-endian octets holding a non-negative integer, one zero octet for zero. +function unsignedOctets(value: bigint): Buffer { + const hex = value.toString(16) + + return Buffer.from(hex.padStart(hex.length + (hex.length % 2), '0'), 'hex') +} + +// The length octets of X.690 8.1.3: the short form below 0x80, otherwise 0x80 plus the count of the length's own fewest big-endian octets, then those octets. +function lengthOctets(length: number): Buffer { + if (length < 0x80) { + return Buffer.from([length]) + } + + const octets = unsignedOctets(BigInt(length)) + + return Buffer.from([0x80 | octets.length, ...octets]) +} + +function element(identifier: number, contents: Uint8Array): Buffer { + return Buffer.concat([ + Buffer.from([identifier]), + lengthOctets(contents.length), + contents, + ]) +} + +// One subidentifier in base 128, most significant group first, every octet but the last carrying the continuation bit, X.690 8.19.2. The groups are +// read from the least significant up: the first one read is the last octet and the only one without the bit, and zero still writes one octet. +function subidentifierOctets(value: bigint): number[] { + const octets: number[] = [] + + for (let rest = value, continuation = 0; octets.length === 0 || rest > 0n; rest >>= 7n, continuation = 0x80) { + octets.unshift(Number(rest & 0x7Fn) | continuation) + } + + return octets +} + +/** + * A SEQUENCE of the elements, in the order given. + * @param elements - The whole elements the sequence holds. + * @returns The SEQUENCE element. + */ +export function sequence(...elements: Uint8Array[]): Buffer { + return element(SEQUENCE, Buffer.concat(elements)) +} + +/** + * A SET OF the elements, sorted by their encodings as X.690 11.6 requires of DER. + * @param elements - The whole elements the set holds. + * @returns The SET element. + */ +export function set(...elements: Uint8Array[]): Buffer { + return element(SET, Buffer.concat(elements.toSorted(Buffer.compare))) +} + +/** + * A non-negative INTEGER in the fewest octets, a leading zero octet keeping it positive when its high bit is set. + * @param value - The integer. + * @returns The INTEGER element. + */ +export function integer(value: bigint): Buffer { + if (value < 0n) { + throw new RangeError(`A DER INTEGER is written only for a non-negative value, got ${value}.`) + } + + const octets = unsignedOctets(value) + + return element(INTEGER, (octets[0] & 0x80) === 0 + ? octets + : Buffer.from([0, ...octets])) +} + +/** + * A BIT STRING of whole octets: its unused-bits octet is zero. + * @param bytes - The string's octets. + * @returns The BIT STRING element. + */ +export function bitString(bytes: Uint8Array): Buffer { + return element(BIT_STRING, Buffer.concat([ + Buffer.from([0]), + bytes, + ])) +} + +/** + * An OBJECT IDENTIFIER from its dotted form, its first two arcs combined as 40 times the first plus the second, X.690 8.19.4. + * @param dotted - The identifier's arcs joined by dots. + * @returns The OBJECT IDENTIFIER element. + */ +export function objectIdentifier(dotted: string): Buffer { + const texts = dotted.split('.') + + if (texts.length < 2) { + throw new RangeError(`An object identifier needs at least two arcs, got '${dotted}'.`) + } + + if (!texts.every(text => ARC.test(text))) { + throw new RangeError(`Every arc of an object identifier must be a decimal number, got '${dotted}'.`) + } + + const [first, second, ...rest] = texts.map(text => BigInt(text)) + + if (first > 2n) { + throw new RangeError(`The first arc of an object identifier must be 0, 1 or 2, got '${dotted}'.`) + } + + if (first < 2n && second > 39n) { + throw new RangeError(`The second arc of an object identifier under a first arc of 0 or 1 must be at most 39, got '${dotted}'.`) + } + + return element(OBJECT_IDENTIFIER, Buffer.from([40n * first + second, ...rest].flatMap(subidentifierOctets))) +} + +/** + * A UTF8String. + * @param text - The string. + * @returns The UTF8String element. + */ +export function utf8String(text: string): Buffer { + return element(UTF8_STRING, Buffer.from(text, 'utf8')) +} + +/** + * A constructed context-specific element, which an empty list of elements leaves empty. + * @param tagNumber - The tag number, written in the identifier octet itself. + * @param elements - The whole elements it holds. + * @returns The context-specific element. + */ +export function context(tagNumber: number, ...elements: Uint8Array[]): Buffer { + if (!Number.isInteger(tagNumber) || tagNumber < 0 || tagNumber > LAST_LOW_TAG_NUMBER) { + throw new RangeError(`A context-specific tag number must be an integer from 0 to ${LAST_LOW_TAG_NUMBER}, got ${tagNumber}.`) + } + + return element(CONTEXT_CONSTRUCTED | tagNumber, Buffer.concat(elements)) +} diff --git a/src/lib/util/libraryVersion.ts b/src/lib/util/libraryVersion.ts new file mode 100644 index 000000000..f7ea8bfbd --- /dev/null +++ b/src/lib/util/libraryVersion.ts @@ -0,0 +1,12 @@ +import { readFileSync } from 'node:fs' + +// The package's version, read once as the module loads. No later caller reads the package file. +const VERSION = (JSON.parse(readFileSync(new URL('../../../package.json', import.meta.url), 'utf8')) as { version: string }).version + +/** + * The library's version, as its package states it. + * @returns The SemVer version string. + */ +export function libraryVersion(): string { + return VERSION +} diff --git a/src/lib/util/ntp.spec.ts b/src/lib/util/ntp.spec.ts new file mode 100644 index 000000000..46f192917 --- /dev/null +++ b/src/lib/util/ntp.spec.ts @@ -0,0 +1,74 @@ +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { ntpTime } 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 { + const bytes = Buffer.alloc(8) + + bytes.writeBigUInt64BE(BigInt.asUintN(64, value)) + + return bytes.toString('hex') +} + +// The two 32-bit words Number arithmetic gives for a wall clock: the seconds since the NTP epoch, which are the Unix seconds plus 2208988800, and the fraction, +// each floored modulo 2^32. +function numberWords(now: number): string { + const bytes = Buffer.alloc(8) + + bytes.writeUInt32BE((Math.floor(now / 1000) + 2208988800) >>> 0, 0) + bytes.writeUInt32BE((now % 1000) / 1000 * 0x100000000 >>> 0, 4) + + return bytes.toString('hex') +} + +describe('ntpTime', () => { + // Each vector is the NTP field of the first box the producer reference time writer's suite writes at that wall clock, where the fragment's decode time + // adds back what the anchor took away. + it.each([ + ['at whole seconds', '2026-11-12T00:00:00.000Z', 'ee9f800000000000'], + ['with the fraction floored', '2026-11-12T00:00:00.003Z', 'ee9f800000c49ba5'], + ['at the NTP era\'s wrap', '2036-02-07T06:28:16.000Z', '0000000000000000'], + ])('converts a wall clock %s to the NTP field the writer\'s vectors hold', (_name, wallClock, expected) => { + expect(field(ntpTime(Date.parse(wallClock)))).toBe(expected) + }) + + it('equals the two 32-bit words Number arithmetic gives, across the era\'s wrap and the fraction\'s exact eighths', () => { + const readings = [ + 0, + 1, + 125, + 999, + 1000, + 1000000007, + 1700000000500, + 1767225600001, + Date.parse('2026-11-12T00:00:00.000Z'), + Date.parse('2026-11-12T00:00:00.003Z'), + Date.parse('2026-11-12T00:00:00.250Z'), + Date.parse('2026-11-12T00:00:00.375Z'), + Date.parse('2026-11-12T00:00:00.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'), + Date.parse('2036-02-07T06:28:16.875Z'), + Date.parse('2040-01-01T12:34:56.789Z'), + Date.parse('2100-01-01T00:00:00.000Z'), + Date.parse('2100-01-01T00:00:00.123Z'), + ] + + expect(readings).toHaveLength(20) + + for (const now of readings) { + expect({ + field: field(ntpTime(now)), + now, + }).toEqual({ + field: numberWords(now), + now, + }) + } + }) +}) diff --git a/src/lib/util/ntp.ts b/src/lib/util/ntp.ts new file mode 100644 index 000000000..031a16528 --- /dev/null +++ b/src/lib/util/ntp.ts @@ -0,0 +1,17 @@ +// 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 + +/** + * 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 + * unreduced: it passes 2^64 on 2036-02-07 when the seconds pass 2^32, and a writer of a 64-bit NTP field reduces it modulo 2^64 for the era. + * @param unixMilliseconds - The wall clock in whole milliseconds since the Unix epoch. + * @returns The NTP time. + */ +export function ntpTime(unixMilliseconds: number): bigint { + return ((BigInt(unixMilliseconds) + NTP_UNIX_OFFSET_MILLISECONDS) << NTP_FRACTION_BITS) / 1000n +} diff --git a/src/test-utils/MockIngestServer.ts b/src/test-utils/MockIngestServer.ts new file mode 100644 index 000000000..f87fa751b --- /dev/null +++ b/src/test-utils/MockIngestServer.ts @@ -0,0 +1,238 @@ +import type { Http2SecureServer, IncomingHttpHeaders, ServerHttp2Session, ServerHttp2Stream } from 'node:http2' +import type { AddressInfo } from 'node:net' + +import { Buffer } from 'node:buffer' +import { readFileSync } from 'node:fs' +import http2 from 'node:http2' +import { setTimeout as sleep } from 'node:timers/promises' + +/* The mock's certificates are fixtures generated once and committed: no run needs openssl and nothing is minted in-process. They were made in a scratch + * directory by these commands, each certificate valid for a hundred years, and the CA keys were discarded: + * + * # OpenSSL 3.0 or later: LibreSSL's x509 -req fails here for want of a serial file. + * ca() { openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout "$1.key" -out "$1.pem" -days 36500 -subj "/CN=$2" \ + * -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign; } + * leaf() { openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -keyout "$1.key" -out "$1.csr" -subj "/CN=$2" && \ + * openssl x509 -req -in "$1.csr" -CA "$3.pem" -CAkey "$3.key" -out "$1.pem" -days 36500 -extfile <(printf "$4"); } + * ca server-ca "Mock Ingest Server CA"; ca hub-ca "Mock Hub CA"; ca stranger-ca "Untrusted CA" + * leaf server localhost server-ca "subjectAltName=DNS:localhost\nextendedKeyUsage=serverAuth" + * leaf client 0E:AE:FC:45:7B:91 hub-ca "extendedKeyUsage=clientAuth" + * leaf stranger 0E:AE:FC:45:7B:92 stranger-ca "extendedKeyUsage=clientAuth" + */ +function fixture(name: string): string { + return readFileSync(new URL(`./ingest/${name}`, import.meta.url), 'utf8') +} + +/** + * The PEM fixtures of an ingest test: the server's CA, the hub's CA with the client certificate and key it issued, and a stranger's CA, certificate and key + * no mock trusts by default. + */ +export const INGEST_CERTIFICATES = Object.freeze({ + clientCertificate: fixture('client.pem'), + clientKey: fixture('client.key'), + hubCA: fixture('hub-ca.pem'), + serverCA: fixture('server-ca.pem'), + strangerCA: fixture('stranger-ca.pem'), + strangerCertificate: fixture('stranger.pem'), + strangerKey: fixture('stranger.key'), +}) + +const SERVER_CERTIFICATE = fixture('server.pem') +const SERVER_KEY = fixture('server.key') + +// The stretch of a request's body one drain pause stands for, 16 KiB: a chunk pauses once for each stretch it starts. +const DRAIN_STRETCH = 16384 + +/** + * One request the mock read whole. + */ +export interface MockIngestRequest { + method: string + path: string + headers: IncomingHttpHeaders + body: Buffer +} + +/** + * How the mock answers a request: a status with an optional body, `location` and delay, a reset of the stream with an HTTP/2 error code, or no answer + * at all, the stream held open. + */ +export type MockIngestAnswer + = | { body?: string, delay?: number, location?: string, status: number } + | { reset: number } + | { hold: true } + +/** + * The mock's options. + */ +export interface MockIngestServerOptions { + /** + * Whether a client without a certificate under the client CAs is refused, true by default. + */ + requireClientCertificate?: boolean + /** + * The CAs the mock trusts for client certificates, as PEM, the hub's CA by default. + */ + clientCAs?: string + /** + * The answer to each request once its body is read, 201 by default. + */ + answer?: (request: MockIngestRequest) => MockIngestAnswer + /** + * A pause per 16 KiB of a request's body the mock reads, in milliseconds, taken after each chunk once for every 16 KiB stretch the chunk starts. A body + * drains slowly whatever chunking the runtime delivers. + */ + drainDelay?: number +} + +/** + * A local HTTP/2 publishing point with mutual TLS, serving `https://localhost:/point/` from 127.0.0.1 under the server fixture certificate. It records + * each request it reads whole, answers as its options say, and follows the sessions clients hold open with it. + */ +export class MockIngestServer implements AsyncDisposable { + /** + * Every request read whole, in the order the mock read them. + */ + readonly requests: MockIngestRequest[] = [] + + /** + * The publishing point's URL. + */ + readonly url: string + + private readonly server: Http2SecureServer + + private readonly options: MockIngestServerOptions + + private readonly sessions = new Set() + + private disposed = false + + private constructor(server: Http2SecureServer, options: MockIngestServerOptions) { + this.server = server + this.options = options + this.url = `https://localhost:${(server.address() as AddressInfo).port}/point/` + + server.on('session', (session) => { + this.sessions.add(session) + session.on('close', () => this.sessions.delete(session)) + session.on('stream', (stream, headers) => void this.serve(stream, headers)) + }) + } + + /** + * Starts a mock on a free port. + * @param options - The mock's options. + * @returns The listening mock. + */ + static async start(options: MockIngestServerOptions = {}): Promise { + const { clientCAs = INGEST_CERTIFICATES.hubCA, requireClientCertificate = true } = options + const server = http2.createSecureServer({ + allowHTTP1: false, + ca: clientCAs, + cert: SERVER_CERTIFICATE + INGEST_CERTIFICATES.serverCA, + key: SERVER_KEY, + rejectUnauthorized: requireClientCertificate, + requestCert: true, + }) + + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', () => { + server.off('error', reject) + resolve() + }) + }) + + return new MockIngestServer(server, options) + } + + /** + * The sessions clients hold open with the mock. + */ + get openSessions(): number { + return this.sessions.size + } + + /** + * Sends GOAWAY on every open session. + */ + goaway(): void { + for (const session of this.sessions) { + session.goaway() + } + } + + /** + * Destroys every open session and closes the server. + */ + async [Symbol.asyncDispose](): Promise { + if (this.disposed) { + return + } + + this.disposed = true + + for (const session of this.sessions) { + session.destroy() + } + + await new Promise(resolve => this.server.close(() => resolve())) + } + + private async serve(stream: ServerHttp2Stream, headers: IncomingHttpHeaders): Promise { + // A stream the mock resets errors on its own side as well, and a client may cancel any stream, which is why every stream carries a listener. + stream.on('error', () => {}) + + const chunks: Buffer[] = [] + + try { + for await (const chunk of stream) { + chunks.push(chunk) + + if (this.options.drainDelay !== undefined) { + await sleep(this.options.drainDelay * Math.ceil(chunk.length / DRAIN_STRETCH)) + } + } + } catch { + return + } + + const request: MockIngestRequest = { + body: Buffer.concat(chunks), + headers, + method: String(headers[':method']), + path: String(headers[':path']), + } + + this.requests.push(request) + + const answer = this.options.answer?.(request) ?? { status: 201 } + + if ('hold' in answer) { + return + } + + if ('reset' in answer) { + stream.close(answer.reset) + + return + } + + if (answer.delay !== undefined) { + await sleep(answer.delay) + } + + if (stream.destroyed) { + return + } + + stream.respond({ + ':status': answer.status, + ...(answer.location === undefined + ? {} + : { location: answer.location }), + }) + stream.end(answer.body) + } +} diff --git a/src/test-utils/ingest/client.key b/src/test-utils/ingest/client.key new file mode 100644 index 000000000..63de4bb78 --- /dev/null +++ b/src/test-utils/ingest/client.key @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgTGIG8w8L4KaQL8Ia +US5r4o310GCJDAkApw4HJ+02jZehRANCAASQ5QUmA1elNLNlVYqcn6953tT9VYLO +549v2Y4/KwKt1X3gLenA/Zo92fDrNgFSOEs+wAdicLjLHOiw4tH5T15d +-----END PRIVATE KEY----- diff --git a/src/test-utils/ingest/client.pem b/src/test-utils/ingest/client.pem new file mode 100644 index 000000000..eb52ccd80 --- /dev/null +++ b/src/test-utils/ingest/client.pem @@ -0,0 +1,9 @@ +-----BEGIN CERTIFICATE----- +MIIBSzCB86ADAgECAhR6ErfCNSnUoyTTgNbcvsJW+grmojAKBggqhkjOPQQDAjAW +MRQwEgYDVQQDDAtNb2NrIEh1YiBDQTAgFw0yNjExMTMwNDQ0MTNaGA8yMTI2MTAy +MDA0NDQxM1owHDEaMBgGA1UEAwwRMEU6QUU6RkM6NDU6N0I6OTEwWTATBgcqhkjO +PQIBBggqhkjOPQMBBwNCAASQ5QUmA1elNLNlVYqcn6953tT9VYLO549v2Y4/KwKt +1X3gLenA/Zo92fDrNgFSOEs+wAdicLjLHOiw4tH5T15doxcwFTATBgNVHSUEDDAK +BggrBgEFBQcDAjAKBggqhkjOPQQDAgNHADBEAiAXHMpeacC9YvY6jrAgR09LcYhJ +epy26bLtU8PMarhnrgIgO2dy4VJymxIBPIh8/czSyceDB6C4p2Sz8bYoHmdJVY0= +-----END CERTIFICATE----- diff --git a/src/test-utils/ingest/hub-ca.pem b/src/test-utils/ingest/hub-ca.pem new file mode 100644 index 000000000..c0688ac1c --- /dev/null +++ b/src/test-utils/ingest/hub-ca.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBcTCCARigAwIBAgIURkvSkmAX1WMiH3F1A+ewn15dYZUwCgYIKoZIzj0EAwIw +FjEUMBIGA1UEAwwLTW9jayBIdWIgQ0EwIBcNMjYxMTEzMDQ0NDEzWhgPMjEyNjEw +MjAwNDQ0MTNaMBYxFDASBgNVBAMMC01vY2sgSHViIENBMFkwEwYHKoZIzj0CAQYI +KoZIzj0DAQcDQgAEuhEJ/68pGPKN8lPV0TgXf3n5nCWkZ2eD9ww7XljZBaP9Ge2B +zubDZSYcQbI3AbdMng7w/M8Cnsp/v1x4k5AIA6NCMEAwHQYDVR0OBBYEFFWAMKUj +lTtt6YFvPf9SznsPNhy9MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgIE +MAoGCCqGSM49BAMCA0cAMEQCIBzRhgwCryXg4TriB/rg0FKkWbCihEc/XO5ZtRxb +pT6FAiB6C+idoXS5N+XT1AqJSCPgM4qNNdXf0HRf+5nX4qUayw== +-----END CERTIFICATE----- diff --git a/src/test-utils/ingest/server-ca.pem b/src/test-utils/ingest/server-ca.pem new file mode 100644 index 000000000..225a3f1b9 --- /dev/null +++ b/src/test-utils/ingest/server-ca.pem @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE----- +MIIBhjCCASygAwIBAgIUDKdr3O0EmB975jyZWC0/c++Iny8wCgYIKoZIzj0EAwIw +IDEeMBwGA1UEAwwVTW9jayBJbmdlc3QgU2VydmVyIENBMCAXDTI2MTExMzA0NDQx +M1oYDzIxMjYxMDIwMDQ0NDEzWjAgMR4wHAYDVQQDDBVNb2NrIEluZ2VzdCBTZXJ2 +ZXIgQ0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQ9vFDw9ECbB5pmb/Q3xd1E +rqgbCiDIyqkblfGKv2dGjZQKsgC+EvVYfgrobk4NDDaqdeYQoDWeDXG+Z+KD9HKy +o0IwQDAdBgNVHQ4EFgQUt6aROHorCGbElNbhq8JWliOaMlUwDwYDVR0TAQH/BAUw +AwEB/zAOBgNVHQ8BAf8EBAMCAgQwCgYIKoZIzj0EAwIDSAAwRQIgBaVDx+Lg8IwQ +c45tn96oRpGc14mmexUpuMBsP88GON0CIQCCGEFv3nAB//gKPKZ9LKN6osqEVfT3 +A8/wXtK89ZGkJA== +-----END CERTIFICATE----- diff --git a/src/test-utils/ingest/server.key b/src/test-utils/ingest/server.key new file mode 100644 index 000000000..fd29596cf --- /dev/null +++ b/src/test-utils/ingest/server.key @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiW2sSBeYn3kVfHts +bw7yMeF1qTZPkWYyu5UJG/1D/cWhRANCAASeBFPky/+zaBm/AXkum1sjZchSdmsh +pMvtol6UV26+JxzVfuwWh9as1/0aiLr5NGiasCUn+c/YLwGnG4UGZyzw +-----END PRIVATE KEY----- diff --git a/src/test-utils/ingest/server.pem b/src/test-utils/ingest/server.pem new file mode 100644 index 000000000..3984388d4 --- /dev/null +++ b/src/test-utils/ingest/server.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBZDCCAQugAwIBAgIUVnctLUHJ/Wl8v+39QcuPrzroZhYwCgYIKoZIzj0EAwIw +IDEeMBwGA1UEAwwVTW9jayBJbmdlc3QgU2VydmVyIENBMCAXDTI2MTExMzA0NDQx +M1oYDzIxMjYxMDIwMDQ0NDEzWjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcq +hkjOPQIBBggqhkjOPQMBBwNCAASeBFPky/+zaBm/AXkum1sjZchSdmshpMvtol6U +V26+JxzVfuwWh9as1/0aiLr5NGiasCUn+c/YLwGnG4UGZyzwoy0wKzAUBgNVHREE +DTALgglsb2NhbGhvc3QwEwYDVR0lBAwwCgYIKwYBBQUHAwEwCgYIKoZIzj0EAwID +RwAwRAIgJiB438PeJJwtSue4nUWbzDomkjZdnilu9J4cHilHKQ0CIA1ZRgOy5Ndx +24kbSyI8m5Ab+ZMm/7IuRH1hlOw1kJrA +-----END CERTIFICATE----- diff --git a/src/test-utils/ingest/stranger-ca.pem b/src/test-utils/ingest/stranger-ca.pem new file mode 100644 index 000000000..4c9b38c33 --- /dev/null +++ b/src/test-utils/ingest/stranger-ca.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBczCCARqgAwIBAgIUFwEyJcCB7WzY3kTabkaECpwPHZUwCgYIKoZIzj0EAwIw +FzEVMBMGA1UEAwwMVW50cnVzdGVkIENBMCAXDTI2MTExMzA0NDQxM1oYDzIxMjYx +MDIwMDQ0NDEzWjAXMRUwEwYDVQQDDAxVbnRydXN0ZWQgQ0EwWTATBgcqhkjOPQIB +BggqhkjOPQMBBwNCAASqAEjZcG50x5GfGOEZ9VkklqLj23geYwcrujhTe+LiNEbB +WdOPFOOeT+YJ6N7nnL0iP2HpYEooLDm6guLzMgYxo0IwQDAdBgNVHQ4EFgQUK4Rh +X9AnQT/vBvasuXhZ0ZqihAcwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AgQwCgYIKoZIzj0EAwIDRwAwRAIgaDnQ7cigjPCwwqRKcKh+qbBgidJ4f3GkwJf2 +g2Fo0gYCIAXqjAyWS7B8YO82bw+4BwCtyS4o/My5vuuntXulamjp +-----END CERTIFICATE----- diff --git a/src/test-utils/ingest/stranger.key b/src/test-utils/ingest/stranger.key new file mode 100644 index 000000000..9370093b2 --- /dev/null +++ b/src/test-utils/ingest/stranger.key @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgvkuWhtkgGug6FUCP +hLVfcsT9Z6Jvqz9qzYagomS3dAmhRANCAARHNCWEgOPr7Cm83NT7ZYdjUkTzUNME +yfOEQFHGjp5Hc17P2QhRWDZIvJYW58FfkoLK9sTq3HlN1IMpZG9+CWpm +-----END PRIVATE KEY----- diff --git a/src/test-utils/ingest/stranger.pem b/src/test-utils/ingest/stranger.pem new file mode 100644 index 000000000..da2c7d629 --- /dev/null +++ b/src/test-utils/ingest/stranger.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBTTCB9KADAgECAhR1Ce2MZkL3XEloVK7DRzmbZMzWyjAKBggqhkjOPQQDAjAX +MRUwEwYDVQQDDAxVbnRydXN0ZWQgQ0EwIBcNMjYxMTEzMDQ0NDEzWhgPMjEyNjEw +MjAwNDQ0MTNaMBwxGjAYBgNVBAMMETBFOkFFOkZDOjQ1OjdCOjkyMFkwEwYHKoZI +zj0CAQYIKoZIzj0DAQcDQgAERzQlhIDj6+wpvNzU+2WHY1JE81DTBMnzhEBRxo6e +R3Nez9kIUVg2SLyWFufBX5KCyvbE6tx5TdSDKWRvfglqZqMXMBUwEwYDVR0lBAww +CgYIKwYBBQUHAwIwCgYIKoZIzj0EAwIDSAAwRQIhAMB1dm2TYWLWpxwKr6KGjlBF +YU3n1XIzv30En+bQW9WsAiA2b6rCQ8n0h6on5W26joRYiNK8hLtgrqvf9k7CFttT +MQ== +-----END CERTIFICATE----- From 8403863dc1092e925b5f9eef5f8fd3931c84df43 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:49 -0600 Subject: [PATCH 12/16] feat(camera): add each video sensor's tier table, pacing every tier's frames from its camera buffer and keeping the tiers a camera holds itself running --- src/lib/camera/StreamingOptions.ts | 25 + src/lib/camera/TierPacer.ts | 492 +++++ src/lib/camera/TierTable.ts | 1886 ++++++++++++++++++++ src/lib/camera/buffer/CameraBuffer.spec.ts | 822 +++++++++ src/lib/camera/buffer/CameraBuffer.ts | 720 ++++++++ src/lib/camera/buffer/TierKeeper.ts | 485 +++++ src/lib/camera/index.ts | 1 + 7 files changed, 4431 insertions(+) create mode 100644 src/lib/camera/TierPacer.ts create mode 100644 src/lib/camera/TierTable.ts create mode 100644 src/lib/camera/buffer/CameraBuffer.spec.ts create mode 100644 src/lib/camera/buffer/CameraBuffer.ts create mode 100644 src/lib/camera/buffer/TierKeeper.ts diff --git a/src/lib/camera/StreamingOptions.ts b/src/lib/camera/StreamingOptions.ts index b90a69d31..34e8f1f86 100644 --- a/src/lib/camera/StreamingOptions.ts +++ b/src/lib/camera/StreamingOptions.ts @@ -641,6 +641,31 @@ export interface MultiTierStreamingOptions { maxSessions?: number } +/** + * The newest keyframe of a video sensor's best running tier, as a movie of that one picture. The library keeps the movie and hands the same one again + * while that keyframe is the newest, which is why a plugin reads its bytes and never changes them. + * + * @group Camera + */ +export interface CameraKeyframe { + /** + * An MP4 of the one HEVC picture: an initialization segment and one fragment holding the keyframe. + */ + readonly movie: Buffer + /** + * The picture's width in pixels, from the stream's description. + */ + readonly width: number + /** + * The picture's height in pixels, from the stream's description. + */ + readonly height: number + /** + * The picture's age in milliseconds since it arrived. + */ + readonly age: number +} + /** * What the options boundary answers for a camera's video sensors, each sensor in the plugin's order. */ diff --git a/src/lib/camera/TierPacer.ts b/src/lib/camera/TierPacer.ts new file mode 100644 index 000000000..e8d99c50b --- /dev/null +++ b/src/lib/camera/TierPacer.ts @@ -0,0 +1,492 @@ +import type { BufferedSample, BufferPlace, TierBuffer } from './buffer/CameraBuffer.js' +import type { StreamTierMedium } from './StreamingOptions.js' + +/* The pacing rule's figures, those of homebridge-plugin-utils' Mp4FrameFeed, whose rule a viewer's eye passed on a camera's own fragments. + * + * The floor is the smallest lateness of the arrivals that came within its window, the one in hand included, and the target stands no higher than the + * ceiling above it. A longer window keeps the ceiling on the lateness a stream had before a stall through a longer stall, and a shorter one lets the ceiling + * follow a stream whose every arrival grew later sooner. The target falls slowly while fragments arrive earlier than it: first pictures stay held to a + * late arrival's lateness through the jitter that recurs after it, giving that delay back gradually. The ceiling is the most delay the pacer adds to a + * fragment's first picture, which bounds how long a stall's catch-up holds a stream back. + */ +const FLOOR_WINDOW = 2000 +const TARGET_FALL_PER_SECOND = 2 +const ADDED_DELAY_CEILING = 200 + +/** + * What a pacer releases to: its tier's demand, which hands each sample it is given to the half of its medium. + */ +export interface PacedDemand { + /** + * Whether a consumer of the demand has an opening whose keyframe the buffer still keeps and which has taken no start yet or waits on its session's room, + * which means the pacer's next turn runs a millisecond on: the opening takes its start in that turn, ahead of the next live picture's release, or the event loop + * frees the room between. An opening that has its start and waits for the live edge, or that waits for the next keyframe's release, counts for nothing + * here, and is handed on in the turn of the release it waits for. + */ + behind(): boolean + /** + * Whether a packet or a frame consumer is joined to the demand, behind the live releases or among them, which means a sample released is sent and not let go. + * The library's own hold of the tier is no consumer. + */ + consumed(): boolean + /** + * Hands one released sample to the half of its medium, which places it on the demand's run and sends it to the consumers joined for its medium. + * @param sample - The sample. + * @param now - The moment of the release, in milliseconds of the steady clock. + */ + release(sample: BufferedSample, now: number): void + /** + * Ends the run of times the samples released so far stood on, and the next sample released opens a later one. + */ + endRun(): void + /** + * Hands each consumer in an opening the pictures of its opening the live edge has reached, in a turn of the pacer's after that turn's releases, which + * move the edge and place the keyframe an opening takes its start from. + * @param now - The moment of the turn, in milliseconds of the steady clock. + */ + open(now: number): void +} + +// An arrival and its lateness, the arrival less the video time its fragment's first picture falls at, each in milliseconds: an arrival in the floor's +// window, or the target with the arrival it was last set at. +interface Arrival { + readonly at: number + readonly lateness: number +} + +/* When the samples of one fragment fall due, read once at the fragment's end: its first picture as it leaves, at its start or, when the fragment before it + * still holds its own first picture past that start, as that picture leaves; every later sample of the fragment at that leaving plus its decode time's + * distance from the first picture, a sound timed before the picture at the leaving itself; and whatever the fragment has left once the next fragment's + * start falls due, never before its own first picture. A fragment of sound alone takes the schedule of the last fragment of its run that held a picture, + * or, before any, a schedule that leaves at its own arrival. Each schedule belongs to the run of the pacer it was made in, and every sample of a run that + * has ended is due at once. + */ +interface Schedule { + readonly run: number + // The moment the fragment's first picture leaves, in milliseconds of the steady clock. + readonly leaves: number + // The first picture's decode time in microseconds, which every sample of the fragment is due at its distance from. + readonly first: number + // The next fragment's start, past which nothing of this fragment waits, and no moment at all until that fragment has ended. + until: number +} + +/* Adds an arrival to the floor's window and answers the smallest lateness the window holds with it. The window keeps its arrivals in the order they came, + * each with a lateness below every one after it, and its first holds the smallest: an arrival leaves from the front once the newest is the window's length + * after it or more, and from the back once a newer one is no later, since the newer one stays in the window longer and the older one can never be the + * smallest again. + */ +function joinFloor(window: Arrival[], at: number, lateness: number): number { + for (let oldest = window.at(0); (oldest !== undefined) && ((at - oldest.at) >= FLOOR_WINDOW); oldest = window.at(0)) { + window.shift() + } + + for (let newest = window.at(-1); (newest !== undefined) && (newest.lateness >= lateness); newest = window.at(-1)) { + window.pop() + } + + const smallest = window.at(0)?.lateness ?? lateness + + window.push({ at, lateness }) + + return smallest +} + +/** + * One tier demand's pacer, which sends the tier's samples to every viewer at once on one schedule, read from the stream's own times and its arrivals. + * + * It hears the tier's buffer through a place that holds no keyframe, which is why it holds no head and no trim displaces it: it is told each sample the buffer + * takes, kept or passed over, each fragment's end and each run's end. It keeps the samples it was told and has not released by reference, never by copy: + * a run's end, which empties the buffer inside the plugin's call, loses none of them. It releases each to its demand on its one timer, in a turn of + * its own and never inside a plugin's call of the stream. A sample is released once its due moment passes, sent where a consumer is joined and let go + * where none is. + * + * The rule: a fragment arrives as the buffer is told its end, its last byte, and its lateness is that arrival less its first picture's decode time's + * distance from its run's first picture. Its start is its arrival plus the target less that lateness, never less than its arrival. The target rises at once + * to a later arrival and falls slowly while arrivals come earlier, never below the lateness in hand, and stands no higher than the ceiling above the floor, + * which is why recurring jitter is paced at the latest late arrival's lateness and a stall leaves the stream at most the ceiling behind its floor. A fragment of sound + * alone enters none of the rule's state. The rule starts afresh at each run's end, an initialization segment's among them, and what an ended run left leaves + * first, in order, in the pacer's next turn. + * + * The schedule is the paced write's, which the rule was measured on, but for choices the pacer makes. What an ended run left leaves in the next turn, where + * the paced write holds a fragment queued ahead of a new header to its own due time. A new run never waits on an old one. Sound is due by its own decode + * time, where the paced write sent it with the picture its bytes adjoined: it plays at its own moment whatever a fragment's layout. On a stream whose + * pictures are out of presentation order, a sound leaves about one composition offset after the picture it plays with, each due by its decode time. A + * fragment of sound alone leaves the schedule of a fragment still held as it stands and is due by its own decode times, where the measured feed wrote it + * whole behind the held fragment, which then sent the frames it had left at once. And a fragment whose picture the format check refuses reaches the buffer + * without it, which means the pacer reads it as a fragment of sound alone and it enters neither the floor nor the target, where the measured feed read every + * fragment it cut into the floor and the target. + * + * With no consumer joined it keeps the rule's state at each fragment's end, lets go each sample whose due moment has passed, read at each fragment's end and + * at a join, and arms no timer; with one joined it lets nothing go unsent. A consumer in an opening counts as joined, and each turn hands it its opening + * after the turn's releases: the opening reads where the releases end and each picture of it is handed once the live edge, which a release moves, has + * reached its timestamp. While the buffer keeps an opening's keyframe, a turn runs a millisecond on for an opening that has taken no start yet, which + * takes it in that turn, and the next live picture's release reaches its keyframe. While the buffer keeps the keyframe of an opening whose session's room holds it + * back, a turn runs a millisecond after the one before: the event loop runs the send completions that free the room between. An opening that has its start and waits for + * the live edge, or that waits for the next keyframe's release, arms no turn of its own: the turns run at the samples' due moments, and the one whose release it waits + * for hands it on. From its demand's failure on it releases nothing and keeps nothing more, and it gives its place up as its demand leaves its tier. + */ +export class TierPacer implements BufferPlace { + private readonly buffer: TierBuffer + private readonly demand: PacedDemand + // The samples told since the last fragment's end, which wait for that end to be scheduled. + private readonly arriving: BufferedSample[] = [] + // The samples scheduled and not yet released, in the order the stream delivered them, each beside its fragment's schedule. + private samples: BufferedSample[] = [] + private schedules: Schedule[] = [] + // The pacer's run, counted from its making, and the run of the latest sample released, whose change ends the demand's run. + private run = 0 + private releasedRun?: number + // The rule's state for the run: the floor's window, the target, the decode time of the run's first picture, in microseconds, and the last schedule of a + // fragment that held a picture. + private floor: Arrival[] = [] + private target?: Arrival + private origin?: number + private last?: Schedule + // The one timer, unref'd, and the moment it is armed for. + private timer?: ReturnType + private armedFor = Number.POSITIVE_INFINITY + private halted = false + + /** + * Makes a demand's pacer, which takes its place in the tier's buffer at once. + * @param buffer - The tier's buffer. + * @param demand - The demand the pacer releases to. + */ + constructor(buffer: TierBuffer, demand: PacedDemand) { + this.buffer = buffer + this.demand = demand + buffer.takePlace(this) + } + + /** + * Whether the pacer has stopped, at its demand's failure, as its demand left its tier or as its place was taken off, from which on it releases nothing. + */ + get stopped(): boolean { + return this.halted + } + + taken(sample: BufferedSample): void { + if (!this.halted) { + this.arriving.push(sample) + } + } + + /* A fragment's end schedules its samples on the rule, at the moment the buffer is told of it, and then arms the timer while a consumer is joined, or lets + * go what has fallen due while none is. + */ + fragmentEnd(): void { + if (this.halted) { + return + } + + const now = performance.now() + + this.schedule(now) + + if (this.demand.consumed()) { + this.arm(now) + } else { + this.release(now) + } + } + + /* A run's end makes every sample of the run due at once, those of a fragment the end cut short among them, and starts the rule afresh for the next run. + * The pacer hears a mark from its demand as the plugin makes it, and a run's end from the buffer, a mark at the stream's next sample, an initialization + * segment or a jump. A mark reaches it twice where the buffer holds a run: an end with nothing told since the one before only starts the rule afresh. + */ + ending(): void { + if (this.halted) { + return + } + + if (this.arriving.length > 0) { + this.enqueue({ + first: Number.POSITIVE_INFINITY, + leaves: Number.NEGATIVE_INFINITY, + run: this.run, + until: Number.POSITIVE_INFINITY, + }) + } + + this.run++ + this.floor = [] + this.target = undefined + this.origin = undefined + this.last = undefined + + if (this.demand.consumed()) { + this.arm(performance.now()) + } + } + + // A place that holds no keyframe is never trimmed, and one whose own call threw hears nothing more. The pacer stops as at its demand's failure. + displaced(): void { + this.halt() + } + + /** + * Releases, in a turn of the caller's own, every sample whose due moment is at or before a moment, each medium in the order the stream delivered it, the + * samples of an ended run first, and the demand's run ended between a run's last sample and the next run's first. This is the pacer's release entry, which + * its timer calls with the steady clock's moment; a caller with no timer passes a moment past every due moment to release everything scheduled, and a + * sample whose fragment has not ended is never due. + * @param now - The moment, in milliseconds of the steady clock, which each sample released is placed at. + */ + release(now: number): void { + if (this.halted) { + return + } + + // The samples due are taken off the waiting ones before the first is handed on, which is why a release that reaches the pacer again finds none of them waiting. + const due: BufferedSample[] = [] + const runs: number[] = [] + + this.collect(now, due, runs) + + for (let index = 0; index < due.length; index++) { + // A release can end its demand, a consumer's failure ending the last session that holds it, which halts the pacer. + if (this.halted) { + return + } + + const run = runs[index] + + if (run !== this.releasedRun) { + if (this.releasedRun !== undefined) { + this.demand.endRun() + } + + this.releasedRun = run + } + + this.demand.release(due[index], now) + } + } + + /** + * Lets go, while no consumer is joined, each sample whose due moment has passed, as a join reads them before its consumer is added. A consumer that + * joins takes nothing that fell due before it. + */ + letGoDue(): void { + if (!this.halted && !this.demand.consumed()) { + this.release(performance.now()) + } + } + + /** + * The place in the delivery order of the first sample of a medium a release at a moment leaves waiting, each sample of the medium before it having fallen + * due, which is how a join and an opening read which samples of the buffer have been released. + * @param medium - The medium. + * @param now - The moment, in milliseconds of the steady clock. + * @returns The sample's order, or `Infinity` while every sample of the medium the pacer was told has fallen due. + */ + waitingFrom(medium: StreamTierMedium, now: number): number { + const { samples, schedules } = this + + for (let index = 0; index < samples.length; index++) { + const sample = samples[index] + + if ((sample.track.medium === medium) && (this.dueOf(sample, schedules[index]) > now)) { + return sample.order + } + } + + return this.arriving.find(sample => sample.track.medium === medium)?.order ?? Number.POSITIVE_INFINITY + } + + /** + * Arms the timer for the next due moment while a consumer is joined, and cancels it while none is, as a join or a release of a consumer leaves the demand. + */ + follow(): void { + if (this.halted) { + return + } + + if (this.demand.consumed()) { + this.arm(performance.now()) + } else { + this.cancel() + } + } + + /** + * Stops the pacer at its demand's failure: the samples waiting are let go unsent, the timer is cancelled, and nothing more is kept or released. + */ + halt(): void { + this.halted = true + this.cancel() + this.arriving.length = 0 + this.samples = [] + this.schedules = [] + } + + /** + * Stops the pacer as its demand leaves its tier and gives its place in the tier's buffer up, before the buffer empties. + */ + close(): void { + this.halt() + this.buffer.givePlaceUp(this) + } + + /* Reads the rule at a fragment's end and schedules the fragment's samples. A fragment that holds a picture moves the floor and the target and is due at + * its own start; one of sound alone is due on the last picture's schedule, or at its own arrival before any. + */ + private schedule(arrival: number): void { + const picture = this.arriving.find(sample => sample.track.medium === 'video') + + if (picture === undefined) { + this.enqueue(this.last ?? { + first: Number.POSITIVE_INFINITY, + leaves: arrival, + run: this.run, + until: Number.POSITIVE_INFINITY, + }) + return + } + + this.origin ??= picture.time + + const lateness = arrival - (picture.time - this.origin) / 1000 + const ceiling = joinFloor(this.floor, arrival, lateness) + ADDED_DELAY_CEILING + const fallen = this.target === undefined + ? lateness + : Math.max(lateness, this.target.lateness - (arrival - this.target.at) * TARGET_FALL_PER_SECOND / 1000) + + this.target = { + at: arrival, + lateness: Math.min(fallen, ceiling), + } + + const start = arrival + Math.max(0, this.target.lateness - lateness) + const schedule: Schedule = { + first: picture.time, + leaves: Math.max(start, this.last?.leaves ?? start), + run: this.run, + until: Number.POSITIVE_INFINITY, + } + + if (this.last !== undefined) { + this.last.until = start + } + + this.last = schedule + this.enqueue(schedule) + } + + // Moves the samples told since the last fragment's end behind the samples waiting, each beside the schedule given. + private enqueue(schedule: Schedule): void { + for (const sample of this.arriving) { + this.samples.push(sample) + this.schedules.push(schedule) + } + + this.arriving.length = 0 + } + + // A sample's due moment on its schedule, at once for a sample of an ended run. + private dueOf(sample: BufferedSample, { first, leaves, run, until }: Schedule): number { + if (run !== this.run) { + return Number.NEGATIVE_INFINITY + } + + return Math.max(leaves, Math.min(leaves + Math.max(0, sample.time - first) / 1000, until)) + } + + /* Takes every sample due at or before a moment off the waiting samples into the lists given, each beside its run, in the order the stream delivered + * them, a medium's samples stopping at its first that is not due: each medium leaves in its own order and neither waits on the other. + */ + private collect(now: number, due: BufferedSample[], runs: number[]): void { + const { samples, schedules } = this + let kept = 0 + let pictureWaits = false + let soundWaits = false + + for (let index = 0; index < samples.length; index++) { + const sample = samples[index] + const schedule = schedules[index] + const picture = sample.track.medium === 'video' + const waits = picture ? pictureWaits : soundWaits + + if (!waits && (this.dueOf(sample, schedule) <= now)) { + due.push(sample) + runs.push(schedule.run) + continue + } + + if (picture) { + pictureWaits = true + } else { + soundWaits = true + } + + samples[kept] = sample + schedules[kept] = schedule + kept++ + } + + samples.length = kept + schedules.length = kept + } + + /* Arms the one timer for the next moment a sample falls due, each medium's first waiting sample being the earliest of its medium, or a millisecond on + * while an opening with its keyframe kept has taken no start yet or waits on its session's room, read from the buffer at each arming: a new opening + * takes its start ahead of the next live picture's release and each turn of an opening held back by its room yields to the event loop, whose completions + * free the room, while an opening that waits for the live edge or the next keyframe's release is handed on at the turn of that release. It keeps a timer + * armed for that moment or earlier. The timer runs at the first whole millisecond at or after the moment, and a turn never wakes before what it waits for. + */ + private arm(now: number): void { + let next = this.demand.behind() + ? now + 1 + : Number.POSITIVE_INFINITY + let pictureRead = false + let soundRead = false + + for (let index = 0; (index < this.samples.length) && !(pictureRead && soundRead); index++) { + const sample = this.samples[index] + const picture = sample.track.medium === 'video' + + if (picture ? pictureRead : soundRead) { + continue + } + + if (picture) { + pictureRead = true + } else { + soundRead = true + } + + next = Math.min(next, this.dueOf(sample, this.schedules[index])) + } + + if ((next === Number.POSITIVE_INFINITY) || ((this.timer !== undefined) && (this.armedFor <= next))) { + return + } + + this.cancel() + this.armedFor = next + this.timer = setTimeout(this.turn, Math.max(0, Math.ceil(next - now))).unref() + } + + private cancel(): void { + clearTimeout(this.timer) + this.timer = undefined + this.armedFor = Number.POSITIVE_INFINITY + } + + // The timer's turn releases what has fallen due, which moves the live edge, then hands each consumer in an opening what the edge has reached, an opening + // with no start taking it there, and arms the timer again for what is left. + private readonly turn = (): void => { + this.timer = undefined + this.armedFor = Number.POSITIVE_INFINITY + + const now = performance.now() + + this.release(now) + + if (!this.halted) { + this.demand.open(now) + } + + this.follow() + } +} diff --git a/src/lib/camera/TierTable.ts b/src/lib/camera/TierTable.ts new file mode 100644 index 000000000..8eb1e577d --- /dev/null +++ b/src/lib/camera/TierTable.ts @@ -0,0 +1,1886 @@ +import type { HAPConnection } from '../util/eventedhttp.js' +import type { BufferedSample, TierBuffer, TierBufferOptions } from './buffer/CameraBuffer.js' +import type { AudioStreamTier, VideoStreamTier } from './capabilities/streamTiers.js' +import type { CameraReporter } from './diagnostics/CameraReporter.js' +import type { Mp4StreamSample, Mp4StreamTracks, Mp4StreamVideoTrack } from './mp4/Mp4StreamReader.js' +import type { + CameraKeyframe, + MultiTierStreamingDelegate, + SensorStreamTiers, + StreamTierMedium, + TierFrame, + TierStream, + TierStreamStatistics, +} from './StreamingOptions.js' + +import { Buffer } from 'node:buffer' + +import { debugChannel } from './diagnostics/debugChannels.js' +import { frameOf, Mp4StreamReader, timeOf } from './mp4/Mp4StreamReader.js' +import { writeKeyframeMovie } from './mp4/mp4Writer.js' +import { decodable, FrameCutter, wellFormedFrame } from './rtp/FrameCutter.js' +import { RTP_HEADER_LENGTH } from './rtp/packetRules.js' +import { ClockRun, openingSpeed, RTPClock } from './rtp/RTPClock.js' +import { HandleScope } from './session/HandleScope.js' +import { DELEGATE_CALL_TIMEOUT, settleWithinBound } from './session/settleWithin.js' +import { bestStreamTier } from './StreamingOptions.js' +import { TierPacer } from './TierPacer.js' + +const TIER_DEBUG = debugChannel('HAP-NodeJS:Camera:Tier') + +// The largest plain RTP packet a demand cuts, by the address family the HAP server listens on. A packet with its tag fits each family's path. +const IPV4_PACKET_SIZE = 1378 +const IPV6_PACKET_SIZE = 1228 + +// The refusal of a stream whose initialization segment holds no video track, since every stream is a video tier's. +const NO_VIDEO_TRACK = 'The stream\'s initialization segment holds no video track.' + +// The word each half of a demand goes by in the sentences it reports. +const PARTS: Readonly> = { audio: 'sound', video: 'picture' } + +// A demand starts at its tier's first join and is started once tierDemandStarted resolves. A demand whose joins all release while its start is pending is +// ending, and a join then takes it back to starting; a demand is ended once its start is refused or once it ends, as it does where its start's own bound, a +// reset, a destroy or the camera going out of service withdraws its pending start, and what was registered on its stream is released as it becomes ended. +export type DemandState = 'starting' | 'started' | 'ending' | 'ended' + +// The sentence a cleanup registered on a demand's stream is reported under, as a plugin-failure problem, where it throws or rejects. +const END_FAILURE = 'MultiTierStreamingDelegate failed to end a tier demand' + +// What the plugin-failure problem of a demand its start's bound withdrew says became of it. +const BOUND_OUTCOME = `within ${DELEGATE_CALL_TIMEOUT / 1000} seconds: the demand is withdrawn and every join waiting on it is refused` + +/** + * The most time a started demand's stream may hand over no picture after its last, whoever holds the tier, which the keeper reads too for the gap it + * tells an open recording of. + */ +export const LONG_GAP_TIME = 10 * 1000 + +/** + * The most time a running demand's stream may hand over no picture from its camera's source being stated reconnecting, counted in place of the long-gap + * time until its next picture, which the keeper reads too for the gap. + */ +export const RECOVERING_GAP_TIME = 30 * 1000 + +// The most time from a start's settling to its demand's first picture. +const FIRST_SAMPLE_BOUND = 30 * 1000 + +// What a demand's silence clock counts, its time and the silence the stream-failed problem of its end names: the first-sample bound from the start's +// settling to the first picture, the long-gap time from each picture, and the recovering gap time from a reconnect's statement to the next picture. +const SILENCE_CLOCKS = { + first: { silence: `no picture within ${FIRST_SAMPLE_BOUND / 1000} seconds of its start's settling`, time: FIRST_SAMPLE_BOUND }, + gap: { silence: `no picture for ${LONG_GAP_TIME / 1000} seconds`, time: LONG_GAP_TIME }, + recovering: { silence: `no picture within ${RECOVERING_GAP_TIME / 1000} seconds of its source being stated reconnecting`, time: RECOVERING_GAP_TIME }, +} as const + +type SilenceClock = keyof typeof SILENCE_CLOCKS + +/* The movie of each keyframe a lookup answered, kept against the buffer's own sample. A keyframe's movie is written once and handed again while that + * keyframe is the newest, and nothing has to forget it: a kept movie goes when the buffer lets its sample go, as the buffer's span passes the sample, as + * the buffer empties, at a reset and at a removal. + */ +const keyframeMovies = new WeakMap() + +// What a tier's demands reach in the table: the camera's delegate, the camera's reporter, which every tier, demand and half reports through, the sensor +// the tiers belong to, the sensor's one RTP clock, whether the camera was given strict, under which a stream past twice its tier's peak raises a +// stream-fault problem rather than writing a debug event, and whether the camera's Microphone is muted, which the table sets for every tier at once and +// the sound half of each demand reads at each release. +export interface TierContext { + readonly delegate: MultiTierStreamingDelegate + readonly reporter: CameraReporter + readonly sensorUUID: string + readonly clock: RTPClock + readonly strict: boolean + microphoneMuted: boolean +} + +/** + * What a viewer's keyframe request came to, which the session at home and the stream from away each write as one debug event: `answered`, its consumer + * opened again from the latest keyframe released, or the first reason the checks find in their order for passing it by: `stopped` for a hold released or + * with no consumer of the picture and for a demand whose pacer has stopped, `no keyframe kept` where the buffer keeps no keyframe whose release has + * fallen due, `answered from this keyframe already` where that keyframe is the one the consumer was last answered from, `in an opening` for a consumer in + * an opening of its own, and `stopped` for a consumer that has left its half. + */ +export type KeyframeAnswer = 'answered' | 'no keyframe kept' | 'answered from this keyframe already' | 'in an opening' | 'stopped' + +/** + * How a demand's start ended for a hold that waited on it, which each holder branches on: `started` where the demand serves, `cut` where the start's own + * bound withdrew it, and `refused` for a refused start, a failed stream and a demand a reset, the + * camera's removal or the camera going out of service withdrew. A holder answers a `cut` as at a cut of its own wait. + */ +export type StartAnswer = 'started' | 'refused' | 'cut' + +/** + * What joins a tier: the holder's route for a failed tier, which ends the holder. The route is called once for each of the holder's holds on the tier, one + * still waiting on the tier's start among them, and the holder releases the hold as it ends. A holder carries no connection: the library holds a tier + * itself with none, and a packet join hands in its own session's connection for the packet size. + */ +export interface TierHolder { + /** + * Ends the holder for a tier whose stream failed. + */ + tierFailed(): void +} + +// What a demand sends each of its packets to: one session's sending half for one medium, answering whether a buffer was free for the packet, sent at the +// moment of the packet's release or of its opening's turn. A throw is reported once, as a library-failure problem, and ends the consumer through its +// holder's route, and the consumers after it are still sent the packet. The consumer answers the packets it can take before it refuses one, which an +// opening hands it no more than in a turn, and the packets it takes with nothing in flight, past which a frame of its opening is sent at once as a live +// release sends it, its packets refused once the consumer is full. +export interface PacketConsumer { + readonly free: number + readonly capacity: number + send(packet: Buffer, octets: number, now: number): boolean +} + +/** + * What a demand hands each frame of a medium whole, after the packets it cuts for that medium's packet consumers: a consumer that carries a frame as one + * unit, joined through a join of its own kind. It never joins or releases in the turn of its own hand-over: its way out is its holder's route or its + * holder's own end, each of which releases in a later turn. + */ +export interface FrameConsumer { + /** + * Takes one frame of the medium the consumer joined for, which the demand checked: a picture of its opening, on the opening's own timestamps, and then + * each frame the tier's pacer releases, at the timestamp the demand placed it at, but for a picture before a keyframe after the consumer's join to the + * live releases and after each run's opening, which it is never handed. A throw is reported once, as a library-failure problem, and ends the consumer + * through its holder's route, and the consumers after it still take the frame. + * @param frame - The frame, its `keyframe` with it, whose bytes the consumer reads before the call returns. + * @param timestamp - The frame's timestamp, whole, which the wire writes modulo 2^32. + * @param opensRun - Whether the frame opens a run of times for its medium, its medium's first of the run, which a live release alone carries: a + * picture of an opening is handed with it unset. + */ + take(frame: TierFrame, timestamp: number, opensRun: boolean): void +} + +/** + * What a join adds to its tier's demand, tagged by the join that made it, which its hold's release takes off again: for a packet or a frame consumer the + * medium it takes, the consumer's own and never the tier's, and the holder whose route a throw from the consumer's send or hand-over takes. A hold alone, + * the library's own hold of the tier, adds no consumer and counts among the demand's joins. + */ +export type TierJoin = { readonly kind: 'packets', readonly medium: StreamTierMedium, readonly consumer: PacketConsumer, readonly holder: TierHolder } + | { readonly kind: 'frames', readonly medium: StreamTierMedium, readonly consumer: FrameConsumer, readonly holder: TierHolder } + | { readonly kind: 'hold' } + +type PacketJoin = Extract +type FrameJoin = Extract +type MediumJoin = Exclude + +/* A consumer of the picture behind the live releases, which the pacer's turns hand the pictures released from the keyframe its opening runs from, on + * timestamps of the opening's own, until it is level with the live releases: its join, whether a viewer's keyframe request made the opening rather than + * the join, that keyframe, or the one the buffer let go while it waits for the next, the place in the delivery order of the last picture it was handed, + * where its timestamps start and the speed they run at, unset from the opening's making until its first turn that finds its keyframe kept and taken + * afresh together in the turn that takes each newer keyframe, and whether its last turn stopped on its session's room. + */ +interface Opening { + readonly join: MediumJoin + readonly answer: boolean + keyframe: BufferedSample + handed: number + start?: number + speed?: number + roomHeld: boolean +} + +// A stretch shorter than a second, the span a bitrate is stated over, is read as a second long. A stretch a moment old, nearly all keyframe, does not +// read as a heavy stream. +const SHORTEST_STRETCH = 1 + +// What a tier's stream's sound is for, from its sensor's source and its settled entry's sound: its own views' under 'tier', and under 'shared' every view's +// on the sound's tier and nothing on any other. +function tierSound(audioSource: SensorStreamTiers['audioSource'], entry: TierStream['tier']): TierSound { + if (audioSource === 'tier') { + return 'own' + } + + return entry.sound + ? 'shared' + : 'ignored' +} + +// Takes one entry off an array of consumers, and does nothing for an entry the array no longer holds, as one a hand-over that threw took off. +function leaveArray(entries: Entry[], entry: Entry): void { + const index = entries.indexOf(entry) + + if (index !== -1) { + entries.splice(index, 1) + } +} + +// Whether a consumer of an array of the live releases takes the frame in hand: any consumer while none waits for a keyframe, and otherwise one the waiting +// consumers given do not hold. +function takenBy(joins: readonly MediumJoin[], waiting: ReadonlySet | undefined): boolean { + if (waiting === undefined) { + return joins.length > 0 + } + + for (const join of joins) { + if (!waiting.has(join)) { + return true + } + } + + return false +} + +/* One medium of a demand's stream, its picture or its sound, which the demand's pacer releases each sample of that medium to: the demand's one run of the + * sensor's clock, which each half places its samples on, its cutter, whose one buffer every joined packet consumer copies each packet from, its consumers + * of each kind, those of the picture behind the live releases with their openings, those of the live pictures still waiting for a keyframe, the keyframe + * each consumer of the picture was last answered from, and what it has carried. Each kind of consumer stands in an array of its own: the packet loop + * reads one kind. Each array changes only at a join and a release, as an opening is level with the live releases, as a viewer's keyframe request + * opens a consumer again, and at a send or a hand-over that throws, which is why each walk goes by index, and a release splices only what an array holds. A sample's + * frame form, which hands a keyframe that holds each of HEVC's video, sequence and picture parameter sets as its sample's octets and copies one that holds + * fewer to put its stream's whole block of them in after its access unit delimiter or at its front, is made only for a consumer to take it, at a release + * while a consumer of the live releases is joined and in an opening for the consumer it hands it to. A half nobody takes copies nothing, and its + * samples are placed whoever is joined. The cutter is made at a packet join that finds no packet consumer of the demand joined, at the size that join's + * connection decides, and a half cuts nothing before a session at home takes it. + * + * A consumer of the live pictures is sent no picture before a keyframe, after its join and after each run's opening, since a decoder can read no picture + * whose keyframe it was never sent: a consumer of the picture the half joins to the live releases with no keyframe to open from waits for one, and so does + * every consumer of the live releases at the half's first picture of a run, whichever medium opened the run and whatever ended the last, while a keyframe's + * release ends every wait before its packets and its frame go out. A consumer opened from the buffer starts at a keyframe already, which means it joins the live + * releases with no wait. The sound half's consumers never wait, and a viewer's sound plays while its picture waits. While no consumer waits, a picture's + * release reads no more than the run's opening and the count of those waiting, and neither walk tests a consumer against them. + */ +export class DemandHalf { + /** + * The half's medium. + */ + readonly medium: StreamTierMedium + /** + * The packets the half's consumers were sent, their bytes and the frames and packets it dropped, which the stream's statistics sum. + */ + packets = 0 + bytes = 0 + drops = 0 + private readonly demand: TierDemand + private readonly buffer: TierBuffer + private readonly consumers: PacketJoin[] = [] + private readonly frameConsumers: FrameJoin[] = [] + private readonly openings: Opening[] = [] + // The consumers of the live pictures sent no keyframe since their join or their run's opening, which the live releases send no other picture. The sound + // half keeps it empty. + private readonly awaitingKeyframe = new Set() + // The place in the buffer's delivery order of the keyframe each consumer was last answered from, which a release, a send and the pacer's arming never + // read. A place holds no sample, and the places only rise for the buffer's life. A restart's keyframe is never taken for an earlier one. + private readonly answered = new Map() + private readonly run: ClockRun + // The table's context for the sound half, whose flag holds the half's live releases back while the camera's Microphone is muted, read as it stands at + // each release, and none for the picture half, which nothing mutes. + private readonly mutedBy?: Pick + private cutter?: FrameCutter + // Whether the half has warned of a keyframe without its parameter sets, once in the demand's life. + private warnedParameterSets = false + + constructor(demand: TierDemand, medium: StreamTierMedium, run: ClockRun, buffer: TierBuffer, mutedBy?: Pick) { + this.demand = demand + this.medium = medium + this.run = run + this.buffer = buffer + this.mutedBy = mutedBy + } + + /** + * The consumers joined to the half, of every kind, those in an opening among them. + */ + get joined(): number { + return this.consumers.length + this.frameConsumers.length + this.openings.length + } + + /** + * Whether an opening of the half has the pacer run its next turn a millisecond on, while the buffer still keeps its keyframe: one that has taken no start + * yet, which takes it in that turn, ahead of the next live picture's release, and that release reaches its keyframe's timestamp and hands it, and one + * whose last turn stopped on a frame its session's sender had no room for, which is why the event loop runs the send completions that free the room between. An + * opening that has its start and waits for the live edge, or that waits for the next keyframe's release, counts for nothing here, since only a release + * moves it on, and a half with no opening answers on its count alone. The pacer's arming for a tier no view is opening on reads no buffer and makes + * nothing. + */ + get behind(): boolean { + return (this.openings.length > 0) && this.openings.some(({ keyframe, roomHeld, start }) => ((start === undefined) || roomHeld) && this.buffer.keeps(keyframe)) + } + + /** + * The packet consumers joined to the half. + */ + get packetConsumers(): number { + return this.consumers.length + } + + /* Checks a sample of the half's medium for its format on its own octets, a picture's lengths tiling it and a sound's holding an octet, and answers + * whether the check lets it through. A sample it refuses is dropped and counted once, and reaches no buffer, pacer, run or consumer. No malformed + * sample reaches the cutter, a packet consumer's protect or a frame consumer. + */ + admits(sample: Mp4StreamSample): boolean { + if (wellFormedFrame(this.medium, sample.data)) { + return true + } + + this.drops++ + + return false + } + + /* Takes one sample of the half's medium as the pacer releases it, at the moment of the release: a sample that finds the demand's run ended opens it at its + * decode time, the sample is placed whoever is joined, which moves the live edge an opening waits on, and its frame form is made only for a consumer of + * the live releases to send it to, a consumer in an opening being handed it by that opening. A keyframe is read for the parameter sets its sample and its + * track carry between them, on its sample's own octets: it is read without the copy its frame form makes of a keyframe that holds fewer than each of + * them, and a keyframe that holds each of them is handed as its sample's octets. A picture reaches no consumer of the live releases still waiting for a + * keyframe, every one of them waiting from the half's first picture of a run, and a keyframe ends every wait before it goes out. A consumer's first live + * picture after its join and after each run's opening is a keyframe, while its sound flows meanwhile. The sound half sends nothing while the camera's + * Microphone is muted, its samples still placed, which is why the run's clock moves on through the mute and the sound resumes in step. The sound half makes nothing for + * a sample it holds back. + */ + release(sample: BufferedSample, now: number): void { + const { data, track } = sample + const time = timeOf(sample) + + if (!this.run.open) { + this.run.openAt(sample.time, now) + } + + const timestamp = this.place(time) + + if (timestamp === undefined) { + return + } + + if (!this.warnedParameterSets && sample.sync && (track.medium === 'video')) { + this.checkParameterSets(data, track.parameterSets) + } + + if (((this.consumers.length + this.frameConsumers.length) > 0) && !this.mutedBy?.microphoneMuted) { + const waiting = (track.medium === 'video') + ? this.stillWaiting(sample.sync) + : undefined + + this.send(frameOf(sample, time), timestamp, this.run.opened, now, waiting) + } + } + + // Makes the half's cutter over a buffer of a packet's size, in place of any earlier cutter, its packets numbered by each consumer that sends them. + makeCutter(packetSize: number): void { + this.cutter = new FrameCutter(this.medium, Buffer.alloc(packetSize)) + } + + /* A join adds its consumer to the live releases, in the array of the kind its join tagged it with, or, given the keyframe its opening runs from, behind + * them, where the pacer's turns hand it its opening until it is level. A consumer of the picture joining the live releases waits there for the next + * keyframe the pacer releases. An opening has no start until its first turn, which the pacer runs a millisecond after it is made, and takes its start + * there after that turn's releases: nothing of it is read between turns. + */ + add(join: MediumJoin, keyframe?: BufferedSample): void { + if (keyframe !== undefined) { + this.openOn(join, keyframe, false) + return + } + + this.joinLive(join) + + if (join.medium === 'video') { + this.awaitingKeyframe.add(join) + } + } + + // A consumer leaves the half wherever it stands, in an opening or among the live releases, and the keyframe it was last answered from and its wait for a + // keyframe go with it. + remove(join: MediumJoin): void { + const opening = this.openings.findIndex(behind => behind.join === join) + + this.answered.delete(join) + this.awaitingKeyframe.delete(join) + + if (opening !== -1) { + this.openings.splice(opening, 1) + } else if (join.kind === 'packets') { + leaveArray(this.consumers, join) + } else { + leaveArray(this.frameConsumers, join) + } + } + + /* Answers a viewer's keyframe request for one consumer of the picture, given the latest keyframe the buffer keeps whose release has fallen due, and + * answers what the request came to. A consumer among the live releases leaves them and opens again from that keyframe, as a join's opening does, its + * start taken in the pacer's turn and any wait for a keyframe ended, since the opening begins at one, and the keyframe becomes the one it was last + * answered from: it is answered once for each keyframe. A consumer in an opening of its own, a join's or an answer's, is passed by, since its opening + * sends it that stretch already, and so is one whose latest keyframe is the one it was last answered from, since a burst that did not take is never sent + * again, and one that has left its half, or a request where the buffer keeps no keyframe released, opens nothing. The reason passed by is the first these + * checks find, in the order the keyframe, the keyframe last answered from and the consumer's place. A join's opening counts for nothing, which is why a viewer's + * first request after its join is answered. + */ + answer(join: MediumJoin, keyframe: BufferedSample | undefined): KeyframeAnswer { + if (keyframe === undefined) { + return 'no keyframe kept' + } + + if (this.answered.get(join) === keyframe.order) { + return 'answered from this keyframe already' + } + + // The live releases hold neither a consumer in an opening nor one that has left its half, and the half's openings tell the one from the other. + if (!this.leaveLive(join)) { + return this.openings.some(opening => opening.join === join) + ? 'in an opening' + : 'stopped' + } + + this.answered.set(join, keyframe.order) + this.awaitingKeyframe.delete(join) + this.openOn(join, keyframe, true) + + return 'answered' + } + + /* Hands each consumer in an opening, in a turn of the pacer's after that turn's releases, the pictures the pacer has released from the keyframe its + * opening runs from, in the order the buffer's walk reads them and on the opening's own timestamps, each once the live edge has reached it, and joins it + * to the live releases in the turn it has been handed every one: it is handed no picture twice and misses none, and every live picture after it + * stands above every timestamp its opening was handed. A packet consumer is handed whole frames while they fit its room, which is why no packet of a frame that can + * fit is refused and the turn after yields to the event loop, whose completions free its room. A frame consumer is handed each picture the edge has + * reached. A frame of more packets than the packet consumer takes with nothing in flight never fits its room, and it is sent at once as a live release + * sends it, each packet the consumer refuses dropped and counted, and the opening goes on to the next picture. Where the buffer has let the opening's + * keyframe go, at a run's end, as its head moved or at a ceiling's drop, the opening reads its cases again, whatever it has been handed: it carries on + * from the latest keyframe the buffer keeps whose release has fallen due, its timestamps starting afresh, and otherwise waits, sent nothing, and opens + * from the next keyframe in the turn that releases it. No consumer joins the live releases before it has been handed every released picture from a + * keyframe on. Each turn reads the consumers still in an opening, and every send goes through the catch a release's does: none is sent anything once + * it has left and nothing is thrown out of the turn. + */ + open(now: number): void { + for (const opening of [...this.openings]) { + if (this.demand.pacer.stopped) { + return + } + + if (this.openings.includes(opening) && this.catchUp(opening, now)) { + leaveArray(this.openings, opening) + this.joinLive(opening.join) + } + } + } + + // Places a frame on the demand's open run. A sound timed before the run's origin is not placed, and is dropped and counted. + private place(time: number): number | undefined { + const timestamp = this.run.place(this.medium, time) + + if (timestamp === undefined) { + this.drops++ + } + + return timestamp + } + + /* Reads a placed picture against the consumers of the live releases waiting for a keyframe, and answers those that wait past it, or nothing while none + * does: a keyframe ends every wait, before its packets and its frame go out, whatever packets a session's room then refuses of it, a loss that session's + * own keyframe request recovers, and the half's first picture of a run that is no keyframe has every consumer of the live releases wait. A restart's + * pictures before its keyframe reach none of them. The run's opening is read after the picture's own placing: it says whether this picture is the + * run's first. + */ + private stillWaiting(keyframe: boolean): ReadonlySet | undefined { + const { awaitingKeyframe } = this + + if (keyframe) { + awaitingKeyframe.clear() + + return undefined + } + + if (this.run.opened) { + for (const join of this.consumers) { + awaitingKeyframe.add(join) + } + + for (const join of this.frameConsumers) { + awaitingKeyframe.add(join) + } + } + + return (awaitingKeyframe.size > 0) + ? awaitingKeyframe + : undefined + } + + /* Sends a placed frame to the consumers of the live releases that take it, its packets to every packet consumer and then the frame whole to every frame + * consumer, each told whether the frame is its medium's first of the run. A consumer the waiting consumers given hold takes no picture, and is neither + * sent the frame nor counted as dropping it; they are given only while one waits, and neither walk tests a consumer while none does. + */ + private send(frame: TierFrame, timestamp: number, opensRun: boolean, now: number, waiting: ReadonlySet | undefined): void { + if (this.consumers.length > 0) { + this.sendPackets(frame, timestamp, opensRun, now, waiting) + } + + if (this.frameConsumers.length > 0) { + this.handOver(frame, timestamp, opensRun, waiting) + } + } + + /* Cuts a placed frame into packets while a packet consumer takes it, each packet handed to every packet consumer that takes it in turn before the next is + * made. A picture every packet consumer waits past is not cut. A sound longer than the cutter's payload is dropped and counted at the cut, and it + * reaches no session at home and still reaches every frame consumer. Every send runs in the pacer's turn: each goes through one catch, which takes a + * consumer that throws off. The walk reads the array's length at each step, which is why the consumers after it are still sent the packet. + */ + private sendPackets(frame: TierFrame, timestamp: number, opensRun: boolean, now: number, waiting: ReadonlySet | undefined): void { + const { consumers, cutter } = this + + if ((cutter === undefined) || !takenBy(consumers, waiting)) { + return + } + + if (!cutter.cut(frame.data, timestamp, opensRun)) { + this.drops++ + + return + } + + for (let packet = cutter.next(); packet !== undefined; packet = cutter.next()) { + const octets = packet.length - RTP_HEADER_LENGTH + + for (let index = 0; index < consumers.length; index++) { + if (waiting?.has(consumers[index])) { + continue + } + + if (!this.sendTo(consumers[index], packet, octets, now)) { + index-- + } + } + } + } + + /* Hands a placed frame to every frame consumer that takes it in the order they joined, passing its fields as arguments, which means no object is made for the + * frame. Passes over each consumer the waiting consumers given hold. A consumer's hand-over runs in the pacer's turn: it goes through one catch, + * which takes a consumer that throws off. The walk reads the array's length at each step, which is why the consumers after it still take the frame. + */ + private handOver(frame: TierFrame, timestamp: number, opensRun: boolean, waiting: ReadonlySet | undefined): void { + for (let index = 0; index < this.frameConsumers.length; index++) { + if (waiting?.has(this.frameConsumers[index])) { + continue + } + + if (!this.handTo(this.frameConsumers[index], frame, timestamp, opensRun)) { + index-- + } + } + } + + /* Sends one packet to one packet consumer, counting it sent or refused, and answers whether the consumer is still joined. The send runs in the pacer's + * turn: a throw is caught here and nothing is thrown out of the pacer's timer. + */ + private sendTo(joined: PacketJoin, packet: Buffer, octets: number, now: number): boolean { + let sent: boolean + + try { + sent = joined.consumer.send(packet, octets, now) + } catch (error) { + this.takeOff(joined, error) + + return false + } + + if (sent) { + this.packets++ + this.bytes += packet.length + } else { + this.drops++ + } + + return true + } + + // Hands one frame to one frame consumer, and answers whether the consumer is still joined, a throw caught as a send's is. + private handTo(joined: FrameJoin, frame: TierFrame, timestamp: number, opensRun: boolean): boolean { + try { + joined.consumer.take(frame, timestamp, opensRun) + } catch (error) { + this.takeOff(joined, error) + + return false + } + + return true + } + + // A consumer whose send or hand-over threw is taken off wherever it stands: it is sent nothing more, reported once, and ended through its holder's + // route. + private takeOff(join: MediumJoin, error: unknown): void { + const unit = (join.kind === 'packets') + ? 'packet' + : 'frame' + const failure = `A ${unit} consumer of the ${PARTS[this.medium]} of ${this.demand.tierName} failed to take a ${unit}, and it ends` + + this.remove(join) + this.demand.reporter.failure('library-failure', failure, error, this.demand.fields) + join.holder.tierFailed() + } + + // A consumer joins the live releases, in the array of its kind. + private joinLive(join: MediumJoin): void { + if (join.kind === 'packets') { + this.consumers.push(join) + } else { + this.frameConsumers.push(join) + } + } + + // A consumer leaves the live releases, and the answer is whether it stood among them: one in an opening or one that has left is left as it stands. + private leaveLive(join: MediumJoin): boolean { + const live: MediumJoin[] = (join.kind === 'packets') + ? this.consumers + : this.frameConsumers + const index = live.indexOf(join) + + if (index === -1) { + return false + } + + live.splice(index, 1) + + return true + } + + // A consumer opens behind the live releases from a keyframe, a join's opening or an answer's, with no start until its first turn. + private openOn(join: MediumJoin, keyframe: BufferedSample, answer: boolean): void { + this.openings.push({ + answer, + handed: Number.NEGATIVE_INFINITY, + join, + keyframe, + roomHeld: false, + }) + } + + /* Hands one opening the pictures the pacer has released from its keyframe on, up to the first picture the pacer still holds, and answers whether it is + * level, handed every such picture. The opening takes its start here, in the turn, after the turn's releases have placed its keyframe: in its first turn + * that finds its keyframe kept, and afresh at each newer keyframe it takes, which is why its timestamps stand past every picture placed whatever keyframe it runs + * from. It takes its speed with its start, from its stretch's rate, before any picture of that start is stamped, and every picture of that start is + * stamped at that speed, while the demand reads the same rate against its tier's peak. Each picture stands at the opening's timestamp for it, read by + * its presentation time, and the handing stops at the first picture whose timestamp the live edge has not reached, the opening waiting for the release + * that moves the edge, or at the first frame its session has no room for, the opening keeping whether its room stopped it. An opening whose keyframe the + * buffer let go carries on from the latest keyframe the buffer keeps whose release has fallen due, which an answer's opening takes as the keyframe its + * consumer was last answered from, since that is the stretch it is sent, and a join's takes as no answer, and with none keeps the keyframe it lost. The + * buffer answers that it does not keep it and the pacer runs no turn a millisecond on for it, and the opening waits with nothing handed for the next keyframe the + * pacer releases. + */ + private catchUp(opening: Opening, now: number): boolean { + const { buffer, demand: { pacer }, run } = this + + opening.roomHeld = false + + if (!buffer.keeps(opening.keyframe)) { + const keyframe = buffer.keyframeBefore(pacer.waitingFrom('video', now)) + + if (keyframe === undefined) { + return false + } + + opening.keyframe = keyframe + opening.start = undefined + + if (opening.answer) { + this.answered.set(opening.join, keyframe.order) + } + } + + const until = pacer.waitingFrom('video', now) + + if (opening.start === undefined) { + const rate = this.stretchRate(opening.keyframe, until) + + opening.start = run.openingStart() + opening.speed = openingSpeed(rate) + this.demand.readStretch(rate) + } + + const { start } = opening + const speed = opening.speed! + const keyframeTime = timeOf(opening.keyframe) + + for (const sample of buffer.walk(opening.keyframe).pictures) { + if (sample.order <= opening.handed) { + continue + } + + if (sample.order >= until) { + return true + } + + const time = timeOf(sample) + const timestamp = run.openingTimestamp(start, time - keyframeTime, speed) + + if (!run.reached(timestamp)) { + return false + } + + if (!this.hand(opening.join, frameOf(sample, time), timestamp, now)) { + opening.roomHeld = true + + return false + } + + opening.handed = sample.order + } + + return true + } + + /* The rate of an opening's stretch in kilobits a second, read in one pass of its own in the turn the opening takes its start, since the stamping walk + * returns at the keyframe in that turn, its timestamp not yet reached: the octets of every picture from the keyframe up to the first the pacer still + * holds, over the stretch's length in decode time, in the pictures' own track's timescale. The length runs from the keyframe's decode time to the decode + * time of the first picture after the stretch, the one the pacer holds, where the buffer keeps it, and otherwise to the last picture's decode time plus + * its own duration, nothing added where it carries none. N pictures in the order the stream delivered them span N decode intervals, whatever order they + * are presented in: read to the last picture's own time every picture's octets would stand against one interval too few, and a stream at its limit + * would read as above it. + */ + private stretchRate(keyframe: BufferedSample, until: number): number { + let octets = 0 + let last = keyframe + let after: BufferedSample | undefined + + for (const sample of this.buffer.walk(keyframe).pictures) { + if (sample.order >= until) { + after = sample + break + } + + octets += sample.data.length + last = sample + } + + const length = (after === undefined) + ? Number(last.decodeTime - keyframe.decodeTime) + (last.duration ?? 0) + : Number(after.decodeTime - keyframe.decodeTime) + const seconds = Math.max(length / keyframe.track.timescale, SHORTEST_STRETCH) + + // Eight bits an octet and a thousand bits a kilobit. + return octets * 8 / 1000 / seconds + } + + /* Hands one picture of an opening to its consumer at the opening's timestamp for it, with the run-opening flag unset, since that flag marks a live + * release alone, and answers whether it was handed: a packet consumer takes a frame only whole within its room, but for a frame of more packets than its + * capacity, which would never fit and is sent at once as a live release sends it, each packet it refuses counted among the half's drops, and a consumer + * that throws is taken off. + */ + private hand(join: MediumJoin, frame: TierFrame, timestamp: number, now: number): boolean { + if (join.kind === 'frames') { + return this.handTo(join, frame, timestamp, false) + } + + const cutter = this.cutter! + const { capacity, free } = join.consumer + const count = cutter.count(frame.data) + + if ((count > free) && (count <= capacity)) { + return false + } + + if (!cutter.cut(frame.data, timestamp, false)) { + this.drops++ + + return true + } + + for (let packet = cutter.next(); packet !== undefined; packet = cutter.next()) { + if (!this.sendTo(join, packet, packet.length - RTP_HEADER_LENGTH, now)) { + return false + } + } + + return true + } + + /* Reads whether a decoder can read a well-formed video keyframe, its units with the parameter sets its track carries beside it, by the rule the keyframe + * lookup reads, and raises one stream-fault problem in the demand's life, before the keyframe's packets, for one it cannot. The keyframe is sent as it + * stands either way, and the read allocates nothing. + */ + private checkParameterSets(data: Buffer, parameterSets: Buffer): void { + if (decodable(data, parameterSets)) { + return + } + + this.warnedParameterSets = true + this.demand.reporter.problem({ + ...this.demand.fields, + kind: 'stream-fault', + level: 'warning', + sentence: `The stream of ${this.demand.tierName} carries a keyframe without its video, sequence and picture parameter sets, in its sample or its ` + + 'initialization segment, which a viewer needs to decode it, and the keyframe is sent as it stands.', + }) + } +} + +/* One demand of one video tier, from its first join to its last, and the stream the plugin writes the tier's fMP4 to for it. The tier holds one demand at a + * time, and each demand hands out a stream of its own. A stream an ended demand handed out never reaches a later demand's consumers. The demand reads + * its stream with a reader of its own, which it calls only from the plugin's own calls of the stream, and those calls only fill the tier's buffer, each + * initialization segment's tracks, each sample its format check lets through with the moment it arrived, and each fragment's end, and tell the buffer + * and its pacer of a mark. The demand's pacer hears the buffer through a place of its own, from the demand's making until it leaves its tier, and releases + * each sample in a turn of its own to the half of its medium, its picture or its sound, each half timing its samples on the demand's one run of the + * sensor's clock and sending them to the consumers joined for its medium, the sound only while the camera's Microphone is unmuted. The run ends where the + * pacer releases past a run's end: a mark, which the demand tells the pacer of as the plugin makes it and the buffer reads at the stream's next sample, or + * an initialization segment or a jump the buffer reads, which means one restart ends the run once in every order its samples arrive in. From its failure on the + * demand ignores what the plugin writes: it feeds the buffer nothing more and its pacer releases nothing, and the buffer empties as the demand leaves + * its tier. + * + * The demand reads every picture its stream hands over, whoever holds it, which is why it holds the stream to its silence bounds with one clock of its own: + * a started stream's first picture is due within the first-sample bound of the start's settling, one written inside the start counting, and each later + * one within the long-gap time of the one before, or within the recovering gap time of a reconnect's statement. Sound moves no clock on. A stream that + * misses its bound fails as a failed stream does, every hold's route called, and its tier's silence is told once, by one stream-failed problem, until the + * tier hands over a picture again. The clock stops at the demand's failure and as it leaves its tier, runs on no demand failed or ended, and keeps no + * process alive. + */ +export class TierDemand implements TierStream { + // Resolves once the demand settles: its start resolved or was refused, or the demand failed or ended first. Each hold's answer is read from the demand's + // state then. + readonly settled: Promise + // Resolves once the demand leaves its tier, at its end or at its refused start, which is how a holder that met it failed can wait for the tier to be free of it. + readonly left: Promise + // The demand's picture and its sound, which the pacer releases each sample of its medium to. + readonly halves: Readonly> + // The demand's pacer, whose release entry a caller with no timer may call itself. + readonly pacer: TierPacer + // The tier's settled entry, the one object every demand of the tier carries. + readonly tier: TierStream['tier'] + // The camera's reporter, the table's, which the demand and its halves report through, and what each of their problems concerns: the tier's sensor and + // the tier. + readonly reporter: CameraReporter + readonly fields: { readonly sensorUUID: string, readonly tierId: number } + state: DemandState = 'starting' + // The demand's one run of times, each half's. + private readonly run: ClockRun + // The table's model of the demand's tier, its context and its buffer. + private readonly videoTier: Tier + private readonly holds: TierHold[] = [] + private readonly reader: Mp4StreamReader + // The joins that add no consumer, the library's own hold of the tier, which the stream's statistics count beside the halves' consumers. + private holdJoins = 0 + // The largest packet the demand cuts, decided at a packet join that finds no packet consumer joined, from the listening family of that join's connection, + // which each packet consumer's pooled buffers are sized for. + private packetSize = 0 + private resolveSettled!: () => void + private resolveLeft!: () => void + private settling = true + private failed = false + // The start's own abort controller, held from the start's call until its settling, which marks the start pending: only an end in that span aborts it. + private pendingStart?: AbortController + // What the plugin registered on the stream, released once in end or refuse, where the demand becomes ended. + private readonly scope: HandleScope + // Whether the start's own bound withdrew the demand, which a hold's answer reads as a cut. + private withdrawnAtBound = false + // Whether the demand has told of a stream past twice its tier's peak, once in its life. + private toldPastPeak = false + // Whether the demand has told of a shared sound tier's stream with no Opus track, once in its life. + private toldNoSound = false + // The silence clock and what it counts, none before the start settles or the first picture, and none once the demand has failed or left its tier. + private silence?: { readonly clock: SilenceClock, readonly timer: ReturnType } + + constructor(tier: Tier) { + const { context: { reporter, sensorUUID }, tierId } = tier + + this.videoTier = tier + this.tier = tier.entry + this.reporter = reporter + this.fields = { sensorUUID, tierId } + this.scope = new HandleScope(END_FAILURE, reporter, this.fields) + this.run = new ClockRun(tier.context.clock) + // The sound half alone reads the camera's Microphone, through the context every tier of the table shares, and a mute reaches a running demand at its + // next sound and the demand keeps no copy of it. + this.halves = { + video: new DemandHalf(this, 'video', this.run, tier.buffer), + audio: new DemandHalf(this, 'audio', this.run, tier.buffer, tier.context), + } + this.pacer = new TierPacer(tier.buffer, { + behind: () => this.halves.video.behind || this.halves.audio.behind, + consumed: () => (this.halves.video.joined + this.halves.audio.joined) > 0, + endRun: () => this.run.end(), + open: (now) => { + this.halves.video.open(now) + this.halves.audio.open(now) + }, + release: (sample, now) => this.halves[sample.track.medium].release(sample, now), + }) + // A tier whose sound is ignored has its reader read no sound: its buffer, its pacer and its halves meet a stream without sound, and no fault of + // that track's can fail the tier. + this.reader = new Mp4StreamReader({ + fail: (reason) => { + this.failWith('The library refused', reason) + }, + fragmentEnd: () => { + this.endFragment() + }, + sample: (sample) => { + this.take(sample) + }, + tracks: (tracks) => { + this.readTracks(tracks) + }, + }, { sound: tier.sound !== 'ignored' }) + this.settled = new Promise((resolve) => { + this.resolveSettled = resolve + }) + this.left = new Promise((resolve) => { + this.resolveLeft = resolve + }) + } + + /** + * The demand's tier as its sentences name it. + */ + get tierName(): string { + const { context: { sensorUUID }, tierId } = this.videoTier + + return `the video tier ${tierId} of the video sensor "${sensorUUID}"` + } + + /** + * Whether the demand's start is still pending, with no failure or end ahead of it. + */ + get waiting(): boolean { + return this.settling + } + + /** + * Whether the demand has started and its stream has not failed, which a hold's answer reads. + */ + get serving(): boolean { + return (this.state === 'started') && !this.failed + } + + /** + * How the demand's start ended for a hold that waited on it, read once the demand has settled: `started` where the demand serves, `cut` where its start's + * own bound withdrew it, still pending `DELEGATE_CALL_TIMEOUT` after its call, and `refused` otherwise. + */ + get startAnswer(): StartAnswer { + if (this.serving) { + return 'started' + } + + return this.withdrawnAtBound + ? 'cut' + : 'refused' + } + + /* Calls the delegate's tierDemandStarted with the demand as its stream and the signal of the start's own controller, once the joins that raised the + * demand are in place. Every field a write reads is set before the call, the raiser's route and its consumers among them: a stream the plugin writes + * inside the call reaches the raiser timed and counted once the pacer releases it, and a stream failed inside it ends the raiser. The start is pending + * from the call until its settling. The signal is aborted only by an end in that span, and a rejection that follows the abort is not reported. The + * start's one bound is counted from this call, whoever waits on the demand, and no join restarts it. + */ + start(): void { + const { context: { delegate } } = this.videoTier + const pendingStart = new AbortController() + + this.pendingStart = pendingStart + + const pending = (async () => delegate.tierDemandStarted(this, pendingStart.signal))() + + this.reporter.rejection('plugin-failure', pending, 'MultiTierStreamingDelegate failed to start a tier demand', pendingStart.signal, this.fields) + void pending.then(value => this.resolve(value), () => this.refuse()) + void this.withdrawAtBound(pending) + } + + // Reads the stream's next bytes into the tier's buffer, each sample they complete in the stream's order, until the demand fails or ends. + write(chunk: Buffer): void { + if (!this.feeds) { + return + } + + this.reader.write(chunk) + } + + /* A mark is told to the buffer, which reads it at the stream's next sample, of whichever track, and to the pacer, whose run it ends at once: the + * samples of a fragment the mark cuts leave in the pacer's next turn and wait on no later write. The reader holds no sample back at a mark, since + * nothing its consumer calls throws. The next sample the buffer takes is the restart's own. + */ + discontinuity(): void { + if (!this.feeds) { + return + } + + this.reader.discontinuity() + this.videoTier.buffer.mark() + this.pacer.ending() + } + + statistics(): TierStreamStatistics { + const { audio, video } = this.halves + + return { + packets: video.packets + audio.packets, + bytes: video.bytes + audio.bytes, + drops: video.drops + audio.drops, + consumers: video.joined + audio.joined + this.holdJoins, + } + } + + use(value: T): T { + return this.scope.use(value) + } + + defer(release: () => unknown): void { + this.scope.defer(release) + } + + // The plugin's failure of the stream, from which on the demand releases nothing, its pacer letting go what waits unsent, and ignores every chunk the + // plugin writes, as it does once it has ended. + fail(reason: string): void { + this.failWith('The plugin failed', reason) + } + + // A join's hold keeps the demand, and takes one whose joins all released while its start was pending back to starting. + addHold(hold: TierHold): void { + this.holds.push(hold) + + if (this.state === 'ending') { + this.state = 'starting' + } + } + + // The demand ends as its last join releases: at once once started, when its start settles while it is pending, and never after a refused start. + releaseHold(hold: TierHold): void { + const index = this.holds.indexOf(hold) + + if (index === -1) { + return + } + + this.holds.splice(index, 1) + + if (this.holds.length > 0) { + return + } + + if (this.state === 'starting') { + this.state = 'ending' + } else if (this.state === 'started') { + this.end() + } + } + + // Whether a hold other than the one given keeps the demand. + heldBeside(hold: TierHold): boolean { + return this.holds.some(other => other !== hold) + } + + /* Decides the packet size for a packet join, from the listening family of its connection's HAP server, when it finds no packet consumer joined, and makes + * the cutter of each half at that size. A cut runs only while a packet consumer is joined: no cutter is made while a frame is being cut, and a server + * listening anew is read again at the next first packet join. A packet join that finds one joined takes the size decided already. + */ + cutFor(connection: HAPConnection): number { + const { audio, video } = this.halves + + if (video.packetConsumers + audio.packetConsumers === 0) { + this.packetSize = connection.server.address().family === 'IPv4' + ? IPV4_PACKET_SIZE + : IPV6_PACKET_SIZE + video.makeCutter(this.packetSize) + audio.makeCutter(this.packetSize) + } + + return this.packetSize + } + + /* A join adds its consumer to the half of its medium, and a hold alone is counted among the demand's joins. A consumer joining a demand that has none + * joined first has the pacer let go what fell due before it. The samples released are those whose due moment has passed, and the join then reads the + * tier's buffer. Where the buffer keeps a keyframe whose release has fallen due, a consumer of the picture joins behind the live releases and opens from + * the latest such keyframe, its timestamps taken in the pacer's turn, and its opening starts at a keyframe already; a consumer of the sound joins the live + * releases at once. Where it keeps a keyframe and none whose release has fallen due, the consumer joins the live releases, that keyframe leaving within + * the pacer's hold, and where it keeps none, the consumer joins the live releases. A consumer of the picture that joins them is sent no picture before + * the next keyframe the pacer releases, as every consumer of the live pictures is after each run's opening, its sound flowing meanwhile. A join runs no + * plugin code: the table calls the delegate's tierDemandStarted only for a demand a join raised, once its joins are in place. The pacer's timer then runs + * for the consumer, in an opening or live. + */ + join(join: TierJoin): void { + if (join.kind === 'hold') { + this.holdJoins++ + return + } + + this.pacer.letGoDue() + this.halves[join.medium].add(join, this.opensFrom(join)) + this.pacer.follow() + } + + // A consumer's leave cancels the pacer's timer where it leaves the demand none, and no release follows a hold's release. + leave(join: TierJoin): void { + if (join.kind === 'hold') { + this.holdJoins-- + } else { + this.halves[join.medium].remove(join) + this.pacer.follow() + } + } + + /* Answers a viewer's keyframe request for the one consumer of the picture it came through, read at the request, and answers what it came to. Where the + * buffer keeps a keyframe whose release has fallen due, whatever later keyframe it keeps, the consumer opens again from the latest such keyframe, as a + * join opens from it, and the pacer follows: its turn a millisecond on takes the opening's start. A demand whose pacer has stopped opens nothing, + * since nothing more is released. A request the demand does not open does nothing, and the viewer's picture comes back at the stream's next keyframe. + */ + answerKeyframeRequest(join: MediumJoin): KeyframeAnswer { + if (this.pacer.stopped) { + return 'stopped' + } + + const answer = this.halves.video.answer(join, this.releasedKeyframe()) + + if (answer === 'answered') { + this.pacer.follow() + } + + return answer + } + + /* Reads the rate of an opening's stretch, in kilobits a second, against twice its tier's settled peak, and tells of the first stretch past it once in + * the demand's life, naming the stretch's rate and the peak: a stream-fault problem where the camera was given strict, and a debug event otherwise. + * Twice the peak, since a short stretch of a stream within its peak reads above it from its keyframe alone. + */ + readStretch(rate: number): void { + const { peakBitrate } = this.tier + + if (this.toldPastPeak || (rate <= 2 * peakBitrate)) { + return + } + + this.toldPastPeak = true + + const sentence = `The stream of ${this.tierName} runs at ${Math.round(rate)} kbps over the stretch a view opens on, read over a second at least, past ` + + `twice the peak of ${Math.round(peakBitrate)} kbps its tier advertises.` + + if (this.videoTier.context.strict) { + this.reporter.problem({ + ...this.fields, + kind: 'stream-fault', + level: 'warning', + sentence, + }) + } else { + this.reporter.debug(TIER_DEBUG, 'stretch-past-peak', () => ({ + ...this.fields, + peakBitrate, + rate, + sentence, + })) + } + } + + /* A demand still pending is withdrawn, and the delegate is told through its start's signal, since the library stops waiting for its start: the start's + * own bound withdraws its demand, a reset or a destroy each demand its sessions left, and the camera going out of service every pending demand of its + * tables. Each withdrawal tells of itself once, in a sentence the caller's outcome closes: the start's bound raises a plugin-failure problem naming the + * plugin, and a reset, a destroy and the camera going out of service, each the library withdrawing for its own reasons while the plugin did nothing + * wrong, write a debug event on the tier's channel and raise no problem. + */ + withdraw(outcome: string, warn = true): void { + if (!this.withdrawable) { + return + } + + if (warn) { + this.reporter.problem({ + ...this.fields, + kind: 'plugin-failure', + level: 'warning', + sentence: `MultiTierStreamingDelegate did not settle tierDemandStarted for ${this.tierName} ${outcome}.`, + }) + } else { + this.reporter.debug(TIER_DEBUG, 'start-withdrawn', () => ({ + ...this.fields, + outcome, + sentence: `The library withdrew the pending start of ${this.tierName} ${outcome}.`, + })) + } + + this.end() + } + + // Holds a running stream through its source's reconnect: a gap clock moves to the recovering gap time from the call, once, until the next picture makes + // it again at the long-gap time. A demand with no picture yet keeps its first-sample bound, and one failed or ended runs no clock. + sourceRecovering(): void { + if (this.silence?.clock === 'gap') { + this.arm('recovering') + } + } + + /* The keyframe a consumer of the picture opens behind the live releases from: the latest the tier's buffer keeps whose release has fallen due, read by + * the picture the pacer would leave waiting. A join into a demand whose pacer has stopped, at its failure, opens nothing, since nothing more is released, + * and every consumer of the sound opens nothing and joins the live releases at once. A viewer's sound plays live while its picture opens. + */ + private opensFrom(join: MediumJoin): BufferedSample | undefined { + if (this.pacer.stopped || (join.medium === 'audio')) { + return undefined + } + + return this.releasedKeyframe() + } + + // The latest keyframe the tier's buffer keeps whose release has fallen due, read by the picture the pacer would leave waiting, which a join opens from and + // an answer opens from. + private releasedKeyframe(): BufferedSample | undefined { + return this.videoTier.buffer.keyframeBefore(this.pacer.waitingFrom('video', performance.now())) + } + + // Whether the demand still reads its stream into its tier's buffer: from its failure or its end on, it reads nothing more. + private get feeds(): boolean { + return (this.state !== 'ended') && !this.failed + } + + // Whether a withdrawal acts on the demand: its start still pending and the demand not ended. + private get withdrawable(): boolean { + return (this.state === 'starting') || (this.state === 'ending') + } + + /* The start's one bound, counted from its call whoever waits on the demand: a start still pending at the bound is withdrawn with the demand's one + * plugin-failure problem, its signal aborted and every join waiting on it refused, and the demand marks that its bound withdrew it, which means each holder + * answers as at a cut of its own wait. The wait is over as the start settles, by its value or its rejection, and a join that takes an ending demand back + * to starting leaves it running, the call being the same one. A start whose last holder left, or whose stream failed, is bound as any other. A bound + * that passes over a demand a reset, a destroy or the camera going out of service withdrew first marks and withdraws nothing. + */ + private async withdrawAtBound(pending: Promise): Promise { + const { cutAtBound } = await settleWithinBound(pending) + + if (cutAtBound && this.withdrawable) { + this.withdrawnAtBound = true + this.withdraw(BOUND_OUTCOME) + } + } + + /* A stream whose initialization segment holds no video track is refused through the reader, and one with no Opus track, or one whose reader reads no + * sound, is a tier without sound. The sound tier of a sensor whose sound is shared tells of a stream with no Opus track as one stream-fault problem in + * its demand's life, since every view of the sensor takes its sound from that stream. The tracks of a stream taken go to the tier's buffer. + */ + private readTracks(tracks: Mp4StreamTracks): void { + if (tracks.video === undefined) { + this.reader.fail(NO_VIDEO_TRACK) + return + } + + if ((tracks.audio === undefined) && (this.videoTier.sound === 'shared') && !this.toldNoSound) { + this.toldNoSound = true + this.reporter.problem({ + ...this.fields, + kind: 'stream-fault', + level: 'warning', + sentence: `The stream of ${this.tierName} carries no Opus track, though every view of its sensor takes its sound from that stream: ` + + 'no view of its sensor and no recording of the tier has sound.', + }) + } + + if (this.feeds) { + this.videoTier.buffer.describe(tracks) + } + } + + // 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. + private take(sample: Mp4StreamSample): void { + if (!this.feeds) { + return + } + + const { medium } = sample.track + + if (!this.halves[medium].admits(sample)) { + return + } + + this.videoTier.buffer.take(sample, performance.now()) + + if ((medium === 'video') && this.feeds) { + this.pictured() + } + } + + /* A picture the tier's buffer took, read once every place in the buffer has read it, the keeper's among them: the tier's silence is over, and the + * silence clock counts the long-gap time from this picture, a running gap clock moved on and any other made again at that time, since a refresh keeps a + * timer's own duration. The keeper's clocks move on at the same picture ahead of the demand's, which is why at a deadline they share the keeper tells an + * open recording of the gap before the demand ends. + */ + private pictured(): void { + this.videoTier.toldSilence = false + + if (this.silence?.clock === 'gap') { + this.silence.timer.refresh() + } else { + this.arm('gap') + } + } + + // Arms the silence clock to count what is given, in place of what it counted. + private arm(clock: SilenceClock): void { + clearTimeout(this.silence?.timer) + this.silence = { + clock, + timer: setTimeout(() => this.silenced(clock), SILENCE_CLOCKS[clock].time).unref(), + } + } + + // Stops the silence clock, at the demand's failure and as it leaves its tier. + private stopSilence(): void { + clearTimeout(this.silence?.timer) + this.silence = undefined + } + + /* A stream that handed over no picture within what its silence clock counted fails as a failed stream does, every hold's route called. The tier's + * silence is told by the first silence end since its last picture, whichever demand of the tier that end comes to, and a later one raises no problem, + * which is why a camera that stays down is told of once however many demands the asks for it raise. + */ + private silenced(clock: SilenceClock): void { + const { videoTier } = this + const told = videoTier.toldSilence + + this.silence = undefined + videoTier.toldSilence = true + this.failWith('The library ended', SILENCE_CLOCKS[clock].silence, told) + } + + private endFragment(): void { + if (this.feeds) { + this.videoTier.buffer.endFragment() + } + } + + // A failed stream raises one stream-failed problem with the failure's own sentence, and one whose failure its tier has told of already raises none. + private failWith(who: string, reason: string, told = false): void { + this.failHolds(told + ? undefined + : `${who} the stream of ${this.tierName} (${reason}), and every session on the tier ends.`) + } + + /* A failed tier calls the route of every join's holder, one waiting on the tier's start among them, which ends it, and the demand ends as the last of + * them releases. A hold's answer reads a failed demand as refused, which means a join waiting on it, and one made later, is answered as refused. A failed + * demand releases nothing and counts no silence: its pacer and its silence clock stop before any route is called. + */ + private failHolds(warning: string | undefined): void { + if (this.failed || this.state === 'ended') { + return + } + + this.failed = true + this.stopSilence() + this.pacer.halt() + this.settle() + + if (warning !== undefined) { + this.reporter.problem({ + ...this.fields, + kind: 'stream-failed', + level: 'warning', + sentence: warning, + }) + } + + for (const hold of [...this.holds]) { + hold.holder.tierFailed() + } + } + + /* The start's settling, its pending mark cleared first. Its answer is read for the settling alone. A value other than undefined, whatever the + * demand's state, is reported once as the delegate's plugin-failure problem, the value rendered nowhere, since the sentence tells the plugin's author + * all a rendering would, and nothing is released for it. The demand's state moves before it settles, which is why every hold's answer reads the state its start + * left: a starting demand starts, an ending one ends, which releases its registrations, and one the library ended while its start was pending is left as + * it stands. A demand that starts and serves with no picture handed over yet counts the first-sample bound from here, and one whose stream failed while + * its start was pending counts nothing. + */ + private resolve(value: unknown): void { + this.pendingStart = undefined + + if (value !== undefined) { + this.reporter.problem({ + ...this.fields, + kind: 'plugin-failure', + level: 'error', + sentence: `MultiTierStreamingDelegate answered tierDemandStarted for ${this.tierName} with a value, which the library does not read, and nothing is ` + + 'released for it.', + }) + } + + if (this.state === 'starting') { + this.state = 'started' + + if (this.serving && (this.silence === undefined)) { + this.arm('first') + } + } else if (this.state === 'ending') { + this.end() + } + + this.settle() + } + + /* A refused start ends its demand as end does, with no abort, since the start has settled: the state moves and the demand settles first, which is why a cleanup + * reads it ended. What the start registered is released before the demand leaves its tier: a join a cleanup sets off meets the ended demand. A + * demand the library ended while its start was pending released at that end, and only settles. + */ + private refuse(): void { + this.pendingStart = undefined + + if ((this.state === 'starting') || (this.state === 'ending')) { + this.state = 'ended' + this.settle() + this.scope.release() + this.leaveTier() + } else { + this.settle() + } + } + + // The first of a start's answer, a failure and an end settles the demand, and any later one finds it settled already. + private settle(): void { + this.settling = false + this.resolveSettled() + } + + /* Every path that ends a demand but a refused start passes here. The state moves and the demand settles first, which means a listener on a pending start's signal, + * which only a withdrawal reaches, and every cleanup read the demand ended, and a write or a fail from them does nothing. The abort comes before the + * release: a start cut while pending is told before what it registered is released. The release comes while the tier still holds the demand, which means + * every cleanup is called before any later start of the tier: the release calls each in this one call, and a join a cleanup sets off meets the ended + * demand, which calls no start. Where that join is the library's own keeper's, the keeper reads its hold as failed, raises its `tier-failed` problem and asks + * for the tier again after its first wait. The demand then leaves its tier, its pacer stopped and its buffer emptied. + */ + private end(): void { + this.state = 'ended' + this.settle() + this.pendingStart?.abort() + this.scope.release() + this.leaveTier() + } + + // The demand leaves its tier, its silence clock and its pacer stopped and its place given up before the buffer empties, which settles what a hold waiting + // on its end reads. A continuation of that wait runs in a later microtask, after every cleanup of the demand's registrations has been called. + private leaveTier(): void { + this.stopSilence() + this.pacer.close() + this.videoTier.release(this) + this.resolveLeft() + } +} + +/** + * What a video tier's stream's sound is for, which the table sets once from its tier set: `'own'` for every tier of a sensor whose audio states its source + * `'tier'`, its sound serving the views of that tier; `'shared'` for the sound's tier of a sensor whose audio states `'shared'`, its sound serving every + * view of the sensor; and `'ignored'` for every other tier of such a sensor, whose stream's Opus track each demand reads as none. + */ +export type TierSound = 'own' | 'shared' | 'ignored' + +/* One video tier of the sensor: the stream tier it was advertised from, what its stream's sound is for, the demand its consumers raise while it has any, + * which carries the tier's stream, picture and sound, and the tier's buffer for the table's life, which the demand feeds and which empties as the demand + * leaves. The advertised stream tier is the very object the plugin's validated options hold, and none of its fields is copied onto the tier. Whatever + * reads a tier's resolution, frame rate or bitrate reads what the service advertises. The tier's settled entry is the very object its tier set holds, which + * each demand's stream carries. + */ +export class Tier { + readonly context: TierContext + readonly advertised: VideoStreamTier + readonly entry: TierStream['tier'] + readonly tierId: number + readonly payloadType: number + readonly buffer: TierBuffer + readonly sound: TierSound + demand?: TierDemand + // Whether the tier's silence is told, from the silence end that raised its stream-failed problem to the tier's next picture, whichever demand takes it. + // It lives as the tier does: a reset, an unpublish and a source stated away or back leave it as it stands, and a removal makes the tiers anew. + toldSilence = false + + constructor(context: TierContext, advertised: VideoStreamTier, entry: TierStream['tier'], payloadType: number, buffer: TierBuffer, sound: TierSound) { + this.context = context + this.advertised = advertised + this.entry = entry + this.tierId = advertised.identifier + this.payloadType = payloadType + this.buffer = buffer + this.sound = sound + } + + // The tier's demand leaves it, and its buffer empties: nothing of a stream that ended stays for the next. + release(demand: TierDemand): void { + if (this.demand === demand) { + this.demand = undefined + this.buffer.empty() + } + } +} + +/** + * The sensor's audio tier as the table keeps it: the stream tier it was advertised from, which describes the Opus the sensor's streams carry, and the + * payload type every video tier's sound is sent under. It raises no demand, since the sound comes inside a video tier's stream: each tier's own, or the + * sensor's sound tier's alone where the sensor's audio states its source `'shared'`. + */ +export interface AudioTier { + readonly context: TierContext + readonly advertised: AudioStreamTier + readonly tierId: number + readonly payloadType: number +} + +/** + * One join's hold on a tier's demand, the handle a join answers: the join raised the demand or kept the one the tier has and added the holder's consumers, + * a consumer of the picture handed its opening from the tier's buffer where it joined behind, and each sent the packets or handed the frames of its medium + * the pacer releases from then on, a picture of the live releases from a keyframe after the join and after each run's opening, or none for a hold alone. + * A viewer's keyframe request comes through the hold its consumer joined with: the demand answers that consumer alone. The hold's release takes + * those consumers off, in an opening or live, and lets the demand end with its last join. + */ +export class TierHold { + /** + * The holder, whose route a failed tier calls. + */ + readonly holder: TierHolder + private readonly demand: TierDemand + private readonly joins: readonly TierJoin[] + private released = false + + constructor(demand: TierDemand, holder: TierHolder, joins: readonly TierJoin[]) { + this.demand = demand + this.holder = holder + this.joins = joins + demand.addHold(this) + } + + /** + * Whether the demand's start is still pending, which means the hold's answer is still to come. + */ + get waiting(): boolean { + return this.demand.waiting + } + + /** + * Whether the demand has started and its stream has not failed, read from the demand's state as it stands. + */ + get started(): boolean { + return this.demand.serving + } + + /** + * Answers how the demand's start ended for this join, once it starts, is refused, fails or ends while the join waits, and at once for a demand that has + * settled: `started` where the demand serves; `cut` where the start's own bound withdrew it, still pending `DELEGATE_CALL_TIMEOUT` after its call, which means + * the holder answers as at a cut of its own wait; and `refused` for a refused start, a failed stream and a demand a reset, the camera's removal or the + * camera going out of service withdrew. A hold no wait answers reads {@link TierHold.started}, the demand serving as it stands. + * @returns The start's answer, never rejecting. + */ + async answer(): Promise { + await this.demand.settled + + return this.demand.startAnswer + } + + /** + * Whether a hold other than this one keeps the demand. + */ + get shared(): boolean { + return this.demand.heldBeside(this) + } + + /** + * Answers once the demand leaves its tier, at its end or at its refused start, after the delegate hears an end the demand sends. + * @returns A promise settled as the demand leaves its tier, never rejecting. + */ + async ended(): Promise { + await this.demand.left + } + + /** + * Takes a viewer's keyframe request for the hold's consumer of the picture, which the demand opens again from the tier's buffer by its answer, and does + * nothing for a hold released already or one with no consumer of the picture. + * @returns What the request came to, `stopped` for a hold released already or one with no consumer of the picture. + */ + answerKeyframeRequest(): KeyframeAnswer { + const picture = this.joins.find((join): join is MediumJoin => (join.kind !== 'hold') && (join.medium === 'video')) + + if (this.released || (picture === undefined)) { + return 'stopped' + } + + return this.demand.answerKeyframeRequest(picture) + } + + /** + * Releases the hold, taking each of its joins' consumers off the demand first, and does nothing more for a hold released already. + */ + release(): void { + if (this.released) { + return + } + + this.released = true + + for (const join of this.joins) { + this.demand.leave(join) + } + + this.demand.releaseHold(this) + } +} + +/** + * One video sensor's tier model, which the camera controller builds for each sensor and hands that sensor's stream management: the sensor's stream tiers + * in the order they are advertised, each video tier's buffer and its demand from its first join to its last, the sensor's one RTP clock every tier's + * picture and sound are timed on, and the delegate's demand calls. A viewer's keyframe request goes to the hold its consumer joined with, whose demand + * answers it from the tier's buffer. A demand reads each sample its stream is written and keeps it in its tier's buffer, and its pacer releases it in a + * turn of its own, when the demand times it and cuts it into the packets its joined consumers send. A holder joins a tier in one step, through the join + * of its consumers' kind, naming the medium each packet or frame consumer takes, and the library's own hold joins with no consumer. Only a join that + * raises a tier's demand runs plugin code, the delegate's tierDemandStarted, and a join into a running demand runs none. + */ +export class TierTable { + /** + * The sensor's stream tiers, the very object the table was made from, which the sensor's services advertise. + */ + readonly streamTiers: SensorStreamTiers + /** + * The sensor's UUID, in lowercase. + */ + readonly sensorUUID: string + /** + * The sensor's video tiers by identifier, in the order they are advertised. + */ + readonly videoTiers: ReadonlyMap + /** + * The sensor's audio tier, its one, which raises no demand. + */ + readonly audioTier: AudioTier + /** + * The sensor's sound tier, the one its tier set names, which a view from away takes its sound from: the sensor's best tier where its audio states its + * source `'tier'`, and the tier whose sound serves every view of the sensor where it states `'shared'`. + */ + readonly soundTier: Tier + // The one context every tier of the sensor and its audio tier share. + private readonly context: TierContext + + /** + * Makes a sensor's tiers, each on the sensor's one clock with a buffer of its own, the Microphone unmuted. The tiers arrive validated by the camera's + * streaming options. + * @param delegate - The camera's delegate, which every tier's demand reports to. + * @param streamTiers - The sensor's stream tiers, with whether the camera was given strict. + * @param buffer - Makes a video tier's buffer, given the tier by its sensor in lowercase and its identifier and the camera's reporter, at the composition + * root that makes the table. + * @param reporter - The camera's reporter, which every tier, demand and half of the table and each tier's buffer report through. + */ + constructor(delegate: MultiTierStreamingDelegate, streamTiers: SensorStreamTiers, buffer: (options: TierBufferOptions) => TierBuffer, reporter: CameraReporter) { + const { audioSource, audioStreamTiers, sensorUUID, soundTierId, strict, tiers, videoStreamTiers } = streamTiers + + this.streamTiers = streamTiers + this.sensorUUID = sensorUUID.toLowerCase() + + // Every tier of the sensor reads the one clock, and a frame captured at one moment carries that moment on each tier. The clock counts from the steady + // clock's moment, as every write's moment does. + const context: TierContext = { + delegate, + reporter, + sensorUUID: this.sensorUUID, + clock: new RTPClock(performance.now()), + strict, + microphoneMuted: false, + } + + this.context = context + // Each tier set holds a settled entry for every tier it advertises, as the options boundary builds it, and each tier's sound is read from the set's + // source and the entry's own sound, the one fact a plugin reads. The table compares no identifier. + this.videoTiers = new Map(videoStreamTiers.tiers.map((advertised) => { + const entry = tiers.get(advertised.identifier)! + + return [ + advertised.identifier, + new Tier(context, advertised, entry, videoStreamTiers.payloadType, buffer({ + reporter, + sensorUUID: this.sensorUUID, + tierId: advertised.identifier, + }), tierSound(audioSource, entry)), + ] + })) + this.audioTier = { + advertised: audioStreamTiers.tiers[0], + context, + payloadType: audioStreamTiers.payloadType, + tierId: audioStreamTiers.tiers[0].identifier, + } + // The options boundary names the sound tier among the tiers it advertises. + this.soundTier = this.videoTiers.get(soundTierId)! + } + + /** + * The tier a view of a tier takes its sound from: the sensor's sound tier for a tier whose sound is ignored, and the tier itself otherwise, its own + * stream's sound serving its views. + * @param tier - The tier the view takes its picture from. + * @returns The tier the view takes its sound from. + */ + soundTierOf(tier: Tier): Tier { + return (tier.sound === 'ignored') + ? this.soundTier + : tier + } + + /** + * Joins a tier with a packet consumer for each medium given, in one step: the join raises the tier's demand when it has none, decides the demand's packet + * size from the listening family of its connection's HAP server when no packet consumer is joined, adds each consumer made for that size, and calls the + * delegate for a demand it raised only after, which is why a stream the plugin writes inside its tierDemandStarted reaches every consumer as the pacer releases it + * and a stream failed inside it ends the holder. A join into a running demand calls the delegate for nothing. + * @param tier - The tier. + * @param holder - The holder, whose route a throw from a consumer's send calls. + * @param connection - The connection of the holder's session, whose HAP server's listening family decides the packet size. + * @param media - The media the holder takes, each sent under the payload type its consumer writes. + * @param joining - Makes a medium's consumer, given the demand's packet size: one of the picture is handed its opening across the pacer's turns where the + * tier's buffer keeps a keyframe the pacer has released, and each is sent every packet the demand cuts of its medium from the next frame the pacer + * releases on once it joins the live releases, the sound's at once, though a consumer of the picture is sent no picture before a keyframe after its join + * to the live releases and after each run's opening, an opening starting at a keyframe already. + * @returns The join's hold. + */ + join( + tier: Tier, + holder: TierHolder, + connection: HAPConnection, + media: readonly StreamTierMedium[], + joining: (medium: StreamTierMedium, packetSize: number) => PacketConsumer, + ): TierHold { + return this.joinDemand(tier, holder, (demand) => { + const packetSize = demand.cutFor(connection) + + return media.map(medium => ({ + kind: 'packets', + medium, + consumer: joining(medium, packetSize), + holder, + })) + }) + } + + /** + * Joins a tier with a frame consumer of one medium, in one step, as {@link TierTable.join} joins packet consumers: the join raises the tier's demand when + * it has none, adds the consumer, and calls the delegate for a demand it raised only after, a join into a running demand calling it for nothing. A + * frame consumer is a view from away's, and opens as a session at home does: a consumer of the picture is handed its opening across the pacer's turns as + * the live edge reaches each picture, and one of the sound joins the live releases. A consumer of the live pictures is handed no picture before a + * keyframe after its join and after each run's opening, its sound flowing meanwhile, and an opening starts at a keyframe already. + * @param tier - The tier. + * @param medium - The medium the consumer takes. + * @param holder - The holder, whose route a throw from the consumer's hand-over calls. + * @param consumer - The consumer, which is handed its opening, if it has one, and then every frame of its medium the pacer releases from the next frame + * on, a picture from the next keyframe where it joins the live releases with no opening and after each run's opening. + * @returns The join's hold. + */ + joinFrames(tier: Tier, medium: StreamTierMedium, holder: TierHolder, consumer: FrameConsumer): TierHold { + return this.joinDemand(tier, holder, () => [ + { + kind: 'frames', + medium, + consumer, + holder, + }, + ]) + } + + /** + * Holds a tier with no consumer, in one step, as {@link TierTable.join} joins packet consumers: the join raises the tier's demand when it has none, + * counts among the stream's consumers, and calls the delegate for a demand it raised only after, a join into a running demand calling it for nothing. + * @param tier - The tier. + * @param holder - The holder, whose route a failed tier calls. + * @returns The join's hold. + */ + hold(tier: Tier, holder: TierHolder): TierHold { + return this.joinDemand(tier, holder, () => [ + { + kind: 'hold', + }, + ]) + } + + /** + * The newest keyframe of the sensor's best running tier, as a movie of that one picture with its size and age: among the tiers whose demand serves and + * whose buffer keeps a keyframe, the best by {@link bestStreamTier} over their advertised tiers, read from the running tiers rather than the sensor's best + * tier, which keeps no keyframe while a lesser tier alone runs, and that buffer's newest keyframe, released or still in the pacer. + * The newest and not the latest released, because a snapshot is held to no viewer's place in the stream, and the newer picture is the fresher one. + * Nothing is raised for the lookup, and no tierDemandStarted runs for it. A tier whose newest keyframe lacks any of HEVC's video, sequence and picture + * parameter sets, in the keyframe and in its stream's description alike, answers none, as a tier that keeps no keyframe, and is passed over for the next + * tier that serves. + * @returns The keyframe, or `undefined` where no tier of the sensor serves with a newest keyframe a decoder can read. + */ + latestKeyframe(): CameraKeyframe | undefined { + // Each serving tier's newest keyframe a decoder can read, by the stream tier it was advertised from, which bestStreamTier reads. + const kept = new Map() + + for (const tier of this.videoTiers.values()) { + const keyframe = tier.demand?.serving + ? tier.buffer.keyframeBefore(Number.POSITIVE_INFINITY) + : undefined + + if (keyframe === undefined) { + continue + } + + // The buffer keeps the picture's keyframes alone, and the keyframe's track is the stream's video track. A keyframe a decoder cannot read is passed + // over with no report of the lookup's own, since the stream's demand raises a stream-fault problem for such a keyframe once, and one it can read + // always gives the movie's writer its parameter sets. The writer's refusal is never reached. + const video = keyframe.track as Mp4StreamVideoTrack + + if (decodable(keyframe.data, video.parameterSets)) { + kept.set(tier.advertised, { keyframe, tier, video }) + } + } + + const best = bestStreamTier(kept.keys()) + + if (best === undefined) { + return undefined + } + + const { keyframe, tier, video } = kept.get(best)! + let movie = keyframeMovies.get(keyframe) + + if (movie === undefined) { + // The movie's one sample needs a duration, which a run's newest picture may not have yet: it takes the tier's frame interval there. + movie = writeKeyframeMovie({ + duration: keyframe.duration ?? Math.round(video.timescale / tier.entry.frameRate), + keyframe: keyframe.data, + video, + }) + keyframeMovies.set(keyframe, movie) + } + + return { + movie, + width: video.width, + height: video.height, + age: Math.round(performance.now() - keyframe.arrival), + } + } + + /** + * Mutes or unmutes the sensor's live sound for every tier at once, through the one context the tiers share, and the sound half of each demand, a running + * one among them, sends a view at home or from away no sound from its next release on while muted. A recording reads the tier's buffer, which the mute + * leaves whole: it keeps its sound. + * @param muted - Whether the camera's Microphone is muted. + */ + muteMicrophone(muted: boolean): void { + this.context.microphoneMuted = muted + } + + /** + * Holds every running tier of the sensor through its source's reconnect, as the camera states it reconnecting: each tier's demand whose gap clock runs + * counts the recovering gap time from the call, once, until its next picture. A demand with no picture yet keeps its first-sample bound. + */ + sourceRecovering(): void { + for (const tier of this.videoTiers.values()) { + tier.demand?.sourceRecovering() + } + } + + /** + * Withdraws each demand whose start is still pending, at a reset, a destroy or as the camera goes out of service, each a withdrawal the library makes for + * its own reasons while the plugin did nothing wrong, which is why each writes one debug event on the tier's channel, which the outcome closes, and raises no + * problem. A start withdrawn at its own bound is the demand's, which raises its plugin-failure problem. + * @param outcome - What the debug event says became of the demand. + */ + withdraw(outcome: string): void { + for (const tier of this.videoTiers.values()) { + tier.demand?.withdraw(outcome, false) + } + } + + // A join's one step: its hold puts the holder's route in place, its consumers join the demand, and only then is the delegate called for a demand the join + // raised, which is why every field a write reads is set before the plugin's code runs. + private joinDemand(tier: Tier, holder: TierHolder, joining: (demand: TierDemand) => readonly TierJoin[]): TierHold { + const raised = !tier.demand + const demand = tier.demand ?? (tier.demand = new TierDemand(tier)) + const joins = joining(demand) + const hold = new TierHold(demand, holder, joins) + + for (const join of joins) { + demand.join(join) + } + + if (raised) { + demand.start() + } + + return hold + } +} diff --git a/src/lib/camera/buffer/CameraBuffer.spec.ts b/src/lib/camera/buffer/CameraBuffer.spec.ts new file mode 100644 index 000000000..41dc8764f --- /dev/null +++ b/src/lib/camera/buffer/CameraBuffer.spec.ts @@ -0,0 +1,822 @@ +import type { TierPictureFixture } from '../../../test-utils/mp4Fixtures.js' +import type { CameraReporter } from '../diagnostics/CameraReporter.js' +import type { StreamTierMedium } from '../StreamingOptions.js' +import type { BufferedSample } from './CameraBuffer.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + sampleFragment, + soundSample, + TIER_STREAM_PARAMETER_SETS, + TIER_STREAM_PICTURE, + TIER_STREAM_SOUND, + tierPicture, + tierStreamFragment, + tierStreamInitialization, +} 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' + +const SENSOR_UUID = 'a1b2c3d4-0000-4000-8000-000000000001' + +// The ticks of a second on the picture's 90 kHz track and the sound's 48 kHz track. +const PICTURE_RATE = 90000 +const SOUND_RATE = 48000 + +interface PictureOptions extends TierPictureFixture { + // The duration the picture states in place of its frame's, 0 among them. + duration?: number + // The moment the fragment arrives, in milliseconds, the picture's own time by default. + moment?: number + // A sound sample timed with the picture in the same fragment, after it. + sound?: boolean +} + +// One buffer of a tier, fed by the library's own stream reader over a stream a row writes, at moments the row sets, with the span given and a place that +// holds no keyframe and keeps the sentence of each trim it is told, as the keeper's place is told them. A mark is told to the reader and then the buffer, as +// the tier's demand tells them. The buffer reports through a reporter of no camera unless a row hands its own. +interface Rig { + readonly buffer: TierBuffer + readonly trims: string[] + write: (chunk: Buffer, moment?: number) => void + // Writes one fragment holding one picture at a time in seconds. + at: (seconds: number, options?: PictureOptions) => void + // Writes one fragment holding one sound alone at a time in seconds, arriving at that time. + sound: (seconds: number) => void + discontinuity: () => void +} + +function rig(span: number, { parameterSets = TIER_STREAM_PARAMETER_SETS, reporter = detachedReporter() }: { + parameterSets?: readonly Buffer[] + reporter?: CameraReporter +} = {}): Rig { + const buffer = new TierBuffer({ reporter, sensorUUID: SENSOR_UUID, tierId: 1 }) + const trims: string[] = [] + + buffer.span = span + buffer.takePlace({ + displaced: () => undefined, + taken: () => undefined, + trimmed: (sentence) => { + trims.push(sentence) + }, + }) + + let moment = 0 + const reader = new Mp4StreamReader({ + fail: (reason) => { + throw new Error(reason) + }, + fragmentEnd: () => buffer.endFragment(), + sample: sample => buffer.take(sample, moment), + tracks: tracks => buffer.describe(tracks), + }) + const write = (chunk: Buffer, at = moment): void => { + moment = at + reader.write(chunk) + } + + write(tierStreamInitialization({ parameterSets })) + + return { + at: (seconds, options = {}) => write(tierStreamFragment({ + picture: [ + options.duration === undefined + ? tierPicture(options) + : { + ...tierPicture(options), + duration: options.duration, + }, + ], + pictureTime: BigInt(seconds * PICTURE_RATE), + sound: options.sound + ? [ + soundSample(Buffer.alloc(40, 0x5A)), + ] + : [], + soundTime: BigInt(seconds * SOUND_RATE), + }), options.moment ?? seconds * 1000), + buffer, + discontinuity: () => { + reader.discontinuity() + buffer.mark() + }, + sound: seconds => write(tierStreamFragment({ + sound: [ + soundSample(Buffer.alloc(40, 0x5A)), + ], + soundTime: BigInt(seconds * SOUND_RATE), + }), seconds * 1000), + trims, + write, + } +} + +// The times in seconds of the samples of one medium the buffer keeps, in the order it keeps them. +function times(buffer: TierBuffer, medium: StreamTierMedium): number[] { + return buffer.samples.filter(({ track }) => track.medium === medium).map(({ time }) => time / 1000000) +} + +// Each sample the buffer keeps as its medium and its time in seconds, in delivery order. +function delivered(buffer: TierBuffer): string[] { + return buffer.samples.map(({ time, track }) => `${track.medium} ${time / 1000000}`) +} + +// The steps of half a second from one time to another, the ends included. +function halves(from: number, to: number): number[] { + return Array.from({ length: (to - from) * 2 + 1 }, (_, index) => from + index / 2) +} + +// The times in seconds of the picture keyframes the buffer keeps. +function keyframeTimes(buffer: TierBuffer): number[] { + return buffer.samples.filter(({ sync, track }) => sync && (track.medium === 'video')).map(({ time }) => time / 1000000) +} + +// A place a row takes, which records each call it is told in a log the row's places share. +interface ScriptedPlace { + keyframe?: BufferedSample + taken: (sample: BufferedSample) => void + trimmed: () => void + displaced: () => void +} + +/* A place named in the shared log, which writes each sample it is told by its medium and its time in seconds, stands at the keyframe of the time given + * once the buffer tells it of that keyframe, and throws from its call of the sample of the time given. + */ +function scriptedPlace(log: string[], name: string, { standsAt, throwsAt }: { standsAt?: number, throwsAt?: number } = {}): ScriptedPlace { + const place: ScriptedPlace = { + displaced: () => { + log.push(`${name}: displaced`) + }, + taken: (sample) => { + const seconds = sample.time / 1000000 + + log.push(`${name}: ${sample.track.medium} ${seconds}`) + + if (sample.sync && (seconds === standsAt)) { + place.keyframe = sample + } + + if (seconds === throwsAt) { + throw new Error('The reader failed.') + } + }, + trimmed: () => { + log.push(`${name}: trimmed`) + }, + } + + return place +} + +// A place a row takes, which holds no keyframe and writes what it is told in the order told: each sample by its medium and its time in seconds, and each +// end of a run. +function hearing(buffer: TierBuffer): string[] { + const told: string[] = [] + + buffer.takePlace({ + displaced: () => undefined, + ending: () => { + told.push('end') + }, + taken: ({ time, track }) => { + told.push(`${track.medium} ${time / 1000000}`) + }, + }) + + return told +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('cameraBuffer', () => { + describe('the span rule', () => { + it('reaches back to the latest keyframe its span allows, over prebuffers of nothing, one keyframe interval and more than it holds, with no sound ' + + 'timed before that keyframe', () => { + for (const [span, from] of [ + [0, 5], + [2000, 3], + [30000, 1], + ]) { + const { at, buffer } = rig(span) + + for (const seconds of halves(0, 6)) { + at(seconds, { + keyframe: [1, 3, 5].includes(seconds), + sound: true, + }) + } + + expect({ + span, + pictures: times(buffer, 'video'), + sound: times(buffer, 'audio'), + }).toEqual({ + span, + pictures: halves(from, 6), + sound: halves(from, 6), + }) + } + }) + + it('keeps the sound a fragment delivers before its keyframe when it is timed at or after that keyframe, and none timed before', () => { + const { at, buffer, write } = rig(0) + // A fragment whose sound run stands before its picture: two sounds of 20 milliseconds from 20 milliseconds before a keyframe. + const soundFirst = (seconds: number): Buffer => sampleFragment( + { + decodeTime: BigInt(seconds * SOUND_RATE - 960), + samples: [ + soundSample(Buffer.alloc(40, 1)), + soundSample(Buffer.alloc(40, 2)), + ], + trackId: TIER_STREAM_SOUND, + }, + { + decodeTime: BigInt(seconds * PICTURE_RATE), + samples: [ + tierPicture({ keyframe: true }), + ], + trackId: TIER_STREAM_PICTURE, + }, + ) + + write(soundFirst(1), 1000) + at(1.5, { sound: true }) + + expect(delivered(buffer)).toEqual([ + 'audio 1', + 'video 1', + 'video 1.5', + 'audio 1.5', + ]) + + // The head moves to a later keyframe whose fragment delivers its sound first. + write(soundFirst(2), 2000) + + expect(delivered(buffer)).toEqual(['audio 2', 'video 2']) + }) + + it('takes a sample\'s duration from its track\'s next decode time once that arrives, whatever the stream states, its run\'s newest keeping its stated ' + + 'duration, or the duration of the sample before it when it states 0 or none', () => { + const { at, buffer, discontinuity } = rig(30000) + const durations = (samples: readonly BufferedSample[]): (number | undefined)[] => samples.map(({ duration }) => duration) + const ticks = (...seconds: number[]): number[] => seconds.map(second => second * PICTURE_RATE) + + // A run's first sample that states none has no sample before it to take a duration from. + at(0, { keyframe: true, untimed: true }) + + expect(durations(buffer.samples)).toEqual([undefined]) + + // The newest stating 0, and then none, takes the duration of the sample before it. + at(0.5, { duration: 0 }) + + expect(durations(buffer.samples)).toEqual(ticks(0.5, 0.5)) + + at(1.25, { untimed: true }) + + expect(durations(buffer.samples)).toEqual(ticks(0.5, 0.75, 0.75)) + + // Each picture from here states its frame's duration, which stands while it is the newest and gives way to the next decode time. + at(1.5) + at(2) + + const run = [...buffer.samples] + + expect(durations(run)).toEqual([ + ...ticks(0.5, 0.75, 0.25, 0.5), + 3000, + ]) + + discontinuity() + at(3, { keyframe: true }) + + // The run's newest keeps its stated duration at the run's end, and the next run starts on its own. + expect(durations(run)).toEqual([ + ...ticks(0.5, 0.75, 0.25, 0.5), + 3000, + ]) + expect(durations(buffer.samples)).toEqual([3000]) + }) + }) + + describe('the ceilings', () => { + 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) + + for (let seconds = 0; seconds <= 16; seconds++) { + at(seconds, { + keyframe: [0, 12].includes(seconds), + }) + } + + expect(times(buffer, 'video')).toEqual([12, 13, 14, 15, 16]) + expect(trims).toEqual([ + `The camera buffer of the video tier 1 of the video sensor "${SENSOR_UUID}" reached back more than its prebuffer and the 10-second keyframe ` + + 'allowance between the stream\'s keyframes: it dropped its oldest samples up to a later keyframe, or every sample without one, and holds less ' + + 'than its prebuffer.', + ]) + + // It holds its span again at 17 seconds, which ends the episode, and the next trim opens an episode of its own. + for (let seconds = 17; seconds <= 28; seconds++) { + at(seconds, { keyframe: seconds === 24 }) + } + + expect(times(buffer, 'video')).toEqual([24, 25, 26, 27, 28]) + expect(trims).toHaveLength(2) + + const short = rig(0) + + for (let seconds = 0; seconds <= 12; seconds++) { + short.at(seconds, { keyframe: seconds === 0 }) + } + + expect([short.buffer.samples, short.trims.length]).toEqual([[], 1]) + + short.at(13, { keyframe: true }) + + expect(times(short.buffer, 'video')).toEqual([13]) + }) + + 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) + const large = 4000000 + + // Four-megabyte pictures four times a second pass the 30,000,000 octets of a two-second span: the buffer drops a second at a time. + for (let quarter = 0; quarter <= 15; quarter++) { + at(quarter / 4, { keyframe: quarter % 4 === 0, octets: large }) + } + + expect([ + times(buffer, 'video'), + trims.length, + ]).toEqual([ + [3, 3.25, 3.5, 3.75], + 1, + ]) + expect(trims[0]).toBe(`The camera buffer of the video tier 1 of the video sensor "${SENSOR_UUID}" held more than its ceiling of 30000000 octets: it ` + + 'dropped its oldest samples up to a later keyframe, or every sample without one, and holds less than its prebuffer.') + + // Small pictures let it hold its span again at five seconds, and large ones then pass the ceiling at seven, an episode of its own. + for (let quarter = 16; quarter <= 28; quarter++) { + at(quarter / 4, { + keyframe: quarter % 4 === 0, + octets: quarter > 20 + ? large + : 100, + }) + } + + expect([ + times(buffer, 'video'), + trims.length, + ]).toEqual([ + [6, 6.25, 6.5, 6.75, 7], + 2, + ]) + expect(buffer.octets).toBe(5 * large) + + const short = rig(0) + + for (let quarter = 0; quarter <= 6; quarter++) { + short.at(quarter / 4, { keyframe: quarter === 0, octets: large }) + } + + expect([short.buffer.samples, short.buffer.octets, short.trims.length]).toEqual([[], 0, 1]) + }) + + it('tells its places of the first trim a later demand brings, the episode an earlier demand opened ending as that demand leaves', () => { + const { at, buffer, trims, write } = rig(2000) + const large = 4000000 + + // Four-megabyte pictures four times a second pass the 30,000,000 octets of a two-second span before the buffer holds that span: the demand + // leaves with its episode still open. + for (let quarter = 0; quarter <= 7; quarter++) { + at(quarter / 4, { keyframe: quarter % 4 === 0, octets: large }) + } + + expect(trims).toHaveLength(1) + + buffer.empty() + + // The next demand's stream passes the ceiling again before the buffer holds its span. + write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + + for (let quarter = 0; quarter <= 7; quarter++) { + at(quarter / 4, { keyframe: quarter % 4 === 0, octets: large }) + } + + expect(trims).toHaveLength(2) + }) + }) + + describe('emptying', () => { + it('empties at a discontinuity, a new initialization segment and the end of its tier\'s demand, and fills again from the next keyframe', () => { + const { at, buffer, discontinuity, write } = rig(0) + + at(0, { keyframe: true, sound: true }) + at(0.5, { sound: true }) + discontinuity() + at(1, { sound: true }) + + expect(buffer.samples).toEqual([]) + + // The mark ends the run at the picture, the first sample after it, and the sound after that picture empties nothing more. + at(1.5, { keyframe: true, sound: true }) + discontinuity() + at(2, { keyframe: true, sound: true }) + + expect(delivered(buffer)).toEqual(['video 2', 'audio 2']) + + write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS }), 2100) + + expect(buffer.samples).toEqual([]) + + at(2.5) + at(3, { keyframe: true }) + + expect(times(buffer, 'video')).toEqual([3]) + + // The tier empties its buffer as its demand leaves it. + buffer.empty() + + expect(buffer.samples).toEqual([]) + }) + + it('empties at a jump of more than a second in a track\'s times with no mark, ahead of the time since the sample before, and keeps a source that ' + + 'pauses on its own time', () => { + const { at, buffer } = rig(30000) + + at(0, { keyframe: true }) + at(0.5) + at(5, { moment: 600 }) + + expect(buffer.samples).toEqual([]) + + at(5.5, { keyframe: true, moment: 700 }) + at(6, { moment: 1200 }) + at(14, { moment: 9200 }) + + expect(times(buffer, 'video')).toEqual([5.5, 6, 14]) + }) + }) + + describe('a restart its demand marks', () => { + it('ends the run once, at a picture that is the first sample after the mark, and nothing more at the sound after it', () => { + const { at, buffer, discontinuity, sound } = rig(0) + + at(0, { keyframe: true, sound: true }) + at(0.5, { sound: true }) + + const told = hearing(buffer) + + discontinuity() + at(1, { keyframe: true }) + sound(1) + + expect(told).toEqual(['end', 'video 1', 'audio 1']) + expect(delivered(buffer)).toEqual(['video 1', 'audio 1']) + }) + + it('ends the run at a sound that opens the restart where it holds no run of sound, and keeps the restart\'s keyframe after it', () => { + const { at, buffer, discontinuity, sound } = rig(0) + + at(0, { keyframe: true }) + at(0.5) + + const told = hearing(buffer) + + discontinuity() + sound(1) + at(1, { keyframe: true }) + + expect(told).toEqual(['end', 'audio 1', 'video 1']) + expect(delivered(buffer)).toEqual(['video 1']) + }) + + it('ends the run at a sound that opens a second restart after a first restart of pictures alone', () => { + const { at, buffer, discontinuity, sound } = rig(0) + + at(0, { keyframe: true, sound: true }) + + const told = hearing(buffer) + + discontinuity() + at(1, { keyframe: true }) + at(1.5) + discontinuity() + sound(2) + at(2, { keyframe: true }) + + expect(told).toEqual([ + 'end', + 'video 1', + 'video 1.5', + 'end', + 'audio 2', + 'video 2', + ]) + expect(delivered(buffer)).toEqual(['video 2']) + }) + + it('ends nothing at a mark made while it holds a run of no track, the mark spent at the first sample after it', () => { + const { at, buffer, discontinuity } = rig(0) + const told = hearing(buffer) + + discontinuity() + at(0, { keyframe: true, sound: true }) + at(0.5) + + expect(told).toEqual(['video 0', 'audio 0', 'video 0.5']) + expect(delivered(buffer)).toEqual(['video 0', 'audio 0', 'video 0.5']) + }) + + it('ends the run once at a mark and the initialization segment after it, at the segment', () => { + const { at, buffer, discontinuity, write } = rig(0) + + at(0, { keyframe: true, sound: true }) + + const told = hearing(buffer) + + discontinuity() + write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS }), 500) + at(1, { keyframe: true, sound: true }) + + expect(told).toEqual(['end', 'video 1', 'audio 1']) + }) + + it('ends the run once at a mark and its demand\'s leave after it, at the leave', () => { + const { at, buffer, discontinuity } = rig(0) + + at(0, { keyframe: true, sound: true }) + + const told = hearing(buffer) + + discontinuity() + buffer.empty() + at(1, { keyframe: true, sound: true }) + + expect(told).toEqual(['end', 'video 1', 'audio 1']) + }) + + it('ends the run at the next sample after a mark made once a fragment\'s end left it holding no sample', () => { + const { at, buffer, discontinuity } = rig(0) + + // A picture that is no keyframe, passed over, and its sound, dropped as its fragment ends. + at(0, { sound: true }) + + expect(buffer.samples).toEqual([]) + + const told = hearing(buffer) + + discontinuity() + at(0.5, { keyframe: true }) + + expect(told).toEqual(['end', 'video 0.5']) + }) + + it('ends the run once at a sample after a mark that also leaps more than a second ahead', () => { + const { at, buffer, discontinuity } = rig(30000) + + at(0, { keyframe: true }) + at(0.5) + + const told = hearing(buffer) + + discontinuity() + at(5, { keyframe: true, moment: 600 }) + + expect(told).toEqual(['end', 'video 5']) + expect(delivered(buffer)).toEqual(['video 5']) + }) + }) + + describe('places', () => { + it('holds its head at the earliest keyframe a place stands at, whichever place was taken first, gives each place up alone, and holds no head for a ' + + 'place that holds no keyframe', () => { + const { at, buffer } = rig(0) + const log: string[] = [] + const later = scriptedPlace(log, 'later', { standsAt: 3 }) + const earlier = scriptedPlace(log, 'earlier', { standsAt: 1 }) + + buffer.takePlace(later) + buffer.takePlace(earlier) + + for (const seconds of halves(0, 6)) { + at(seconds, { + keyframe: [1, 3, 5].includes(seconds), + }) + } + + expect(keyframeTimes(buffer)).toEqual([1, 3, 5]) + + buffer.givePlaceUp(earlier) + + expect(keyframeTimes(buffer)).toEqual([3, 5]) + + // The rig's own place, which holds no keyframe, stays and holds nothing. + buffer.givePlaceUp(later) + + expect([ + keyframeTimes(buffer), + times(buffer, 'video'), + ]).toEqual([ + [5], + [5, 5.5, 6], + ]) + }) + + it('holds its head at the earliest keyframe a place stands at when the place standing there was taken before the place standing later', () => { + const { at, buffer } = rig(0) + const log: string[] = [] + + buffer.takePlace(scriptedPlace(log, 'earlier', { standsAt: 1 })) + buffer.takePlace(scriptedPlace(log, 'later', { standsAt: 3 })) + + for (const seconds of halves(0, 6)) { + at(seconds, { + keyframe: [1, 3, 5].includes(seconds), + }) + } + + expect(keyframeTimes(buffer)).toEqual([1, 3, 5]) + }) + + it('takes a place whose call throws off, logs it once and tells it it is displaced once the step has finished, the other places and the write ' + + 'carrying on', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { at, buffer } = rig(0) + const log: string[] = [] + + buffer.takePlace(scriptedPlace(log, 'before')) + buffer.takePlace(scriptedPlace(log, 'failing', { standsAt: 1, throwsAt: 2 })) + buffer.takePlace(scriptedPlace(log, 'after')) + + expect(() => { + for (const seconds of halves(1, 3)) { + at(seconds, { + keyframe: [1, 3].includes(seconds), + }) + } + }).not.toThrow() + + expect(log.filter(line => line.startsWith('failing'))).toEqual([ + 'failing: video 1', + 'failing: video 1.5', + 'failing: video 2', + 'failing: displaced', + ]) + expect(log.slice(log.indexOf('failing: video 2'), log.indexOf('failing: displaced') + 1)).toEqual([ + 'failing: video 2', + 'after: video 2', + 'failing: displaced', + ]) + expect(['before', 'after'].map(name => log.filter(line => line.startsWith(name)).length)).toEqual([5, 5]) + expect(keyframeTimes(buffer)).toEqual([3]) + expect(error.mock.calls.map(([line]) => String(line).split(': ')[0])).toEqual([ + `A reader of the camera buffer of the video tier 1 of the video sensor "${SENSOR_UUID}" failed to take the buffer's step, and its place is taken off`, + ]) + }) + + it('reports a reader\'s throw from its step and the throw of its displacement each as a library failure of its tier on its camera\'s channel, printing ' + + 'nothing', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { problems, reporter } = problemsOf() + const { at, buffer } = rig(0, { reporter }) + const stepFailure = new Error('The reader failed to take a step.') + const endFailure = new Error('The reader failed to end.') + const tier = `A reader of the camera buffer of the video tier 1 of the video sensor "${SENSOR_UUID}"` + + buffer.takePlace({ + displaced: () => { + throw endFailure + }, + taken: () => { + throw stepFailure + }, + }) + at(1, { keyframe: true }) + + expect(problems.map(problem => ({ ...problem, sentence: problem.sentence.split('\n')[0] }))).toEqual([ + { + accessoryUUID: REPORTER_ACCESSORY_UUID, + error: stepFailure, + kind: 'library-failure', + level: 'error', + sensorUUID: SENSOR_UUID, + sentence: `${tier} failed to take the buffer's step, and its place is taken off: Error: The reader failed to take a step.`, + tierId: 1, + }, + { + accessoryUUID: REPORTER_ACCESSORY_UUID, + error: endFailure, + kind: 'library-failure', + level: 'error', + sensorUUID: SENSOR_UUID, + sentence: `${tier} failed to take the end of its place: Error: The reader failed to end.`, + tierId: 1, + }, + ]) + expect(error).not.toHaveBeenCalled() + }) + + it('tells a place a ceiling\'s trim passes that it is displaced once the step has finished, after the other places hear of the trim and the sample', () => { + const { at, buffer } = rig(0) + const log: string[] = [] + + buffer.takePlace(scriptedPlace(log, 'standing', { standsAt: 0 })) + buffer.takePlace(scriptedPlace(log, 'other')) + + for (let seconds = 0; seconds <= 11; seconds++) { + at(seconds, { keyframe: seconds === 0 }) + } + + expect(log.slice(log.indexOf('standing: video 10') + 1)).toEqual([ + 'other: video 10', + 'other: trimmed', + 'other: video 11', + 'standing: displaced', + ]) + }) + }) + + describe('ready', () => { + it('is ready once it holds its prebuffer, and again after a trim or an emptying only once it holds it anew', () => { + const { at, buffer, discontinuity } = rig(2000) + const readings: boolean[] = [] + + for (const seconds of halves(0, 2)) { + at(seconds, { keyframe: seconds === 0 }) + readings.push(buffer.ready) + } + + expect(readings).toEqual([false, false, false, false, true]) + + // Twelve seconds with no later keyframe pass the reach ceiling, which leaves nothing. + for (let seconds = 3; seconds <= 13; seconds++) { + at(seconds) + } + + expect([buffer.samples, buffer.ready]).toEqual([[], false]) + + at(14, { keyframe: true }) + at(15) + + expect(buffer.ready).toBe(false) + + at(16) + + expect(buffer.ready).toBe(true) + + discontinuity() + at(17, { keyframe: true }) + + expect(buffer.ready).toBe(false) + + at(19) + + expect(buffer.ready).toBe(true) + }) + + it('is never ready for a tier whose description and keyframes both lack parameter sets, and ready once a keyframe carries them in band', () => { + const { at, buffer } = rig(0, { parameterSets: [] }) + + at(0, { keyframe: true }) + at(0.5) + + expect([buffer.tracks!.video!.parameterSets.length, buffer.ready]).toEqual([0, false]) + + at(1, { inBand: true, keyframe: true }) + + expect(buffer.ready).toBe(true) + }) + + it('is never ready for a tier whose description holds the sequence and picture parameter sets alone and whose keyframes carry none, and ready once ' + + 'its head keyframe carries the video set in band', () => { + const [VPS, ...described] = TIER_STREAM_PARAMETER_SETS + // The span is 0: the head the buffer opens on is its newest keyframe. + const { at, buffer } = rig(0, { parameterSets: described }) + + at(0, { keyframe: true }) + at(0.5) + at(1, { keyframe: true }) + at(1.5) + + expect([buffer.tracks!.video!.parameterSets.length > 0, buffer.head?.time, buffer.ready]).toEqual([true, 1000000, false]) + + at(2, { + inBand: [VPS], + keyframe: true, + }) + + expect([buffer.head?.time, buffer.ready]).toEqual([2000000, true]) + }) + }) +}) diff --git a/src/lib/camera/buffer/CameraBuffer.ts b/src/lib/camera/buffer/CameraBuffer.ts new file mode 100644 index 000000000..37e614f86 --- /dev/null +++ b/src/lib/camera/buffer/CameraBuffer.ts @@ -0,0 +1,720 @@ +import type { Buffer } from 'node:buffer' + +import type { CameraReporter, FailureFields } from '../diagnostics/CameraReporter.js' +import type { Mp4StreamSample, Mp4StreamTrack, Mp4StreamTracks } from '../mp4/Mp4StreamReader.js' +import type { StreamTierMedium } from '../StreamingOptions.js' + +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. + */ + +// 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 +// reach: a segment's cap over the segment target, 2.5 MB a second, read as 2,500,000 octets a second. +const KEYFRAME_ALLOWANCE = 10 * 1000 +const OCTETS_PER_MILLISECOND = 2500 + +// A sample timed more than a second ahead of where the sample before it and the time since that sample arrived put it marks a restart its source did not +// mark, as the live path's run reads one. One timed at or before the sample before it never arrives, the stream reader refusing its stream. +const JUMP_LIMIT = 1000000 + +const MICROSECONDS = 1000000n + +/** + * One sample a tier's buffer keeps, with its times as the stream states them in its track's timescale. + */ +export interface BufferedSample { + /** + * The track the sample belongs to, as the initialization segment it follows describes it. + */ + readonly track: Mp4StreamTrack + /** + * The sample's octets as the stream reader handed them over: a view of the plugin's chunk, or the reader's own joined copy for a sample that spanned + * chunks. + */ + readonly data: Buffer + /** + * The sample's decode time. + */ + readonly decodeTime: bigint + /** + * The sample's duration: the distance to its track's next decode time in its run once that sample has arrived, whatever the stream states, since a + * stream's stated durations need not follow its decode times. While the sample is unsettled, its run's newest, it is a stand-in: the stream's own, or + * for a sample that states 0 or none the duration of the sample before it, and absent for a run's first sample that states 0 or none. A recording + * writes a picture's stand-in, and for an unsettled sound the duration its own packet states wherever the packet says one. + */ + readonly duration?: number + /** + * Whether the sample's duration is settled, its track's next decode time in its run having arrived. + */ + readonly settled: boolean + /** + * The time from the sample's decode time to its presentation. + */ + readonly compositionOffset: number + /** + * Whether the sample is a sync sample, a picture's keyframe. + */ + readonly sync: boolean + /** + * The moment the sample arrived, in milliseconds of the steady clock. + */ + readonly arrival: number + /** + * The sample's decode time in whole microseconds, which the buffer compares its tracks on. + */ + readonly time: number + /** + * The fragment the sample arrived in, counted by the buffer's fragment ends. The sample's fragment has ended once the buffer's count passes it. + */ + readonly fragment: number + /** + * The sample's place in the order the stream delivered its samples, counted over every sample the buffer read since its making, kept or passed over, + * and a sample delivered earlier than another has the lower. + */ + readonly order: number +} + +/** + * The samples a walk of a tier's buffer from a keyframe on reads: the pictures from the keyframe on in the order the stream delivered them, and every sound + * the buffer keeps timed at or after the keyframe, in that order too. + */ +export interface BufferWalk { + readonly pictures: readonly BufferedSample[] + readonly sounds: readonly BufferedSample[] +} + +/** + * A reader's place in a tier's buffer: the keyframe it stands at, which the span rule never moves the head past, and what the reader is told of the + * buffer's steps, each call made inside the step, but for a displacement, told once the step has finished. A reader hears only the calls it implements. + */ +export interface BufferPlace { + /** + * The keyframe the place stands at, absent for a place that holds no keyframe, which holds no head and which no trim displaces. + */ + readonly keyframe?: BufferedSample + /** + * Takes each sample the buffer read, once it kept or passed over it. + * @param sample - The sample. + */ + taken(sample: BufferedSample): void + /** + * Marks the end of a fragment, once the buffer has every sample of it. + */ + fragmentEnd?(): void + /** + * Takes the tracks of a new initialization segment, before the run they end empties the buffer. + * @param tracks - The tracks. + */ + describing?(tracks: Mp4StreamTracks): void + /** + * Marks the end of a run, while the buffer still holds its samples, each track's newest sample unsettled with its stand-in duration. + */ + ending?(): void + /** + * Takes the sentence of a ceiling's trim, told to each place once for each episode of trims. + * @param sentence - The trim's sentence, naming the tier and the ceiling it passed. + */ + trimmed?(sentence: string): void + /** + * Marks the place taken off the buffer, by a ceiling's trim past its keyframe or by a throw from one of its own calls, told once the buffer's step has + * finished. + */ + displaced(): void +} + +/** + * What a tier's buffer is made with: the tier it keeps, which its sentences name, and the camera's reporter. + */ +export interface TierBufferOptions { + /** + * The camera's reporter, through which a reader's failure inside the buffer's step is the library's. + */ + readonly reporter: CameraReporter + /** + * The video sensor whose tier the buffer keeps, in lowercase. + */ + readonly sensorUUID: string + /** + * The video tier the buffer keeps. + */ + readonly tierId: number +} + +// A kept sample, whose duration the buffer settles as its track's next decode time arrives. +type KeptSample = Omit & { duration?: number, settled: boolean } + +// What the buffer reads of one track since it last emptied: its newest sample, which a jump is read from and whose duration the next decode time settles. +interface TrackRun { + newest: KeptSample +} + +/** + * One tier's buffer: its samples in delivery order, picture and sound, beside the tier's latest track descriptions. + * + * The span rule: the buffer reaches back to the latest picture keyframe whose time is at or before its newest picture's less its span, and holds no sound + * timed before that keyframe, which means it always opens on a keyframe. It fills from a keyframe: a picture that arrives while it holds none is passed over, + * and sound that arrives then is kept only until its fragment ends, for the keyframe that fragment may still hold. + * + * Its span is nothing until the tier's keeper sets one, and a tier only viewers hold keeps the samples since its latest keyframe. Its ceilings bound a source + * that misbehaves: the buffer never reaches back further than its span and the keyframe allowance, and never holds more octets than that reach at the + * segment rate. Past a ceiling it drops from its head to its next keyframe, or drops everything when it holds no later one, and tells each place of the trim + * once for the episode, which ends once the buffer holds its span again inside its ceilings with nothing dropped, or as its tier's demand leaves. + * + * The buffer empties at a new initialization segment, at the end of a run, and as its tier's demand leaves the tier. A run ends at a restart its demand + * marks, read at the next sample the buffer takes, of whichever track, while it holds a run of some track, and at a leap ahead in a track's times on a + * track it holds a run of, the two read together on the runs as they stood before that sample, which is why one restart ends the run once. A run is held from a + * track's first sample until the run ends, whatever a fragment's end or a ceiling drops. It is ready while it holds its span, a keyframe at or before its + * newest picture's time less its span, and each of HEVC's video, sequence and picture parameter sets in the picture's description or in that keyframe. + * + * Each reader of its steps keeps a place in it, given up by the reader alone. An open recording's stands at its segment in progress: the span rule + * moves the head no further than the earliest keyframe a place stands at and the buffer reaches back past its span while the segment grows, and a place + * that holds no keyframe hears the buffer's steps and holds no head. The ceilings still trim past a place's keyframe, which takes the place off. A place + * whose call throws is taken off too, and reported once as a library-failure problem. No reader's fault reaches the plugin's write. A place taken off + * is told it is displaced once the buffer's step has finished, never inside it: a reader that acts on being told cannot re-enter the step. A place + * given up lets the buffer fall back to its span at once. + * + * The buffer offers one walk from a keyframe on, which a recording's segments read and a view's opening reads. A view's opening holds no place: it reads + * the walk from its keyframe while the buffer keeps that keyframe, and once the buffer lets it go reads the buffer's keyframes again. + */ +export class TierBuffer { + /** + * The video sensor whose tier the buffer keeps, in lowercase. + */ + readonly sensorUUID: string + /** + * The video tier the buffer keeps. + */ + readonly tierId: number + private readonly reporter: CameraReporter + // What a reader's failure concerns: the buffer's sensor and its tier. + private readonly fields: FailureFields + // How far back the buffer reaches from its newest picture, in milliseconds. + private spanTime = 0 + // The places the buffer holds, in the order they were taken. Each change replaces the array, which is why a step's walk reads the places as the step found them. + private places: readonly BufferPlace[] = [] + // The places a step took off, each told it is displaced once the step has finished. + private displacing: BufferPlace[] = [] + private kept: KeptSample[] = [] + // The picture keyframes kept, oldest first, the first the buffer's head. + private keyframes: KeptSample[] = [] + private newest?: KeptSample + private octetCount = 0 + private described?: Mp4StreamTracks + private runs: Partial> = {} + // Whether the demand marked a restart the buffer has not yet read, which the next sample it takes reads. + private marked = false + // Whether a ceiling has dropped samples since the buffer last held its span inside its ceilings or emptied as its tier's demand left. + private trimming = false + private fragmentCount = 0 + // The samples the buffer has read since its making, which gives each the next place in the delivery order. + private sampleCount = 0 + + /** + * Makes a tier's buffer, which holds nothing until its first keyframe and reaches back no further than that keyframe until its span is set. + * @param options - The buffer's options. + */ + constructor(options: TierBufferOptions) { + this.sensorUUID = options.sensorUUID + this.tierId = options.tierId + this.reporter = options.reporter + this.fields = { sensorUUID: options.sensorUUID, tierId: options.tierId } + } + + /** + * How far back the buffer reaches from its newest picture, in milliseconds: nothing until the tier's keeper sets its prebuffer. Setting it moves the + * head at once as far as the new span allows. + */ + get span(): number { + return this.spanTime + } + + set span(span: number) { + this.spanTime = span + this.advance() + } + + /** + * The tier's latest track descriptions, absent until the buffer is handed its first. + */ + get tracks(): Mp4StreamTracks | undefined { + return this.described + } + + /** + * The samples the buffer keeps, in the order the stream delivered them. + */ + get samples(): readonly BufferedSample[] { + return this.kept + } + + /** + * The octets of every sample the buffer keeps. + */ + get octets(): number { + return this.octetCount + } + + /** + * The keyframe the buffer opens on, absent while it holds none. + */ + get head(): BufferedSample | undefined { + return this.keyframes[0] + } + + /** + * How many fragments have ended since the buffer was made. A sample's fragment has ended once this count passes the sample's. + */ + get fragments(): number { + return this.fragmentCount + } + + /** + * Whether the buffer holds its span, a keyframe at or before its newest picture's time less its span, and the parameter sets a decoder needs for that + * keyframe: the keyframe's own units and its track's description hold between them each of HEVC's video, sequence and picture parameter sets. + */ + get ready(): boolean { + const video = this.described?.video + + if (!this.holdsSpan || (video === undefined)) { + return false + } + + return decodable(this.keyframes[0].data, video.parameterSets) + } + + /** + * Takes the tracks of the stream's latest initialization segment, each place told of them first, which end the run before them and empty the buffer. + * @param tracks - The tracks. + */ + describe(tracks: Mp4StreamTracks): void { + this.tell(place => place.describing?.(tracks)) + this.described = tracks + this.endRun() + this.displace() + } + + /** + * Takes one sample of the picture or the sound, in the stream's order, and tells each place of it. The sample first reads the runs as they stand: a + * restart marked since the buffer took its last sample ends the run while the buffer holds a run of some track, and a leap ahead in the sample's times + * ends it on a track it holds a run of, a sample that brings a mark and a leap ending it once. The mark is spent at this sample whatever it ends. + * @param sample - The sample, whose octets the buffer keeps as they are. + * @param moment - The moment the sample arrived, in milliseconds of the steady clock. + */ + take(sample: Mp4StreamSample, moment: number): void { + const kept = keptOf(sample, moment, this.fragmentCount, this.sampleCount++) + const { medium } = sample.track + const run = this.runs[medium] + const restarted = this.marked && this.holdsRun + + this.marked = false + + if (restarted || ((run !== undefined) && jumped(run, kept))) { + this.endRun() + } + + this.follow(medium, kept) + + if (medium === 'video') { + this.keepPicture(kept) + } else { + this.keepSound(kept) + } + + this.tell(place => place.taken(kept)) + this.displace() + } + + /** + * Marks the end of a fragment: sound kept while the buffer holds no keyframe is dropped, its fragment having brought none. + */ + endFragment(): void { + if (this.keyframes.length === 0) { + this.clear() + } + + this.fragmentCount++ + this.tell(place => place.fragmentEnd?.()) + this.displace() + } + + /** + * Marks the stream's restart, as the tier's demand tells of it, which the buffer reads at the next sample it takes, of whichever track, and records + * nothing more: that sample ends the run where the buffer holds a run of some track, and ends nothing where it holds a run of none. + */ + mark(): void { + this.marked = true + } + + /** + * Ends the run and empties the buffer, which fills again from the next keyframe, as the tier's demand leaves the tier. Each place is told of the end while + * the buffer still holds the run, each track's newest sample unsettled with its stand-in duration. The descriptions stay, and a trim episode ends, which means the + * next demand's first trim is told. + */ + empty(): void { + this.trimming = false + this.endRun() + this.displace() + } + + /** + * Takes a reader's place, which holds the buffer's head at or before its keyframe and is told of the buffer's steps until its reader gives it up, a + * ceiling trims past its keyframe or one of its calls throws. + * @param place - The place. + */ + takePlace(place: BufferPlace): void { + this.places = [...this.places, place] + } + + /** + * Gives up a reader's place, and moves the buffer's head as far as its span and the places left allow at once. + * @param place - The place. + */ + givePlaceUp(place: BufferPlace): void { + this.places = this.places.filter(other => other !== place) + this.advance() + } + + /** + * Walks the buffer from a keyframe on, the one walk that a recording's segments read and a view's opening reads: the pictures from the keyframe on in the + * order the stream delivered them, and every sound the buffer keeps timed at or after the keyframe, wherever it stands, since the buffer keeps such a + * sound that arrived ahead of its keyframe. + * @param keyframe - The keyframe, one the buffer keeps. + * @returns The walk's pictures and sounds. + */ + walk(keyframe: BufferedSample): BufferWalk { + const pictures: BufferedSample[] = [] + const sounds: BufferedSample[] = [] + + for (const sample of this.kept) { + if (sample.track.medium === 'video') { + if ((pictures.length > 0) || (sample === keyframe)) { + pictures.push(sample) + } + } else if (sample.time >= keyframe.time) { + sounds.push(sample) + } + } + + return { pictures, sounds } + } + + /** + * The latest keyframe the buffer keeps that the stream delivered before a place in its delivery order. + * @param before - The place, a sample's order, which the keyframe stands before. + * @returns The keyframe, or `undefined` when the buffer keeps none before that place. + */ + keyframeBefore(before: number): BufferedSample | undefined { + return this.keyframes.findLast(keyframe => keyframe.order < before) + } + + /** + * Whether the buffer still keeps a keyframe it kept, and with it everything a walk from that keyframe reads, since the buffer lets samples go only from + * its head or all at once. + * @param keyframe - The keyframe. + * @returns Whether the buffer keeps it. + */ + keeps(keyframe: BufferedSample): boolean { + const head = this.keyframes[0] + + return (head !== undefined) && (head.order <= keyframe.order) + } + + // The buffer's tier as its sentences name it. + private get tierName(): string { + return `the video tier ${this.tierId} of the video sensor "${this.sensorUUID}"` + } + + // Whether the head keyframe stands at or before the newest picture's time less the span. + private get holdsSpan(): boolean { + const head = this.keyframes[0] + + return (head !== undefined) && (this.newest !== undefined) && (head.time <= this.newest.time - this.spanTime * 1000) + } + + // Whether the buffer holds a run of some track, from that track's first sample until the run ends. + private get holdsRun(): boolean { + return (this.runs.video !== undefined) || (this.runs.audio !== undefined) + } + + // How far back the buffer reaches from its newest picture to its head keyframe, in microseconds. + private get reach(): number { + const head = this.keyframes[0] + + return (head === undefined) || (this.newest === undefined) + ? 0 + : this.newest.time - head.time + } + + /* Reads a sample into its track's run. The sample before it takes the distance to this decode time as its duration, whatever the stream stated, since a + * muxer that cuts a fragment at every frame can state 0, or half a step, before a decode time that moves on by a whole one, and is settled. The sample + * stands unsettled until the next arrives, with the duration the stream states as its stand-in, or the duration of the sample before it when it states + * 0 or none, and a run's newest picture holds one too, which a segment closed as it stands at the end of a run reads. + */ + private follow(medium: StreamTierMedium, kept: KeptSample): void { + const run = this.runs[medium] + + if (run !== undefined) { + run.newest.duration = Number(kept.decodeTime - run.newest.decodeTime) + run.newest.settled = true + } + + if ((kept.duration === undefined) || (kept.duration === 0)) { + kept.duration = run?.newest.duration + } + + if (run === undefined) { + this.runs[medium] = { newest: kept } + + return + } + + run.newest = kept + } + + /* Keeps a picture: one that arrives while the buffer holds no keyframe is passed over unless it is one, which opens the buffer and drops the sound kept + * before it timed before it. The head then moves to the latest keyframe the span rule allows, and the ceilings are read. + */ + private keepPicture(kept: KeptSample): void { + if (this.keyframes.length === 0) { + if (!kept.sync) { + return + } + + this.dropBefore(kept) + } + + this.kept.push(kept) + this.octetCount += kept.data.length + this.newest = kept + + if (kept.sync) { + this.keyframes.push(kept) + } + + this.advance() + this.bound() + } + + // Moves the head to the latest keyframe at or before the newest picture's time less the span, and no further than the earliest keyframe a place stands + // at, dropping what stands before it. + private advance(): void { + if (this.newest === undefined) { + return + } + + const latest = this.newest.time - this.spanTime * 1000 + let head = 0 + + while ((head + 1 < this.keyframes.length) && (this.keyframes[head + 1].time <= latest) && !this.standsAt(this.keyframes[head])) { + head++ + } + + if (head > 0) { + this.keyframes.splice(0, head) + this.dropBefore(this.keyframes[0]) + } + } + + // Whether a place stands at a keyframe. + private standsAt(keyframe: KeptSample): boolean { + for (const place of this.places) { + if (place.keyframe === keyframe) { + return true + } + } + + return false + } + + // Keeps a sound unless it is timed before the head keyframe, and reads the ceilings. + private keepSound(kept: KeptSample): void { + const head = this.keyframes[0] + + if ((head !== undefined) && (kept.time < head.time)) { + return + } + + this.kept.push(kept) + this.octetCount += kept.data.length + this.bound() + } + + /* Drops from the head to the next keyframe while the buffer passes a ceiling, and everything once it holds no later keyframe, telling each place of the + * trim once for an episode, named by the first ceiling it passed. An episode ends at a sample that drops nothing while the buffer holds its span. A drop + * of a place's keyframe takes the place off before the places are told, and the place is told it is displaced once the step has finished. The sentence + * 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 + let passed: 'octets' | 'reach' | undefined + + for (;;) { + const over = this.reach > reachLimit + ? 'reach' + : this.octetCount > octetLimit + ? 'octets' + : undefined + + if (over === undefined) { + break + } + + passed ??= over + + if (this.keyframes.length > 1) { + this.displaceAt(this.keyframes[0]) + this.keyframes.shift() + this.dropBefore(this.keyframes[0]) + } else { + this.displaceAt() + this.clear() + } + } + + if (passed === undefined) { + if (this.trimming && this.holdsSpan) { + this.trimming = false + } + + return + } + + if (this.trimming) { + return + } + + this.trimming = true + + const prebuffer = this.spanTime > 0 + const ceiling = passed === 'reach' + ? `reached back more than ${prebuffer ? 'its prebuffer and ' : ''}the ${KEYFRAME_ALLOWANCE / 1000}-second keyframe allowance between the stream's ` + + 'keyframes' + : `held more than its ceiling of ${octetLimit} octets` + const sentence = `The camera buffer of ${this.tierName} ${ceiling}: it dropped its oldest samples up to a later keyframe, or every sample without ` + + `one${prebuffer ? ', and holds less than its prebuffer' : ''}.` + + this.tell(place => place.trimmed?.(sentence)) + } + + // Takes off each place a trim passes: the places standing at the keyframe the trim drops, or with none given, every place that stands at a keyframe. + private displaceAt(dropped?: KeptSample): void { + for (const place of this.places) { + if ((place.keyframe !== undefined) && ((dropped === undefined) || (place.keyframe === dropped))) { + this.takeOff(place) + } + } + } + + /* Makes one call of each place in the order the places were taken, skipping a place given up or taken off since the walk began. No place is told + * anything once it is off the buffer, whatever a reader does inside its call. A call that throws takes its place off and is reported once as a + * library-failure problem: it never reaches the plugin's write, and the place is told it is displaced once the step has finished. + */ + private tell(call: (place: BufferPlace) => void): void { + for (const place of this.places) { + if (!this.places.includes(place)) { + continue + } + + try { + call(place) + } catch (error) { + this.takeOff(place) + this.reporter.failure('library-failure', `A reader of the camera buffer of ${this.tierName} failed to take the buffer's step, and its place is taken off`, + error, this.fields) + } + } + } + + // Takes a place off the buffer, which then holds no head for it and tells it nothing more but its displacement once the step has finished. + private takeOff(place: BufferPlace): void { + this.places = this.places.filter(other => other !== place) + this.displacing.push(place) + } + + // Tells each place a step took off that it is displaced, once the step has finished. A throw from that call is reported once as a library-failure + // problem and goes no further. + private displace(): void { + if (this.displacing.length === 0) { + return + } + + const displaced = this.displacing + + this.displacing = [] + + for (const place of displaced) { + try { + place.displaced() + } catch (error) { + this.reporter.failure('library-failure', `A reader of the camera buffer of ${this.tierName} failed to take the end of its place`, error, this.fields) + } + } + } + + // Keeps the pictures from a keyframe on, in their order, and the sound timed at or after it, recounting the octets kept. + private dropBefore(head: KeptSample): void { + const kept: KeptSample[] = [] + let reached = false + let octets = 0 + + for (const sample of this.kept) { + reached ||= sample === head + + const keep = sample.track.medium === 'video' + ? reached + : sample.time >= head.time + + if (keep) { + kept.push(sample) + octets += sample.data.length + } + } + + this.kept = kept + this.octetCount = octets + } + + // Ends the run and drops every sample, each place told of the end while the buffer still holds the run. + private endRun(): void { + this.runs = {} + this.tell(place => place.ending?.()) + this.clear() + } + + // Drops every sample, the run's reading of each track staying. + private clear(): void { + this.kept = [] + this.keyframes = [] + this.newest = undefined + this.octetCount = 0 + } +} + +// 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. +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, + } +} + +// 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. +function jumped({ newest }: TrackRun, kept: KeptSample): boolean { + return kept.time > newest.time + (kept.arrival - newest.arrival) * 1000 + JUMP_LIMIT +} diff --git a/src/lib/camera/buffer/TierKeeper.ts b/src/lib/camera/buffer/TierKeeper.ts new file mode 100644 index 000000000..cc7af470e --- /dev/null +++ b/src/lib/camera/buffer/TierKeeper.ts @@ -0,0 +1,485 @@ +import type { CameraReporter } from '../diagnostics/CameraReporter.js' +import type { CameraProblemKind } from '../diagnostics/problems.js' +import type { Tier, TierHold, TierHolder, TierTable } from '../TierTable.js' +import type { BufferedSample, BufferPlace, TierBuffer } from './CameraBuffer.js' + +import { DELEGATE_CALL_TIMEOUT, settleWithin } from '../session/settleWithin.js' +import { LONG_GAP_TIME, RECOVERING_GAP_TIME } from '../TierTable.js' + +// The clocks of a held tier, its pictures alone moving them on: a running stream that hands over no picture for the stall time has stalled, and an open +// recording is told of a gap at the tier table's long-gap time, or at its recovering gap time once the source is stated reconnecting; and a tier is asked +// for again after a wait that doubles from the first to the longest. +const STALL_TIME = 2 * 1000 +const FIRST_WAIT = 1000 +const LONGEST_WAIT = 30 * 1000 + +/** + * Why the library holds a tier: it is the recorded tier and the user's switch allows recording, or it is marked `keepRunning` and the user's switch + * allows streaming, each while the camera is in service, its accessory published and its source not stated away. + */ +export type TierKeeperReason = 'kept-running' | 'recording' + +/** + * What a keeper holds and how it reaches it: the callback that tells an open recording of a gap, the prebuffer the tier's buffer spans while the keeper + * holds it for its recording, the camera's reporter, the tier by its sensor and identifier, and the lookup the sensor's tier table, which holds the tier's + * buffer, is reached through, since the tables are built after the keeper. + */ +export interface TierKeeperOptions { + /** + * Tells an open recording that the long-gap time passed since the last picture the keeper read from the tier's buffer, whatever the tier's demand did + * meanwhile, absent on a tier no recording reads. + */ + readonly gap?: () => void + /** + * How far back the tier's buffer reaches while the keeper holds the tier for its recording, in milliseconds. + */ + readonly prebuffer: number + /** + * The camera's reporter, through which the keeper raises the problems of the held tier, its own and its buffer's, on the camera's channel. + */ + readonly reporter: CameraReporter + /** + * The video sensor whose tier the keeper holds, in lowercase. + */ + readonly sensorUUID: string + /** + * The video tier the keeper holds. + */ + readonly tierId: number + /** + * Finds a sensor's tier table. + */ + readonly tierTable: (sensorUUID: string) => TierTable | undefined +} + +// What a kept hold hands its keeper: each sample the tier's buffer read, each trim of that buffer, the failure of its tier, and the taking off of its own +// place for a throw of one of its calls, the library's own reading failing. +interface KeptHoldRoutes { + readonly displaced: () => void + readonly failed: () => void + readonly taken: (sample: BufferedSample) => void + readonly trimmed: (sentence: string) => void +} + +/* One join of the keeper's tier, from the join to its drop: the join's holder, its place in the tier's buffer, which holds no keyframe and hands each + * sample the buffer reads and each trim on to the keeper, and the clock that is the join's own, the stall from its demand's last picture. A release or a + * failure drops it, which gives its place up, aborts its signal and stops its clock: it hears nothing more and its wait on the tier's start ends. A later + * join is a hold of its own, and nothing of an earlier one reaches it. + */ +class KeptHold implements BufferPlace, TierHolder { + hold?: TierHold + // Whether the hold's demand has handed it a picture, which starts the stall clock and lets a reconnect hold the tier. + running = false + stallTimer?: ReturnType + private readonly buffer: TierBuffer + private readonly routes: KeptHoldRoutes + private readonly controller = new AbortController() + + constructor(buffer: TierBuffer, routes: KeptHoldRoutes) { + this.buffer = buffer + this.routes = routes + } + + // Aborts once the hold is dropped. + get signal(): AbortSignal { + return this.controller.signal + } + + get dropped(): boolean { + return this.controller.signal.aborted + } + + taken(sample: BufferedSample): void { + this.routes.taken(sample) + } + + trimmed(sentence: string): void { + this.routes.trimmed(sentence) + } + + // A throw from one of the place's own calls took it off the buffer, which the keeper treats as its tier's failure, told as the library's own and ending + // a hold still kept. + displaced(): void { + if (!this.dropped) { + this.routes.displaced() + } + } + + // The route of a failed tier, which ends a hold still kept. + tierFailed(): void { + if (!this.dropped) { + this.routes.failed() + } + } + + drop(): void { + this.controller.abort() + clearTimeout(this.stallTimer) + this.buffer.givePlaceUp(this) + } + + // Drops the hold and releases its join, leaving its demand to end with its last join. + release(): void { + this.drop() + this.hold?.release() + } +} + +/** + * The library's own hold of one video tier, the one keeper of its tier, kept for as long as any of its reasons stands: raised for its first reason, it + * joins the tier through the table with no consumer, with a holder that carries no connection, which raises the tier's demand and calls + * `tierDemandStarted` when the tier has none, and reads its clocks from a place of its own in the tier's buffer, which holds no keyframe; released from + * its last, it leaves the demand, which ends with its last join as any demand does, and every clock it runs stops. The tier's buffer spans the prebuffer + * while the recording reason stands and nothing otherwise, the head moving at once as the span falls, whatever other reason holds the tier. A closed + * keeper takes no reason, and once the reasons that stood are released it holds nothing, whatever is raised after. + * + * A start still pending is waited on as the engine's joins wait, with no bound of the keeper's own: the start's own bound, `DELEGATE_CALL_TIMEOUT` counted + * once from its call whoever joined it, withdraws a start that never settles, the hold among the joins it refuses, and a join onto a demand whose start is + * pending already is refused at that bound and not at one counted from the join. The wait reads a signal the hold's drop aborts. An answer read after a + * release does nothing: a release while the start is pending is no failure, and neither is the withdrawal of the hold's own demand that a reset or a + * removal makes through the table. + * + * The keeper's clocks read pictures alone, a sound moving none of them on, and none runs while the hold's demand has handed it no picture: the demand + * holds its own stream to its first-sample bound and its gaps, whoever holds it, and ends a stream that misses them, the keeper ending none. Once the + * hold runs, its stall counts from its demand's last picture, and a stall opens an outage. The long-gap time from the last picture the keeper read tells + * an open recording of the gap, whatever the demand does meanwhile, and the keeper reads each picture ahead of its demand, which is why at the deadline + * they share it tells of the gap before the demand ends. A source stated reconnecting stops a running hold's stall clock and moves the gap to the + * recovering gap time, once, until the next picture sets each clock back: a reconnect within that time raises no problem. A failure, the stream's own, a + * silence its demand ends it for, the reader's refusal, a start refused or cut at its bound, or a throw from its place's own call, opens an outage, drops + * the hold and asks again, the failed join released in a later turn than the failure's route. Neither empties the tier's buffer, which viewers read too: + * the buffer empties as its demand leaves the tier. Its place raises one `buffer-trimmed` for each episode of trims of the tier's buffer, and a tier no + * keeper holds raises none. + * + * An outage ends at the tier's next picture and raises at most one `tier-stalled` and one `tier-failed`, and one `tier-resumed` as it ends: a camera + * that stays down is told of once however many asks it takes, as its demands tell its silence once. Each ask is a fresh join after a wait that doubles + * from a second to its longest and stays there, and the waits start over once the tier hands over a keyframe. An ask that finds the tier's demand failed + * while other holders keep it releases its join, waits for that demand to leave the tier, its registrations released first and not awaited, and joins + * again, with no problem and no wait doubled. A release ends an outage with no problem, cancels every timer, and arms no ask, a wait for a failed + * demand's end among them. + */ +export class TierKeeper implements Disposable { + private readonly options: TierKeeperOptions + // The reasons that stand, and whether the keeper is closed, which takes no reason more. + private readonly reasons = new Set() + private closed = false + // What the keeper holds while it is raised: the tier and the table it joins through. + private target?: { readonly table: TierTable, readonly tier: Tier } + private held?: KeptHold + private askTimer?: ReturnType + private gapTimer?: ReturnType + // Whether the long-gap clock is moved to the recovering gap time, which the next picture, the gap's telling and a release each set back. + private gapMoved = false + private wait = FIRST_WAIT + // The open outage, with whether it has raised its stall's problem and its failure's. + private outage?: { stalled: boolean, failed: boolean } + + /** + * Makes a keeper, which holds nothing until it is raised. + * @param options - The keeper's options. + */ + constructor(options: TierKeeperOptions) { + this.options = options + } + + /** + * Adds a reason to hold the tier and raises the hold, which a raise while it is raised leaves as it stands but for the span. A raise whose lookup finds + * no such tier holds nothing and leaves the keeper unraised, and a closed keeper takes no reason. + * @param reason - The reason added. + */ + raise(reason: TierKeeperReason): void { + if (this.closed) { + return + } + + this.reasons.add(reason) + + if (this.target !== undefined) { + this.target.tier.buffer.span = this.span + return + } + + const { sensorUUID, tierId, tierTable } = this.options + const table = tierTable(sensorUUID) + const tier = table?.videoTiers.get(tierId) + + if ((table === undefined) || (tier === undefined)) { + return + } + + this.target = { table, tier } + tier.buffer.span = this.span + this.join() + } + + /** + * Removes a reason to hold the tier, and releases the hold once no reason stands, doing nothing while it is not raised: every clock and a pending ask + * stop, an open outage ends with no problem, the span of the tier's buffer falls to nothing at once, and the hold's join leaves the tier's demand, whose end + * empties the buffer. While another reason stands the hold stays, the span falling to nothing at once with the recording reason. + * @param reason - The reason removed. + */ + release(reason: TierKeeperReason): void { + this.reasons.delete(reason) + + if ((this.target !== undefined) && (this.reasons.size > 0)) { + this.target.tier.buffer.span = this.span + return + } + + this.releaseHold() + } + + /** + * Closes the keeper, and no later raise adds a reason, while the reasons that stand keep the hold until each is released. + */ + close(): void { + this.closed = true + } + + /** + * Holds a running tier through its source's reconnect: on a hold whose demand runs, the hold's stall clock stops and the keeper's long-gap clock moves to + * the recovering gap time from the call, once. A hold not yet running, no hold, or a long-gap clock already moved does nothing. A repeat cannot stretch + * the wait. The next picture the keeper reads arms the stall clock afresh and sets the long-gap clock back to the long-gap time from that picture, and at + * the moved clock's end an open recording is told of the gap, the tier's demand, its own clock moved by the same statement, ending in that same moment. + * A loss during the wait is told and asked for again as any loss is, and the moved clock runs on: an open recording is told of the gap at its end unless + * a picture comes first. + */ + sourceRecovering(): void { + const { held } = this + + if ((held?.running !== true) || this.gapMoved) { + return + } + + clearTimeout(held.stallTimer) + held.stallTimer = undefined + clearTimeout(this.gapTimer) + this.gapTimer = setTimeout(() => this.lapsed(), RECOVERING_GAP_TIME).unref() + this.gapMoved = true + } + + /** + * Closes the keeper, removes every reason and releases the hold. Safe to call more than once. + */ + [Symbol.dispose](): void { + this.close() + this.reasons.clear() + this.releaseHold() + } + + // The span of the tier's buffer: the prebuffer while the recording reason stands, and nothing otherwise. + private get span(): number { + return this.reasons.has('recording') + ? this.options.prebuffer + : 0 + } + + // Releases the hold, and does nothing while it is not raised. + private releaseHold(): void { + if (this.target === undefined) { + return + } + + const { tier } = this.target + + this.target = undefined + clearTimeout(this.askTimer) + clearTimeout(this.gapTimer) + this.askTimer = undefined + this.gapTimer = undefined + this.gapMoved = false + this.wait = FIRST_WAIT + this.outage = undefined + tier.buffer.span = 0 + this.held?.release() + this.held = undefined + } + + // The tier's name in the keeper's problems. + private get tierName(): string { + const { sensorUUID, tierId } = this.options + + return `the video tier ${tierId} of the video sensor "${sensorUUID}"` + } + + /* Joins the tier with a hold of its own, its place in the tier's buffer taken first, which is why it reads a sample the plugin writes inside the start of a demand + * the join raises. Plugin code runs inside the join, and a stream it fails there has dropped the hold already. A started demand is left to its own + * bounds. A demand found failed that other holders keep, a silence's or any other failure's, is one the keeper has told of already: it gives its place up + * and releases its own join at once, since the demand ends only as its last hold releases, and joins again once the demand has left the tier, with no + * problem and no wait doubled. A failed demand no other holder keeps, one whose start is still pending, is lost as any failure is. + */ + private join(): void { + const { table, tier } = this.target! + const held = new KeptHold(tier.buffer, { + displaced: () => this.lost(held, `The library's own reading of the camera buffer failed and ended its hold of the stream of ${this.tierName}`), + failed: () => this.lost(held, `The stream of ${this.tierName}, which the library holds, failed`), + taken: sample => this.taken(held, sample), + trimmed: sentence => this.problem('buffer-trimmed', sentence), + }) + + this.held = held + tier.buffer.takePlace(held) + + const hold = held.hold = table.hold(tier, held) + + if (held.dropped) { + hold.release() + return + } + + if (hold.started) { + return + } + + if (hold.waiting) { + void this.awaitStart(held, hold).catch((error: unknown) => { + this.waitFailed(`The library failed to wait on the start of ${this.tierName} it holds`, error) + }) + } else if (hold.shared) { + tier.buffer.givePlaceUp(held) + hold.release() + void this.awaitEnd(held, hold).catch((error: unknown) => { + this.waitFailed(`The library failed to wait on the end of the failed stream of ${this.tierName} it holds`, error) + }) + } else { + this.lost(held, `The stream of ${this.tierName}, which the library holds, had failed when the library joined it`) + } + } + + // Waits for a failed demand to leave the tier within the hold's signal, which is why a release while it waits ends the wait and arms nothing. The keeper joins again + // once the demand has left the tier. + private async awaitEnd(held: KeptHold, hold: TierHold): Promise { + await settleWithin(hold.ended(), held.signal) + + if (!held.dropped) { + this.join() + } + } + + /* Waits on the tier's start within the hold's signal alone, since the start's own bound withdraws a start that never settles and refuses every join + * waiting on it. A hold dropped while it waited is left as it stands. A release, and the withdrawal a reset makes beside it, act on nothing here. The + * hold's answer is branched on: started leaves the hold to its demand's bounds, cut, a start its bound withdrew, loses the hold as a start that did not + * settle, beside the demand's one plugin-failure problem, and refused, a refused start, a failed stream or a withdrawal, loses the hold as refused. + */ + private async awaitStart(held: KeptHold, hold: TierHold): Promise { + const answer = (await settleWithin(hold.answer(), held.signal))?.value + + if (held.dropped || (answer === 'started')) { + return + } + + if (answer === 'cut') { + this.lost(held, `The start of the stream of ${this.tierName}, which the library holds, did not settle within ${DELEGATE_CALL_TIMEOUT / 1000} seconds`) + + return + } + + this.lost(held, `The start of the stream of ${this.tierName}, which the library holds, was refused`) + } + + /* Reads each picture the tier's buffer read, through the hold's place, a sound moving nothing on: the hold runs from its first, the stall and the gap + * each count again from this one, the waits start over at a keyframe, and an open outage ends. Each clock is made once and moved on at each picture + * after, but a long-gap clock moved to the recovering gap time, which is made again at the long-gap time, since a refresh keeps a timer's own duration. + */ + private taken(held: KeptHold, sample: BufferedSample): void { + if (sample.track.medium !== 'video') { + return + } + + held.running = true + + if (held.stallTimer === undefined) { + held.stallTimer = setTimeout(() => this.stalled(held), STALL_TIME).unref() + } else { + held.stallTimer.refresh() + } + + if ((this.gapTimer === undefined) || this.gapMoved) { + clearTimeout(this.gapTimer) + this.gapTimer = setTimeout(() => this.lapsed(), LONG_GAP_TIME).unref() + this.gapMoved = false + } else { + this.gapTimer.refresh() + } + + if (sample.sync) { + this.wait = FIRST_WAIT + } + + if (this.outage !== undefined) { + this.outage = undefined + this.problem('tier-resumed', `The stream of ${this.tierName}, which the library holds, hands over its pictures again.`) + } + } + + // A running stream with no picture for the stall time opens an outage, which raises its one `tier-stalled` problem. The stall's clock moves on again at + // the next picture. + private stalled(held: KeptHold): void { + held.stallTimer = undefined + this.outage ??= { failed: false, stalled: false } + + if (!this.outage.stalled) { + this.outage.stalled = true + this.problem('tier-stalled', `The stream of ${this.tierName}, which the library holds, handed over no picture for ${STALL_TIME / 1000} seconds.`) + } + } + + /* The long-gap time, or the recovering gap time it was moved to, passed since the last picture the keeper read: an open recording is told of the gap, + * and nothing more. The demand holds its own stream to its bounds and ends one that misses them, which reaches the keeper through its hold's route as + * any failure does: at a gap the keeper's clock and the demand's count from the same picture, the keeper's read first, which is why the gap is told + * before the demand ends. + */ + private lapsed(): void { + this.gapTimer = undefined + this.gapMoved = false + this.options.gap?.() + } + + /* A kept hold whose tier failed or was refused is dropped, giving its place up, the outage it opens or holds raises its one `tier-failed` problem, and the tier is + * asked for again. The tier's buffer is left to its demand, which empties it as it leaves the tier. The join is released in a later turn, since a failed + * tier's route runs inside the stream's own failure. + */ + private lost(held: KeptHold, failure: string): void { + held.drop() + this.held = undefined + queueMicrotask(() => held.release()) + this.outage ??= { failed: false, stalled: false } + + if (!this.outage.failed) { + this.outage.failed = true + this.problem('tier-failed', `${failure}, and the library asks for it again.`) + } + + this.ask() + } + + // Asks for the tier again once the wait passes, the next wait twice this one up to the longest. + private ask(): void { + const { wait } = this + + this.wait = Math.min(wait * 2, LONGEST_WAIT) + this.askTimer = setTimeout(() => { + this.askTimer = undefined + this.join() + }, wait).unref() + } + + // Raises a problem of the held tier on the camera's channel, at the level the console warns at where nothing subscribes. + private problem(kind: Extract, sentence: string): void { + const { reporter, sensorUUID, tierId } = this.options + + reporter.problem({ + kind, + level: 'warning', + sensorUUID, + sentence, + tierId, + }) + } + + // Reports a wait of the keeper's own that failed as the library's failure on the held tier, its sentence followed by the thrown value as it renders. + private waitFailed(failure: string, error: unknown): void { + const { reporter, sensorUUID, tierId } = this.options + + reporter.failure('library-failure', failure, error, { sensorUUID, tierId }) + } +} diff --git a/src/lib/camera/index.ts b/src/lib/camera/index.ts index 133e28961..524f980d9 100644 --- a/src/lib/camera/index.ts +++ b/src/lib/camera/index.ts @@ -7,6 +7,7 @@ export * from './RTPProxy.js' export * from './RTPStreamManagement.js' export type { CameraAudioTier, + CameraKeyframe, CameraVideoSensor, CameraVideoTier, MultiTierStreamingDelegate, From 70e2b26e8fc50d302d44075750f8087273474066 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:50 -0600 Subject: [PATCH 13/16] feat(camera): stream live views at home through each video sensor's multi-tier RTP stream management, with its talkback --- src/lib/camera/MultiTierStreamManagement.ts | 1386 +++++++++++++++++ src/lib/camera/index.ts | 1 + .../camera/session/SessionTalkback.spec.ts | 569 +++++++ src/lib/camera/session/SessionTalkback.ts | 220 +++ .../camera/session/StreamingEnabledSwitch.ts | 101 ++ src/lib/controller/CameraController.ts | 32 + src/test-utils/talkbackSink.ts | 39 + 7 files changed, 2348 insertions(+) create mode 100644 src/lib/camera/MultiTierStreamManagement.ts create mode 100644 src/lib/camera/session/SessionTalkback.spec.ts create mode 100644 src/lib/camera/session/SessionTalkback.ts create mode 100644 src/lib/camera/session/StreamingEnabledSwitch.ts create mode 100644 src/test-utils/talkbackSink.ts diff --git a/src/lib/camera/MultiTierStreamManagement.ts b/src/lib/camera/MultiTierStreamManagement.ts new file mode 100644 index 000000000..31fe4ef34 --- /dev/null +++ b/src/lib/camera/MultiTierStreamManagement.ts @@ -0,0 +1,1386 @@ +import type { Socket, SocketType } from 'node:dgram' + +import type { CameraLiveView, ControllerServiceMap, StateChangeDelegate } from '../controller/index.js' +import type { CameraMultiTierRTPStreamManagement } from '../definitions/index.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { RTPStreamingControlRequest, RTPStreamingControlResponse } from './capabilities/rtpStreaming.js' +import type { SetupEndpointsRequest, SetupEndpointsResponse } from './capabilities/setupEndpoints.js' +import type { CameraReporter, DebugWriter } from './diagnostics/CameraReporter.js' +import type { OperatingModePolicy, StreamingEnabledChange } from './OperatingModePolicy.js' +import type { MultiTierStreamingDelegate, StreamTierMedium, TalkbackSink, Talker } from './StreamingOptions.js' +import type { Tier, TierHold, TierHolder, TierTable } from './TierTable.js' + +import { Buffer } from 'node:buffer' +import crypto from 'node:crypto' +import dgram from 'node:dgram' + +import { Characteristic } from '../Characteristic.js' +import { HAPStatus } from '../HAPServer.js' +import { Service } from '../Service.js' +import { AsyncDisposableStack } from '../util/asyncDisposableStack.js' +import { nounFor } from '../util/counted.js' +import { DisposableStack } from '../util/disposableStack.js' +import { errorMessage } from '../util/errors.js' +import { HapStatusError } from '../util/hapStatusError.js' +import { ntpTime } from '../util/ntp.js' +import * as uuid from '../util/uuid.js' +import { decodeRTPStreamingControlRequest, encodeRTPStreamingControlResponse, RTPStreamingCommand, RTPStreamingStatus } from './capabilities/rtpStreaming.js' +import { + decodeSetupEndpointsRequest, + encodeSetupEndpointsResponse, + SETUP_ENDPOINTS_ERROR, + SetupEndpointsStatus, + SRTPCryptoSuites, +} from './capabilities/setupEndpoints.js' +import { encodeSupportedAudioStreamTiers, encodeSupportedVideoStreamTiers } from './capabilities/streamTiers.js' +import { encodeSupportedRTPConfiguration } from './capabilities/supportedRtpConfiguration.js' +import { reconcileSensorServices, sensorServiceKey } from './capabilityKeys.js' +import { debugChannel } from './diagnostics/debugChannels.js' +import { firstSequence, nextSequence, RTP_HEADER_LENGTH, wireTimestamp } from './rtp/packetRules.js' +import { CLOCK_RATES } from './rtp/RTPClock.js' +import { CommandQueue } from './session/CommandQueue.js' +import { ConnectionSessions } from './session/ConnectionSessions.js' +import { wireControlPoint } from './session/controlPoint.js' +import { SessionTalkback } from './session/SessionTalkback.js' +import { settleWithin } from './session/settleWithin.js' +import { StreamingEnabledSwitch } from './session/StreamingEnabledSwitch.js' +import { PLAIN_PACKET_LIMIT, SRTPContext } from './srtp/SRTPContext.js' + +const MULTI_TIER_DEBUG = debugChannel('HAP-NodeJS:Camera:MultiTier') + +// The reason the exit's debug event gives a session endSession ends, alone or among every session the service ends at once. +const ENDED_BY_OWNER = 'its owner ended it' + +/* A prepared session nobody starts within this bound ends. A hub prepares again whenever its tile asks again. An abandoned preparation is routine, and a + * hub's connection, whose close would otherwise end the session, can live for days while the session holds one of the service's slots. + */ +const PREPARE_TIMEOUT = 60 * 1000 + +// RFC 3550 6.2's minimum interval between sender reports, and the delay of the first report, half of it. +const REPORT_INTERVAL = 5 * 1000 +const FIRST_REPORT_DELAY = REPORT_INTERVAL / 2 + +// RFC 3550 A.7 divides each randomized report interval by e - 3/2, which compensates for the timer reconsideration that would otherwise lower the rate. +const REPORT_COMPENSATION = Math.E - 1.5 + +// RFC 3550 6.3.5 counts a participant gone once it has sent nothing for five reporting intervals at the minimum interval. +const LIVENESS_WINDOW = 5 * REPORT_INTERVAL + +// AES_CM_128_HMAC_SHA1_80's master key and salt, which the accessory generates for each medium of each session. +const SRTP_MASTER_KEY_LENGTH = 16 +const SRTP_MASTER_SALT_LENGTH = 14 + +// The SRTP tag each pooled buffer leaves room for after its packet, and the index and tag SRTCP appends. +const SRTP_TAG_LENGTH = 10 +const SRTCP_TRAILER_LENGTH = 14 + +/* The buffers each sender pools at first, sized for a keyframe burst at the highest tier delivered in one turn for video and a few frames for audio, and the + * most its pool grows to. A send that finds every buffer in flight adds as many buffers again as the pool holds, up to its medium's ceiling. A burst + * larger than the pool is sent whole, and a pool never shrinks: each growth is allocated once and kept. + */ +const POOL_SIZES: Readonly> = { audio: 16, video: 256 } +const POOL_CEILINGS: Readonly> = { audio: 128, video: 2048 } + +// The two media every session carries, one socket each, in the order their sockets bind. +const MEDIA: readonly StreamTierMedium[] = ['video', 'audio'] + +// The medium a view at home joins its own tier for where it takes its sound from the sensor's sound tier, and the medium it joins that tier for. +const PICTURE: readonly StreamTierMedium[] = ['video'] +const SOUND: readonly StreamTierMedium[] = ['audio'] + +// RFC 5761 4 tells RTCP from RTP on a multiplexed port by the second octet: from 192 to 223 it is RTCP. +const RTCP_SECOND_OCTET_MINIMUM = 192 +const RTCP_SECOND_OCTET_MAXIMUM = 223 + +// The payload type below the marker bit in the second octet of RFC 3550 5.1's fixed RTP header, whose octets 2 and 3 carry the sequence number and +// octets 8 to 11 the SSRC. +const RTP_PAYLOAD_TYPE_MASK = 0x7F +const SEQUENCE_OFFSET = 2 + +// RFC 3550 6.4.1's sender report, header to octet count, and RFC 4585 6.1's payload-specific feedback with the formats asking for a keyframe: the picture +// loss indication (RFC 4585 6.3.1) and the full intra request (RFC 5104 4.3.1). +const SENDER_REPORT = 200 +const SENDER_REPORT_LENGTH = 28 +const PAYLOAD_SPECIFIC_FEEDBACK = 206 +const KEYFRAME_FORMATS: ReadonlySet = new Set([1, 4]) + +// The one suite the multi-tier service supports (the HomeKit Secure Video compatibility guide, section 3.6), as Supported RTP Configuration advertises it. +const SUPPORTED_RTP_CONFIGURATION = encodeSupportedRTPConfiguration([SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80]) + +/** + * The options of a {@link MultiTierStreamManagement}, one per video sensor. The camera controller validates the camera's streaming options before it builds + * one, which is why the options reach the class already coherent. + */ +export interface MultiTierStreamManagementOptions { + /** + * The camera's delegate, which starts each session's talkback. The table reports each tier's demand to the same delegate. + */ + delegate: MultiTierStreamingDelegate + /** + * The video sensor's tier table, which the camera controller builds for the sensor: its stream tiers, which the service advertises and its key names, + * each video tier's demand, which reads the tier's stream, times its picture and its sound on the sensor's one clock and cuts them into the packets each + * joined session sends, and answers a viewer's keyframe request from the tier's buffer. + */ + table: TierTable + /** + * The most sessions the service holds at once, prepared or streaming, as the camera's streaming options defaulted and validated it. + */ + maxSessions: number + /** + * Called once for each session whose view started, as its disposal opens, in the exit's own turn. + */ + onLiveViewEnded?: (view: CameraLiveView) => void + /** + * Called once for each session whose Start is answered with success, as it is answered. + */ + onLiveViewStarted?: (view: CameraLiveView) => void + /** + * Called once for each change of the service's Streaming Enabled, before the state-change delegate. + */ + onStreamingEnabledChange?: (change: StreamingEnabledChange) => void + /** + * The camera's reporter, through which each session's talkback reports a failure of the plugin's sink, of its start or of what the plugin registered on + * the talker. + */ + reporter: CameraReporter + /** + * Whether the camera's Speaker is muted, read as it stands at each talkback datagram a session takes: a muted Speaker has every session drop its + * controller's talkback after the datagram is unprotected, which keeps the session's SRTP index in step with the controller's through a mute, and a sink + * a session started stays started, written nothing until the Speaker is unmuted. + */ + speakerMuted: () => boolean +} + +/** + * The persisted state of one video sensor's Camera Multi-Tier RTP Stream Management service. + */ +export interface MultiTierStreamManagementState { + /** + * The value of Streaming Enabled. + */ + streamingEnabled: boolean +} + +type SessionState = 'prepared' | 'streaming' + +// What a session's talkback and its view's end reach in the management that registered it, beside the session table. A keyframe request goes to the hold +// the session's Start joined its tier with, which the session keeps, and the context carries no route for it. +interface MultiTierSessionContext { + // The audio tier's payload type, which a controller's talkback carries, the delegate's talkbackStarted, which takes the talker, answering undefined for a + // delegate without it, the reader of whether the camera's Speaker is muted, and the camera's reporter, which each session's talkback reports through. + readonly audioPayloadType: number + readonly talkbackStarted: (talker: Talker) => TalkbackSink | undefined + readonly speakerMuted: () => boolean + readonly reporter: CameraReporter + // The video sensor the sessions view, in lowercase, and the hook a streaming session's disposal tells of its view's end through. + readonly sensorUUID: string + readonly liveViewEnded?: (view: CameraLiveView) => void +} + +// One medium of a session: its socket, connected to the controller, the context protecting what the accessory sends, the context unprotecting what the +// controller sends, its RTCP and on the audio socket its talkback, the SSRC the accessory answered, and the sender a successful Start joined to the +// medium's tier, which its sender reports read until the session leaves. +interface SessionMedium { + readonly socket: Socket + readonly outbound: SRTPContext + readonly inbound: SRTPContext + readonly ssrc: number + sender?: TierSender +} + +// A Start's join of its video tier: its hold, and the sender the join made for each of the session's media. +interface SessionHold { + readonly hold: TierHold + readonly senders: Readonly> +} + +type MasterKeyAndSalt = Pick + +// Walks a compound RTCP packet (RFC 3550 6.1), answering whether any of its packets asks for a keyframe, or undefined for one whose lengths do not tile it. +function asksForKeyframe(packet: Buffer, length: number): boolean | undefined { + let keyframe = false + + for (let offset = 0; offset < length;) { + if (length - offset < 4 || packet[offset] >> 6 !== 2) { + return undefined + } + + const end = offset + (packet.readUInt16BE(offset + 2) + 1) * 4 + + if (end > length) { + return undefined + } + + if (packet[offset + 1] === PAYLOAD_SPECIFIC_FEEDBACK && KEYFRAME_FORMATS.has(packet[offset] & 0x1F)) { + keyframe = true + } + + offset = end + } + + return keyframe +} + +// The accessory's own master key and salt for one medium of a session, fresh from the system's random source. +function masterKeyAndSalt(): MasterKeyAndSalt { + return { + masterKey: crypto.randomBytes(SRTP_MASTER_KEY_LENGTH), + masterSalt: crypto.randomBytes(SRTP_MASTER_SALT_LENGTH), + } +} + +// A report interval drawn as RFC 3550 6.2 and A.7 draw one at the minimum interval: uniformly from half to one and a half times it, then compensated. +function reportInterval(): number { + return REPORT_INTERVAL * (0.5 + Math.random()) / REPORT_COMPENSATION +} + +// Binds a socket at port 0 on its family's wildcard. The bind's own error listener answers a failure, as RTPProxy's does, and either way the socket then +// carries the session's listener, because a dgram socket without one ends the process at its first error. +async function bind(socket: Socket, address: string, listener: (error: Error) => void): Promise { + return new Promise((resolve) => { + const failed = (): void => { + socket.on('error', listener) + resolve(false) + } + + socket.once('error', failed) + socket.bind(0, address, () => { + socket.removeListener('error', failed) + socket.on('error', listener) + resolve(true) + }) + }) +} + +// Connects a socket to the controller's port, and every datagram from another source is dropped and no send looks up an address. +async function connect(socket: Socket, port: number, address: string): Promise { + return new Promise((resolve) => { + socket.connect(port, address, (error?: Error) => resolve(!error)) + }) +} + +async function close(socket: Socket): Promise { + return new Promise((resolve) => { + socket.close(() => resolve()) + }) +} + +/* One session's sending half for one medium while the session is joined to a tier. Its pool of preallocated buffers, a ring, carries the packets in + * flight: a send takes the next buffer, copies the packet in, rewrites its payload type and SSRC and writes its own sequence number, numbering the packets + * it sends from a random start of its own, which means one session's opening shows no other session a gap. The send protects the packet in place and sends a view of it + * with the one completion callback the sender keeps. Sends complete in the order they were made: each completion frees the oldest buffer. A send that finds + * every buffer in flight grows the pool first, up to its ceiling, and one that finds a pool at its ceiling in flight refuses the packet, which the tier's + * stream counts as dropped and which takes the next sequence number all the same. The session's numbering carries the gap its viewer reads as a loss + * while every other session's own numbering runs on unbroken. The sender answers the room its ceiling leaves, which a view's opening is handed no more + * than in a turn, and its ceiling as its capacity, past which a frame of an opening is sent at once as a live release sends it. It reports from its first + * packet on, since an opening's timestamps stand past every timestamp its tier has sent and run at no more than the live edge: each packet's timestamp + * is a live one a report can map the clock to. + */ +class TierSender { + readonly session: MultiTierSession + packets = 0 + octets = 0 + private readonly medium: SessionMedium + private readonly payloadType: number + private readonly clockRate: number + private readonly slotLength: number + private readonly ceiling: number + private readonly slots: Buffer[] + private oldest = 0 + private inFlight = 0 + private sequence = firstSequence() + private lastTimestamp = 0 + private lastSendTime = 0 + + constructor(session: MultiTierSession, medium: SessionMedium, payloadType: number, clockRate: number, packetSize: number, poolSize: number, ceiling: number) { + this.session = session + this.medium = medium + this.payloadType = payloadType + this.clockRate = clockRate + this.slotLength = packetSize + SRTP_TAG_LENGTH + this.ceiling = ceiling + this.slots = this.allocate(poolSize) + } + + // The packets the sender can still take before a send meets its pool at its ceiling with every buffer in flight. + get free(): number { + return this.ceiling - this.inFlight + } + + // The packets the sender takes with nothing in flight, its pool's ceiling. + get capacity(): number { + return this.ceiling + } + + // Sends one plain RTP packet, answering whether a buffer was free for it. + send(packet: Buffer, octets: number, now: number): boolean { + const slots = this.slots + + if (this.inFlight === slots.length) { + if (slots.length === this.ceiling) { + this.sequence = nextSequence(this.sequence) + + return false + } + + this.grow(Math.min(slots.length, this.ceiling - slots.length)) + } + + const slot = slots[(this.oldest + this.inFlight) % slots.length] + packet.copy(slot, 0) + slot[1] = (slot[1] & 0x80) | this.payloadType + slot.writeUInt16BE(this.sequence, SEQUENCE_OFFSET) + slot.writeUInt32BE(this.medium.ssrc, 8) + this.sequence = nextSequence(this.sequence) + + const length = this.medium.outbound.protect(slot.subarray(0, packet.length), slot) + this.inFlight++ + this.medium.socket.send(slot.subarray(0, length), this.sent) + + this.packets++ + this.octets += octets + this.lastTimestamp = packet.readUInt32BE(4) + this.lastSendTime = now + + return true + } + + /* Sends a sender report (RFC 3550 6.4.1) once the medium has sent a packet: its SSRC, the NTP time of the report, the last packet's RTP timestamp + * advanced by the steady time since it was sent, and the packet and octet counts. The NTP time is written as one 64-bit value modulo 2^64, which means its seconds + * wrap on 2036-02-07 (the RFC 5905 era). Each 32-bit word after it is written modulo 2^32, as the RTP timestamp and both counts wrap under RFC 3550. + */ + report(moment: number, ntp: bigint): void { + if (this.packets === 0) { + return + } + + const report = Buffer.alloc(SENDER_REPORT_LENGTH) + report[0] = 0x80 + report[1] = SENDER_REPORT + report.writeUInt16BE(SENDER_REPORT_LENGTH / 4 - 1, 2) + report.writeUInt32BE(this.medium.ssrc, 4) + report.writeBigUInt64BE(BigInt.asUintN(64, ntp), 8) + report.writeUInt32BE(wireTimestamp(this.lastTimestamp + Math.round((moment - this.lastSendTime) * this.clockRate / 1000)), 16) + report.writeUInt32BE(this.packets >>> 0, 20) + report.writeUInt32BE(this.octets >>> 0, 24) + + const output = Buffer.alloc(SENDER_REPORT_LENGTH + SRTCP_TRAILER_LENGTH) + this.medium.socket.send(output.subarray(0, this.medium.outbound.protectRTCP(report, output))) + } + + // Allocates buffers for the pool in one allocation, each a view of its own stretch, as long as the largest packet and its tag. + private allocate(count: number): Buffer[] { + const pool = Buffer.alloc(count * this.slotLength) + + return Array.from({ length: count }, (_slot, index) => pool.subarray(index * this.slotLength, (index + 1) * this.slotLength)) + } + + /* Adds buffers to a pool whose every buffer is in flight. They go in at the oldest buffer's place in the ring and the oldest moves past them. The ring + * runs from the oldest buffer in flight through the newest and then into the added ones: every buffer in flight keeps its bytes, the sends still complete + * in the order they were made, and the next send takes the first added buffer. + */ + private grow(count: number): void { + this.slots.splice(this.oldest, 0, ...this.allocate(count)) + this.oldest += count + } + + // Each completion frees the oldest buffer, and one that reports an error, as a platform's send can for a controller that has gone, is counted on the + // session, which streams on until its connection closes, its RTCP falls silent or its tier fails, a silence of the tier's pictures among the failures. + private readonly sent = (error: Error | null): void => { + this.oldest = (this.oldest + 1) % this.slots.length + this.inFlight-- + + if (error) { + this.session.sendFailed(error) + } + } +} + +/* The holder of a view at home's sound where the view takes it from the sensor's sound tier rather than from the tier of its picture: a holder of its own, + * which is why that tier's failure, a silence of its pictures among them, and a throw from the view's sound sender end the view's sound alone and never + * the view, which goes on silent. Its route releases its hold in a microtask of its own, as the keeper's does, since the route runs inside the stream's + * failure and a failed demand ends only as its last hold releases. The failed tier is left to its other holders rather than held by the view until it + * ends. A view whose sound is released this way is joined to no later demand of that tier. + */ +class SoundHolder implements TierHolder { + // The hold the view's sound joined the sound tier with, set as the join answers, which the route reads in its microtask, after the join has answered. + hold?: TierHold + + tierFailed(): void { + queueMicrotask(() => this.hold?.release()) + } +} + +/* A registered session: its identifier, the connection that opened it, its state, its two media, the talkback that writes its controller's talkback to the + * plugin's sink, and the stack every resource it holds stands on in the order it was acquired. Its disposal is the one exit routine every path that ends a + * session runs, through the session table's exit. It holds the tier of its picture itself, and of its sound where the two are one: a failed tier, and a + * throw from one of its senders as the tier's pacer releases a packet, reach it through its route, which is that exit. A sound it takes from the sensor's + * sound tier is held through a sound holder, whose route ends the sound alone. + */ +class MultiTierSession implements AsyncDisposable, TierHolder { + readonly sessionIdentifier: string + readonly connection: HAPConnection + state: SessionState = 'prepared' + readonly media: Readonly> + // The SSRCs the controller's Start names for its own streams, which its RTCP reports and its talkback carry. + controllerSSRCs?: Readonly> + private readonly stack = new AsyncDisposableStack() + private readonly sessions: ConnectionSessions + private readonly context: MultiTierSessionContext + private readonly controller = new AbortController() + // The work buffer each authenticated RTCP packet is unprotected into, allocated once. It is as long as the longest plain packet a context unprotects, + // which a controller's compound reports fit, and a datagram whose packet is longer is dropped. + private readonly rtcp = Buffer.alloc(PLAIN_PACKET_LIMIT) + // The session's talkback, which starts the sink at the first talkback packet that authenticates while the Speaker is unmuted and closes once the + // delegate declined talkback or the talkback ended, its talker's registrations released, and every later talkback datagram is dropped before any + // cryptography. + private readonly sessionTalkback: SessionTalkback + // The talkback datagrams the audio context refused, the first a debug event as it happens and the rest one event, as the session ends. A flood writes + // no event per packet. + private refusedTalkback = 0 + // The sends whose completion reported an error, on any of the session's media, the first a debug event as it happens and the rest one count as it ends. + private failedSends = 0 + + private videoTier = 0 + // The hold a successful Start joined the session's video tier with for its picture, which a keyframe request goes to until the session leaves. + private tierHold?: TierHold + private prepareTimer?: ReturnType + private reportTimer?: ReturnType + private livenessTimer?: ReturnType + + constructor( + sessionIdentifier: string, + connection: HAPConnection, + media: Record, + sessions: ConnectionSessions, + context: MultiTierSessionContext, + ) { + this.sessionIdentifier = sessionIdentifier + this.connection = connection + this.media = media + this.sessions = sessions + this.context = context + this.sessionTalkback = new SessionTalkback({ + defer: release => this.stack.defer(release), + ended: () => this.signal.aborted, + reporter: context.reporter, + sensorUUID: context.sensorUUID, + session: `multi-tier session ${sessionIdentifier}`, + sessionIdentifier, + start: context.talkbackStarted, + }) + } + + // The session takes over what its preparation acquired, the sockets and the contexts on one stack, once the session table holds it. + hold(acquired: AsyncDisposableStack): void { + this.stack.use(acquired.move()) + } + + /* Reaches a Start's own stack of joins from the session's, through the one registration the Start makes before its first join. A session that exits + * while its Start waits releases each join, and with it each sender, above its contexts and sockets, as a streaming session's exit does. A join that + * raises a demand runs plugin code that can end the session, whose disposal starts in that turn and refuses a registration made after it, which is why none is + * made then. The Start leaves the registration nothing to release as it ends, its own disposal emptying the stack, or as it streams, its move emptying + * it, and a retried Start holds nothing through an earlier one's registration. + */ + reach(joins: AsyncDisposableStack): void { + this.stack.use(joins) + } + + // Aborts when the session ends, which cuts a Start's wait for its demands. + get signal(): AbortSignal { + return this.controller.signal + } + + // The view a streaming session is, as the live-view events tell of it: at home, of the sensor, from the video tier its Start named. + get liveView(): CameraLiveView { + return { + sensorUUID: this.context.sensorUUID, + sessionIdentifier: this.sessionIdentifier, + tierId: this.videoTier, + where: 'home', + } + } + + armPrepareTimeout(): void { + this.prepareTimer = setTimeout(() => void this.exit('nobody started it within the prepare timeout'), PREPARE_TIMEOUT).unref() + this.stack.defer(() => clearTimeout(this.prepareTimer)) + } + + // The session's route for a failed tier: its exit, as for every other path that ends it. + tierFailed(): void { + void this.exit('its tier failed') + } + + // Counts one send whose completion reported an error, on any of the session's media, and writes a debug event of the session's first. A flood writes + // no event per packet. + sendFailed(error: Error): void { + if (++this.failedSends === 1) { + const { message } = error + + this.context.reporter.debug(MULTI_TIER_DEBUG, 'packet-send-failed', () => ({ + message, + sentence: `Multi-tier session ${this.sessionIdentifier} failed to send a packet: ${message}`, + sessionIdentifier: this.sessionIdentifier, + })) + } + } + + /* A successful Start moves its holds onto the session's stack, above the sockets and contexts its preparation put there: each tier releases the session + * before a context is zeroed or a socket closed. It stops the prepare timeout and starts the session's reading: each socket's datagrams read, and the + * sender reports scheduled, the timers' clears registered now so a report or the liveness window armed later registers nothing. The hold of the Start's + * picture, which a keyframe request goes to, is kept beside the senders, the picture's and the sound's, and as the session leaves each socket's listener + * is removed before the hold is cleared and the holds are released, which means no request reaches a released hold. + */ + stream(holds: AsyncDisposableStack, videoTier: number, joined: SessionHold, ssrcs: Record): void { + this.stack.use(holds.move()) + clearTimeout(this.prepareTimer) + this.state = 'streaming' + this.videoTier = videoTier + this.controllerSSRCs = ssrcs + this.tierHold = joined.hold + this.stack.defer(() => { + this.tierHold = undefined + }) + + for (const medium of MEDIA) { + const path = this.media[medium] + const listener = (datagram: Buffer): void => this.receive(medium, datagram) + + path.sender = joined.senders[medium] + path.socket.on('message', listener) + this.stack.defer(() => { + path.socket.removeListener('message', listener) + path.sender = undefined + }) + } + + this.stack.defer(() => { + clearTimeout(this.reportTimer) + clearTimeout(this.livenessTimer) + }) + + // The talkback and send counts are read as the session ends, after the talkback's end releases what its talker registered, which stands above this on + // the stack once a sink is taken. + this.stack.defer(() => { + const dropped = this.refusedTalkback - 1 + const unsent = this.failedSends - 1 + + if (dropped > 0) { + this.context.reporter.debug(MULTI_TIER_DEBUG, 'talkback-dropped', () => ({ + dropped, + sentence: `Multi-tier session ${this.sessionIdentifier} dropped ${dropped} more ${nounFor(dropped, 'talkback datagram')}.`, + sessionIdentifier: this.sessionIdentifier, + })) + } + + if (unsent > 0) { + this.context.reporter.debug(MULTI_TIER_DEBUG, 'packets-unsent', () => ({ + sentence: `Multi-tier session ${this.sessionIdentifier} failed to send ${unsent} more ${nounFor(unsent, 'packet')}.`, + sessionIdentifier: this.sessionIdentifier, + unsent, + })) + } + + this.sessionTalkback.logFailedWrites() + }) + this.scheduleReport(FIRST_REPORT_DELAY) + } + + // Ends the session through the session table's exit, for every path that ends it from outside the management's own commands. + async exit(reason: string): Promise { + await this.sessions.exit(this, reason) + } + + /* The exit's disposal. Its opening in the session table removes the session and releases its connection's held answers, and guards the rest: a close, an + * End, a timeout or an error arriving while the exit runs finds the session gone, and a disposal that finds nothing to remove has run already. The + * answers go first: a read during the teardown answers the empty value. A streaming session's view ends in the same turn, ahead of every await, which is why + * the end of a removal reaches the camera's listeners before the controller drops them. The stack then releases everything in reverse: the talkback's + * end, releasing what its talker registered, and the talkback and send counts, written as debug events, the timers, the report listeners and the + * senders, the holds, a streaming session's or a waiting Start's, a demand ending with its last join, the contexts, zeroed, and the sockets, closed. + */ + async [Symbol.asyncDispose](): Promise { + if (!this.sessions.beginDisposal(this)) { + return + } + + this.controller.abort() + + if (this.state === 'streaming') { + this.context.liveViewEnded?.(this.liveView) + } + + await this.stack.disposeAsync() + } + + /* Reads one datagram from the controller, RTCP and RTP told apart by RFC 5761 4. Every authenticated RTCP packet arms or restarts the liveness window, + * whatever it carries, and a picture loss indication or a full intra request on the video socket goes to the session's hold on its picture's tier, whose + * demand answers it for this session alone, from the camera buffer where it keeps a keyframe released, and writes one debug event with what it came to, a + * session whose hold has gone reading as stopped. RTP on the audio socket is the controller's talkback, which goes to its own method and never touches + * the liveness window, and RTP on the video socket is dropped. + */ + private receive(medium: StreamTierMedium, datagram: Buffer): void { + if (datagram.length < 2) { + return + } + + if (datagram[1] < RTCP_SECOND_OCTET_MINIMUM || datagram[1] > RTCP_SECOND_OCTET_MAXIMUM) { + if (medium === 'audio') { + this.talkback(datagram) + } + + return + } + + if (datagram.length - SRTCP_TRAILER_LENGTH > this.rtcp.length) { + const { length } = datagram + + this.context.reporter.debug(MULTI_TIER_DEBUG, 'rtcp-too-long', () => ({ + length, + medium, + sentence: `Multi-tier session ${this.sessionIdentifier} drops a ${medium} RTCP datagram of ${length} octets, longer than it reads.`, + sessionIdentifier: this.sessionIdentifier, + })) + return + } + + const length = this.media[medium].inbound.unprotectRTCP(datagram, this.rtcp) + + if (length === undefined) { + this.context.reporter.debug(MULTI_TIER_DEBUG, 'rtcp-refused', () => ({ + medium, + sentence: `Multi-tier session ${this.sessionIdentifier} drops a ${medium} RTCP datagram that fails authentication or replays an index.`, + sessionIdentifier: this.sessionIdentifier, + })) + return + } + + this.touchLiveness() + + const keyframe = asksForKeyframe(this.rtcp, length) + + if (keyframe === undefined) { + this.context.reporter.debug(MULTI_TIER_DEBUG, 'rtcp-malformed', () => ({ + medium, + sentence: `Multi-tier session ${this.sessionIdentifier} drops a malformed ${medium} RTCP packet.`, + sessionIdentifier: this.sessionIdentifier, + })) + return + } + + if (keyframe && medium === 'video') { + const outcome = this.tierHold?.answerKeyframeRequest() ?? 'stopped' + + this.context.reporter.debug(MULTI_TIER_DEBUG, 'keyframe-request', () => ({ + outcome, + sentence: `Multi-tier session ${this.sessionIdentifier} takes a keyframe request on video tier ${this.videoTier}: ${outcome}.`, + sessionIdentifier: this.sessionIdentifier, + tierId: this.videoTier, + })) + } + } + + /* Hands one talkback datagram to the session's talkback. The checks that need no cryptography come first: nothing is read once the session's talkback is + * closed, the delegate having declined talkback or the talkback having ended, or once the session's exit began, and a datagram too short for an RTP + * header, of another payload type than the audio tier's, or from another SSRC than the one the controller's Start named for audio is dropped. The packet + * is then unprotected in place, in the buffer its datagram arrived in: the sink is written a view of that buffer, which it may keep, and the session + * copies nothing and keeps no reference. A refused datagram is left as it arrived. The camera's Speaker mute is read last, after the unprotect, which is why a + * muted packet still moves the SRTP index as the controller's does and the first packet after a mute reads under the right rollover counter, while the + * muted packet itself is dropped and starts no sink. The talkback starts the sink at the first packet that authenticates while the Speaker is unmuted and + * guards every write, since the sink is plugin code running inside a socket listener. The talkback's end, which releases what its talker registered, + * stands on the stack above the socket listeners: every path that ends the session runs it while they stand. + */ + private talkback(datagram: Buffer): void { + if (this.sessionTalkback.closed || this.signal.aborted || datagram.length < RTP_HEADER_LENGTH + || (datagram[1] & RTP_PAYLOAD_TYPE_MASK) !== this.context.audioPayloadType || datagram.readUInt32BE(8) !== this.controllerSSRCs?.audio) { + return + } + + const length = this.media.audio.inbound.unprotect(datagram, datagram) + + if (length === undefined) { + if (++this.refusedTalkback === 1) { + this.context.reporter.debug(MULTI_TIER_DEBUG, 'talkback-refused', () => ({ + sentence: `Multi-tier session ${this.sessionIdentifier} drops a talkback datagram too short for its header and tag, longer than it reads, ` + + 'replaying an index or failing authentication.', + sessionIdentifier: this.sessionIdentifier, + })) + } + + return + } + + if (this.context.speakerMuted()) { + return + } + + this.sessionTalkback.write(datagram.subarray(0, length)) + } + + // The liveness window arms at the controller's first authenticated RTCP packet and restarts at each later one. A controller that reports and then falls + // silent ends its session, and one that never reports streams until its End, its connection's close, its tier's failure or the camera turning off. + private touchLiveness(): void { + if (this.livenessTimer) { + this.livenessTimer.refresh() + return + } + + this.livenessTimer = setTimeout(() => void this.exit('its controller sent no RTCP within the liveness window'), LIVENESS_WINDOW).unref() + } + + /* Each turn reads the steady clock once, which every report's RTP timestamp advances by, and the time of day once, for the one thing it serves: the NTP + * time each report states, the same for every medium's report of the turn. A correction of the time of day moves the NTP time alone. + */ + private scheduleReport(delay: number): void { + this.reportTimer = setTimeout(() => { + const moment = performance.now() + const ntp = ntpTime(Date.now()) + + for (const medium of MEDIA) { + this.media[medium].sender?.report(moment, ntp) + } + + this.scheduleReport(reportInterval()) + }, delay).unref() + } +} + +/** + * Serves one video sensor's Camera Multi-Tier RTP Stream Management service. It prepares each session on its own sockets and SRTP contexts, holds it in a + * session table that ties it to the connection that opened it, starts and ends it, holds its video tier's picture and sound in the sensor's tier table and + * sends it, under its own key and SSRC, every packet the tier's stream makes, its sound under the audio tier's payload type while the camera's Microphone + * is unmuted, reads each controller's RTCP and sends it sender reports, and writes each controller's talkback to a sink the delegate gives that session + * while the camera's Speaker is unmuted. The tier table reads each video tier's stream, times its picture and its sound on the sensor's one clock, cuts + * them into packets and reports each tier's demand to the delegate, which runs one encoding for each video tier as demand comes and goes and never sees a + * session. Its Status Active is the policy's, and its Streaming Enabled is its own. + * + * Where the sensor's audio states its source `'shared'`, a session of a tier other than the sensor's sound tier holds its own tier for its picture and the + * sound tier for its sound alone, through a hold of its own. It starts and runs on its own tier, its sound joining as the sound tier runs, which runs for + * it where nothing else holds it, and it goes on silent until it is opened again where the sound tier is refused, cut or fails, the failure told as that + * tier's own problem. + * + * Both control points are transient by their definitions: a writer's last answer reaches it in the write response and on its plain reads alone, until its + * session ends, the service is destroyed or reset, or the camera is switched off or goes out of service. The service runs its writes one at a time. A + * capacity check, the change to the session table and the answer are atomic across the delegate's awaits. A malformed write, or one a plugin makes without + * a connection, fails with `INVALID_VALUE_IN_REQUEST`, and a Setup Endpoints write while the camera is out of service fails with the communication failure, + * `SERVICE_COMMUNICATION_FAILURE`. + */ +export class MultiTierStreamManagement { + /** + * The service's key, in the camera's service map and in the policy alike. + * @private + */ + readonly serviceKey: string + private readonly policy: OperatingModePolicy + private readonly sensorUUID: string + private readonly maxSessions: number + private readonly service: CameraMultiTierRTPStreamManagement + private readonly table: TierTable + private readonly streamingEnabled: StreamingEnabledSwitch + private readonly queue = new CommandQueue() + private readonly sessions: ConnectionSessions + private readonly context: MultiTierSessionContext + // The camera's reporter's debug events on the service's debug name, which the session table and each control point write through as well. + private readonly debug: DebugWriter + // The hook a session's view is told of through as its Start is answered with success. + private readonly onLiveViewStarted?: (view: CameraLiveView) => void + // The payload type each medium's packets carry: the video tiers' for picture and the audio tier's for sound, whichever video tier the sound comes from. + private readonly payloadTypes: Readonly> + + /** + * Adopts the saved service or builds one, and sets its static characteristics. The options arrive validated by the camera's streaming options. + * @param options - The service's options. + * @param policy - The camera's operating-mode policy, which derives the service's Status Active. + * @param service - A saved service to adopt, which keeps its Streaming Enabled. + */ + constructor(options: MultiTierStreamManagementOptions, policy: OperatingModePolicy, service?: CameraMultiTierRTPStreamManagement) { + const { delegate, maxSessions, onLiveViewEnded, onLiveViewStarted, onStreamingEnabledChange, reporter, speakerMuted, table } = options + const { audioStreamTiers, videoStreamTiers } = table.streamTiers + + this.policy = policy + this.sensorUUID = table.sensorUUID + this.serviceKey = MultiTierStreamManagement.serviceKey(this.sensorUUID) + this.maxSessions = maxSessions + this.table = table + this.onLiveViewStarted = onLiveViewStarted + this.context = { + audioPayloadType: audioStreamTiers.payloadType, + talkbackStarted: talker => delegate.talkbackStarted?.(talker), + speakerMuted, + reporter, + sensorUUID: this.sensorUUID, + liveViewEnded: onLiveViewEnded, + } + this.debug = reporter.writer(MULTI_TIER_DEBUG) + this.payloadTypes = { video: videoStreamTiers.payloadType, audio: audioStreamTiers.payloadType } + this.service = service ?? MultiTierStreamManagement.constructService(this.sensorUUID) + this.sessions = new ConnectionSessions(this.service, this.debug, 'multi-tier') + this.streamingEnabled = new StreamingEnabledSwitch(this.service.getCharacteristic(Characteristic.StreamingEnabled), this.sensorUUID, 'home', onStreamingEnabledChange) + + this.service.updateCharacteristic(Characteristic.SensorUUID, uuid.write(this.sensorUUID).toString('base64')) + this.service.updateCharacteristic(Characteristic.SupportedVideoStreamTiers, encodeSupportedVideoStreamTiers(videoStreamTiers)) + this.service.updateCharacteristic(Characteristic.SupportedAudioStreamTiers, encodeSupportedAudioStreamTiers(audioStreamTiers)) + this.service.updateCharacteristic(Characteristic.SupportedRTPConfiguration, SUPPORTED_RTP_CONFIGURATION) + this.setupServiceHandlers() + } + + /** + * The key a video sensor's service carries in the camera's service map and in the policy. + * @param sensorUUID - The video sensor's UUID. + * @returns The capability prefix, `multiTierStream:` and the UUID in lowercase. + * @private + */ + static serviceKey(sensorUUID: string): string { + return sensorServiceKey('multiTierStream', sensorUUID) + } + + /** + * Reconciles every video sensor's service in a restored service map, in the order given: a sensor's saved service under its key is adopted, and a sensor + * without one gets a new service, inserted. The key of a sensor missing from the camera's inventory is left to the capability key sweep. + * @param serviceMap - The camera's service map, changed in place. + * @param sensors - Each video sensor's options, in the camera's order. + * @param create - Builds a sensor's management over its saved service, or over a new one when it is given none. + * @returns Whether the map changed. + * @private + */ + static reconcile( + serviceMap: ControllerServiceMap, + sensors: readonly MultiTierStreamManagementOptions[], + create: (options: MultiTierStreamManagementOptions, service?: CameraMultiTierRTPStreamManagement) => MultiTierStreamManagement, + ): boolean { + return reconcileSensorServices( + serviceMap, + sensors, + options => MultiTierStreamManagement.serviceKey(options.table.sensorUUID), + (options, service?: CameraMultiTierRTPStreamManagement) => create(options, service).getService(), + ) + } + + /** + * The Camera Multi-Tier RTP Stream Management service. + * @returns The service. + */ + getService(): CameraMultiTierRTPStreamManagement { + return this.service + } + + /** + * Binds the service's Streaming Enabled into the policy and subscribes whether the service may stream and its Status Active, once the camera's services + * are configured. It writes no Status Active, which {@link writeStatusActive} writes once the camera's restore has run. + * @private + */ + configureServices(): void { + this.policy.bindStreamingEnabled(this.serviceKey, this.service.getCharacteristic(Characteristic.StreamingEnabled)) + this.policy.subscribeDerivation('streamOpen', this.streamOpenChanged, this.serviceKey) + this.policy.subscribeDerivation('statusActive', this.statusActiveChanged, this.serviceKey) + + // The listener comes after the bind: the policy's listener, and with it the release and the session end, runs ahead of the state-change delegate, whose + // throw would otherwise leave a disabled service's answers held and its sessions live. + this.streamingEnabled.listen() + } + + /** + * Writes the service's Status Active from the policy as it stands, which the camera controller calls at the first context its accessory hands it in + * each configuration, after the restore. A derivation tells its listeners only when it moves, which is why this write carries the value it held before its first + * move, and each later move reaches the service through the subscription. + * @private + */ + writeStatusActive(): void { + this.service.updateCharacteristic(Characteristic.StatusActive, this.policy.statusActive(this.serviceKey)) + } + + /** + * The state to persist. + * @returns The value of Streaming Enabled. + * @private + */ + serialize(): MultiTierStreamManagementState { + return { + streamingEnabled: this.streamingEnabled.value, + } + } + + /** + * Restores persisted state, applying its Streaming Enabled when it is a boolean. + * @param state - The persisted state. + * @private + */ + deserialize(state: MultiTierStreamManagementState): void { + this.streamingEnabled.restore(state.streamingEnabled) + } + + /** + * Sets the delegate a change of Streaming Enabled calls, which is how the owner persists it. + * @param delegate - The delegate, or `undefined` to clear it. + * @private + */ + setupStateChangeDelegate(delegate?: StateChangeDelegate): void { + this.streamingEnabled.setupStateChangeDelegate(delegate) + } + + /** + * Releases every answer the control points hold, ends every session, withdraws each tier demand still pending, refusing every join waiting on it, and + * restores Streaming Enabled to its default, true. + */ + handleFactoryReset(): void { + void this.endAllSessionsAndDemands() + this.streamingEnabled.reset() + } + + /** + * Ends a session. An identifier no registered session carries is ignored. + * @param sessionIdentifier - The session's identifier. + */ + async endSession(sessionIdentifier: string): Promise { + await this.sessions.end(sessionIdentifier, ENDED_BY_OWNER) + } + + /** + * Ends every session, releases every answer the control points hold, withdraws each tier demand still pending, refusing every join waiting on it, and + * answers each later write without a session, before the service is dropped. + */ + async destroy(): Promise { + this.sessions.markDestroyed() + await this.endAllSessionsAndDemands() + } + + // A service this class builds is keyed by the sensor's UUID, in lowercase, and the sensor's identity and not its position binds it. + private static constructService(subtype: string): CameraMultiTierRTPStreamManagement { + const service = new Service.CameraMultiTierRTPStreamManagement('', subtype) + service.updateCharacteristic(Characteristic.StreamingEnabled, true) + + return service + } + + private setupServiceHandlers(): void { + // A read answers the policy at once, and it is right even for a change no derivation hears, such as a direct assignment to a projection's value. + this.service.getCharacteristic(Characteristic.StatusActive).onGet(() => this.policy.statusActive(this.serviceKey)) + + // R15 9.75 answers a read before any write with Error, naming no session; a writer's held answer is served ahead of this handler. + this.service.getCharacteristic(Characteristic.SetupEndpoints).onGet(() => SETUP_ENDPOINTS_ERROR) + + wireControlPoint( + this.service.getCharacteristic(Characteristic.SetupEndpoints), + this.queue, + this.debug, + decodeSetupEndpointsRequest, + this.setupEndpoints.bind(this), + encodeSetupEndpointsResponse, + ) + wireControlPoint( + this.service.getCharacteristic(Characteristic.RTPStreamingControl), + this.queue, + this.debug, + decodeRTPStreamingControlRequest, + this.streamingControl.bind(this), + encodeRTPStreamingControlResponse, + ) + } + + // The policy tells this listener each time the service's gate opens or closes. A gate that closes, the camera switched off or out of service, releases + // every connection's answers and ends every session through the session table, its promise voided, which is why nothing throws into the write or the statement + // that closed it. + private readonly streamOpenChanged = (open: boolean): void => { + if (!open) { + void this.sessions.endAll(ENDED_BY_OWNER) + } + } + + // The policy tells this listener each time the service's Status Active moves, which the user's switches and its own Streaming Enabled alone move, after + // the gate's listener has ended the sessions of a switch-off. + private readonly statusActiveChanged = (active: boolean): void => { + this.service.updateCharacteristic(Characteristic.StatusActive, active) + } + + /* Whether a Setup Endpoints write may prepare a session, read at its first check and at its re-check after the sockets bind: false while the camera is + * switched off, which the write answers with its own refusal, and a throw of the communication failure while the camera is out of service, which fails + * the write with that status, after one debug event of its own. + */ + private setupOpen(): boolean { + const gate = this.policy.streamGate(this.serviceKey) + + if (gate === 'out of service') { + this.debug('setup-out-of-service', () => ({ + sentence: 'Setup Endpoints fails with the communication failure while the camera is out of service.', + })) + throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + return gate === 'open' + } + + /* Ends every session and withdraws each tier demand whose start is still pending in the same turn, while the exits run and before a later write can hold + * one: a delegate whose start has not settled hears through its start's signal at the reset or the destroy itself that the library stops waiting, not + * at the start's own bound, and a Start that was waiting on it finds its session gone and answers Unknown Session Identifier. + */ + private async endAllSessionsAndDemands(): Promise { + const ended = this.sessions.endAll(ENDED_BY_OWNER) + + this.table.withdraw('when its service ended every session: the demand is withdrawn and every join waiting on it is refused') + await ended + } + + // Whether a live session of the management carries an SSRC, on either medium. + private carries(ssrc: number): boolean { + return this.sessions.identifiers().some((sessionIdentifier) => { + const media = this.sessions.get(sessionIdentifier)!.media + + return media.video.ssrc === ssrc || media.audio.ssrc === ssrc + }) + } + + // A random 32-bit SSRC (RFC 3550 8.1) no live session of the management carries and other than the session's other SSRC. + private freshSSRC(other?: number): number { + for (;;) { + const ssrc = crypto.randomBytes(4).readUInt32BE(0) + + if (ssrc !== other && !this.carries(ssrc)) { + return ssrc + } + } + } + + private async setupEndpoints(request: SetupEndpointsRequest, connection: HAPConnection): Promise { + const { audioSRTPParameters, sessionIdentifier, videoSRTPParameters } = request + const refuse = (status: SetupEndpointsStatus.BUSY | SetupEndpointsStatus.ERROR, reason: string): SetupEndpointsResponse => { + this.debug('setup-refused', () => ({ + reason, + sentence: `Refusing Setup Endpoints for multi-tier session ${sessionIdentifier}: ${reason}`, + sessionIdentifier, + })) + + return { status, sessionIdentifier } + } + + if (!this.sessions.serves(connection)) { + return refuse(SetupEndpointsStatus.ERROR, 'the management no longer serves its connection.') + } + + if (videoSRTPParameters.cryptoSuite !== SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80 || audioSRTPParameters.cryptoSuite !== SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80) { + return refuse(SetupEndpointsStatus.ERROR, 'it names an SRTP suite other than AES_CM_128_HMAC_SHA1_80.') + } + + // The contexts stand on this stack until the session registers, and every answer short of success zeroes what they derived. + using contexts = new DisposableStack() + let inbound: Record + + try { + inbound = { + video: contexts.use(new SRTPContext(videoSRTPParameters.masterKey, videoSRTPParameters.masterSalt)), + audio: contexts.use(new SRTPContext(audioSRTPParameters.masterKey, audioSRTPParameters.masterSalt)), + } + } catch (error) { + return refuse(SetupEndpointsStatus.ERROR, errorMessage(error)) + } + + // A session that cannot start binds no socket: a camera switched off answers Error, and one out of service fails the write. + if (!this.setupOpen()) { + return refuse(SetupEndpointsStatus.ERROR, 'Status Active is false.') + } + + const held = this.sessions.get(sessionIdentifier) + + if (held && (held.connection !== connection || held.state === 'streaming')) { + return refuse(SetupEndpointsStatus.ERROR, 'another connection\'s session, or a streaming one, holds its identifier.') + } + + // A connection that prepares again replaces the prepared sessions it holds, what the hubs do when their tile asks again, its own identifier's among them. + await Promise.all(this.sessions.identifiers() + .map(identifier => this.sessions.get(identifier)!) + .filter(session => session.connection === connection && session.state === 'prepared') + .map(async session => this.sessions.exit(session, 'its connection prepared another session'))) + + if (this.sessions.size >= this.maxSessions) { + return refuse(SetupEndpointsStatus.BUSY, `the service holds its most sessions, ${this.maxSessions}.`) + } + + return await this.prepare(request, connection, contexts, inbound) + } + + /* Prepares a session: two sockets on the controller's address family, bound at port 0 on its wildcard, which means a scoped IPv6 address never reaches a bind, and + * connected to the controller's ports; the accessory's own master key and salt and a fresh SSRC per medium; and the contexts. The served and destroyed + * reads and the service's gate are taken again in the synchronous turn that registers the session, because the binds await. A camera out of service + * by then fails the write and its sockets close. + */ + private async prepare( + request: SetupEndpointsRequest, + connection: HAPConnection, + contexts: DisposableStack, + inbound: Record, + ): Promise { + const { audioSRTPParameters, controllerAddress, sessionIdentifier, videoSRTPParameters } = request + const { addressVersion } = controllerAddress + const refused = (reason: string): SetupEndpointsResponse => { + this.debug('setup-refused', () => ({ + reason, + sentence: `Refusing Setup Endpoints for multi-tier session ${sessionIdentifier}: ${reason}`, + sessionIdentifier, + })) + + return { status: SetupEndpointsStatus.ERROR, sessionIdentifier } + } + + let address: string + + try { + address = connection.getLocalAddress(addressVersion) + } catch (error) { + return refused(errorMessage(error)) + } + + // The sockets stand on this stack until the session registers, and every answer short of success closes them. + await using pending = new AsyncDisposableStack() + let session: MultiTierSession | undefined + + // A connected socket reports a controller's closed port as an error, which ends the session it carries. + const failed = (error: Error): void => { + const { message } = error + + this.debug('socket-error', () => ({ + message, + sentence: `A socket of multi-tier session ${sessionIdentifier} reports an error: ${message}`, + sessionIdentifier, + })) + + if (session) { + void session.exit('its socket reported an error') + } + } + + const type: SocketType = addressVersion === 'ipv6' + ? 'udp6' + : 'udp4' + const wildcard = addressVersion === 'ipv6' + ? '::' + : '0.0.0.0' + const sockets: Record = { + video: pending.adopt(dgram.createSocket(type), close), + audio: pending.adopt(dgram.createSocket(type), close), + } + + if (!(await Promise.all(MEDIA.map(async medium => bind(sockets[medium], wildcard, failed)))).every(Boolean)) { + return refused('a socket failed to bind.') + } + + const ports: Record = { video: controllerAddress.videoRTPPort, audio: controllerAddress.audioRTPPort } + + if (!(await Promise.all(MEDIA.map(async medium => connect(sockets[medium], ports[medium], controllerAddress.address)))).every(Boolean)) { + return refused('a socket failed to connect to the controller.') + } + + const keys: Record = { + video: masterKeyAndSalt(), + audio: masterKeyAndSalt(), + } + const videoSSRC = this.freshSSRC() + const audioSSRC = this.freshSSRC(videoSSRC) + const media: Record = { + video: { + socket: sockets.video, + outbound: contexts.use(new SRTPContext(keys.video.masterKey, keys.video.masterSalt)), + inbound: inbound.video, + ssrc: videoSSRC, + }, + audio: { + socket: sockets.audio, + outbound: contexts.use(new SRTPContext(keys.audio.masterKey, keys.audio.masterSalt)), + inbound: inbound.audio, + ssrc: audioSSRC, + }, + } + + if (!this.sessions.serves(connection) || !this.setupOpen()) { + return refused('its connection closed, the management was destroyed or its gate read switched off while its sockets bound.') + } + + // The session is registered before it takes over the sockets and the contexts, and before the socket error listener can end it: a registration that + // throws leaves them on the stacks that release them. + const prepared = new MultiTierSession(sessionIdentifier, connection, media, this.sessions, this.context) + this.sessions.add(prepared) + session = prepared + pending.use(contexts.move()) + prepared.hold(pending) + prepared.armPrepareTimeout() + + const accessoryAddress = { + addressVersion, + address, + videoRTPPort: sockets.video.address().port, + audioRTPPort: sockets.audio.address().port, + } + + // The keys and salts are secrets and debug output is often shared in public, which is why the event names each one's length and never its bytes. + this.debug('session-prepared', () => { + const suite = SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80 + const keyLengths = [videoSRTPParameters.masterKey.length, audioSRTPParameters.masterKey.length] + const saltLengths = [videoSRTPParameters.masterSalt.length, audioSRTPParameters.masterSalt.length] + + return { + accessoryAddress: address, + accessoryPorts: [accessoryAddress.videoRTPPort, accessoryAddress.audioRTPPort], + controllerAddress: controllerAddress.address, + controllerPorts: [ports.video, ports.audio], + keyLengths, + saltLengths, + sentence: `Prepared multi-tier session ${sessionIdentifier} from ${controllerAddress.address} ports ${ports.video} and ${ports.audio} on ${address} ` + + `ports ${accessoryAddress.videoRTPPort} and ${accessoryAddress.audioRTPPort}, suite ${suite}, controller key lengths ${keyLengths[0]} and ` + + `${keyLengths[1]} and salt lengths ${saltLengths[0]} and ${saltLengths[1]}.`, + sessionIdentifier, + suite, + } + }) + + return { + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier, + accessoryAddress, + videoSRTPParameters: { cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, ...keys.video }, + audioSRTPParameters: { cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, ...keys.audio }, + videoSSRC, + audioSSRC, + } + } + + private async streamingControl(request: RTPStreamingControlRequest, connection: HAPConnection): Promise { + const { sessionIdentifier } = request + const session = this.sessions.liveSession(sessionIdentifier, connection) + + if (!session) { + return { sessionIdentifier, status: RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } + } + + if (request.command === RTPStreamingCommand.START) { + return await this.start(session, request) + } + + // An End of a session that never started answers No Such Stream, and the session ends either way. + const streaming = session.state === 'streaming' + await this.sessions.exit(session, 'its controller ended it') + + return { + sessionIdentifier, + status: streaming + ? RTPStreamingStatus.SUCCESS + : RTPStreamingStatus.NO_SUCH_STREAM, + } + } + + private async start( + session: MultiTierSession, + request: Extract, + ): Promise { + const { sessionIdentifier } = session + const answer = (status: RTPStreamingStatus): RTPStreamingControlResponse => ({ sessionIdentifier, status }) + const { audioTier } = this.table + const videoTier = this.table.videoTiers.get(request.videoTier) + + if (session.state === 'streaming' || !this.policy.streamOpen(this.serviceKey) || !videoTier || request.audioTier !== audioTier.tierId) { + return answer(RTPStreamingStatus.ERROR) + } + + // The joins' holds stand on this Start's own stack until it succeeds: a Start answered busy leaves no tier holding the session, and a retried Start + // joins anew. The session reaches that stack before the joins, which is why a session that ends while its Start waits releases the joins, and its senders, above + // its contexts and sockets. A join that raises a demand runs plugin code, the demand's start, and that code can end the session. A join made as the + // session's signal aborted is released at once. + await using holds = new AsyncDisposableStack() + + session.reach(holds) + + const joined = this.hold(holds, session, videoTier) + + if (joined === undefined) { + return answer(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + } + + const { hold } = joined + + // The picture's demand still waiting on its start is waited for within the session's exit alone, since the start's own bound withdraws a start that never + // settles and refuses every join waiting on it, and a sound taken from the sensor's sound tier is never waited for: it holds back no view. A session + // gone once the wait is over, which a wait its session's signal cut always finds, a failed tier among the ways, answers Unknown Session Identifier. A + // wait answered anything but started, a refused start or one a withdrawal cut, its bound's among them, answers Busy with no report of the management's + // own and leaves the session prepared, which means a call that never settles releases the service's queue. A hold no wait answers reads its demand as it stands. + const started = hold.waiting + ? (await settleWithin(hold.answer(), session.signal))?.value === 'started' + : hold.started + + if (!this.sessions.holds(session)) { + return answer(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + } + + if (!started) { + return answer(RTPStreamingStatus.BUSY) + } + + session.stream( + holds, + request.videoTier, + joined, + { video: request.videoSSRC, audio: request.audioSSRC }, + ) + this.onLiveViewStarted?.(session.liveView) + + return answer(RTPStreamingStatus.SUCCESS) + } + + /* Joins a video tier for a session's picture and its sound in one step, its hold's release on the Start's stack, before the Start waits, which is why a stream the + * plugin writes while the tier's demand is starting reaches the session that raised it as the tier's pacer releases it, its picture and its sound alike. + * The table raises the demand when the tier has none, decides its packet size from the listening family of the session's HAP server when no session is + * joined, and makes the session's sender of each medium for that size, under that medium's payload type, before it calls the delegate for a demand it + * raised, a join into a running demand calling it for nothing. A join into a tier whose buffer keeps a keyframe the pacer has released opens its picture + * from the latest such keyframe, handed across the pacer's turns as the live edge reaches each picture and while it fits its sender's room, while its + * sound joins the live releases at once, and a join into a tier whose buffer keeps no such keyframe has its picture start at the stream's next keyframe. + * + * A tier whose sound the sensor takes from its sound tier is joined for its picture alone, and the sound tier then for the sound alone, through a sound + * holder of the session's own, its release on the Start's stack beside the picture's: the sound tier's failure ends the sound and never the view, and + * a sound tier whose demand failed before the join is released at once, the view silent from its start. The answer carries the picture's hold, which + * the Start waits on and a keyframe request goes to, and a sender of each medium from the join that took it. Each join whose plugin code ended the + * session finds the Start's stack swept by the session's exit already, a join made before it released by that sweep, which means its hold is released at once + * and the join answers none. + */ + private hold(holds: AsyncDisposableStack, session: MultiTierSession, tier: Tier): SessionHold | undefined { + const senders: Partial> = {} + const joining = (medium: StreamTierMedium, packetSize: number): TierSender => { + const sender = new TierSender(session, session.media[medium], this.payloadTypes[medium], CLOCK_RATES[medium], packetSize, POOL_SIZES[medium], + POOL_CEILINGS[medium]) + + senders[medium] = sender + + return sender + } + const soundTier = this.table.soundTierOf(tier) + const apart = soundTier !== tier + const hold = this.table.join(tier, session, session.connection, apart + ? PICTURE + : MEDIA, joining) + + if (session.signal.aborted) { + hold.release() + + return undefined + } + + holds.defer(() => hold.release()) + + if (apart) { + const holder = new SoundHolder() + const sound = this.table.join(soundTier, holder, session.connection, SOUND, joining) + + holder.hold = sound + + if (session.signal.aborted) { + sound.release() + + return undefined + } + + holds.defer(() => sound.release()) + + // A demand that failed before this join, which another holder still keeps, calls this holder's route for no failure, the route having run for the + // holds that stood then. The sound's hold is released here. The failed tier is left to its other holders and the view goes on silent. + if (!sound.waiting && !sound.started) { + sound.release() + } + } + + return { hold, senders: senders as Record } + } +} diff --git a/src/lib/camera/index.ts b/src/lib/camera/index.ts index 524f980d9..9fd9445e9 100644 --- a/src/lib/camera/index.ts +++ b/src/lib/camera/index.ts @@ -1,6 +1,7 @@ export * from './capabilities/index.js' export * from './diagnostics/problems.js' export type { MotionZones, MotionZonesManagementState } from './MotionZonesManagement.js' +export type { MultiTierStreamManagementState } from './MultiTierStreamManagement.js' export type { CameraChangeReason, OperatingModeChange, OperatingModeField, OperatingModeState, StreamingEnabledChange } from './OperatingModePolicy.js' export * from './RecordingManagement.js' export * from './RTPProxy.js' diff --git a/src/lib/camera/session/SessionTalkback.spec.ts b/src/lib/camera/session/SessionTalkback.spec.ts new file mode 100644 index 000000000..11ec59b49 --- /dev/null +++ b/src/lib/camera/session/SessionTalkback.spec.ts @@ -0,0 +1,569 @@ +import type { Mock } from 'vitest' + +import type { TalkbackSink, Talker } from '../StreamingOptions.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' + +import { detachedReporter } from '../../../test-utils/reporterFixtures.js' +import { deferred, settle } from '../../../test-utils/settle.js' +import { keepingSink } from '../../../test-utils/talkbackSink.js' +import { DisposableStack } from '../../util/disposableStack.js' +import { SessionTalkback } from './SessionTalkback.js' + +// The words the rows' talkback names its session by, the session's identifier, and the UUID of the sensor its talker talks on, each made up. +const SESSION_IDENTIFIER = '6f1e2d3c-4b5a-4968-8796-a5b4c3d2e1f0' +const SESSION = `multi-tier session ${SESSION_IDENTIFIER}` +const SENSOR_UUID = '3a9e8d7c-6b5a-4f49-8e3d-2c1b0a9f8e7d' + +// The line a promise answer declines talkback with. +const DECLINED = `MultiTierStreamingDelegate answered talkbackStarted with a promise rather than a sink, and talkback is declined for ${SESSION}.` + +// The line an answer with no write function declines talkback with. +const NO_WRITE = `MultiTierStreamingDelegate answered talkbackStarted with a sink that has no write function, and talkback is declined for ${SESSION}.` + +// The sentence a talker's failed cleanup is logged under. +const TALKER_FAILURE = `MultiTierStreamingDelegate failed to end the talkback of ${SESSION}` + +// A session's talkback over a stack of the row's own, which stands for the session's, its exit begun once the row says so. +interface Harness { + readonly ending: { begun: boolean } + readonly stack: DisposableStack + readonly start: Mock<(talker: Talker) => TalkbackSink | undefined> + readonly talkback: SessionTalkback +} + +// The row's answer is handed the session's ending mark and the talker. An answer can register on its talker and begin the session's exit inside the +// start. +function harness(answer: (ending: { begun: boolean }, talker: Talker) => TalkbackSink | undefined): Harness { + const ending = { begun: false } + const stack = new DisposableStack() + const start = vi.fn((talker: Talker) => answer(ending, talker)) + + return { + ending, + stack, + start, + talkback: new SessionTalkback({ + defer: release => stack.defer(release), + ended: () => ending.begun, + reporter: detachedReporter(), + sensorUUID: SENSOR_UUID, + session: SESSION, + sessionIdentifier: SESSION_IDENTIFIER, + start, + }), + } +} + +// A talkback packet the rows hand on, its octets patterned from a seed. +function packet(seed: number): Buffer { + return Buffer.alloc(20, seed) +} + +// Every line the rows' console.error is handed, each as one string. +function errorLines(): string[] { + const lines: string[] = [] + + vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { + lines.push(args.map(String).join(' ')) + }) + + return lines +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('sessionTalkback', () => { + it('starts the sink at the first write and hands it each packet, the very buffer written', () => { + const { packets, sink } = keepingSink() + const { start, talkback } = harness(() => sink) + const written = [ + packet(1), + packet(2), + packet(3), + ] + + expect(talkback.closed).toBe(false) + expect(start).not.toHaveBeenCalled() + + for (const each of written) { + talkback.write(each) + } + + expect(start).toHaveBeenCalledOnce() + expect(packets).toHaveLength(written.length) + expect(packets.every((each, index) => each === written[index])).toBe(true) + expect(talkback.closed).toBe(false) + }) + + it('declines talkback for an answer of undefined, a promise, a throw and a then that throws, asking once and logging a promise once in the session\'s ' + + 'words', async () => { + const lines = errorLines() + const promised = keepingSink() + const thenThrows = keepingSink() + const answers: (() => TalkbackSink | undefined)[] = [ + () => undefined, + () => Promise.resolve(promised.sink) as unknown as TalkbackSink, + () => { + throw new Error('The plugin failed to start talkback.') + }, + () => Object.defineProperty({ ...thenThrows.sink }, 'then', { + get: () => { + throw new Error('The answer\'s then cannot be read.') + }, + }), + ] + + for (const answer of answers) { + const { stack, start, talkback } = harness(answer) + + talkback.write(packet(1)) + talkback.write(packet(2)) + stack.dispose() + + expect(start).toHaveBeenCalledOnce() + expect(talkback.closed).toBe(true) + } + + await settle() + + expect(promised.sink.write).not.toHaveBeenCalled() + expect(thenThrows.sink.write).not.toHaveBeenCalled() + expect(lines).toEqual([ + `MultiTierStreamingDelegate answered talkbackStarted with a promise rather than a sink, and talkback is declined for ${SESSION}.`, + expect.stringContaining('MultiTierStreamingDelegate failed to start talkback: Error: The plugin failed to start talkback.'), + expect.stringContaining('MultiTierStreamingDelegate failed to start talkback: Error: The answer\'s then cannot be read.'), + ]) + }) + + it('logs the first write that throws or rejects as it happens and counts the rest in the one closing line, writing on after each', async () => { + const lines = errorLines() + const { packets, sink } = keepingSink() + const { talkback } = harness(() => sink) + + sink.write.mockImplementationOnce(() => { + throw new Error('The sink failed to write.') + }).mockImplementationOnce(async () => Promise.reject(new Error('The sink failed to write later.'))).mockImplementationOnce(() => { + throw new Error('The sink failed to write again.') + }) + + for (const seed of [1, 2, 3, 4]) { + talkback.write(packet(seed)) + } + + await settle() + talkback.logFailedWrites() + + expect(sink.write).toHaveBeenCalledTimes(4) + expect(packets).toEqual([ + packet(4), + ]) + expect(lines).toEqual([ + expect.stringContaining('TalkbackSink failed to write a packet: Error: The sink failed to write.'), + `TalkbackSink failed 2 more writes before ${SESSION} ended.`, + ]) + }) + + it('ends the sink once at the session\'s end, ahead of what the stack held before the start, and starts and writes nothing after', () => { + const kept = keepingSink() + const { stack, start, talkback } = harness((_, talker) => kept.start(talker)) + const released: string[] = [] + + stack.defer(() => released.push('registered before the start')) + kept.release.mockImplementation(() => { + released.push('the talker\'s release') + }) + talkback.write(packet(1)) + stack.dispose() + + expect(released).toEqual(['the talker\'s release', 'registered before the start']) + expect(talkback.closed).toBe(true) + + talkback.write(packet(2)) + + expect(start).toHaveBeenCalledOnce() + expect(kept.release).toHaveBeenCalledOnce() + expect(kept.packets).toEqual([ + packet(1), + ]) + }) + + it('ends a started sink once at its own end, a second end and the session\'s teardown after it ending nothing more', () => { + const kept = keepingSink() + const { stack, start, talkback } = harness((_, talker) => kept.start(talker)) + + talkback.write(packet(1)) + talkback.end() + + expect(kept.release).toHaveBeenCalledOnce() + expect(talkback.closed).toBe(true) + + talkback.end() + stack.dispose() + talkback.write(packet(2)) + + expect(kept.release).toHaveBeenCalledOnce() + expect(start).toHaveBeenCalledOnce() + expect(kept.packets).toEqual([ + packet(1), + ]) + }) + + it('closes a talkback ended before its first write, a later write starting nothing', () => { + const kept = keepingSink() + const { stack, start, talkback } = harness((_, talker) => kept.start(talker)) + + talkback.end() + + expect(talkback.closed).toBe(true) + expect(talkback.write(packet(1))).toBe(false) + + stack.dispose() + + expect(start).not.toHaveBeenCalled() + expect(kept.sink.write).not.toHaveBeenCalled() + expect(kept.release).not.toHaveBeenCalled() + }) + + it('answers whether each write reached a sink: one whose write throws or rejects among them, and neither a closed talkback\'s nor the declined one\'s', async () => { + errorLines() + + const { packets, sink } = keepingSink() + const { talkback } = harness(() => sink) + const declined = harness(() => undefined).talkback + + sink.write.mockImplementationOnce(() => { + throw new Error('The sink failed to write.') + }).mockImplementationOnce(async () => Promise.reject(new Error('The sink failed to write later.'))) + + expect([1, 2, 3].map(seed => talkback.write(packet(seed)))).toEqual([true, true, true]) + + talkback.end() + + expect(talkback.write(packet(4))).toBe(false) + expect([5, 6].map(seed => declined.write(packet(seed)))).toEqual([false, false]) + + await settle() + + expect(sink.write).toHaveBeenCalledTimes(3) + expect(packets).toEqual([ + packet(3), + ]) + }) + + it('ends at once and writes nothing to a sink started inside a session exit already begun, ending the session inside the start among them', () => { + const kept = keepingSink() + const { stack, start, talkback } = harness((ending, talker) => { + ending.begun = true + + return kept.start(talker) + }) + const defer = vi.spyOn(stack, 'defer') + + talkback.write(packet(1)) + talkback.write(packet(2)) + + expect(start).toHaveBeenCalledOnce() + expect(kept.release).toHaveBeenCalledOnce() + expect(kept.sink.write).not.toHaveBeenCalled() + expect(defer).not.toHaveBeenCalled() + expect(talkback.closed).toBe(true) + }) + + it('joins a rejection that settles after the closing line to no line, and logs one that is the session\'s first failure then', async () => { + const lines = errorLines() + const counted = keepingSink() + const first = keepingSink() + const late = deferred() + const firstLate = deferred() + const countedTalkback = harness(() => counted.sink).talkback + const firstTalkback = harness(() => first.sink).talkback + + counted.sink.write.mockImplementationOnce(() => { + throw new Error('The sink failed to write.') + }).mockImplementationOnce(async () => late.promise) + first.sink.write.mockImplementationOnce(async () => firstLate.promise) + countedTalkback.write(packet(1)) + countedTalkback.write(packet(2)) + firstTalkback.write(packet(3)) + countedTalkback.logFailedWrites() + firstTalkback.logFailedWrites() + + expect(lines).toEqual([ + expect.stringContaining('TalkbackSink failed to write a packet: Error: The sink failed to write.'), + ]) + + late.reject(new Error('The sink failed after the closing line.')) + firstLate.reject(new Error('The sink failed first, after the closing line.')) + await settle() + + expect(lines).toEqual([ + expect.stringContaining('TalkbackSink failed to write a packet: Error: The sink failed to write.'), + expect.stringContaining('TalkbackSink failed to write a packet: Error: The sink failed first, after the closing line.'), + ]) + }) + + it('declines an answer of nothing, undefined and null among them, with no line, releasing what the call registered before the write returns', () => { + const lines = errorLines() + // Each falsy answer a plugin written in JavaScript can give, cast past the contract's types. + const answers = [undefined, null, false, 0, ''] as unknown as (TalkbackSink | undefined)[] + + for (const answer of answers) { + const release = vi.fn<() => void>() + const { stack, start, talkback } = harness((_, talker) => { + talker.defer(release) + + return answer + }) + + expect(talkback.write(packet(1))).toBe(false) + expect(release).toHaveBeenCalledOnce() + expect(talkback.closed).toBe(true) + + talkback.write(packet(2)) + stack.dispose() + + expect(start).toHaveBeenCalledOnce() + expect(release).toHaveBeenCalledOnce() + } + + expect(lines).toEqual([]) + }) + + it('declines a call that throws and an answer whose then throws when read, logging each as the call\'s failure, and releases what the call registered ' + + 'before the throw', () => { + const lines = errorLines() + const { sink } = keepingSink() + const answers: (() => TalkbackSink)[] = [ + () => { + throw new Error('The plugin failed to start talkback.') + }, + () => Object.defineProperty({ ...sink }, 'then', { + get: () => { + throw new Error('The answer\'s then cannot be read.') + }, + }), + ] + const releases = answers.map(() => vi.fn<() => void>()) + + for (const [index, answer] of answers.entries()) { + const { start, talkback } = harness((_, talker) => { + talker.use({ [Symbol.dispose]: releases[index] }) + + return answer() + }) + + expect(talkback.write(packet(1))).toBe(false) + expect(talkback.write(packet(2))).toBe(false) + expect(start).toHaveBeenCalledOnce() + expect(talkback.closed).toBe(true) + } + + expect(releases.map(release => release.mock.calls.length)).toEqual([1, 1]) + expect(sink.write).not.toHaveBeenCalled() + expect(lines).toEqual([ + expect.stringContaining('MultiTierStreamingDelegate failed to start talkback: Error: The plugin failed to start talkback.'), + expect.stringContaining('MultiTierStreamingDelegate failed to start talkback: Error: The answer\'s then cannot be read.'), + ]) + }) + + it('declines a promise with one line, writing nothing it resolves to, releases what its function registered in the call at once and what it registers ' + + 'after the decline in a microtask of its own, and logs a rejected promise, leaving no rejection unhandled', async () => { + const lines = errorLines() + const unhandled = vi.fn<(reason: unknown) => void>() + + process.on('unhandledRejection', unhandled) + onTestFinished(() => { + process.off('unhandledRejection', unhandled) + }) + + const { sink } = keepingSink() + const opened = deferred() + const order: string[] = [] + const early = vi.fn<() => void>() + const late = vi.fn<() => void>(() => { + order.push('the late release') + }) + // An async talkbackStarted answers a promise the contract's types refuse, which is why each answer is cast past them. + const resolving = harness(((_: unknown, talker: Talker) => (async () => { + talker.defer(early) + await opened.promise + talker.defer(late) + order.push('the line after the late registration') + + return sink + })()) as unknown as (ending: { begun: boolean }, talker: Talker) => TalkbackSink) + + expect(resolving.talkback.write(packet(1))).toBe(false) + expect(early).toHaveBeenCalledOnce() + expect(late).not.toHaveBeenCalled() + expect(resolving.talkback.closed).toBe(true) + + opened.resolve() + await settle() + + expect(order).toEqual(['the line after the late registration', 'the late release']) + + const rejecting = harness((async () => Promise.reject(new Error('The decoder would not start.'))) as unknown as () => TalkbackSink) + + expect(rejecting.talkback.write(packet(2))).toBe(false) + + await settle() + resolving.talkback.write(packet(3)) + resolving.stack.dispose() + rejecting.stack.dispose() + + expect([ + early.mock.calls.length, + late.mock.calls.length, + resolving.start.mock.calls.length, + rejecting.start.mock.calls.length, + sink.write.mock.calls.length, + unhandled.mock.calls.length, + ]).toEqual([1, 1, 1, 1, 0, 0]) + expect(lines).toEqual([ + DECLINED, + DECLINED, + expect.stringContaining('MultiTierStreamingDelegate failed to start talkback: Error: The decoder would not start.'), + ]) + }) + + it('writes a sink with write alone each packet, logging nothing at its start or its end and throwing nothing', async () => { + const lines = errorLines() + const written: Buffer[] = [] + const plain: TalkbackSink = { + write: (each) => { + written.push(each) + }, + } + const { stack, talkback } = harness(() => plain) + + talkback.write(packet(1)) + talkback.write(packet(2)) + + expect(() => { + talkback.end() + stack.dispose() + }).not.toThrow() + + await settle() + + expect([written, lines]).toEqual([ + [ + packet(1), + packet(2), + ], + [], + ]) + }) + + it('never disposes a sink that carries a dispose method and is not registered on its talker, logging nothing', async () => { + const lines = errorLines() + const sink = { + [Symbol.asyncDispose]: vi.fn<() => Promise>(async () => undefined), + [Symbol.dispose]: vi.fn<() => void>(), + write: vi.fn(), + } + const { stack, talkback } = harness(() => sink) + + talkback.write(packet(1)) + talkback.end() + stack.dispose() + await settle() + + expect([ + sink.write.mock.calls.length, + sink[Symbol.asyncDispose].mock.calls.length, + sink[Symbol.dispose].mock.calls.length, + lines, + ]).toEqual([1, 0, 0, []]) + }) + + it('declines an answer with no write function, logging the line once for each, and releases what the call registered', () => { + const lines = errorLines() + // Each answer a plugin written in JavaScript can give with no write function, cast past the contract's types. + const answers = [ + {}, + { write: 'a decoder' }, + 7, + ] as unknown as TalkbackSink[] + const releases = answers.map(() => vi.fn<() => void>()) + + for (const [index, answer] of answers.entries()) { + const { stack, start, talkback } = harness((_, talker) => { + talker.defer(releases[index]) + + return answer + }) + + expect(talkback.write(packet(1))).toBe(false) + expect(talkback.write(packet(2))).toBe(false) + + stack.dispose() + + expect(start).toHaveBeenCalledOnce() + expect(talkback.closed).toBe(true) + } + + expect(releases.map(release => release.mock.calls.length)).toEqual([1, 1, 1]) + expect(lines).toEqual([NO_WRITE, NO_WRITE, NO_WRITE]) + }) + + it('hands each start a frozen talker of its own, whose own keys are defer, sensorUUID and use alone, sensorUUID the sensor\'s, use answering its value', () => { + const talkers: Talker[] = [] + const { sink } = keepingSink() + const answer = (_: unknown, talker: Talker): TalkbackSink => { + talkers.push(talker) + + return sink + } + + harness(answer).talkback.write(packet(1)) + harness(answer).talkback.write(packet(2)) + + const [talker, other] = talkers + const disposable = { + [Symbol.dispose]: vi.fn<() => void>(), + } + + expect(talkers).toHaveLength(2) + expect(other).not.toBe(talker) + expect(Object.isFrozen(talker)).toBe(true) + expect(Reflect.ownKeys(talker)).toEqual(['defer', 'sensorUUID', 'use']) + expect(talker.sensorUUID).toBe(SENSOR_UUID) + expect(talker.use(disposable)).toBe(disposable) + }) + + it('logs a talker\'s cleanup that throws and one that rejects once each under the talker\'s sentence, calling every other cleanup', async () => { + const lines = errorLines() + const called: string[] = [] + const { sink } = keepingSink() + const { stack, talkback } = harness((_, talker) => { + talker.defer(() => called.push('the oldest cleanup')) + talker.defer(() => { + throw new Error('The decoder would not stop.') + }) + talker.use({ + [Symbol.asyncDispose]: async () => { + throw new Error('The decoder would not close.') + }, + }) + + return sink + }) + + talkback.write(packet(1)) + stack.dispose() + await settle() + + expect(called).toEqual(['the oldest cleanup']) + expect(lines).toEqual([ + expect.stringContaining(`${TALKER_FAILURE}: Error: The decoder would not stop.`), + expect.stringContaining(`${TALKER_FAILURE}: Error: The decoder would not close.`), + ]) + }) +}) diff --git a/src/lib/camera/session/SessionTalkback.ts b/src/lib/camera/session/SessionTalkback.ts new file mode 100644 index 000000000..dfedcd6ef --- /dev/null +++ b/src/lib/camera/session/SessionTalkback.ts @@ -0,0 +1,220 @@ +import type { Buffer } from 'node:buffer' + +import type { CameraReporter, FailureFields } from '../diagnostics/CameraReporter.js' +import type { TalkbackSink, Talker } from '../StreamingOptions.js' + +import { nounFor } from '../../util/counted.js' +import { isThenable } from '../../util/promise-utils.js' +import { HandleScope } from './HandleScope.js' + +/** + * What a session's talkback is made from: the start that asks the plugin for a sink, the sensor its talker carries, the session's exit, its stack, the + * camera's reporter and the words its problems name it by. + */ +export interface SessionTalkbackOptions { + /** + * Registers a callback on the session's stack, run at the session's teardown. + */ + readonly defer: (release: () => void) => void + /** + * Whether the session's exit has begun. + */ + readonly ended: () => boolean + /** + * The camera's reporter, through which a failure of the sink, of its start or of what the plugin registered on the talker is the plugin's. + */ + readonly reporter: CameraReporter + /** + * The UUID of the sensor whose stream the talker talks on, in lowercase, which its talker carries. + */ + readonly sensorUUID: string + /** + * The words a problem's sentence names the session by, such as `multi-tier session` and its identifier. + */ + readonly session: string + /** + * The identifier of the session the talkback belongs to, which each of its failures carries. + */ + readonly sessionIdentifier: string + /** + * The delegate's `talkbackStarted`, which takes the talker, answering `undefined` for a delegate without it. + */ + readonly start: (talker: Talker) => TalkbackSink | undefined +} + +/** + * One talker's talkback, a session's at home and a viewer's from away: the plugin's sink, started at the talkback's first packet with the talker the + * plugin registers on what it makes for it, and every write to the sink guarded. A sink's failure is the sink's and the session goes on. Every path + * that hands a talker's talkback to a plugin writes through one. + * + * The talker is a frozen object of its own, carrying the sensor's UUID and `use` and `defer`, which forward to the talkback's scope and reach nothing else + * of the talkback. The scope is released once, at the talkback's end, by whichever comes first of the session's end and the talkback's own, and at a + * decline: what the plugin registered is released at every end. The sink is unset until the first write, then the delegate's sink, kept for writing + * alone, and closed once the delegate declined talkback or the talkback ended, after which every write is dropped. The writes that throw or reject are + * counted: the first is a plugin-failure problem as it happens and the rest one problem, raised as the session's end or the talkback's own comes, + * whichever first. A flood raises no problem per packet. A rejection that settles after that closing problem joins none, and one that is the + * talkback's first failure is reported then. + */ +export class SessionTalkback { + private readonly defer: SessionTalkbackOptions['defer'] + private readonly ended: SessionTalkbackOptions['ended'] + private readonly reporter: CameraReporter + private readonly sensorUUID: string + private readonly session: string + private readonly start: SessionTalkbackOptions['start'] + // What each failure of the talkback concerns: the sensor and the session. + private readonly fields: FailureFields + // What the plugin registered on the talker, released at the talkback's end and at a decline under the talker's own sentence. + private readonly scope: HandleScope + private sink?: TalkbackSink | null + private failedWrites = 0 + // Counts one failed write and reports the talkback's first as a plugin-failure problem, for a write that threw and for the rejection of a promise one + // returned alike. It is allocated once with the talkback, and a rejection is handed to it with no closure made per packet. + private readonly writeFailed = (error: unknown): void => { + if (++this.failedWrites === 1) { + this.reporter.failure('plugin-failure', 'TalkbackSink failed to write a packet', error, this.fields) + } + } + + /** + * Makes a session's talkback, holding no sink until its first write. + * @param options - The talkback's options. + */ + constructor(options: SessionTalkbackOptions) { + this.defer = options.defer + this.ended = options.ended + this.reporter = options.reporter + this.sensorUUID = options.sensorUUID + this.session = options.session + this.start = options.start + this.fields = { sensorUUID: options.sensorUUID, sessionIdentifier: options.sessionIdentifier } + this.scope = new HandleScope(`MultiTierStreamingDelegate failed to end the talkback of ${options.session}`, options.reporter, this.fields) + } + + /** + * Whether the delegate declined talkback or the talkback ended: a caller drops a talkback packet before any work on it. + */ + get closed(): boolean { + return this.sink === null + } + + /** + * Hands one talkback packet to the sink, starting the sink at the first, and writes nothing once the talkback is closed. The sink's write is plugin code + * running inside a listener, where a throw or a rejection no handler takes would end the process, which is why it is guarded, and the rejection of a promise it + * returns is guarded as a throw is. + * @param packet - The packet, in a buffer the sink may keep. + * @returns Whether the packet was handed to the sink's `write`, a write that throws or rejects among them: false once the talkback is closed and for the + * write whose start the delegate declined. + */ + write(packet: Buffer): boolean { + if (this.sink === null) { + return false + } + + const sink = this.sink ?? this.startSink() + + if (!sink) { + return false + } + + try { + const written: unknown = sink.write(packet) + + if (isThenable(written)) { + written.then(undefined, this.writeFailed) + } + } catch (error) { + this.writeFailed(error) + } + + return true + } + + /** + * Ends the talkback: the talkback is closed, which means a later write starts nothing, and what the plugin registered on the talker is released, a throw or a + * rejection of a cleanup reported under the talker's sentence as a plugin-failure problem. A second call does nothing, and the session's teardown runs + * this same end. The talker's registrations are released once, by whichever comes first. + */ + end(): void { + this.sink = null + this.scope.release() + } + + /** + * Reports, as the session's end or the talkback's own comes, whichever first, the one plugin-failure problem for the failed writes past the talkback's + * first, which was reported as it happened. + */ + logFailedWrites(): void { + const failed = this.failedWrites - 1 + + if (failed > 0) { + this.pluginFailed(`TalkbackSink failed ${failed} more ${nounFor(failed, 'write')} before ${this.session} ended.`) + } + } + + /* Asks the delegate for the sink at the talkback's first packet, with the talker made for it. Every answer that is no sink declines talkback at the one + * end after the call, which releases what the call registered: an answer of nothing, a throw, an answer whose `then` cannot be read, a promise and an + * answer with no `write` function. A promise is not awaited and never read as the talkback's sink. What it resolves to is never written, and what its + * function registers after the decline is released as it is registered, the scope being released by then. The call is plugin code that can end the + * session, which is why the exit is read again once it returns: an exit begun inside the call has the session's stack disposing already, and the talkback ends at + * once and the sink is written nothing. Otherwise the talkback's end stands on the stack above everything registered before it: every path that ends + * the session runs it first, and a talkback its own end reached first releases nothing a second time. + */ + private startSink(): TalkbackSink | null { + const { scope } = this + const talker: Talker = Object.freeze({ + defer: (release: () => unknown): void => scope.defer(release), + sensorUUID: this.sensorUUID, + use: (value: T): T => scope.use(value), + }) + let sink: TalkbackSink | undefined + + // The answer's then, and the write of an answer that is no thenable, are read inside the call the reporter's guard runs: a getter that throws is + // reported as the call's plugin-failure problem and declines talkback. A promise is handed back to the guard, which reports its rejection. + this.reporter.guard('plugin-failure', () => { + const answer = this.start(talker) + + if (isThenable(answer)) { + this.pluginFailed(`MultiTierStreamingDelegate answered talkbackStarted with a promise rather than a sink, and talkback is declined for ${this.session}.`) + + return answer + } + + if (answer && (typeof answer.write !== 'function')) { + this.pluginFailed(`MultiTierStreamingDelegate answered talkbackStarted with a sink that has no write function, and talkback is declined for ${this.session}.`) + } else { + sink = answer + } + + return undefined + }, 'MultiTierStreamingDelegate failed to start talkback', this.fields) + + if (!sink) { + this.end() + + return null + } + + this.sink = sink + + if (this.ended()) { + this.end() + + return null + } + + this.defer(() => this.end()) + + return sink + } + + // Reports a failure of the plugin's that carries no thrown value, its sink's or its start's, at the level the console errs at. + private pluginFailed(sentence: string): void { + this.reporter.problem({ + ...this.fields, + kind: 'plugin-failure', + level: 'error', + sentence, + }) + } +} diff --git a/src/lib/camera/session/StreamingEnabledSwitch.ts b/src/lib/camera/session/StreamingEnabledSwitch.ts new file mode 100644 index 000000000..545b43248 --- /dev/null +++ b/src/lib/camera/session/StreamingEnabledSwitch.ts @@ -0,0 +1,101 @@ +import type { Characteristic } from '../../Characteristic.js' +import type { StateChangeDelegate } from '../../controller/index.js' +import type { CameraChangeReason, StreamingEnabledChange } from '../OperatingModePolicy.js' + +import { CharacteristicEventTypes } from '../../Characteristic.js' +import { changeReason } from '../OperatingModePolicy.js' + +/** + * One stream service's own Streaming Enabled: it reports each change to the service's hook with the service's sensor and place and the change's value and + * reason, then calls the state-change delegate that persists it, and writes a restored value and the reset each under its own reason. The owner registers + * the listener at the point its own order needs and names what a change to false runs first, because the release of every held answer and the end of every + * session must come before the hook and the delegate, whose throw would otherwise leave them undone: an owner whose policy listener ends its sessions + * registers after that listener, and one that ends its own sessions passes that work to the listener. + */ +export class StreamingEnabledSwitch { + private readonly characteristic: Characteristic + private readonly sensorUUID: string + private readonly where: StreamingEnabledChange['where'] + private readonly onChange?: (change: StreamingEnabledChange) => void + private stateChangeDelegate?: StateChangeDelegate + // The reason the owner's own restore or reset gives the change of Streaming Enabled its write causes, unset for every other change. + private ownChange?: CameraChangeReason + + /** + * Holds one service's Streaming Enabled. The switch hears none of its changes until {@link listen} registers its listener. + * @param characteristic - The service's Streaming Enabled. + * @param sensorUUID - The video sensor the service streams, in lowercase, which each change reports. + * @param where - Whether the service streams views at home or from away, which each change reports. + * @param onChange - Called once for each change, before the state-change delegate. + */ + constructor(characteristic: Characteristic, sensorUUID: string, where: StreamingEnabledChange['where'], onChange?: (change: StreamingEnabledChange) => void) { + this.characteristic = characteristic + this.sensorUUID = sensorUUID + this.where = where + this.onChange = onChange + } + + /** + * The value of Streaming Enabled. + */ + get value(): boolean { + return Boolean(this.characteristic.value) + } + + /** + * Registers the switch's listener of Streaming Enabled. A change to false runs `onDisabled` first; each change then reaches the hook, reporting the + * restore's or the reset's reason for the owner's own writes and a write's or an update's for every other change, and then the state-change delegate. + * @param onDisabled - What a change to false runs before the hook and the state-change delegate, for an owner that ends its own sessions. + */ + listen(onDisabled?: () => void): void { + this.characteristic.on(CharacteristicEventTypes.CHANGE, ({ newValue, reason }) => { + if (!newValue) { + onDisabled?.() + } + + this.onChange?.({ + sensorUUID: this.sensorUUID, + where: this.where, + value: !!newValue, + reason: this.ownChange ?? changeReason(reason), + }) + this.stateChangeDelegate?.() + }) + } + + /** + * Writes a persisted value under the restore's reason, applying it only when it is a boolean. + * @param value - The persisted value. + */ + restore(value: unknown): void { + if (typeof value === 'boolean') { + this.write(value, 'restore') + } + } + + /** + * Writes the default, true, under the reset's reason. + */ + reset(): void { + this.write(true, 'reset') + } + + /** + * Sets the delegate a change of Streaming Enabled calls, which is how the owner persists it. + * @param delegate - The delegate, or `undefined` to clear it. + */ + setupStateChangeDelegate(delegate?: StateChangeDelegate): void { + this.stateChangeDelegate = delegate + } + + // The listener runs inside the update. The own-change reason it reports is set for exactly that change and cleared even when a listener throws. + private write(value: boolean, reason: CameraChangeReason): void { + this.ownChange = reason + + try { + this.characteristic.updateValue(value) + } finally { + this.ownChange = undefined + } + } +} diff --git a/src/lib/controller/CameraController.ts b/src/lib/controller/CameraController.ts index 9dd087130..538a37b3e 100644 --- a/src/lib/controller/CameraController.ts +++ b/src/lib/controller/CameraController.ts @@ -366,6 +366,38 @@ export enum CameraControllerEvents { SPEAKER_PROPERTIES_CHANGED = 'speaker-change', } +/** + * A live view, as the `live-view-started` and `live-view-ended` events tell of it, told apart by `where`: a view at home, which a session of the video + * sensor's Camera Multi-Tier RTP Stream Management streams from the one video tier its Start names, or a view from away, which a session of the sensor's + * Camera WebRTC Stream Management streams from every video tier. + * + * @group Camera + */ +export type CameraLiveView = { + /** + * The video sensor viewed, in lowercase. + */ + readonly sensorUUID: string + /** + * The identifier of the view's session. + */ + readonly sessionIdentifier: string +} & ({ + /** + * A view at home. + */ + readonly where: 'home' + /** + * The video tier the view streams. + */ + readonly tierId: number +} | { + /** + * A view from away. + */ + readonly where: 'away' +}) + export declare interface CameraController { on(event: 'microphone-change', listener: (muted: boolean, volume: number) => void): this on(event: 'speaker-change', listener: (muted: boolean, volume: number) => void): this diff --git a/src/test-utils/talkbackSink.ts b/src/test-utils/talkbackSink.ts new file mode 100644 index 000000000..9d075e109 --- /dev/null +++ b/src/test-utils/talkbackSink.ts @@ -0,0 +1,39 @@ +// The talkback sink every spec that hands a session's talkback to a plugin reads, in a module of its own. No spec imports another. +import type { Buffer } from 'node:buffer' +import type { Mock } from 'vitest' + +import type { TalkbackSink, Talker } from '../lib/camera/StreamingOptions.js' + +import { vi } from 'vitest' + +export interface KeepingSink { + sink: { write: Mock } + packets: Buffer[] + // The cleanup the start registers on its talker, a mock a row reads for the talker's release. + release: Mock<() => void> + // A talkbackStarted that registers the release on the talker it is handed and answers the sink. + start: (talker: Talker) => TalkbackSink +} + +// A talkback sink, write alone, that keeps each packet it is written as it was handed over, with no copy, which lets a row read the very buffers the session +// wrote. The sink comes with a start that registers a release of its own on its talker. +export function keepingSink(): KeepingSink { + const packets: Buffer[] = [] + const release = vi.fn<() => void>() + const sink = { + write: vi.fn((packet) => { + packets.push(packet) + }), + } + + return { + sink, + packets, + release, + start: (talker) => { + talker.defer(release) + + return sink + }, + } +} From b6fa9200ad227f43067cca4613240b10b9d2e2f9 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:51 -0600 Subject: [PATCH 14/16] feat(camera): stream live views from away through each video sensor's WebRTC stream management, on a WebRTC engine over werift --- eslint.config.mjs | 50 + package-lock.json | 148 +- package.json | 3 +- src/lib/camera/WebRTCStreamManagement.ts | 882 ++++++++++ src/lib/camera/index.ts | 1 + src/lib/camera/webrtc/EngineSession.spec.ts | 169 ++ src/lib/camera/webrtc/EngineSession.ts | 437 +++++ src/lib/camera/webrtc/WebRTCEngine.ts | 964 +++++++++++ .../camera/webrtc/sessionDescription.spec.ts | 168 ++ src/lib/camera/webrtc/sessionDescription.ts | 151 ++ src/lib/camera/webrtc/sframe.spec.ts | 376 ++++ src/lib/camera/webrtc/sframe.ts | 378 ++++ .../camera/webrtc/voice/ReceiveKeys.spec.ts | 154 ++ src/lib/camera/webrtc/voice/ReceiveKeys.ts | 85 + .../camera/webrtc/voice/ViewerVoice.spec.ts | 1527 +++++++++++++++++ src/lib/camera/webrtc/voice/ViewerVoice.ts | 779 +++++++++ src/lib/camera/webrtc/voice/opusVoice.spec.ts | 495 ++++++ src/lib/camera/webrtc/voice/opusVoice.ts | 249 +++ src/lib/camera/webrtc/werift.spec.ts | 197 +++ src/lib/camera/webrtc/werift.ts | 60 + src/test-utils/engineDebug.ts | 74 + src/test-utils/openingStamp.ts | 10 + src/test-utils/sframeVectors.ts | 763 ++++++++ src/test-utils/webRTCEngineFixtures.ts | 264 +++ tsconfig.json | 5 +- 25 files changed, 8385 insertions(+), 4 deletions(-) create mode 100644 src/lib/camera/WebRTCStreamManagement.ts create mode 100644 src/lib/camera/webrtc/EngineSession.spec.ts create mode 100644 src/lib/camera/webrtc/EngineSession.ts create mode 100644 src/lib/camera/webrtc/WebRTCEngine.ts create mode 100644 src/lib/camera/webrtc/sessionDescription.spec.ts create mode 100644 src/lib/camera/webrtc/sessionDescription.ts create mode 100644 src/lib/camera/webrtc/sframe.spec.ts create mode 100644 src/lib/camera/webrtc/sframe.ts create mode 100644 src/lib/camera/webrtc/voice/ReceiveKeys.spec.ts create mode 100644 src/lib/camera/webrtc/voice/ReceiveKeys.ts create mode 100644 src/lib/camera/webrtc/voice/ViewerVoice.spec.ts create mode 100644 src/lib/camera/webrtc/voice/ViewerVoice.ts create mode 100644 src/lib/camera/webrtc/voice/opusVoice.spec.ts create mode 100644 src/lib/camera/webrtc/voice/opusVoice.ts create mode 100644 src/lib/camera/webrtc/werift.spec.ts create mode 100644 src/lib/camera/webrtc/werift.ts create mode 100644 src/test-utils/engineDebug.ts create mode 100644 src/test-utils/openingStamp.ts create mode 100644 src/test-utils/sframeVectors.ts create mode 100644 src/test-utils/webRTCEngineFixtures.ts diff --git a/eslint.config.mjs b/eslint.config.mjs index ff7a83f07..06938df91 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -149,6 +149,56 @@ export default antfu( 'test/valid-title': 'error', }, }) + .append({ + // The number-based 64-bit helpers lose precision above 2^53, which is why none of these modules reaches them: the Camera Capabilities codecs carry every uint64 wire + // value as a bigint, the MP4 box readers carry decode times as bigints, the recording modules carry sequence numbers, key numbers and session identifiers + // as bigints, the camera session helpers hold the sessions that carry those values, the SRTP context keeps its packet index exact as Numbers and reaches + // none of these helpers, the multi-tier stream management carries every session value as a Number or a Buffer and reaches no number-based 64-bit helper, + // the WebRTC stream management hands SFrame key IDs to its delegate as the bigints the codecs decode, the DER writer takes every INTEGER as a bigint, the + // NTP conversion answers its 64-bit fixed-point time as a bigint, and the recording provisioning record keeps the Camera Key's number and its high-water + // marks as bigints. + files: [ + 'src/lib/camera/capabilities/**/*.ts', + 'src/lib/camera/mp4/**/*.ts', + 'src/lib/camera/recording/**/*.ts', + 'src/lib/camera/session/**/*.ts', + 'src/lib/camera/srtp/**/*.ts', + 'src/lib/camera/MultiTierStreamManagement.ts', + 'src/lib/camera/WebRTCStreamManagement.ts', + 'src/lib/util/der.ts', + 'src/lib/util/ntp.ts', + 'src/lib/model/RecordingProvisioning.ts', + ], + rules: { + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + regex: '(?:^|/)util/tlv\\.js$', + importNames: ['readUInt64LE', 'readVariableUIntLE', 'writeVariableUIntLE'], + message: 'Read and write 64-bit integers as bigint through readBigUInt64LE and writeBigUInt64LE.', + }, + { + regex: '(?:^|/)util/hapCrypto\\.js$', + importNames: ['writeUInt64LE'], + message: 'Write 64-bit integers as bigint through writeBigUInt64LE from tlv.js.', + }, + { + regex: '(?:^|/)util/time\\.js$', + importNames: ['epochMillisFromMillisSince2001_01_01Buffer'], + message: 'Read 64-bit integers as bigint through readBigUInt64LE from tlv.js.', + }, + { + regex: '(?:^|/)datastream/(?:index|DataStreamParser)\\.js$', + importNames: ['Int64'], + message: 'Carry 64-bit integers as bigint, which Int64 cannot hold exactly.', + }, + ], + }, + ], + }, + }) .append({ // A constant set and the type derived from it share one name in the capability codecs, which this rule reads as a redeclaration. files: ['src/lib/camera/capabilities/**/*.ts'], diff --git a/package-lock.json b/package-lock.json index 73e946f06..e32415a3a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,7 +14,8 @@ "dbus-native": "^0.16.3", "debug": "^4.4.3", "fast-srp-hap": "2.0.5", - "source-map-support": "^0.5.21" + "source-map-support": "^0.5.21", + "werift": "0.28.0" }, "devDependencies": { "@antfu/eslint-config": "^10.0.0", @@ -1048,6 +1049,24 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "peer": true, + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@eslint/config-helpers": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", @@ -2156,6 +2175,21 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/dom-mediacapture-transform": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz", + "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==", + "license": "MIT", + "dependencies": { + "@types/dom-webcodecs": "*" + } + }, + "node_modules/@types/dom-webcodecs": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz", + "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==", + "license": "MIT" + }, "node_modules/@types/escape-html": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/@types/escape-html/-/escape-html-1.0.4.tgz", @@ -2826,7 +2860,6 @@ "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "dev": true, "funding": [ { "type": "github", @@ -2958,6 +2991,30 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -4206,6 +4263,24 @@ "node": ">= 4" } }, + "node_modules/eslint/node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "peer": true, + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/espree": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", @@ -4545,6 +4620,23 @@ "node": ">=10.13.0" } }, + "node_modules/glob/node_modules/minimatch": { + "version": "11.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz", + "integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/globals": { "version": "17.14.0", "resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz", @@ -4634,6 +4726,26 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/ignore": { "version": "7.0.16", "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.16.tgz", @@ -5608,6 +5720,24 @@ "dev": true, "license": "MIT" }, + "node_modules/mediabunny": { + "version": "1.66.2", + "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.66.2.tgz", + "integrity": "sha512-NTzRrBhAyRVi8qpJ9AH6XPyxiDVkfugxYY+gu3Z5zi+Nw2R/7nTAnXJEt2Ucy8wTIve1/UYGnCFf50x2LpvMDQ==", + "license": "MPL-2.0", + "workspaces": [ + ".", + "packages/*" + ], + "dependencies": { + "@types/dom-mediacapture-transform": "^0.1.11", + "@types/dom-webcodecs": "0.1.13" + }, + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/Vanilagy" + } + }, "node_modules/micromark": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", @@ -7776,6 +7906,20 @@ "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0" } }, + "node_modules/werift": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/werift/-/werift-0.28.0.tgz", + "integrity": "sha512-Ro4r5OOtcLgx4VbrXGRS80sNZHptLIyJ2o/EGOj6dyRksTbiTLbtP/u2psDIpsXUOYl3vW+aK3YBPsKPl9SxJw==", + "license": "MIT", + "dependencies": { + "buffer": "^6.0.3", + "mediabunny": "^1.62.1", + "multicast-dns": "^7.2.5" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index a1dca9576..8df5377db 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,8 @@ "dbus-native": "^0.16.3", "debug": "^4.4.3", "fast-srp-hap": "2.0.5", - "source-map-support": "^0.5.21" + "source-map-support": "^0.5.21", + "werift": "0.28.0" }, "devDependencies": { "@antfu/eslint-config": "^10.0.0", diff --git a/src/lib/camera/WebRTCStreamManagement.ts b/src/lib/camera/WebRTCStreamManagement.ts new file mode 100644 index 000000000..fc8de29b4 --- /dev/null +++ b/src/lib/camera/WebRTCStreamManagement.ts @@ -0,0 +1,882 @@ +import type { Buffer } from 'node:buffer' + +import type { CameraLiveView, ControllerServiceMap, StateChangeDelegate } from '../controller/index.js' +import type { CameraWebRTCStreamManagement } from '../definitions/index.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { SupportedAudioStreamTiersPayload, SupportedVideoStreamTiersPayload } from './capabilities/streamTiers.js' +import type { + WebRTCProvideAnswerRequest, + WebRTCReofferRequest, + WebRTCReofferResponse, + WebRTCSessionStatusResponse, + WebRTCSolicitOfferRequest, + WebRTCSolicitOfferResponse, + WebRTCStreamingControlRequest, + WebRTCUpdateSessionRequest, +} from './capabilities/webrtc.js' +import type { CameraReporter, DebugWriter, FailureFields } from './diagnostics/CameraReporter.js' +import type { StreamGate, StreamingEnabledChange } from './OperatingModePolicy.js' + +import crypto from 'node:crypto' + +import { Characteristic } from '../Characteristic.js' +import { HAPStatus } from '../HAPServer.js' +import { Service } from '../Service.js' +import { HapStatusError } from '../util/hapStatusError.js' +import * as uuid from '../util/uuid.js' +import { encodeSupportedAudioStreamTiers, encodeSupportedVideoStreamTiers } from './capabilities/streamTiers.js' +import { + decodeWebRTCProvideAnswerRequest, + decodeWebRTCReofferRequest, + decodeWebRTCSolicitOfferRequest, + decodeWebRTCStreamingControlRequest, + decodeWebRTCUpdateSessionRequest, + encodeWebRTCReofferResponse, + encodeWebRTCSessionStatusResponse, + encodeWebRTCSolicitOfferResponse, + WebRTCSolicitOfferStatus, + WebRTCStreamingStatus, +} from './capabilities/webrtc.js' +import { reconcileSensorServices, sensorServiceKey } from './capabilityKeys.js' +import { debugChannel, inspectInline } from './diagnostics/debugChannels.js' +import { CommandQueue } from './session/CommandQueue.js' +import { ConnectionSessions } from './session/ConnectionSessions.js' +import { wireControlPoint } from './session/controlPoint.js' +import { DELEGATE_CALL_TIMEOUT, settleWithinBound } from './session/settleWithin.js' +import { StreamingEnabledSwitch } from './session/StreamingEnabledSwitch.js' + +const WEBRTC_DEBUG = debugChannel('HAP-NodeJS:Camera:WebRTC') + +// The spec's floor of simultaneous WebRTC sessions, which a camera must support, the default capacity, and the floor below which the camera controller +// reads a camera's bound as a minimum of the specification. +export const WEBRTC_MINIMUM_SESSIONS = 6 +// The largest count WebRTC Number of Active Sessions, a uint8, can carry. +const MAX_SESSIONS = 255 + +// The reason the exit's debug event gives a session endSession ends, alone or among every session the owner ends at once. +const ENDED_BY_OWNER = 'its engine or its owner ended it' + +/* An offered session whose answer has not been accepted within this bound ends. HAP answers a write once the accessory's own write timeout passes, well + * inside this bound, while its handler keeps running. A controller can give up on a Solicit Offer whose session the library has registered, and an + * offered session the controller never learned of is routine; a hub's connection can live for days, and its close alone would hold that session's slot + * for as long. + */ +const OFFER_ANSWER_TIMEOUT = 60 * 1000 + +/** + * The request {@link WebRTCStreamEngine.createOffer} receives: the controller's offer options, the identifier the library minted for the session, the + * video sensor the session streams from, the HAP connection that opened the session, a signal that aborts when the session ends, and the camera's + * reporter. + */ +export interface WebRTCOfferRequest extends WebRTCSolicitOfferRequest { + /** + * The UUID identifying the session, which every later call for the session names. + */ + sessionIdentifier: string + /** + * The lowercase UUID of the video sensor the session streams from. One engine can serve the service of every sensor a camera has, and without it the + * engine could stream a session another sensor's video. + */ + sensorUUID: string + /** + * The HAP connection that opened the session, which the engine's session names as it joins the sensor's tiers, as a session at home does: a demand + * it raises cuts packets of the size that connection's HAP server decides. + */ + connection: HAPConnection + /** + * Aborts when the session ends, whichever path ends it, which lets the engine abandon the offer and the media it prepared. + */ + signal: AbortSignal + /** + * The reporter of the camera whose management solicited the session, which the engine's session keeps for every report of that session: each names + * the configuration that made it. + */ + reporter: CameraReporter +} + +/** + * The offer {@link WebRTCStreamEngine.createOffer} answers with: the SDP offer, the ICE candidates it does not carry, and the SFrame key of the session's + * media, which the library's engine returns with every offer. + */ +export type WebRTCOffer = Omit, 'sessionIdentifier' | 'status'> + +/** + * The controller's answer {@link WebRTCStreamEngine.acceptAnswer} receives: the SDP answer and the ICE candidates it does not carry. + */ +export type WebRTCAnswer = Omit + +/** + * The controller's renegotiation {@link WebRTCStreamEngine.reoffer} receives: its SDP offer and its offer options. + */ +export type WebRTCReoffer = Omit + +/** + * The answer {@link WebRTCStreamEngine.reoffer} answers with: the SDP answer, and the SFrame key of the session's media when it changes. + */ +export type WebRTCReofferAnswer = Omit, 'sessionIdentifier' | 'status'> + +/** + * The receive keys {@link WebRTCStreamEngine.updateReceiveKeys} receives: the SFrame keys to add and the key IDs of those to remove. + */ +export type WebRTCReceiveKeysUpdate = Omit + +/** + * The library's WebRTC engine, as a {@link WebRTCStreamManagement} calls it. The library owns the signaling, the sessions and their identifiers; the engine + * owns the media, from ICE and DTLS-SRTP to SFrame. Each method mirrors a step of the WebRTC call sequence and answers through its promise, and a + * rejection answers the controller with an error status. + * + * A session is registered before {@link createOffer} is called, which means an exit can reach the engine while its offer is still pending. Every session ends + * exactly once, whatever ends it: the controller's End, its connection closing, Streaming Enabled turning off, the offer expiring unanswered, a call cut at + * its bound, a failed {@link createOffer} or {@link acceptAnswer}, an offer the Solicit Offer response cannot carry, the engine's own + * {@link WebRTCStreamManagement.endSession}, or the owner's {@link WebRTCStreamManagement.handleFactoryReset}, {@link WebRTCStreamManagement.endAllSessions} + * or {@link WebRTCStreamManagement.destroy}. At that exit the offer request's signal aborts first, cancelling any call still in flight, and + * {@link endSession} follows as the session's teardown. + * + * The engine owns each receive key from the {@link updateReceiveKeys} call that hands it over, and the library keeps none: the engine zeroes a key at its + * removal, at its replacement, once the keys it holds for the session pass their bound, and at the session's teardown, and zeroes at once a key it does + * not take. A key the engine returns stays the engine's, and the library never alters it. + */ +export interface WebRTCStreamEngine { + /** + * Creates the offer of a session the controller solicited. + * @param request - The session's offer request. + * @returns The offer. + */ + createOffer(request: WebRTCOfferRequest): Promise + /** + * Accepts the controller's answer and establishes the session's media; the session counts as active once this resolves. + * @param sessionIdentifier - The session's identifier. + * @param answer - The controller's answer. + */ + acceptAnswer(sessionIdentifier: string, answer: WebRTCAnswer): Promise + /** + * Renegotiates an active session. + * @param sessionIdentifier - The session's identifier. + * @param offer - The controller's offer. + * @returns The answer. + */ + reoffer(sessionIdentifier: string, offer: WebRTCReoffer): Promise + /** + * Adds and removes the SFrame keys the session's received media is protected with. + * @param sessionIdentifier - The session's identifier. + * @param update - The keys to add and the key IDs to remove. + * @param reporter - The reporter of the camera whose management calls, which the engine reports through where it holds no session of that identifier. + */ + updateReceiveKeys(sessionIdentifier: string, update: WebRTCReceiveKeysUpdate, reporter: CameraReporter): Promise + /** + * Tears down a session that has ended; called once per session, after its signal has aborted. + * @param sessionIdentifier - The session's identifier. + * @param reporter - The reporter of the camera whose management calls, which the engine reports through where it holds no session of that identifier. + */ + endSession(sessionIdentifier: string, reporter: CameraReporter): Promise +} + +/** + * The settings of a camera's WebRTC streaming, as the camera controller's capabilities block carries them. Every camera with the block answers views + * from away, the library's own engine answering the Camera WebRTC Stream Management service of every video sensor the camera has, and these settings + * alone are the plugin's to give. + * + * @group Camera + */ +export interface WebRTCStreamingOptions { + /** + * The most sessions each video sensor's Camera WebRTC Stream Management service holds at once, offered or active: an integer from 1 to 255, and 6 by + * default, the specification's floor. A value below the floor is taken as given, with a debug event under `HAP-NodeJS:Camera:Controller`, and refused + * under the camera capabilities block's `strict`. + */ + maxSessions?: number + /** + * Which of a viewer's two voice streams a view from away writes to that viewer's talkback sink: `'automatic'`, the default, plays the better stream, + * which carries a wider band, while it keeps pace with the dependable one and, once it has fallen behind, again after it has kept pace for a + * second, each change falling between packets so nothing is played twice, and `'dependable'` plays the dependable stream alone. + */ + voice?: 'automatic' | 'dependable' +} + +/** + * The options of a {@link WebRTCStreamManagement}, one per video sensor. + */ +export interface WebRTCStreamManagementOptions { + /** + * The engine that answers the service's sessions. + */ + engine: WebRTCStreamEngine + /** + * The camera's reporter, through which a failed engine call is the library's failure, and which each offer request and each call naming a session hands + * the engine. + */ + reporter: CameraReporter + /** + * The video stream tiers WebRTC Supported Video Stream Tiers advertises. + */ + videoStreamTiers: SupportedVideoStreamTiersPayload + /** + * The audio stream tiers WebRTC Supported Audio Stream Tiers advertises, which hold exactly one tier. + */ + audioStreamTiers: SupportedAudioStreamTiersPayload + /** + * The UUID of the video sensor the service streams, which Sensor UUID carries and the service's subtype is derived from. + */ + sensorUUID: string + /** + * The most sessions the service holds at once, offered or active, as {@link webRTCMaxSessions} validated it. + */ + maxSessions: number + /** + * Called once for each connected session as its exit takes it off Number of Active Sessions, in the exit's own turn. + */ + onLiveViewEnded?: (view: CameraLiveView) => void + /** + * Called once for each session whose answer is accepted, as it joins Number of Active Sessions, whether or not its media connects after. + */ + onLiveViewStarted?: (view: CameraLiveView) => void + /** + * Called once for each change of the service's Streaming Enabled, before the state-change delegate. + */ + onStreamingEnabledChange?: (change: StreamingEnabledChange) => void +} + +/** + * The persisted state of a video sensor's Camera WebRTC Stream Management service. + */ +export interface WebRTCStreamManagementState { + /** + * The value of Streaming Enabled. + */ + streamingEnabled: boolean +} + +// A registered session is offered from its Solicit Offer until its answer is accepted, and connected after. +type WebRTCSessionState = 'offered' | 'connected' + +// What a session's exit and its problems reach in the management that registered it, beside the session table: the engine, the camera's reporter, which +// the teardown's guard and every problem of the session's report through and the teardown hands the engine, and the sensor the session streams from, in +// lowercase, which each of those reports names. +interface WebRTCSessionContext { + readonly engine: WebRTCStreamEngine + readonly reporter: CameraReporter + readonly sensorUUID: string + // Decrements Number of Active Sessions and notifies it, and tells of the session's view's end, for a connected session's exit. + readonly disconnected: (sessionIdentifier: string) => void +} + +/* A registered session: its identifier, the connection that opened it, its state, and the abort controller whose signal its engine calls carry. Its + * disposal is the one exit routine every path that ends a session runs, through the session table's exit. + */ +class WebRTCSession implements AsyncDisposable { + readonly sessionIdentifier: string + readonly connection: HAPConnection + state: WebRTCSessionState = 'offered' + readonly controller = new AbortController() + // What a failed engine call on the session concerns: its sensor and the session. + readonly fields: FailureFields + // The signal the library's waits on the session carry: the controller's, composed with the offer expiry while the session is offered. + signal: AbortSignal + private readonly expiry: AbortSignal + private readonly sessions: ConnectionSessions + readonly context: WebRTCSessionContext + + constructor(sessionIdentifier: string, connection: HAPConnection, sessions: ConnectionSessions, context: WebRTCSessionContext) { + this.sessionIdentifier = sessionIdentifier + this.connection = connection + this.sessions = sessions + this.context = context + this.fields = { sensorUUID: context.sensorUUID, sessionIdentifier } + this.expiry = AbortSignal.timeout(OFFER_ANSWER_TIMEOUT) + this.signal = AbortSignal.any([this.controller.signal, this.expiry]) + this.expiry.addEventListener('abort', this.expire, { once: true }) + } + + // The accepted answer connects the session, and a connected session never expires. + connect(): void { + this.state = 'connected' + this.signal = this.controller.signal + this.expiry.removeEventListener('abort', this.expire) + } + + // Ends the session through the session table's exit, for every path that ends it from outside the management's own commands. + async exit(reason: string): Promise { + await this.sessions.exit(this, reason) + } + + /* The exit's disposal. Its opening in the session table removes the session and releases its connection's held answers, and guards the rest: a close, + * an End or the engine's endSession arriving while the exit runs finds the session gone, and a disposal that finds nothing to remove has run already. + * The answers go before the engine's endSession: a read during that bounded wait answers the empty value. A connected session leaves Number of Active + * Sessions and its view ends in the same turn, ahead of every await. The end of a removal reaches the camera's listeners before the controller drops + * them. + */ + async [Symbol.asyncDispose](): Promise { + if (!this.sessions.beginDisposal(this)) { + return + } + + this.expiry.removeEventListener('abort', this.expire) + this.controller.abort() + + if (this.state === 'connected') { + this.context.disconnected(this.sessionIdentifier) + } + + const { engine, reporter } = this.context + const pending = (async () => engine.endSession(this.sessionIdentifier, reporter))() + // The teardown's guard takes no signal, since the session's has aborted before the call. A rejected teardown is always the engine's own failure. + reporter.rejection('library-failure', pending, 'The WebRTC engine failed to end a session', undefined, this.fields) + + // The session's signal has aborted already, and the wait for its teardown is bounded by the call bound alone. + if ((await settleWithinBound(pending)).cutAtBound) { + warnCut(this.context, 'endSession', this.sessionIdentifier) + } + } + + // An offered session whose answer is not accepted within OFFER_ANSWER_TIMEOUT ends like a close, with one view-failed problem, since its controller has + // likely moved on. + private readonly expire = (): void => { + const { reporter, sensorUUID } = this.context + + reporter.problem({ + kind: 'view-failed', + level: 'warning', + sensorUUID, + sentence: `WebRTC session ${this.sessionIdentifier} had no answer to its offer accepted within ${OFFER_ANSWER_TIMEOUT / 1000} seconds. The session ends.`, + sessionIdentifier: this.sessionIdentifier, + }) + void this.exit('its offer expired') + } +} + +/* Awaits an engine call on a session until it settles or its wait is cut, by the session's exit or at DELEGATE_CALL_TIMEOUT. A cut at the bound raises a + * library-failure problem and ends the session: a call that never settles releases the service's queue, and the caller then finds the session gone + * from the table. Each call's guard takes the signal of the session's controller, `session.controller.signal`, which aborts at the session's end alone, + * while the wait here reads `session.signal`, the controller's joined with the offer's expiry. A rejection that settles once the session has ended, + * which follows the library's own end of it rather than the engine's failure, is not reported, and a call cut at the bound has raised its problem before + * that end. + */ +async function awaitEngine(session: WebRTCSession, call: string, pending: Promise): Promise<{ value: T } | undefined> { + const { cutAtBound, outcome } = await settleWithinBound(pending, session.signal) + + if (cutAtBound) { + warnCut(session.context, call, session.sessionIdentifier) + await session.exit(`${call} was cut at its bound`) + } + + return outcome +} + +// An engine call cut at its bound raises one library-failure problem, naming the call, the session and the bound, because the cut ends a session the +// engine may still be serving. +function warnCut({ reporter, sensorUUID }: WebRTCSessionContext, call: string, sessionIdentifier: string): void { + reporter.problem({ + kind: 'library-failure', + level: 'warning', + sensorUUID, + sentence: `The WebRTC engine did not settle ${call} for WebRTC session ${sessionIdentifier} within ${DELEGATE_CALL_TIMEOUT / 1000} seconds, ` + + 'and the session ends without it.', + sessionIdentifier, + }) +} + +// An engine result its response cannot carry raises one library-failure problem, naming the call, the session and the encoder's message, because only an +// engine defect reaches it. +function warnUnencodable({ reporter, sensorUUID }: WebRTCSessionContext, call: string, sessionIdentifier: string, error: unknown, outcome: string): void { + reporter.problem({ + error, + kind: 'library-failure', + level: 'warning', + sensorUUID, + sentence: `The WebRTC engine answered ${call} for WebRTC session ${sessionIdentifier} with a value its response cannot carry ` + + `(${(error as Error | undefined)?.message ?? String(error)}): ${outcome}.`, + sessionIdentifier, + }) +} + +function zero(keys: readonly Buffer[]): void { + for (const key of keys) { + key.fill(0) + } +} + +/** + * The bound a WebRTC stream management holds its sessions to, defaulted and validated once, by the camera controller as it is constructed, which hands + * each management the value. It refuses only a bound Number of Active Sessions cannot carry. A bound below the specification's floor is taken here and + * the controller writes it as a debug event, or refuses it under `strict`. + * @param maxSessions - The bound, or `undefined` for the default. + * @returns The bound, 6 by default. + * @throws TypeError for a bound that is not an integer from 1 to 255. + */ +export function webRTCMaxSessions(maxSessions = WEBRTC_MINIMUM_SESSIONS): number { + if (!Number.isInteger(maxSessions) || (maxSessions < 1) || (maxSessions > MAX_SESSIONS)) { + throw new TypeError(`The WebRTC stream management takes a maxSessions that is an integer from 1 to ${MAX_SESSIONS}, but ${maxSessions} is not one.`) + } + + return maxSessions +} + +/** + * Serves one Camera WebRTC Stream Management service: it runs the WebRTC call sequence against a {@link WebRTCStreamEngine}, keys each session by the + * connection that opened it and ends it when that connection closes, answers a command naming the session from any other connection with Unknown Session + * Identifier, answers every protocol outcome in the write response's status but one, a Solicit Offer while the camera is out of service, which fails the + * write with the communication failure, and persists its Streaming Enabled. + * + * Every control point is transient by its definition: its write response and a plain read on the writer's connection carry that writer's last answer + * alone, until its session ends, the service is destroyed or reset, Streaming Enabled turns off or the owner ends every session, and every other plain read + * answers an empty TLV. The service runs its writes one at a time. A capacity check, the change to the session table and the response are atomic across + * the engine's awaits. A response the codec cannot carry for a value the engine returned takes the answer of a failed engine call: Solicit Offer ends the + * session and answers Error, and Reoffer answers Error and keeps the session. A malformed write, or one a plugin makes without a connection, fails with + * {@link HAPStatus.INVALID_VALUE_IN_REQUEST}, and a Solicit Offer while the camera is out of service with {@link HAPStatus.SERVICE_COMMUNICATION_FAILURE}. + */ +export class WebRTCStreamManagement { + /** + * The service's key, in the camera's service map and in the policy alike. + * @private + */ + readonly serviceKey: string + private readonly engine: WebRTCStreamEngine + private readonly reporter: CameraReporter + // The camera's reporter's debug events on the service's debug name, which the session table and every control point write through as well. + private readonly debug: DebugWriter + private readonly streamGate: () => StreamGate + private readonly maxSessions: number + private readonly sensorUUID: string + private readonly service: CameraWebRTCStreamManagement + private readonly streamingEnabled: StreamingEnabledSwitch + private readonly queue = new CommandQueue() + private readonly sessions: ConnectionSessions + private readonly context: WebRTCSessionContext + // The hook a session's view is told of through as its answer is accepted. + private readonly onLiveViewStarted?: (view: CameraLiveView) => void + private activeSessions = 0 + + /** + * Validates the options, then adopts the saved service or builds one, and sets its static characteristics. It throws a `TypeError` for a sensor UUID + * that is not a UUID, audio stream tiers that do not hold exactly one tier, and stream tiers their characteristics cannot encode, and takes the + * `maxSessions` it is handed, which the camera controller validated. + * @param options - The service's options. + * @param streamGate - Reads the service's gate as the camera's state sets it, beside the service's own Streaming Enabled: a Solicit Offer is answered + * Privacy Mode Active while it reads switched off and fails with the communication failure while it reads out of service. + * @param service - A saved service to adopt, which keeps its Streaming Enabled. + */ + constructor(options: WebRTCStreamManagementOptions, streamGate: () => StreamGate, service?: CameraWebRTCStreamManagement) { + const { audioStreamTiers, engine, maxSessions, onLiveViewEnded, onLiveViewStarted, onStreamingEnabledChange, reporter, sensorUUID, videoStreamTiers } = options + + if (!uuid.isValid(sensorUUID)) { + throw new TypeError(`The WebRTC stream management takes a sensor UUID, but "${sensorUUID}" is not one.`) + } + + if (audioStreamTiers.tiers.length !== 1) { + throw new TypeError(`The WebRTC stream management takes exactly one audio stream tier, but ${audioStreamTiers.tiers.length} were supplied.`) + } + + let supportedVideoStreamTiers: string + let supportedAudioStreamTiers: string + try { + supportedVideoStreamTiers = encodeSupportedVideoStreamTiers(videoStreamTiers) + supportedAudioStreamTiers = encodeSupportedAudioStreamTiers(audioStreamTiers) + } catch (error) { + throw new TypeError('The WebRTC stream management has stream tiers that WebRTC Supported Video or Audio Stream Tiers cannot encode.', { cause: error }) + } + + this.engine = engine + this.reporter = reporter + this.debug = reporter.writer(WEBRTC_DEBUG) + this.streamGate = streamGate + this.maxSessions = maxSessions + this.sensorUUID = sensorUUID.toLowerCase() + this.serviceKey = WebRTCStreamManagement.serviceKey(this.sensorUUID) + this.onLiveViewStarted = onLiveViewStarted + this.context = { + engine, + reporter, + sensorUUID: this.sensorUUID, + disconnected: (sessionIdentifier) => { + this.countSessions(-1) + onLiveViewEnded?.(this.liveView(sessionIdentifier)) + }, + } + this.service = service ?? this.constructService(this.sensorUUID) + this.sessions = new ConnectionSessions(this.service, this.debug, 'WebRTC') + this.streamingEnabled = new StreamingEnabledSwitch(this.service.getCharacteristic(Characteristic.StreamingEnabled), this.sensorUUID, 'away', onStreamingEnabledChange) + + this.service.updateCharacteristic(Characteristic.SensorUUID, uuid.write(sensorUUID).toString('base64')) + this.service.updateCharacteristic(Characteristic.WebRTCSupportedVideoStreamTiers, supportedVideoStreamTiers) + this.service.updateCharacteristic(Characteristic.WebRTCSupportedAudioStreamTiers, supportedAudioStreamTiers) + this.service.updateCharacteristic(Characteristic.WebRTCNumberOfActiveSessions, this.activeSessions) + this.setupServiceHandlers() + } + + /** + * The key a video sensor's service carries in the camera's service map and in the policy. + * @param sensorUUID - The video sensor's UUID. + * @returns The capability prefix, `webRTCStream:` and the UUID in lowercase. + * @private + */ + static serviceKey(sensorUUID: string): string { + return sensorServiceKey('webRTCStream', sensorUUID) + } + + /** + * Reconciles every video sensor's service in a restored service map, in the order given: a sensor's saved service under its key is adopted, and a sensor + * without one gets a new service, inserted. The key of a sensor missing from the camera's inventory is left to the capability key sweep. + * @param serviceMap - The camera's service map, changed in place. + * @param sensors - Each video sensor's options, in the camera's order. + * @param create - Builds a sensor's management over its saved service, or over a new one when it is given none. + * @returns Whether the map changed. + * @private + */ + static reconcile( + serviceMap: ControllerServiceMap, + sensors: readonly WebRTCStreamManagementOptions[], + create: (options: WebRTCStreamManagementOptions, service?: CameraWebRTCStreamManagement) => WebRTCStreamManagement, + ): boolean { + return reconcileSensorServices( + serviceMap, + sensors, + options => WebRTCStreamManagement.serviceKey(options.sensorUUID), + (options, service?: CameraWebRTCStreamManagement) => create(options, service).getService(), + ) + } + + /** + * The Camera WebRTC Stream Management service. + * @returns The service. + */ + getService(): CameraWebRTCStreamManagement { + return this.service + } + + /** + * The state to persist. + * @returns The value of Streaming Enabled. + * @private + */ + serialize(): WebRTCStreamManagementState { + return { + streamingEnabled: this.streamingEnabled.value, + } + } + + /** + * Restores persisted state, applying its Streaming Enabled when it is a boolean. + * @param state - The persisted state. + * @private + */ + deserialize(state: WebRTCStreamManagementState): void { + this.streamingEnabled.restore(state.streamingEnabled) + } + + /** + * Sets the delegate a change of Streaming Enabled calls, which is how the owner persists it. + * @param delegate - The delegate, or `undefined` to clear it. + * @private + */ + setupStateChangeDelegate(delegate?: StateChangeDelegate): void { + this.streamingEnabled.setupStateChangeDelegate(delegate) + } + + /** + * Releases every answer the control points hold, ends every session and then restores Streaming Enabled to its default, true. + */ + handleFactoryReset(): void { + void this.endAllSessions() + this.streamingEnabled.reset() + } + + /** + * Ends a session, as the engine does when its media fails. An identifier no registered session carries is ignored. + * @param sessionIdentifier - The session's identifier. + */ + async endSession(sessionIdentifier: string): Promise { + await this.sessions.end(sessionIdentifier, ENDED_BY_OWNER) + } + + /** + * Releases every answer the control points hold, then ends every session, as the owner does when the camera's state stops allowing sessions. A connection + * can hold an answer with no session left, which is why the release reaches every connection and not only those whose sessions end here. + */ + async endAllSessions(): Promise { + await this.sessions.endAll(ENDED_BY_OWNER) + } + + /** + * Ends every session, releases every answer the control points hold and answers each later write without a session, before the service is dropped. + */ + async destroy(): Promise { + this.sessions.markDestroyed() + await this.endAllSessions() + } + + // A service this class builds is keyed by the sensor's UUID, in lowercase: the sensor's identity and not its position binds it. + private constructService(subtype: string): CameraWebRTCStreamManagement { + const service = new Service.CameraWebRTCStreamManagement('', subtype) + service.updateCharacteristic(Characteristic.StreamingEnabled, true) + + return service + } + + private setupServiceHandlers(): void { + // The release and the session end, which endAllSessions makes, come before the hook and the state-change delegate, whose throw would otherwise leave a + // disabled service's answers held and its sessions live; the release reaches a connection whose answer has no session left too. + this.streamingEnabled.listen(() => void this.endAllSessions()) + + wireControlPoint( + this.service.getCharacteristic(Characteristic.WebRTCSolicitOffer), + this.queue, + this.debug, + decodeWebRTCSolicitOfferRequest, + this.solicitOffer.bind(this), + encodeWebRTCSolicitOfferResponse, + this.refuseOffer.bind(this), + ) + wireControlPoint( + this.service.getCharacteristic(Characteristic.WebRTCProvideAnswer), + this.queue, + this.debug, + decodeWebRTCProvideAnswerRequest, + this.provideAnswer.bind(this), + encodeWebRTCSessionStatusResponse, + ) + wireControlPoint( + this.service.getCharacteristic(Characteristic.WebRTCStreamingControl), + this.queue, + this.debug, + decodeWebRTCStreamingControlRequest, + this.streamingControl.bind(this), + encodeWebRTCSessionStatusResponse, + ) + wireControlPoint( + this.service.getCharacteristic(Characteristic.WebRTCReoffer), + this.queue, + this.debug, + decodeWebRTCReofferRequest, + this.reoffer.bind(this), + encodeWebRTCReofferResponse, + this.refuseReofferAnswer.bind(this), + ) + wireControlPoint( + this.service.getCharacteristic(Characteristic.WebRTCUpdateSession), + this.queue, + this.debug, + decodeWebRTCUpdateSessionRequest, + this.updateSession.bind(this), + encodeWebRTCSessionStatusResponse, + ) + } + + private countSessions(change: 1 | -1): void { + this.activeSessions += change + this.service.updateCharacteristic(Characteristic.WebRTCNumberOfActiveSessions, this.activeSessions) + } + + // The view a session from away is, as the live-view events tell of it: of the sensor, from every video tier. + private liveView(sessionIdentifier: string): CameraLiveView { + return { sensorUUID: this.sensorUUID, sessionIdentifier, where: 'away' } + } + + private async solicitOffer(request: WebRTCSolicitOfferRequest, connection: HAPConnection): Promise { + if (!this.sessions.serves(connection)) { + return { status: WebRTCSolicitOfferStatus.ERROR } + } + + // A camera its user switched off, or a service whose own Streaming Enabled is off, answers Privacy Mode Active, the user's switch read first, and a + // camera out of service fails the write with the communication failure, after one debug event of its own, before any session is made or the engine is + // called. + const gate = this.streamingEnabled.value + ? this.streamGate() + : 'switched off' + + if (gate === 'switched off') { + return { status: WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE } + } + + if (gate === 'out of service') { + this.debug('offer-out-of-service', () => ({ + sentence: 'Solicit Offer fails with the communication failure while the camera is out of service.', + })) + throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + if (this.sessions.size >= this.maxSessions) { + return { status: WebRTCSolicitOfferStatus.ERROR } + } + + // The session registers before the engine is asked for its offer, and a teardown during that wait reaches the engine through the session's exit. + const sessionIdentifier = crypto.randomUUID() + const session = new WebRTCSession(sessionIdentifier, connection, this.sessions, this.context) + this.sessions.add(session) + + const pending = (async () => this.engine.createOffer({ + options: request.options, + sessionIdentifier, + sensorUUID: this.sensorUUID, + connection, + signal: session.controller.signal, + reporter: this.reporter, + }))() + this.reporter.rejection('library-failure', pending, 'The WebRTC engine failed to create an offer', session.controller.signal, session.fields) + const offer = await awaitEngine(session, 'createOffer', pending) + + if (!this.sessions.holds(session)) { + return { status: WebRTCSolicitOfferStatus.ERROR } + } + + if (!offer) { + await this.sessions.exit(session, 'its offer failed') + return { status: WebRTCSolicitOfferStatus.ERROR } + } + + // The response is built field by field, and nothing else the engine's result carries reaches the controller. + return { + status: WebRTCSolicitOfferStatus.SUCCESS, + sessionIdentifier, + sdpOffer: offer.value.sdpOffer, + additionalCandidates: offer.value.additionalCandidates, + sframeConfiguration: offer.value.sframeConfiguration, + } + } + + // An offer the Solicit Offer response cannot carry is answered as a failed offer is, inside the same command: the session ends and the write answers Error. + private async refuseOffer(response: WebRTCSolicitOfferResponse, error: unknown): Promise { + if (response.status === WebRTCSolicitOfferStatus.SUCCESS) { + warnUnencodable(this.context, 'createOffer', response.sessionIdentifier, error, 'the session ends') + await this.sessions.end(response.sessionIdentifier, 'its offer cannot be encoded') + } + + return { status: WebRTCSolicitOfferStatus.ERROR } + } + + private async provideAnswer(request: WebRTCProvideAnswerRequest, connection: HAPConnection): Promise { + const { sessionIdentifier } = request + const session = this.sessions.liveSession(sessionIdentifier, connection) + + if (!session) { + return { sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } + } + + if (session.state === 'connected') { + return { sessionIdentifier, status: WebRTCStreamingStatus.BUSY } + } + + const answer: WebRTCAnswer = { sdpAnswer: request.sdpAnswer, additionalCandidates: request.additionalCandidates } + const pending = (async () => this.engine.acceptAnswer(sessionIdentifier, answer))() + this.reporter.rejection('library-failure', pending, 'The WebRTC engine failed to accept an answer', session.controller.signal, session.fields) + const accepted = await awaitEngine(session, 'acceptAnswer', pending) + + if (!this.sessions.holds(session)) { + return { sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } + } + + if (!accepted) { + await this.sessions.exit(session, 'its answer failed') + return { sessionIdentifier, status: WebRTCStreamingStatus.ERROR } + } + + session.connect() + this.countSessions(1) + this.onLiveViewStarted?.(this.liveView(sessionIdentifier)) + + return { sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS } + } + + // The decoder refuses every command but End: a decoded write ends its session. + private async streamingControl(request: WebRTCStreamingControlRequest, connection: HAPConnection): Promise { + const { sessionIdentifier } = request + const session = this.sessions.liveSession(sessionIdentifier, connection) + + if (!session) { + return { sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } + } + + await this.sessions.exit(session, 'its controller ended it') + + return { sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS } + } + + private async reoffer(request: WebRTCReofferRequest, connection: HAPConnection): Promise { + const { sessionIdentifier } = request + const session = this.sessions.liveSession(sessionIdentifier, connection) + + if (!session) { + return { sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } + } + + if (session.state === 'offered') { + return { sessionIdentifier, status: WebRTCStreamingStatus.BUSY } + } + + const offer: WebRTCReoffer = { sdpOffer: request.sdpOffer, options: request.options } + const pending = (async () => this.engine.reoffer(sessionIdentifier, offer))() + this.reporter.rejection('library-failure', pending, 'The WebRTC engine failed to answer a reoffer', session.controller.signal, session.fields) + const answer = await awaitEngine(session, 'reoffer', pending) + + if (!this.sessions.holds(session)) { + return { sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } + } + + if (!answer) { + return { sessionIdentifier, status: WebRTCStreamingStatus.ERROR } + } + + return { + sessionIdentifier, + status: WebRTCStreamingStatus.SUCCESS, + sdpAnswer: answer.value.sdpAnswer, + sframeConfiguration: answer.value.sframeConfiguration, + } + } + + // An answer the Reoffer response cannot carry is answered as a failed reoffer is: the write answers Error and the session continues. + private async refuseReofferAnswer(response: WebRTCReofferResponse, error: unknown): Promise { + warnUnencodable(this.context, 'reoffer', response.sessionIdentifier, error, 'the reoffer answers Error and the session continues') + + return { sessionIdentifier: response.sessionIdentifier, status: WebRTCStreamingStatus.ERROR } + } + + /* The decoded receive keys go to the engine, which owns each from the call that hands it over, and the session keeps none. A write answered without + * reaching the engine zeroes its own keys at once. + */ + private async updateSession(request: WebRTCUpdateSessionRequest, connection: HAPConnection): Promise { + const { receiveKeysToAdd, receiveKIDsToRemove, sessionIdentifier } = request + const keys = receiveKeysToAdd.map(({ key }) => key) + const session = this.sessions.liveSession(sessionIdentifier, connection) + + this.debug('keys-updated', () => { + const added = receiveKeysToAdd.map(({ kid }) => kid.toString()) + const lengths = keys.map(({ length }) => length) + const removed = receiveKIDsToRemove.map(({ kid }) => kid.toString()) + + return { + added, + lengths, + removed, + sentence: `Update Session for WebRTC session ${sessionIdentifier} adds key IDs ${inspectInline(added)} (${inspectInline(lengths)} bytes) and removes ` + + `key IDs ${inspectInline(removed)}.`, + sessionIdentifier, + } + }) + + if (session?.state !== 'connected') { + zero(keys) + return { + sessionIdentifier, + status: session + ? WebRTCStreamingStatus.BUSY + : WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + } + } + + const update: WebRTCReceiveKeysUpdate = { receiveKeysToAdd, receiveKIDsToRemove } + const pending = (async () => this.engine.updateReceiveKeys(sessionIdentifier, update, this.reporter))() + this.reporter.rejection('library-failure', pending, 'The WebRTC engine failed to update the receive keys', session.controller.signal, session.fields) + const updated = await awaitEngine(session, 'updateReceiveKeys', pending) + + if (!this.sessions.holds(session)) { + return { sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } + } + + return { + sessionIdentifier, + status: updated + ? WebRTCStreamingStatus.SUCCESS + : WebRTCStreamingStatus.ERROR, + } + } +} diff --git a/src/lib/camera/index.ts b/src/lib/camera/index.ts index 9fd9445e9..64e2f4eb6 100644 --- a/src/lib/camera/index.ts +++ b/src/lib/camera/index.ts @@ -20,3 +20,4 @@ export type { TierStreamStatistics, } from './StreamingOptions.js' export { TALKBACK_PAYLOAD_TYPE } from './StreamingOptions.js' +export type { WebRTCStreamingOptions, WebRTCStreamManagementState } from './WebRTCStreamManagement.js' diff --git a/src/lib/camera/webrtc/EngineSession.spec.ts b/src/lib/camera/webrtc/EngineSession.spec.ts new file mode 100644 index 000000000..bf51a71aa --- /dev/null +++ b/src/lib/camera/webrtc/EngineSession.spec.ts @@ -0,0 +1,169 @@ +import type * as werift from 'werift' +import type { RTCPeerConnection } from 'werift' + +import type { Tier, TierTable } from '../TierTable.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { buildEmitterConnection } from '../../../test-utils/connectionFixtures.js' +import { detachedReporter } from '../../../test-utils/reporterFixtures.js' +import { deferred, fakeTimeoutSignals, settle } from '../../../test-utils/settle.js' +import { CALL_TIMEOUT, EngineSession, EngineStream, settleWerift } from './EngineSession.js' +import { deriveStreamKeys, SFRAME_VIDEO_SUITE, SFrameSealer } from './sframe.js' + +function engineSession(): EngineSession { + return new EngineSession({ + connection: buildEmitterConnection(), + reporter: detachedReporter(), + sensorUUID: '7d3e0f9a-1b2c-4d5e-8f60-718293a4b5c6', + sessionIdentifier: 'e7f1c3a2-5b4d-4e6f-9a8b-0c1d2e3f4a5b', + signal: new AbortController().signal, + }) +} + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('engineSession', () => { + it('releases what a session holds in the reverse of the order it was made, none of it inside the turn its teardown begins in', async () => { + const session = engineSession() + const released: string[] = [] + const close = vi.fn(async () => { + released.push('connection') + }) + + session.holdPeerConnection({ close } as unknown as RTCPeerConnection) + session.defer(() => released.push('key')) + session.use({ + [Symbol.dispose]: () => released.push('sealer'), + }) + + const teardown = session.end() + + expect(session.ending).toBe(true) + expect(released).toEqual([]) + + await teardown + + expect(released).toEqual(['sealer', 'key', 'connection']) + expect(close).toHaveBeenCalledOnce() + }) + + it('marks its end once, answering whether the call set the mark', () => { + const session = engineSession() + + expect(session.ending).toBe(false) + expect(session.markEnding()).toBe(true) + expect(session.markEnding()).toBe(false) + expect(session.ending).toBe(true) + }) + + it('settles its teardown within the call budget when the connection\'s close never settles', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + const session = engineSession() + let settled = false + + session.holdPeerConnection({ + close: async () => new Promise(() => undefined), + } as unknown as RTCPeerConnection) + + const teardown = session.end().then(() => { + settled = true + }) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT - 1) + + expect(settled).toBe(false) + + await vi.advanceTimersByTimeAsync(1) + await teardown + + expect(settled).toBe(true) + }) + + it('rejects its teardown with a release\'s failure, every other release still run', async () => { + const session = engineSession() + const failure = new Error('The release failed.') + const released = vi.fn() + + session.defer(released) + session.defer(() => { + throw failure + }) + + await expect(session.end()).rejects.toBe(failure) + expect(released).toHaveBeenCalledOnce() + }) + + it('answers a werift operation\'s value or failure, or nothing for a wait its signal cut, keeping a handler on an operation that rejects after the cut', async () => { + const failure = new Error('The operation failed.') + const unhandled = vi.fn() + const late = deferred() + const controller = new AbortController() + + process.on('unhandledRejection', unhandled) + + try { + expect(await settleWerift(Promise.resolve(7), new AbortController().signal)).toEqual({ value: 7 }) + expect(await settleWerift(Promise.reject(failure), new AbortController().signal)).toEqual({ error: failure }) + + const cut = settleWerift(late.promise, controller.signal) + + controller.abort() + + expect(await cut).toBeUndefined() + + late.reject(failure) + await settle() + + expect(unhandled).not.toHaveBeenCalled() + } finally { + process.off('unhandledRejection', unhandled) + } + }) + + it('sends a stream\'s frame at its placed timestamp modulo 2^32, its sequence stepping by one', async () => { + const actual = await vi.importActual('werift') + const sent: werift.RtpPacket[] = [] + const sender = { + sendRtp: vi.fn(async (packet: werift.RtpPacket) => { + sent.push(packet) + }), + ssrc: 0x1A2B3C4D, + } + const stream = new EngineStream({ + medium: 'video', + payloadType: 99, + route: vi.fn(), + sealer: new SFrameSealer(deriveStreamKeys({ + keyId: 0x8000n, + sessionKey: Buffer.alloc(32, 1), + ssrc: sender.ssrc, + suite: SFRAME_VIDEO_SUITE, + })), + sender: sender as unknown as werift.RTCRtpSender, + table: {} as TierTable, + tier: {} as Tier, + werift: actual, + }) + + stream.take({ + data: Buffer.alloc(2000, 3), + time: 0, + }, 2 ** 32 + 7, false) + + const [first] = sent.map(({ header }) => header.sequenceNumber) + + expect(sent.map(({ header }) => header.timestamp)).toEqual([7, 7]) + expect(sent.map(({ header }) => header.sequenceNumber)).toEqual([first, (first + 1) % 0x10000]) + expect(stream.counts).toEqual({ failedSends: 0, frames: 1, packets: 2 }) + }) +}) diff --git a/src/lib/camera/webrtc/EngineSession.ts b/src/lib/camera/webrtc/EngineSession.ts new file mode 100644 index 000000000..8c8e0922f --- /dev/null +++ b/src/lib/camera/webrtc/EngineSession.ts @@ -0,0 +1,437 @@ +import type { RTCPeerConnection, RTCRtpSender } from 'werift' + +import type { HAPConnection } from '../../util/eventedhttp.js' +import type { CameraReporter } from '../diagnostics/CameraReporter.js' +import type { StreamTierMedium, TierFrame } from '../StreamingOptions.js' +import type { FrameConsumer, Tier, TierHolder, TierTable } from '../TierTable.js' +import type { WebRTCOfferRequest } from '../WebRTCStreamManagement.js' +import type { SFrameSealer } from './sframe.js' +import type { ReceiveKeys } from './voice/ReceiveKeys.js' +import type { ViewerVoice } from './voice/ViewerVoice.js' +import type { Werift } from './werift.js' + +import { AsyncDisposableStack } from '../../util/asyncDisposableStack.js' +import { debugChannel } from '../diagnostics/debugChannels.js' +import { firstSequence, marksPacket, nextSequence, RTP_HEADER_LENGTH, wireTimestamp } from '../rtp/packetRules.js' +import { settleWithin } from '../session/settleWithin.js' +import { sframePayloads } from './sframe.js' + +/** + * The channel of the engine's debug events, under one name for every module of the engine. + */ +export const ENGINE_DEBUG = debugChannel('HAP-NodeJS:Camera:WebRTC:engine') + +// The most octets a picture's packet takes, the size of the packets a hub's viewer plays, and the most its RTP payload takes, its SFrame octet +// among them: that size less the packet's fixed RTP header. +const PICTURE_PACKET_SIZE = 1100 +const PICTURE_PAYLOAD_SIZE = PICTURE_PACKET_SIZE - RTP_HEADER_LENGTH + +/** + * The budget of every engine call but the offer, its teardown among them. HAP answers a pending write with a timeout after about nine seconds, and the + * signaling class waits on an End's teardown before it answers. Every call settles well inside that window. + */ +export const CALL_TIMEOUT = 2 * 1000 + +/** + * The most time from a session's accepted answer to its connection's first report of connected. The signaling class counts every session against its + * sensor's bound and an answered session never expires. A view whose ICE consents and whose DTLS never completes would otherwise hold a slot for good. + */ +export const CONNECT_TIMEOUT = 30 * 1000 + +/** + * A werift operation's outcome within a signal: its value, its failure, or `undefined` for a wait the signal cut. + */ +export type WeriftOutcome = { readonly value: T } | { readonly error: unknown } | undefined + +/** + * Awaits a werift operation until it settles or the signal aborts. The operation's handler is in place before the race, which means an operation werift rejects + * once its close overtakes it, after the wait has been cut, never rejects unhandled. + * @param pending - The operation's promise. + * @param signal - The signal that cuts the wait. + * @returns The operation's value or failure, or `undefined` when the signal cut the wait. + */ +export async function settleWerift(pending: Promise, signal: AbortSignal): Promise> { + const settled = pending.then(value => ({ value }), (error: unknown) => ({ error })) + + return (await settleWithin(settled, signal))?.value +} + +/** + * What a stream is made from: the medium it sends and the payload type its packets carry, the route that ends its session for a failed tier, its sealer, + * the werift sender of its section, the video tier whose stream it takes its medium from with that tier's table, and the werift exports its packets are + * built from. + */ +export interface EngineStreamOptions { + /** + * The medium the stream sends, the picture or the sound of its tier's stream. + */ + readonly medium: StreamTierMedium + /** + * The payload type every packet of the stream carries, its section's own. + */ + readonly payloadType: number + /** + * Ends the stream's session for a tier whose stream failed, or one whose hand-over the stream threw from. + */ + readonly route: () => void + /** + * The stream's sealer, keyed by the SSRC the stream's section names. + */ + readonly sealer: SFrameSealer + /** + * The werift sender of the stream's section. + */ + readonly sender: RTCRtpSender + /** + * The table of the tier the stream takes its medium from. + */ + readonly table: TierTable + /** + * The video tier whose stream the stream takes its medium from. + */ + readonly tier: Tier + /** + * The werift exports the stream's packets are built from. + */ + readonly werift: Pick +} + +/** + * What a stream has sent: the frames it sealed, the packets it handed werift and the sends werift rejected. + */ +export interface EngineStreamCounts { + readonly failedSends: number + readonly frames: number + readonly packets: number +} + +/** + * One stream a session offers: the medium it sends and the video tier whose stream it takes that medium from, the werift sender of the stream's section, + * the SSRC that section names, and the stream's sealer, keyed by that SSRC. The stream is both the frame consumer of its tier's join and the holder of that + * join, which is how its tier's failure ends its session. Its medium and its payload type are its own, never read from the tier it joins: sound joined to a video + * tier is sealed and sent as sound. + * + * Each frame is sealed whole under the stream's sealer, whose count runs for the session whatever a keyframe request, a source's restart or a Reoffer + * does, and is sent through the stream's own sender: a picture cut into payloads of at most PICTURE_PAYLOAD_SIZE octets, the marker on the last alone, + * and a sound in one payload, marked when it opens a run. Every packet carries the stream's own sequence, from a random start, and the frame's + * timestamp modulo 2^32. werift keeps the payload buffer it is handed for retransmission, which is why each packet's payload is a buffer of its own that nothing + * writes after its send. + */ +export class EngineStream implements FrameConsumer, TierHolder { + /** + * The medium the stream sends. + */ + readonly medium: StreamTierMedium + /** + * The payload type every packet of the stream carries. + */ + readonly payloadType: number + /** + * The stream's sealer. + */ + readonly sealer: SFrameSealer + /** + * The werift sender of the stream's section. + */ + readonly sender: RTCRtpSender + /** + * The SSRC the stream's section names, which keys its sealer. + */ + readonly ssrc: number + /** + * The table of the tier the stream takes its medium from. + */ + readonly table: TierTable + /** + * The video tier whose stream the stream takes its medium from. + */ + readonly tier: Tier + private readonly route: () => void + private readonly werift: Pick + private sequenceNumber = firstSequence() + private frames = 0 + private packets = 0 + private failedSends = 0 + + /** + * Makes a stream of a session's offer. + * @param options - The stream's options. + */ + constructor(options: EngineStreamOptions) { + this.medium = options.medium + this.payloadType = options.payloadType + this.route = options.route + this.sealer = options.sealer + this.sender = options.sender + this.ssrc = options.sender.ssrc + this.table = options.table + this.tier = options.tier + this.werift = options.werift + } + + /** + * What the stream has sent so far. + */ + get counts(): EngineStreamCounts { + return { + failedSends: this.failedSends, + frames: this.frames, + packets: this.packets, + } + } + + /** + * Seals a frame of the stream's medium whole and sends its packets through the stream's sender. + * @param frame - The frame, whose bytes are sealed before the call returns. + * @param timestamp - The frame's timestamp, whole, which the wire writes modulo 2^32. + * @param opensRun - Whether the frame opens a run of times. + */ + take(frame: TierFrame, timestamp: number, opensRun: boolean): void { + const ciphertext = this.sealer.seal(frame.data) + const picture = this.medium === 'video' + const payloads = sframePayloads(ciphertext, picture + ? PICTURE_PAYLOAD_SIZE + : ciphertext.length + 1) + const rtpTimestamp = wireTimestamp(timestamp) + + this.frames++ + + for (let index = 0; index < payloads.length; index++) { + const header = new this.werift.RtpHeader({ + marker: marksPacket(picture, index === payloads.length - 1, opensRun), + payloadType: this.payloadType, + sequenceNumber: this.sequenceNumber, + timestamp: rtpTimestamp, + }) + + this.sequenceNumber = nextSequence(this.sequenceNumber) + this.packets++ + void this.sender.sendRtp(new this.werift.RtpPacket(header, payloads[index])).catch(this.countFailedSend) + } + } + + /** + * Ends the stream's session for its tier, whose stream failed. + */ + tierFailed(): void { + this.route() + } + + // werift resolves a send it drops as it resolves one it writes: a resolved send is never read as delivered, and a rejected one is counted. + private readonly countFailedSend = (): void => { + this.failedSends++ + } +} + +/** + * One session of the engine, from its offer to its teardown: the request's identifier, sensor, HAP connection, signal and reporter, the WebRTC connection, + * the store of the keys a hub writes, the reader of its viewers' voices and the streams its offer made, the mark that its end has begun, and the one stack + * every resource the session holds stands on. + * + * Every resource is registered on the stack where it is made and released in the reverse of the order it was made: the session's WebRTC connection, + * made first, closes last. The teardown is the stack's disposal and nothing beside it. The ending mark is what every route and every method of the engine + * reads after each of its awaits, which is why none of them registers anything once the end has begun. + */ +export class EngineSession { + /** + * The HAP connection that opened the session. + */ + readonly connection: HAPConnection + /** + * The lowercase UUID of the video sensor the session streams from. + */ + readonly sensorUUID: string + /** + * The session's identifier. + */ + readonly sessionIdentifier: string + /** + * The request's signal, which aborts as the signaling class ends the session, whichever path ends it. + */ + readonly signal: AbortSignal + /** + * The reporter of the camera whose management solicited the session, which every report of the session goes through: the engine, which serves every + * configuration of its camera, holds none of its own. + */ + readonly reporter: CameraReporter + /** + * The session's WebRTC connection, once its offer has built it. + */ + peerConnection?: RTCPeerConnection + /** + * The store of the receive keys a hub writes for the session, the one holder of each, once its offer has built the connection. + */ + receiveKeys?: ReceiveKeys + /** + * The reader of its viewers' voices, each written to a talkback sink of that viewer's own, once the session's offer has made it, for a sensor whose + * delegate takes talkback. + */ + voice?: ViewerVoice + /** + * The streams the session's offer made, each video tier's picture in the advertised order and then the sound tier's sound. + */ + streams: readonly EngineStream[] = [] + private readonly stack = new AsyncDisposableStack() + private endMark = false + // Whether the connection has reported connected, set at its first report and never cleared, which means neither a Reoffer nor a connection that drops later + // arms the connect bound again: consent ends a connection that drops. + private connectedMark = false + // Whether the session has written a debug event of a viewer's pause and resume feedback, set at the first such packet and never cleared, which means a viewer + // that sends it every half second writes one event a session. + private pauseMark = false + // The connect bound's timeout and its one listener, while the bound stands. + private connectBound?: { readonly expire: () => void, readonly signal: AbortSignal } + + /** + * Makes a session from its offer request. + * @param request - The request's identifier, sensor, HAP connection, signal and reporter. + */ + constructor(request: Pick) { + this.connection = request.connection + this.sensorUUID = request.sensorUUID + this.sessionIdentifier = request.sessionIdentifier + this.signal = request.signal + this.reporter = request.reporter + } + + /** + * Whether the session's end has begun, through a route of the engine or the session's teardown. + */ + get ending(): boolean { + return this.endMark + } + + /** + * Marks the session's end as begun, as a route that ends the session does before it calls the signaling class. + * @returns Whether this call set the mark, which no earlier route or teardown had. + */ + markEnding(): boolean { + if (this.endMark) { + return false + } + + this.endMark = true + + return true + } + + /** + * Whether the connection has reported connected. + */ + get connected(): boolean { + return this.connectedMark + } + + /** + * Records a report of connected, lifting the connect bound at the first. + * @returns Whether this report is the connection's first. + */ + reportConnected(): boolean { + if (this.connectedMark) { + return false + } + + this.connectedMark = true + this.liftConnectBound() + + return true + } + + /** + * Records a transport layer feedback packet of RFC 7728's pause and resume from the session's viewer. + * @returns Whether this packet is the session's first. + */ + reportPause(): boolean { + if (this.pauseMark) { + return false + } + + this.pauseMark = true + + return true + } + + /** + * Arms the connect bound as the session's answer is applied, unless the connection has reported connected already. The bound is a timeout with one + * listener, on that timeout alone and composed with nothing, since nothing waits on it, and the listener comes off at the first report of connected + * and at the teardown. + * @param expire - Called once the bound passes with no report of connected. + */ + armConnectBound(expire: () => void): void { + if (this.connectedMark) { + return + } + + const signal = AbortSignal.timeout(CONNECT_TIMEOUT) + + signal.addEventListener('abort', expire, { once: true }) + this.connectBound = { expire, signal } + this.stack.defer(() => this.liftConnectBound()) + } + + /** + * Registers a disposable resource, released at the session's teardown. + * @param value - The resource. + * @returns The resource. + */ + use(value: T): T { + return this.stack.use(value) + } + + /** + * Registers a callback, run at the session's teardown. + * @param release - The callback. + */ + defer(release: () => void): void { + this.stack.defer(release) + } + + /** + * Takes the WebRTC connection the session's offer built, the first resource on the stack, which means it closes after everything the session made from it. + * @param peerConnection - The connection. + */ + holdPeerConnection(peerConnection: RTCPeerConnection): void { + this.peerConnection = peerConnection + this.stack.adopt(peerConnection, async (held) => { + await held.close().catch(() => this.reporter.debug(ENGINE_DEBUG, 'connection-close-failed', () => ({ + sentence: `WebRTC session ${this.sessionIdentifier} failed to close its connection.`, + sessionIdentifier: this.sessionIdentifier, + }))) + }) + } + + /* The session's teardown: the stack's disposal, within the call budget counted from this call. The connection's close, which comes last, is awaited + * in what remains of it, since werift bounds only its own close_notify. Its synchronous part only marks the end and then yields, its first await one + * microtask: no release runs inside the caller's turn, which can be a frame's hand-over, a failed tier's walk or the signaling class's own exit. + */ + async end(): Promise { + this.endMark = true + + const bound = AbortSignal.timeout(CALL_TIMEOUT) + + await Promise.resolve() + + const outcome = await settleWerift(this.stack.disposeAsync(), bound) + + if (!outcome) { + this.reporter.debug(ENGINE_DEBUG, 'teardown-overran', () => { + const seconds = CALL_TIMEOUT / 1000 + + return { + seconds, + sentence: `WebRTC session ${this.sessionIdentifier} did not finish its teardown within ${seconds} seconds.`, + sessionIdentifier: this.sessionIdentifier, + } + }) + } else if ('error' in outcome) { + throw outcome.error + } + } + + private liftConnectBound(): void { + const bound = this.connectBound + + this.connectBound = undefined + bound?.signal.removeEventListener('abort', bound.expire) + } +} diff --git a/src/lib/camera/webrtc/WebRTCEngine.ts b/src/lib/camera/webrtc/WebRTCEngine.ts new file mode 100644 index 000000000..8a2f9ae82 --- /dev/null +++ b/src/lib/camera/webrtc/WebRTCEngine.ts @@ -0,0 +1,964 @@ +import type { Buffer } from 'node:buffer' +import type { RTCDtlsTransport, RTCPeerConnection, RTCPeerConnectionConfig, RTCRtpTransceiver } from 'werift' + +import type { VideoStreamTier } from '../capabilities/streamTiers.js' +import type { CameraReporter } from '../diagnostics/CameraReporter.js' +import type { StreamTierMedium } from '../StreamingOptions.js' +import type { Tier, TierHold, TierTable } from '../TierTable.js' +import type { + WebRTCAnswer, + WebRTCOffer, + WebRTCOfferRequest, + WebRTCReceiveKeysUpdate, + WebRTCReoffer, + WebRTCReofferAnswer, + WebRTCStreamEngine, + WebRTCStreamingOptions, +} from '../WebRTCStreamManagement.js' +import type { WeriftOutcome } from './EngineSession.js' +import type { ViewerVoiceSetting } from './voice/ViewerVoice.js' +import type { Werift } from './werift.js' + +import { randomBytes } from 'node:crypto' + +import { counted } from '../../util/counted.js' +import { inspectInline } from '../diagnostics/debugChannels.js' +import { SessionTalkback } from '../session/SessionTalkback.js' +import { settleWithin } from '../session/settleWithin.js' +import { CALL_TIMEOUT, CONNECT_TIMEOUT, ENGINE_DEBUG, EngineSession, EngineStream, settleWerift } from './EngineSession.js' +import { describeShape, dropMDNSCandidates, isMDNSCandidate, retransmissionSSRCs, writeTierRestrictions } from './sessionDescription.js' +import { deriveStreamKeys, SFRAME_AUDIO_SUITE, SFRAME_VIDEO_SUITE, SFrameSealer } from './sframe.js' +import { ReceiveKeys } from './voice/ReceiveKeys.js' +import { ViewerVoice, viewerVoiceSetting } from './voice/ViewerVoice.js' +import { loadWerift } from './werift.js' + +// The offer's budget, from createOffer's entry over the werift load, the connection's build, werift's own offer, which makes the session's certificate, +// and the gather. HAP answers a pending write with a timeout after about nine seconds. The offer settles well inside that window. +const OFFER_TIMEOUT = 5 * 1000 + +// The most connections an offer builds while a sender's SSRC shares its low sixteen bits with another's, which a viewer reads as a stream's identifier. +// SSRCs drawn at random share them rarely. A second build is rare, and an offer still drawing shared bits at the bound fails rather than build on, since +// only a broken draw reaches it. +const SSRC_BUILDS = 8 +const SSRC_LOW_BITS = 0xFFFF + +// A session's key and its key ID: 32 random octets, and 48 random bits above 0x8000 in the low sixteen, the form of every key ID a hub plays. +const SESSION_KEY_LENGTH = 32 +const KEY_ID_LOW_BITS = 0xFFFFn +const KEY_ID_MARK = 0x8000n + +// The options every session's connection takes, whatever its sensor: one bundle, a certificate of the connection's own, a keyframe request routed only to +// the sender whose SSRC it names, and no STUN or TURN server, since the camera's side reaches outward to the relay's public address on its host +// candidates, of both families. No compatibility preset and no ICE nomination: toward an ICE-lite far end, as the relay is, werift nominates once. +const CONNECTION_OPTIONS: Readonly = { + bundlePolicy: 'max-bundle', + certificateScope: 'standard', + iceServers: [], + iceUseDefaultStunServer: false, + iceUseIpv6: true, + keyFrameRequestRouting: 'standard', +} + +// The DTLS records a transport keeps while its state is new, the far end's ClientHello among them, which arrives within a millisecond of ICE connecting +// and before werift has a DTLS server to hear it: at most this many and this many octets, a record past either dropped and counted. A DTLS record opens +// with an octet from 20 to 63, as RFC 7983 tells it apart from STUN and media. +const EARLY_RECORDS = 8 +const EARLY_OCTETS = 16 * 1024 +const DTLS_FIRST_OCTET = 20 +const DTLS_LAST_OCTET = 63 + +// The RTCP packet type of transport layer feedback (RFC 4585 6.1), and the format within it of RFC 7728's pause and resume, which werift parses into no +// feedback of its own. +const TRANSPORT_FEEDBACK = 205 +const PAUSE_RESUME_FORMAT = 9 + +/** + * What the camera controller hands the engine: its reach into each sensor's tier table, its way to end a session of a sensor's WebRTC service, and the + * camera's voice setting. + */ +export interface WebRTCEngineOptions { + /** + * Ends a session of a sensor's WebRTC service through that service's management, which aborts the session's signal and calls the engine's + * {@link WebRTCEngine.endSession} back. + */ + endSession: (sensorUUID: string, sessionIdentifier: string) => Promise + /** + * Whether the camera's Speaker is muted, which the engine hands each session's reader of its viewers' voices, read as it stands at each voice packet. A + * muted Speaker has every viewer's packet dropped before it is opened, and a sink a viewer started stays started, written nothing until the Speaker is + * unmuted. + */ + speakerMuted: () => boolean + /** + * The tier table of a video sensor, by its lowercase UUID, or `undefined` for a sensor without one. + */ + tierTable: (sensorUUID: string) => TierTable | undefined + /** + * Which of a viewer's voice streams each session plays, as the camera's WebRTC streaming gives it, which the engine's constructor checks. + */ + voice?: WebRTCStreamingOptions['voice'] +} + +// A transceiver of one medium, with the video tier whose stream it takes that medium from and the payload type it sends under. +interface TierTransceiver { + readonly medium: StreamTierMedium + readonly payloadType: number + readonly tier: Tier + readonly transceiver: RTCRtpTransceiver +} + +// A stream's join of its tier, with the stream that joined. +interface StreamJoin { + readonly hold: TierHold + readonly stream: EngineStream +} + +// A session's connection, built for its sensor's tiers, its transceivers in the offer's order and each layer's tier by its rid. +interface SessionBuild { + readonly layers: ReadonlyMap + readonly peerConnection: RTCPeerConnection + readonly transceivers: readonly TierTransceiver[] +} + +/* The configuration of one connection: the fixed options, the sensor's codecs, and the MID and RID header extensions. The extensions are one fresh array of + * fresh objects passed for both kinds, since werift writes each extension's identifier into the objects it is handed. Every section carries the same + * identifiers, as an offer a hub plays does. + */ +function configuration(werift: Werift, table: TierTable): RTCPeerConnectionConfig { + const { audioStreamTiers, videoStreamTiers } = table.streamTiers + const { numberOfChannels, packetTime } = table.audioTier.advertised + const extensions = [ + werift.useSdesMid(), + werift.useSdesRTPStreamId(), + ] + + return { + ...CONNECTION_OPTIONS, + codecs: { + audio: [ + new werift.RTCRtpCodecParameters({ + channels: numberOfChannels, + clockRate: 48000, + mimeType: 'audio/opus', + parameters: `minptime=${packetTime};useinbandfec=0`, + payloadType: audioStreamTiers.payloadType, + }), + ], + video: [ + new werift.RTCRtpCodecParameters({ + clockRate: 90000, + mimeType: 'video/H265', + payloadType: videoStreamTiers.payloadType, + rtcpFeedback: [ + { type: 'nack' }, + { parameter: 'pli', type: 'nack' }, + { parameter: 'fir', type: 'ccm' }, + ], + }), + ], + }, + headerExtensions: { + audio: extensions, + video: extensions, + }, + } +} + +// Whether every SSRC of a build differs from the others in its low sixteen bits. +function lowBitsDiffer(transceivers: readonly TierTransceiver[]): boolean { + return new Set(transceivers.map(({ transceiver }) => transceiver.sender.ssrc & SSRC_LOW_BITS)).size === transceivers.length +} + +/* Builds a session's connection: a send-only video transceiver for each tier in the advertised order, the tier's rid its place from 1 and its one simulcast + * layer with no send encoding, which means werift writes the section's rid and simulcast lines and puts no stream ID on a packet. After the video transceivers comes a + * send-only audio transceiver for the sound of the sensor's sound tier, under the audio tier's payload type. While a sender's SSRC shares its low sixteen bits with + * another's, the connection is closed and the transceivers built again on a fresh one. werift draws each SSRC as it makes the sender and binds no socket before the + * gather: a connection discarded here opened nothing, and the engine never writes an SSRC itself. + */ +function build(werift: Werift, table: TierTable, sessionIdentifier: string, reporter: CameraReporter): SessionBuild { + for (let built = 1; built <= SSRC_BUILDS; built++) { + const peerConnection = new werift.RTCPeerConnection(configuration(werift, table)) + const layers = new Map() + const transceivers: TierTransceiver[] = Array.from(table.videoTiers.values(), (tier, index) => { + const rid = String(index + 1) + + layers.set(rid, tier.advertised) + + return { + medium: 'video', + payloadType: tier.payloadType, + tier, + transceiver: peerConnection.addTransceiver('video', { + direction: 'sendonly', + simulcast: [ + { direction: 'send', rid }, + ], + }), + } + }) + + transceivers.push({ + medium: 'audio', + payloadType: table.audioTier.payloadType, + tier: table.soundTier, + transceiver: peerConnection.addTransceiver('audio', { direction: 'sendonly' }), + }) + + if (lowBitsDiffer(transceivers)) { + return { layers, peerConnection, transceivers } + } + + reporter.debug(ENGINE_DEBUG, 'ssrcs-drawn-again', () => ({ + build: built, + sentence: `WebRTC session ${sessionIdentifier} drew SSRCs sharing their low sixteen bits on build ${built}.`, + sessionIdentifier, + })) + void peerConnection.close().catch(() => reporter.debug(ENGINE_DEBUG, 'redrawn-close-failed', () => ({ + sentence: `WebRTC session ${sessionIdentifier} failed to close a connection it drew again.`, + sessionIdentifier, + }))) + } + + throw new Error(`WebRTC session ${sessionIdentifier} drew SSRCs sharing their low sixteen bits on ${SSRC_BUILDS} connections in a row, and its offer fails.`) +} + +// One call of the engine on a session, which the sentences of a failed step name: its call, the budget it runs under, and the signal that cuts it, that +// budget composed with the session's signal. +interface SessionCall { + readonly budget: number + readonly cut: AbortSignal + readonly name: string + readonly session: EngineSession +} + +function sessionCall(session: EngineSession, name: string, budget: number): SessionCall { + return { + budget, + cut: AbortSignal.any([ + session.signal, + AbortSignal.timeout(budget), + ]), + name, + session, + } +} + +/* Awaits one step of a call on a session within the call's cut, and reads after it whether the session's end has begun. A step the session's end overtook, + * one cut at the budget and one that failed each reject the call in a sentence of its own, a failure's error as its cause. + */ +async function callStep(call: SessionCall, pending: Promise, step: string): Promise { + return readStep(call, await settleWerift(pending, call.cut), step) +} + +// Reads one settled step of a call on a session as callStep does, for a caller that reads the step's outcome itself first. +function readStep(call: SessionCall, outcome: WeriftOutcome, step: string): T { + const { budget, name, session } = call + const { sessionIdentifier } = session + + if (session.ending || session.signal.aborted) { + throw new Error(`WebRTC session ${sessionIdentifier} ended during ${step}, and its ${name} fails.`) + } + + if (!outcome) { + throw new Error(`The ${name} of WebRTC session ${sessionIdentifier} was cut at ${step} by its budget of ${budget / 1000} seconds.`) + } + + if ('error' in outcome) { + throw new Error(`WebRTC session ${sessionIdentifier} failed at ${step}, and its ${name} fails.`, { cause: outcome.error }) + } + + return outcome.value +} + +/* Wraps a subscriber the engine gives werift, which runs it inside werift's own pass over its subscribers, where a throw would stop the subscribers after + * it: its throw is reported here as the library's failure on the session and never reaches werift. + */ +function guarded(session: EngineSession, event: string, subscriber: (...args: Args) => void): (...args: Args) => void { + return (...args) => { + try { + subscriber(...args) + } catch (error) { + engineFailed(session, `The WebRTC engine failed to handle ${event} for WebRTC session ${session.sessionIdentifier}`, error) + } + } +} + +// Reports a failure of the engine's own on a session as the library's, through the reporter the session was made under, naming its sensor and the session. +function engineFailed({ reporter, sensorUUID, sessionIdentifier }: EngineSession, failure: string, error: unknown): void { + reporter.failure('library-failure', failure, error, { sensorUUID, sessionIdentifier }) +} + +// What a route that ends a session with the engine's own view-failed problem tells of the view's end: its sentence, and the tier that refused the session +// where one did. +interface ViewEndReport { + readonly sentence: string + readonly tierId?: number +} + +/** + * The library's WebRTC engine, built on werift: one for a camera, serving the WebRTC service of every video sensor the camera has, its sessions keyed by + * session identifier. A session's offer names a video section for each tier the sensor advertises and then its audio, and carries a fresh SFrame key. + * The receive keys a hub writes for a session are held in the session's one store, by key ID, and zeroed at their removal, their replacement, past the + * store's bound and at the session's teardown. For a sensor whose delegate takes talkback, the session's reader opens each viewer's voice under those keys + * and writes it to a talkback sink of that viewer's own while the camera's Speaker is unmuted. Once its connection connects, the session joins every video + * tier it offered for its picture and the sensor's sound tier for its sound, which the tier table holds back while the camera's Microphone is muted, and + * each frame is sealed whole and sent through its stream's own sender, while each picture stream's keyframe requests go to its own join's hold, whose + * demand answers that stream alone. + * + * Every session holds its resources on its one stack, released in the reverse of the order acquired at its teardown, which is {@link endSession} and + * nothing beside it. Every method reads whether its session's end has begun after each of its awaits and registers nothing once it has, and every wait + * on werift is raced against its budget and the session's signal with a handler kept on werift's promise. + */ +export class WebRTCEngine implements WebRTCStreamEngine { + /** + * Which of a viewer's voice streams each session plays, as the constructor checked it. + */ + readonly voice: ViewerVoiceSetting + private readonly endWebRTCSession: WebRTCEngineOptions['endSession'] + private readonly speakerMuted: WebRTCEngineOptions['speakerMuted'] + private readonly tierTable: WebRTCEngineOptions['tierTable'] + private readonly sessions = new Map() + + /** + * Takes the camera controller's reach into each sensor's tier table, its way to end a session, its reader of the Speaker's mute and the camera's voice + * setting, which it checks. + * @param options - The engine's options. + * @throws TypeError for a voice setting that is neither value. + */ + constructor(options: WebRTCEngineOptions) { + this.endWebRTCSession = options.endSession + this.speakerMuted = options.speakerMuted + this.tierTable = options.tierTable + this.voice = viewerVoiceSetting(options.voice) + } + + /** + * Starts werift's load ahead of a first offer, as the camera controller builds each sensor's WebRTC service. The load is the process's one, which every + * offer then awaits, and its promise keeps its handler. A failed load leaves no rejection unhandled here. + */ + preload(): void { + void loadWerift() + } + + /** + * Creates the offer of a session the controller solicited, registering the session before its first wait, which is how a teardown during the offer finds it. The + * offer settles within its budget and the request's signal, and a failed or cut offer rejects and leaves its session to {@link endSession}, which the + * signaling class calls at every exit. + * @param request - The session's offer request. + * @returns The offer, every candidate in its text, and the session's SFrame key, returned whatever the solicit says. + */ + async createOffer(request: WebRTCOfferRequest): Promise { + const { connection, options, reporter, sensorUUID, sessionIdentifier, signal } = request + const session = new EngineSession({ + connection, + reporter, + sensorUUID, + sessionIdentifier, + signal, + }) + const call = sessionCall(session, 'offer', OFFER_TIMEOUT) + + this.sessions.set(sessionIdentifier, session) + + // The decoder reads a solicit with no options and one that does not ask for SFrame alike, which means a solicit that asks is the one the engine can tell. + if (options.sframeEnabled) { + reporter.debug(ENGINE_DEBUG, 'sframe-solicited', () => ({ + sentence: `WebRTC session ${sessionIdentifier} was solicited asking for SFrame.`, + sessionIdentifier, + })) + } + + const table = this.tierTable(sensorUUID) + + if (!table) { + throw new Error(`WebRTC session ${sessionIdentifier} streams from the video sensor "${sensorUUID}", which has no stream tiers, and its offer fails.`) + } + + const werift = await callStep(call, loadWerift(), 'the werift load') + const { layers, peerConnection, transceivers } = build(werift, table, sessionIdentifier, reporter) + + session.holdPeerConnection(peerConnection) + + const { key, keyId } = this.makeKey(session) + + // The store of the keys a hub writes stands above the connection and the session's own key, which is why the teardown zeroes every key it holds before it zeroes + // the session's own key and closes the connection. + const receiveKeys = session.receiveKeys = session.use(new ReceiveKeys()) + + this.hearViewer(session, receiveKeys, table, werift) + session.streams = transceivers.map(({ medium, payloadType, tier, transceiver: { sender } }) => new EngineStream({ + medium, + payloadType, + route: guarded(session, 'a failed tier', () => this.endForFailedTier(session, tier)), + sealer: session.use(new SFrameSealer(deriveStreamKeys({ + keyId, + sessionKey: key, + ssrc: sender.ssrc, + suite: medium === 'video' + ? SFRAME_VIDEO_SUITE + : SFRAME_AUDIO_SUITE, + }))), + sender, + table, + tier, + werift, + })) + + // The counts are stated as the session's joins have released, which the stack runs before this: no frame is sealed after them. + session.defer(() => reporter.debug(ENGINE_DEBUG, 'session-sent', () => { + const sent = session.streams.map(({ counts }) => counts) + const total = (count: keyof EngineStream['counts']): number => sent.reduce((sum, counts) => sum + counts[count], 0) + const failedSends = total('failedSends') + const frames = total('frames') + const packets = total('packets') + + return { + failedSends, + frames, + packets, + sentence: `WebRTC session ${sessionIdentifier} sealed ${counted(frames, 'frame')} and handed werift ${counted(packets, 'packet')}, ${failedSends} of whose ` + + 'sends werift rejected.', + sessionIdentifier, + } + })) + + const offer = await callStep(call, peerConnection.createOffer(), 'werift\'s offer') + + await callStep(call, peerConnection.setLocalDescription(offer), 'the gather') + + const sdp = peerConnection.localDescription?.sdp + + if (sdp === undefined) { + throw new Error(`WebRTC session ${sessionIdentifier} has no local description after its gather, and its offer fails.`) + } + + reporter.debug(ENGINE_DEBUG, 'offer-made', () => { + const { audioSections, candidates, videoSections } = describeShape(sdp) + + return { + audioSections, + candidates, + sentence: `WebRTC session ${sessionIdentifier} offers ${videoSections} video and ${counted(audioSections, 'audio section')} with the candidates ` + + `${inspectInline(candidates)}.`, + sessionIdentifier, + videoSections, + } + }) + + return { + sdpOffer: writeTierRestrictions(sdp, layers), + additionalCandidates: [], + sframeConfiguration: { key, kid: keyId }, + } + } + + /** + * Accepts the controller's answer. Every candidate on an mDNS host is left out of the answer's text and its additional candidates before werift sees + * either, the answer is applied and each candidate added within the call budget and the session's signal, and the session's connection is watched from + * before the apply, which means a DTLS record that arrives early is kept, and a connection that fails, closes or never connects ends the session. + * @param sessionIdentifier - The session's identifier. + * @param answer - The controller's answer. + */ + async acceptAnswer(sessionIdentifier: string, answer: WebRTCAnswer): Promise { + const session = this.sessions.get(sessionIdentifier) + const peerConnection = session?.peerConnection + + if (!session || session.ending || !peerConnection) { + throw new Error(`WebRTC session ${sessionIdentifier} has no offered connection, and its answer fails.`) + } + + const call = sessionCall(session, 'answer', CALL_TIMEOUT) + const { dropped, sdp } = dropMDNSCandidates(answer.sdpAnswer) + const candidates = answer.additionalCandidates.filter(({ candidate }) => !isMDNSCandidate(candidate)) + + session.reporter.debug(ENGINE_DEBUG, 'answer-taken', () => { + const shape = describeShape(sdp) + const leftOut = dropped + answer.additionalCandidates.length - candidates.length + + return { + additionalCandidates: candidates.length, + audioSections: shape.audioSections, + candidates: shape.candidates, + leftOut, + sentence: `WebRTC session ${sessionIdentifier} takes an answer of ${shape.videoSections} video and ${counted(shape.audioSections, 'audio section')} with the ` + + `candidates ${inspectInline(shape.candidates)} and ${candidates.length} more, leaving out ${leftOut} on an mDNS host.`, + sessionIdentifier, + videoSections: shape.videoSections, + } + }) + + this.watch(session, peerConnection) + + await callStep(call, peerConnection.setRemoteDescription({ sdp, type: 'answer' }), 'the answer\'s apply') + session.voice?.setRetransmissions(retransmissionSSRCs(sdp)) + + for (const candidate of candidates) { + await callStep(call, peerConnection.addIceCandidate(candidate), 'a candidate\'s add') + } + + session.armConnectBound(guarded(session, 'the connect bound', () => this.routeEnd(session, { + sentence: `WebRTC session ${sessionIdentifier} did not connect within ${CONNECT_TIMEOUT / 1000} seconds of its accepted answer. The session ends.`, + }))) + } + + /** + * Answers the controller's renegotiation of an active session, all or nothing. Every candidate on an mDNS host is left out of the offer before werift + * sees it, the offer is applied, and an answer made and applied within the call budget and the session's signal. A Reoffer that rejects leaves the + * session as it was, its key and its sealing untouched: werift's own recovery leaves an offer it refuses stable, and a failure after the offer applied, + * or a cut before the answer's apply begins, rolls the offer back. A cut by the session's end rolls nothing back, since the teardown closes the + * connection. + * @param sessionIdentifier - The session's identifier. + * @param offer - The controller's offer. + * @returns The answer's text, every candidate in it, and no key, since a Reoffer changes neither the key nor the sealing. + */ + async reoffer(sessionIdentifier: string, offer: WebRTCReoffer): Promise { + const session = this.sessions.get(sessionIdentifier) + const peerConnection = session?.peerConnection + + if (!session || session.ending || !peerConnection) { + throw new Error(`WebRTC session ${sessionIdentifier} has no offered connection, and its reoffer fails.`) + } + + const call = sessionCall(session, 'reoffer', CALL_TIMEOUT) + const { dropped, sdp } = dropMDNSCandidates(offer.sdpOffer) + const listed = [...peerConnection.dtlsTransports] + // Whether a failure owes the offer's rollback: from the moment its apply is asked, since a cut leaves that apply pending, until the answer applies. + let owed = true + + session.reporter.debug(ENGINE_DEBUG, 'reoffer-taken', () => { + const { audioSections, candidates, videoSections } = describeShape(sdp) + + return { + audioSections, + candidates, + leftOut: dropped, + sentence: `WebRTC session ${sessionIdentifier} takes a reoffer of ${videoSections} video and ${counted(audioSections, 'audio section')} with the candidates ` + + `${inspectInline(candidates)}, leaving out ${dropped} on an mDNS host.`, + sessionIdentifier, + videoSections, + } + }) + + try { + const applied = await settleWerift(peerConnection.setRemoteDescription({ sdp, type: 'offer' }), call.cut) + + owed = !(applied && ('error' in applied)) + readStep(call, applied, 'the reoffer\'s apply') + + const answer = await callStep(call, peerConnection.createAnswer(), 'werift\'s answer') + + // callStep read the budget and the signal as werift's answer settled, and no turn passes before the answer's apply begins. werift runs description + // operations one at a time, which is why that apply, once begun, is awaited whole: a cut there would let the descriptions apply after the hub was told Error. + readStep(call, await peerConnection.setLocalDescription(answer).then(value => ({ value }), (error: unknown) => ({ error })), + 'the reoffer answer\'s apply') + owed = false + } catch (error) { + if (owed && !session.ending && !session.signal.aborted) { + this.rollBack(session, peerConnection) + } + + throw error + } + + const sdpAnswer = peerConnection.localDescription?.sdp + + if (sdpAnswer === undefined) { + throw new Error(`WebRTC session ${sessionIdentifier} has no local description after its reoffer, and its reoffer fails.`) + } + + session.voice?.setRetransmissions(retransmissionSSRCs(sdp)) + + for (const transport of peerConnection.dtlsTransports) { + if (!listed.includes(transport)) { + this.watchTransport(session, peerConnection, transport) + } + } + + return { sdpAnswer } + } + + /** + * Applies the controller's receive keys to the session's store in the call's own turn, its removals and then its additions, and resolves. The engine owns + * each key from this call on and is its one holder: the store holds the very buffer it is handed by its key ID and zeroes it at its removal, at its + * replacement, past the store's bound and at the session's teardown, and the session's reader zeroes what it derived from each key the store zeroed. A + * removal that leaves a key ID unheld after the call, or a key's drop past the store's bound, ends its viewer's talkback inside the call, releasing what + * its talker registered, while a key replaced under its ID, one removed and written again in the same call among them, leaves its viewer's talker as it + * is, and a key written again in a later call starts a new talker. For a session the engine does not hold, one whose end has begun or one whose offer + * has not built its store, each key handed is zeroed at once and nothing is held. The debug event counts keys and never states a key's bytes, and goes + * through the reporter of the session the call finds, or the caller's where it finds none. + * @param sessionIdentifier - The session's identifier. + * @param update - The keys to add and the key IDs to remove. + * @param reporter - The caller's reporter, for a call that finds no session. + */ + async updateReceiveKeys(sessionIdentifier: string, update: WebRTCReceiveKeysUpdate, reporter: CameraReporter): Promise { + const session = this.sessions.get(sessionIdentifier) + const store = session?.receiveKeys + + if (!session || session.ending || session.signal.aborted || !store) { + for (const { key } of update.receiveKeysToAdd) { + key.fill(0) + } + + const { length } = update.receiveKeysToAdd + const sessionReporter = session?.reporter ?? reporter + + sessionReporter.debug(ENGINE_DEBUG, 'keys-zeroed', () => ({ + keys: length, + sentence: `WebRTC session ${sessionIdentifier} is handed ${counted(length, 'receive key')} while the engine holds no live store for it, and zeroes each.`, + sessionIdentifier, + })) + return + } + + const zeroed = store.update(update) + + session.voice?.forget(zeroed) + + session.reporter.debug(ENGINE_DEBUG, 'keys-added', () => { + const added = update.receiveKeysToAdd.length + const held = store.size + + return { + added, + held, + sentence: `WebRTC session ${sessionIdentifier} adds ${counted(added, 'receive key')} and zeroes ${zeroed.length}, holding ${held}.`, + sessionIdentifier, + zeroed: zeroed.length, + } + }) + } + + /** + * Tears a session down: the first call for an identifier takes the session out of the engine and disposes its stack, in any state, while another call + * on the session is in flight too, and settles within the call budget. A later call, and one for an identifier the engine never held, finds no session + * and resolves, its debug event going through the caller's reporter. + * @param sessionIdentifier - The session's identifier. + * @param reporter - The caller's reporter, for a call that finds no session. + */ + async endSession(sessionIdentifier: string, reporter: CameraReporter): Promise { + const session = this.sessions.get(sessionIdentifier) + + if (!session) { + reporter.debug(ENGINE_DEBUG, 'end-unheld', () => ({ + sentence: `WebRTC session ${sessionIdentifier} has ended already or was never held.`, + sessionIdentifier, + })) + return + } + + this.sessions.delete(sessionIdentifier) + await session.end() + } + + /* Makes the reader of its viewers' voices for a session of a sensor whose delegate takes talkback, on the stack above the store it reads, with the way it + * makes each viewer's talkback, whose talker carries the sensor's UUID, and the engine's reader of the Speaker's mute. The reader keeps no copy of the + * camera's value. A talkback's end, which releases what its talker registered, is registered as its sink starts: it stands above the reader, whose + * disposal raises the failed-writes problem of each viewer it still holds once every talker's registrations have been released. A talkback names its + * viewer by the key ID, as the opened-packet event writes it, and its session: its reports tell viewers apart and stay true when a viewer leaves + * before its session ends. A sensor whose delegate has no talkbackStarted gets none of them, and no transport of its session is subscribed for RTP. + */ + private hearViewer(session: EngineSession, keys: ReceiveKeys, table: TierTable, werift: Werift): void { + const { context: { delegate, sensorUUID }, payloadType } = table.audioTier + + if (!delegate.talkbackStarted) { + return + } + + const { sessionIdentifier } = session + + session.voice = session.use(new ViewerVoice({ + keys, + payloadType, + reporter: session.reporter, + sessionIdentifier, + speakerMuted: this.speakerMuted, + talkback: keyId => new SessionTalkback({ + defer: release => session.defer(release), + ended: () => session.ending || session.signal.aborted, + reporter: session.reporter, + sensorUUID, + session: `viewer ${keyId} of WebRTC session ${sessionIdentifier}`, + sessionIdentifier, + start: talker => delegate.talkbackStarted?.(talker), + }), + voice: this.voice, + werift, + })) + } + + // Makes a session's key and key ID, the key zeroed at the session's teardown, a sealer it keys standing above it on the stack and zeroed before it. + private makeKey(session: EngineSession): { key: Buffer, keyId: bigint } { + const key = randomBytes(SESSION_KEY_LENGTH) + const keyId = (randomBytes(8).readBigUInt64BE() & ~KEY_ID_LOW_BITS) | KEY_ID_MARK + + session.defer(() => key.fill(0)) + + return { key, keyId } + } + + /* Watches a session's connection from before its answer's apply: each DTLS transport's early records, its state, its RTCP packets and, for a session + * that reads a viewer's voice, the RTP packets it receives, and the connection's state, whose first report of connected joins the session's tiers, on + * the connection the offer kept and never on one the SSRC rule discarded. Each subscription is registered on the session's stack as it is made: the + * teardown takes it off before the connection closes, and the closed state the engine's own close sets is never read as the far end's. + */ + private watch(session: EngineSession, peerConnection: RTCPeerConnection): void { + const { sessionIdentifier } = session + const connectionState = peerConnection.connectionStateChange.subscribe(guarded(session, 'a connection state', (state) => { + if (state === 'connected') { + if (session.reportConnected() && !session.ending) { + this.join(session) + } + } else if (state === 'failed') { + this.routeEnd(session, { sentence: `WebRTC session ${sessionIdentifier} lost its connection. The session ends.` }) + } + })) + + session.defer(() => connectionState.unSubscribe()) + + for (const transport of peerConnection.dtlsTransports) { + this.watchTransport(session, peerConnection, transport) + } + } + + // Watches one DTLS transport of a session's connection: its early records, its state, whose closed or failed ends the session, its RTCP packets, whose + // pause and resume feedback is written as one debug event a session, and, for a session that reads a viewer's voice, the RTP packets it receives, each + // handed to the reader. + private watchTransport(session: EngineSession, peerConnection: RTCPeerConnection, transport: RTCDtlsTransport): void { + this.keepEarlyRecords(session, transport) + + // A transport the connection no longer lists is read as nothing, as werift's own reading does, since werift stops its transceivers before it marks a + // transport closed. A far end's close_notify closes a transport and leaves the connection's state as it was, and it stops every send. + const transportState = transport.onStateChange.subscribe(guarded(session, 'a DTLS transport state', (state) => { + if ((state === 'closed' || state === 'failed') && peerConnection.dtlsTransports.includes(transport)) { + this.routeEnd(session, { sentence: `WebRTC session ${session.sessionIdentifier} had its DTLS transport ${state}. The session ends.` }) + } + })) + + session.defer(() => transportState.unSubscribe()) + + // A viewer sends RFC 7728's pause and resume feedback about its own voice stream, which asks nothing of the camera: the first is a debug event and + // every RTCP packet is left to werift as it stands. + const feedback = transport.onRtcp.subscribe(guarded(session, 'an RTCP packet', (rtcp) => { + if ((rtcp.type === TRANSPORT_FEEDBACK) && (rtcp.header.count === PAUSE_RESUME_FORMAT) && session.reportPause()) { + session.reporter.debug(ENGINE_DEBUG, 'pause-feedback', () => ({ + sentence: `WebRTC session ${session.sessionIdentifier} was sent pause and resume feedback by its viewer, which changes nothing it sends.`, + sessionIdentifier: session.sessionIdentifier, + })) + } + })) + + session.defer(() => feedback.unSubscribe()) + + const { voice } = session + + if (voice) { + const packets = transport.onRtp.subscribe(guarded(session, 'a viewer\'s RTP packet', (packet) => { + voice.take(packet) + })) + + session.defer(() => packets.unSubscribe()) + } + } + + /* Keeps the DTLS records that reach a transport while its state is new, within EARLY_RECORDS and EARLY_OCTETS, and hands them back through the ICE + * connection's data event on the turn after the transport reports connecting, once werift has built its DTLS server over that event. The keep's + * subscriber comes off at the replay, or as the transport leaves new with nothing kept, and the teardown takes it off and cancels a replay still + * pending. + */ + private keepEarlyRecords(session: EngineSession, transport: RTCDtlsTransport): void { + const { connection } = transport.iceTransport + const kept: Buffer[] = [] + let octets = 0 + let dropped = 0 + let leftNew = false + let replay: ReturnType | undefined + + const records = connection.onData.subscribe(guarded(session, 'an early DTLS record', (record) => { + if ((transport.state !== 'new') || (record[0] < DTLS_FIRST_OCTET) || (record[0] > DTLS_LAST_OCTET)) { + return + } + + if ((kept.length === EARLY_RECORDS) || (octets + record.length > EARLY_OCTETS)) { + dropped++ + return + } + + kept.push(record) + octets += record.length + })) + + const states = transport.onStateChange.subscribe(guarded(session, 'a DTLS transport state', (state) => { + if (leftNew || (state === 'new')) { + return + } + + leftNew = true + + if ((state !== 'connecting') || (kept.length === 0)) { + records.unSubscribe() + kept.length = 0 + return + } + + replay = setImmediate(guarded(session, 'the early DTLS records', () => { + replay = undefined + records.unSubscribe() + session.reporter.debug(ENGINE_DEBUG, 'early-records-replayed', () => ({ + dropped, + replayed: kept.length, + sentence: `WebRTC session ${session.sessionIdentifier} replays ${counted(kept.length, 'early DTLS record')}, ${dropped} dropped.`, + sessionIdentifier: session.sessionIdentifier, + })) + + for (const record of kept.splice(0)) { + connection.onData.execute(record) + } + })) + })) + + session.defer(() => { + clearImmediate(replay) + records.unSubscribe() + states.unSubscribe() + kept.length = 0 + }) + } + + /* Joins every stream a session offered, at its connection's first report of connected, in one synchronous pass, each video tier's picture and then the + * sound tier's sound, which is why the sound's stream joins the live releases in the turn the pictures open. Each stream joins its tier as the frame consumer of + * its own medium and the join's holder. A picture stream opens from the latest keyframe its tier's pacer has released, handed across the pacer's turns + * as the live edge reaches each picture, as a session's at home is, and starts at the stream's next keyframe where its tier's buffer keeps no such + * keyframe; the sound stream joins the live releases. A join that raises a demand runs plugin code, the delegate's tierDemandStarted, which can end the + * session. The pass reads the session's ending after each join, joins nothing once that end has begun and releases at once a join made after it + * began. Each kept join's release is registered on the session's stack, and after it each picture stream's subscription of its keyframe requests to its + * own join's hold, which is why the subscription is undone before the hold's release and no request reaches a released hold, each request writing one debug event + * with what it came to. + */ + private join(session: EngineSession): void { + const joins: StreamJoin[] = [] + + for (const stream of session.streams) { + const { medium, table, tier } = stream + const hold = table.joinFrames(tier, medium, stream, stream) + + if (session.ending) { + hold.release() + return + } + + session.defer(() => hold.release()) + joins.push({ hold, stream }) + + if (medium === 'video') { + const requests = stream.sender.onKeyFrameRequest.subscribe(guarded(session, 'a keyframe request', () => { + const outcome = hold.answerKeyframeRequest() + + session.reporter.debug(ENGINE_DEBUG, 'keyframe-request', () => ({ + outcome, + sentence: `WebRTC session ${session.sessionIdentifier} takes a keyframe request on video tier ${tier.tierId}: ${outcome}.`, + sessionIdentifier: session.sessionIdentifier, + tierId: tier.tierId, + })) + })) + + session.defer(() => requests.unSubscribe()) + } + } + + void this.awaitJoins(session, joins).catch((error: unknown) => { + engineFailed(session, `The WebRTC engine failed to wait on the tiers of WebRTC session ${session.sessionIdentifier}`, error) + }) + } + + /* Waits for every join whose demand is still starting, together, within the session's signal alone, as a Start at home does, while the frames written + * during the wait are sent, since each demand's own bound withdraws a start that never settles and refuses every join waiting on it. A waiting join + * answered cut, its demand withdrawn at its bound, ends the session with no problem of the engine's own, the demand's one plugin-failure problem naming + * its tier, and a tier that refused its join, read over every join as not started, ends the session with the engine's one view-failed problem, naming + * the first such tier. A session whose end began during the wait, a tier that failed among the ways, is left to that end. + */ + private async awaitJoins(session: EngineSession, joins: readonly StreamJoin[]): Promise { + const { sensorUUID, sessionIdentifier, signal } = session + const waiting = joins.filter(({ hold }) => hold.waiting) + const answers = (waiting.length > 0) + ? (await settleWithin(Promise.all(waiting.map(async ({ hold }) => hold.answer())), signal))?.value + : [] + + if (session.ending || signal.aborted) { + return + } + + if (answers?.includes('cut')) { + if (this.routeEnd(session)) { + session.reporter.debug(ENGINE_DEBUG, 'join-cut', () => ({ + sentence: `WebRTC session ${sessionIdentifier} ends, a demand it joined not started within its bound.`, + sessionIdentifier, + })) + } + + return + } + + const refused = joins.find(({ hold }) => !hold.started)?.stream.tier + + if (refused) { + this.routeEnd(session, { + sentence: `The video tier ${refused.tierId} of the video sensor "${sensorUUID}" refused WebRTC session ${sessionIdentifier}. The session ends.`, + tierId: refused.tierId, + }) + } + } + + /* Rolls a Reoffer's remote offer back through werift's setRemoteDescription, which takes a rollback in have-remote-offer and refuses it in stable. The + * rollback is queued whatever the state reads, since werift runs description operations one at a time: one asked while the offer's apply is pending runs + * once that apply settles, and its handler takes the refusal where the offer never applied. + */ + private rollBack(session: EngineSession, peerConnection: RTCPeerConnection): void { + void peerConnection.setRemoteDescription({ type: 'rollback' }).catch(() => { + session.reporter.debug(ENGINE_DEBUG, 'rollback-unapplied', () => ({ + sentence: `WebRTC session ${session.sessionIdentifier} had no applied reoffer to roll back.`, + sessionIdentifier: session.sessionIdentifier, + })) + }) + } + + // Ends a session for a tier it joined whose stream failed, a silence among the failures, under the problem the tier table raises for it, which names the + // tier, or under the one its silence raised already: the engine adds no second one. + private endForFailedTier(session: EngineSession, tier: Tier): void { + if (this.routeEnd(session)) { + session.reporter.debug(ENGINE_DEBUG, 'ended-for-tier', () => ({ + sentence: `WebRTC session ${session.sessionIdentifier} ends, the stream of its video tier ${tier.tierId} failed.`, + sessionIdentifier: session.sessionIdentifier, + tierId: tier.tierId, + })) + } + } + + /* Ends a session from a route of the engine's own, through the signaling class, with one view-failed problem, the view's failure on the session's sensor + * and the tier that refused it where one did, or with none for a route whose failure the tier table reports itself. The route marks the session ending + * synchronously, before it calls the signaling class, which calls endSession back in that same turn, and a route that finds the mark set does nothing. + * The routes for one failure end a session once between them: werift runs the connection's failed subscribers inside the DTLS transport's own pass, + * where an unSubscribe made during the pass does not stop them. A handler is kept on the call's promise. + */ + private routeEnd(session: EngineSession, report?: ViewEndReport): boolean { + if (!session.markEnding()) { + return false + } + + const { reporter, sensorUUID, sessionIdentifier } = session + + if (report !== undefined) { + reporter.problem({ + ...report, + kind: 'view-failed', + level: 'warning', + sensorUUID, + sessionIdentifier, + }) + } + + void this.endWebRTCSession(sensorUUID, sessionIdentifier).catch((error: unknown) => { + engineFailed(session, `The WebRTC engine failed to end WebRTC session ${sessionIdentifier}`, error) + }) + + return true + } +} diff --git a/src/lib/camera/webrtc/sessionDescription.spec.ts b/src/lib/camera/webrtc/sessionDescription.spec.ts new file mode 100644 index 000000000..d9ecfbe85 --- /dev/null +++ b/src/lib/camera/webrtc/sessionDescription.spec.ts @@ -0,0 +1,168 @@ +import type { VideoStreamTier } from '../capabilities/streamTiers.js' + +import { describe, expect, it } from 'vitest' +import { SessionDescription } from 'werift' + +import { CameraVideoQuality } from '../capabilities/streamTiers.js' +import { describeShape, dropMDNSCandidates, isMDNSCandidate, retransmissionSSRCs, writeTierRestrictions } from './sessionDescription.js' + +const FIRST_TIER: VideoStreamTier = { + identifier: 1, + quality: CameraVideoQuality.HIGHEST, + targetAverageBitrate: 1700, + width: 1920, + height: 1080, + frameRate: 30, +} +const SECOND_TIER: VideoStreamTier = { + identifier: 2, + quality: CameraVideoQuality.MEDIUM, + targetAverageBitrate: 600, + width: 1280, + height: 720, + frameRate: 15, +} + +// A synthetic description in werift's shape: video sections of one layer each and an audio section, every section repeating a host candidate on a +// documentation address and a server-reflexive candidate. +const CANDIDATES = [ + 'a=candidate:1 1 udp 2122317823 192.0.2.10 50000 typ host generation 0', + 'a=candidate:2 1 udp 1686052607 198.51.100.7 50001 typ srflx raddr 192.0.2.10 rport 50000 generation 0', +] +const DESCRIPTION = [ + 'v=0', + 'a=group:BUNDLE 0 1 2', + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + ...CANDIDATES, + 'a=rid:1 send', + 'a=simulcast:send 1', + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + ...CANDIDATES, + 'a=rid:2 send', + 'a=simulcast:send 2', + 'm=audio 9 UDP/TLS/RTP/SAVPF 110', + ...CANDIDATES, + '', +].join('\r\n') + +describe('sessionDescription', () => { + it('writes each layer line with its tier\'s width, height, frame rate and bitrate in bits a second, leaving every other line as written', () => { + const written = writeTierRestrictions(DESCRIPTION, new Map([ + ['1', FIRST_TIER], + ['2', SECOND_TIER], + ])) + const lines = written.split('\r\n') + + expect(lines.filter(line => line.startsWith('a=rid:'))).toEqual([ + 'a=rid:1 send max-width=1920;max-height=1080;max-fps=30;max-br=1700000', + 'a=rid:2 send max-width=1280;max-height=720;max-fps=15;max-br=600000', + ]) + expect(lines.filter(line => !line.startsWith('a=rid:'))).toEqual(DESCRIPTION.split('\r\n').filter(line => !line.startsWith('a=rid:'))) + expect(written.endsWith('\r\n')).toBe(true) + }) + + it('counts a description\'s sections by kind and its candidates by type, each candidate once however many sections repeat it', () => { + expect(describeShape(DESCRIPTION)).toEqual({ + audioSections: 1, + candidates: { host: 1, srflx: 1 }, + videoSections: 2, + }) + }) + + it('leaves out every candidate line on an mDNS host and counts them, reading a candidate\'s own text alike', () => { + const mdns = 'a=candidate:3 1 udp 2122317823 0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0.LOCAL 50002 typ host generation 0' + const answer = [ + 'v=0', + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + ...CANDIDATES, + mdns, + 'a=sendonly', + '', + ].join('\r\n') + const { dropped, sdp } = dropMDNSCandidates(answer) + + expect(dropped).toBe(1) + expect(sdp).toBe(answer.replace(`${mdns}\r\n`, '')) + expect(isMDNSCandidate(mdns.slice('a='.length))).toBe(true) + expect(CANDIDATES.map(isMDNSCandidate)).toEqual([false, false]) + + // werift looks up every host that contains .local: a host with a label after it or a trailing dot reads as on an mDNS host too, in any case. + expect([ + 'printer.local', + 'printer.local.example', + 'printer.local.', + 'PRINTER.LOCAL.EXAMPLE', + '192.0.2.40', + 'printer.example', + ].map(host => isMDNSCandidate(`a=candidate:4 1 udp 2122317823 ${host} 50003 typ host`))).toEqual([true, true, true, true, false, false]) + }) + + it('leaves out the same mDNS candidate of an answer written in CRLF and in LF alone, each text keeping its own line ending', () => { + const mdns = 'a=candidate:3 1 udp 2122317823 0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0.local 50002 typ host generation 0' + const lines = [ + 'v=0', + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + ...CANDIDATES, + mdns, + 'a=sendonly', + '', + ] + + for (const end of ['\r\n', '\n']) { + expect(dropMDNSCandidates(lines.join(end))).toEqual({ + dropped: 1, + sdp: lines.filter(line => line !== mdns).join(end), + }) + } + }) + + it('reads a text whose lines mix CRLF and LF as werift does, on CRLF alone, leaving out the one mDNS candidate werift would read', () => { + const routable = 'a=candidate:1 1 udp 2122317823 192.0.2.10 50000 typ host' + // Candidates on an mDNS host inside CRLF lines, each behind an LF, which werift reads as part of the line before it, and one on a CRLF line of its own. + const answer = [ + 'v=0', + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + `${routable}\na=candidate:2 1 udp 2122317823 printer.local 50002 typ host`, + 'a=sendonly\na=candidate:3 1 udp 2122317823 scanner.local 50004 typ host', + 'a=candidate:4 1 udp 2122317823 camera.local 50006 typ host', + '', + ].join('\r\n') + const hosts = (sdp: string): string[] => SessionDescription.parse(sdp).media.flatMap(({ iceCandidates }) => iceCandidates.map(({ ip }) => ip)) + const { dropped, sdp } = dropMDNSCandidates(answer) + + expect(hosts(answer)).toEqual(['192.0.2.10', 'camera.local']) + expect(dropped).toBe(1) + expect(sdp).toBe(answer.replace('a=candidate:4 1 udp 2122317823 camera.local 50006 typ host\r\n', '')) + expect(hosts(sdp)).toEqual(['192.0.2.10']) + }) + + it('counts the sections and candidates of a description written in LF alone as those of its CRLF text', () => { + expect(describeShape(DESCRIPTION.replaceAll('\r\n', '\n'))).toEqual({ + audioSections: 1, + candidates: { host: 1, srflx: 1 }, + videoSections: 2, + }) + }) + + it('reads the SSRCs a description gives to retransmission, the second of each FID group, in CRLF and in LF alone', () => { + const lines = [ + 'v=0', + 'm=audio 9 UDP/TLS/RTP/SAVPF 111 97', + 'a=ssrc-group:FID 1111111111 2222222222', + 'a=ssrc:1111111111 cname:viewer', + 'a=ssrc:2222222222 cname:viewer', + 'a=ssrc-group:SIM 3333333333 4444444444', + 'm=video 9 UDP/TLS/RTP/SAVPF 99 98', + 'a=ssrc-group:FID 5555555555 6666666666', + '', + ] + + for (const end of ['\r\n', '\n']) { + expect([ + ...retransmissionSSRCs(lines.join(end)), + ]).toEqual([2222222222, 6666666666]) + } + + expect(retransmissionSSRCs(['v=0', 'm=audio 9 UDP/TLS/RTP/SAVPF 111', ''].join('\r\n')).size).toBe(0) + }) +}) diff --git a/src/lib/camera/webrtc/sessionDescription.ts b/src/lib/camera/webrtc/sessionDescription.ts new file mode 100644 index 000000000..bc55b2db7 --- /dev/null +++ b/src/lib/camera/webrtc/sessionDescription.ts @@ -0,0 +1,151 @@ +import type { VideoStreamTier } from '../capabilities/streamTiers.js' + +/* The engine's text work on a session description, beside what werift writes itself: each video section's one layer stated with its tier's restrictions, + * a far end's candidates on an mDNS host left out, the SSRCs a far end's description gives to retransmission, and the shape of a description counted for a + * debug line, which never carries the description's text, since its candidates and credentials carry network addresses and secrets. werift ends every + * line of its own descriptions in CRLF, as RFC 8866 writes it, and reads a far end's lines as linesOf does: every reading of a far end's text here sees + * the lines werift will. + */ + +const LINE_END = '\r\n' + +// The line ending werift reads a description holding no CRLF by. +const BARE_LINE_END = '\n' + +// A video section's one layer as werift writes it for a transceiver of one simulcast layer: its rid and its direction, and nothing after them. +const LAYER_LINE = /^a=rid:(\S+) send$/ + +// A candidate line, whose type follows its typ keyword. +const CANDIDATE_LINE = /^a=candidate:\S+ \d+ \S+ \d+ \S+ \d+ typ (\S+)/ + +// A candidate, as a line of a description or as a candidate's own text, whose connection address is its fifth field, after its foundation, its component, +// its transport and its priority. +const CANDIDATE_ADDRESS = /^(?:a=)?candidate:\S+ \d+ \S+ \d+ (\S+) / + +// A source group of RFC 5576 pairing a stream's SSRC with its retransmission's, as RFC 4588 8.1 names the pair: the stream's first and the retransmission's +// second. +const FID_GROUP = /^a=ssrc-group:FID \d+ (\d+)/ + +// The domain of an mDNS host name. werift starts a multicast DNS lookup of its own for every candidate whose host contains it anywhere, a label after it or +// a trailing dot among the forms, and no caller can catch that lookup's failure, which is why the filter leaves out every host that contains it, in any case. The +// camera's side reaches a far end on its routable candidates alone. +const MDNS_DOMAIN = '.local' + +/** + * What a description holds, counted: its audio and video sections, and its candidates by type, each counted once however many sections repeat it. + */ +export interface DescriptionShape { + readonly audioSections: number + readonly candidates: Readonly> + readonly videoSections: number +} + +/** + * Writes each video section's layer line with the restrictions of the tier it sends, in RFC 8851's form: the tier's width, height and frame rate, and its + * bitrate in bits a second. A viewer is given each tier as a record of its own and picks among them by what each line states, which is why a line states exactly + * the tier its section sends. Every other line is left as written. + * @param sdp - The description, as werift wrote it. + * @param tiers - Each layer's tier, by the layer's rid. + * @returns The description with each layer line restricted. + */ +export function writeTierRestrictions(sdp: string, tiers: ReadonlyMap): string { + return sdp.split(LINE_END).map((line) => { + const rid = LAYER_LINE.exec(line)?.[1] + const tier = rid === undefined + ? undefined + : tiers.get(rid) + + if (!tier) { + return line + } + + const { frameRate, height, targetAverageBitrate, width } = tier + + return `${line} max-width=${width};max-height=${height};max-fps=${frameRate};max-br=${targetAverageBitrate * 1000}` + }).join(LINE_END) +} + +/** + * Whether a candidate's host is one werift would look up by multicast DNS: a host that contains `.local` anywhere, in any case, since werift looks up + * every host that contains it, and not only one that ends in it. + * @param candidate - The candidate, as a description's line or as its own text. + * @returns Whether its host contains `.local`. + */ +export function isMDNSCandidate(candidate: string): boolean { + return CANDIDATE_ADDRESS.exec(candidate)?.[1].toLowerCase().includes(MDNS_DOMAIN) === true +} + +/* A description's lines as werift's own parser splits them, with the ending they were split on: on CRLF, and on LF alone when the text holds no CRLF. A + * text whose lines mix the endings is split on CRLF alone, and an LF inside one of its lines stays inside it, as werift reads that line. + */ +function linesOf(sdp: string): { end: string, lines: string[] } { + const lines = sdp.split(LINE_END) + + if (lines.length > 1) { + return { end: LINE_END, lines } + } + + return { + end: BARE_LINE_END, + lines: sdp.split(BARE_LINE_END), + } +} + +/** + * Leaves out of a description every candidate line whose host is an mDNS name, reading its lines as werift does, which means werift never sees one. The text keeps + * the line ending it came with. + * @param sdp - The description. + * @returns The description without those lines, and how many it left out. + */ +export function dropMDNSCandidates(sdp: string): { dropped: number, sdp: string } { + const { end, lines } = linesOf(sdp) + const kept = lines.filter(line => !isMDNSCandidate(line)) + + return { + dropped: lines.length - kept.length, + sdp: kept.join(end), + } +} + +/** + * Counts what a description holds, for a debug line that states the counts alone, reading its lines as werift does. + * @param sdp - The description. + * @returns Its sections by kind and its candidates by type. + */ +export function describeShape(sdp: string): DescriptionShape { + const { lines } = linesOf(sdp) + const candidates: Record = {} + + for (const line of new Set(lines)) { + const type = CANDIDATE_LINE.exec(line)?.[1] + + if (type !== undefined) { + candidates[type] = (candidates[type] ?? 0) + 1 + } + } + + return { + audioSections: lines.filter(line => line.startsWith('m=audio ')).length, + candidates, + videoSections: lines.filter(line => line.startsWith('m=video ')).length, + } +} + +/** + * The SSRCs a description gives to retransmission, the second of each `FID` source group, reading its lines as werift does. + * @param sdp - The description. + * @returns The SSRCs. + */ +export function retransmissionSSRCs(sdp: string): Set { + const ssrcs = new Set() + + for (const line of linesOf(sdp).lines) { + const ssrc = FID_GROUP.exec(line)?.[1] + + if (ssrc !== undefined) { + ssrcs.add(Number(ssrc)) + } + } + + return ssrcs +} diff --git a/src/lib/camera/webrtc/sframe.spec.ts b/src/lib/camera/webrtc/sframe.spec.ts new file mode 100644 index 000000000..d568feb68 --- /dev/null +++ b/src/lib/camera/webrtc/sframe.spec.ts @@ -0,0 +1,376 @@ +import type { SFrameVector } from '../../../test-utils/sframeVectors.js' +import type { SFrameStreamKeys, SFrameSuite } from './sframe.js' + +import { Buffer } from 'node:buffer' +import { randomBytes } from 'node:crypto' + +import { describe, expect, it } from 'vitest' + +import { openSFrameReference, SFRAME_VECTORS } from '../../../test-utils/sframeVectors.js' +import { + deriveStreamKeys, + openSFrame, + readSFrameHeader, + sealSFrame, + SFRAME_AUDIO_SUITE, + SFRAME_VIDEO_SUITE, + sframeHeader, + sframeNonce, + sframePayloads, + SFrameSealer, +} from './sframe.js' + +const SESSION_KEY = Buffer.from(SFRAME_VECTORS.sessionKey, 'hex') + +// The counters a stream's sealer reaches by counting from zero in a row's time; the vectors' wider counters are sealed at their named counter. +const COUNTED_LIMIT = 1024n + +// The suite a vector names. +function suiteOf(vector: SFrameVector): SFrameSuite { + return vector.suite === SFRAME_VIDEO_SUITE.identifier + ? SFRAME_VIDEO_SUITE + : SFRAME_AUDIO_SUITE +} + +// The keys of a vector's stream, under the vectors' session key. +function keysOf(vector: SFrameVector): ReturnType { + return deriveStreamKeys({ + keyId: vector.keyId, + sessionKey: SESSION_KEY, + ssrc: vector.ssrc, + suite: suiteOf(vector), + }) +} + +// A vector's plaintext. +function plaintextOf(vector: SFrameVector): Buffer { + return Buffer.from(SFRAME_VECTORS.plaintexts[vector.plaintext], 'hex') +} + +// A vector's ciphertext opened under the suite's own opener. +function openVector(vector: SFrameVector, ciphertext: Buffer): Buffer | undefined { + return openSFrameReference({ + ciphertext, + sessionKey: SESSION_KEY, + ssrc: vector.ssrc, + suite: vector.suite, + tagLength: vector.tagLength, + }) +} + +// A ciphertext opened under the module's own opener, its header read first, as a reader of a viewer's packets opens one. +function opened(keys: SFrameStreamKeys, ciphertext: Buffer): Buffer | undefined { + const header = readSFrameHeader(ciphertext) + + return header && openSFrame(keys, header, ciphertext) +} + +describe('sframe', () => { + it('makes every vector\'s stream secret, keys, salt, nonce, header, tag and ciphertext, a sealer counting from zero and the sealing at a named counter alike', () => { + for (const vector of SFRAME_VECTORS.vectors) { + const keys = keysOf(vector) + const plaintext = plaintextOf(vector) + + expect(keys.secret.toString('hex')).toBe(vector.streamSecret) + expect(keys.encryptionKey.toString('hex')).toBe(vector.encryptionKey) + expect(keys.authenticationKey.toString('hex')).toBe(vector.authenticationKey) + expect(keys.salt.toString('hex')).toBe(vector.salt) + expect(sframeNonce(keys.salt, vector.counter).toString('hex')).toBe(vector.nonce) + expect(sframeHeader(vector.keyId, vector.counter).toString('hex')).toBe(vector.header) + + const ciphertext = sealSFrame(keys, vector.counter, plaintext) + + expect(ciphertext.toString('hex')).toBe(vector.ciphertext) + expect(ciphertext.subarray(ciphertext.length - vector.tagLength).toString('hex')).toBe(vector.tag) + } + + const counted = SFRAME_VECTORS.vectors.filter(vector => vector.counter < COUNTED_LIMIT) + + for (const vector of counted) { + const plaintext = plaintextOf(vector) + const sealer = new SFrameSealer(keysOf(vector)) + + for (let count = 0n; count < vector.counter; count++) { + sealer.seal(plaintext) + } + + expect(sealer.seal(plaintext).toString('hex')).toBe(vector.ciphertext) + } + + expect(counted.length).toBeGreaterThan(0) + expect(counted.length).toBeLessThan(SFRAME_VECTORS.vectors.length) + expect(sealSFrame(keysOf(SFRAME_VECTORS.vectors[0]), 0xFFFFFFFFFFFFFFFFn, Buffer.from('frame')).subarray(0, 17).toString('hex')) + .toBe(`ff${SFRAME_VECTORS.vectors[0].keyId.toString(16)}ffffffffffffffff`) + expect(() => sealSFrame(keysOf(SFRAME_VECTORS.vectors[0]), 0x10000000000000000n, Buffer.from('frame'))).toThrow(RangeError) + }) + + it('seals what opens under the suite\'s own opener to its frame, which refuses a changed header octet, ciphertext octet or tag octet', () => { + const sessionKey = randomBytes(32) + + for (const suite of [SFRAME_VIDEO_SUITE, SFRAME_AUDIO_SUITE]) { + const sealer = new SFrameSealer(deriveStreamKeys({ + keyId: 0x1234568000n, + sessionKey, + ssrc: 0x01020304, + suite, + })) + + for (const length of [1, 9, 300, 4000]) { + const frame = randomBytes(length) + const ciphertext = sealer.seal(frame) + const open = (sealed: Buffer): Buffer | undefined => openSFrameReference({ + ciphertext: sealed, + sessionKey, + ssrc: 0x01020304, + suite: suite.identifier, + tagLength: suite.tagLength, + }) + + expect(open(ciphertext)?.equals(frame)).toBe(true) + + for (const offset of [ + 0, + 1, + ciphertext.length - suite.tagLength - 1, + ciphertext.length - 1, + ]) { + const changed = Buffer.from(ciphertext) + + changed[offset] ^= 0x01 + expect(open(changed)).toBeUndefined() + } + } + } + + for (const vector of SFRAME_VECTORS.vectors) { + const ciphertext = Buffer.from(vector.ciphertext, 'hex') + const headerLength = vector.header.length / 2 + + expect(openVector(vector, ciphertext)?.equals(plaintextOf(vector))).toBe(true) + + for (const offset of [headerLength - 1, headerLength, ciphertext.length - 1]) { + const changed = Buffer.from(ciphertext) + + changed[offset] ^= 0x80 + expect(openVector(vector, changed)).toBeUndefined() + } + } + }) + + it('cuts a ciphertext into the vectors\' payloads at their size, each put back giving the ciphertext, one that fits a payload behind 0xc0', () => { + for (const vector of SFRAME_VECTORS.vectors) { + const ciphertext = Buffer.from(vector.ciphertext, 'hex') + const payloads = sframePayloads(ciphertext, SFRAME_VECTORS.rtpPayloadSize) + const octets = payloads.length === 1 + ? [0xC0] + : [ + 0x80, + ...Array.from({ length: payloads.length - 2 }).fill(0x00), + 0x40, + ] + + expect(payloads.map(payload => payload.toString('hex'))).toEqual(vector.rtpPayloads) + expect(Buffer.concat(payloads.map(payload => payload.subarray(1))).equals(ciphertext)).toBe(true) + expect(payloads.every(payload => payload.length <= SFRAME_VECTORS.rtpPayloadSize)).toBe(true) + expect(payloads.map(payload => payload[0])).toEqual(octets) + } + + expect(SFRAME_VECTORS.vectors.some(vector => vector.rtpPayloads.length > 2)).toBe(true) + + const ciphertext = randomBytes(5000) + const payloads = sframePayloads(ciphertext, 1088) + + expect(payloads.map(payload => payload.length)).toEqual([1088, 1088, 1088, 1088, 653]) + expect(new Set(payloads.map(payload => payload.buffer)).size).toBe(payloads.length) + expect(Buffer.concat(payloads.map(payload => payload.subarray(1))).equals(ciphertext)).toBe(true) + }) + + it('zeroes a sealer\'s stream secret, keys and salt at its disposal, read on the bytes', () => { + for (const suite of [SFRAME_VIDEO_SUITE, SFRAME_AUDIO_SUITE]) { + const keys = deriveStreamKeys({ + keyId: 0xFEDCBA9876548000n, + sessionKey: SESSION_KEY, + ssrc: 0x0BADCAFE, + suite, + }) + const sealer = new SFrameSealer(keys) + + sealer.seal(Buffer.from('frame')) + + for (const value of [ + keys.secret, + keys.encryptionKey, + keys.authenticationKey, + keys.salt, + ]) { + expect(value.some(octet => octet !== 0)).toBe(true) + } + + sealer[Symbol.dispose]() + + for (const value of [ + keys.secret, + keys.encryptionKey, + keys.authenticationKey, + keys.salt, + ]) { + expect(value.every(octet => octet === 0)).toBe(true) + } + + expect([ + keys.secret.length, + keys.encryptionKey.length, + keys.authenticationKey.length, + keys.salt.length, + ]).toEqual([64, 32, 64, 12]) + } + }) + + it('opens every vector under the module\'s own opener to its plaintext, its header read back to the vector\'s key ID, counter and length', () => { + for (const vector of SFRAME_VECTORS.vectors) { + const ciphertext = Buffer.from(vector.ciphertext, 'hex') + + expect(readSFrameHeader(ciphertext)).toEqual({ + counter: vector.counter, + keyId: vector.keyId, + length: vector.header.length / 2, + }) + expect(opened(keysOf(vector), ciphertext)?.equals(plaintextOf(vector))).toBe(true) + } + }) + + it('refuses under the module\'s own opener a changed header octet, ciphertext octet or tag octet, of every vector and of what the sealer seals', () => { + for (const vector of SFRAME_VECTORS.vectors) { + const ciphertext = Buffer.from(vector.ciphertext, 'hex') + const headerLength = vector.header.length / 2 + + for (const offset of [headerLength - 1, headerLength, ciphertext.length - 1]) { + const changed = Buffer.from(ciphertext) + + changed[offset] ^= 0x80 + expect(opened(keysOf(vector), changed)).toBeUndefined() + } + } + + const sessionKey = randomBytes(32) + + for (const suite of [SFRAME_VIDEO_SUITE, SFRAME_AUDIO_SUITE]) { + const keys = deriveStreamKeys({ + keyId: 0x1234568000n, + sessionKey, + ssrc: 0x01020304, + suite, + }) + const sealer = new SFrameSealer(keys) + + for (const length of [1, 9, 300, 4000]) { + const ciphertext = sealer.seal(randomBytes(length)) + + for (const offset of [ + 0, + 1, + ciphertext.length - suite.tagLength - 1, + ciphertext.length - 1, + ]) { + const changed = Buffer.from(ciphertext) + + changed[offset] ^= 0x01 + expect(opened(keys, changed)).toBeUndefined() + } + } + } + }) + + it('refuses a ciphertext shorter than its suite\'s tag, one shorter than its header and tag, and one shorter than its config byte\'s header, throwing ' + + 'nothing', () => { + const keyId = 0xFEDCBA9876548000n + + for (const suite of [SFRAME_VIDEO_SUITE, SFRAME_AUDIO_SUITE]) { + const keys = deriveStreamKeys({ + keyId, + sessionKey: SESSION_KEY, + ssrc: 0x0BADCAFE, + suite, + }) + const sealed = sealSFrame(keys, 0n, Buffer.from('frame')) + const header = readSFrameHeader(sealed)! + const shorterThanTag = Buffer.alloc(suite.tagLength - 1) + const shorterThanHeaderAndTag = sealed.subarray(0, header.length + suite.tagLength - 1) + const shorterThanHeader = sframeHeader(keyId, 300n).subarray(0, 6) + + expect(readSFrameHeader(shorterThanTag)).toEqual({ counter: 0n, keyId: 0n, length: 1 }) + expect(shorterThanHeaderAndTag.length).toBeGreaterThanOrEqual(suite.tagLength) + expect(readSFrameHeader(shorterThanHeader)).toBeUndefined() + expect(readSFrameHeader(Buffer.alloc(0))).toBeUndefined() + + for (const ciphertext of [ + shorterThanTag, + shorterThanHeaderAndTag, + shorterThanHeader, + Buffer.alloc(0), + ]) { + expect(() => opened(keys, ciphertext)).not.toThrow() + expect(opened(keys, ciphertext)).toBeUndefined() + } + } + }) + + it('reads back every key ID and counter sframeHeader writes, each in its config byte\'s bits and in the octets after it, reading no octet past the header', + () => { + const values = [ + 0n, + 7n, + 8n, + 255n, + 256n, + 0x8000n, + 0xFEDCBA9876548000n, + 2n ** 64n - 1n, + ] + + for (const keyId of values) { + for (const counter of values) { + const header = sframeHeader(keyId, counter) + + expect(readSFrameHeader(Buffer.concat([ + header, + Buffer.from([0xFF, 0xFF]), + ]))).toEqual({ counter, keyId, length: header.length }) + } + } + + expect(sframeHeader(7n, 7n)).toHaveLength(1) + expect(sframeHeader(2n ** 64n - 1n, 2n ** 64n - 1n)).toHaveLength(17) + }) + + it('opens what the sealer seals under the module\'s own opener and the suite\'s own opener alike, each frame in a buffer of its own', () => { + const sessionKey = randomBytes(32) + + for (const suite of [SFRAME_VIDEO_SUITE, SFRAME_AUDIO_SUITE]) { + const keys = deriveStreamKeys({ + keyId: 0x2468ACE08000n, + sessionKey, + ssrc: 0x05060708, + suite, + }) + const sealer = new SFrameSealer(keys) + + for (const [count, length] of [1, 9, 300, 4000].entries()) { + const frame = randomBytes(length) + const ciphertext = sealer.seal(frame) + const frameOpened = opened(keys, ciphertext) + + expect(readSFrameHeader(ciphertext)?.counter).toBe(BigInt(count)) + expect(frameOpened?.equals(frame)).toBe(true) + expect(frameOpened?.buffer).not.toBe(ciphertext.buffer) + expect(openSFrameReference({ + ciphertext, + sessionKey, + ssrc: 0x05060708, + suite: suite.identifier, + tagLength: suite.tagLength, + })?.equals(frame)).toBe(true) + } + } + }) +}) diff --git a/src/lib/camera/webrtc/sframe.ts b/src/lib/camera/webrtc/sframe.ts new file mode 100644 index 000000000..4442a6472 --- /dev/null +++ b/src/lib/camera/webrtc/sframe.ts @@ -0,0 +1,378 @@ +import { Buffer } from 'node:buffer' +import { createCipheriv, createDecipheriv, createHmac, hkdfSync, timingSafeEqual } from 'node:crypto' + +/* SFrame (RFC 9605) as HomeKit's WebRTC streams build it, in both directions: the engine seals what the camera sends and opens a viewer's voice, by one + * construction read forwards and backwards. One session key keys every stream of a session, each stream under a secret of its own drawn from that key and + * the SSRC that keys the stream, which stands where RFC 9605 has the base key; the key and the salt come from that secret under the RFC's labels, and the + * nonce, the header and the tag are the RFC's, with no metadata. One whole encoded frame is one ciphertext, cut across RTP payloads each behind the octet + * that marks its place in the ciphertext. + */ + +// A stream's secret: HKDF-SHA-512 of the session key, with the stream's SSRC in four octets as the salt and this info, 64 octets. +const STREAM_SECRET_INFO = 'SFrame 1.0 RTP Stream' +const STREAM_SECRET_LENGTH = 64 + +// The labels a stream's keys and salt are derived under from its secret, each followed by the key ID in eight octets and the suite in two. Each label ends +// in a space, which the derivation covers. +const KEY_LABEL = Buffer.from('SFrame 1.0 Secret key ') +const SALT_LABEL = Buffer.from('SFrame 1.0 Secret salt ') + +// Every suite of HomeKit's streams is AES-256 in counter mode with an HMAC-SHA-512 tag: the 32-octet encryption key and the 64-octet authentication key +// derived as one run, and a salt of the nonce's length. +const ENCRYPTION_KEY_LENGTH = 32 +const AUTHENTICATION_KEY_LENGTH = 64 +const NONCE_LENGTH = 12 + +// The counter block the cipher starts from is the nonce and four octets of zero, the block count AES-256 in counter mode steps. +const COUNTER_BLOCK_LENGTH = 16 + +// The widest count a header carries, eight octets, past which a stream's key can seal nothing. +const COUNTER_LIMIT = 0xFFFFFFFFFFFFFFFFn + +// A header's config byte: the flag that marks a key ID written after it and the three bits that carry the ID or its length, then the same for the counter. +// A value under 8 sits in its three bits, and a larger one is written in the fewest octets that hold it, its length less one in the bits. +const KEY_EXTENDED = 0x80 +const KEY_SHIFT = 4 +const COUNTER_EXTENDED = 0x08 +const VALUE_BITS = 0x07 +const INLINE_LIMIT = 8n + +// The octet before each RTP payload of a ciphertext: its first bit marks the payload that opens the ciphertext and its second the one that closes it. A +// payload holding the whole ciphertext carries both. +export const FIRST_PAYLOAD = 0x80 +export const LAST_PAYLOAD = 0x40 + +/** + * A suite of HomeKit's streams: its identifier, which the key and salt derivations carry, and the length of its tag in octets. + */ +export interface SFrameSuite { + readonly identifier: number + readonly tagLength: number +} + +/** + * The suite a video stream is sealed under, identifier 6 with a ten-octet tag, outside RFC 9605's registry. + */ +export const SFRAME_VIDEO_SUITE: SFrameSuite = { identifier: 6, tagLength: 10 } + +/** + * The suite an audio stream is sealed under, identifier 8 with a four-octet tag, outside RFC 9605's registry. + */ +export const SFRAME_AUDIO_SUITE: SFrameSuite = { identifier: 8, tagLength: 4 } + +/** + * What one stream seals and opens under for one key ID: the stream's secret, the keys and the salt derived from it, the key ID its headers carry and its + * suite. + */ +export interface SFrameStreamKeys { + readonly authenticationKey: Buffer + readonly encryptionKey: Buffer + readonly keyId: bigint + readonly salt: Buffer + readonly secret: Buffer + readonly suite: SFrameSuite +} + +/** + * An SFrame header as a ciphertext carries it: the key ID, the counter and the octets the header takes, the config byte among them. + */ +export interface SFrameHeader { + readonly counter: bigint + readonly keyId: bigint + readonly length: number +} + +/** + * Derives what one stream seals and opens under, each value once for the stream and its key ID. + * @param stream - The stream's key ID, the session key, the SSRC that keys the stream and the stream's suite. + * @param stream.keyId - The key ID the stream's headers carry, a 64-bit value. + * @param stream.sessionKey - The session's key. + * @param stream.ssrc - The SSRC that keys the stream: for a stream the camera sends, the SSRC the stream was set up with, which its section names, whatever + * a packet's own SSRC reads; for a viewer's voice, which no section names, the voice stream's own SSRC. + * @param stream.suite - The stream's suite. + * @returns The stream's secret, keys and salt, with its key ID and suite. + */ +export function deriveStreamKeys(stream: { keyId: bigint, sessionKey: Buffer, ssrc: number, suite: SFrameSuite }): SFrameStreamKeys { + const { keyId, sessionKey, ssrc, suite } = stream + const ssrcOctets = Buffer.alloc(4) + const label = Buffer.alloc(10) + + ssrcOctets.writeUInt32BE(ssrc) + label.writeBigUInt64BE(keyId) + label.writeUInt16BE(suite.identifier, 8) + + const secret = Buffer.from(hkdfSync('sha512', sessionKey, ssrcOctets, STREAM_SECRET_INFO, STREAM_SECRET_LENGTH)) + const keys = Buffer.from(hkdfSync('sha512', secret, Buffer.alloc(0), Buffer.concat([KEY_LABEL, label]), ENCRYPTION_KEY_LENGTH + AUTHENTICATION_KEY_LENGTH)) + const salt = Buffer.from(hkdfSync('sha512', secret, Buffer.alloc(0), Buffer.concat([SALT_LABEL, label]), NONCE_LENGTH)) + + return { + authenticationKey: keys.subarray(ENCRYPTION_KEY_LENGTH), + encryptionKey: keys.subarray(0, ENCRYPTION_KEY_LENGTH), + keyId, + salt, + secret, + suite, + } +} + +/** + * Zeroes what a stream seals and opens under: its secret, both keys and its salt, every value its derivation made. + * @param keys - The stream's keys. + */ +export function zeroStreamKeys(keys: SFrameStreamKeys): void { + keys.secret.fill(0) + keys.encryptionKey.fill(0) + keys.authenticationKey.fill(0) + keys.salt.fill(0) +} + +// The octets a header value takes after the config byte: none for a value the config byte carries, and otherwise the fewest that hold it. +function valueLength(value: bigint): number { + if (value < INLINE_LIMIT) { + return 0 + } + + let length = 1 + + while ((value >> BigInt(8 * length)) > 0n) { + length++ + } + + return length +} + +// Writes a header value big-endian in its octets. +function writeValue(header: Buffer, offset: number, value: bigint, length: number): void { + for (let index = length - 1; index >= 0; index--) { + header[offset + index] = Number(value & 0xFFn) + value >>= 8n + } +} + +/** + * Writes the SFrame header RFC 9605 defines for a key ID and a counter, each in its config byte's bits while under 8 and otherwise after it. + * @param keyId - The key ID. + * @param counter - The counter. + * @returns The header. + */ +export function sframeHeader(keyId: bigint, counter: bigint): Buffer { + const keyLength = valueLength(keyId) + const counterLength = valueLength(counter) + const header = Buffer.alloc(1 + keyLength + counterLength) + const keyBits = keyLength + ? KEY_EXTENDED | ((keyLength - 1) << KEY_SHIFT) + : Number(keyId) << KEY_SHIFT + const counterBits = counterLength + ? COUNTER_EXTENDED | (counterLength - 1) + : Number(counter) + + header[0] = keyBits | counterBits + writeValue(header, 1, keyId, keyLength) + writeValue(header, 1 + keyLength, counter, counterLength) + + return header +} + +// Reads a header value big-endian from its octets. +function readValue(data: Buffer, offset: number, length: number): bigint { + let value = 0n + + for (let index = 0; index < length; index++) { + value = (value << 8n) | BigInt(data[offset + index]) + } + + return value +} + +/** + * Reads the SFrame header RFC 9605 writes at a ciphertext's start: the key ID and the counter, each from its config byte's bits or from the octets after + * it that the bits give the length of, and the octets the header takes. + * @param ciphertext - The ciphertext. + * @returns The header, or `undefined` for a ciphertext shorter than the header its config byte states, an empty one among them. + */ +export function readSFrameHeader(ciphertext: Buffer): SFrameHeader | undefined { + if (ciphertext.length === 0) { + return undefined + } + + const config = ciphertext[0] + const keyBits = (config >> KEY_SHIFT) & VALUE_BITS + const counterBits = config & VALUE_BITS + const keyLength = (config & KEY_EXTENDED) + ? keyBits + 1 + : 0 + const counterLength = (config & COUNTER_EXTENDED) + ? counterBits + 1 + : 0 + const length = 1 + keyLength + counterLength + + if (ciphertext.length < length) { + return undefined + } + + return { + counter: counterLength + ? readValue(ciphertext, 1 + keyLength, counterLength) + : BigInt(counterBits), + keyId: keyLength + ? readValue(ciphertext, 1, keyLength) + : BigInt(keyBits), + length, + } +} + +// The counter block a frame's cipher starts from: the salt with the counter in eight octets laid over its last eight by XOR, the nonce, then four zero +// octets. +function counterBlock(salt: Buffer, counter: bigint): Buffer { + const block = Buffer.alloc(COUNTER_BLOCK_LENGTH) + + salt.copy(block) + block.writeBigUInt64BE(block.readBigUInt64BE(NONCE_LENGTH - 8) ^ counter, NONCE_LENGTH - 8) + + return block +} + +/** + * The nonce a frame is sealed under: the stream's salt with the counter in eight octets laid over its last eight by XOR. + * @param salt - The stream's salt. + * @param counter - The frame's counter. + * @returns The twelve-octet nonce. + */ +export function sframeNonce(salt: Buffer, counter: bigint): Buffer { + return counterBlock(salt, counter).subarray(0, NONCE_LENGTH) +} + +// A ciphertext's tag, the one computation the sealer writes and the opener checks: HMAC-SHA-512 under the stream's authentication key over the header's +// and the encrypted frame's lengths, the tag's length, the nonce, the header and the encrypted frame, cut to the suite's tag length. +function tagOf(keys: SFrameStreamKeys, nonce: Buffer, header: Buffer, body: Buffer): Buffer { + const { tagLength } = keys.suite + const lengths = Buffer.alloc(24) + + lengths.writeBigUInt64BE(BigInt(header.length), 0) + lengths.writeBigUInt64BE(BigInt(body.length), 8) + lengths.writeBigUInt64BE(BigInt(tagLength), 16) + + return createHmac('sha512', keys.authenticationKey).update(lengths).update(nonce).update(header).update(body).digest().subarray(0, tagLength) +} + +/** + * Seals one whole frame under a stream's keys at a counter: the header, the frame encrypted under AES-256 in counter mode, and the tag, HMAC-SHA-512 over + * the header's and the encrypted frame's lengths, the tag's length, the nonce, the header and the encrypted frame, cut to the suite's tag length. + * @param keys - The stream's keys. + * @param counter - The frame's counter, used once under the stream's key. + * @param frame - The frame. + * @returns The ciphertext, its header first and its tag last. + * @throws RangeError for a counter past the widest a header carries. + */ +export function sealSFrame(keys: SFrameStreamKeys, counter: bigint, frame: Buffer): Buffer { + if (counter > COUNTER_LIMIT) { + throw new RangeError('An SFrame counter past 2^64 - 1 cannot be sealed, because no header carries it.') + } + + const header = sframeHeader(keys.keyId, counter) + const block = counterBlock(keys.salt, counter) + const ciphertext = Buffer.alloc(header.length + frame.length + keys.suite.tagLength) + const body = ciphertext.subarray(header.length, header.length + frame.length) + const cipher = createCipheriv('aes-256-ctr', keys.encryptionKey, block) + + header.copy(ciphertext) + cipher.update(frame).copy(body) + cipher.final() + tagOf(keys, block.subarray(0, NONCE_LENGTH), header, body).copy(ciphertext, header.length + body.length) + + return ciphertext +} + +/** + * Opens one ciphertext under a stream's keys: the tag is computed as the sealer computes it and compared with the ciphertext's own in constant time, and + * the encrypted frame is decrypted, under the counter block the sealer builds from the header's counter, only once the tag holds. Nothing is decrypted + * for a ciphertext that does not open. + * @param keys - The stream's keys for the key ID the header names. + * @param header - The ciphertext's header, as {@link readSFrameHeader} reads it. + * @param ciphertext - The ciphertext, its header first and its tag last. + * @returns The frame, in a buffer of its own, or `undefined` for a ciphertext shorter than its header and the suite's tag or one whose tag does not hold. + */ +export function openSFrame(keys: SFrameStreamKeys, header: SFrameHeader, ciphertext: Buffer): Buffer | undefined { + const end = ciphertext.length - keys.suite.tagLength + + if (end < header.length) { + return undefined + } + + const block = counterBlock(keys.salt, header.counter) + const body = ciphertext.subarray(header.length, end) + + if (!timingSafeEqual(tagOf(keys, block.subarray(0, NONCE_LENGTH), ciphertext.subarray(0, header.length), body), ciphertext.subarray(end))) { + return undefined + } + + const decipher = createDecipheriv('aes-256-ctr', keys.encryptionKey, block) + const frame = decipher.update(body) + + decipher.final() + + return frame +} + +/** + * Cuts a ciphertext into RTP payloads of at most a size, each a buffer of its own: the octet that marks the payload's place first, `0x80` on the first, + * `0x00` on one in the middle, `0x40` on the last and `0xC0` on one that holds the ciphertext whole, then the ciphertext's octets. + * @param ciphertext - The ciphertext. + * @param payloadSize - The most octets a payload takes, its octet in front among them. + * @returns The payloads, in order. + */ +export function sframePayloads(ciphertext: Buffer, payloadSize: number): Buffer[] { + const pieceSize = payloadSize - 1 + const payloads: Buffer[] = [] + + for (let start = 0; start < ciphertext.length; start += pieceSize) { + const end = Math.min(start + pieceSize, ciphertext.length) + const payload = Buffer.alloc(1 + end - start) + + if (start === 0) { + payload[0] |= FIRST_PAYLOAD + } + + if (end === ciphertext.length) { + payload[0] |= LAST_PAYLOAD + } + + ciphertext.copy(payload, 1, start, end) + payloads.push(payload) + } + + return payloads +} + +/** + * The sealer of one stream: its keys, held from their derivation to its disposal, and its count, from zero, which every seal steps once. No count is + * sealed twice under the stream's key whatever the stream's source or its viewer does. + */ +export class SFrameSealer implements Disposable { + private count = 0n + + /** + * Takes a stream's keys, which the sealer zeroes at its disposal. + * @param keys - The stream's keys. + */ + constructor(private readonly keys: SFrameStreamKeys) {} + + /** + * Seals one whole frame at the stream's next count. + * @param frame - The frame. + * @returns The ciphertext. + * @throws RangeError once the stream has sealed its widest count. + */ + seal(frame: Buffer): Buffer { + const ciphertext = sealSFrame(this.keys, this.count, frame) + + this.count++ + + return ciphertext + } + + // Zeroes the stream's secret, keys and salt, every copy the sealer derived. + [Symbol.dispose](): void { + zeroStreamKeys(this.keys) + } +} diff --git a/src/lib/camera/webrtc/voice/ReceiveKeys.spec.ts b/src/lib/camera/webrtc/voice/ReceiveKeys.spec.ts new file mode 100644 index 000000000..f12594a71 --- /dev/null +++ b/src/lib/camera/webrtc/voice/ReceiveKeys.spec.ts @@ -0,0 +1,154 @@ +import type { WebRTCReceiveKeysUpdate } from '../../WebRTCStreamManagement.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { RECEIVE_KEY_LIMIT, ReceiveKeys } from './ReceiveKeys.js' + +// A made-up 32-octet key, its octets patterned from a seed. +function key(seed: number): Buffer { + return Buffer.alloc(32, seed) +} + +// An update of the keys to add, by key ID, and the key IDs to remove. +function update(add: [bigint, Buffer][], remove: bigint[] = []): WebRTCReceiveKeysUpdate { + return { + receiveKeysToAdd: add.map(([kid, added]) => ({ key: added, kid })), + receiveKIDsToRemove: remove.map(kid => ({ kid })), + } +} + +function zeroed(buffer: Buffer): boolean { + return buffer.every(octet => octet === 0) +} + +describe('receiveKeys', () => { + it('holds each key an update adds by its key ID as the very buffer handed, copying none and answering no key ID zeroed', () => { + const store = new ReceiveKeys() + const first = key(1) + const second = key(2) + + expect(store.update(update([ + [0x8001n, first], + [0x8002n, second], + ]))).toEqual([]) + expect(store.get(0x8001n)).toBe(first) + expect(store.get(0x8002n)).toBe(second) + expect(store.get(0x8003n)).toBeUndefined() + expect(store.size).toBe(2) + expect(first.equals(key(1))).toBe(true) + }) + + it('zeroes and drops the key a removal names, answering its key ID, and answers nothing for a removal of a key ID it does not hold', () => { + const store = new ReceiveKeys() + const removed = key(1) + const kept = key(2) + + store.update(update([ + [0x8001n, removed], + [0x8002n, kept], + ])) + + expect(store.update(update([], [0x8001n, 0x8009n]))).toEqual([0x8001n]) + expect(zeroed(removed)).toBe(true) + expect(store.get(0x8001n)).toBeUndefined() + expect(store.get(0x8002n)).toBe(kept) + expect(kept.equals(key(2))).toBe(true) + expect(store.size).toBe(1) + }) + + it('zeroes the key an addition replaces under its key ID, answering that ID and holding the key added', () => { + const store = new ReceiveKeys() + const replaced = key(1) + const added = key(2) + + store.update(update([ + [0x8001n, replaced], + ])) + + expect(store.update(update([ + [0x8001n, added], + ]))).toEqual([0x8001n]) + expect(zeroed(replaced)).toBe(true) + expect(store.get(0x8001n)).toBe(added) + expect(added.equals(key(2))).toBe(true) + }) + + it('applies an update\'s removals before its additions, which is why one that removes and adds one key ID holds the key added, intact', () => { + const store = new ReceiveKeys() + const held = key(1) + const added = key(2) + + store.update(update([ + [0x8001n, held], + ])) + + expect(store.update(update([ + [0x8001n, added], + ], [0x8001n]))).toEqual([0x8001n]) + expect(zeroed(held)).toBe(true) + expect(store.get(0x8001n)).toBe(added) + expect(added.equals(key(2))).toBe(true) + expect(store.size).toBe(1) + }) + + it('zeroes and drops every key it holds at its disposal', () => { + const store = new ReceiveKeys() + const keys = [ + key(1), + key(2), + key(3), + ] + + store.update(update(keys.map((each, index) => [ + BigInt(0x8000 + index), + each, + ]))) + store[Symbol.dispose]() + + expect(keys.map(zeroed)).toEqual([true, true, true]) + expect(store.size).toBe(0) + }) + + it('answers nothing and changes nothing for an update with no key and no key ID', () => { + const store = new ReceiveKeys() + const held = key(1) + + store.update(update([ + [0x8001n, held], + ])) + + expect(store.update(update([]))).toEqual([]) + expect(store.get(0x8001n)).toBe(held) + expect(held.equals(key(1))).toBe(true) + }) + + it('zeroes and drops the key written longest ago for an addition past its bound, answering its key ID, a replaced key counting as written anew', () => { + const store = new ReceiveKeys() + const keys = Array.from({ length: RECEIVE_KEY_LIMIT }, (_, index) => key(index + 1)) + const rewritten = key(0xA0) + const added = key(0xA1) + + expect(RECEIVE_KEY_LIMIT).toBe(64) + + store.update(update(keys.map((each, index) => [ + BigInt(index + 1), + each, + ]))) + store.update(update([ + [1n, rewritten], + ])) + + expect(store.size).toBe(RECEIVE_KEY_LIMIT) + expect(store.update(update([ + [1000n, added], + ]))).toEqual([2n]) + expect(zeroed(keys[1])).toBe(true) + expect(store.get(2n)).toBeUndefined() + expect(store.get(1n)).toBe(rewritten) + expect(store.get(1000n)).toBe(added) + expect(store.size).toBe(RECEIVE_KEY_LIMIT) + expect(keys.slice(2).some(zeroed)).toBe(false) + }) +}) diff --git a/src/lib/camera/webrtc/voice/ReceiveKeys.ts b/src/lib/camera/webrtc/voice/ReceiveKeys.ts new file mode 100644 index 000000000..5f3c69a67 --- /dev/null +++ b/src/lib/camera/webrtc/voice/ReceiveKeys.ts @@ -0,0 +1,85 @@ +import type { Buffer } from 'node:buffer' + +import type { WebRTCReceiveKeysUpdate } from '../../WebRTCStreamManagement.js' + +/** + * The most keys a session's store holds, several times what a hub writes in one session. A store's memory stays bounded whatever a hub writes. + */ +export const RECEIVE_KEY_LIMIT = 64 + +/** + * The receive keys of one session: the SFrame keys a hub writes for what a viewer sends, each held by its key ID as the very buffer it was handed, and the + * store is the one holder of a key's bytes. A key leaves the store zeroed, whichever way it leaves: removed, replaced by a key written under its ID, + * dropped past the store's bound as the key written longest ago, or held at the store's disposal, which the session's teardown runs. + */ +export class ReceiveKeys implements Disposable { + // Each key by its ID, in the order written: the first is the one written longest ago. + private readonly keys = new Map() + + /** + * How many keys the store holds. + */ + get size(): number { + return this.keys.size + } + + /** + * The key held under a key ID. + * @param keyId - The key ID. + * @returns The key, or `undefined` for a key ID the store does not hold. + */ + get(keyId: bigint): Buffer | undefined { + return this.keys.get(keyId) + } + + /** + * Applies an update's removals and then its additions, each addition held as the buffer it carries and none copied. Each key a removal names, each key + * an addition replaces under its ID, and the key written longest ago once an addition takes the store past its bound, is zeroed and dropped. + * @param update - The keys to add and the key IDs to remove. + * @returns The key IDs whose keys the update zeroed, in the order zeroed. + */ + update(update: WebRTCReceiveKeysUpdate): bigint[] { + const zeroed: bigint[] = [] + + for (const { kid } of update.receiveKIDsToRemove) { + this.drop(kid, zeroed) + } + + for (const { key, kid } of update.receiveKeysToAdd) { + this.drop(kid, zeroed) + this.keys.set(kid, key) + + if (this.keys.size > RECEIVE_KEY_LIMIT) { + const [oldest] = this.keys.keys() + + this.drop(oldest, zeroed) + } + } + + return zeroed + } + + /** + * Zeroes and drops every key the store holds. + */ + [Symbol.dispose](): void { + for (const key of this.keys.values()) { + key.fill(0) + } + + this.keys.clear() + } + + // Zeroes and drops the key held under an ID, if any, and records its ID among those the update zeroed. + private drop(keyId: bigint, zeroed: bigint[]): void { + const key = this.keys.get(keyId) + + if (key === undefined) { + return + } + + key.fill(0) + this.keys.delete(keyId) + zeroed.push(keyId) + } +} diff --git a/src/lib/camera/webrtc/voice/ViewerVoice.spec.ts b/src/lib/camera/webrtc/voice/ViewerVoice.spec.ts new file mode 100644 index 000000000..70b690317 --- /dev/null +++ b/src/lib/camera/webrtc/voice/ViewerVoice.spec.ts @@ -0,0 +1,1527 @@ +import type { Buffer as NodeBuffer } from 'node:buffer' +import type { Mock } from 'vitest' + +import type { KeepingSink } from '../../../../test-utils/talkbackSink.js' +import type { TalkbackSink, Talker } from '../../StreamingOptions.js' +import type * as sframe from '../sframe.js' +import type { SFrameStreamKeys } from '../sframe.js' +import type { ViewerVoiceSetting, VoiceKind, VoicePlace } from './ViewerVoice.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { RtpHeader, RtpPacket } from 'werift' + +import { captureDebug, endDebugCapture } from '../../../../test-utils/engineDebug.js' +import { detachedReporter } from '../../../../test-utils/reporterFixtures.js' +import { keepingSink } from '../../../../test-utils/talkbackSink.js' +import { DisposableStack } from '../../../util/disposableStack.js' +import { SessionTalkback } from '../../session/SessionTalkback.js' +import { deriveStreamKeys } from '../sframe.js' +import { ReceiveKeys } from './ReceiveKeys.js' +import { BETTER_VOICE, DEPENDABLE_VOICE, ViewerVoice } from './ViewerVoice.js' + +/* The suite's setup file imports the definitions, whose graph imports the sealing module through the camera controller: it stands evaluated before this + * file's mock is in place. The module registry is reset first, which is why this file's imports evaluate the reader over the recorded derivation. + */ +vi.hoisted(() => vi.resetModules()) + +// The sealing module as it is, its derivation recorded, which lets a row read the SSRC each stream's keys were derived for and zeroing on their bytes. +vi.mock('../sframe.js', async (importOriginal) => { + const actual = await importOriginal() + + return { + ...actual, + deriveStreamKeys: vi.fn(actual.deriveStreamKeys), + } +}) + +// The sealing module unrecorded, which seals what the rows' viewers send. +const sealing = await vi.importActual('../sframe.js') + +const SESSION_IDENTIFIER = '5d2c1b0a-9f8e-4d7c-b6a5-948372615041' + +// The UUID of the sensor the rows' talkers talk on, made up. +const SENSOR_UUID = '8e7d6c5b-4a39-4f28-9b1a-0f9e8d7c6b5a' + +// The audio tier's payload type the rows' reader writes, and the key IDs a hub wrote for the rows' viewers with the seed of each key, each made up. +const AUDIO_PAYLOAD_TYPE = 110 +const KEY_ID = 0x4F3E2D1C8001n +const OTHER_KEY_ID = 0x4F3E2D1C8002n +const KEY_SEED = 0x2A +const OTHER_KEY_SEED = 0x3B + +function hubKey(seed = KEY_SEED): NodeBuffer { + return Buffer.alloc(16, seed) +} + +// The SSRCs the rows' viewers send on, made up, none named by any section, each with a low octet of its own, which names its packets. +const DEPENDABLE_SSRC = 0x1A2B3C4D +const BETTER_SSRC = 0x5E6F7081 +const SECOND_DEPENDABLE_SSRC = 0x2B3C4D5E +const SECOND_BETTER_SSRC = 0x6F708192 + +// The milliseconds of voice each packet of a stream holds, which is the step from one of its packets' timestamps to the next. +const PACKET_TIMES: Record = { + better: 40, + dependable: 20, +} + +// A viewer's clock in 48 kHz units, and the span of an RTP timestamp. +const TICKS_PER_MILLISECOND = 48 +const TIMESTAMP_RANGE = 2 ** 32 + +/* An Opus packet of the speech layer alone, its first frame's voice flag set or clear, then its stream's octet and its index as two octets, which name the + * packet in the rows: one frame of 20 milliseconds on the dependable stream, and two of 20 milliseconds on the better stream. A packet lasts its + * stream's step. + */ +function opus(kind: VoiceKind, voice: boolean, stream: number, index: number): NodeBuffer { + return Buffer.from([ + kind.place === 'better' + ? 0x49 + : 0x48, + voice + ? 0x80 + : 0x00, + stream, + index >> 8, + index & 0xFF, + ]) +} + +// One stream a row's viewer sends: its kind and SSRC, the key ID and key it seals under, the timestamp its viewer's clock reads at the row's time 0, and the +// time, counter and sequence number of its next packet. +interface Sender { + readonly kind: VoiceKind + readonly origin: number + readonly ssrc: number + at: number + counter: bigint + key: NodeBuffer + keyId: bigint + sequenceNumber: number +} + +// What a row sets of a stream: its key ID and key's seed, its viewer's clock at time 0 and its first sequence number. +interface SenderOptions { + readonly keyId?: bigint + readonly origin?: number + readonly seed?: number + readonly sequenceNumber?: number +} + +function sender(kind: VoiceKind, ssrc: number, options: SenderOptions = {}): Sender { + return { + at: 0, + counter: 0n, + key: hubKey(options.seed), + keyId: options.keyId ?? KEY_ID, + kind, + origin: options.origin ?? 48000, + sequenceNumber: options.sequenceNumber ?? 1000, + ssrc, + } +} + +// A packet's options the rows set by hand: its time, counter, sequence number and marker, a plaintext sealed in place of its Opus packet, and a ciphertext +// a row changes before it is sent. +interface SendOptions { + readonly at?: number + readonly counter?: bigint + readonly marker?: boolean + readonly plaintext?: NodeBuffer + readonly sequenceNumber?: number + readonly spoil?: (ciphertext: NodeBuffer) => void +} + +/* The stream's packet at a time, by default its next: the Opus packet sealed under the stream's key and its own SSRC behind the octet that marks a whole + * ciphertext, its timestamp the viewer's clock at that time and its index the time over the stream's step. The stream steps on by one counter, one + * sequence number and one step from it. + */ +function send(stream: Sender, voice: boolean, options: SendOptions = {}): RtpPacket { + const step = PACKET_TIMES[stream.kind.place] + const at = options.at ?? stream.at + const counter = options.counter ?? stream.counter + const sequenceNumber = options.sequenceNumber ?? stream.sequenceNumber + const keys = sealing.deriveStreamKeys({ + keyId: stream.keyId, + sessionKey: stream.key, + ssrc: stream.ssrc, + suite: sealing.SFRAME_AUDIO_SUITE, + }) + const ciphertext = sealing.sealSFrame(keys, counter, options.plaintext ?? opus(stream.kind, voice, stream.ssrc & 0xFF, at / step)) + + options.spoil?.(ciphertext) + stream.at = at + step + stream.counter = counter + 1n + stream.sequenceNumber = (sequenceNumber + 1) % 0x10000 + + return new RtpPacket(new RtpHeader({ + marker: options.marker ?? false, + payloadType: stream.kind.payloadType, + sequenceNumber, + ssrc: stream.ssrc, + timestamp: (stream.origin + at * TICKS_PER_MILLISECOND) % TIMESTAMP_RANGE, + }), Buffer.concat([ + Buffer.from([0xC0]), + ciphertext, + ])) +} + +// A session's reader over a store holding the rows' keys, each viewer's talkback over a stack of the row's own, and the sink each talkback starts, with +// the release it registers on its talker, by the key ID of its viewer. +interface Harness { + readonly reader: ViewerVoice + readonly sinks: Map + readonly stack: DisposableStack + readonly start: Mock<(keyId: bigint, talker: Talker) => TalkbackSink | undefined> + readonly store: ReceiveKeys + // The packets a viewer's sink was written, none for a viewer whose sink never started. + packets: (keyId?: bigint) => NodeBuffer[] +} + +// What a row asks of its harness: the viewers whose talkback the delegate declines, the keys the store holds with their seeds, and the voice setting. +interface HarnessOptions { + readonly declines?: readonly bigint[] + readonly keys?: readonly (readonly [keyId: bigint, seed: number])[] + readonly voice?: ViewerVoiceSetting +} + +// The keys a harness's store holds unless a row names its own: the rows' first viewer's alone. +const ONE_VIEWER: NonNullable = [ + [KEY_ID, KEY_SEED], +] + +function harness(options: HarnessOptions = {}): Harness { + const { declines = [], keys = ONE_VIEWER, voice = 'automatic' } = options + const store = new ReceiveKeys() + const stack = new DisposableStack() + const sinks = new Map() + const start = vi.fn((keyId: bigint, talker: Talker): TalkbackSink | undefined => { + if (declines.includes(keyId)) { + return undefined + } + + const kept = keepingSink() + + sinks.set(keyId, kept) + + return kept.start(talker) + }) + + store.update({ + receiveKeysToAdd: keys.map(([kid, seed]) => ({ + key: hubKey(seed), + kid, + })), + receiveKIDsToRemove: [], + }) + + return { + packets: (keyId = KEY_ID) => sinks.get(keyId)?.packets ?? [], + reader: stack.use(new ViewerVoice({ + keys: store, + payloadType: AUDIO_PAYLOAD_TYPE, + reporter: detachedReporter(), + sessionIdentifier: SESSION_IDENTIFIER, + speakerMuted: () => false, + talkback: keyId => new SessionTalkback({ + defer: release => stack.defer(release), + ended: () => false, + reporter: detachedReporter(), + sensorUUID: SENSOR_UUID, + session: `viewer ${keyId} of WebRTC session ${SESSION_IDENTIFIER}`, + sessionIdentifier: SESSION_IDENTIFIER, + start: talker => start(keyId, talker), + }), + voice, + werift: { RtpHeader, RtpPacket }, + })), + sinks, + stack, + start, + store, + } +} + +// A packet written, read at its octets' offsets in RFC 3550's fixed header, the octets that name the viewer's packet it carries, and that packet's duration +// in 48 kHz units, read from its frame count code. +interface Written { + readonly duration: number + readonly length: number + readonly marker: boolean + readonly name: string + readonly payloadType: number + readonly sequenceNumber: number + readonly ssrc: number + readonly timestamp: number + readonly version: number +} + +function written(packets: readonly NodeBuffer[]): Written[] { + return packets.map(packet => ({ + duration: (packet[12] & 0x03) === 0 + ? 960 + : 1920, + length: packet.length, + marker: (packet[1] & 0x80) !== 0, + name: `${packet[14].toString(16)}:${packet.readUInt16BE(15)}`, + payloadType: packet[1] & 0x7F, + sequenceNumber: packet.readUInt16BE(2), + ssrc: packet.readUInt32BE(8), + timestamp: packet.readUInt32BE(4), + version: packet[0], + })) +} + +function names(packets: readonly NodeBuffer[]): string[] { + return written(packets).map(({ name }) => name) +} + +// The name a written packet gives the viewer's packet it carries: the low octet of the stream's SSRC in hex, then its index in that stream. +function nameOf(stream: Sender, index: number): string { + return `${(stream.ssrc & 0xFF).toString(16)}:${index}` +} + +// The names of a stream's packets from one time to another, a step apart. +function namesOf(stream: Sender, from: number, to: number): string[] { + const step = PACKET_TIMES[stream.kind.place] + + return Array.from({ length: (to - from) / step + 1 }, (_, index) => nameOf(stream, from / step + index)) +} + +/* The milliseconds of the viewer's clock between each packet written and the end of the one written before it, each difference read modulo 2^32 as + * signed: none where the packets meet, a gap where a moment was not written, and less than none where a moment was written twice. + */ +function gapsOf(packets: readonly NodeBuffer[]): number[] { + const read = written(packets) + + return read.slice(1).map(({ timestamp }, index) => { + const end = read[index].timestamp + read[index].duration + + return (((timestamp - end + TIMESTAMP_RANGE + 2 ** 31) % TIMESTAMP_RANGE) - 2 ** 31) / TICKS_PER_MILLISECOND + }) +} + +// One packet a row's viewer sends: the time it arrives, which orders the packets handed to the reader, its time on the stream, its stream, and whether it +// says voice. +type Event = readonly [arrival: number, at: number, stream: Sender, voice: boolean] + +// A stream's packets every step from one time to another, each saying voice or not, arriving as its time ends and late or early by the lateness given. +function every(stream: Sender, from: number, to: number, voice: boolean, lateness = 0): Event[] { + const step = PACKET_TIMES[stream.kind.place] + const events: Event[] = [] + + for (let at = from; at <= to; at += step) { + events.push([ + at + step + lateness, + at, + stream, + voice, + ]) + } + + return events +} + +// The events of several streams merged in order of arrival, a stream listed first going first at a shared arrival. +function merged(...streams: Event[][]): Event[] { + return streams.flat().sort((left, right) => left[0] - right[0]) +} + +// Hands the reader each event's packet in order. +function play(reader: ViewerVoice, events: readonly Event[]): void { + for (const [, at, stream, voice] of events) { + reader.take(send(stream, voice, { at })) + } +} + +// The keys each derivation made, by the SSRC they were derived for. +function derivedFor(ssrc: number): SFrameStreamKeys[] { + const { calls, results } = vi.mocked(deriveStreamKeys).mock + + return results.filter((_, index) => calls[index][0].ssrc === ssrc).map(result => result.value as SFrameStreamKeys) +} + +function zeroed(keys: SFrameStreamKeys): boolean { + return [ + keys.secret, + keys.encryptionKey, + keys.authenticationKey, + keys.salt, + ].every(buffer => buffer.every(octet => octet === 0)) +} + +// The reader's closing line among the lines a row captured. +function closingLines(lines: readonly string[]): string[] { + return lines.filter(line => /voice packets? and wrote/.test(line)) +} + +// The closing line for the counts a row reads. +function closingLine(counts: { opened: number, stale?: number, unkeyed?: number, unopened?: number, viewers: number, written: number }): string { + const packets = counts.opened === 1 + ? 'voice packet' + : 'voice packets' + const [sinks, viewers] = counts.viewers === 1 + ? ['talkback sink', 'viewer'] + : ['talkback sinks', 'viewers'] + + return `WebRTC session ${SESSION_IDENTIFIER} opened ${counts.opened} ${packets} and wrote ${counts.written} of them to the ${sinks} of the ` + + `${counts.viewers} ${viewers} it followed, dropping ${counts.unkeyed ?? 0} whose key was not held, ${counts.stale ?? 0} whose counter did not pass its ` + + `stream's last and ${counts.unopened ?? 0} that did not open.` +} + +// Every line console.error is handed, each as one string. +function errorLines(): string[] { + const lines: string[] = [] + + vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { + lines.push(args.map(String).join(' ')) + }) + + return lines +} + +beforeEach(() => { + vi.mocked(deriveStreamKeys).mockClear() +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('viewerVoice', () => { + describe('opening', () => { + it('opens no packet of another payload type, one not behind the octet of a whole ciphertext, or one on an SSRC given to retransmission', () => { + const { packets, reader, stack } = harness() + const lines = captureDebug() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const retransmitted = sender(BETTER_VOICE, BETTER_SSRC) + const other = send(dependable, true) + const notWhole = send(dependable, true) + + other.header.payloadType = 111 + notWhole.payload[0] = 0x80 + reader.setRetransmissions(new Set([BETTER_SSRC])) + reader.take(other) + reader.take(notWhole) + reader.take(send(retransmitted, true)) + stack.dispose() + + expect(deriveStreamKeys).not.toHaveBeenCalled() + expect(packets()).toEqual([]) + expect(closingLines(lines)).toEqual([ + closingLine({ opened: 0, viewers: 0, written: 0 }), + ]) + }) + + it('drops a packet whose key is not held, holding nothing of it, and opens the next once its key is written', () => { + const { packets, reader, stack, store } = harness() + const lines = captureDebug() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC, { keyId: OTHER_KEY_ID, seed: OTHER_KEY_SEED }) + + reader.take(send(dependable, true)) + store.update({ + receiveKeysToAdd: [ + { + key: hubKey(OTHER_KEY_SEED), + kid: OTHER_KEY_ID, + }, + ], + receiveKIDsToRemove: [], + }) + reader.take(send(dependable, true)) + stack.dispose() + + expect(names(packets(OTHER_KEY_ID))).toEqual([ + nameOf(dependable, 1), + ]) + expect(closingLines(lines)).toEqual([ + closingLine({ + opened: 1, + unkeyed: 1, + viewers: 1, + written: 1, + }), + ]) + }) + + it('drops a packet whose counter does not pass the last its stream opened, before any cryptography', () => { + const { packets, reader, stack } = harness() + const lines = captureDebug() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + + reader.take(send(dependable, true, { counter: 5n })) + reader.take(send(dependable, true, { counter: 5n })) + reader.take(send(dependable, true, { counter: 3n })) + reader.take(send(dependable, true, { counter: 6n })) + stack.dispose() + + expect(names(packets())).toEqual([ + nameOf(dependable, 0), + nameOf(dependable, 3), + ]) + expect(deriveStreamKeys).toHaveBeenCalledOnce() + expect(closingLines(lines)).toEqual([ + closingLine({ + opened: 2, + stale: 2, + viewers: 1, + written: 2, + }), + ]) + }) + + it('drops a packet whose tag does not hold, making no viewer for it and zeroing the keys derived for it', () => { + const { packets, reader, stack } = harness({ + keys: [ + [KEY_ID, KEY_SEED], + [OTHER_KEY_ID, OTHER_KEY_SEED], + ], + }) + const lines = captureDebug() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const other = sender(DEPENDABLE_VOICE, SECOND_DEPENDABLE_SSRC, { keyId: OTHER_KEY_ID, seed: OTHER_KEY_SEED }) + const spoil = (ciphertext: NodeBuffer): void => { + ciphertext[ciphertext.length - 1] ^= 0x01 + } + + reader.take(send(dependable, true, { spoil })) + reader.take(send(dependable, true)) + reader.take(send(other, true, { spoil })) + stack.dispose() + + const [spoiled, kept] = derivedFor(DEPENDABLE_SSRC) + + expect(names(packets())).toEqual([ + nameOf(dependable, 1), + ]) + expect(derivedFor(DEPENDABLE_SSRC)).toHaveLength(2) + expect(zeroed(spoiled)).toBe(true) + expect(kept).not.toBe(spoiled) + expect(derivedFor(SECOND_DEPENDABLE_SSRC).map(zeroed)).toEqual([true]) + expect(closingLines(lines)).toEqual([ + closingLine({ + opened: 1, + unopened: 2, + viewers: 1, + written: 1, + }), + ]) + }) + }) + + describe('talk', () => { + it('starts nothing for a viewer\'s packets that say no voice, starts its sink at the first that says voice, asked for once, and writes every later packet ' + + 'of its stream', () => { + const { packets, reader, sinks, start } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + play(reader, merged(every(dependable, 0, 40, false), every(better, 0, 40, false))) + + expect(start).not.toHaveBeenCalled() + expect(packets()).toEqual([]) + + play(reader, merged(every(dependable, 60, 60, true), every(dependable, 80, 100, false))) + + expect(start).toHaveBeenCalledExactlyOnceWith(KEY_ID, expect.objectContaining({ sensorUUID: SENSOR_UUID })) + expect(sinks.get(KEY_ID)?.sink.write).toHaveBeenCalledTimes(3) + expect(names(packets())).toEqual(namesOf(dependable, 60, 100)) + }) + + it('starts a sink of its own for a viewer under a second key ID, each sink written its own viewer\'s packets alone while both talk at once', () => { + const { packets, reader, start } = harness({ + keys: [ + [KEY_ID, KEY_SEED], + [OTHER_KEY_ID, OTHER_KEY_SEED], + ], + }) + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + const second = sender(DEPENDABLE_VOICE, SECOND_DEPENDABLE_SSRC, { keyId: OTHER_KEY_ID, seed: OTHER_KEY_SEED }) + + play(reader, merged(every(dependable, 0, 200, true), every(second, 0, 200, true), every(better, 0, 200, true))) + + expect(start.mock.calls.map(([keyId]) => keyId)).toEqual([ + KEY_ID, + OTHER_KEY_ID, + ]) + expect(names(packets())).toEqual(namesOf(dependable, 0, 20).concat(namesOf(better, 40, 200))) + expect(names(packets(OTHER_KEY_ID))).toEqual(namesOf(second, 0, 200)) + }) + + it('declines a viewer whose talkback the delegate declines alone, opening and counting none of its later packets and zeroing its keys', () => { + const { packets, reader, stack, start } = harness({ + declines: [KEY_ID], + keys: [ + [KEY_ID, KEY_SEED], + [OTHER_KEY_ID, OTHER_KEY_SEED], + ], + }) + const lines = captureDebug() + const declined = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const second = sender(DEPENDABLE_VOICE, SECOND_DEPENDABLE_SSRC, { keyId: OTHER_KEY_ID, seed: OTHER_KEY_SEED }) + + for (const stream of [ + declined, + declined, + declined, + second, + second, + ]) { + reader.take(send(stream, true)) + } + + // The declined viewer's keys are zeroed at the decline, before the disposal zeroes every viewer's. + expect(derivedFor(DEPENDABLE_SSRC).map(zeroed)).toEqual([true]) + + stack.dispose() + + expect(start.mock.calls.map(([keyId]) => keyId)).toEqual([ + KEY_ID, + OTHER_KEY_ID, + ]) + expect(packets()).toEqual([]) + expect(names(packets(OTHER_KEY_ID))).toEqual(namesOf(second, 0, 20)) + expect(lines.filter(line => line.includes(`opened a voice packet of payload type 119 on SSRC ${DEPENDABLE_SSRC} `))).toHaveLength(1) + expect(closingLines(lines)).toEqual([ + closingLine({ opened: 3, viewers: 2, written: 2 }), + ]) + }) + + it('writes each header at its offsets: one SSRC, the payload type, the sequence rule, the timestamp stepping by media time across a change of stream ' + + 'and a fall back\'s unwritten span, a gap kept in both, and the marker', () => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC, { origin: 9600, sequenceNumber: 100 }) + const better = sender(BETTER_VOICE, BETTER_SSRC, { origin: 9600, sequenceNumber: 7000 }) + + // The dependable stream starts the sink, the better stream marks 40 milliseconds and plays from there to 120, and the dependable stream falls back at + // the packet whose end is the lag bound past it, then loses a packet and marks one of its own. + reader.take(send(dependable, true)) + reader.take(send(dependable, true)) + reader.take(send(better, true)) + reader.take(send(dependable, true)) + reader.take(send(better, true)) + reader.take(send(better, true)) + + for (let at = 60; at <= 260; at += 20) { + reader.take(send(dependable, true, { at })) + } + + reader.take(send(dependable, true, { at: 300, sequenceNumber: 115 })) + reader.take(send(dependable, true, { marker: true })) + + // Each packet written: the viewer's packet it carries, and the sequence number, timestamp and marker its header is written. + const expected = [ + { + index: 0, + marker: true, + sequenceNumber: 100, + stream: dependable, + timestamp: 9600, + }, + { + index: 1, + marker: false, + sequenceNumber: 101, + stream: dependable, + timestamp: 10560, + }, + { + index: 1, + marker: false, + sequenceNumber: 102, + stream: better, + timestamp: 11520, + }, + { + index: 2, + marker: false, + sequenceNumber: 103, + stream: better, + timestamp: 13440, + }, + { + index: 13, + marker: false, + sequenceNumber: 104, + stream: dependable, + timestamp: 22080, + }, + { + index: 15, + marker: false, + sequenceNumber: 106, + stream: dependable, + timestamp: 24000, + }, + { + index: 16, + marker: true, + sequenceNumber: 107, + stream: dependable, + timestamp: 24960, + }, + ] + + expect(packets().every(packet => packet.length === 12 + 5)).toBe(true) + expect(written(packets()).map(({ marker, name, payloadType, sequenceNumber, ssrc, timestamp, version }) => ({ + marker, + name, + payloadType, + sequenceNumber, + ssrc, + timestamp, + version, + }))).toEqual(expected.map(({ index, marker, sequenceNumber, stream, timestamp }) => ({ + marker, + name: nameOf(stream, index), + payloadType: AUDIO_PAYLOAD_TYPE, + sequenceNumber, + ssrc: DEPENDABLE_SSRC, + timestamp, + version: 0x80, + }))) + expect(packets().map(packet => [ + ...packet.subarray(12), + ])).toEqual(expected.map(({ index, stream }) => [ + ...opus(stream.kind, true, stream.ssrc & 0xFF, index), + ])) + }) + + it('writes a viewer whose timestamps and sequence numbers wrap in order, throwing nothing, its header wrapping too, with a mark and a fall back each ' + + 'falling across the wrap', () => { + const marking = harness() + const origin = TIMESTAMP_RANGE - 30 * TICKS_PER_MILLISECOND + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC, { origin, sequenceNumber: 0xFFFD }) + const better = sender(BETTER_VOICE, BETTER_SSRC, { origin, sequenceNumber: 0xFFFE }) + + // The better stream marks the moment 40 milliseconds in, past the wrap, and plays from there. + play(marking.reader, merged(every(dependable, 0, 200, true), every(better, 0, 200, true))) + + expect(written(marking.packets()).map(({ name, sequenceNumber, timestamp }) => ({ name, sequenceNumber, timestamp }))).toEqual([ + { + index: 0, + sequenceNumber: 0xFFFD, + stream: dependable, + timestamp: origin, + }, + { + index: 1, + sequenceNumber: 0xFFFE, + stream: dependable, + timestamp: TIMESTAMP_RANGE - 480, + }, + { + index: 1, + sequenceNumber: 0xFFFF, + stream: better, + timestamp: 480, + }, + { + index: 2, + sequenceNumber: 0, + stream: better, + timestamp: 2400, + }, + { + index: 3, + sequenceNumber: 1, + stream: better, + timestamp: 4320, + }, + { + index: 4, + sequenceNumber: 2, + stream: better, + timestamp: 6240, + }, + { + index: 5, + sequenceNumber: 3, + stream: better, + timestamp: 8160, + }, + ].map(({ index, sequenceNumber, stream, timestamp }) => ({ + name: nameOf(stream, index), + sequenceNumber, + timestamp, + }))) + + const falling = harness() + const lateOrigin = TIMESTAMP_RANGE - 500 * TICKS_PER_MILLISECOND + const lateDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC, { origin: lateOrigin }) + const lateBetter = sender(BETTER_VOICE, BETTER_SSRC, { origin: lateOrigin }) + + // The better stream plays from its first packet, ahead of the dependable packets it covers, and stops 100 milliseconds before the wrap. The + // dependable stream falls back after it. + play(falling.reader, merged(every(lateDependable, 0, 700, true), every(lateBetter, 0, 360, true, -30))) + + expect(written(falling.packets()).map(({ name, timestamp }) => [name, timestamp])).toEqual([ + ...namesOf(lateBetter, 0, 360).map((name, index) => [name, (lateOrigin + index * 40 * TICKS_PER_MILLISECOND) % TIMESTAMP_RANGE]), + ...namesOf(lateDependable, 540, 700).map((name, index) => [name, (lateOrigin + (540 + index * 20) * TICKS_PER_MILLISECOND) % TIMESTAMP_RANGE]), + ]) + expect(gapsOf(falling.packets())).toEqual([ + ...Array.from({ length: 9 }).fill(0), + 140, + ...Array.from({ length: 8 }).fill(0), + ]) + }) + }) + + describe('the stream that plays', () => { + it('plays the dependable stream of a viewer whose better stream sends nothing from its first packet that says voice, every packet written', () => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + + play(reader, merged(every(dependable, 0, 40, false), every(dependable, 60, 60, true), every(dependable, 80, 120, false), every(dependable, 140, 200, true))) + + expect(names(packets())).toEqual(namesOf(dependable, 60, 200)) + expect(gapsOf(packets()).every(gap => gap === 0)).toBe(true) + }) + + it.each([ + { arrives: 'before the dependable packets it covers', lateness: -30, takes: 120 }, + { arrives: 'just after the dependable packets it covers', lateness: 0, takes: 120 }, + { arrives: 'after one later dependable packet', lateness: 20, takes: 160 }, + { arrives: 'after two later dependable packets', lateness: 40, takes: 160 }, + ])('moves a start on the dependable stream to a better stream that keeps pace at its first packet at or past the mark, each moment written once, for a ' + + 'better packet that arrives $arrives', ({ lateness, takes }) => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + play(reader, merged(every(dependable, 0, 400, true), every(better, 80, 400, true, lateness))) + + expect(names(packets())).toEqual(namesOf(dependable, 0, takes - 20).concat(namesOf(better, takes, 400))) + expect(gapsOf(packets()).every(gap => gap === 0)).toBe(true) + }) + + it('writes no moment twice for a better stream stamped off the dependable stream\'s packets, a dependable packet that would run past the mark left ' + + 'unwritten', () => { + // The better stream's packets start 5, 10 or 15 milliseconds off the dependable stream's: its mark falls inside the dependable packet from 120, + // which runs past it by 15, 10 or 5, and the one span unwritten is the offset. + for (const offset of [5, 10, 15]) { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + play(reader, merged(every(dependable, 0, 400, true), every(better, 80 + offset, 400 + offset, true))) + + expect(written(packets()).at(-1)?.duration).toBe(1920) + expect(gapsOf(packets()).filter(gap => gap !== 0)).toEqual([offset]) + } + }) + + it('marks nothing for an unreadable better packet behind the dependable stream, the next readable packet marking as usual, each moment written ' + + 'once', () => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream's first packet, at 40 milliseconds, opens to a frame count code 3 with no count octet, which lasts no time, and arrives 80 + // behind the dependable stream's end. Its next packet arrives 20 behind and marks 160. + play(reader, every(dependable, 0, 100, true)) + reader.take(send(better, true, { + at: 40, + plaintext: Buffer.from([0x4B]), + })) + play(reader, merged(every(dependable, 120, 400, true), every(better, 80, 400, true, 20))) + + expect(names(packets())).toEqual(namesOf(dependable, 0, 140).concat(namesOf(better, 160, 400))) + expect(gapsOf(packets()).every(gap => gap === 0)).toBe(true) + }) + + it('marks nothing for a better packet exactly the keeping-pace bound behind the dependable stream, which plays on', () => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream's only packet ends at 40 milliseconds and arrives as the dependable stream's end reaches 160. + play(reader, merged(every(dependable, 0, 200, true), every(better, 0, 0, true, 120))) + + expect(names(packets())).toEqual(namesOf(dependable, 0, 200)) + }) + + it('holds nothing down at a stop for a better stream never read behind, which moves up at its first packet after the stop that keeps pace', () => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream's only packet arrives the keeping-pace bound behind, and both streams stop before the dependable stream reads it as behind, + // resuming at 3,000 milliseconds. The better stream marks 3,040 with no stay-down wait. + play(reader, merged(every(dependable, 0, 160, true), every(better, 0, 0, true, 120), every(dependable, 3000, 3200, true), + every(better, 3000, 3200, true))) + + expect(names(packets())).toEqual([ + ...namesOf(dependable, 0, 160), + ...namesOf(dependable, 3000, 3020), + ...namesOf(better, 3040, 3200), + ]) + }) + + it('falls back for no single lost better packet, and for a better stream gone at the dependable packet that reaches the lag bound and at none before, ' + + 'that packet written and none between', () => { + const lost = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream starts the sink, its packets arriving ahead of the dependable packets they cover, and loses its packet at 200 milliseconds. + play(lost.reader, merged(every(dependable, 0, 600, true), every(better, 0, 160, true, -30), every(better, 240, 600, true, -30))) + + expect(names(lost.packets())).toEqual(namesOf(better, 0, 600).filter(name => name !== nameOf(better, 5))) + + const gone = harness() + const goneDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const goneBetter = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream ends at 400 milliseconds, and the dependable packet ending at 560 is the first the lag bound reads it behind at. + play(gone.reader, merged(every(goneDependable, 0, 700, true), every(goneBetter, 0, 360, true, -30))) + + expect(names(gone.packets())).toEqual(namesOf(goneBetter, 0, 360).concat(namesOf(goneDependable, 540, 700))) + expect(gapsOf(gone.packets()).filter(gap => gap !== 0)).toEqual([140]) + }) + + it('lets a better stream that returns after a fall back take the talk back in the middle of talk once it keeps pace and has run the stay-down bound ' + + 'past the hold, which its return after a drop-out moves on, and at no packet before, each moment written once', () => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream takes the talk at 40 milliseconds and stops at 400, the dependable stream falls back at 540 and is read ahead of the better stream + // until the better stream returns at 800. The hold stands at 840 and the better stream marks 1,840. + play(reader, merged(every(dependable, 0, 2000, true), every(better, 0, 360, true), every(better, 800, 2000, true))) + + expect(names(packets())).toEqual([ + ...namesOf(dependable, 0, 20), + ...namesOf(better, 40, 360), + ...namesOf(dependable, 540, 1820), + ...namesOf(better, 1840, 2000), + ]) + expect(gapsOf(packets()).filter(gap => gap !== 0)).toEqual([140]) + }) + + it('makes no change of stream when both streams resume after a stop and the better packet comes within the lag bound, and plays the dependable stream ' + + 'when none does', () => { + const returning = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + play(returning.reader, merged(every(dependable, 0, 400, true), every(better, 0, 360, true), every(dependable, 3000, 3400, true), + every(better, 3000, 3360, true))) + + expect(names(returning.packets())).toEqual([ + ...namesOf(dependable, 0, 20), + ...namesOf(better, 40, 360), + ...namesOf(better, 3000, 3360), + ]) + + const alone = harness() + const aloneDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const aloneBetter = sender(BETTER_VOICE, BETTER_SSRC) + + play(alone.reader, merged(every(aloneDependable, 0, 400, true), every(aloneBetter, 0, 360, true), every(aloneDependable, 3000, 3400, true))) + + expect(names(alone.packets())).toEqual([ + ...namesOf(aloneDependable, 0, 20), + ...namesOf(aloneBetter, 40, 360), + ...namesOf(aloneDependable, 3140, 3400), + ]) + }) + + it('writes the same packets with the debug name off and every clock throwing, and changes nothing for a packet that says no voice in the middle of ' + + 'talk', () => { + const lines = captureDebug() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + // The packets of the row on a return after a fall back, from streams of their own for each run, some of each stream's in the middle of talk saying + // no voice when the run is quiet. + const events = (quiet: boolean): Event[] => { + const runDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const runBetter = sender(BETTER_VOICE, BETTER_SSRC) + + return merged(every(runDependable, 0, 580, true), every(runDependable, 600, 700, !quiet), every(runDependable, 720, 2000, true), + every(runBetter, 0, 360, true), every(runBetter, 800, 960, true), every(runBetter, 1000, 1200, !quiet), every(runBetter, 1240, 2000, true)) + } + const header = (packets: readonly NodeBuffer[]): unknown[] => written(packets).map(({ marker, name, sequenceNumber, ssrc, timestamp }) => ({ + marker, + name, + sequenceNumber, + ssrc, + timestamp, + })) + const plain = harness() + + play(plain.reader, events(false)) + + expect(lines.length).toBeGreaterThan(0) + expect(names(plain.packets())).toEqual([ + ...namesOf(dependable, 0, 20), + ...namesOf(better, 40, 360), + ...namesOf(dependable, 540, 1820), + ...namesOf(better, 1840, 2000), + ]) + + endDebugCapture(lines) + + for (const clock of [performance, Date]) { + vi.spyOn(clock, 'now').mockImplementation(() => { + throw new Error('The reader read a clock.') + }) + } + + const unclocked = harness() + + play(unclocked.reader, events(true)) + + expect(header(unclocked.packets())).toEqual(header(plain.packets())) + }) + + it('holds the better stream down after a fall back: one gone past the stay-down bound waits it from its return, one that comes and goes inside it ' + + 'never takes the talk back, and one lost packet counts nothing again', () => { + const away = harness() + const awayDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const awayBetter = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream is gone from 400 to 2,000 milliseconds: the hold stands at 2,040 as it returns and it marks 3,040. + play(away.reader, merged(every(awayDependable, 0, 3200, true), every(awayBetter, 0, 360, true), every(awayBetter, 2000, 3200, true))) + + expect(names(away.packets())).toEqual([ + ...namesOf(awayDependable, 0, 20), + ...namesOf(awayBetter, 40, 360), + ...namesOf(awayDependable, 540, 3020), + ...namesOf(awayBetter, 3040, 3200), + ]) + + // A better stream that stops and returns, each stretch shorter than the bound. + const cutting = harness() + const cuttingDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const cuttingBetter = sender(BETTER_VOICE, BETTER_SSRC) + + play(cutting.reader, merged(every(cuttingDependable, 0, 3200, true), every(cuttingBetter, 0, 360, true), every(cuttingBetter, 800, 1200, true), + every(cuttingBetter, 1600, 2000, true), every(cuttingBetter, 2400, 2800, true))) + + expect(names(cutting.packets())).toEqual([ + ...namesOf(cuttingDependable, 0, 20), + ...namesOf(cuttingBetter, 40, 360), + ...namesOf(cuttingDependable, 540, 3200), + ]) + + // A better stream that sends unbroken from its return at 800 milliseconds but falls behind in arrival and catches up in a clump, each time inside the + // bound, which is why each fall behind moves the hold on. + const clumped = harness() + const clumpedDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const clumpedBetter = sender(BETTER_VOICE, BETTER_SSRC) + const clumps = every(clumpedBetter, 800, 3200, true).map(([arrival, at, stream, voice]): Event => { + const clump = [1400, 2200].find(from => (at >= from) && (at < from + 200)) + const arrives = (clump === undefined) + ? arrival + : clump + 230 + + return [arrives, at, stream, voice] + }) + + play(clumped.reader, merged(every(clumpedDependable, 0, 3200, true), every(clumpedBetter, 0, 360, true), clumps)) + + expect(names(clumped.packets())).toEqual([ + ...namesOf(clumpedDependable, 0, 20), + ...namesOf(clumpedBetter, 40, 360), + ...namesOf(clumpedDependable, 540, 3200), + ]) + + // A better stream that returns at 800 milliseconds and loses its packet at 1,200, a gap short of the lag bound, which means the hold stays at 840 and it + // marks 1,840. + const lossy = harness() + const lossyDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const lossyBetter = sender(BETTER_VOICE, BETTER_SSRC) + + play(lossy.reader, merged(every(lossyDependable, 0, 2600, true), every(lossyBetter, 0, 360, true), every(lossyBetter, 800, 1160, true), + every(lossyBetter, 1240, 2600, true))) + + expect(names(lossy.packets())).toEqual([ + ...namesOf(lossyDependable, 0, 20), + ...namesOf(lossyBetter, 40, 360), + ...namesOf(lossyDependable, 540, 1820), + ...namesOf(lossyBetter, 1840, 2600), + ]) + }) + + it('holds the better stream down at a mark dropped as at a fall back, leaving the lag bound less a packet unwritten once and waiting the stay-down bound ' + + 'at its return', () => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream's one packet marks 40 milliseconds and it sends nothing more until 200, just after the dependable packet that drops the mark, its + // packets from then on arriving ahead of the dependable packets they cover. + play(reader, merged(every(dependable, 0, 1400, true), every(better, 0, 0, true), every(better, 200, 1400, true, -30))) + + expect(names(packets())).toEqual([ + ...namesOf(dependable, 0, 20), + ...namesOf(dependable, 180, 1180), + ...namesOf(better, 1200, 1400), + ]) + expect(gapsOf(packets()).filter(gap => gap !== 0)).toEqual([140]) + + // The sequence numbers written run on by one across the span the dropped mark leaves unwritten, each step taken from the last packet opened. + expect(written(packets()).map(({ sequenceNumber }) => sequenceNumber)).toEqual(Array.from({ length: packets().length }, (_, index) => 1000 + index)) + }) + + it('counts the stay-down bound again from the better stream\'s return after a stop while it is held down, a stop of the lag bound counting it and one a ' + + 'better packet shorter counting nothing, and keeps a standing mark across a stop when the better packet comes within the lag bound, dropping it when ' + + 'none does', () => { + const held = harness() + const heldDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const heldBetter = sender(BETTER_VOICE, BETTER_SSRC) + + // The better stream is held down from 840 milliseconds when both streams stop at 1,240 and resume at 3,000: it marks 4,000. + play(held.reader, merged(every(heldDependable, 0, 1200, true), every(heldBetter, 0, 360, true), every(heldBetter, 800, 1200, true), + every(heldDependable, 3000, 4200, true), every(heldBetter, 3000, 4200, true))) + + expect(names(held.packets())).toEqual([ + ...namesOf(heldDependable, 0, 20), + ...namesOf(heldBetter, 40, 360), + ...namesOf(heldDependable, 540, 1200), + ...namesOf(heldDependable, 3000, 3980), + ...namesOf(heldBetter, 4000, 4200), + ]) + + // Both streams stop at 1,200 milliseconds and resume at 1,360, a stop of the lag bound. The hold moves on to 1,360 and the better stream marks 2,360. + const edge = harness() + const edgeDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const edgeBetter = sender(BETTER_VOICE, BETTER_SSRC) + + play(edge.reader, merged(every(edgeDependable, 0, 1180, true), every(edgeBetter, 0, 360, true), every(edgeBetter, 800, 1160, true), + every(edgeDependable, 1360, 2600, true), every(edgeBetter, 1360, 2600, true))) + + expect(names(edge.packets())).toEqual([ + ...namesOf(edgeDependable, 0, 20), + ...namesOf(edgeBetter, 40, 360), + ...namesOf(edgeDependable, 540, 1180), + ...namesOf(edgeDependable, 1360, 2340), + ...namesOf(edgeBetter, 2360, 2600), + ]) + + // They resume at 1,320 instead, a stop one better packet short of the lag bound. The hold stays at 840 and the better stream marks 1,840. + const short = harness() + const shortDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const shortBetter = sender(BETTER_VOICE, BETTER_SSRC) + + play(short.reader, merged(every(shortDependable, 0, 1180, true), every(shortBetter, 0, 360, true), every(shortBetter, 800, 1160, true), + every(shortDependable, 1320, 2600, true), every(shortBetter, 1320, 2600, true))) + + expect(names(short.packets())).toEqual([ + ...namesOf(shortDependable, 0, 20), + ...namesOf(shortBetter, 40, 360), + ...namesOf(shortDependable, 540, 1180), + ...namesOf(shortDependable, 1320, 1820), + ...namesOf(shortBetter, 1840, 2600), + ]) + + // The better stream's one packet marks 40 milliseconds and both streams stop before the dependable stream reaches it, resuming at 3,000. + const kept = harness() + const keptDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const keptBetter = sender(BETTER_VOICE, BETTER_SSRC) + + play(kept.reader, merged(every(keptDependable, 0, 20, true), every(keptBetter, 0, 0, true), every(keptDependable, 3000, 3200, true), + every(keptBetter, 3000, 3200, true))) + + expect(names(kept.packets())).toEqual([ + ...namesOf(keptDependable, 0, 20), + ...namesOf(keptBetter, 3000, 3200), + ]) + + const dropped = harness() + const droppedDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const droppedBetter = sender(BETTER_VOICE, BETTER_SSRC) + + play(dropped.reader, merged(every(droppedDependable, 0, 20, true), every(droppedBetter, 0, 0, true), every(droppedDependable, 3000, 3300, true))) + + expect(names(dropped.packets())).toEqual([ + ...namesOf(droppedDependable, 0, 20), + ...namesOf(droppedDependable, 3140, 3300), + ]) + }) + + it('takes a packet on a new SSRC of a kind its viewer holds in that stream\'s place, zeroing the old stream\'s keys, the replaced stream playing on and ' + + 'the sequence number written stepping by one', () => { + const { packets, reader } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const better = sender(BETTER_VOICE, BETTER_SSRC, { sequenceNumber: 5000 }) + const replacing = sender(BETTER_VOICE, SECOND_BETTER_SSRC, { sequenceNumber: 9000 }) + + play(reader, merged(every(dependable, 0, 800, true), every(better, 0, 360, true), every(replacing, 400, 800, true))) + + expect(derivedFor(BETTER_SSRC).map(zeroed)).toEqual([true]) + expect(derivedFor(SECOND_BETTER_SSRC).map(zeroed)).toEqual([false]) + expect(names(packets())).toEqual([ + ...namesOf(dependable, 0, 20), + ...namesOf(better, 40, 360), + ...namesOf(replacing, 400, 800), + ]) + expect(written(packets()).map(({ sequenceNumber }) => sequenceNumber)).toEqual(Array.from({ length: 22 }, (_, index) => 1000 + index)) + }) + + it('reads a replaced stream\'s first packet against the end of the stream it replaces: a better stream that returns on a new SSRC after a stop while it ' + + 'is held down counts the stay-down bound again, and one that moves to a new SSRC where the old stream ended counts nothing', () => { + const returning = harness() + const returningDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const returningBetter = sender(BETTER_VOICE, BETTER_SSRC) + const returningReplacing = sender(BETTER_VOICE, SECOND_BETTER_SSRC, { sequenceNumber: 9000 }) + + // The better stream is held down from 840 milliseconds when both streams stop at 1,240 and resume at 3,000, the better stream on a new SSRC, whose + // first packet comes 1,760 after the old stream's end: it marks 4,000. + play(returning.reader, merged(every(returningDependable, 0, 1200, true), every(returningBetter, 0, 360, true), every(returningBetter, 800, 1200, true), + every(returningDependable, 3000, 4200, true), every(returningReplacing, 3000, 4200, true))) + + expect(names(returning.packets())).toEqual([ + ...namesOf(returningDependable, 0, 20), + ...namesOf(returningBetter, 40, 360), + ...namesOf(returningDependable, 540, 1200), + ...namesOf(returningDependable, 3000, 3980), + ...namesOf(returningReplacing, 4000, 4200), + ]) + + // The better stream is held down from 840 milliseconds and moves to a new SSRC at 1,200, its first packet there starting where the old stream ended, + // which means the hold stays at 840 and it marks 1,840. + const seamless = harness() + const seamlessDependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const seamlessBetter = sender(BETTER_VOICE, BETTER_SSRC) + const seamlessReplacing = sender(BETTER_VOICE, SECOND_BETTER_SSRC, { sequenceNumber: 9000 }) + + play(seamless.reader, merged(every(seamlessDependable, 0, 2600, true), every(seamlessBetter, 0, 360, true), every(seamlessBetter, 800, 1160, true), + every(seamlessReplacing, 1200, 2600, true))) + + expect(names(seamless.packets())).toEqual([ + ...namesOf(seamlessDependable, 0, 20), + ...namesOf(seamlessBetter, 40, 360), + ...namesOf(seamlessDependable, 540, 1820), + ...namesOf(seamlessReplacing, 1840, 2600), + ]) + }) + + it('never reads the better payload type under the dependable setting, and reads its move between dependable streams as a stream replaced', () => { + const { packets, reader } = harness({ voice: 'dependable' }) + const first = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const second = sender(DEPENDABLE_VOICE, SECOND_DEPENDABLE_SSRC, { sequenceNumber: 3000 }) + const better = sender(BETTER_VOICE, BETTER_SSRC) + + play(reader, merged(every(first, 0, 100, true), every(better, 0, 400, true), every(second, 300, 340, true))) + + expect(derivedFor(BETTER_SSRC)).toEqual([]) + expect(names(packets())).toEqual(namesOf(first, 0, 100).concat(namesOf(second, 300, 340))) + expect(written(packets()).map(({ sequenceNumber }) => sequenceNumber)).toEqual([ + 1000, + 1001, + 1002, + 1003, + 1004, + 1005, + 1006, + 1007, + 1008, + ]) + }) + }) + + describe('keys', () => { + it('ends the sink of a viewer whose key the store no longer holds once, logging its failed writes under its own words, zeroing its keys and dropping ' + + 'it, which means a later packet naming the key is dropped as not held', () => { + const lines = errorLines() + const debugLines = captureDebug() + const { reader, sinks, stack, store } = harness({ + keys: [ + [KEY_ID, KEY_SEED], + [OTHER_KEY_ID, OTHER_KEY_SEED], + ], + }) + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const second = sender(DEPENDABLE_VOICE, SECOND_DEPENDABLE_SSRC, { keyId: OTHER_KEY_ID, seed: OTHER_KEY_SEED }) + + reader.take(send(dependable, true)) + reader.take(send(second, true)) + + const leaving = sinks.get(KEY_ID) + const staying = sinks.get(OTHER_KEY_ID) + + leaving?.sink.write.mockImplementation(() => { + throw new Error('The sink failed to write.') + }) + reader.take(send(dependable, true)) + reader.take(send(dependable, true)) + reader.forget(store.update({ + receiveKeysToAdd: [], + receiveKIDsToRemove: [ + { kid: KEY_ID }, + ], + })) + + expect(leaving?.release).toHaveBeenCalledOnce() + expect(staying?.release).not.toHaveBeenCalled() + expect(derivedFor(DEPENDABLE_SSRC).map(zeroed)).toEqual([true]) + expect(lines).toEqual([ + expect.stringContaining('TalkbackSink failed to write a packet: Error: The sink failed to write.'), + `TalkbackSink failed 1 more write before viewer ${KEY_ID} of WebRTC session ${SESSION_IDENTIFIER} ended.`, + ]) + + reader.take(send(dependable, true)) + reader.take(send(second, true)) + stack.dispose() + + expect(leaving?.release).toHaveBeenCalledOnce() + expect(staying?.release).toHaveBeenCalledOnce() + expect(leaving?.sink.write).toHaveBeenCalledTimes(3) + expect(names(staying?.packets ?? [])).toEqual(namesOf(second, 0, 20)) + expect(closingLines(debugLines)).toEqual([ + closingLine({ + opened: 5, + unkeyed: 1, + viewers: 2, + written: 5, + }), + ]) + }) + + it('starts a new talker for a key written again in a later update than the one that removed it, the first talker\'s registrations released once, inside ' + + 'the removal', () => { + const { reader, sinks, stack, start, store } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + + reader.take(send(dependable, true)) + + const first = sinks.get(KEY_ID) + + reader.forget(store.update({ + receiveKeysToAdd: [], + receiveKIDsToRemove: [ + { kid: KEY_ID }, + ], + })) + + expect(first?.release).toHaveBeenCalledOnce() + + reader.forget(store.update({ + receiveKeysToAdd: [ + { + key: hubKey(), + kid: KEY_ID, + }, + ], + receiveKIDsToRemove: [], + })) + reader.take(send(dependable, true)) + + const second = sinks.get(KEY_ID) + const [[, firstTalker], [, secondTalker]] = start.mock.calls + + expect(start.mock.calls.map(([keyId]) => keyId)).toEqual([KEY_ID, KEY_ID]) + expect(secondTalker).not.toBe(firstTalker) + expect(second).not.toBe(first) + expect([first?.packets.length, second?.packets.length]).toEqual([1, 1]) + expect([first?.release.mock.calls.length, second?.release.mock.calls.length]).toEqual([1, 0]) + + stack.dispose() + + expect([first?.release.mock.calls.length, second?.release.mock.calls.length]).toEqual([1, 1]) + }) + + it('keeps a viewer whose key is replaced under its ID with its sink, zeroing what it derived and opening its next packet from a first count', () => { + const { packets, reader, sinks, start, store } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + + reader.take(send(dependable, true)) + reader.take(send(dependable, true)) + reader.forget(store.update({ + receiveKeysToAdd: [ + { + key: hubKey(0x5C), + kid: KEY_ID, + }, + ], + receiveKIDsToRemove: [], + })) + dependable.key = hubKey(0x5C) + reader.take(send(dependable, true, { counter: 0n })) + + const [replaced, written] = derivedFor(DEPENDABLE_SSRC) + + expect(zeroed(replaced)).toBe(true) + expect(zeroed(written)).toBe(false) + expect(start).toHaveBeenCalledOnce() + expect(sinks.get(KEY_ID)?.release).not.toHaveBeenCalled() + expect(names(packets())).toEqual(namesOf(dependable, 0, 40)) + }) + + it('follows five viewers talking at once, each written to a sink of its own and none ending another\'s', () => { + const viewers = [1n, 2n, 3n, 4n, 5n].map(offset => ({ keyId: KEY_ID + offset, seed: 0x40 + Number(offset) })) + const { packets, reader, sinks, stack, start } = harness({ + keys: viewers.map(({ keyId, seed }) => [keyId, seed] as const), + }) + const lines = captureDebug() + const streams = viewers.map(({ keyId, seed }, index) => sender(DEPENDABLE_VOICE, 0x10000001 + index, { keyId, seed })) + + play(reader, merged(...streams.map(stream => every(stream, 0, 100, true)))) + + expect(start.mock.calls.map(([keyId]) => keyId)).toEqual(viewers.map(({ keyId }) => keyId)) + expect(viewers.map(({ keyId }) => names(packets(keyId)))).toEqual(streams.map(stream => namesOf(stream, 0, 100))) + expect(viewers.map(({ keyId }) => sinks.get(keyId)?.release.mock.calls.length)).toEqual([0, 0, 0, 0, 0]) + + stack.dispose() + + expect(viewers.map(({ keyId }) => sinks.get(keyId)?.release.mock.calls.length)).toEqual([1, 1, 1, 1, 1]) + expect(closingLines(lines)).toEqual([ + closingLine({ opened: 30, viewers: 5, written: 30 }), + ]) + }) + + it('ends no sink at its disposal, zeroing every derived key and writing its closing line once, its written count leaving out a declined write', () => { + const { reader, sinks } = harness({ + declines: [OTHER_KEY_ID], + keys: [ + [KEY_ID, KEY_SEED], + [OTHER_KEY_ID, OTHER_KEY_SEED], + ], + }) + const lines = captureDebug() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + + reader.take(send(dependable, true)) + reader.take(send(dependable, true)) + reader.take(send(sender(BETTER_VOICE, BETTER_SSRC), false)) + reader.take(send(sender(DEPENDABLE_VOICE, SECOND_DEPENDABLE_SSRC, { keyId: OTHER_KEY_ID, seed: OTHER_KEY_SEED }), true)) + reader[Symbol.dispose]() + + expect(sinks.get(KEY_ID)?.release).not.toHaveBeenCalled() + expect(vi.mocked(deriveStreamKeys).mock.results.map(result => zeroed(result.value as SFrameStreamKeys))).toEqual([true, true, true]) + expect(closingLines(lines)).toEqual([ + closingLine({ opened: 4, viewers: 2, written: 2 }), + ]) + }) + + it('writes the failed-writes line of each viewer it still holds at its disposal, for the writes that failed after the first it logged', () => { + const lines = errorLines() + const { reader, sinks } = harness() + const dependable = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC) + const firstFailure = expect.stringContaining('TalkbackSink failed to write a packet: Error: The sink failed to write.') + + reader.take(send(dependable, true)) + sinks.get(KEY_ID)?.sink.write.mockImplementation(() => { + throw new Error('The sink failed to write.') + }) + reader.take(send(dependable, true)) + reader.take(send(dependable, true)) + + expect(lines).toEqual([firstFailure]) + + reader[Symbol.dispose]() + + expect(lines).toEqual([ + firstFailure, + `TalkbackSink failed 1 more write before viewer ${KEY_ID} of WebRTC session ${SESSION_IDENTIFIER} ended.`, + ]) + }) + }) + + describe('debug', () => { + it('states each opened packet\'s fields, a sink\'s start, each change of stream with its reason, a mark dropped, a viewer leaving and the closing line, ' + + 'with no key\'s bytes, and makes none of them with the debug name off', () => { + const lines = captureDebug() + const opened = harness() + const fields = sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC, { origin: 654321, sequenceNumber: 321 }) + + opened.reader.take(send(fields, true, { marker: true })) + opened.reader.take(send(fields, false)) + + expect(lines).toEqual([ + `WebRTC session ${SESSION_IDENTIFIER} opened a voice packet of payload type 119 on SSRC ${DEPENDABLE_SSRC} under key ID ${KEY_ID}, sequence 321, ` + + 'timestamp 654321, marker true: 5 octets opening 4880, frames opening 80, saying voice.', + `WebRTC session ${SESSION_IDENTIFIER} starts the talkback sink of viewer ${KEY_ID} on its dependable stream, SSRC ${DEPENDABLE_SSRC}.`, + `WebRTC session ${SESSION_IDENTIFIER} opened a voice packet of payload type 119 on SSRC ${DEPENDABLE_SSRC} under key ID ${KEY_ID}, sequence 322, ` + + 'timestamp 655281, marker false: 5 octets opening 4800, frames opening 00, saying no voice.', + ]) + + // One viewer starts on its dependable stream, moves to its better stream and falls back, and a second starts, has its mark dropped and leaves. + const scenario = (reader: ViewerVoice): Event[] => { + const events = merged(every(sender(DEPENDABLE_VOICE, DEPENDABLE_SSRC), 0, 600, true), every(sender(BETTER_VOICE, BETTER_SSRC), 0, 200, true), + every(sender(DEPENDABLE_VOICE, SECOND_DEPENDABLE_SSRC, { keyId: OTHER_KEY_ID, seed: OTHER_KEY_SEED }), 0, 400, true), + every(sender(BETTER_VOICE, SECOND_BETTER_SSRC, { keyId: OTHER_KEY_ID, seed: OTHER_KEY_SEED }), 0, 0, true)) + + play(reader, events) + + return events + } + const both = harness({ + keys: [ + [KEY_ID, KEY_SEED], + [OTHER_KEY_ID, OTHER_KEY_SEED], + ], + }) + + lines.length = 0 + + const events = scenario(both.reader) + // Every key's bytes as a line would state them in hex: the keys the hub wrote and those the reader derived, read before any is zeroed. + const secrets = [ + hubKey(KEY_SEED), + hubKey(OTHER_KEY_SEED), + ...vi.mocked(deriveStreamKeys).mock.results.flatMap(({ value }) => { + const { authenticationKey, encryptionKey, salt, secret } = value as SFrameStreamKeys + + return [ + authenticationKey, + encryptionKey, + salt, + secret, + ] + }), + ].map(key => key.toString('hex')) + + both.reader.forget(both.store.update({ + receiveKeysToAdd: [], + receiveKIDsToRemove: [ + { kid: OTHER_KEY_ID }, + ], + })) + both.stack.dispose() + + expect(lines.filter(line => !line.includes('opened a voice packet'))).toEqual([ + `WebRTC session ${SESSION_IDENTIFIER} starts the talkback sink of viewer ${KEY_ID} on its dependable stream, SSRC ${DEPENDABLE_SSRC}.`, + `WebRTC session ${SESSION_IDENTIFIER} starts the talkback sink of viewer ${OTHER_KEY_ID} on its dependable stream, SSRC ${SECOND_DEPENDABLE_SSRC}.`, + `WebRTC session ${SESSION_IDENTIFIER} moves viewer ${KEY_ID} to its better stream, SSRC ${BETTER_SSRC}, the better stream keeping pace.`, + `WebRTC session ${SESSION_IDENTIFIER} drops the mark of viewer ${OTHER_KEY_ID}, its better stream having fallen behind.`, + `WebRTC session ${SESSION_IDENTIFIER} moves viewer ${KEY_ID} to its dependable stream, SSRC ${DEPENDABLE_SSRC}, the better stream having fallen ` + + 'behind.', + `WebRTC session ${SESSION_IDENTIFIER} drops viewer ${OTHER_KEY_ID}, whose key the session no longer holds, and ends its talkback.`, + closingLine({ opened: events.length, viewers: 2, written: both.packets().length + both.packets(OTHER_KEY_ID).length }), + ]) + expect(both.packets(OTHER_KEY_ID)).not.toHaveLength(0) + expect(lines.filter(line => secrets.some(secret => line.includes(secret)))).toEqual([]) + + endDebugCapture(lines) + + const quiet = harness({ + keys: [ + [KEY_ID, KEY_SEED], + [OTHER_KEY_ID, OTHER_KEY_SEED], + ], + }) + const before = lines.length + const hex = vi.spyOn(Buffer.prototype, 'toString') + const bigint = vi.spyOn(BigInt.prototype, 'toString') + + scenario(quiet.reader) + quiet.reader.forget(quiet.store.update({ + receiveKeysToAdd: [], + receiveKIDsToRemove: [ + { kid: OTHER_KEY_ID }, + ], + })) + quiet.stack.dispose() + + expect(hex.mock.calls.filter(([encoding]) => encoding === 'hex')).toEqual([]) + expect(bigint).not.toHaveBeenCalled() + expect(lines).toHaveLength(before) + }) + }) +}) diff --git a/src/lib/camera/webrtc/voice/ViewerVoice.ts b/src/lib/camera/webrtc/voice/ViewerVoice.ts new file mode 100644 index 000000000..d62a76f87 --- /dev/null +++ b/src/lib/camera/webrtc/voice/ViewerVoice.ts @@ -0,0 +1,779 @@ +import type { Buffer } from 'node:buffer' +import type { RtpHeader, RtpPacket } from 'werift' + +import type { CameraReporter } from '../../diagnostics/CameraReporter.js' +import type { SessionTalkback } from '../../session/SessionTalkback.js' +import type { WebRTCStreamingOptions } from '../../WebRTCStreamManagement.js' +import type { SFrameHeader, SFrameStreamKeys } from '../sframe.js' +import type { Werift } from '../werift.js' +import type { ReceiveKeys } from './ReceiveKeys.js' + +import { counted, nounFor } from '../../../util/counted.js' +import { marksPacket, nextSequence, SEQUENCE_RANGE, wireTimestamp } from '../../rtp/packetRules.js' +import { ENGINE_DEBUG } from '../EngineSession.js' +import { deriveStreamKeys, FIRST_PAYLOAD, LAST_PAYLOAD, openSFrame, readSFrameHeader, SFRAME_AUDIO_SUITE, zeroStreamKeys } from '../sframe.js' +import { OPUS_TICKS_PER_MILLISECOND, readOpusVoice } from './opusVoice.js' + +/** + * Which of a viewer's voice streams a session plays, as the WebRTC streaming's `voice` names its values: `'automatic'` the better stream whenever it + * keeps pace with the dependable one, and `'dependable'` the dependable stream alone. + */ +export type ViewerVoiceSetting = NonNullable + +/** + * A voice stream's place among a viewer's: the dependable stream, which carries the talk in every session that has any, or the better stream, which + * carries a wider band when it carries the talk at all. + */ +export type VoicePlace = 'better' | 'dependable' + +/** + * What one kind of a viewer's voice stream is: the payload type it arrives on, which no SDP section names, and its place. + */ +export interface VoiceKind { + readonly payloadType: number + readonly place: VoicePlace +} + +/** + * A viewer's dependable voice stream: Opus coded at 16 kHz in packets of 20 milliseconds, on payload type 119. + */ +export const DEPENDABLE_VOICE: VoiceKind = { payloadType: 119, place: 'dependable' } + +/** + * A viewer's better voice stream: Opus coded at 24 kHz in packets of 40 milliseconds, on payload type 97. + */ +export const BETTER_VOICE: VoiceKind = { payloadType: 97, place: 'better' } + +/** + * How far the dependable stream runs past the better stream before the better stream is read as behind, in milliseconds of the viewer's clock: a + * dependable packet whose end is this or more past the latest of the better stream's end, a standing mark and the dependable stream's last resume reads it + * so. A single lost better packet falls short of it, and a better stream that stopped with its viewer is given this long to come back at a resume. + */ +export const LAG_BOUND = 160 + +/** + * How far a better packet's end may be behind the dependable stream's end and still keep pace, in milliseconds of the viewer's clock. + */ +export const KEEPING_PACE_BOUND = 120 + +/** + * How long the better stream keeps pace before it takes the talk back once it has been read as behind, in milliseconds of the viewer's clock. A better + * stream that keeps cutting out leaves its lag unwritten once and then stays off the sink. Until the better stream marks where it takes the talk, a + * drop-out of LAG_BOUND or more and a stop in sending each count it again, and a single lost packet does not. A mark that stands is kept across either. + */ +export const STAY_DOWN_BOUND = 1000 + +// The octet in front of a payload that holds one SFrame ciphertext whole, which every voice packet carries. +const WHOLE_CIPHERTEXT = FIRST_PAYLOAD | LAST_PAYLOAD + +// The span of an RTP timestamp, a 32-bit field, and half of it, the most two timestamps are read apart either way. +const TIMESTAMP_RANGE = 2 ** 32 +const HALF_TIMESTAMP_RANGE = 2 ** 31 + +// The bounds in the 48 kHz units of a viewer's clock, which its timestamps count. +const LAG_TICKS = LAG_BOUND * OPUS_TICKS_PER_MILLISECOND +const KEEPING_PACE_TICKS = KEEPING_PACE_BOUND * OPUS_TICKS_PER_MILLISECOND +const STAY_DOWN_TICKS = STAY_DOWN_BOUND * OPUS_TICKS_PER_MILLISECOND + +// How far one timestamp of a viewer's clock is past another: their difference modulo 2^32 read as signed, within half the range either way. A wrap +// changes nothing and a timestamp that is ahead reads as ahead. +function ticksPast(timestamp: number, from: number): number { + return ((timestamp - from + TIMESTAMP_RANGE + HALF_TIMESTAMP_RANGE) % TIMESTAMP_RANGE) - HALF_TIMESTAMP_RANGE +} + +// The later of two timestamps of a viewer's clock. +function later(timestamp: number, other: number): number { + return (ticksPast(timestamp, other) >= 0) + ? timestamp + : other +} + +/** + * The voice setting a session plays, checked once for the engine's constructor. A bad setting in the camera's block is refused at the controller's + * construction, which builds the engine. + * @param voice - The setting, or `undefined` for the default. + * @returns The setting, `'automatic'` by default. + * @throws TypeError for a setting that is neither value. + */ +export function viewerVoiceSetting(voice: ViewerVoiceSetting = 'automatic'): ViewerVoiceSetting { + if ((voice !== 'automatic') && (voice !== 'dependable')) { + throw new TypeError(`The WebRTC streaming takes a voice of 'automatic' or 'dependable', but ${String(voice)} is neither.`) + } + + return voice +} + +/** + * What a session's voice reader is made from: the session's store of receive keys, the audio tier's payload type, the session's identifier, the way a + * viewer's talkback is made, the session's voice setting, and the werift exports the packets it writes are built from. + */ +export interface ViewerVoiceOptions { + /** + * The session's store of the receive keys a hub writes. + */ + readonly keys: ReceiveKeys + /** + * The audio tier's payload type, which every packet written carries. + */ + readonly payloadType: number + /** + * The reporter the session was made under, which the reader's debug events go through. + */ + readonly reporter: CameraReporter + /** + * The session's identifier, which the debug events name. + */ + readonly sessionIdentifier: string + /** + * Whether the camera's Speaker is muted, read as it stands at each packet that names a viewer. A muted Speaker has every viewer's packet dropped before + * it is opened or counted, and a viewer's sink already started stays started, written nothing until the Speaker is unmuted. + */ + readonly speakerMuted: () => boolean + /** + * Makes a new talkback for a viewer, from the key ID its packets are sealed under, which every packet written for that viewer goes through. + */ + readonly talkback: (keyId: bigint) => SessionTalkback + /** + * Which of a viewer's voice streams the session plays. + */ + readonly voice: ViewerVoiceSetting + /** + * The werift exports the packets written are built from. + */ + readonly werift: Pick +} + +// What the reader has done with what its viewers sent: the voice packets opened and those a sink was handed, the viewers followed, and the packets dropped +// by their reason, a key not held, a counter that did not pass its stream's last and a ciphertext that did not open. +interface VoiceCounts { + opened: number + stale: number + unkeyed: number + unopened: number + viewers: number + written: number +} + +/** + * The keys one stream opens under, with the last counter opened under them. + */ +export interface OpenedKeys { + counter: bigint + readonly keys: SFrameStreamKeys +} + +/** + * One voice stream a viewer sends, tracked by its SSRC from its first packet that opens: its kind, the keys it opens under with the last counter opened + * under them, where it stands on its viewer's clock, and the sequence number of its last opened packet, which the step of its next is taken from. + */ +export class VoiceStream { + /** + * The stream's kind, which its first packet's payload type names. + */ + readonly kind: VoiceKind + /** + * The stream's SSRC, which keys it. + */ + readonly ssrc: number + /** + * The keys the stream opens under, derived under its viewer's key and its own SSRC, with the last counter opened under them, or `undefined` once that key + * is zeroed, which means its next packet opens from a first count. + */ + opened?: OpenedKeys + /** + * Where the stream's last opened packet ends on its viewer's clock: that packet's timestamp plus its duration, modulo 2^32. Until its first packet is + * clocked it is where the stream starts from. + */ + end: number + /** + * How far the stream's last opened packet started past the end of the one before it, in 48 kHz units: none for a packet that starts where the last ended, + * the span not sent, or lost, for one that starts later, and less than none for one that starts before it. A stream's first packet is read against where + * the stream starts from, and it has none unless its stream takes another's place. + */ + gap = 0 + /** + * The timestamp at which the stream last resumed: its first packet's, or that of its last packet whose timestamp was not its packet before's end. + */ + resumedAt: number + /** + * The sequence number of the stream's last opened packet. + */ + sequenceNumber: number + + /** + * Tracks a stream from its first packet that opens, which is where it resumed. + * @param kind - The stream's kind. + * @param header - The packet's header. + * @param opened - The keys the packet opened under, with its counter. + * @param end - Where the stream starts from on its viewer's clock, which its first packet's gap is read against: the end of the stream it takes the place + * of, and by default the packet's own timestamp. + */ + constructor(kind: VoiceKind, header: RtpHeader, opened: OpenedKeys, end = header.timestamp) { + this.kind = kind + this.ssrc = header.ssrc + this.opened = opened + this.end = end + this.resumedAt = header.timestamp + this.sequenceNumber = header.sequenceNumber + } + + /** + * Moves the stream on to an opened packet on its viewer's clock: a packet whose timestamp is not the stream's end, after a stop in sending or a loss, is + * where the stream resumed, its distance past that end is the stream's gap, and the packet's end is the stream's. + * @param header - The packet's header. + * @param duration - The packet's duration in 48 kHz units. + */ + clock(header: RtpHeader, duration: number): void { + this.gap = ticksPast(header.timestamp, this.end) + + if (this.gap !== 0) { + this.resumedAt = header.timestamp + } + + this.end = wireTimestamp(header.timestamp + duration) + } + + /** + * Zeroes and drops the keys the stream opens under. + */ + zero(): void { + if (this.opened) { + zeroStreamKeys(this.opened.keys) + this.opened = undefined + } + } +} + +// The header a viewer's sink is written: the SSRC of the viewer's first played packet for the sink's whole life, and the sequence number and the stream of +// the last packet written. The timestamp is each packet's own. +interface WrittenHeader { + sequenceNumber: number + readonly ssrc: number + stream: VoiceStream +} + +/** + * One viewer of a session, the key ID its packets are sealed under, beside the session's reader: its streams by their place, its talkback, the place of + * the stream that plays once its sink starts, the mark the better stream takes the talk from, the hold the better stream is held down from, and the + * header its sink has been written. + */ +export class Viewer { + /** + * The key ID the viewer's packets are sealed under, which keys it. + */ + readonly keyId: bigint + /** + * The viewer's streams by their place, each tracked from its first packet that opens. + */ + readonly streams: { better?: VoiceStream, dependable?: VoiceStream } = {} + /** + * The viewer's talkback, which every packet written for the viewer goes through. + */ + readonly talkback: SessionTalkback + /** + * The place of the stream that plays, from the packet that starts the viewer's sink. + */ + playing?: VoicePlace + /** + * The timestamp the better stream takes the talk from, while the dependable stream plays and waits for it. + */ + mark?: number + /** + * The timestamp the better stream is held down from, once a dependable packet has read it as behind and until it takes the talk back. + */ + hold?: number + /** + * The header the viewer's sink has been written, from its first packet. + */ + written?: WrittenHeader + + /** + * Follows a viewer from its first packet that opens. + * @param keyId - The key ID the viewer's packets are sealed under. + * @param talkback - The viewer's talkback. + */ + constructor(keyId: bigint, talkback: SessionTalkback) { + this.keyId = keyId + this.talkback = talkback + } + + /** + * Zeroes and drops the keys each of the viewer's streams opens under. + */ + zero(): void { + this.streams.better?.zero() + this.streams.dependable?.zero() + } +} + +/** + * A session's reader of its viewers' voices, handed every RTP packet a transport of the session receives. A voice packet is one on a voice stream's + * payload type, the better stream's read under `'automatic'` alone, whose payload holds one SFrame ciphertext whole and whose SSRC the applied remote + * description gives to no retransmission. It opens under keys derived from the receive key its header names and its own SSRC, once for a stream, and a + * packet whose key the store does not hold, whose counter does not pass its stream's last or which does not open is dropped and counted, and nothing is + * held for a key that comes later. + * + * A viewer is the key ID its packets are sealed under, followed, with a talkback of its own, from its first packet that opens. Viewers share no sink + * and a plugin decides who is heard. The reader follows every viewer whose key the session's store holds, the store's bound being the bound on viewers. + * A viewer's sink starts at its first opened packet that says voice, whose stream then plays, and every opened packet of the stream that plays is + * written, whatever it says. No pause is read, no arrival time and no voice flag after the one that starts a sink: every rule reads the viewer's own + * clock, the timestamps both its streams count in 48 kHz units from one origin, where a stream's end is its last packet's timestamp plus that packet's + * duration and a packet that does not start at its stream's end is where that stream resumed. A stream on a new SSRC that takes another's place starts + * from that stream's end. + * + * With the dependable stream playing, a better packet whose end is less than KEEPING_PACE_BOUND behind the dependable stream's end marks where the better + * stream takes the talk: that packet's end, stepped on by whole packets of its length to the dependable stream's end or past it, which is why every change falls on + * a packet's boundary and nothing is written twice. Dependable packets that end at or before the mark are written, and the better stream's first packet at + * or past it plays. A dependable packet whose end is LAG_BOUND or more past the latest of the better stream's end, a standing mark and the dependable stream's last + * resume reads the better stream as behind: the dependable stream plays from that packet, a standing mark is dropped, and the better stream is held down + * from that packet's end. Held down, the better stream marks only once its end is STAY_DOWN_BOUND past the hold, which a better packet that comes + * LAG_BOUND or more after its stream's end moves on to itself: until it marks, a drop-out and a stop in sending count the bound again and a single lost + * packet does not. A mark that stands is kept across a drop-out and a stop, and only a dependable packet that reads the better stream as behind drops it. + * No timer runs and no packet is held. + * + * Each packet written is werift's packet, its header written by the reader and its payload the opened Opus packet untouched: the audio tier's payload type, + * the SSRC of the viewer's first played packet, a sequence number that starts at that packet's own and runs on by the playing stream's own steps and by + * one at each change of stream, and a timestamp on the viewer's own clock, which is why a moment not written stays a gap of its true length. + */ +export class ViewerVoice implements Disposable { + private readonly keys: ReceiveKeys + private readonly payloadType: number + private readonly reporter: CameraReporter + private readonly sessionIdentifier: string + private readonly speakerMuted: ViewerVoiceOptions['speakerMuted'] + private readonly talkback: ViewerVoiceOptions['talkback'] + private readonly voice: ViewerVoiceSetting + private readonly werift: Pick + private readonly viewers = new Map() + private retransmissions: ReadonlySet = new Set() + private readonly counts: VoiceCounts = { + opened: 0, + stale: 0, + unkeyed: 0, + unopened: 0, + viewers: 0, + written: 0, + } + + /** + * Makes a session's voice reader, following no viewer. + * @param options - The reader's options. + */ + constructor(options: ViewerVoiceOptions) { + this.keys = options.keys + this.payloadType = options.payloadType + this.reporter = options.reporter + this.sessionIdentifier = options.sessionIdentifier + this.speakerMuted = options.speakerMuted + this.talkback = options.talkback + this.voice = options.voice + this.werift = options.werift + } + + /** + * Takes the SSRCs the applied remote description gives to retransmission, none of whose packets is read as voice from then on. + * @param ssrcs - The SSRCs. + */ + setRetransmissions(ssrcs: ReadonlySet): void { + this.retransmissions = ssrcs + } + + /** + * Reads one RTP packet a transport of the session received. A packet of a viewer whose talkback is closed, declined or ended, and every viewer's packet + * while the camera's Speaker is muted, is neither opened nor counted, read from the key ID its SFrame header names before any cryptography. A muted + * packet starts no sink and moves no stream's counter or clock. + * @param packet - The packet, as werift parsed it. + */ + take(packet: RtpPacket): void { + const { header, payload } = packet + const kind = this.kindOf(header.payloadType) + + if (!kind || (payload[0] !== WHOLE_CIPHERTEXT) || this.retransmissions.has(header.ssrc)) { + return + } + + const ciphertext = payload.subarray(1) + const sframe = readSFrameHeader(ciphertext) + + if (!sframe) { + this.counts.unopened++ + return + } + + if (this.viewers.get(sframe.keyId)?.talkback.closed || this.speakerMuted()) { + return + } + + const opened = this.open(kind, header, sframe, ciphertext) + + if (!opened) { + return + } + + const { frame, stream, viewer } = opened + const { duration, frames, voice } = readOpusVoice(frame) + + this.counts.opened++ + + // The event's values are made only while the engine's channel has a subscriber, since a viewer's packets come many times a second. It names the key by + // its ID, written as the Update Session event writes it: a packet is read against the key a hub wrote, and never by the key's bytes. + if (ENGINE_DEBUG.hasSubscribers) { + this.reporter.debug(ENGINE_DEBUG, 'voice-packet-opened', () => { + const saying = voice + ? 'saying voice' + : 'saying no voice' + const openings = frames.map(opus => opus.toString('hex', 0, 1) || 'none').join(' ') + const { marker, payloadType, sequenceNumber, ssrc, timestamp } = header + const keyId = sframe.keyId.toString() + + return { + keyId, + marker, + octets: frame.length, + payloadType, + sentence: `WebRTC session ${this.sessionIdentifier} opened a voice packet of payload type ${payloadType} on SSRC ${ssrc} under key ID ${keyId}, ` + + `sequence ${sequenceNumber}, timestamp ${timestamp}, marker ${marker}: ${counted(frame.length, 'octet')} opening ${frame.toString('hex', 0, 2)}, frames ` + + `opening ${openings}, ${saying}.`, + sequenceNumber, + sessionIdentifier: this.sessionIdentifier, + ssrc, + timestamp, + voice, + } + }) + } + + stream.clock(header, duration) + + if (this.plays(viewer, stream, header, duration, voice)) { + this.write(viewer, stream, header, frame) + } + + stream.sequenceNumber = header.sequenceNumber + } + + /** + * Takes the key IDs whose keys the store zeroed. Each viewer's keys derived under one are zeroed with their counters, and a key written again under it opens + * from a first count. A viewer whose key ID the store no longer holds has left: its talkback is ended, its failed-writes problem raised and the viewer + * dropped, while a viewer whose key was replaced under its ID stays with its sink. + * @param keyIds - The key IDs. + */ + forget(keyIds: readonly bigint[]): void { + for (const keyId of keyIds) { + const viewer = this.viewers.get(keyId) + + if (!viewer) { + continue + } + + viewer.zero() + + if (this.keys.get(keyId) !== undefined) { + continue + } + + // The viewer leaves the map before its talkback's end releases what its talker registered, which is plugin code: nothing that release sets off + // finds the viewer again. + this.viewers.delete(keyId) + viewer.talkback.end() + viewer.talkback.logFailedWrites() + + if (ENGINE_DEBUG.hasSubscribers) { + this.reporter.debug(ENGINE_DEBUG, 'viewer-dropped', () => ({ + keyId: keyId.toString(), + sentence: `WebRTC session ${this.sessionIdentifier} drops viewer ${keyId}, whose key the session no longer holds, and ends its talkback.`, + sessionIdentifier: this.sessionIdentifier, + })) + } + } + } + + /** + * Raises the failed-writes problem of each viewer it still holds, zeroes every key it derived and states what it read. It ends no talkback, since each + * talkback's end, which releases what its talker registered, stands on the session's stack above the reader and has run by then. + */ + [Symbol.dispose](): void { + for (const viewer of this.viewers.values()) { + viewer.talkback.logFailedWrites() + viewer.zero() + } + + this.viewers.clear() + + this.reporter.debug(ENGINE_DEBUG, 'voice-summary', () => { + const { opened, stale, unkeyed, unopened, viewers, written } = this.counts + + return { + opened, + sentence: `WebRTC session ${this.sessionIdentifier} opened ${counted(opened, 'voice packet')} and wrote ${written} of them to the ` + + `${nounFor(viewers, 'talkback sink')} of the ${counted(viewers, 'viewer')} it followed, dropping ${unkeyed} whose key was not held, ${stale} whose ` + + `counter did not pass its stream's last and ${unopened} that did not open.`, + sessionIdentifier: this.sessionIdentifier, + stale, + unkeyed, + unopened, + viewers, + written, + } + }) + } + + // The voice stream a payload type is, the better stream's read under 'automatic' alone. + private kindOf(payloadType: number): VoiceKind | undefined { + if (payloadType === DEPENDABLE_VOICE.payloadType) { + return DEPENDABLE_VOICE + } + + return ((payloadType === BETTER_VOICE.payloadType) && (this.voice === 'automatic')) + ? BETTER_VOICE + : undefined + } + + /* Opens a voice packet's ciphertext, or drops and counts it: one whose key the store does not hold, one whose counter does not pass the last its stream + * opened, before any cryptography, and one that does not open. The keys are derived from the key and the packet's own SSRC the first time a stream opens + * under its viewer's key and kept with the counter, and keys derived for a packet that does not open are zeroed at once: a viewer is followed, and a + * stream tracked with its keys, from its first packet that opens. A packet on a new SSRC of a kind its viewer holds takes that stream's place, whose keys + * are zeroed, and is where the stream on the new SSRC resumed, its gap read against the end of the stream it replaces. A stream that returns on a new + * SSRC after a drop-out is read as one that returns on its own. + */ + private open(kind: VoiceKind, header: RtpHeader, sframe: SFrameHeader, ciphertext: Buffer): { frame: Buffer, stream: VoiceStream, viewer: Viewer } | undefined { + const key = this.keys.get(sframe.keyId) + + if (!key) { + this.counts.unkeyed++ + return undefined + } + + const known = this.viewers.get(sframe.keyId) + const held = known?.streams[kind.place] + const tracked = (held?.ssrc === header.ssrc) + ? held + : undefined + const last = tracked?.opened + + if (last && (sframe.counter <= last.counter)) { + this.counts.stale++ + return undefined + } + + const keys = last?.keys ?? deriveStreamKeys({ + keyId: sframe.keyId, + sessionKey: key, + ssrc: header.ssrc, + suite: SFRAME_AUDIO_SUITE, + }) + const frame = openSFrame(keys, sframe, ciphertext) + + if (!frame) { + if (!last) { + zeroStreamKeys(keys) + } + + this.counts.unopened++ + return undefined + } + + const viewer = known ?? this.follow(sframe.keyId) + + if (!tracked) { + held?.zero() + + const stream = viewer.streams[kind.place] = new VoiceStream(kind, header, { counter: sframe.counter, keys }, held?.end) + + return { frame, stream, viewer } + } + + if (last) { + last.counter = sframe.counter + } else { + tracked.opened = { counter: sframe.counter, keys } + } + + return { frame, stream: tracked, viewer } + } + + // Follows a viewer from its first packet that opens, with a talkback of its own. + private follow(keyId: bigint): Viewer { + const viewer = new Viewer(keyId, this.talkback(keyId)) + + this.viewers.set(keyId, viewer) + this.counts.viewers++ + + return viewer + } + + /* Whether an opened packet is written, its stream already moved on to it, with the viewer's choice of stream moved as the rule moves it. A viewer's sink + * starts at its first packet that says voice, which plays its own stream, and before it nothing is read but its streams' ends and resumes. After it a + * packet's place decides which half of the rule reads it. + */ + private plays(viewer: Viewer, stream: VoiceStream, header: RtpHeader, duration: number, voice: boolean): boolean { + if (viewer.playing === undefined) { + if (!voice) { + return false + } + + viewer.playing = stream.kind.place + + if (ENGINE_DEBUG.hasSubscribers) { + this.reporter.debug(ENGINE_DEBUG, 'talkback-sink-started', () => ({ + keyId: viewer.keyId.toString(), + sentence: `WebRTC session ${this.sessionIdentifier} starts the talkback sink of viewer ${viewer.keyId} on its ${stream.kind.place} stream, SSRC ` + + `${stream.ssrc}.`, + sessionIdentifier: this.sessionIdentifier, + ssrc: stream.ssrc, + stream: stream.kind.place, + })) + } + + return true + } + + return (stream.kind.place === 'better') + ? this.readBetter(viewer, stream, header, duration) + : this.readDependable(viewer, stream) + } + + /* Reads a better packet. The better stream playing writes it. With the dependable stream playing, a standing mark lets the better stream's first packet + * at or past it take the talk, and with none a packet that keeps pace marks where the better stream takes the talk: its end, stepped on by whole packets + * of its length until it is at or past the dependable stream's end, which means nothing the dependable stream wrote is written again. A packet that lasts no time + * steps nothing: it marks only once it reaches the dependable stream's end itself. While the better stream is held down it marks only once its end is + * STAY_DOWN_BOUND past the hold, and a packet that comes LAG_BOUND or more after its stream's end, after a drop-out or a stop in sending, moves the hold + * on to itself, which is why each counts the bound again and a single lost packet counts nothing again. A standing mark is read before the hold and no gap drops + * it: a drop-out or a stop between a mark and its take counts nothing. The packet in hand never takes the talk itself. + */ + private readBetter(viewer: Viewer, better: VoiceStream, header: RtpHeader, duration: number): boolean { + if (viewer.playing === 'better') { + return true + } + + // The dependable stream plays only from one of its own packets: it is tracked whenever it plays, and a stream replaced takes its place. + const { dependable } = viewer.streams + + if (!dependable) { + return false + } + + if (viewer.mark !== undefined) { + if (ticksPast(header.timestamp, viewer.mark) < 0) { + return false + } + + viewer.mark = undefined + viewer.hold = undefined + viewer.playing = 'better' + this.sayChange(viewer, better, 'the better stream keeping pace') + + return true + } + + if ((viewer.hold !== undefined) && (better.gap >= LAG_TICKS)) { + viewer.hold = later(viewer.hold, header.timestamp) + } + + const behind = ticksPast(dependable.end, better.end) + + if ((behind >= KEEPING_PACE_TICKS) || ((viewer.hold !== undefined) && (ticksPast(better.end, viewer.hold) < STAY_DOWN_TICKS))) { + return false + } + + if (behind <= 0) { + viewer.mark = better.end + } else if (duration > 0) { + viewer.mark = wireTimestamp(better.end + Math.ceil(behind / duration) * duration) + } + + return false + } + + /* Reads a dependable packet. One whose end is LAG_BOUND or more past the latest of the better stream's end, a standing mark and the dependable stream's + * last resume reads the better stream as behind: a fall back when the better stream plays, a mark dropped when it is waited for and a hold moved on when + * the dependable stream plays already, the dependable stream playing from that packet and the better stream held down from its end. What goes unwritten + * at a fall back or a mark dropped is the span from the better stream's end, or from the mark, to that packet's start. A viewer with no better stream reads + * nothing. Otherwise the dependable stream playing writes a packet that ends at or before a standing mark and none that runs past it, which means a better stream + * stamped off the dependable stream's packets leaves less than a packet unwritten at the mark and writes no moment twice. + */ + private readDependable(viewer: Viewer, dependable: VoiceStream): boolean { + const { better } = viewer.streams + + if (better) { + const reached = later(later(better.end, dependable.resumedAt), viewer.mark ?? better.end) + + if (ticksPast(dependable.end, reached) >= LAG_TICKS) { + if (viewer.playing === 'better') { + viewer.playing = 'dependable' + this.sayChange(viewer, dependable, 'the better stream having fallen behind') + } else if ((viewer.mark !== undefined) && ENGINE_DEBUG.hasSubscribers) { + this.reporter.debug(ENGINE_DEBUG, 'viewer-mark-dropped', () => ({ + keyId: viewer.keyId.toString(), + sentence: `WebRTC session ${this.sessionIdentifier} drops the mark of viewer ${viewer.keyId}, its better stream having fallen behind.`, + sessionIdentifier: this.sessionIdentifier, + })) + } + + viewer.mark = undefined + viewer.hold = dependable.end + + return true + } + } + + if (viewer.playing === 'better') { + return false + } + + return (viewer.mark === undefined) || (ticksPast(dependable.end, viewer.mark) <= 0) + } + + // States a change of the stream that plays, with its reason, its values made only while the engine's channel has a subscriber. + private sayChange(viewer: Viewer, stream: VoiceStream, reason: string): void { + if (ENGINE_DEBUG.hasSubscribers) { + this.reporter.debug(ENGINE_DEBUG, 'viewer-moved', () => ({ + keyId: viewer.keyId.toString(), + reason, + sentence: `WebRTC session ${this.sessionIdentifier} moves viewer ${viewer.keyId} to its ${stream.kind.place} stream, SSRC ${stream.ssrc}, ${reason}.`, + sessionIdentifier: this.sessionIdentifier, + ssrc: stream.ssrc, + stream: stream.kind.place, + })) + } + } + + /* Writes one opened packet of the stream that plays to its viewer's talkback, under the header the reader writes: the first played packet's own values, + * then the playing stream's own steps from its last opened packet, the sequence's taken within SEQUENCE_RANGE, and one sequence number at a change of + * stream, a replaced stream's first packet among them. The timestamp is the viewer's own packet's, since both of a viewer's streams count one clock: + * it runs on by the media time between packets and a moment not written stays a gap of its true length. The marker is set on the sink's first packet and + * wherever the viewer's own packet carried it. A packet is counted written once the sink was handed it, and a talkback the write leaves closed has its + * viewer's keys zeroed. + */ + private write(viewer: Viewer, stream: VoiceStream, header: RtpHeader, frame: Buffer): void { + const first = !viewer.written + const written = viewer.written ??= { + sequenceNumber: header.sequenceNumber, + ssrc: header.ssrc, + stream, + } + + if (written.stream !== stream) { + written.sequenceNumber = nextSequence(written.sequenceNumber) + written.stream = stream + } else if (!first) { + written.sequenceNumber = (written.sequenceNumber + (header.sequenceNumber - stream.sequenceNumber + SEQUENCE_RANGE) % SEQUENCE_RANGE) % SEQUENCE_RANGE + } + + const rtpHeader = new this.werift.RtpHeader({ + marker: marksPacket(false, true, first || header.marker), + payloadType: this.payloadType, + sequenceNumber: written.sequenceNumber, + ssrc: written.ssrc, + timestamp: header.timestamp, + }) + + if (viewer.talkback.write(new this.werift.RtpPacket(rtpHeader, frame).serialize())) { + this.counts.written++ + } + + if (viewer.talkback.closed) { + viewer.zero() + } + } +} diff --git a/src/lib/camera/webrtc/voice/opusVoice.spec.ts b/src/lib/camera/webrtc/voice/opusVoice.spec.ts new file mode 100644 index 000000000..4f476df0c --- /dev/null +++ b/src/lib/camera/webrtc/voice/opusVoice.spec.ts @@ -0,0 +1,495 @@ +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { readOpusVoice } from './opusVoice.js' + +// A table-of-contents octet: the configuration in the top five bits, the stereo flag and the frame count code in the last two. +function toc(config: number, code: number, stereo = false): number { + return (config << 3) | (stereo + ? 0x04 + : 0) | code +} + +// The configurations the rows read, each by RFC 6716's table: the speech layer alone at wideband for frames of 10, 20, 40 and 60 milliseconds, the hybrid at +// super-wideband for 20, and the transform layer alone at fullband for 20. +const SPEECH_10 = 8 +const SPEECH_20 = 9 +const SPEECH_40 = 10 +const SPEECH_60 = 11 +const HYBRID_20 = 13 +const TRANSFORM_20 = 31 + +interface Case { + readonly frames: number[][] + readonly name: string + readonly packet: number[] + readonly voice: boolean +} + +const PADDED_FRAME = [0x80, 0x01, 0x02] + +const CASES: Case[] = [ + { + frames: [ + [0x80, 0x11], + ], + name: 'a frame of 20 milliseconds whose flag is set', + packet: [ + toc(SPEECH_20, 0), + 0x80, + 0x11, + ], + voice: true, + }, + { + frames: [ + [0x7F, 0x11], + ], + name: 'a frame of 20 milliseconds whose flag is clear and every lower bit set', + packet: [ + toc(SPEECH_20, 0), + 0x7F, + 0x11, + ], + voice: false, + }, + { + frames: [ + [0x80], + ], + name: 'a frame of 10 milliseconds whose flag is set', + packet: [ + toc(SPEECH_10, 0), + 0x80, + ], + voice: true, + }, + { + frames: [ + [0x40], + ], + name: 'a frame of 10 milliseconds whose second bit alone is set', + packet: [ + toc(SPEECH_10, 0), + 0x40, + ], + voice: false, + }, + { + frames: [ + [0x40], + ], + name: 'a frame of 40 milliseconds whose second flag alone is set', + packet: [ + toc(SPEECH_40, 0), + 0x40, + ], + voice: true, + }, + { + frames: [ + [0x20], + ], + name: 'a frame of 40 milliseconds whose third bit alone is set', + packet: [ + toc(SPEECH_40, 0), + 0x20, + ], + voice: false, + }, + { + frames: [ + [0x20], + ], + name: 'a frame of 60 milliseconds whose third flag alone is set', + packet: [ + toc(SPEECH_60, 0), + 0x20, + ], + voice: true, + }, + { + frames: [ + [0x10], + ], + name: 'a frame of 60 milliseconds whose fourth bit alone is set', + packet: [ + toc(SPEECH_60, 0), + 0x10, + ], + voice: false, + }, + { + frames: [ + [0x80, 0x05], + ], + name: 'a stereo frame whose mid flag is set', + packet: [ + toc(SPEECH_20, 0, true), + 0x80, + 0x05, + ], + voice: true, + }, + { + frames: [ + [0x20, 0x05], + ], + name: 'a stereo frame whose side flag alone is set', + packet: [ + toc(SPEECH_20, 0, true), + 0x20, + 0x05, + ], + voice: false, + }, + { + frames: [ + [0x80, 0x07], + ], + name: 'a hybrid frame whose flag is set', + packet: [ + toc(HYBRID_20, 0), + 0x80, + 0x07, + ], + voice: true, + }, + { + frames: [ + [0x40, 0x07], + ], + name: 'a hybrid frame whose second bit alone is set', + packet: [ + toc(HYBRID_20, 0), + 0x40, + 0x07, + ], + voice: false, + }, + { + frames: [ + [0x00, 0x00], + ], + name: 'a frame of no speech layer, of any length', + packet: [ + toc(TRANSFORM_20, 0), + 0x00, + 0x00, + ], + voice: true, + }, + { + frames: [[]], + name: 'an empty frame of no speech layer', + packet: [ + toc(TRANSFORM_20, 0), + ], + voice: false, + }, + { + frames: [[]], + name: 'an empty frame of the speech layer', + packet: [ + toc(SPEECH_20, 0), + ], + voice: false, + }, + { + frames: [ + [0x00, 0x01], + [0x80, 0x02], + ], + name: 'code 1, two frames of one length, the second saying voice', + packet: [ + toc(SPEECH_20, 1), + 0x00, + 0x01, + 0x80, + 0x02, + ], + voice: true, + }, + { + frames: [], + name: 'code 1 over an odd number of octets', + packet: [ + toc(SPEECH_20, 1), + 0x80, + 0x01, + 0x02, + ], + voice: false, + }, + { + frames: [ + [0x00], + [0x80, 0x05], + ], + name: 'code 2, a first frame of one octet', + packet: [ + toc(SPEECH_20, 2), + 1, + 0x00, + 0x80, + 0x05, + ], + voice: true, + }, + { + frames: [[], []], + name: 'code 2, two empty frames', + packet: [ + toc(SPEECH_20, 2), + 0, + ], + voice: false, + }, + { + frames: [], + name: 'code 2 whose first frame runs past the packet', + packet: [ + toc(SPEECH_20, 2), + 5, + 0x80, + ], + voice: false, + }, + { + frames: [], + name: 'code 2 whose length runs past the packet', + packet: [ + toc(SPEECH_20, 2), + 252, + ], + voice: false, + }, + { + frames: [ + [0x00, 0x01], + [0x00, 0x02], + [0x80, 0x03], + ], + name: 'code 3, three frames of one length', + packet: [ + toc(SPEECH_20, 3), + 0x03, + 0x00, + 0x01, + 0x00, + 0x02, + 0x80, + 0x03, + ], + voice: true, + }, + { + frames: [ + [0x00], + [0x80, 0x01], + ], + name: 'code 3, frames of their own lengths and padding', + packet: [ + toc(SPEECH_20, 3), + 0xC2, + 2, + 1, + 0x00, + 0x80, + 0x01, + 0, + 0, + ], + voice: true, + }, + { + frames: [PADDED_FRAME], + name: 'code 3, padding of 255 and a further octet', + packet: [ + toc(SPEECH_20, 3), + 0x41, + 255, + 0, + ...PADDED_FRAME, + ...Array.from({ length: 254 }).fill(0), + ], + voice: true, + }, + { + frames: [], + name: 'code 3 with no frames', + packet: [ + toc(SPEECH_20, 3), + 0x00, + 0x80, + ], + voice: false, + }, + { + frames: [], + name: 'code 3 whose frame lengths run past the packet', + packet: [ + toc(SPEECH_20, 3), + 0x82, + 10, + 0x80, + ], + voice: false, + }, + { + frames: [], + name: 'code 3 whose padding runs past the packet', + packet: [ + toc(SPEECH_20, 3), + 0x41, + 9, + 0x80, + ], + voice: false, + }, + { + frames: [], + name: 'code 3 whose frames do not divide its octets', + packet: [ + toc(SPEECH_20, 3), + 0x02, + 0x80, + 0x01, + 0x02, + ], + voice: false, + }, + { + frames: [], + name: 'code 3 with no frame count octet', + packet: [ + toc(SPEECH_20, 3), + ], + voice: false, + }, + { + frames: [], + name: 'an empty packet', + packet: [], + voice: false, + }, +] + +describe('readOpusVoice', () => { + it('reads every frame count code, padding and frame lengths of one octet and two, and says voice by the flags of each configuration\'s speech layer', () => { + for (const { frames, name, packet, voice } of CASES) { + const read = readOpusVoice(Buffer.from(packet)) + + expect({ + frames: read.frames.map(frame => [...frame]), + name, + }).toEqual({ frames, name }) + expect({ name, voice: read.voice }).toEqual({ name, voice }) + } + }) + + it('reads a first frame whose length takes two octets', () => { + const first = Buffer.alloc(260, 0x00) + const read = readOpusVoice(Buffer.concat([ + Buffer.from([ + toc(SPEECH_20, 2), + 252, + 2, + ]), + first, + Buffer.from([0x80, 0x09]), + ])) + + expect(read.frames.map(frame => frame.length)).toEqual([260, 2]) + expect(read.frames[1][0]).toBe(0x80) + expect(read.voice).toBe(true) + }) + + it('reads a packet\'s duration as its frame count times its configuration\'s frame time, for every configuration and frame count code, and none for no ' + + 'frames', () => { + // The frame time of each configuration in milliseconds, a row of RFC 6716 3.1's table a line, in configuration order. + const frameTimes = [ + [10, 20, 40, 60], + [10, 20, 40, 60], + [10, 20, 40, 60], + [10, 20], + [10, 20], + [2.5, 5, 10, 20], + [2.5, 5, 10, 20], + [2.5, 5, 10, 20], + [2.5, 5, 10, 20], + ].flat() + // The octets after a table-of-contents octet of each frame count code, with the frames they pack: one, two of one length, two of their own lengths, + // and three of one length behind a frame count octet. + const packings: { readonly after: number[], readonly code: number, readonly frames: number }[] = [ + { + after: [0x00], + code: 0, + frames: 1, + }, + { + after: [0x00, 0x00], + code: 1, + frames: 2, + }, + { + after: [1, 0x00, 0x00], + code: 2, + frames: 2, + }, + { + after: [0x03, 0x00, 0x00, 0x00], + code: 3, + frames: 3, + }, + ] + + expect(frameTimes).toHaveLength(32) + + for (const [config, time] of frameTimes.entries()) { + for (const { after, code, frames } of packings) { + const packet = Buffer.from([ + toc(config, code), + ...after, + ]) + + expect(readOpusVoice(packet).duration, `configuration ${config}, code ${code}`).toBe(frames * time * 48) + } + } + + // An empty packet, a packet of frame count code 3 with no frames, and one whose packing breaks its own rule. + const unread = [ + [], + [ + toc(SPEECH_20, 3), + 0x00, + ], + [ + toc(SPEECH_20, 1), + 0x80, + 0x01, + 0x02, + ], + ] + + for (const packet of unread) { + expect(readOpusVoice(Buffer.from(packet)).duration).toBe(0) + } + }) + + it('answers each frame as a view of the packet\'s own octets', () => { + const packet = Buffer.from([ + toc(SPEECH_20, 1), + 0x80, + 0x01, + 0x00, + 0x02, + ]) + const [first] = readOpusVoice(packet).frames + + packet[1] = 0x00 + + expect(first[0]).toBe(0x00) + }) +}) diff --git a/src/lib/camera/webrtc/voice/opusVoice.ts b/src/lib/camera/webrtc/voice/opusVoice.ts new file mode 100644 index 000000000..2348531a0 --- /dev/null +++ b/src/lib/camera/webrtc/voice/opusVoice.ts @@ -0,0 +1,249 @@ +import type { Buffer } from 'node:buffer' + +/* An Opus packet read as far as a viewer's voice needs it, with nothing decoded: its frames, found as RFC 6716 3.2 packs them, how long it lasts, and + * whether it says voice. Every frame of a configuration that carries the speech layer opens with that layer's voice activity flags, the first symbols its + * range coder writes at uniform odds, which is why RFC 6716 4.2.3 reads them from the most significant bits of the frame's first octet: one flag for each 20 + * milliseconds of speech-layer frame the Opus frame holds, a frame of 10 milliseconds taking one. A stereo frame's mid channel's flags stand first, and + * those are the ones read. + */ + +/** + * The RTP clock of every Opus stream, 48,000 a second whatever the codec codes at (RFC 7587 4.1), in ticks a millisecond. + */ +export const OPUS_TICKS_PER_MILLISECOND = 48 + +// The table-of-contents octet: the configuration in its top five bits and the frame count code in its last two. +const CONFIG_SHIFT = 3 +const COUNT_CODE_BITS = 0x03 + +// The configurations with the speech layer alone, whose frames run 10, 20, 40 and 60 milliseconds by the configuration's last two bits, and the hybrid +// configurations after them, whose frames run 10 and 20 milliseconds. Every configuration from the first of the transform layer alone carries no speech +// layer. +const HYBRID_FIRST_CONFIG = 12 +const TRANSFORM_FIRST_CONFIG = 16 +const SPEECH_FRAME_SIZE_BITS = 0x03 + +// The frame time in milliseconds each configuration states, by RFC 6716 3.1's table: the speech layer's and the transform layer's by the configuration's +// last two bits, and the hybrid's by its last bit. +const SPEECH_FRAME_TIMES = [10, 20, 40, 60] +const HYBRID_FRAME_TIMES = [10, 20] +const TRANSFORM_FRAME_TIMES = [2.5, 5, 10, 20] +const HYBRID_FRAME_SIZE_BIT = 0x01 +const TRANSFORM_FRAME_SIZE_BITS = 0x03 + +// The voice activity flags a speech-layer frame opens with, by the frame's size: the top bit for a frame of 10 or 20 milliseconds, and the top two and +// three for one of 40 and 60, one flag for each 20 milliseconds. +const ONE_FLAG = 0x80 +const SPEECH_FLAGS = [ONE_FLAG, ONE_FLAG, 0xC0, 0xE0] + +// The frame count octet of a packet of frame count code 3: its first bit marks frames of their own lengths, its second Opus padding, and its last six the +// number of frames. +const VARIABLE_FRAMES = 0x80 +const PADDED = 0x40 +const FRAME_COUNT_BITS = 0x3F + +// A frame length's first octet: up to 251 the length itself, and from 252 the low part of a length a second octet completes, four for each of its counts. +const TWO_OCTET_LENGTH = 252 +const SECOND_OCTET_WEIGHT = 4 + +// A padding length octet of 255 adds 254 octets of padding and a further padding length octet after it. +const PADDING_CONTINUES = 255 +const PADDING_STEP = 254 + +/** + * An Opus packet's duration, its frames, each a view of the packet's own octets, and whether the packet says voice. + */ +export interface OpusVoice { + /** + * How long the packet lasts in 48 kHz units, its frame count times the frame time its configuration states. + */ + readonly duration: number + readonly frames: readonly Buffer[] + readonly voice: boolean +} + +const UNREAD: OpusVoice = { duration: 0, frames: [], voice: false } + +// A packet's frames, laid as RFC 6716 3.2 lays them for each frame count code, or undefined for one whose packing runs past its end or breaks a rule of +// its own: an empty packet, an odd number of octets split into two frames of one length, a frame count of zero and lengths that do not divide evenly. +function framesOf(packet: Buffer): Buffer[] | undefined { + if (packet.length === 0) { + return undefined + } + + const code = packet[0] & COUNT_CODE_BITS + + switch (code) { + case 0: { + return [ + packet.subarray(1), + ] + } + + case 1: { + const length = (packet.length - 1) / 2 + + return Number.isInteger(length) + ? [ + packet.subarray(1, 1 + length), + packet.subarray(1 + length), + ] + : undefined + } + + case 2: { + const first = readLength(packet, 1, packet.length) + + if (!first || (first.end + first.length > packet.length)) { + return undefined + } + + return [ + packet.subarray(first.end, first.end + first.length), + packet.subarray(first.end + first.length), + ] + } + + default: { + return framesOfCodeThree(packet) + } + } +} + +// The frames of a packet of frame count code 3: the frame count octet, any padding lengths after it with the padding they name taken off the packet's end, +// then either one length shared by every frame or a length for each but the last, which takes what remains. +function framesOfCodeThree(packet: Buffer): Buffer[] | undefined { + if (packet.length < 2) { + return undefined + } + + const countOctet = packet[1] + const count = countOctet & FRAME_COUNT_BITS + let offset = 2 + let end = packet.length + + if (count === 0) { + return undefined + } + + if (countOctet & PADDED) { + let padding = 0 + let octet = PADDING_CONTINUES + + while (octet === PADDING_CONTINUES) { + if (offset >= packet.length) { + return undefined + } + + octet = packet[offset++] + padding += (octet === PADDING_CONTINUES) + ? PADDING_STEP + : octet + } + + end -= padding + } + + if (end < offset) { + return undefined + } + + if (!(countOctet & VARIABLE_FRAMES)) { + const length = (end - offset) / count + + return Number.isInteger(length) + ? Array.from({ length: count }, (_, index) => packet.subarray(offset + index * length, offset + (index + 1) * length)) + : undefined + } + + const lengths: number[] = [] + + for (let index = 1; index < count; index++) { + const read = readLength(packet, offset, end) + + if (!read) { + return undefined + } + + lengths.push(read.length) + offset = read.end + } + + const frames: Buffer[] = [] + + for (const length of lengths) { + if (offset + length > end) { + return undefined + } + + frames.push(packet.subarray(offset, offset + length)) + offset += length + } + + frames.push(packet.subarray(offset, end)) + + return frames +} + +// A frame length of one or two octets at an offset, with the offset after it, or undefined for one that runs past the end given. +function readLength(packet: Buffer, offset: number, end: number): { end: number, length: number } | undefined { + if (offset >= end) { + return undefined + } + + const first = packet[offset] + + if (first < TWO_OCTET_LENGTH) { + return { end: offset + 1, length: first } + } + + if (offset + 1 >= end) { + return undefined + } + + return { end: offset + 2, length: first + SECOND_OCTET_WEIGHT * packet[offset + 1] } +} + +// The frame time in milliseconds a configuration states. +function frameTime(config: number): number { + if (config >= TRANSFORM_FIRST_CONFIG) { + return TRANSFORM_FRAME_TIMES[config & TRANSFORM_FRAME_SIZE_BITS] + } + + return (config >= HYBRID_FIRST_CONFIG) + ? HYBRID_FRAME_TIMES[config & HYBRID_FRAME_SIZE_BIT] + : SPEECH_FRAME_TIMES[config & SPEECH_FRAME_SIZE_BITS] +} + +// The voice activity flags a frame of a configuration opens with, or undefined for a configuration with no speech layer. +function speechFlags(config: number): number | undefined { + if (config >= TRANSFORM_FIRST_CONFIG) { + return undefined + } + + return (config >= HYBRID_FIRST_CONFIG) + ? ONE_FLAG + : SPEECH_FLAGS[config & SPEECH_FRAME_SIZE_BITS] +} + +/** + * Reads an Opus packet's duration, its frames and whether it says voice. Its duration is its frame count times the frame time its configuration states, + * a frame of no octets counting as a frame. A frame of a configuration that carries the speech layer says voice when one of its voice activity flags is + * set, and a packet of a configuration with no speech layer when it holds a frame of any length. A frame of no octets says nothing, and a packet says + * voice when one of its frames does. + * @param packet - The Opus packet, its table-of-contents octet first. + * @returns The packet's duration, frames and whether it says voice, or no duration, no frames and no voice for a packet whose packing runs past its end. + */ +export function readOpusVoice(packet: Buffer): OpusVoice { + const frames = framesOf(packet) + + if (!frames) { + return UNREAD + } + + const config = packet[0] >> CONFIG_SHIFT + const flags = speechFlags(config) + const voice = frames.some(frame => (frame.length > 0) && ((flags === undefined) || ((frame[0] & flags) !== 0))) + + return { duration: frames.length * frameTime(config) * OPUS_TICKS_PER_MILLISECOND, frames, voice } +} diff --git a/src/lib/camera/webrtc/werift.spec.ts b/src/lib/camera/webrtc/werift.spec.ts new file mode 100644 index 000000000..f63552241 --- /dev/null +++ b/src/lib/camera/webrtc/werift.spec.ts @@ -0,0 +1,197 @@ +import type * as werift from 'werift' + +import type * as loader from './werift.js' + +import createDebug from 'debug' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { settle } from '../../../test-utils/settle.js' + +const WERIFT_DEBUG_NAME = 'HAP-NodeJS:Camera:WebRTC:werift' + +// A werift namespace of each form werift names its loggers in. +const WERIFT_NAMESPACES = ['werift:packages/webrtc/src/peerConnection.ts', 'werift-ice : packages/ice/src/ice.ts : log'] + +// The loader of a fresh module graph, which means a row's first load is the first the loader has made. +async function freshLoader(): Promise { + vi.resetModules() + + return await import('./werift.js') +} + +// The debug package's namespaces as the row found them, restored after it, since a row turns the library's werift debug name on. +let debugNamespaces: string + +beforeEach(() => { + debugNamespaces = createDebug.disable() + createDebug.enable(debugNamespaces) +}) + +afterEach(async () => { + createDebug.enable(debugNamespaces) + vi.doUnmock('werift') + vi.restoreAllMocks() + + // werift's log state is one global that a module reset leaves, which is why each row leaves werift's own output off, as a process without DEBUG starts. + const { debug } = await vi.importActual('werift') + debug.disable() +}) + +describe('loadWerift', () => { + it('answers one promise of werift\'s named exports to every load', async () => { + const actual = await vi.importActual('werift') + const { loadWerift } = await freshLoader() + const first = loadWerift() + + expect(loadWerift()).toBe(first) + expect(await first).toEqual({ + RTCPeerConnection: actual.RTCPeerConnection, + RTCRtpCodecParameters: actual.RTCRtpCodecParameters, + RtpHeader: actual.RtpHeader, + RtpPacket: actual.RtpPacket, + useSdesMid: actual.useSdesMid, + useSdesRTPStreamId: actual.useSdesRTPStreamId, + }) + expect(await loadWerift()).toBe(await first) + }) + + it('turns werift\'s own output off as it loads while the library\'s werift debug name is off, though werift\'s own setting turned it on', async () => { + const { debug } = await vi.importActual('werift') + debug.enable('werift*') + + expect(WERIFT_NAMESPACES.map(namespace => debug.enabled(namespace))).toEqual([true, true]) + + const { loadWerift } = await freshLoader() + await loadWerift() + + expect(createDebug.enabled(WERIFT_DEBUG_NAME)).toBe(false) + expect(WERIFT_NAMESPACES.map(namespace => debug.enabled(namespace))).toEqual([false, false]) + }) + + it('turns every werift namespace on as it loads while the library\'s werift debug name is on', async () => { + const { debug } = await vi.importActual('werift') + createDebug.enable(WERIFT_DEBUG_NAME) + + expect(WERIFT_NAMESPACES.map(namespace => debug.enabled(namespace))).toEqual([false, false]) + + const { loadWerift } = await freshLoader() + await loadWerift() + + expect(WERIFT_NAMESPACES.map(namespace => debug.enabled(namespace))).toEqual([true, true]) + }) + + it('leaves werift\'s own output off as it loads while the debug setting is *, which covers the library\'s werift debug name', async () => { + const { debug } = await vi.importActual('werift') + createDebug.enable('*') + + expect(createDebug.enabled(WERIFT_DEBUG_NAME)).toBe(true) + + const { loadWerift } = await freshLoader() + await loadWerift() + + expect(WERIFT_NAMESPACES.map(namespace => debug.enabled(namespace))).toEqual([false, false]) + }) + + it('leaves werift\'s own output off as it loads while the debug setting is HAP-NodeJS:* or HAP-NodeJS:Camera:WebRTC*, each covering the library\'s werift ' + + 'debug name', async () => { + const { debug } = await vi.importActual('werift') + + for (const pattern of ['HAP-NodeJS:*', 'HAP-NodeJS:Camera:WebRTC*']) { + createDebug.enable(pattern) + + expect(createDebug.enabled(WERIFT_DEBUG_NAME)).toBe(true) + + const { loadWerift } = await freshLoader() + await loadWerift() + + expect({ + enabled: WERIFT_NAMESPACES.map(namespace => debug.enabled(namespace)), + pattern, + }).toEqual({ + enabled: [false, false], + pattern, + }) + } + }) + + it('turns every werift namespace on as it loads while the library\'s werift debug name is listed beside another entry', async () => { + const { debug } = await vi.importActual('werift') + createDebug.enable(`HAP-NodeJS:Camera:MultiTier,${WERIFT_DEBUG_NAME}`) + + const { loadWerift } = await freshLoader() + await loadWerift() + + expect(WERIFT_NAMESPACES.map(namespace => debug.enabled(namespace))).toEqual([true, true]) + }) + + it('leaves werift\'s own output off as it loads while the library\'s werift debug name is listed and skipped', async () => { + const { debug } = await vi.importActual('werift') + debug.enable('werift*') + createDebug.enable(`${WERIFT_DEBUG_NAME},-${WERIFT_DEBUG_NAME}`) + + const { loadWerift } = await freshLoader() + await loadWerift() + + expect(WERIFT_NAMESPACES.map(namespace => debug.enabled(namespace))).toEqual([false, false]) + }) + + it('finds each entry of a debug setting as written in the debug package\'s names, which the loader reads its werift debug name from', () => { + createDebug.enable(`HAP-NodeJS:*, ${WERIFT_DEBUG_NAME},-HAP-NodeJS:Camera:MultiTier`) + + expect(createDebug.names).toEqual(['HAP-NodeJS:*', WERIFT_DEBUG_NAME]) + }) + + it('reads werift\'s named exports alone, never a default export', async () => { + const actual = await vi.importActual('werift') + const reads: PropertyKey[] = [] + + // The module records every member read of it, and a read of its default export shows whatever the read answers. + vi.doMock('werift', () => new Proxy({ ...actual }, { + get: (target, property, receiver) => { + reads.push(property) + + return Reflect.get(target, property, receiver) as unknown + }, + })) + + const { loadWerift } = await freshLoader() + + expect(await loadWerift()).toMatchObject({ RTCPeerConnection: actual.RTCPeerConnection }) + expect(reads).toContain('RTCPeerConnection') + expect(reads).not.toContain('default') + }) + + it('logs a load that fails once as an error, rejects every awaiter of it and leaves no rejection unhandled', async () => { + const failure = new Error('The werift install is broken.') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const unhandled = vi.fn() + + vi.doMock('werift', () => { + throw failure + }) + process.on('unhandledRejection', unhandled) + + try { + const { loadWerift } = await freshLoader() + + // A load started and never awaited, as a caller that starts it early makes, leaves the rejection handled as well. + void loadWerift() + + const awaiters = [ + loadWerift(), + loadWerift(), + ] + + for (const awaiter of awaiters) { + await expect(awaiter).rejects.toThrow() + } + + await settle() + + expect(error).toHaveBeenCalledExactlyOnceWith('The WebRTC engine could not load werift, and every WebRTC offer fails.', expect.anything()) + expect(unhandled).not.toHaveBeenCalled() + } finally { + process.off('unhandledRejection', unhandled) + } + }) +}) diff --git a/src/lib/camera/webrtc/werift.ts b/src/lib/camera/webrtc/werift.ts new file mode 100644 index 000000000..33854c895 --- /dev/null +++ b/src/lib/camera/webrtc/werift.ts @@ -0,0 +1,60 @@ +import type * as werift from 'werift' + +import createDebug from 'debug' + +/* The one place the library loads werift, the WebRTC stack its engine is built on. The load is lazy, since only a camera that serves WebRTC needs it, and + * made once for the process: every caller shares one promise of the module's named exports, and every other module takes werift's types by type alone. + * The promise carries a handler from its making. A load that fails, a broken install or a throw as werift evaluates, logs once and is never an unhandled + * rejection, while every caller that awaits it still rejects. + */ + +// The library's debug name that turns werift's own output on. werift logs network addresses, the ICE passwords of both ends and the DTLS record layer's +// write keys and nonces, which is why its output is off unless this name is listed by itself in the debug setting, and a wider pattern that covers the name, `*` or +// `HAP-NodeJS:*` among them, leaves it off. +const WERIFT_DEBUG_NAME = 'HAP-NodeJS:Camera:WebRTC:werift' + +/** + * The werift exports the engine builds on. + */ +export type Werift = Pick + +let loading: Promise | undefined + +/* Imports werift and sets its own output as it resolves. werift keeps its log state in one global: the switch is process-wide and reaches any werift + * copy in the process, another plugin's among them. Its output carries network addresses, the ICE passwords of both ends and the DTLS record layer's write + * keys and nonces, which is why only the library's werift debug name listed by itself turns every werift namespace on: the name must be an entry of the debug + * setting as written, which the debug package keeps in its names, and must read enabled. A skip of it still turns the output off. A wider pattern + * that covers the name leaves every werift namespace off, as a setting without the name does. + */ +async function importWerift(): Promise { + const { debug, RTCPeerConnection, RTCRtpCodecParameters, RtpHeader, RtpPacket, useSdesMid, useSdesRTPStreamId } = await import('werift') + + if (createDebug.names.includes(WERIFT_DEBUG_NAME) && createDebug.enabled(WERIFT_DEBUG_NAME)) { + debug.enable('werift*') + } else { + debug.disable() + } + + return { + RTCPeerConnection, + RTCRtpCodecParameters, + RtpHeader, + RtpPacket, + useSdesMid, + useSdesRTPStreamId, + } +} + +/** + * Loads werift once for the process, the first call starting the load and every call answering the same promise. The function is not async: it hands + * out that promise itself, whose handler is in place, and a caller that starts the load without awaiting it leaves no rejection unhandled. + * @returns The promise of werift's exports, which rejects for every caller when the load fails. + */ +export function loadWerift(): Promise { + if (!loading) { + loading = importWerift() + loading.catch((error: unknown) => console.error('The WebRTC engine could not load werift, and every WebRTC offer fails.', error)) + } + + return loading +} diff --git a/src/test-utils/engineDebug.ts b/src/test-utils/engineDebug.ts new file mode 100644 index 000000000..2d055d842 --- /dev/null +++ b/src/test-utils/engineDebug.ts @@ -0,0 +1,74 @@ +// The capture a spec takes of the debug events of one debug name or several while a row runs, the WebRTC engine's where the row names none, in a module of +// its own. No spec imports another. +import type { CameraDebugEvent } from '../lib/camera/diagnostics/debugChannels.js' + +import { subscribe, unsubscribe } from 'node:diagnostics_channel' + +import { onTestFinished } from 'vitest' + +import { DEBUG_NAMES } from '../lib/camera/diagnostics/debugChannels.js' + +// The one debug name every module of the engine writes under. +const ENGINE_DEBUG_NAME = 'HAP-NodeJS:Camera:WebRTC:engine' + +// The end of each capture a row still holds, by the list the capture answered, which lets a row end its capture before the row does. +const captures = new WeakMap void>() + +/* The channels the names given open, the engine's where none is given: each name as itself, and a name ending in `:*` standing for every debug name it + * opens, as the DEBUG setting reads such a name. + */ +function channelsOf(names: readonly string[]): string[] { + const given = (names.length === 0) + ? [ENGINE_DEBUG_NAME] + : names + + const channels = given.flatMap(name => name.endsWith(':*') + ? DEBUG_NAMES.filter(debugName => debugName.startsWith(name.slice(0, -1))) + : [name]) + + return Array.from(new Set(channels)) +} + +/* Subscribes one listener to the channels the names given open until the row finishes or the capture is ended, and answers the list the listener fills, + * kept as the capture's key. + */ +function capture(names: readonly string[], entry: (event: CameraDebugEvent) => Entry): Entry[] { + const entries: Entry[] = [] + const channels = channelsOf(names) + const listener = (message: unknown): void => { + entries.push(entry(message as CameraDebugEvent)) + } + const end = (): void => { + if (captures.delete(entries)) { + for (const name of channels) { + unsubscribe(name, listener) + } + } + } + + for (const name of channels) { + subscribe(name, listener) + } + + captures.set(entries, end) + onTestFinished(end) + + return entries +} + +/* Every debug event the debug names given publish while a row runs, the engine's where none is given, each as its sentence, in the order published. A + * subscription is what has a camera build its events, and a row reads what one call adds by the list's length before and after that call. + */ +export function captureDebug(...names: string[]): string[] { + return capture(names, event => event.sentence) +} + +// Every debug event the debug names given publish while a row runs, as `captureDebug` reads them, each whole. +export function captureDebugEvents(...names: string[]): CameraDebugEvent[] { + return capture(names, event => event) +} + +// Ends a capture before its row does: the row's later calls publish to no subscriber of the capture and build no event for it. +export function endDebugCapture(captured: readonly unknown[]): void { + captures.get(captured)?.() +} diff --git a/src/test-utils/openingStamp.ts b/src/test-utils/openingStamp.ts new file mode 100644 index 000000000..af0cafb9e --- /dev/null +++ b/src/test-utils/openingStamp.ts @@ -0,0 +1,10 @@ +// The opening's timestamp rule every spec that reads an opening's pictures computes its stamps by, in a module of its own with no import. The WebRTC +// engine's spec, which cannot load the shared camera fixtures over its mocks, reads the same rule the shared camera fixtures re-export. + +/* The timestamp an opening hands a picture at, by the opening's rule: one millisecond past the highest timestamp its tier's picture was placed at as the + * opening took its keyframe, at 90 kHz, plus the picture's distance from that keyframe, in milliseconds of presentation time, over the opening's speed, + * fifty unless a row names the speed its stretch's rate gives, at that rate to the nearest tick. A row reading a packet's timestamp takes it modulo 2^32. + */ +export function openingStamp(highest: number, distance: number, speed = 50): number { + return highest + 90 + Math.round(distance * 90 / speed) +} diff --git a/src/test-utils/sframeVectors.ts b/src/test-utils/sframeVectors.ts new file mode 100644 index 000000000..1d2b30cc9 --- /dev/null +++ b/src/test-utils/sframeVectors.ts @@ -0,0 +1,763 @@ +/* The SFrame sealing vectors the suites hold the WebRTC engine's sealing to: one whole encoded frame sealed as one SFrame ciphertext, as HomeKit's streams + * build it. Every input is synthetic: the session key is the octets 00 to 1f, the SSRCs and key IDs are made up, and each plaintext is patterned octets + * behind HEVC NAL unit headers, each unit behind its length in four octets. Nothing comes from a hub, a camera or a capture. Each ciphertext was computed + * twice by implementations apart, a sealer whose streams a home hub's viewer plays and the construction's octet formulas written out with node:crypto + * alone, and a vector stands only where the two agree. Each vector states its stream's secret, keys and salt, its nonce, header and tag, the ciphertext and + * that ciphertext cut into RTP payloads of at most the set's payload size, each behind its octet. Long hex is held as lines joined. + */ +import { Buffer } from 'node:buffer' +import { createDecipheriv, createHmac, hkdfSync, timingSafeEqual } from 'node:crypto' + +// The plaintexts the vectors seal, by name: a keyframe with its parameter sets, a frame that spans several RTP payloads and a short one. +export type SFramePlaintextName = 'keyframe' | 'long' | 'short' + +// One frame sealed on one stream: the inputs, every value on the way, the ciphertext and its RTP payloads. +export interface SFrameVector { + readonly authenticationKey: string + readonly ciphertext: string + readonly counter: bigint + readonly encryptionKey: string + readonly header: string + readonly keyId: bigint + readonly nonce: string + readonly plaintext: SFramePlaintextName + readonly rtpPayloads: readonly string[] + readonly salt: string + readonly ssrc: number + readonly streamSecret: string + readonly suite: number + readonly tag: string + readonly tagLength: number +} + +// The vectors with the plaintexts they seal, the payload size their ciphertexts were cut at and the one session key every stream's secret comes from. +export interface SFrameVectorSet { + readonly plaintexts: Readonly> + readonly rtpPayloadSize: number + readonly sessionKey: string + readonly vectors: readonly SFrameVector[] +} + +export const SFRAME_VECTORS: SFrameVectorSet = { + plaintexts: { + keyframe: [ + '0000001840010c01ffff01600000030090000003000003005d9598090000001842010101600000030090000003000003005da00280802d16000000074401c172', + 'b462400000002a2601030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d14', + ].join(''), + long: [ + '00000a8e0201030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b12', + '1920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2', + 'd9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b92', + '99a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b52', + '5960676e757c838a91989fa6adb4bbc2c9d0', + ].join(''), + short: '0000000b0201030a11181f262d343b', + }, + rtpPayloadSize: 1100, + sessionKey: '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', + vectors: [ + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'f011223344556680005cce038fa3f1d5d00999ebaa197c4b2d359a4a9343792bf655', + counter: 0n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f01122334455668000', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e39fc6c', + plaintext: 'short', + rtpPayloads: [ + 'c0f011223344556680005cce038fa3f1d5d00999ebaa197c4b2d359a4a9343792bf655', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '2d359a4a9343792bf655', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'f111223344556680007b0211a952e010ffc5c5d2b7eb164d5dac3ec42d0084b1c641', + counter: 1n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f11122334455668000', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e39fc6d', + plaintext: 'short', + rtpPayloads: [ + 'c0f111223344556680007b0211a952e010ffc5c5d2b7eb164d5dac3ec42d0084b1c641', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '5dac3ec42d0084b1c641', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'f711223344556680002e4aef4fbccaeffae78e607a923dd38245646d01a95fe9410b', + counter: 7n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f71122334455668000', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e39fc6b', + plaintext: 'short', + rtpPayloads: [ + 'c0f711223344556680002e4aef4fbccaeffae78e607a923dd38245646d01a95fe9410b', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '8245646d01a95fe9410b', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'f8112233445566800008c68bf7ecc5d3b747dd1c969ea24ca497c9724b89bb05fb315f', + counter: 8n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f8112233445566800008', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e39fc64', + plaintext: 'short', + rtpPayloads: [ + 'c0f8112233445566800008c68bf7ecc5d3b747dd1c969ea24ca497c9724b89bb05fb315f', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '97c9724b89bb05fb315f', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'f81122334455668000ff14e25190a4305e0241986d0cf652d02ea366ac4f62089d7548', + counter: 255n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f81122334455668000ff', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e39fc93', + plaintext: 'short', + rtpPayloads: [ + 'c0f81122334455668000ff14e25190a4305e0241986d0cf652d02ea366ac4f62089d7548', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '2ea366ac4f62089d7548', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'f91122334455668000010075c444d417f073e733fc71bbdcd6fe37e999b35481f222f647', + counter: 256n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f911223344556680000100', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e39fd6c', + plaintext: 'short', + rtpPayloads: [ + 'c0f91122334455668000010075c444d417f073e733fc71bbdcd6fe37e999b35481f222f647', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '37e999b35481f222f647', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'f91122334455668000ffff9f03a0a9f8d92c19b732b4b241e74194b947995e1ad6b64ab4', + counter: 65535n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f91122334455668000ffff', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e390393', + plaintext: 'short', + rtpPayloads: [ + 'c0f91122334455668000ffff9f03a0a9f8d92c19b732b4b241e74194b947995e1ad6b64ab4', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '94b947995e1ad6b64ab4', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'fa1122334455668000010000788eb798137294d8602417f7d1a3feb7ec2337f2096160320d', + counter: 65536n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'fa1122334455668000010000', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e38fc6c', + plaintext: 'short', + rtpPayloads: [ + 'c0fa1122334455668000010000788eb798137294d8602417f7d1a3feb7ec2337f2096160320d', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: 'b7ec2337f2096160320d', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'fb1122334455668000ffffffffd6d6c40134c3af00ff38df8118cab131cec6ff3d25153cbc13', + counter: 4294967295n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'fb1122334455668000ffffffff', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b71c60393', + plaintext: 'short', + rtpPayloads: [ + 'c0fb1122334455668000ffffffffd6d6c40134c3af00ff38df8118cab131cec6ff3d25153cbc13', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '31cec6ff3d25153cbc13', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'fc11223344556680000100000000199c4ef283b561a320530cac358f68c3260653ea22e7764189', + counter: 4294967296n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'fc11223344556680000100000000', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0a8e39fc6c', + plaintext: 'short', + rtpPayloads: [ + 'c0fc11223344556680000100000000199c4ef283b561a320530cac358f68c3260653ea22e7764189', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: 'c3260653ea22e7764189', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: 'ff11223344556680000123456789abcdef34198f5d48f3abd37e1c033d40c3e38175257b612ee009bb81', + counter: 81985529216486895n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'ff11223344556680000123456789abcdef', + keyId: 0x1122334455668000n, + nonce: 'd48905e2906a596c07923183', + plaintext: 'short', + rtpPayloads: [ + 'c0ff11223344556680000123456789abcdef34198f5d48f3abd37e1c033d40c3e38175257b612ee009bb81', + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '8175257b612ee009bb81', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: [ + 'f011223344556680005cce039ce1f1dadbe77ef5ec344873a65eae587c0744ffefee2ea723c5bbef49d0031ca25fee5542c57fae9b0f41e98af65b79e1f32d24', + '753effe6c7e5440981e8575659abce125901d9ab7c1dc1688f8c3f1c881c2292d7255a4820559d635044a8981af3c8a0f3186a433d64737230d9df41f44e2d67', + '299fecff', + ].join(''), + counter: 0n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f01122334455668000', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e39fc6c', + plaintext: 'keyframe', + rtpPayloads: [ + [ + 'c0f011223344556680005cce039ce1f1dadbe77ef5ec344873a65eae587c0744ffefee2ea723c5bbef49d0031ca25fee5542c57fae9b0f41e98af65b79e1f32d', + '24753effe6c7e5440981e8575659abce125901d9ab7c1dc1688f8c3f1c881c2292d7255a4820559d635044a8981af3c8a0f3186a433d64737230d9df41f44e2d', + '67299fecff', + ].join(''), + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: 'df41f44e2d67299fecff', + tagLength: 10, + }, + { + authenticationKey: '420daf93387624d29037933b00c72e0a28e9a68d981376c52b6e3c3e6e95cd6359952d5dd732d7b6bbc731bded661f07c7c7d2ed8bdeb44cbf110e6f8359ebd2', + ciphertext: [ + 'f111223344556680007b021b2c52e010ffc5c5d2b7eb164d5961dc79995642557e7fd8c1be11ffc205636317effc4bbfb5981b18c07e2ce535904a079cf24ae6', + '3dd748ce27d450f4df8d7a839071987156d81bd6220d1f4a60265c397f9168b330dfc759d8cd22500eaca124bdbd39f56b6e08c7de0d1716e1ce14995911d0b0', + 'dffa1f6512f0b866817de9b914a4ae2960825eb444b55d5033c7562df4bd064bf8b00536bfd505a9f1f169fe0b137e5ef26cf223dd8f3e3e3976f3dcda6e8324', + 'b5a584bb004b77db8d508f5061f2f34c54f59ac9fb19e06b689c6df1f8c0b34e948fcd7891ae721957fbc21386a07e715260786cc953ed4372f3de5987425327', + 'be72dc0354332be3a7b0f069606402084bc48bb1c2b81d3a3166b064eec9f66d624651cc996facf41eff54dce8d39a7a62143a3147058a016e128aee7840c0ad', + '0290dc7a8713be396a0de25aecc7ba2455e72cd17cf99fe676d74041b8e888cc1dc8bd338f093db42b75a1cda11a8c1d52aadb3319cded317abd4cc30b8ec1e8', + 'f34d486b6e7aac8bbc99e1d8eefce5f80b4ab2c682db26bc71fc255804d6dd7d8119c309e96380b1a2523c14ca77ab87d6a6c3db991e80b50a830e657856116f', + 'cc846f91155f831f5b9bb9325a7f0039bc6e2f4ed1c91214cd0af22152218a1c665c363de3c1f0aba3df2ffc9497e7df6ec4bf7305f78d9cfa1fd4c63dd481e0', + '30bb1b9d5ceefa42cc98456741bb8f53a5d7986428b3a4e6961de244063c8c98303bf8cb5b60ec0bcc76fd7fc178331d3331b0bc1075a2cecb11facf9bf8e142', + '562aa380301d6b9a0e7e1cae0350788b68088bd8946691e4bb98a0768d345eb2ade93ceec4578b7cff726d5cb1d4442fb95d2b855af294a2122b6c8f6c1fe029', + '9f0f17656777ae766df02a46c28146fa53027e0afe2fc779794e7254cd4cb10e106704f47fb5cb42d0e02b726762949920d0805932399110273be83bfbcfdc4a', + 'c67cfdec274a877c959bf476d5b90ba495471ee6dd2272ac1a123fa3c7b4b04c1edd55c18a492db05c7fe943dac8020d937be36fda446dc19d9ab6d071851f35', + '07bd8babc08fcebd22e0e3d61249eea3d96214f881df29a8f479638e1f8ac55f83c6086dfdf5474f65d8fbf8d2852dfd69f0c52114c6f53ced158d1760cc3e35', + '19e34c5e1c4ae2bd6821111f624344429a862a4071d599d8130b988436cb42018929b1479208c186eeab840fa80cdf560f45a59fa4b3f0d5babcf19ea396a4e7', + '8800d66b1e46f1ae8a2cdcb3b90a65fa501812b78a747b18beca69ced6816514404093cfe0b3b6a908b4d57bcbfda44f9d5edeb420ac6d67bb44c6ccbbeacbd5', + '758dea7ff795d126fd80363299ba57d7c2e76086e2e6f437a525441c54e941d7b0c1a5019f84ce16b269c033cf77fe701e6c59f635aad60d7936cc2c2bf84e1f', + '0733dc7dc2a23c87a6c87cce71e11d7833e22ccae9bec957e21fb5bfeed53c4d8801a299768079db0e425f1923caa83f46834e6a96a2ab3080ae6e1483a4c683', + '30afc775121151171b1cf7159b8a051e37350148bec2b20367867795de67d7b7bf67da45c62550d74acd58892767f5f6acfd9207bbb1cd3475773a2361fee551', + '5ae8cabaaa985a52d82ae45c267f569cf49360d3e6dd97134da76ec32fe4d8d9c069b47d570d66a87520da3f4436041287096c1832faf1a1b2f83c9b6965d59e', + '3087d249913a59993424a4f04ad068caec7fca82f53363496eeccb5fafa88cdac2670a788c7cfbf7e70832649b6abe09952d1d924e06ebdc45612ec4ef7ce0fd', + '877fc1c515e3ef6dc797d11282945c8eb0feee5dc08e1df5bd50fa9a5180d51912e4d4ff587437887c073f0e36e726c6e9a924051d3c3222f86f4249e6b340b2', + '837f653d2dfccc62700d757b407a991a5e993f710a985f7042c2f61135aea868a69b1880d1987756cfe51fdcaf4f156bd7f559ff756a72328fb430d7e81ab29c', + 'a247da9df6351d5cafd45ed4b4e5f27d54b0d6fff6ded2c0fcdad3d1b897779954bddeafd5632a380498603d3a4f7600d7c1a592f9fc6a4bb350dadd5a956499', + 'a33c60efae3a9ac61618e15eee3fe06b194e67642c566938ff5004cfdc4fc0029dbba89a1ea7032b5d4e33e0e4ae1f5c1d486dd95e8a9cf481b836c900717c12', + '25d16f346dfda8ae3395d11c828fce3a43be9554367513f18a6081f11257ad8dcbbecb84ee8731d1da1f35b33c6a1ff941c7b42d61a4b5ba96d918e5793aac7b', + 'f78e297e195d83fe397fd90cd35296896e7ebbae1ce89dc76356bc2afb23b68a98fefa461f9caae1779eb0316797f04b31934dab063d2c94306e94bff43fcb7f', + '058ebf51052ae224c4d2a0a18334e36e2314427f71a53e09419f139e87b0f25e4a23ba8e3e33897c9f740df46b89fe9466866b9830695447347e0bda8c7c96dc', + 'e64c754d382ebc4b883b71840dbb754a036fa76717c42fddb27b216cb7d7dc96218d6fd12bf8c8b420d18217d6c6da6efd0444cc544d7876586debeaac74b4b2', + 'b7621053dd62d36f66b7261f63476daa3210bfd835762a1135b62bd139c60980a39330842b9e595b23a7e30f1e3847b76c08a339158848ce61df9d7458fcbf34', + '6ce8351ad83c12176bfc9f4971ecc329b30f07907559f8ae94c92ec13421e8e012f49d6f3ab1113cd78eb97ba48d3405f738e8dd2e37abf1725e68428f5db50e', + 'c48d2dfeef839c35357164dcf52abfea10efa1d4115fe316ecbfce247e0240ba17f8382fcc8510de04a5da5df4b53c4ed2e70d94fdd3bb04c1f04677d1164f98', + '8c8539ba75d85ae2b0b42703bb71e7a4a9db6f882c9cdd8a6461008a6f50b71cf2cf3322ff8ebd5f476d32b6bfc85bd6539c335dcad49c0b99c8f0beec78b788', + '720bb6aa96a06446797dfcb11ea14855974fd358e581adf8654d2ca0b64214713d9ffa614c3348851569333360904b1517050f746dc2e4cbca3d4646f278d893', + '210ba3f5b335ffbe9e2a9b4ae1ba93c425bb4ac62063a628b90747e7ec06c1c001df3d0e8a2dd68cb714da9063bf01ae9ecacf162bd4204641effde671b598c7', + '309cf685fac6b67bf5ea7e34bd9054a6c5513e377184a380790c650907c7eb9a8f515eb0c1a58299200f460c6bb7b07934d6db29856ea3b813d3522fea530716', + 'dd467b15a5f84e87240cc7905f0b68802ec27e9a887402bdfaf365fd50e18ae58370558b6c2ca5fb6f886626dd6903b768b7c0d5e3991e44ec9bb8831116057c', + '0d3382cae57e60a4446c7325e0f4f7af7a20b25a45f1389ea489a65816375ae9e79480e96c78aa43f0a6f678469df5e4c4d924ba88068fe2f608cc28c9827633', + '1bd0b526bb7e7855fb7923aaec8789d270e12677e823858fbbe0b14fad91540acb3a33560faef1a8c701c86ffe6e5a9f0f5faa3dcd56a61bb271eae4fffdf9ac', + 'e8861e1869b3125357324a3f2368e1f131e636a7e1538748020217b0c8acea3024e1a4966326ebd8858224cf24f1f767c8b9654f160b24d16bc6d13c3f281aeb', + '30a73a340bc260c1475d6541bb94b9e1bce80004ab91b31602a91f1822cefa794a41698088a7ab9e3253c0f6658c532c71f8aeda5d0c19ab21e3028a14d5d876', + '9a7599f2c609d19946873801e059cc1eb422979b2bf234ad5b9386acca2595da47886a069e08859e2e9000b7512c2a41361dc5418f005b85bccb9a595eeffa8b', + '5c9f2f4eaa8b8275058c564b6e50d3a09a88c3b0dc2ab1c5d8b8278fb2d1895bd37cd86bcf3c8398b2281e6b4e4fa67f39b63f888d87b81480f6755d2ba449da', + '97dca7bd0e135e887810f64f70cc38d594cdd05e1be76ddde8cb745b3c4b9a27ee4c093557', + ].join(''), + counter: 1n, + encryptionKey: 'ff81b465ff04e166c17a02b122d4204bc259eee0d13f0378cd805df6f59e1781', + header: 'f11122334455668000', + keyId: 0x1122334455668000n, + nonce: 'd48905e291491c0b8e39fc6d', + plaintext: 'long', + rtpPayloads: [ + [ + '80f111223344556680007b021b2c52e010ffc5c5d2b7eb164d5961dc79995642557e7fd8c1be11ffc205636317effc4bbfb5981b18c07e2ce535904a079cf24a', + 'e63dd748ce27d450f4df8d7a839071987156d81bd6220d1f4a60265c397f9168b330dfc759d8cd22500eaca124bdbd39f56b6e08c7de0d1716e1ce14995911d0', + 'b0dffa1f6512f0b866817de9b914a4ae2960825eb444b55d5033c7562df4bd064bf8b00536bfd505a9f1f169fe0b137e5ef26cf223dd8f3e3e3976f3dcda6e83', + '24b5a584bb004b77db8d508f5061f2f34c54f59ac9fb19e06b689c6df1f8c0b34e948fcd7891ae721957fbc21386a07e715260786cc953ed4372f3de59874253', + '27be72dc0354332be3a7b0f069606402084bc48bb1c2b81d3a3166b064eec9f66d624651cc996facf41eff54dce8d39a7a62143a3147058a016e128aee7840c0', + 'ad0290dc7a8713be396a0de25aecc7ba2455e72cd17cf99fe676d74041b8e888cc1dc8bd338f093db42b75a1cda11a8c1d52aadb3319cded317abd4cc30b8ec1', + 'e8f34d486b6e7aac8bbc99e1d8eefce5f80b4ab2c682db26bc71fc255804d6dd7d8119c309e96380b1a2523c14ca77ab87d6a6c3db991e80b50a830e65785611', + '6fcc846f91155f831f5b9bb9325a7f0039bc6e2f4ed1c91214cd0af22152218a1c665c363de3c1f0aba3df2ffc9497e7df6ec4bf7305f78d9cfa1fd4c63dd481', + 'e030bb1b9d5ceefa42cc98456741bb8f53a5d7986428b3a4e6961de244063c8c98303bf8cb5b60ec0bcc76fd7fc178331d3331b0bc1075a2cecb11facf9bf8e1', + '42562aa380301d6b9a0e7e1cae0350788b68088bd8946691e4bb98a0768d345eb2ade93ceec4578b7cff726d5cb1d4442fb95d2b855af294a2122b6c8f6c1fe0', + '299f0f17656777ae766df02a46c28146fa53027e0afe2fc779794e7254cd4cb10e106704f47fb5cb42d0e02b726762949920d0805932399110273be83bfbcfdc', + '4ac67cfdec274a877c959bf476d5b90ba495471ee6dd2272ac1a123fa3c7b4b04c1edd55c18a492db05c7fe943dac8020d937be36fda446dc19d9ab6d071851f', + '3507bd8babc08fcebd22e0e3d61249eea3d96214f881df29a8f479638e1f8ac55f83c6086dfdf5474f65d8fbf8d2852dfd69f0c52114c6f53ced158d1760cc3e', + '3519e34c5e1c4ae2bd6821111f624344429a862a4071d599d8130b988436cb42018929b1479208c186eeab840fa80cdf560f45a59fa4b3f0d5babcf19ea396a4', + 'e78800d66b1e46f1ae8a2cdcb3b90a65fa501812b78a747b18beca69ced6816514404093cfe0b3b6a908b4d57bcbfda44f9d5edeb420ac6d67bb44c6ccbbeacb', + 'd5758dea7ff795d126fd80363299ba57d7c2e76086e2e6f437a525441c54e941d7b0c1a5019f84ce16b269c033cf77fe701e6c59f635aad60d7936cc2c2bf84e', + '1f0733dc7dc2a23c87a6c87cce71e11d7833e22ccae9bec957e21fb5bfeed53c4d8801a299768079db0e425f1923caa83f46834e6a96a2ab3080ae6e1483a4c6', + '8330afc775121151171b1cf7', + ].join(''), + [ + '00159b8a051e37350148bec2b20367867795de67d7b7bf67da45c62550d74acd58892767f5f6acfd9207bbb1cd3475773a2361fee5515ae8cabaaa985a52d82a', + 'e45c267f569cf49360d3e6dd97134da76ec32fe4d8d9c069b47d570d66a87520da3f4436041287096c1832faf1a1b2f83c9b6965d59e3087d249913a59993424', + 'a4f04ad068caec7fca82f53363496eeccb5fafa88cdac2670a788c7cfbf7e70832649b6abe09952d1d924e06ebdc45612ec4ef7ce0fd877fc1c515e3ef6dc797', + 'd11282945c8eb0feee5dc08e1df5bd50fa9a5180d51912e4d4ff587437887c073f0e36e726c6e9a924051d3c3222f86f4249e6b340b2837f653d2dfccc62700d', + '757b407a991a5e993f710a985f7042c2f61135aea868a69b1880d1987756cfe51fdcaf4f156bd7f559ff756a72328fb430d7e81ab29ca247da9df6351d5cafd4', + '5ed4b4e5f27d54b0d6fff6ded2c0fcdad3d1b897779954bddeafd5632a380498603d3a4f7600d7c1a592f9fc6a4bb350dadd5a956499a33c60efae3a9ac61618', + 'e15eee3fe06b194e67642c566938ff5004cfdc4fc0029dbba89a1ea7032b5d4e33e0e4ae1f5c1d486dd95e8a9cf481b836c900717c1225d16f346dfda8ae3395', + 'd11c828fce3a43be9554367513f18a6081f11257ad8dcbbecb84ee8731d1da1f35b33c6a1ff941c7b42d61a4b5ba96d918e5793aac7bf78e297e195d83fe397f', + 'd90cd35296896e7ebbae1ce89dc76356bc2afb23b68a98fefa461f9caae1779eb0316797f04b31934dab063d2c94306e94bff43fcb7f058ebf51052ae224c4d2', + 'a0a18334e36e2314427f71a53e09419f139e87b0f25e4a23ba8e3e33897c9f740df46b89fe9466866b9830695447347e0bda8c7c96dce64c754d382ebc4b883b', + '71840dbb754a036fa76717c42fddb27b216cb7d7dc96218d6fd12bf8c8b420d18217d6c6da6efd0444cc544d7876586debeaac74b4b2b7621053dd62d36f66b7', + '261f63476daa3210bfd835762a1135b62bd139c60980a39330842b9e595b23a7e30f1e3847b76c08a339158848ce61df9d7458fcbf346ce8351ad83c12176bfc', + '9f4971ecc329b30f07907559f8ae94c92ec13421e8e012f49d6f3ab1113cd78eb97ba48d3405f738e8dd2e37abf1725e68428f5db50ec48d2dfeef839c353571', + '64dcf52abfea10efa1d4115fe316ecbfce247e0240ba17f8382fcc8510de04a5da5df4b53c4ed2e70d94fdd3bb04c1f04677d1164f988c8539ba75d85ae2b0b4', + '2703bb71e7a4a9db6f882c9cdd8a6461008a6f50b71cf2cf3322ff8ebd5f476d32b6bfc85bd6539c335dcad49c0b99c8f0beec78b788720bb6aa96a06446797d', + 'fcb11ea14855974fd358e581adf8654d2ca0b64214713d9ffa614c3348851569333360904b1517050f746dc2e4cbca3d4646f278d893210ba3f5b335ffbe9e2a', + '9b4ae1ba93c425bb4ac62063a628b90747e7ec06c1c001df3d0e8a2dd68cb714da9063bf01ae9ecacf162bd4204641effde671b598c7309cf685fac6b67bf5ea', + '7e34bd9054a6c5513e377184', + ].join(''), + [ + '40a380790c650907c7eb9a8f515eb0c1a58299200f460c6bb7b07934d6db29856ea3b813d3522fea530716dd467b15a5f84e87240cc7905f0b68802ec27e9a88', + '7402bdfaf365fd50e18ae58370558b6c2ca5fb6f886626dd6903b768b7c0d5e3991e44ec9bb8831116057c0d3382cae57e60a4446c7325e0f4f7af7a20b25a45', + 'f1389ea489a65816375ae9e79480e96c78aa43f0a6f678469df5e4c4d924ba88068fe2f608cc28c98276331bd0b526bb7e7855fb7923aaec8789d270e12677e8', + '23858fbbe0b14fad91540acb3a33560faef1a8c701c86ffe6e5a9f0f5faa3dcd56a61bb271eae4fffdf9ace8861e1869b3125357324a3f2368e1f131e636a7e1', + '538748020217b0c8acea3024e1a4966326ebd8858224cf24f1f767c8b9654f160b24d16bc6d13c3f281aeb30a73a340bc260c1475d6541bb94b9e1bce80004ab', + '91b31602a91f1822cefa794a41698088a7ab9e3253c0f6658c532c71f8aeda5d0c19ab21e3028a14d5d8769a7599f2c609d19946873801e059cc1eb422979b2b', + 'f234ad5b9386acca2595da47886a069e08859e2e9000b7512c2a41361dc5418f005b85bccb9a595eeffa8b5c9f2f4eaa8b8275058c564b6e50d3a09a88c3b0dc', + '2ab1c5d8b8278fb2d1895bd37cd86bcf3c8398b2281e6b4e4fa67f39b63f888d87b81480f6755d2ba449da97dca7bd0e135e887810f64f70cc38d594cdd05e1b', + 'e76ddde8cb745b3c4b9a27ee4c093557', + ].join(''), + ], + salt: 'd48905e291491c0b8e39fc6c', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '5b3c4b9a27ee4c093557', + tagLength: 10, + }, + { + authenticationKey: '769368de436b483e654d52d3bb33e610d7b8fae1bef7dddbf7a96e98f10423e93cb0a2ed11cd8ef023320c8c8d6834e3aecbaeaa64f8d4a301daf9a8302a3b2d', + ciphertext: [ + 'f0112233445566800039cd936ed9b09767192a6645545b229017d1ed4d037ee67cc31bff44dd0cfa26619d3494471c40c70f2e9bd890eccdbf78f95754c2e390', + 'ec639eac1487cc95ccd708630e081dc94d7d6ee40c6a6012417a9cbf32e4ad7564e6464a3cdb8003019e52332fd44105667e3141f9e610a777b4bebab33624ea', + '72a94382', + ].join(''), + counter: 0n, + encryptionKey: '20e533d0743cb23c86cb952223286e382c4882f0e20e8caa317e156dead18441', + header: 'f01122334455668000', + keyId: 0x1122334455668000n, + nonce: 'f622fcfd892b5616e2e53d04', + plaintext: 'keyframe', + rtpPayloads: [ + [ + 'c0f0112233445566800039cd936ed9b09767192a6645545b229017d1ed4d037ee67cc31bff44dd0cfa26619d3494471c40c70f2e9bd890eccdbf78f95754c2e3', + '90ec639eac1487cc95ccd708630e081dc94d7d6ee40c6a6012417a9cbf32e4ad7564e6464a3cdb8003019e52332fd44105667e3141f9e610a777b4bebab33624', + 'ea72a94382', + ].join(''), + ], + salt: 'f622fcfd892b5616e2e53d04', + ssrc: 0x1A2B3C4E, + streamSecret: 'ba2d61a6fc4ceeb72ec407a9934da3d9832e15fe889429a3f6901e647b93de207fc4bb115f9d595a47c0d2bf91a29cd872d82a6a94162a580980782b1509639c', + suite: 6, + tag: 'bebab33624ea72a94382', + tagLength: 10, + }, + { + authenticationKey: '769368de436b483e654d52d3bb33e610d7b8fae1bef7dddbf7a96e98f10423e93cb0a2ed11cd8ef023320c8c8d6834e3aecbaeaa64f8d4a301daf9a8302a3b2d', + ciphertext: [ + 'f11122334455668000b06b9da259c3901cbccdb6cb378b8c62d569d970421471c9679fc0549578c401e1c8cdc43119870c7b4e4d9b4e0bbec61c94c75b871605', + 'ba887e3f8dfb00d2f9eecda3c45ddfb79e7abbe1ebba3c1651acfeceb3d62ff7d6fabc46ec6ba4965d480b8efa1d4e23c834cfcf5bbcf918f44eb2d90a531801', + '03120ef3870a10cf6b176e05fc1d29ce0bd846b3c27b6c611bbf7c70716e922abae71748ccc7e680dfcf4b93a4c50b005e2609108d06ab63112b2e3a242a8bc1', + '1ad80dd168de702383ca0e530b0428867169605f24853b90aafc96d615bad5269b405772cf9127bcb9c70d8ea5bd4d6b2065121bc025c331ee553819e6cc34a7', + '784cee6c7627faaa439ec86fe67e4ed410fff057588c0539f1e4c7390f7db5dff905534afdefe623add5700a2283f0845f914a863169b724a4323ed3a008bc67', + 'ab2c523b082c7c90e4d1ed090aa4e6b69b6d0a6313974b0a9d708c2c96046bd1acef9764a65e331869256957f72dfc3949b2afa52e25d9f2beecd32a04d53c1b', + 'f2be38d369d1a40d97fcc43032c58e2115463bfbda93f97b5936122a3ae71fa3d891db4000a79c87755b0877edd5f421189f480e9e10f0c5d18c3174f03c2efd', + '5b7bb1073be9080903ab0e6589b985f583c9cb914a331a4d78cdb6b8473c5b71d6da6cfd9e59e89c92d98ee81f8d9ebd14adb4d2d403cc2a4c8e500e4ba902f0', + '684dca663b65f531fab11e0b296a7fa727a6016c0f93eef05f1b821fee3366db2b282a80f6cb7f135c2b2ef0ce047a672c57aa6e42569326d5e7bbb0cda16e04', + 'fafac443c2e5fdabce6136a6fd970fea3db71824c68a37ac7c79c8ebf0ccfd53fcec057bf172f6a3e907a83810c43cb9cbb3f0e9d166d3b5a32b9f622349f26a', + '7c3eafca644af79b6c1aa63e68add8a398d1ad952e8beec3c67cc824278fd3a299bdae4c6f1cdf4e5eae1648e7d74468a470f8ef7ccecf7d70712411014a7430', + 'a1ba46556d352323b86d1597c30ec6e201d4504248d42c8f376f47dc0f74e10682814922b9abd38922feee2c376b2f32da1d1b9e1918e7e5243974ca67dd2bfb', + '7bd915192c26ca112c0cf3c0f4a43cce187f8536b857332deb17dc172670aca7a453c4e698fa007d9500afc3ecb87fbffedf94138f0fc7f0f4094e6903b44650', + 'fd671d6e764f887d75cb66c1f4f4f0381abd678e02f125ea28310bf40873a55a6efefea20cb36513d49e625b085a570fd9fd4bb869d6cf60444f4a0715adaf17', + 'e7f72ec27c3061b6751e2fb7b77b887bf7f360655ec35fc0e402555c0e118429d6776c5223ca86c08ca5d2e941537ae882e294b02ddabb23c4e47af756104d9a', + 'bd7b509404166b4c04543b25332fb2fb525ec4116a8579062e0f2a678c3626619ea13aee60451580049508bbd2bec4322cf654c18092f206959f9ba2ec7569ea', + 'fc50ddd08b529ac606e18d91b7d1c309be6fd741f53b5d1860f0e138681045d297fc793db28675dfafd49577a7df3142848f71dc6d1061fdca1ead838d171120', + '4697b2b0dcf6cafde141b11c882bddac2ed6a9b877054001f319e1291d93ef2ceca1b7085e79d34065c77da12f5c9162846de222a748104ecc4329d604750676', + 'b71827664a35a2d49e6662147493f9909b5b225ae06e4a78a62476292ebfc44df737515350062a5a29c26e7e0e00e9bdcb09d58a1e5afc81bc5cb06c9da80621', + 'b651049583c3bae209e2dedfdf813259950cfe108294f2c0941bd6c84d20cd56fcb333f705c560366f5873e1e01c1a1b6245ce01a8d0f732d95c90cef5e6dac8', + '64bb725424075a0de50d0221f6c16e842cf4205d7d7f1e894597a1751e839ff7ae1765a8eabefa1cf646cfee470e44d21500fc9721a39f4151465f9355ea203c', + '33076d825e4f3f9f3839121ffc28fdef6f96a426e2bc27b81d7da6b60c5071f5674490c4bfa9fbe41436d1844906f2c1475ea338887263b10d36132a2f194c29', + '6424d7b5c973f9c415f66cf842259dce40b9eae5d61486e852e25e2ecc5574f4a03ad8c5fbcb1123d0692202288703449865849f474bd5ab468fd94893310c3c', + '128d5cbb1b03925e84ec8a29668267f7e40e2e7e20cb4e4d01501bd84f4a900bd4d6147eb4f63794b9b8dc812c95d4cb64317984254f5af6a7c45314f2dafac5', + 'e8f3a67042bcf54a486c9372b6f524af4905324f4cabf41dd6d8c47fa7c81e7367bbd5af43844d23fd429a969510c2fd4776d8a888aa42c3519e609a7377d609', + '5ecde710733c6a264defafff9f6f91526d57b4d7ad4022ac8bbbfa88e3a28af37b2305bf057d37f08e25f1959268a3b4c7919daa40f913d9ff3c87bba9b8a54e', + '8c1b8be255a3d6d7b744ac44713414ad848d3b67694a6da2408c05dd620540891542277d66af69854d6800d23f524d1436d21c7f42f12e5aa3c55bdeef39e719', + '491dd1c216128f3fec90598fa0c364765746a6a4caeb481e30c2423f3ce41b6699ebe0776cdc1a50279da6da073d72c0d41ac42ba7742847dd812072dbcb691f', + 'a13b62db3aa5bea4886d60ecc1331e2b506cd0e04e32897f4b8138e9bc05b9fcd73d82abf4fcb147a715e7ca19447fd35526a528ff3451ec56c0527f3d226137', + 'ba5c69316dc6da5155e54fb375d420cc78bd5114df8fd9a49f81198889c7cd15f35c7acd12e29ab2fae086792ae821bf6453a366744ebd7c80f4d621e33c24b2', + '8fc3b49b5082560ab95476517da36a92ee793a2e48793d1f8a7048c1add040c0e2430ceb18d5876d0417171738e54690da5b61520ad16bb3e0921c082c0dba51', + 'ef5d7e1be231adf56824a9c30d027d4d2fb62cefcdd256973cc1849e9c0fe202c9e2b1cf2f1fe650620cd980529f849b6378852e79e2362720f089d4f11084ea', + 'fb6b8dcae32f7c8e5a5688250142beedd4b1ab298533df3137651f441b31b82b5c9ee225d6c67da24d08748d58d2d6e29c49130deb6bb6eac80e307bfd629b95', + '25fe1060646bd39794768bffe2877e94ee080c1fa0d144cffff72c7180cbfd2657af98836ca7d101cf30efc52e4779366821ae8c4b9b2fdd6a4db4756b7c23c0', + 'be303ce97bdfb22e5a4b2d6e5931ff9ec7dd620be31c794f5e6a844f69c8476da33582a1e6ea9f4e17c78fd92b3a21adf6e3e76a0650c35c4f5b978293dbec6f', + '2b2dbcd506f84b78670c45dcc5e58364f0f74e49e86570573a025c80f5d298a043764e82d2ac9f69b42d5aa2b145463966daee1db5184abe9862b9cabadced9b', + '70ad4be0c0fd58bbf39fc67772a90147b34830c7478b9ad642746430da65e8d5970b0397603311c24e742bb8979c17d3a0b5ae746b47b7ae04a1f8d85aa7a1a8', + 'd91b47b7cea6ff336ade708473f95562666fd135e9159efcd130f43b6ea565afbbaa7f09784f423f0f4fb77084c837268cd52e923a1a6c38fac1fb92946e2f7a', + 'b62e83aa3f0400f88698d3c5054d82701f1c1a7afddb3ff9d629ec8efc570c5066f183d7709119faf93f71885ad346b963eb9452ed9254450791d968f8c541be', + 'bc06b32b3b801206e2909493a749d6135e020f586461fbd08584c57c0cec8ea3ed5cbf0cd068860b92ccabf53a947960cbd7ee4d49501976d482fdc5e7889bcd', + '5365505debf7434dcad63e869045d7dfc04cd3218bb456837ca109a7941795566398e52c83c92c30b1bb705265322cf3918ee4b67f96284e6e4c8bb3fe23488c', + '5d411ab320636b05e6c6f032509bf2010146f91eb3d35f778b7ad4ead7e5fb34e0c9489e6dbde02510b4d3415a69842b822f94f17aaf3d0a8fa5e2e63a06bee3', + '72aa14d5020b0a130ba10aa87b89334e5c9415c60619f31298d1a3ef0873074216d814e480', + ].join(''), + counter: 1n, + encryptionKey: '20e533d0743cb23c86cb952223286e382c4882f0e20e8caa317e156dead18441', + header: 'f11122334455668000', + keyId: 0x1122334455668000n, + nonce: 'f622fcfd892b5616e2e53d05', + plaintext: 'long', + rtpPayloads: [ + [ + '80f11122334455668000b06b9da259c3901cbccdb6cb378b8c62d569d970421471c9679fc0549578c401e1c8cdc43119870c7b4e4d9b4e0bbec61c94c75b8716', + '05ba887e3f8dfb00d2f9eecda3c45ddfb79e7abbe1ebba3c1651acfeceb3d62ff7d6fabc46ec6ba4965d480b8efa1d4e23c834cfcf5bbcf918f44eb2d90a5318', + '0103120ef3870a10cf6b176e05fc1d29ce0bd846b3c27b6c611bbf7c70716e922abae71748ccc7e680dfcf4b93a4c50b005e2609108d06ab63112b2e3a242a8b', + 'c11ad80dd168de702383ca0e530b0428867169605f24853b90aafc96d615bad5269b405772cf9127bcb9c70d8ea5bd4d6b2065121bc025c331ee553819e6cc34', + 'a7784cee6c7627faaa439ec86fe67e4ed410fff057588c0539f1e4c7390f7db5dff905534afdefe623add5700a2283f0845f914a863169b724a4323ed3a008bc', + '67ab2c523b082c7c90e4d1ed090aa4e6b69b6d0a6313974b0a9d708c2c96046bd1acef9764a65e331869256957f72dfc3949b2afa52e25d9f2beecd32a04d53c', + '1bf2be38d369d1a40d97fcc43032c58e2115463bfbda93f97b5936122a3ae71fa3d891db4000a79c87755b0877edd5f421189f480e9e10f0c5d18c3174f03c2e', + 'fd5b7bb1073be9080903ab0e6589b985f583c9cb914a331a4d78cdb6b8473c5b71d6da6cfd9e59e89c92d98ee81f8d9ebd14adb4d2d403cc2a4c8e500e4ba902', + 'f0684dca663b65f531fab11e0b296a7fa727a6016c0f93eef05f1b821fee3366db2b282a80f6cb7f135c2b2ef0ce047a672c57aa6e42569326d5e7bbb0cda16e', + '04fafac443c2e5fdabce6136a6fd970fea3db71824c68a37ac7c79c8ebf0ccfd53fcec057bf172f6a3e907a83810c43cb9cbb3f0e9d166d3b5a32b9f622349f2', + '6a7c3eafca644af79b6c1aa63e68add8a398d1ad952e8beec3c67cc824278fd3a299bdae4c6f1cdf4e5eae1648e7d74468a470f8ef7ccecf7d70712411014a74', + '30a1ba46556d352323b86d1597c30ec6e201d4504248d42c8f376f47dc0f74e10682814922b9abd38922feee2c376b2f32da1d1b9e1918e7e5243974ca67dd2b', + 'fb7bd915192c26ca112c0cf3c0f4a43cce187f8536b857332deb17dc172670aca7a453c4e698fa007d9500afc3ecb87fbffedf94138f0fc7f0f4094e6903b446', + '50fd671d6e764f887d75cb66c1f4f4f0381abd678e02f125ea28310bf40873a55a6efefea20cb36513d49e625b085a570fd9fd4bb869d6cf60444f4a0715adaf', + '17e7f72ec27c3061b6751e2fb7b77b887bf7f360655ec35fc0e402555c0e118429d6776c5223ca86c08ca5d2e941537ae882e294b02ddabb23c4e47af756104d', + '9abd7b509404166b4c04543b25332fb2fb525ec4116a8579062e0f2a678c3626619ea13aee60451580049508bbd2bec4322cf654c18092f206959f9ba2ec7569', + 'eafc50ddd08b529ac606e18d91b7d1c309be6fd741f53b5d1860f0e138681045d297fc793db28675dfafd49577a7df3142848f71dc6d1061fdca1ead838d1711', + '204697b2b0dcf6cafde141b1', + ].join(''), + [ + '001c882bddac2ed6a9b877054001f319e1291d93ef2ceca1b7085e79d34065c77da12f5c9162846de222a748104ecc4329d604750676b71827664a35a2d49e66', + '62147493f9909b5b225ae06e4a78a62476292ebfc44df737515350062a5a29c26e7e0e00e9bdcb09d58a1e5afc81bc5cb06c9da80621b651049583c3bae209e2', + 'dedfdf813259950cfe108294f2c0941bd6c84d20cd56fcb333f705c560366f5873e1e01c1a1b6245ce01a8d0f732d95c90cef5e6dac864bb725424075a0de50d', + '0221f6c16e842cf4205d7d7f1e894597a1751e839ff7ae1765a8eabefa1cf646cfee470e44d21500fc9721a39f4151465f9355ea203c33076d825e4f3f9f3839', + '121ffc28fdef6f96a426e2bc27b81d7da6b60c5071f5674490c4bfa9fbe41436d1844906f2c1475ea338887263b10d36132a2f194c296424d7b5c973f9c415f6', + '6cf842259dce40b9eae5d61486e852e25e2ecc5574f4a03ad8c5fbcb1123d0692202288703449865849f474bd5ab468fd94893310c3c128d5cbb1b03925e84ec', + '8a29668267f7e40e2e7e20cb4e4d01501bd84f4a900bd4d6147eb4f63794b9b8dc812c95d4cb64317984254f5af6a7c45314f2dafac5e8f3a67042bcf54a486c', + '9372b6f524af4905324f4cabf41dd6d8c47fa7c81e7367bbd5af43844d23fd429a969510c2fd4776d8a888aa42c3519e609a7377d6095ecde710733c6a264def', + 'afff9f6f91526d57b4d7ad4022ac8bbbfa88e3a28af37b2305bf057d37f08e25f1959268a3b4c7919daa40f913d9ff3c87bba9b8a54e8c1b8be255a3d6d7b744', + 'ac44713414ad848d3b67694a6da2408c05dd620540891542277d66af69854d6800d23f524d1436d21c7f42f12e5aa3c55bdeef39e719491dd1c216128f3fec90', + '598fa0c364765746a6a4caeb481e30c2423f3ce41b6699ebe0776cdc1a50279da6da073d72c0d41ac42ba7742847dd812072dbcb691fa13b62db3aa5bea4886d', + '60ecc1331e2b506cd0e04e32897f4b8138e9bc05b9fcd73d82abf4fcb147a715e7ca19447fd35526a528ff3451ec56c0527f3d226137ba5c69316dc6da5155e5', + '4fb375d420cc78bd5114df8fd9a49f81198889c7cd15f35c7acd12e29ab2fae086792ae821bf6453a366744ebd7c80f4d621e33c24b28fc3b49b5082560ab954', + '76517da36a92ee793a2e48793d1f8a7048c1add040c0e2430ceb18d5876d0417171738e54690da5b61520ad16bb3e0921c082c0dba51ef5d7e1be231adf56824', + 'a9c30d027d4d2fb62cefcdd256973cc1849e9c0fe202c9e2b1cf2f1fe650620cd980529f849b6378852e79e2362720f089d4f11084eafb6b8dcae32f7c8e5a56', + '88250142beedd4b1ab298533df3137651f441b31b82b5c9ee225d6c67da24d08748d58d2d6e29c49130deb6bb6eac80e307bfd629b9525fe1060646bd3979476', + '8bffe2877e94ee080c1fa0d144cffff72c7180cbfd2657af98836ca7d101cf30efc52e4779366821ae8c4b9b2fdd6a4db4756b7c23c0be303ce97bdfb22e5a4b', + '2d6e5931ff9ec7dd620be31c', + ].join(''), + [ + '40794f5e6a844f69c8476da33582a1e6ea9f4e17c78fd92b3a21adf6e3e76a0650c35c4f5b978293dbec6f2b2dbcd506f84b78670c45dcc5e58364f0f74e49e8', + '6570573a025c80f5d298a043764e82d2ac9f69b42d5aa2b145463966daee1db5184abe9862b9cabadced9b70ad4be0c0fd58bbf39fc67772a90147b34830c747', + '8b9ad642746430da65e8d5970b0397603311c24e742bb8979c17d3a0b5ae746b47b7ae04a1f8d85aa7a1a8d91b47b7cea6ff336ade708473f95562666fd135e9', + '159efcd130f43b6ea565afbbaa7f09784f423f0f4fb77084c837268cd52e923a1a6c38fac1fb92946e2f7ab62e83aa3f0400f88698d3c5054d82701f1c1a7afd', + 'db3ff9d629ec8efc570c5066f183d7709119faf93f71885ad346b963eb9452ed9254450791d968f8c541bebc06b32b3b801206e2909493a749d6135e020f5864', + '61fbd08584c57c0cec8ea3ed5cbf0cd068860b92ccabf53a947960cbd7ee4d49501976d482fdc5e7889bcd5365505debf7434dcad63e869045d7dfc04cd3218b', + 'b456837ca109a7941795566398e52c83c92c30b1bb705265322cf3918ee4b67f96284e6e4c8bb3fe23488c5d411ab320636b05e6c6f032509bf2010146f91eb3', + 'd35f778b7ad4ead7e5fb34e0c9489e6dbde02510b4d3415a69842b822f94f17aaf3d0a8fa5e2e63a06bee372aa14d5020b0a130ba10aa87b89334e5c9415c606', + '19f31298d1a3ef0873074216d814e480', + ].join(''), + ], + salt: 'f622fcfd892b5616e2e53d04', + ssrc: 0x1A2B3C4E, + streamSecret: 'ba2d61a6fc4ceeb72ec407a9934da3d9832e15fe889429a3f6901e647b93de207fc4bb115f9d595a47c0d2bf91a29cd872d82a6a94162a580980782b1509639c', + suite: 6, + tag: 'ef0873074216d814e480', + tagLength: 10, + }, + { + authenticationKey: 'e96d9bbabc434ce071aac8b5c6357eaee4413f759cdf50635782928dd71e363c66ca5398271237595e7a59da46052f4680ee622a3952505c28bebc598142631d', + ciphertext: 'f2fedcba98765480007c5eb25ea2414c0f9b8b01893ca7ca27bffa15c5b7a6ba7d91', + counter: 2n, + encryptionKey: '039860210309eac397fdd6c583a783c9dd7282b4bd7c2458688552defccf4690', + header: 'f2fedcba9876548000', + keyId: 0xFEDCBA9876548000n, + nonce: '0a8f2f9fdba71f53d5ad84d3', + plaintext: 'short', + rtpPayloads: [ + 'c0f2fedcba98765480007c5eb25ea2414c0f9b8b01893ca7ca27bffa15c5b7a6ba7d91', + ], + salt: '0a8f2f9fdba71f53d5ad84d1', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: '27bffa15c5b7a6ba7d91', + tagLength: 10, + }, + { + authenticationKey: 'ea47555259329883ec91661ee0ca66d016c775a0a6284f7df851b47e17cf72cec799f13f821ff2725a82af9900b162ef95e3170218147b05055a99d1be290627', + ciphertext: '52a087627221e4338acadf8c8272eae4ec2fcd3792175885a4af', + counter: 2n, + encryptionKey: '598e6f651d91105c50095395606b001e61020efc20ed3262f72963f1efa17770', + header: '52', + keyId: 5n, + nonce: '7bae7d3165981a039289e4e7', + plaintext: 'short', + rtpPayloads: [ + 'c052a087627221e4338acadf8c8272eae4ec2fcd3792175885a4af', + ], + salt: '7bae7d3165981a039289e4e5', + ssrc: 0x1A2B3C4D, + streamSecret: 'd0483abc7c8457c22a93e5aba8546bc8d3fd9e28f1d1ad5bc41966c8d2a1db9b09337ecc1552a1fd993fdc835b58285b752698bc12f45cfd4d5a4da6948a9ee6', + suite: 6, + tag: 'ec2fcd3792175885a4af', + tagLength: 10, + }, + { + authenticationKey: 'f5b69be42da9298591697441f7249b49665734d865e0ea505424b098de6782df31ab384c955b1330f31958d56697f5b249f485e3725d577c1602ae93ff964161', + ciphertext: 'f01122334455668000c24ce150d521527926cff9464c04c3228dce98', + counter: 0n, + encryptionKey: 'a22910debcdbd953e62effbf4b1d6ee6eba0c8bf5b9a3d7bbf001d20587f29c9', + header: 'f01122334455668000', + keyId: 0x1122334455668000n, + nonce: '7f445c79413c74233db0a270', + plaintext: 'short', + rtpPayloads: [ + 'c0f01122334455668000c24ce150d521527926cff9464c04c3228dce98', + ], + salt: '7f445c79413c74233db0a270', + ssrc: 0x0BADCAFE, + streamSecret: '1a01c8bf2d4e5ce17b216416f4357deaa4d21608655b5f9f4f8a5e9b9eed3656bfc92a8a49ff57c5f8beb5eefcd502bd1137e2041dd97e1569cdc71cd37b4472', + suite: 8, + tag: '228dce98', + tagLength: 4, + }, + { + authenticationKey: 'f5b69be42da9298591697441f7249b49665734d865e0ea505424b098de6782df31ab384c955b1330f31958d56697f5b249f485e3725d577c1602ae93ff964161', + ciphertext: 'f91122334455668000012c8182de3526adab65dfc5cadc0143fc747c9ee7', + counter: 300n, + encryptionKey: 'a22910debcdbd953e62effbf4b1d6ee6eba0c8bf5b9a3d7bbf001d20587f29c9', + header: 'f91122334455668000012c', + keyId: 0x1122334455668000n, + nonce: '7f445c79413c74233db0a35c', + plaintext: 'short', + rtpPayloads: [ + 'c0f91122334455668000012c8182de3526adab65dfc5cadc0143fc747c9ee7', + ], + salt: '7f445c79413c74233db0a270', + ssrc: 0x0BADCAFE, + streamSecret: '1a01c8bf2d4e5ce17b216416f4357deaa4d21608655b5f9f4f8a5e9b9eed3656bfc92a8a49ff57c5f8beb5eefcd502bd1137e2041dd97e1569cdc71cd37b4472', + suite: 8, + tag: '747c9ee7', + tagLength: 4, + }, + ], +} + +// The opener's derivations, written apart from the engine's: each HKDF-SHA-512 whole, the stream's secret under the stream label with its SSRC as the salt, +// and its keys and salt under labels that end in a space, followed by the key ID in eight octets and the suite in two. +const STREAM_LABEL = 'SFrame 1.0 RTP Stream' +const KEY_LABEL = 'SFrame 1.0 Secret key ' +const SALT_LABEL = 'SFrame 1.0 Secret salt ' + +// A header value's octets read big-endian, from the octet after the config byte or the key ID. +function readValue(data: Buffer, offset: number, length: number): bigint { + let value = 0n + + for (let index = 0; index < length; index++) { + value = (value << 8n) | BigInt(data[offset + index]) + } + + return value +} + +/** + * Opens one SFrame ciphertext of a stream as the construction's octet formulas give it, with node:crypto alone and nothing of the engine's sealing: the + * header read as RFC 9605 writes it, the stream's secret from the session key and the SSRC, the keys and salt from the header's key ID and the suite, the + * nonce from the salt and the header's counter, and the tag over the three lengths, the nonce, the header and the encrypted frame, with no metadata. + * @param options - The ciphertext, the session key and the stream's SSRC, its suite's identifier and its tag length. + * @param options.ciphertext - The ciphertext, its header first and its tag last. + * @param options.sessionKey - The session key every stream's secret comes from. + * @param options.ssrc - The SSRC the stream was set up with. + * @param options.suite - The suite's identifier, which the key and salt derivations carry. + * @param options.tagLength - The suite's tag length in octets. + * @returns The plaintext, or `undefined` for a ciphertext whose tag does not hold, a changed header, encrypted frame or tag among them. + */ +export function openSFrameReference(options: { ciphertext: Buffer, sessionKey: Buffer, ssrc: number, suite: number, tagLength: number }): Buffer | undefined { + const { ciphertext, sessionKey, ssrc, suite, tagLength } = options + const config = ciphertext[0] + const keyLength = (config & 0x80) + ? ((config >> 4) & 0x07) + 1 + : 0 + const counterLength = (config & 0x08) + ? (config & 0x07) + 1 + : 0 + const headerLength = 1 + keyLength + counterLength + + if (ciphertext.length < headerLength + tagLength) { + return undefined + } + + const keyId = keyLength + ? readValue(ciphertext, 1, keyLength) + : BigInt((config >> 4) & 0x07) + const counter = counterLength + ? readValue(ciphertext, 1 + keyLength, counterLength) + : BigInt(config & 0x07) + const header = ciphertext.subarray(0, headerLength) + const body = ciphertext.subarray(headerLength, ciphertext.length - tagLength) + const tag = ciphertext.subarray(ciphertext.length - tagLength) + const ssrcOctets = Buffer.alloc(4) + const label = Buffer.alloc(10) + + ssrcOctets.writeUInt32BE(ssrc) + label.writeBigUInt64BE(keyId) + label.writeUInt16BE(suite, 8) + + const secret = Buffer.from(hkdfSync('sha512', sessionKey, ssrcOctets, STREAM_LABEL, 64)) + const derived = Buffer.from(hkdfSync('sha512', secret, Buffer.alloc(0), Buffer.concat([ + Buffer.from(KEY_LABEL), + label, + ]), 96)) + const nonce = Buffer.from(hkdfSync('sha512', secret, Buffer.alloc(0), Buffer.concat([ + Buffer.from(SALT_LABEL), + label, + ]), 12)) + const counterOctets = Buffer.alloc(8) + + counterOctets.writeBigUInt64BE(counter) + + for (let index = 0; index < 8; index++) { + nonce[4 + index] ^= counterOctets[index] + } + + const lengths = Buffer.alloc(24) + + lengths.writeBigUInt64BE(BigInt(header.length), 0) + lengths.writeBigUInt64BE(BigInt(body.length), 8) + lengths.writeBigUInt64BE(BigInt(tagLength), 16) + + const expected = createHmac('sha512', derived.subarray(32)).update(Buffer.concat([lengths, nonce, header, body])).digest().subarray(0, tagLength) + + if (!timingSafeEqual(expected, tag)) { + return undefined + } + + const decipher = createDecipheriv('aes-256-ctr', derived.subarray(0, 32), Buffer.concat([ + nonce, + Buffer.alloc(4), + ])) + + return Buffer.concat([ + decipher.update(body), + decipher.final(), + ]) +} diff --git a/src/test-utils/webRTCEngineFixtures.ts b/src/test-utils/webRTCEngineFixtures.ts new file mode 100644 index 000000000..e2719d2f0 --- /dev/null +++ b/src/test-utils/webRTCEngineFixtures.ts @@ -0,0 +1,264 @@ +/* The fixtures the WebRTC engine's suites share: the synthetic sensor and its stream tiers, the loader a spec's mock of the engine's werift loader answers, + * the packet rules a spec's mock of them answers, a video frame of one synthetic picture unit and the SSRC each section of an offer names. A mock's + * factory is hoisted above every import, which is why it takes what it shares from here by a dynamic import of its own. + */ +import type { Mock } from 'vitest' +import type * as werift from 'werift' +import type { RTCPeerConnection, RTCPeerConnectionConfig } from 'werift' + +import type * as packetRules from '../lib/camera/rtp/packetRules.js' +import type { CameraVideoTier, SensorStreamTiers } from '../lib/camera/StreamingOptions.js' +import type { Werift } from '../lib/camera/webrtc/werift.js' + +import { Buffer } from 'node:buffer' + +import { vi } from 'vitest' + +import { + CameraVideoQuality, + TieredAudioBitDepth, + TieredAudioCodecType, + TieredAudioSampleRate, + TieredVideoCodecType, +} from '../lib/camera/capabilities/streamTiers.js' +import { FRAME_LENGTH_SIZE } from '../lib/camera/StreamingOptions.js' + +export const SENSOR_UUID = '7d3e0f9a-1b2c-4d5e-8f60-718293a4b5c6' + +// The settled entries of a literal tier set, by identifier, each frozen, carrying the sensor's UUID and marked to carry the sensor's sound, as the options +// boundary leaves them for a sensor whose audio states its source 'tier'. +function settled(...tiers: Required[]): SensorStreamTiers['tiers'] { + return new Map(tiers.map(tier => [ + tier.id, + Object.freeze({ ...tier, sensorUUID: SENSOR_UUID, sound: true }), + ])) +} + +// A sensor of several video tiers, the largest first, and its audio tier, all synthetic, each tier's stream carrying its own sound and the best tier the +// sound tier. +export const STREAM_TIERS: SensorStreamTiers = { + sensorUUID: SENSOR_UUID, + videoStreamTiers: { + codec: TieredVideoCodecType.H265, + payloadType: 99, + tiers: [ + { + identifier: 1, + quality: CameraVideoQuality.HIGHEST, + targetAverageBitrate: 1700, + width: 1920, + height: 1080, + frameRate: 30, + }, + { + identifier: 2, + quality: CameraVideoQuality.MEDIUM, + targetAverageBitrate: 600, + width: 1280, + height: 720, + frameRate: 30, + }, + { + identifier: 3, + quality: CameraVideoQuality.LOW, + targetAverageBitrate: 150, + width: 640, + height: 360, + frameRate: 15, + }, + ], + }, + audioStreamTiers: { + codec: TieredAudioCodecType.OPUS, + payloadType: 110, + tiers: [ + { + identifier: 1, + targetAverageBitrate: 32000, + sampleRate: TieredAudioSampleRate.KHZ_48, + bitDepth: TieredAudioBitDepth.BITS_16, + packetTime: 20, + numberOfChannels: 1, + }, + ], + }, + audioSource: 'tier', + soundTierId: 1, + tiers: settled( + { + bitrate: 1700, + frameRate: 30, + height: 1080, + id: 1, + keepRunning: false, + peakBitrate: 1800, + quality: CameraVideoQuality.HIGHEST, + recorded: true, + width: 1920, + }, + { + bitrate: 600, + frameRate: 30, + height: 720, + id: 2, + keepRunning: false, + peakBitrate: 800, + quality: CameraVideoQuality.MEDIUM, + recorded: false, + width: 1280, + }, + { + bitrate: 150, + frameRate: 15, + height: 360, + id: 3, + keepRunning: false, + peakBitrate: 190, + quality: CameraVideoQuality.LOW, + recorded: false, + width: 640, + }, + ), + strict: false, +} + +// The same sensor with its best tier, its sound tier, advertised after another: a smaller tier first, then two of one size, the later at the higher +// target bitrate. +export const LATER_BEST_TIERS: SensorStreamTiers = { + ...STREAM_TIERS, + soundTierId: 3, + videoStreamTiers: { + ...STREAM_TIERS.videoStreamTiers, + tiers: [ + { + identifier: 1, + quality: CameraVideoQuality.MEDIUM, + targetAverageBitrate: 600, + width: 1280, + height: 720, + frameRate: 30, + }, + { + identifier: 2, + quality: CameraVideoQuality.HIGH, + targetAverageBitrate: 1000, + width: 1920, + height: 1080, + frameRate: 30, + }, + { + identifier: 3, + quality: CameraVideoQuality.HIGH, + targetAverageBitrate: 1700, + width: 1920, + height: 1080, + frameRate: 30, + }, + ], + }, + tiers: settled( + { + bitrate: 600, + frameRate: 30, + height: 720, + id: 1, + keepRunning: false, + peakBitrate: 800, + quality: CameraVideoQuality.MEDIUM, + recorded: false, + width: 1280, + }, + { + bitrate: 1000, + frameRate: 30, + height: 1080, + id: 2, + keepRunning: false, + peakBitrate: 1800, + quality: CameraVideoQuality.HIGH, + recorded: false, + width: 1920, + }, + { + bitrate: 1700, + frameRate: 30, + height: 1080, + id: 3, + keepRunning: false, + peakBitrate: 1800, + quality: CameraVideoQuality.HIGH, + recorded: true, + width: 1920, + }, + ), +} + +// What a spec's loopback loader records of the connections its class makes: each connection in the order made, and the configuration each was handed +// before the class bound it to the loopback interface. +export interface LoopbackConnections { + readonly configs: (Partial | undefined)[] + readonly peers: RTCPeerConnection[] +} + +/* The engine's werift loader as a spec's mock of it answers: werift's own exports with a connection class that binds the loopback interface alone. No + * row opens a socket on another address or prints one in a failed assertion, and no production code carries a test option. The far end of a loopback row + * is made from the same exports. + */ +export async function loopbackLoader(connections: LoopbackConnections): Promise<{ loadWerift: Mock<() => Promise> }> { + const actual = await vi.importActual('werift') + + class LoopbackPeerConnection extends actual.RTCPeerConnection { + constructor(config?: Partial) { + super({ + ...config, + iceInterfaceAddresses: { udp4: '127.0.0.1' }, + iceUseIpv6: false, + }) + connections.configs.push(config) + connections.peers.push(this) + } + } + + const exports: Werift = { + RTCPeerConnection: LoopbackPeerConnection, + RTCRtpCodecParameters: actual.RTCRtpCodecParameters, + RtpHeader: actual.RtpHeader, + RtpPacket: actual.RtpPacket, + useSdesMid: actual.useSdesMid, + useSdesRTPStreamId: actual.useSdesRTPStreamId, + } + + return { + loadWerift: vi.fn(async () => exports), + } +} + +// The packet rules as a spec's mock of them answers: the rules as they are, the first sequence number's draw recorded, which lets a row set the number every +// stream's packets start from. +export function recordedDraw(actual: typeof packetRules): typeof packetRules { + return { + ...actual, + firstSequence: vi.fn(actual.firstSequence), + } +} + +// A video frame of one synthetic NAL unit of a picture type, which no keyframe walk reads, its octets patterned from a seed. +export function picture(length: number, seed: number): Buffer { + const frame = Buffer.alloc(FRAME_LENGTH_SIZE + 2 + length, seed) + + frame.writeUInt32BE(2 + length) + frame[FRAME_LENGTH_SIZE] = 0x02 + frame[FRAME_LENGTH_SIZE + 1] = 0x01 + + return frame +} + +// The SSRC each section of a description names in its first ssrc line, in section order. +export function ssrcsOf(sdp: string): number[] { + return sdp.split('\r\nm=').slice(1).map(section => Number(/\r\na=ssrc:(\d+) /.exec(section)?.[1])) +} + +// A pause of real time, for a row whose check waits on sockets and timers of its own. +export async function realTimePause(): Promise { + await new Promise(resolve => setTimeout(resolve, 10)) +} diff --git a/tsconfig.json b/tsconfig.json index d6cba15e6..5f28c044e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,7 +11,10 @@ "noUnusedParameters": true, "declaration": true, "outDir": "./dist", - "sourceMap": true + "sourceMap": true, + // The setting leaves every declaration file unchecked, a dependency's and the library's own hand-written src/types/simple-plist.d.ts alike, because + // werift's published declaration files do not compile on their own. + "skipLibCheck": true }, "include": [ "src/" From d85cb25afa2e203021b76452c5e6e110b3d42665 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:05:52 -0600 Subject: [PATCH 15/16] feat(camera): compose every camera, legacy and modern, in the camera controller, recording from the camera buffer, with the suites that drive it --- src/lib/Accessory.spec.ts | 773 +- src/lib/Accessory.ts | 29 +- src/lib/Characteristic.ts | 22 +- src/lib/HAPServer.spec.ts | 15 +- src/lib/HAPServer.ts | 6 +- src/lib/Service.ts | 3 +- src/lib/camera/GlobalOperatingMode.spec.ts | 334 + src/lib/camera/MotionAttribution.spec.ts | 987 +++ src/lib/camera/MotionZonesManagement.spec.ts | 1323 ++++ .../camera/MultiTierStreamManagement.spec.ts | 6781 +++++++++++++++++ src/lib/camera/RTPStreamManagement.spec.ts | 695 +- src/lib/camera/RTPStreamManagement.ts | 455 +- src/lib/camera/RecordingManagement.spec.ts | 2595 ++++++- src/lib/camera/RecordingManagement.ts | 1223 ++- src/lib/camera/SensorRegistry.spec.ts | 370 + src/lib/camera/StreamingOptions.spec.ts | 714 ++ src/lib/camera/StreamingOptions.ts | 71 + src/lib/camera/TierPacer.spec.ts | 4645 +++++++++++ src/lib/camera/WebRTCStreamManagement.spec.ts | 3144 ++++++++ src/lib/camera/buffer/TierKeeper.spec.ts | 1978 +++++ .../capabilities/setupEndpoints.spec.ts | 175 + src/lib/camera/index.ts | 1 + .../camera/recording/BufferRecorder.spec.ts | 2114 +++++ src/lib/camera/recording/BufferRecorder.ts | 1004 +++ .../recording/CMAFRecordingManagement.spec.ts | 3849 ++++++++++ src/lib/camera/srtp/SRTPContext.spec.ts | 632 ++ src/lib/camera/srtp/keystream.spec.ts | 51 + .../webrtc/WebRTCEngine.loopback.spec.ts | 744 ++ src/lib/camera/webrtc/WebRTCEngine.spec.ts | 3521 +++++++++ .../CameraController.characterization.spec.ts | 1861 +++++ src/lib/controller/CameraController.spec.ts | 3874 +++++++++- src/lib/controller/CameraController.ts | 2904 +++++-- src/lib/controller/DoorbellController.spec.ts | 55 +- src/lib/controller/DoorbellController.ts | 23 +- src/lib/controller/eventDispatch.spec.ts | 210 + src/lib/controller/eventDispatch.ts | 29 + src/test-utils/ReferenceSRTP.ts | 193 + src/test-utils/cameraFixtures.ts | 772 ++ src/test-utils/certificateAuthority.ts | 140 + 39 files changed, 46800 insertions(+), 1515 deletions(-) create mode 100644 src/lib/camera/GlobalOperatingMode.spec.ts create mode 100644 src/lib/camera/MotionAttribution.spec.ts create mode 100644 src/lib/camera/MotionZonesManagement.spec.ts create mode 100644 src/lib/camera/MultiTierStreamManagement.spec.ts create mode 100644 src/lib/camera/SensorRegistry.spec.ts create mode 100644 src/lib/camera/StreamingOptions.spec.ts create mode 100644 src/lib/camera/TierPacer.spec.ts create mode 100644 src/lib/camera/WebRTCStreamManagement.spec.ts create mode 100644 src/lib/camera/buffer/TierKeeper.spec.ts create mode 100644 src/lib/camera/capabilities/setupEndpoints.spec.ts create mode 100644 src/lib/camera/recording/BufferRecorder.spec.ts create mode 100644 src/lib/camera/recording/BufferRecorder.ts create mode 100644 src/lib/camera/recording/CMAFRecordingManagement.spec.ts create mode 100644 src/lib/camera/srtp/SRTPContext.spec.ts create mode 100644 src/lib/camera/srtp/keystream.spec.ts create mode 100644 src/lib/camera/webrtc/WebRTCEngine.loopback.spec.ts create mode 100644 src/lib/camera/webrtc/WebRTCEngine.spec.ts create mode 100644 src/lib/controller/CameraController.characterization.spec.ts create mode 100644 src/lib/controller/eventDispatch.spec.ts create mode 100644 src/lib/controller/eventDispatch.ts create mode 100644 src/test-utils/ReferenceSRTP.ts create mode 100644 src/test-utils/cameraFixtures.ts create mode 100644 src/test-utils/certificateAuthority.ts diff --git a/src/lib/Accessory.spec.ts b/src/lib/Accessory.spec.ts index a2e8759cd..d0045b8d1 100644 --- a/src/lib/Accessory.spec.ts +++ b/src/lib/Accessory.spec.ts @@ -19,7 +19,7 @@ import type { CharacteristicGetCallback, CharacteristicSetCallback, } from './Characteristic.js' -import type { Controller, ControllerIdentifier, ControllerServiceMap } from './controller/index.js' +import type { Controller, ControllerAccessoryContext, ControllerIdentifier, ControllerServiceMap } from './controller/index.js' import type { IdentifyCallback } from './HAPServer.js' import type { PairingInformation } from './model/AccessoryInfo.js' @@ -28,9 +28,21 @@ import crypto from 'node:crypto' import { format } from 'node:util' import createDebug from 'debug' +import tweetnacl from 'tweetnacl' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + capabilitiesCameraOptions, + createCameraControllerOptions, + FIRST_VIDEO_SENSOR, + idleStreaming, + MOCK_IMAGE, + snapshotFunction, +} from '../test-utils/cameraFixtures.js' import { buildEmitterConnection } from '../test-utils/connectionFixtures.js' +import { HAPHTTPClient } from '../test-utils/HAPHTTPClient.js' +import { PairVerifyClient } from '../test-utils/PairVerifyClient.js' +import { deferred, until } from '../test-utils/settle.js' import { ResourceRequestType, } from '../types.js' @@ -45,13 +57,15 @@ import { Perms, Units, } from './Characteristic.js' -import { createCameraControllerOptions, MOCK_IMAGE } from './controller/CameraController.spec.js' import { CameraController } from './controller/index.js' import { HAPHTTPCode, HAPServer, HAPStatus, TLVErrorCode } from './HAPServer.js' import { AccessoryInfo, PermissionTypes } from './model/AccessoryInfo.js' +import { ControllerStorage } from './model/ControllerStorage.js' +import { HAPStorage } from './model/HAPStorage.js' import { IdentifierCache } from './model/IdentifierCache.js' +import { RecordingProvisioning } from './model/RecordingProvisioning.js' import { Service } from './Service.js' -import { EventedHTTPServer, HAPConnection } from './util/eventedhttp.js' +import { EventedHTTPServer, HAPConnection, HAPConnectionEvent } from './util/eventedhttp.js' import { HapStatusError } from './util/hapStatusError.js' import { awaitEventOnce, PromiseTimeout } from './util/promise-utils.js' import * as uuid from './util/uuid.js' @@ -524,6 +538,653 @@ describe('Accessory', () => { }) }) + // The rows that follow publish under usernames of their own, every one cleaned after its row with whatever the row published. + const usernames: string[] = [] + const published: Accessory[] = [] + + afterEach(async () => { + for (const target of published.splice(0)) { + await target.unpublish() + await target.destroy() + } + + for (const username of usernames.splice(0)) { + Accessory.cleanupAccessoryData(username) + } + }) + + function username(last: number): string { + const name = `AB:CD:EF:00:33:${last.toString(16).padStart(2, '0').toUpperCase()}` + + usernames.push(name) + return name + } + + // Publishes an accessory through the advertiser the suite mocks, and nothing is announced. + async function publish(target: Accessory, name: string): Promise { + if (!published.includes(target)) { + published.push(target) + } + + await target.publish({ + advertiser: MDNSAdvertiser.BONJOUR, + category: Categories.CAMERA, + pincode: '031-45-154', + username: name, + }) + } + + describe('a controller\'s accessory context', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + // A camera whose every handed context is recorded as its UUID, whether it reads published and its username, the method itself still running. + function recordedCamera(): { camera: CameraController, contexts: { accessoryUUID: string, published: boolean, username?: string }[] } { + const camera = new CameraController(createCameraControllerOptions()) + const contexts: { accessoryUUID: string, published: boolean, username?: string }[] = [] + const handle = camera.handleAccessoryContext.bind(camera) + + vi.spyOn(camera, 'handleAccessoryContext').mockImplementation((context) => { + contexts.push({ accessoryUUID: context.accessoryUUID, published: context.published, username: context.username }) + handle(context) + }) + + return { camera, contexts } + } + + function heldContext(camera: CameraController): unknown { + // @ts-expect-error: private access + return camera.accessoryContext + } + + it('hands a published accessory\'s camera a context with its username and UUID once the restore has run', async () => { + const name = username(1) + const target = new Accessory('Camera', uuid.generate('context published')) + const source = new CameraController(createCameraControllerOptions()) + source.constructServices() + source.configureServices() + HAPStorage.storage().setItemSync(ControllerStorage.persistKey(name), { + accessories: { + [target.UUID]: [ + { + type: 'camera', + controllerData: { + data: source.serialize(), + }, + }, + ], + }, + }) + source.handleControllerRemoved() + const { camera, contexts } = recordedCamera() + const restore = camera.deserialize.bind(camera) + const handedBeforeRestore: number[] = [] + vi.spyOn(camera, 'deserialize').mockImplementation((state) => { + handedBeforeRestore.push(contexts.length) + restore(state) + }) + target.configureController(camera) + + await publish(target, name) + + expect(contexts).toEqual([ + { accessoryUUID: target.UUID, published: false, username: undefined }, + { accessoryUUID: target.UUID, published: false, username: name }, + { accessoryUUID: target.UUID, published: true, username: name }, + ]) + expect(handedBeforeRestore).toEqual([1]) + expect(heldContext(camera)).toEqual({ + accessoryInformation: target.getService(Service.AccessoryInformation), + accessoryUUID: target.UUID, + published: true, + username: name, + }) + }) + + it('hands an unpublished accessory\'s camera a context without a username', () => { + const target = new Accessory('Camera', uuid.generate('context unpublished')) + const { camera, contexts } = recordedCamera() + + target.configureController(camera) + + expect(contexts).toEqual([ + { accessoryUUID: target.UUID, published: false, username: undefined }, + ]) + }) + + it('hands a bridged camera its bridge\'s username, and none once it leaves the bridge', async () => { + const name = username(2) + const bridge = new Bridge('Bridge', uuid.generate('context bridge')) + await publish(bridge, name) + const target = new Accessory('Camera', uuid.generate('context bridged')) + const { camera, contexts } = recordedCamera() + target.configureController(camera) + + bridge.addBridgedAccessory(target) + bridge.removeBridgedAccessory(target) + + expect(contexts).toEqual([ + { accessoryUUID: target.UUID, published: false, username: undefined }, + { accessoryUUID: target.UUID, published: true, username: name }, + { accessoryUUID: target.UUID, published: false, username: undefined }, + ]) + }) + + it('hands a camera the new username when its accessory is published again under another', async () => { + const first = username(3) + const second = username(4) + const target = new Accessory('Camera', uuid.generate('context renamed')) + const { camera, contexts } = recordedCamera() + target.configureController(camera) + await publish(target, first) + await target.unpublish() + + await publish(target, second) + + expect(contexts.map(context => context.username)).toEqual([ + undefined, + first, + first, + first, + second, + second, + ]) + expect((heldContext(camera) as { username: string }).username).toBe(second) + }) + + it('hands a controller that is not serializable no context', async () => { + const target = new Accessory('Switch', uuid.generate('context plain')) + const controller = Object.assign(new TestController(), { + handleAccessoryContext: vi.fn(), + }) + target.configureController(controller) + + await publish(target, username(5)) + + expect(controller.handleAccessoryContext).not.toHaveBeenCalled() + }) + + it('hands a camera the same context again at a second publish, alone and behind a bridge, holding one equal to the first and loading or writing no ' + + 'record', async () => { + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + const load = vi.spyOn(RecordingProvisioning, 'load') + const name = username(6) + const target = new Accessory('Camera', uuid.generate('context repeated')) + const { camera, contexts } = recordedCamera() + target.configureController(camera) + await publish(target, name) + const held = heldContext(camera) + + await target.unpublish() + await publish(target, name) + + const bridgeName = username(7) + const bridge = new Bridge('Bridge', uuid.generate('context repeated bridge')) + const bridged = new Accessory('Camera', uuid.generate('context repeated bridged')) + const behind = recordedCamera() + bridged.configureController(behind.camera) + bridge.addBridgedAccessory(bridged) + await publish(bridge, bridgeName) + const heldBehind = heldContext(behind.camera) + + await bridge.unpublish() + await publish(bridge, bridgeName) + + expect(contexts.map(context => context.username)).toEqual([ + undefined, + name, + name, + name, + name, + name, + ]) + expect(heldContext(camera)).toEqual(held) + expect(heldContext(camera)).not.toBe(held) + expect(behind.contexts.map(context => context.username)).toEqual([ + undefined, + undefined, + bridgeName, + bridgeName, + bridgeName, + bridgeName, + bridgeName, + ]) + expect(heldContext(behind.camera)).toEqual(heldBehind) + expect(heldContext(behind.camera)).not.toBe(heldBehind) + expect(setItemSync.mock.calls.filter(([key]) => key.startsWith('RecordingProvisioning.'))).toEqual([]) + expect(load).not.toHaveBeenCalled() + }) + + it('hands a standalone accessory\'s camera a context reading not published at its configure and after its first publish\'s restore, published at ' + + 'the publish\'s end and not published at its unpublish', async () => { + const name = username(8) + const target = new Accessory('Camera', uuid.generate('context published standalone')) + const { camera, contexts } = recordedCamera() + + target.configureController(camera) + await publish(target, name) + await target.unpublish() + + expect(contexts).toEqual([ + { accessoryUUID: target.UUID, published: false, username: undefined }, + { accessoryUUID: target.UUID, published: false, username: name }, + { accessoryUUID: target.UUID, published: true, username: name }, + { accessoryUUID: target.UUID, published: false, username: name }, + ]) + }) + + it('hands a bridged camera a context reading published at its link to a published bridge, not published at its unlink and at the bridge\'s ' + + 'unpublish, and published at the end of the bridge\'s publish', async () => { + const name = username(9) + const bridge = new Bridge('Bridge', uuid.generate('context published bridge')) + const target = new Accessory('Camera', uuid.generate('context published bridged')) + const { camera, contexts } = recordedCamera() + + await publish(bridge, name) + target.configureController(camera) + bridge.addBridgedAccessory(target) + bridge.removeBridgedAccessory(target) + bridge.addBridgedAccessory(target) + await bridge.unpublish() + await publish(bridge, name) + + // The configure, the link, the unlink, the link again, the bridge's unpublish, and the bridge's publish after its restore and at its end. + expect(contexts).toEqual([ + { accessoryUUID: target.UUID, published: false, username: undefined }, + { accessoryUUID: target.UUID, published: true, username: name }, + { accessoryUUID: target.UUID, published: false, username: undefined }, + { accessoryUUID: target.UUID, published: true, username: name }, + { accessoryUUID: target.UUID, published: false, username: name }, + { accessoryUUID: target.UUID, published: false, username: name }, + { accessoryUUID: target.UUID, published: true, username: name }, + ]) + }) + + it('hands a context reading not published at a destroy to its own camera and to each bridged camera, a bridged accessory\'s own destroy among ' + + 'them', async () => { + const name = username(10) + const bridgeName = username(11) + const target = new Accessory('Camera', uuid.generate('context destroyed')) + const bridge = new Bridge('Bridge', uuid.generate('context destroyed bridge')) + const bridged = new Accessory('Camera', uuid.generate('context destroyed bridged')) + const leaving = new Accessory('Camera', uuid.generate('context destroyed leaving')) + const own = recordedCamera() + const behind = recordedCamera() + const left = recordedCamera() + target.configureController(own.camera) + bridged.configureController(behind.camera) + leaving.configureController(left.camera) + bridge.addBridgedAccessory(bridged) + bridge.addBridgedAccessory(leaving) + await publish(target, name) + await publish(bridge, bridgeName) + const ownHanded = own.contexts.length + const behindHanded = behind.contexts.length + const leftHanded = left.contexts.length + + await leaving.destroy() + const leftAtOwnDestroy = left.contexts.slice(leftHanded) + await target.destroy() + await bridge.destroy() + + // A destroy unpublishes first, and then hands its own context once its data is removed, a bridged accessory's own reading its bridge's username. + expect(leftAtOwnDestroy).toEqual([ + { accessoryUUID: leaving.UUID, published: false, username: bridgeName }, + ]) + expect(own.contexts.slice(ownHanded)).toEqual([ + { accessoryUUID: target.UUID, published: false, username: name }, + { accessoryUUID: target.UUID, published: false, username: undefined }, + ]) + expect(behind.contexts.slice(behindHanded)).toEqual([ + { accessoryUUID: bridged.UUID, published: false, username: bridgeName }, + { accessoryUUID: bridged.UUID, published: false, username: undefined }, + ]) + }) + + it('hands a camera being removed a context reading not published, after its untrack and before its factory reset', async () => { + const name = username(12) + const target = new Accessory('Camera', uuid.generate('context removed')) + const { camera, contexts } = recordedCamera() + target.configureController(camera) + await publish(target, name) + const untrack = vi.spyOn(ControllerStorage.prototype, 'untrackController') + const reset = vi.spyOn(camera, 'handleFactoryReset') + const handle = vi.mocked(camera.handleAccessoryContext) + const handed = contexts.length + + target.removeController(camera) + + expect(contexts.slice(handed)).toEqual([ + { accessoryUUID: target.UUID, published: false, username: name }, + ]) + expect(untrack.mock.invocationCallOrder[0]).toBeLessThan(handle.mock.invocationCallOrder[handed]) + expect(handle.mock.invocationCallOrder[handed]).toBeLessThan(reset.mock.invocationCallOrder[0]) + }) + + it('replaces the context a camera holds with one differing in whether it reads published alone, its clip path loading and writing no provisioning ' + + 'record', async () => { + const name = username(13) + const target = new Accessory('Camera', uuid.generate('context published alone')) + const camera = new CameraController(capabilitiesCameraOptions({ + streaming: idleStreaming(), + videoSensors: [FIRST_VIDEO_SENSOR], + })) + target.configureController(camera) + await publish(target, name) + const held = heldContext(camera) as ControllerAccessoryContext + const load = vi.spyOn(RecordingProvisioning, 'load') + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + const removeItemSync = vi.spyOn(HAPStorage.storage(), 'removeItemSync') + const moved = { ...held, published: !held.published } + + camera.handleAccessoryContext(moved) + + expect(heldContext(camera)).toBe(moved) + // @ts-expect-error: private access + expect(camera.cmafRecordingManagement.identity).toEqual({ accessoryUUID: target.UUID, username: name }) + expect(load).not.toHaveBeenCalled() + expect(setItemSync.mock.calls.filter(([key]) => key.startsWith('RecordingProvisioning.'))).toEqual([]) + expect(removeItemSync.mock.calls.filter(([key]) => key.startsWith('RecordingProvisioning.'))).toEqual([]) + }) + + it('logs a controller\'s failure to take its accessory\'s context and goes on with the hand and its caller, a bridge\'s unpublish destroying its ' + + 'advertiser and telling every later controller, and a publish, an unlink and the controller\'s own removal each running to its end', async () => { + const name = username(14) + const bridge = new Bridge('Bridge', uuid.generate('context guarded bridge')) + const failing = new Accessory('Failing Camera', uuid.generate('context guarded failing')) + const later = new Accessory('Camera', uuid.generate('context guarded later')) + const own = recordedCamera() + const after = recordedCamera() + const thrower = new CameraController(createCameraControllerOptions()) + const handle = thrower.handleAccessoryContext.bind(thrower) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + // The first line of each logged failure: the accessory's name, the sentence and the thrown error's own first line. + const failures = (): string[] => error.mock.calls.map(([line]) => String(line).split('\n')[0]) + const FAILED = '[Failing Camera] A controller failed to take its accessory\'s context: Error: A listener of the plugin\'s failed.' + let throwing = false + + // Once armed, the controller throws out of its handler, as a listener a plugin attached to a characteristic the handler writes would. + vi.spyOn(thrower, 'handleAccessoryContext').mockImplementation((context) => { + if (throwing) { + throw new Error('A listener of the plugin\'s failed.') + } + + handle(context) + }) + + bridge.configureController(own.camera) + failing.configureController(thrower) + later.configureController(after.camera) + bridge.addBridgedAccessory(failing) + bridge.addBridgedAccessory(later) + await publish(bridge, name) + + const destroy = vi.spyOn(bridge._advertiser!, 'destroy') + const ownHanded = own.contexts.length + const laterHanded = after.contexts.length + + throwing = true + + await expect(bridge.unpublish()).resolves.toBeUndefined() + expect(destroy).toHaveBeenCalledOnce() + expect(own.contexts.slice(ownHanded)).toEqual([ + { accessoryUUID: bridge.UUID, published: false, username: name }, + ]) + expect(after.contexts.slice(laterHanded)).toEqual([ + { accessoryUUID: later.UUID, published: false, username: name }, + ]) + expect(failures()).toEqual([FAILED]) + + error.mockClear() + await publish(bridge, name) + + // A publish hands its context once its controller storage has restored what it holds and again at its end, and the controller fails at each. + expect(after.contexts.at(-1)).toEqual({ accessoryUUID: later.UUID, published: true, username: name }) + expect(failures()).toEqual([FAILED, FAILED]) + + error.mockClear() + bridge.removeBridgedAccessory(failing) + + expect(bridge.bridgedAccessories).toEqual([later]) + expect(failures()).toEqual([FAILED]) + + const reset = vi.spyOn(thrower, 'handleFactoryReset') + const removed = vi.spyOn(thrower, 'handleControllerRemoved') + + error.mockClear() + failing.removeController(thrower) + + // The removal's own factory reset runs before handleControllerRemoved, which resets the camera again itself. + expect(removed).toHaveBeenCalledOnce() + expect(reset.mock.invocationCallOrder[0]).toBeLessThan(removed.mock.invocationCallOrder[0]) + expect(failures()).toEqual([FAILED]) + }) + }) + + describe('the recording provisioning record', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + const CAMERA_KEY = { + key: Buffer.alloc(32, 0x5A), + keyNumber: 1n, + } + const PUBLISHING_POINT = { + serverCACertificates: [ + { + certificate: Buffer.from('3082a1', 'hex'), + }, + ], + url: 'https://ingest.example/v1/token/', + } + + // A camera's entry with a hub's Camera Key and publishing point beside its marks. + function provisioned(name: string, accessoryUUID: string): void { + RecordingProvisioning.save(name, accessoryUUID, { + cameraKey: CAMERA_KEY, + clipMark: 9n, + publishingPoint: PUBLISHING_POINT, + sequenceMark: 5n, + }) + } + + it('clears the camera\'s entry to its marks at the last pairing\'s removal before the camera resets', () => { + vi.spyOn(EventedHTTPServer, 'destroyExistingConnectionsAfterUnpair').mockImplementation(() => undefined) + const name = username(16) + const target = new Accessory('Camera', uuid.generate('record unpaired')) + const camera = new CameraController(createCameraControllerOptions()) + target.configureController(camera) + const pairings = AccessoryInfo.create(name) + pairings.addPairedClient(clientUsername0, clientPublicKey0, PermissionTypes.ADMIN) + pairings.save = vi.fn() + target._accessoryInfo = pairings + provisioned(name, target.UUID) + const readAtReset: unknown[] = [] + const reset = camera.handleFactoryReset.bind(camera) + vi.spyOn(camera, 'handleFactoryReset').mockImplementation(() => { + readAtReset.push(RecordingProvisioning.load(name, target.UUID)) + reset() + }) + + // @ts-expect-error: private access + target.handleRemovePairing(connection, clientUsername0, callback) + + expect(callback).toHaveBeenCalledWith(0) + expect(readAtReset).toEqual([ + { clipMark: 9n, sequenceMark: 5n }, + ]) + expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ clipMark: 9n, sequenceMark: 5n }) + }) + + it('clears every bridged camera\'s entry to its marks at the bridge\'s last pairing\'s removal before the camera resets', async () => { + vi.spyOn(EventedHTTPServer, 'destroyExistingConnectionsAfterUnpair').mockImplementation(() => undefined) + const name = username(19) + const bridge = new Bridge('Bridge', uuid.generate('record unpaired bridge')) + const target = new Accessory('Camera', uuid.generate('record unpaired bridged')) + const camera = new CameraController(createCameraControllerOptions()) + target.configureController(camera) + bridge.addBridgedAccessory(target) + await publish(bridge, name) + bridge._accessoryInfo!.addPairedClient(clientUsername0, clientPublicKey0, PermissionTypes.ADMIN) + provisioned(name, target.UUID) + const readAtReset: unknown[] = [] + const reset = camera.handleFactoryReset.bind(camera) + vi.spyOn(camera, 'handleFactoryReset').mockImplementation(() => { + readAtReset.push(RecordingProvisioning.load(name, target.UUID)) + reset() + }) + + // @ts-expect-error: private access + bridge.handleRemovePairing(connection, clientUsername0, callback) + + expect(callback).toHaveBeenCalledWith(0) + expect(readAtReset).toEqual([ + { clipMark: 9n, sequenceMark: 5n }, + ]) + expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ clipMark: 9n, sequenceMark: 5n }) + }) + + it('keeps the record as stored and warns once per failed write at a bridged camera\'s removal, a first publish and the last pairing\'s removal', async () => { + vi.spyOn(EventedHTTPServer, 'destroyExistingConnectionsAfterUnpair').mockImplementation(() => undefined) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const removedName = username(20) + const removedBridge = new Bridge('Front Bridge', uuid.generate('record failed removal bridge')) + const removed = new Accessory('Front Camera', uuid.generate('record failed removal')) + const earlyName = username(21) + const earlyBridge = new Bridge('Back Bridge', uuid.generate('record failed early bridge')) + const early = new Accessory('Back Camera', uuid.generate('record failed early')) + const unpairedName = username(22) + const unpaired = new Accessory('Side Camera', uuid.generate('record failed unpaired')) + const pairings = AccessoryInfo.create(unpairedName) + const keyOnly = { cameraKey: CAMERA_KEY, publishingPoint: PUBLISHING_POINT } + await publish(removedBridge, removedName) + removedBridge.addBridgedAccessory(removed) + provisioned(removedName, removed.UUID) + provisioned(earlyName, early.UUID) + earlyBridge.addBridgedAccessory(early) + earlyBridge.removeBridgedAccessory(early) + pairings.addPairedClient(clientUsername0, clientPublicKey0, PermissionTypes.ADMIN) + pairings.save = vi.fn() + unpaired._accessoryInfo = pairings + RecordingProvisioning.save(unpairedName, unpaired.UUID, keyOnly) + + // Only the record's own writes fail. The publish still stores the accessory's pairing data. + const storage = HAPStorage.storage() + const setItemSync = storage.setItemSync.bind(storage) + const removeItemSync = storage.removeItemSync.bind(storage) + const failing = (key: string): void => { + if (key.startsWith('RecordingProvisioning.')) { + throw new Error('The disk is full.') + } + } + vi.spyOn(storage, 'setItemSync').mockImplementation((key, value) => { + failing(key) + setItemSync(key, value) + }) + vi.spyOn(storage, 'removeItemSync').mockImplementation((key) => { + failing(key) + removeItemSync(key) + }) + + expect(() => removedBridge.removeBridgedAccessory(removed)).not.toThrow() + await expect(publish(earlyBridge, earlyName)).resolves.toBeUndefined() + // @ts-expect-error: private access + expect(() => unpaired.handleRemovePairing(connection, clientUsername0, callback)).not.toThrow() + + expect(callback).toHaveBeenCalledWith(0) + expect(warn.mock.calls).toEqual([ + [`[${removedBridge.displayName}] The recording provisioning record could not be written: The disk is full.`], + [`[${earlyBridge.displayName}] The recording provisioning record could not be written: The disk is full.`], + ['[Side Camera] The recording provisioning record could not be written: The disk is full.'], + ]) + expect(RecordingProvisioning.load(removedName, removed.UUID)).toStrictEqual({ + cameraKey: CAMERA_KEY, + clipMark: 9n, + publishingPoint: PUBLISHING_POINT, + sequenceMark: 5n, + }) + expect(RecordingProvisioning.load(earlyName, early.UUID)).toStrictEqual({ + cameraKey: CAMERA_KEY, + clipMark: 9n, + publishingPoint: PUBLISHING_POINT, + sequenceMark: 5n, + }) + expect(RecordingProvisioning.load(unpairedName, unpaired.UUID)).toStrictEqual(keyOnly) + }) + + it('clears a camera\'s entry to its marks when it leaves a published bridge and keeps its neighbor\'s whole', async () => { + const name = username(17) + const bridge = new Bridge('Bridge', uuid.generate('record bridge')) + const target = new Accessory('Camera', uuid.generate('record bridged')) + const neighbor = uuid.generate('record neighbor') + await publish(bridge, name) + provisioned(name, target.UUID) + provisioned(name, neighbor) + bridge.addBridgedAccessory(target) + + bridge.removeBridgedAccessory(target) + + expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ clipMark: 9n, sequenceMark: 5n }) + expect(RecordingProvisioning.load(name, neighbor)).toStrictEqual({ + cameraKey: CAMERA_KEY, + clipMark: 9n, + publishingPoint: PUBLISHING_POINT, + sequenceMark: 5n, + }) + }) + + it('clears the entry of a camera that left a bridge before its first publish to its marks once that publish loads storage, before the camera hears it', async () => { + const name = username(18) + const bridge = new Bridge('Bridge', uuid.generate('record unpublished bridge')) + const target = new Accessory('Camera', uuid.generate('record removed early')) + const neighbor = uuid.generate('record early neighbor') + const camera = new CameraController(createCameraControllerOptions()) + target.configureController(camera) + provisioned(name, target.UUID) + provisioned(name, neighbor) + bridge.addBridgedAccessory(target) + bridge.removeBridgedAccessory(target) + + expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ + cameraKey: CAMERA_KEY, + clipMark: 9n, + publishingPoint: PUBLISHING_POINT, + sequenceMark: 5n, + }) + + // The camera is added back before the publish: the publish hands it the username, which it must hear only after its entry is cleared. + bridge.addBridgedAccessory(target) + const load = vi.spyOn(bridge.controllerStorage, 'load') + const clearProvisioning = vi.spyOn(RecordingProvisioning, 'clearProvisioning') + const handleAccessoryContext = vi.spyOn(camera, 'handleAccessoryContext') + + await publish(bridge, name) + + const heard = handleAccessoryContext.mock.calls.findIndex(([context]) => context.username === name) + + expect(handleAccessoryContext.mock.invocationCallOrder[heard]).toBeGreaterThan(clearProvisioning.mock.invocationCallOrder[0]) + + expect(RecordingProvisioning.load(name, target.UUID)).toStrictEqual({ clipMark: 9n, sequenceMark: 5n }) + expect(RecordingProvisioning.load(name, neighbor)).toStrictEqual({ + cameraKey: CAMERA_KEY, + clipMark: 9n, + publishingPoint: PUBLISHING_POINT, + sequenceMark: 5n, + }) + + // The accessory's clear comes first, and the camera, which starts without the capabilities block, then clears its own entry inside the context it + // hears, finding it cleared already and writing nothing. + expect(clearProvisioning.mock.calls).toEqual([ + [name, target.UUID], + [name, target.UUID], + ]) + expect(clearProvisioning.mock.invocationCallOrder[1]).toBeGreaterThan(handleAccessoryContext.mock.invocationCallOrder[heard]) + expect(clearProvisioning.mock.invocationCallOrder[0]).toBeGreaterThan(load.mock.invocationCallOrder[0]) + }) + }) + describe('publish', () => { it('blocks a standalone accessory containing invalid characteristic permissions', async () => { const service = accessory.addService(Service.Switch) @@ -3009,21 +3670,21 @@ describe('Accessory', () => { accessory.configureController(cameraController) }) - const testRequestResponse = async (partial: Partial = {}) => { + const testRequestResponse = async (partial: Partial = {}, requestConnection = buildEmitterConnection()) => { // @ts-expect-error: private access accessory.handleResource({ 'resource-type': ResourceRequestType.IMAGE, 'image-width': 200, 'image-height': 200, ...partial, - }, callback) + }, callback, requestConnection) await callbackPromise } it('unknown resource type', () => { // @ts-expect-error: private access - accessory.handleResource({ 'resource-type': 'unknown' }, callback) + accessory.handleResource({ 'resource-type': 'unknown' }, callback, buildEmitterConnection()) expect(callback).toHaveBeenCalledWith({ httpCode: HAPHTTPCode.NOT_FOUND, @@ -3039,7 +3700,7 @@ describe('Accessory', () => { 'resource-type': ResourceRequestType.IMAGE, 'image-width': 200, 'image-height': 200, - }, callback) + }, callback, buildEmitterConnection()) expect(callback).toHaveBeenCalledWith({ httpCode: HAPHTTPCode.NOT_FOUND, @@ -3100,6 +3761,36 @@ describe('Accessory', () => { await testRequestResponse() expect(callback).toHaveBeenCalledWith({ httpCode: HAPHTTPCode.MULTI_STATUS, status: HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE }) }) + + it('takes back the close listener and the max-listener slot a snapshot adds to a connection that stays open once it settles, answered and refused', + async () => { + const open = buildEmitterConnection() + const held = (): number[] => [ + open.listenerCount(HAPConnectionEvent.CLOSED), + open.getMaxListeners(), + ] + const before = held() + const pending = testRequestResponse({}, open) + + expect(held()).toEqual([before[0] + 1, before[1] + 1]) + + await pending + + expect(callback).toHaveBeenCalledWith(undefined, MOCK_IMAGE) + expect(held()).toEqual(before) + + callback.mockReset() + cameraController.recordingManagement!.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + + const refused = testRequestResponse({}, open) + + expect(held()).toEqual([before[0] + 1, before[1] + 1]) + + await refused + + expect(callback).toHaveBeenCalledWith({ httpCode: HAPHTTPCode.MULTI_STATUS, status: HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE }) + expect(held()).toEqual(before) + }) }) describe('characteristic read/write characteristicWarning', () => { @@ -3279,6 +3970,74 @@ describe('Accessory', () => { }) }) + describe('a snapshot over a paired connection', () => { + const clientUsername = 'CA:FE:00:00:00:05' + + it('aborts the signal of a pending snapshot of a camera with the block as the connection its resource request arrived on is destroyed', async () => { + const clientKeyPair = tweetnacl.sign.keyPair() + const clientInfo = { + privateKey: Buffer.from(clientKeyPair.secretKey), + publicKey: Buffer.from(clientKeyPair.publicKey), + username: clientUsername, + } + const paired = AccessoryInfo.create(serverUsername) + const snapshot = snapshotFunction() + + // @ts-expect-error: private access + paired.setupID = Accessory._generateSetupID() + paired.displayName = 'Camera' + paired.category = Categories.IP_CAMERA + paired.pincode = '031-45-154' + paired.save = saveMock + paired.addPairedClient(clientUsername, clientInfo.publicKey, PermissionTypes.ADMIN) + // The published accessory loads the paired record above in place of a stored one. + vi.spyOn(AccessoryInfo, 'load').mockReturnValue(paired) + snapshot.mockImplementation(async () => await deferred().promise) + accessory.configureController(new CameraController(capabilitiesCameraOptions({ + snapshot, + streaming: idleStreaming(), + videoSensors: [FIRST_VIDEO_SENSOR], + }))) + + const listening: Promise<[port: number, hostname: string]> = awaitEventOnce(accessory, AccessoryEventTypes.LISTENING) + + await accessory.publish({ + advertiser: MDNSAdvertiser.BONJOUR, + category: Categories.IP_CAMERA, + pincode: paired.pincode, + port: 0, + username: serverUsername, + }) + + const [port] = await listening + const client = new HAPHTTPClient('127.0.0.1', port) + + await client.connect() + client.enableEncryption(await new PairVerifyClient(client).sendPairVerify({ + publicKey: Buffer.from(paired.signPk), + username: serverUsername, + }, clientInfo)) + + // The request is never answered, since its asker is gone. The row waits on the function's signal and not on the request. + void client.sendResourceRequest({ + 'image-height': 360, + 'image-width': 640, + 'resource-type': ResourceRequestType.IMAGE, + }).catch(() => undefined) + + await until(() => snapshot.mock.calls.length === 1) + + const [[, signal]] = snapshot.mock.calls + + expect(signal.aborted).toBe(false) + + client.destroy() + await until(() => signal.aborted) + + expect(signal.aborted).toBe(true) + }) + }) + describe('characteristicWarning', () => { let consoleWarnSpy: MockInstance diff --git a/src/lib/Accessory.ts b/src/lib/Accessory.ts index f9a1f8602..8d3058b54 100644 --- a/src/lib/Accessory.ts +++ b/src/lib/Accessory.ts @@ -84,6 +84,7 @@ import { Service, ServiceEventTypes } from './Service.js' import { checkName } from './util/checkName.js' import { clone } from './util/clone.js' import { errorMessage, errorStack } from './util/errors.js' +import { HAPConnectionEvent } from './util/eventedhttp.js' import { HapStatusError } from './util/hapStatusError.js' import { once } from './util/once.js' import { callDelegate } from './util/promise-utils.js' @@ -1494,7 +1495,8 @@ export class Accessory extends EventEmitter { // get our accessory information in HAP format and determine if our configuration (that is, our // Accessories/Services/Characteristics) has changed since the last time we were published. make - // sure to omit actual values since these are not part of the "configuration". + // sure to omit actual values since these are not part of the "configuration", but for the types + // whose value states a camera's configuration, which a characteristic's representation keeps. const config = this.internalHAPRepresentation(false) // TODO queue this check until about 5 seconds after startup, allowing some last changes after the publish call // without constantly incrementing the current config number @@ -1662,7 +1664,8 @@ export class Accessory extends EventEmitter { if (this._advertiser && this._identifierCache) { // get our accessory information in HAP format and determine if our configuration (that is, our // Accessories/Services/Characteristics) has changed since the last time we were published. make - // sure to omit actual values since these are not part of the "configuration". + // sure to omit actual values since these are not part of the "configuration", but for the types + // whose value states a camera's configuration, which a characteristic's representation keeps. try { const config = this.internalHAPRepresentation() this.dropStaleEventRegistrations() @@ -2179,7 +2182,7 @@ export class Accessory extends EventEmitter { return { status: HAPStatus.SUCCESS } } - private handleResource(data: ResourceRequest, callback: ResourceRequestCallback): void { + private handleResource(data: ResourceRequest, callback: ResourceRequestCallback, connection: HAPConnection): void { if (data['resource-type'] === ResourceRequestType.IMAGE) { const aid = data.aid // aid is optionally supplied by HomeKit (for example when camera is bridged, multiple cams, etc) @@ -2197,15 +2200,31 @@ export class Accessory extends EventEmitter { } if (!controller) { - debug('[%s] received snapshot request though no camera controller was associated!') + debug('[%s] received snapshot request though no camera controller was associated!', this.displayName) callback({ httpCode: HAPHTTPCode.NOT_FOUND, status: HAPStatus.RESOURCE_DOES_NOT_EXIST }) return } - controller.handleSnapshotRequest(data['image-height'], data['image-width'], accessory?.displayName, data.reason) + /* The accessory makes the snapshot's signal because the protocol layer is where a request's asker is known to be gone, and the controller runs the + * call: the request's connection closing aborts it, through one close listener and one more max-listener slot, each taken back as the snapshot + * settles, whichever way. A connection that stays open holds nothing of a settled snapshot. A legacy camera's handler is handed no signal. + */ + const asker = new AbortController() + const listener = (): void => asker.abort() + const release = (): void => { + connection.removeListener(HAPConnectionEvent.CLOSED, listener) + connection.setMaxListeners(connection.getMaxListeners() - 1) + } + + connection.setMaxListeners(connection.getMaxListeners() + 1) + connection.on(HAPConnectionEvent.CLOSED, listener) + + controller.handleSnapshotRequest(data['image-height'], data['image-width'], accessory?.displayName, data.reason, asker.signal) .then((buffer) => { + release() callback(undefined, buffer) }, (status: HAPStatus) => { + release() callback({ httpCode: HAPHTTPCode.MULTI_STATUS, status }) }) diff --git a/src/lib/Characteristic.ts b/src/lib/Characteristic.ts index b5872c870..7e1250506 100644 --- a/src/lib/Characteristic.ts +++ b/src/lib/Characteristic.ts @@ -784,6 +784,19 @@ interface TransientAnswer { readonly listener: () => void } +/* The types whose value states a camera's configuration, which the hashed representation writes where it writes `null` for every other value: a hub + * learns a camera's capabilities and its stream tiers from these values alone. A change to one must raise the configuration number as a change to a + * service does. Each is named by its class on `Characteristic` and read at the call, since the generated definitions attach the classes after this module + * loads, and the names are held to the class's own: a misspelled one fails the compile. + */ +const CONFIGURATION_VALUE_TYPES = [ + 'CameraCapabilitiesData', + 'SupportedVideoStreamTiers', + 'SupportedAudioStreamTiers', + 'WebRTCSupportedVideoStreamTiers', + 'WebRTCSupportedAudioStreamTiers', +] as const satisfies readonly (keyof typeof Characteristic)[] + /** * Characteristic represents a particular typed variable that can be assigned to a Service. For instance, a * "Hue" Characteristic might store a 'float' value of type 'arcdegrees'. You could add the Hue Characteristic @@ -3516,16 +3529,19 @@ export class Characteristic extends EventEmitter { } /** - * Returns a JSON representation of this characteristic without the value. + * Returns the JSON representation of this characteristic the configuration number is hashed from: its value is `null`, but for a type whose value + * states a camera's configuration, `CONFIGURATION_VALUE_TYPES`, whose value it holds. A change to that value raises the number. * @private */ internalHAPRepresentation(): CharacteristicJsonObject { assert(this.iid, `iid cannot be undefined for characteristic '${this.displayName}'`) - // TODO include the value for characteristics of the AccessoryInformation service + // TODO the values of the AccessoryInformation service's characteristics state the accessory's configuration too, and could join the list. return { 'type': toShortForm(this.UUID), 'iid': this.iid, - 'value': null, + 'value': CONFIGURATION_VALUE_TYPES.some(name => Characteristic[name].UUID === this.UUID) + ? this.value + : null, 'perms': this.props.perms, 'description': this.props.description || this.displayName, 'format': this.props.format, diff --git a/src/lib/HAPServer.spec.ts b/src/lib/HAPServer.spec.ts index 4c86fba9b..41814d131 100644 --- a/src/lib/HAPServer.spec.ts +++ b/src/lib/HAPServer.spec.ts @@ -1524,13 +1524,26 @@ describe('HAPServer', () => { 'resource-type': ResourceRequestType.IMAGE, } - server.on(HAPServerEventTypes.REQUEST_RESOURCE, (resource, callback) => { + const connections: HAPConnection[] = [] + + server.on(HAPServerEventTypes.ACCESSORIES, (connection, callback) => { + connections.push(connection) + callback(undefined, { accessories: [] }) + }) + server.on(HAPServerEventTypes.REQUEST_RESOURCE, (resource, callback, connection) => { expect(resource).toEqual(request) + connections.push(connection) callback(undefined, image) }) + await client.sendAccessoriesRequest() + const result = await client.sendResourceRequest(request) expect(result).toEqual(image) + + // The listener is handed the connection the request arrived on, the one the client's earlier request reached. + expect(connections).toHaveLength(2) + expect(connections[1]).toBe(connections[0]) }) }) diff --git a/src/lib/HAPServer.ts b/src/lib/HAPServer.ts index 44c4e0901..91cbbccc7 100644 --- a/src/lib/HAPServer.ts +++ b/src/lib/HAPServer.ts @@ -288,7 +288,7 @@ export declare interface HAPServer { event: 'set-characteristics', listener: (connection: HAPConnection, request: CharacteristicsWriteRequest, callback: WriteCharacteristicsCallback) => void ): this - on(event: 'request-resource', listener: (resource: ResourceRequest, callback: ResourceRequestCallback) => void): this + on(event: 'request-resource', listener: (resource: ResourceRequest, callback: ResourceRequestCallback, connection: HAPConnection) => void): this on(event: 'connection-closed', listener: (connection: HAPConnection) => void): this @@ -310,7 +310,7 @@ export declare interface HAPServer { emit(event: 'accessories', connection: HAPConnection, callback: AccessoriesCallback): boolean emit(event: 'get-characteristics', connection: HAPConnection, request: CharacteristicsReadRequest, callback: ReadCharacteristicsCallback): boolean emit(event: 'set-characteristics', connection: HAPConnection, request: CharacteristicsWriteRequest, callback: WriteCharacteristicsCallback): boolean - emit(event: 'request-resource', resource: ResourceRequest, callback: ResourceRequestCallback): boolean + emit(event: 'request-resource', resource: ResourceRequest, callback: ResourceRequestCallback, connection: HAPConnection): boolean emit(event: 'connection-closed', connection: HAPConnection): boolean } @@ -1272,7 +1272,7 @@ export class HAPServer extends EventEmitter { response.writeHead(HAPHTTPCode.OK, { 'Content-Type': HAPMimeTypes.IMAGE_JPEG }) response.end(resource) } - })) + }), connection) } else { response.writeHead(HAPHTTPCode.BAD_REQUEST, { 'Content-Type': HAPMimeTypes.HAP_JSON }) // method not allowed response.end(JSON.stringify({ status: HAPStatus.INVALID_VALUE_IN_REQUEST })) diff --git a/src/lib/Service.ts b/src/lib/Service.ts index 892f8a37e..5efe3ecc0 100644 --- a/src/lib/Service.ts +++ b/src/lib/Service.ts @@ -930,7 +930,8 @@ export class Service extends EventEmitter { this.emitCharacteristicWarningEvent(characteristic, CharacteristicWarningType.TIMEOUT_READ, `The read handler for the characteristic '${characteristic?.displayName }' didn't respond at all! Please check that you properly call the callback!`) - service.characteristics.push(characteristic.internalHAPRepresentation()) // value is set to null + // The representation's value is null, but for a type whose value states a camera's configuration, whose held value stands. + service.characteristics.push(characteristic.internalHAPRepresentation()) } } catch (error) { // thrown inside a timer, this would end the process diff --git a/src/lib/camera/GlobalOperatingMode.spec.ts b/src/lib/camera/GlobalOperatingMode.spec.ts new file mode 100644 index 000000000..c84cf8c74 --- /dev/null +++ b/src/lib/camera/GlobalOperatingMode.spec.ts @@ -0,0 +1,334 @@ +import type { Mock } from 'vitest' + +import type { CharacteristicsWriteRequest } from '../../types.js' +import type { CameraControllerLegacyOptions, CameraControllerOptions, CameraControllerServiceMap } from '../controller/index.js' +import type { CameraGlobalOperatingMode } from '../definitions/index.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { OperatingModeState } from './OperatingModePolicy.js' + +import { describe, expect, it, vi } from 'vitest' + +import { + capabilitiesCameraOptions, + createCameraControllerOptions, + idleStreaming, + NUMBERED_USERNAME, + numberedAccessory, + savedMapOf, + videoSensor, +} from '../../test-utils/cameraFixtures.js' +import { Accessory } from '../Accessory.js' +import { Access, Characteristic } from '../Characteristic.js' +import { CameraController, CameraControllerEvents, DoorbellController } from '../controller/index.js' +import { HAPStatus } from '../HAPServer.js' +import { IdentifierCache } from '../model/IdentifierCache.js' +import { Service } from '../Service.js' +import * as uuid from '../util/uuid.js' + +import '../definitions/index.js' + +const GLOBAL_OPERATING_MODE = 'cameraCapabilities:globalOperatingMode' +const HUB = {} as HAPConnection + +const SENSOR = videoSensor('a1b2c3d4-0000-4000-8000-000000000001') + +const PERSISTED_SLICE: OperatingModeState = { + recordingActive: false, + recordingAudioActive: false, + eventSnapshotsActive: true, + homeKitCameraActive: true, + periodicSnapshotsActive: true, +} + +const GLOBAL_SLICE: OperatingModeState = { + ...PERSISTED_SLICE, + globalStreamingEnabled: false, + operatingModeIndicator: true, + manuallyDisabled: false, + nightVision: false, + thirdPartyCameraActive: false, +} + +function legacyOptions(overrides: Partial = {}): CameraControllerLegacyOptions { + return { + ...createCameraControllerOptions(), + ...overrides, + } +} + +function withCapabilities(): CameraControllerOptions { + return capabilitiesCameraOptions({ + videoSensors: [SENSOR], + streaming: idleStreaming(), + }) +} + +function configured(options: CameraControllerOptions): { camera: CameraController, map: CameraControllerServiceMap } { + const camera = new CameraController(options) + const map = camera.constructServices() + camera.configureServices() + return { camera, map } +} + +function globalOf(map: CameraControllerServiceMap): CameraGlobalOperatingMode { + return map[GLOBAL_OPERATING_MODE] as CameraGlobalOperatingMode +} + +function capabilityKeys(map: CameraControllerServiceMap): string[] { + return Object.keys(map).filter(key => key.startsWith('cameraCapabilities:')) +} + +describe('global operating mode', () => { + it('builds the service with the policy\'s values', () => { + const { map } = configured(withCapabilities()) + const global = globalOf(map) + + expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.ON) + expect(global.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true) + expect(global.getCharacteristic(Characteristic.CameraOperatingModeIndicator).value).toBe(Characteristic.CameraOperatingModeIndicator.ENABLE) + }) + + it('marks the camera state and the status light admin-only on both services and leaves night vision unmarked', () => { + const { camera, map } = configured(withCapabilities()) + const global = globalOf(map) + const legacyIndicator = camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.CameraOperatingModeIndicator) + + expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).props.adminOnlyAccess).toEqual([Access.WRITE]) + expect(global.getCharacteristic(Characteristic.CameraOperatingModeIndicator).props.adminOnlyAccess).toEqual([Access.WRITE]) + expect(global.getCharacteristic(Characteristic.StreamingEnabled).props.adminOnlyAccess).toEqual([Access.WRITE]) + expect(global.getCharacteristic(Characteristic.NightVision).props.adminOnlyAccess).toBeUndefined() + expect(legacyIndicator.props.adminOnlyAccess).toEqual([Access.WRITE]) + }) + + it('marks the legacy operating-mode fields admin-only on a recording camera and leaves recording audio unmarked', () => { + const { camera } = configured(legacyOptions()) + const { operatingModeService, recordingManagementService } = camera.recordingManagement! + + expect(operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).props.adminOnlyAccess).toEqual([Access.WRITE]) + expect(operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive).props.adminOnlyAccess).toEqual([Access.WRITE]) + expect(operatingModeService.getCharacteristic(Characteristic.PeriodicSnapshotsActive).props.adminOnlyAccess).toEqual([Access.WRITE]) + expect(recordingManagementService.getCharacteristic(Characteristic.Active).props.adminOnlyAccess).toEqual([Access.WRITE]) + expect(recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive).props.adminOnlyAccess).toBeUndefined() + }) + + it('adopts a saved service with its cached values and reports no change', () => { + const saved = savedMapOf(new CameraController(withCapabilities())) + const global = globalOf(saved) + global.getCharacteristic(Characteristic.StreamingEnabled).value = false + global.getCharacteristic(Characteristic.CameraOperatingModeIndicator).value = Characteristic.CameraOperatingModeIndicator.DISABLE + const camera = new CameraController(withCapabilities()) + const changes = vi.fn() + const saves = vi.fn() + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, changes) + camera.setupStateChangeDelegate(saves) + + expect(camera.initWithServices(saved)).toBeUndefined() + + camera.configureServices() + + expect(globalOf(saved)).toBe(global) + expect(camera.serialize()!.operatingMode).toMatchObject({ + globalStreamingEnabled: false, + operatingModeIndicator: false, + }) + expect(changes).not.toHaveBeenCalled() + expect(saves).not.toHaveBeenCalled() + }) + + it('constructs the global service under its prefixed key only for a camera with the capabilities block', () => { + expect(capabilityKeys(configured(withCapabilities()).map)).toContain(GLOBAL_OPERATING_MODE) + expect(capabilityKeys(configured(legacyOptions()).map)).toEqual([]) + }) + + it('deletes every prefixed key a camera without the block restores, keeps every other key and reports the change', () => { + const saved = savedMapOf(new CameraController(withCapabilities())) + saved['cameraCapabilities:retired'] = new Service.CameraCapabilities('', '') + const kept = Object.keys(saved).filter(key => !key.startsWith('cameraCapabilities:')) + + const restored = new CameraController(legacyOptions()).initWithServices(saved) + + expect(restored).toBeDefined() + expect(capabilityKeys(restored!)).toEqual([]) + expect(Object.keys(restored!)).toEqual(expect.arrayContaining(kept)) + }) + + it('reconciles the prefixed keys of a doorbell', () => { + const constructed = new DoorbellController(withCapabilities()).constructServices() + const saved = savedMapOf(new DoorbellController(withCapabilities())) + + const restored = new DoorbellController(legacyOptions()).initWithServices(saved) + + expect(capabilityKeys(constructed)).toContain(GLOBAL_OPERATING_MODE) + expect(capabilityKeys(restored!)).toEqual([]) + }) + + it('emits one operating-mode change per write on either projection and none for the refresh', async () => { + const { camera, map } = configured(withCapabilities()) + const changes = vi.fn() + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, changes) + + await camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(0, HUB) + await globalOf(map).getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(1, HUB) + + expect(changes.mock.calls).toEqual([ + [ + { field: 'homeKitCameraActive', value: false, reason: 'write' }, + ], + [ + { field: 'homeKitCameraActive', value: true, reason: 'write' }, + ], + ]) + }) + + // A camera with the capabilities block must record, because one without the recording option throws at its construction, which is why this row resets the global + // service of a recording camera alone. + it('resets the global service at a factory reset run twice', () => { + const { camera, map } = configured(withCapabilities()) + const global = globalOf(map) + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + global.updateCharacteristic(Characteristic.StreamingEnabled, false) + global.updateCharacteristic(Characteristic.CameraOperatingModeIndicator, Characteristic.CameraOperatingModeIndicator.DISABLE) + + camera.handleFactoryReset() + camera.handleFactoryReset() + + expect(global.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.ON) + expect(global.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true) + expect(global.getCharacteristic(Characteristic.CameraOperatingModeIndicator).value).toBe(Characteristic.CameraOperatingModeIndicator.ENABLE) + }) + + it('builds a new global service over the new policy when a removed instance is configured again', () => { + const camera = new CameraController(withCapabilities()) + const first = new Accessory('First', uuid.generate('global-operating-mode-first')) + first.configureController(camera) + const removed = first.getService(Service.CameraGlobalOperatingMode)! + first.removeController(camera) + const second = new Accessory('Second', uuid.generate('global-operating-mode-second')) + + second.configureController(camera) + const global = second.getService(Service.CameraGlobalOperatingMode)! + global.updateCharacteristic(Characteristic.StreamingEnabled, false) + removed.updateCharacteristic(Characteristic.StreamingEnabled, true) + + expect(global).not.toBe(removed) + expect(camera.serialize()!.operatingMode!.globalStreamingEnabled).toBe(false) + }) + + it('serves a stream on a camera with neither recording nor the block after it restores a recording camera with the camera off', async () => { + const recordingCamera = configured(legacyOptions()).camera + recordingCamera.recordingManagement!.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + const { camera } = configured(legacyOptions({ recording: undefined })) + + camera.deserialize(recordingCamera.serialize()!) + + await expect(camera.streamManagements[0].service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest('AAAA', HUB)) + .rejects + .toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + }) + + it('carries the global fields a recording camera without the block restores until a factory reset', async () => { + const { camera } = configured(legacyOptions()) + + camera.deserialize({ + ...camera.serialize()!, + operatingMode: GLOBAL_SLICE, + }) + + await expect(camera.streamManagements[0].service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest('AAAA', HUB)) + .rejects + .toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(camera.serialize()!.operatingMode).toEqual(GLOBAL_SLICE) + + camera.handleFactoryReset() + + expect(camera.serialize()!.operatingMode).toEqual(PERSISTED_SLICE) + }) + + it('carries a slice with the global fields untouched through a camera with neither recording nor the block, and no other slice', () => { + const { camera } = configured(legacyOptions({ recording: undefined })) + + camera.deserialize({ + streamManagements: [], + operatingMode: GLOBAL_SLICE, + }) + + expect(camera.serialize()!.operatingMode).toEqual(GLOBAL_SLICE) + + camera.deserialize({ + streamManagements: [], + operatingMode: PERSISTED_SLICE, + }) + + expect(camera.serialize()!.operatingMode).toBeUndefined() + }) + + it('hands the policy a timed write of Manually Disabled on the global service, one operating-mode change with the written value', async () => { + const { aid, changes, connection, iid, write } = manuallyDisabledCamera() + + connection.timedWritePid = 1337 + + await expect(write({ + characteristics: [ + { aid, iid, value: 1 }, + ], + pid: 1337, + })).resolves.toEqual({ + characteristics: [ + { aid, iid, status: HAPStatus.SUCCESS }, + ], + }) + expect(changes.mock.calls).toEqual([ + [ + { field: 'manuallyDisabled', value: true, reason: 'write' }, + ], + ]) + }) + + it('answers a plain write of Manually Disabled on the global service with an invalid value, the policy hearing no change', async () => { + const { aid, changes, iid, write } = manuallyDisabledCamera() + + await expect(write({ + characteristics: [ + { aid, iid, value: 1 }, + ], + })).resolves.toEqual({ + characteristics: [ + { aid, iid, status: HAPStatus.INVALID_VALUE_IN_REQUEST }, + ], + }) + expect(changes).not.toHaveBeenCalled() + }) +}) + +/* A numbered camera with the capabilities block whose global operating mode service carries Manually Disabled, with the characteristic's numbers, the + * camera's operating-mode changes a mock, and a write that goes through the accessory on one connection, as a hub's does. + */ +function manuallyDisabledCamera(): { + aid: number + changes: Mock + connection: HAPConnection + iid: number + write: (request: CharacteristicsWriteRequest) => Promise +} { + const camera = new CameraController(withCapabilities()) + const cache = new IdentifierCache(NUMBERED_USERNAME) + const accessory = numberedAccessory(camera, cache) + const characteristic = accessory.getService(Service.CameraGlobalOperatingMode)!.addCharacteristic(Characteristic.ManuallyDisabled) + const connection = {} as HAPConnection + const changes = vi.fn() + + // The characteristic joins after the accessory was numbered, which is why it is numbered again. + accessory._assignIDs(cache) + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, changes) + + return { + aid: accessory.aid!, + changes, + connection, + iid: characteristic.iid!, + write: async request => new Promise((resolve) => { + // @ts-expect-error: private access + accessory.handleSetCharacteristics(connection, request, (_error: unknown, written: unknown) => resolve(written)) + }), + } +} diff --git a/src/lib/camera/MotionAttribution.spec.ts b/src/lib/camera/MotionAttribution.spec.ts new file mode 100644 index 000000000..1dff49188 --- /dev/null +++ b/src/lib/camera/MotionAttribution.spec.ts @@ -0,0 +1,987 @@ +import type { CharacteristicChange } from '../Characteristic.js' +import type { CameraControllerOptions, CameraControllerServiceMap } from '../controller/index.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { CameraReporter } from './diagnostics/CameraReporter.js' +import type { CameraProblem } from './diagnostics/problems.js' +import type { OperatingModeChange } from './OperatingModePolicy.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' + +import { + createCameraControllerOptions, + definedEntries, + FIRST_VIDEO_SENSOR, + handPublishedContext, + NUMBERED_ACCESSORY_UUID, + numberedAccessory, + SECOND_VIDEO_SENSOR, + twoSensorCameraOptions, +} from '../../test-utils/cameraFixtures.js' +import { detachedReporter, problemsOf } from '../../test-utils/reporterFixtures.js' +import { settle } from '../../test-utils/settle.js' +import { Accessory } from '../Accessory.js' +import { Access, Characteristic, CharacteristicEventTypes } from '../Characteristic.js' +import { CameraController, CameraControllerEvents, DoorbellController } from '../controller/index.js' +import { HAPStatus } from '../HAPServer.js' +import { AccessoryInfo, PermissionTypes } from '../model/AccessoryInfo.js' +import { IdentifierCache } from '../model/IdentifierCache.js' +import { Service, ServiceEventTypes } from '../Service.js' +import { decodeContributingSensors, encodeContributingSensors } from './capabilities/cameraSensors.js' +import { onCameraProblem } from './diagnostics/problems.js' +import { MotionAttribution } from './MotionAttribution.js' +import { CMAFRecordingManagement } from './recording/CMAFRecordingManagement.js' + +// The first and the second video sensor's UUIDs in the registry's order and in lowercase, as the attribution takes them, and one no camera here has. +const FIRST = FIRST_VIDEO_SENSOR.uuid.toLowerCase() +const SECOND = SECOND_VIDEO_SENSOR.uuid.toLowerCase() +const SENSOR_UUIDS = [FIRST, SECOND] +const UNKNOWN = 'e0000009-0000-4000-8000-000000000009' +const ANOTHER_UNKNOWN = 'e000000a-0000-4000-8000-00000000000a' + +const HUB = {} as HAPConnection + +// The cameras a row wires, removed after it. No listener outlives its row. +const wiredCameras: CameraController[] = [] + +afterEach(() => { + for (const camera of wiredCameras.splice(0)) { + camera.handleControllerRemoved() + } + + vi.restoreAllMocks() +}) + +// An attribution over the given motion sensor and the fixture's video sensors, which hears no edge of Motion Detected, its reporter one of no camera +// unless a row hands its own. +function attributed(sensor = new Service.MotionSensor('', ''), reporter: CameraReporter = detachedReporter()): { attribution: MotionAttribution, sensor: Service } { + return { + attribution: new MotionAttribution(sensor, SENSOR_UUIDS, reporter), + sensor, + } +} + +// The attribution of a configured two-sensor camera whose motion sensor is the given one: each edge of Motion Detected reaches it through the camera +// controller's own listener. +function wired(sensor = new Service.MotionSensor('', '')): { attribution: MotionAttribution, camera: CameraController, sensor: Service } { + const camera = new CameraController({ + ...twoSensorCameraOptions(), + sensors: { motion: sensor }, + }) + + wiredCameras.push(camera) + camera.constructServices() + camera.configureServices() + + // @ts-expect-error: private access + return { attribution: camera.motionAttribution!, camera, sensor } +} + +// The video sensors a motion sensor's Contributing Sensors lists, in its order, as the codec decodes them. +function listed(sensor: Service): string[] { + return decodeContributingSensors(sensor.getCharacteristic(Characteristic.ContributingSensors).value as string).sensorList.map(({ sensorUUID }) => sensorUUID) +} + +// Each write of Contributing Sensors and Motion Detected from here on, in the order their change events arrive. +function writesOf(sensor: Service): string[] { + const writes: string[] = [] + + sensor.getCharacteristic(Characteristic.ContributingSensors).on(CharacteristicEventTypes.CHANGE, () => writes.push('contributing sensors')) + sensor.getCharacteristic(Characteristic.MotionDetected).on(CharacteristicEventTypes.CHANGE, () => writes.push('motion detected')) + + return writes +} + +describe('motion attribution', () => { + it('adds contributing sensors listing none to a sensor at rest, and lists every sensor in registry order on one with motion and a stale list', () => { + const sensor = new Service.MotionSensor('', '') + + expect(sensor.testCharacteristic(Characteristic.ContributingSensors)).toBe(false) + + attributed(sensor) + + expect(sensor.testCharacteristic(Characteristic.ContributingSensors)).toBe(true) + expect(listed(sensor)).toEqual([]) + + const stale = new Service.MotionSensor('', '') + const staleList = encodeContributingSensors({ + sensorList: [ + { sensorUUID: SECOND }, + ], + }) + stale.updateCharacteristic(Characteristic.MotionDetected, true) + stale.getCharacteristic(Characteristic.ContributingSensors).updateValue(staleList) + + attributed(stale) + + expect(listed(stale)).toEqual([FIRST, SECOND]) + }) + + it('lists every sensor in registry order at a direct write of motion detected true', () => { + const { sensor } = wired() + + sensor.updateCharacteristic(Characteristic.MotionDetected, true) + + expect(listed(sensor)).toEqual([FIRST, SECOND]) + }) + + it('lists no sensor at a direct write of motion detected false', () => { + const { sensor } = wired() + sensor.updateCharacteristic(Characteristic.MotionDetected, true) + + sensor.updateCharacteristic(Characteristic.MotionDetected, false) + + expect(listed(sensor)).toEqual([]) + }) + + it('writes the list before the service forwards the motion change at a direct write of motion detected, raised and cleared alike', () => { + const { sensor } = wired() + const forwarded: string[] = [] + sensor.on(ServiceEventTypes.CHARACTERISTIC_CHANGE, ({ characteristic }) => forwarded.push(characteristic.UUID)) + + sensor.updateCharacteristic(Characteristic.MotionDetected, true) + sensor.updateCharacteristic(Characteristic.MotionDetected, false) + + expect(forwarded).toEqual([ + Characteristic.ContributingSensors.UUID, + Characteristic.MotionDetected.UUID, + Characteristic.ContributingSensors.UUID, + Characteristic.MotionDetected.UUID, + ]) + }) + + it('lists every sensor for a report of motion that names none', () => { + const { attribution, sensor } = attributed() + + attribution.report(true) + + expect(listed(sensor)).toEqual([FIRST, SECOND]) + + attribution.report(true, [SECOND]) + attribution.report(true, []) + + expect(listed(sensor)).toEqual([FIRST, SECOND]) + }) + + it('lists each named sensor once in registry order whatever its case, leaving out an unknown one with one warning, and every sensor for all unknown', () => { + const { attribution, sensor } = attributed() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + attribution.report(true, [ + SECOND_VIDEO_SENSOR.uuid, + FIRST, + SECOND, + UNKNOWN, + ]) + + expect(listed(sensor)).toEqual([FIRST, SECOND]) + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain(UNKNOWN) + + warn.mockClear() + attribution.report(true, [UNKNOWN, ANOTHER_UNKNOWN]) + + expect(listed(sensor)).toEqual([FIRST, SECOND]) + expect(warn).toHaveBeenCalledTimes(2) + expect(warn.mock.calls[0][0]).toContain(UNKNOWN) + expect(warn.mock.calls[1][0]).toContain(ANOTHER_UNKNOWN) + }) + + it('rewrites the list and writes no motion detected for a report of motion while motion is detected', () => { + const { attribution, sensor } = attributed() + attribution.report(true) + const writes = writesOf(sensor) + + attribution.report(true, [FIRST]) + + expect(listed(sensor)).toEqual([FIRST]) + expect(writes).toEqual(['contributing sensors']) + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true) + }) + + it('lists no sensor and warns nothing for a report of cleared motion naming an unknown sensor', () => { + const { attribution, sensor } = attributed() + attribution.report(true) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + attribution.report(false, [UNKNOWN]) + + expect(listed(sensor)).toEqual([]) + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + expect(warn).not.toHaveBeenCalled() + }) + + it('writes the list once and then motion detected once for a report of motion at rest', () => { + const { attribution, sensor } = attributed() + const writes = writesOf(sensor) + + attribution.report(true, [SECOND]) + + expect(writes).toEqual(['contributing sensors', 'motion detected']) + expect(listed(sensor)).toEqual([SECOND]) + }) + + it('writes the list once and then motion detected once for a report of cleared motion while motion is detected', () => { + const { attribution, sensor } = attributed() + attribution.report(true) + const writes = writesOf(sensor) + + attribution.report(false) + + expect(writes).toEqual(['contributing sensors', 'motion detected']) + expect(listed(sensor)).toEqual([]) + }) + + it('lists no sensor at a direct write of motion detected false after a report of motion naming the second sensor', () => { + const { attribution, sensor } = wired() + attribution.report(true, [SECOND]) + + sensor.updateCharacteristic(Characteristic.MotionDetected, false) + + expect(listed(sensor)).toEqual([]) + }) + + it('leaves the list at a motion detected write after its camera\'s removal, the service keeping its own listener alone', () => { + const sensor = new Service.MotionSensor('', '') + const motionDetected = sensor.getCharacteristic(Characteristic.MotionDetected) + const own = motionDetected.listenerCount(CharacteristicEventTypes.CHANGE) + const { attribution, camera } = wired(sensor) + + expect(motionDetected.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(own + 1) + + attribution.report(true, [SECOND]) + camera.handleControllerRemoved() + sensor.updateCharacteristic(Characteristic.MotionDetected, false) + + expect(motionDetected.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(own) + expect(listed(sensor)).toEqual([SECOND]) + }) + + it('keeps a named list at a direct write that leaves motion detected as it stands, and writes no motion detected for cleared motion at rest', () => { + const { attribution, sensor } = wired() + attribution.report(true, [SECOND]) + + sensor.updateCharacteristic(Characteristic.MotionDetected, true) + + expect(listed(sensor)).toEqual([SECOND]) + + attribution.report(false) + const writes = writesOf(sensor) + attribution.report(false) + + expect(writes).toEqual(['contributing sensors']) + expect(listed(sensor)).toEqual([]) + }) + + it('lists every sensor for a report whose names are no list, and leaves out an entry that is no string, each with one warning', () => { + const { attribution, sensor } = attributed() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + attribution.report(true, SECOND as unknown as readonly string[]) + + expect(listed(sensor)).toEqual([FIRST, SECOND]) + expect(warn).toHaveBeenCalledTimes(1) + + warn.mockClear() + attribution.report(true, [SECOND, 7] as unknown as readonly string[]) + + expect(listed(sensor)).toEqual([SECOND]) + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('7') + }) + + it.each([ + { + named: [UNKNOWN], + refusal: 'an unknown sensor', + }, + { + named: SECOND as unknown as readonly string[], + refusal: 'names that are no list', + }, + { + named: [7] as unknown as readonly string[], + refusal: 'an entry that is no string', + }, + ])('raises one value-refused problem at the level warning, carrying no field but its accessory, for a report naming $refusal', ({ named }) => { + const { problems, reporter } = problemsOf() + const { attribution } = attributed(new Service.MotionSensor('', ''), reporter) + + attribution.report(true, named) + + // Each problem is read whole, its sentence's wording aside, and a field it gains or loses is read too. + expect(problems).toEqual([ + { + accessoryUUID: expect.any(String), + kind: 'value-refused', + level: 'warning', + sentence: expect.any(String), + }, + ]) + }) + + describe('camera controller wiring', () => { + // The username of an accessory a row pairs and numbers, and the pairings a write arrives under. Each row numbers over an identifier cache of its own. + const USERNAME = 'AA:BB:CC:DD:EE:01' + const ADMIN = 'AA:BB:CC:DD:EE:02' + const USER = 'AA:BB:CC:DD:EE:03' + + // The cameras a row builds, removed after it. No policy or attribution listener outlives its row. + const cameras: CameraController[] = [] + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + }) + + // A camera built from the given options, by default the two-sensor camera with the capabilities block. + function cameraOf(options: CameraControllerOptions = twoSensorCameraOptions()): CameraController { + const camera = new CameraController(options) + + cameras.push(camera) + return camera + } + + // A camera's services, constructed and configured as a first run of the accessory configures them. + function configured(camera: CameraController): CameraControllerServiceMap { + const map = camera.constructServices() + camera.configureServices() + + return map + } + + // A saved accessory as a cached accessory restores at startup, its camera not yet configured. + function cachedAccessory(saved: Accessory): Accessory { + return Accessory.deserialize(Accessory.serialize(saved)) + } + + // Each change of Motion Detected the sensor's service forwards from here on, by its old and new values. + function motionForwarded(sensor: Service): Pick[] { + const forwarded: Pick[] = [] + + sensor.on(ServiceEventTypes.CHARACTERISTIC_CHANGE, ({ characteristic, newValue, oldValue }) => { + if (characteristic.UUID === Characteristic.MotionDetected.UUID) { + forwarded.push({ newValue, oldValue }) + } + }) + + return forwarded + } + + // Each way a plugin writes motion on a motion sensor's Motion Detected, or answers it to a hub's read through a read handler. + const WRITERS = [ + { + read: false, + write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).updateValue(true), + writer: 'updateValue of true', + }, + { + read: false, + write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).updateValue(1), + writer: 'updateValue of 1', + }, + { + read: false, + write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).setValue(true), + writer: 'setValue', + }, + { + read: false, + write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).sendEventNotification(true), + writer: 'sendEventNotification', + }, + { + read: false, + write: async (sensor: Service) => sensor.updateCharacteristic(Characteristic.MotionDetected, true), + writer: 'the service\'s updateCharacteristic', + }, + { + read: false, + write: async (sensor: Service) => sensor.setCharacteristic(Characteristic.MotionDetected, true), + writer: 'the service\'s setCharacteristic', + }, + { + read: true, + write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected).onGet(() => true).handleGetRequest(HUB), + writer: 'an onGet handler\'s answer to a hub\'s read', + }, + { + read: true, + write: async (sensor: Service) => sensor.getCharacteristic(Characteristic.MotionDetected) + .on(CharacteristicEventTypes.GET, callback => callback(null, true)) + .handleGetRequest(HUB), + writer: 'a get listener\'s answer to a hub\'s read', + }, + ] + + it('adds contributing sensors listing none and motion enabled reading on to a block camera\'s own motion sensor', () => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + + expect(sensor.testCharacteristic(Characteristic.ContributingSensors)).toBe(true) + expect(listed(sensor)).toEqual([]) + expect(sensor.getCharacteristic(Characteristic.MotionEnabled).value).toBe(true) + }) + + it('adds neither characteristic to the motion sensor of a camera without the block', () => { + const camera = cameraOf(createCameraControllerOptions()) + configured(camera) + + expect(camera.motionService!.testCharacteristic(Characteristic.ContributingSensors)).toBe(false) + expect(camera.motionService!.testCharacteristic(Characteristic.MotionEnabled)).toBe(false) + }) + + it('raises motion naming the second sensor and clears it, listing the second sensor and then none', () => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + + camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid]) + + expect(listed(sensor)).toEqual([SECOND]) + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true) + + camera.updateMotionDetected(false) + + expect(listed(sensor)).toEqual([]) + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + }) + + it('hands the attribution each edge of a direct write of motion detected once, from the controller\'s one listener', () => { + const motionChanged = vi.spyOn(MotionAttribution.prototype, 'motionChanged') + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + + sensor.updateCharacteristic(Characteristic.MotionDetected, true) + + expect(listed(sensor)).toEqual([FIRST, SECOND]) + + sensor.updateCharacteristic(Characteristic.MotionDetected, false) + + expect(listed(sensor)).toEqual([]) + expect(motionChanged.mock.calls).toEqual([ + [true], + [false], + ]) + }) + + it('hands the attribution the edge of a report once, which leaves the list the report named', () => { + const motionChanged = vi.spyOn(MotionAttribution.prototype, 'motionChanged') + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + + camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid]) + + expect(listed(sensor)).toEqual([SECOND]) + expect(motionChanged.mock.calls).toEqual([ + [true], + ]) + }) + + it('hands the attribution nothing for a repeat, and releases the controller\'s listener at a removal', () => { + const motionChanged = vi.spyOn(MotionAttribution.prototype, 'motionChanged') + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + const motionDetected = sensor.getCharacteristic(Characteristic.MotionDetected) + const listening = motionDetected.listenerCount(CharacteristicEventTypes.CHANGE) + camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid]) + motionChanged.mockClear() + + sensor.updateCharacteristic(Characteristic.MotionDetected, true) + camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid]) + + expect(motionChanged).not.toHaveBeenCalled() + expect(listed(sensor)).toEqual([SECOND]) + + camera.handleControllerRemoved() + + expect(motionDetected.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(listening - 1) + }) + + it('writes motion detected alone on a camera without the block', () => { + const camera = cameraOf(createCameraControllerOptions()) + configured(camera) + + camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid]) + + expect(camera.motionService!.getCharacteristic(Characteristic.MotionDetected).value).toBe(true) + expect(camera.motionService!.testCharacteristic(Characteristic.ContributingSensors)).toBe(false) + }) + + it('warns once and changes nothing for a motion update on a camera without a motion sensor', () => { + // A camera with the block needs its motion sensor unless it is a doorbell, which is why the camera without one is a doorbell with the block. + const camera = new DoorbellController({ + ...twoSensorCameraOptions(), + sensors: { occupancy: true }, + }) + + cameras.push(camera) + + const map = configured(camera) + const before = camera.serialize() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + camera.updateMotionDetected(true, [FIRST]) + + expect(warn).toHaveBeenCalledTimes(1) + expect(camera.motionService).toBeUndefined() + expect(Object.values(map).some(service => service?.UUID === Service.MotionSensor.UUID)).toBe(false) + expect(camera.serialize()).toEqual(before) + }) + + it('reports a motion update on a camera with the block and without a motion sensor as a refused value, printed bare before its configure and ' + + 'published on its accessory\'s channel once it holds that accessory and the channel has a subscriber', async () => { + const sentence = 'The camera has no motion sensor, which means the motion update reaches nothing.' + const camera = new DoorbellController({ + ...twoSensorCameraOptions(), + sensors: { occupancy: true }, + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const problems: CameraProblem[] = [] + + cameras.push(camera) + camera.updateMotionDetected(true) + + expect(warn.mock.calls).toEqual([ + [sentence], + ]) + + configured(camera) + handPublishedContext(camera) + + const subscription = onCameraProblem(NUMBERED_ACCESSORY_UUID, problem => problems.push(problem)) + + onTestFinished(() => { + subscription[Symbol.dispose]() + }) + camera.updateMotionDetected(true, [FIRST]) + await settle() + + expect(problems).toEqual([ + { + accessoryUUID: NUMBERED_ACCESSORY_UUID, + kind: 'value-refused', + level: 'warning', + sentence, + }, + ]) + expect(warn).toHaveBeenCalledOnce() + }) + + it('adds each characteristic only the block adds to a plugin\'s own motion sensor and removes them from it at a restore without the block, where a ' + + 'camera that never had the block keeps what the plugin gave its sensor', () => { + const supplied = new Service.MotionSensor('', '') + const map = configured(cameraOf({ + ...twoSensorCameraOptions(), + sensors: { motion: supplied, occupancy: true }, + })) + + expect(supplied.testCharacteristic(Characteristic.ContributingSensors)).toBe(true) + expect(supplied.testCharacteristic(Characteristic.MotionEnabled)).toBe(true) + + const legacy = cameraOf({ + ...createCameraControllerOptions(), + sensors: { motion: supplied, occupancy: true }, + }) + legacy.initWithServices(definedEntries(map)) + legacy.configureServices() + + expect(legacy.motionService).toBe(supplied) + expect(supplied.testCharacteristic(Characteristic.ContributingSensors)).toBe(false) + expect(supplied.testCharacteristic(Characteristic.MotionEnabled)).toBe(false) + + // A plugin's own sensor on a camera that never had the block carries the Motion Enabled its plugin gave it, and the map that camera saved carries no + // key under the capability prefix. + const own = new Service.MotionSensor('', '') + own.getCharacteristic(Characteristic.MotionEnabled) + const ownOptions = { + ...createCameraControllerOptions(), + sensors: { motion: own, occupancy: true }, + } + const legacySaved = definedEntries(configured(cameraOf(ownOptions))) + + cameraOf(ownOptions).initWithServices(legacySaved) + + expect(Object.keys(legacySaved).filter(key => key.startsWith('cameraCapabilities:'))).toEqual([]) + expect(own.testCharacteristic(Characteristic.MotionEnabled)).toBe(true) + }) + + it('adopts a block camera\'s saved owned sensor a plugin hands back as its own at a restore without the block, removing each characteristic only the ' + + 'block adds', () => { + const saved = definedEntries(configured(cameraOf())) + const owned = saved.motionService! + + const restored = cameraOf({ + ...createCameraControllerOptions(), + sensors: { motion: owned, occupancy: true }, + }) + restored.initWithServices(saved) + + expect(restored.motionService).toBe(owned) + expect(owned.testCharacteristic(Characteristic.ContributingSensors)).toBe(false) + expect(owned.testCharacteristic(Characteristic.MotionEnabled)).toBe(false) + }) + + it('drops each characteristic only the block adds from an owned sensor a block camera saved at a restore without the block, and keeps a legacy camera\'s', () => { + const saved = definedEntries(configured(cameraOf())) + const owned = saved.motionService! + + expect(owned.testCharacteristic(Characteristic.ContributingSensors)).toBe(true) + expect(owned.testCharacteristic(Characteristic.MotionEnabled)).toBe(true) + + const restored = cameraOf(createCameraControllerOptions()) + restored.initWithServices(saved) + + expect(restored.motionService).toBe(owned) + expect(owned.testCharacteristic(Characteristic.ContributingSensors)).toBe(false) + expect(owned.testCharacteristic(Characteristic.MotionEnabled)).toBe(false) + + // A legacy camera's plugin gave its own sensor Motion Enabled, and the map it saved carries no key under the capability prefix. + const legacySaved = definedEntries(configured(cameraOf(createCameraControllerOptions()))) + const legacy = legacySaved.motionService! + legacy.getCharacteristic(Characteristic.MotionEnabled) + + expect(Object.keys(legacySaved).filter(key => key.startsWith('cameraCapabilities:'))).toEqual([]) + + cameraOf(createCameraControllerOptions()).initWithServices(legacySaved) + + expect(legacy.testCharacteristic(Characteristic.MotionEnabled)).toBe(true) + }) + + it('reports motion enabled for a hub write, a factory reset and a restore, each under its reason, and serializes the value each leaves', async () => { + const camera = cameraOf() + configured(camera) + const motionEnabled = camera.motionService!.getCharacteristic(Characteristic.MotionEnabled) + const changes: OperatingModeChange[] = [] + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, change => changes.push(change)) + const heard = (): OperatingModeChange[] => changes.filter(({ field }) => field === 'motionEnabled') + + await motionEnabled.handleSetRequest(false, HUB) + + expect(heard()).toEqual([ + { field: 'motionEnabled', value: false, reason: 'write' }, + ]) + expect(camera.serialize()!.operatingMode!.motionEnabled).toBe(false) + + camera.handleFactoryReset() + + expect(heard().at(-1)).toEqual({ field: 'motionEnabled', value: true, reason: 'reset' }) + expect(camera.serialize()!.operatingMode!.motionEnabled).toBe(true) + + camera.deserialize({ + streamManagements: [], + operatingMode: { + ...camera.serialize()!.operatingMode!, + motionEnabled: false, + }, + }) + + expect(heard().at(-1)).toEqual({ field: 'motionEnabled', value: false, reason: 'restore' }) + expect(heard()).toHaveLength(3) + expect(camera.serialize()!.operatingMode!.motionEnabled).toBe(false) + expect(motionEnabled.value).toBe(false) + }) + + it('refuses a user pairing\'s write of a motion enabled cached without the admin-only mark, leaving the value and the policy', async () => { + const restored = cachedAccessory(numberedAccessory(cameraOf())) + const motionEnabled = restored.getService(Service.MotionSensor)!.getCharacteristic(Characteristic.MotionEnabled) + motionEnabled.setProps({ adminOnlyAccess: null }) + + expect(motionEnabled.props.adminOnlyAccess).toBeUndefined() + + const camera = cameraOf() + const accessory = numberedAccessory(camera, new IdentifierCache(USERNAME), restored) + const changes = vi.fn() + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, changes) + const pairings = AccessoryInfo.create(USERNAME) + pairings.addPairedClient(ADMIN, Buffer.alloc(32, 1), PermissionTypes.ADMIN) + pairings.addPairedClient(USER, Buffer.alloc(32, 2), PermissionTypes.USER) + accessory._accessoryInfo = pairings + + const response = await new Promise((resolve) => { + // @ts-expect-error: private access + accessory.handleSetCharacteristics({ username: USER } as HAPConnection, { + characteristics: [ + { aid: accessory.aid!, iid: motionEnabled.iid!, value: false }, + ], + }, (_error: unknown, written: unknown) => resolve(written)) + }) + + expect(response).toEqual({ + characteristics: [ + { aid: accessory.aid, iid: motionEnabled.iid, status: HAPStatus.INSUFFICIENT_PRIVILEGES }, + ], + }) + expect(motionEnabled.props.adminOnlyAccess).toEqual([Access.WRITE]) + expect(motionEnabled.value).toBe(true) + expect(camera.serialize()!.operatingMode!.motionEnabled).toBe(true) + expect(changes).not.toHaveBeenCalled() + }) + + it('leaves motion detected and motion enabled their service\'s listener alone after a removal, a motion detected write rewriting no list', () => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + camera.updateMotionDetected(true, [SECOND]) + + camera.handleControllerRemoved() + + expect(sensor.getCharacteristic(Characteristic.MotionDetected).listenerCount(CharacteristicEventTypes.CHANGE)).toBe(1) + expect(sensor.getCharacteristic(Characteristic.MotionEnabled).listenerCount(CharacteristicEventTypes.CHANGE)).toBe(1) + + sensor.updateCharacteristic(Characteristic.MotionDetected, false) + + expect(listed(sensor)).toEqual([SECOND]) + }) + + it.each(WRITERS)('stores motion written by $writer while motion enabled reads on, the service forwarding one change to it', async ({ write }) => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + const forwarded = motionForwarded(sensor) + + await write(sensor) + + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true) + expect(forwarded).toEqual([ + { + newValue: true, + oldValue: false, + }, + ]) + }) + + it('stores motion written on its motion detected after a removal, whatever motion enabled is written to after it', () => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + + // The removal's factory reset writes Motion Enabled on before the guard goes, and only a write of off after the removal shows a guard left behind. + camera.handleControllerRemoved() + sensor.getCharacteristic(Characteristic.MotionEnabled).updateValue(false) + + const forwarded = motionForwarded(sensor) + + sensor.getCharacteristic(Characteristic.MotionDetected).updateValue(true) + + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true) + expect(forwarded).toEqual([ + { + newValue: true, + oldValue: false, + }, + ]) + }) + + it('adopts a cached owned sensor with one of each characteristic, its cached motion enabled off standing until the restore writes the field', () => { + const saved = numberedAccessory(cameraOf()) + saved.getService(Service.MotionSensor)!.getCharacteristic(Characteristic.MotionEnabled).updateValue(false) + const camera = cameraOf() + const sensor = numberedAccessory(camera, new IdentifierCache(USERNAME), cachedAccessory(saved)).getService(Service.MotionSensor)! + const motionEnabled = sensor.getCharacteristic(Characteristic.MotionEnabled) + + expect(sensor.characteristics.filter(({ UUID }) => UUID === Characteristic.ContributingSensors.UUID)).toHaveLength(1) + expect(sensor.characteristics.filter(({ UUID }) => UUID === Characteristic.MotionEnabled.UUID)).toHaveLength(1) + expect(motionEnabled.value).toBe(false) + + camera.deserialize({ + streamManagements: [], + operatingMode: { + ...camera.serialize()!.operatingMode!, + motionEnabled: true, + }, + }) + + expect(motionEnabled.value).toBe(true) + }) + + describe('motion enabled off', () => { + /* A cached accessory saved with its motion standing and its Motion Enabled as the row asks, each written into its serialized form, since the saved + * camera's guard stores no motion written while Motion Enabled reads off, and a fresh camera configured on it, as a cached accessory restores at + * startup with no stored operating mode. + */ + function restoredStanding(motionEnabled: boolean): { camera: CameraController, sensor: Service } { + const serialized = Accessory.serialize(numberedAccessory(cameraOf())) + const savedSensor = serialized.services.find(({ UUID }) => UUID === Service.MotionSensor.UUID)! + + for (const characteristic of savedSensor.characteristics) { + if (characteristic.UUID === Characteristic.MotionDetected.UUID) { + characteristic.value = true + } + + if (characteristic.UUID === Characteristic.MotionEnabled.UUID) { + characteristic.value = motionEnabled + } + } + + const camera = cameraOf() + + return { + camera, + sensor: numberedAccessory(camera, new IdentifierCache(USERNAME), Accessory.deserialize(serialized)).getService(Service.MotionSensor)!, + } + } + + it('holds back reported motion and motion written directly, writing no characteristic and raising no problem for a refused report, and lets a ' + + 'reported clear through', async () => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + + await sensor.getCharacteristic(Characteristic.MotionEnabled).handleSetRequest(false, HUB) + + const writes = writesOf(sensor) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + // The refused report names a sensor the camera does not have beside its own, and reads neither. + camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid, UNKNOWN]) + + expect(writes).toEqual([]) + expect(warn).not.toHaveBeenCalled() + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + + // Motion the plugin writes directly is stored as no motion, and a reported clear lists none. + sensor.updateCharacteristic(Characteristic.MotionDetected, true) + + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + + camera.updateMotionDetected(false) + + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + expect(listed(sensor)).toEqual([]) + }) + + it.each(WRITERS)('stores no motion for motion written by $writer, which the clip path does not hear and a read answers as none', async ({ + read, + write, + }) => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + + await sensor.getCharacteristic(Characteristic.MotionEnabled).handleSetRequest(false, HUB) + + const clip = vi.spyOn(CMAFRecordingManagement.prototype, 'motionChanged') + const forwarded = motionForwarded(sensor) + const motionDetected = sensor.getCharacteristic(Characteristic.MotionDetected) + + await write(sensor) + + expect(motionDetected.value).toBe(false) + // A write forwards one change of no motion to no motion, and a read handler's answer forwards none. + expect(forwarded).toEqual(read + ? [] + : [ + { + newValue: false, + oldValue: false, + }, + ]) + expect(listed(sensor)).toEqual([]) + expect(clip).not.toHaveBeenCalled() + expect(await motionDetected.handleGetRequest(HUB)).toBe(false) + }) + + it('answers no motion to a hub\'s read of motion assigned directly to motion detected\'s value, with no read handler', async () => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + const motionDetected = sensor.getCharacteristic(Characteristic.MotionDetected) + + await sensor.getCharacteristic(Characteristic.MotionEnabled).handleSetRequest(false, HUB) + motionDetected.value = true + + expect(await motionDetected.handleGetRequest(HUB)).toBe(false) + }) + + it('clears standing motion at a hub write of motion enabled off, writing an empty list and then motion detected false, and hands the clip path ' + + 'the clear', async () => { + const clip = vi.spyOn(CMAFRecordingManagement.prototype, 'motionChanged') + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + + camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid]) + + const writes = writesOf(sensor) + + await sensor.getCharacteristic(Characteristic.MotionEnabled).handleSetRequest(false, HUB) + + expect(writes).toEqual(['contributing sensors', 'motion detected']) + expect(listed(sensor)).toEqual([]) + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + expect(clip.mock.calls).toEqual([ + [true], + [false], + ]) + }) + + it('clears the motion a cached accessory restored standing at a restore of motion enabled off', () => { + const { camera, sensor } = restoredStanding(true) + + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true) + expect(listed(sensor)).toEqual([FIRST, SECOND]) + + camera.deserialize({ + streamManagements: [], + operatingMode: { + ...camera.serialize()!.operatingMode!, + motionEnabled: false, + }, + }) + + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + expect(listed(sensor)).toEqual([]) + }) + + it('clears the motion a cached accessory restored standing beside motion enabled off at its configure, with no stored operating mode', () => { + const { sensor } = restoredStanding(false) + + expect(sensor.getCharacteristic(Characteristic.MotionEnabled).value).toBe(false) + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + expect(listed(sensor)).toEqual([]) + }) + + it('raises nothing as motion enabled turns on again, and the next report of motion passes', async () => { + const camera = cameraOf() + configured(camera) + const sensor = camera.motionService! + const motionEnabled = sensor.getCharacteristic(Characteristic.MotionEnabled) + + await motionEnabled.handleSetRequest(false, HUB) + camera.updateMotionDetected(true) + + const writes = writesOf(sensor) + + await motionEnabled.handleSetRequest(true, HUB) + + expect(writes).toEqual([]) + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(false) + + camera.updateMotionDetected(true, [SECOND_VIDEO_SENSOR.uuid]) + + expect(sensor.getCharacteristic(Characteristic.MotionDetected).value).toBe(true) + expect(listed(sensor)).toEqual([SECOND]) + }) + }) + + it('serializes the base fields alone in the operating mode of a camera without the block', () => { + const camera = cameraOf(createCameraControllerOptions()) + configured(camera) + + expect(Object.keys(camera.serialize()!.operatingMode!)).toEqual([ + 'recordingActive', + 'recordingAudioActive', + 'eventSnapshotsActive', + 'homeKitCameraActive', + 'periodicSnapshotsActive', + ]) + }) + }) +}) diff --git a/src/lib/camera/MotionZonesManagement.spec.ts b/src/lib/camera/MotionZonesManagement.spec.ts new file mode 100644 index 000000000..374dc529f --- /dev/null +++ b/src/lib/camera/MotionZonesManagement.spec.ts @@ -0,0 +1,1323 @@ +import type { Deferred } from '../../test-utils/settle.js' +import type { CameraControllerCapabilitiesOptions, CameraControllerOptions, CameraControllerServiceMap } from '../controller/index.js' +import type { CameraMotionZones } from '../definitions/index.js' +import type { CameraZonePolygon, CameraZoneVertex } from './capabilities/index.js' +import type { MotionZonesManagementState } from './MotionZonesManagement.js' + +import { Buffer } from 'node:buffer' +import { getEventListeners } from 'node:events' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { + buildEmitterConnection, + capabilitiesCameraOptions, + createCameraControllerOptions, + FIRST_VIDEO_SENSOR, + idleStreaming, + motionZonesFunction, + savedMapOf, + SECOND_VIDEO_SENSOR, + twoSensorCameraOptions, + webRTCStreamingOptions, +} from '../../test-utils/cameraFixtures.js' +import { detachedReporter } from '../../test-utils/reporterFixtures.js' +import { deferred, fakeTimeoutSignals, settle } from '../../test-utils/settle.js' +import { Characteristic } from '../Characteristic.js' +import { CameraController } from '../controller/index.js' +import { HAPStatus } from '../HAPServer.js' +import { Service } from '../Service.js' +import { HAPConnectionEvent } from '../util/eventedhttp.js' +import { CAMERA_SPECIFICATION_VERSION } from './capabilities/cameraSensors.js' +import { CameraZoneApplicationMethod } from './capabilities/index.js' +import { decodeCameraZones, encodeCameraZones } from './capabilities/zones.js' +import { MotionZonesManagement } from './MotionZonesManagement.js' +import { DELEGATE_CALL_TIMEOUT } from './session/settleWithin.js' + +// The first and the second video sensor's UUIDs in lowercase, as the registry keys them. +const FIRST = FIRST_VIDEO_SENSOR.uuid.toLowerCase() +const SECOND = SECOND_VIDEO_SENSOR.uuid.toLowerCase() + +// The zone identifier the rows draw with. +const ZONE = 'a0000001-0000-4000-8000-00000000000a' + +// The Camera Zones value a service starts with, Zone Data Version 2 with no entry, built through the codec as every value here is. +const DEFAULT_ZONES = encodeCameraZones({ zoneDataVersion: 2, zoneData: [] }) +const DEFAULT_STATE: MotionZonesManagementState = { active: true, zones: DEFAULT_ZONES } + +function polygon(identifier: string, vertices: CameraZoneVertex[]): CameraZonePolygon { + return { identifier, vertices } +} + +// A Camera Zones value holding one Zone Data entry of the given polygons. +function zonesValue(...polygons: CameraZonePolygon[]): string { + return encodeCameraZones({ + zoneDataVersion: 2, + zoneData: [ + { method: CameraZoneApplicationMethod.NORMAL, polygons }, + ], + }) +} + +// A triangle inside each fixture sensor's dimensions, and the Zone Data the sensor's function is handed for it. +const TRIANGLE = zonesValue(polygon(ZONE, [ + [0, 0], + [100, 0], + [0, 100], +])) +const TRIANGLE_DATA = decodeCameraZones(TRIANGLE).zoneData + +// A write's answer once it arrives, recorded rather than awaited. A row reads whether a write is still waiting: the status it was refused or failed +// with, or resolved. +function answerOf(write: Promise): { answer?: 'resolved' | HAPStatus } { + const record: { answer?: 'resolved' | HAPStatus } = {} + + write.then(() => { + record.answer = 'resolved' + }, (status: HAPStatus) => { + record.answer = status + }) + + return record +} + +// The managements a row builds, destroyed after it. +const managements: MotionZonesManagement[] = [] + +afterEach(() => { + for (const management of managements.splice(0)) { + management.destroy() + } + + vi.useRealTimers() + vi.restoreAllMocks() +}) + +// A management over the first sensor's dimensions, its motionZones function the fixture's and its saves recorded, over the given saved service or a new one. +function harness(service?: CameraMotionZones): { + management: MotionZonesManagement + motionZones: ReturnType + saves: ReturnType + service: CameraMotionZones + active: Characteristic + zones: Characteristic +} { + const motionZones = motionZonesFunction() + const saves = vi.fn() + const management = new MotionZonesManagement({ + motionZones, + reporter: detachedReporter(), + sensorUUID: FIRST_VIDEO_SENSOR.uuid, + sensorDimensions: { ...FIRST_VIDEO_SENSOR.dimensions }, + }, service) + management.setupStateChangeDelegate(saves) + managements.push(management) + + const built = management.getService() + + return { + management, + motionZones, + saves, + service: built, + active: built.getCharacteristic(Characteristic.Active), + zones: built.getCharacteristic(Characteristic.CameraZones), + } +} + +/* A Camera Zones write of the triangle over a fresh harness, whose function call returns a held promise that a factory reset follows the given number of + * no-op continuations deep, as a plugin's own continuation on the call it was handed can run one. The write waits on the call before the row releases it, + * and its answer is the status it failed with, or resolved. + */ +async function writeWithResetAfterSettling(depth: number): Promise & { answer: 'resolved' | HAPStatus }> { + const built = harness() + const held = deferred() + + built.motionZones.mockImplementationOnce(() => { + let continuation: Promise = held.promise + + for (let turn = 0; turn < depth; turn++) { + continuation = continuation.then(() => undefined) + } + + void continuation.then(() => built.management.handleFactoryReset()) + + return held.promise + }) + + const write = built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection()).then(() => 'resolved' as const, (status: HAPStatus) => status) + await settle() + held.resolve() + const answer = await write + await settle() + + return { ...built, answer } +} + +describe('motionZonesManagement', () => { + // The listener collects each rejection no handler takes during a row, any of which would end a Homebridge process. + const unhandled: unknown[] = [] + const collect = (reason: unknown): void => { + unhandled.push(reason) + } + + beforeEach(() => { + unhandled.length = 0 + process.on('unhandledRejection', collect) + }) + + afterEach(() => { + process.off('unhandledRejection', collect) + }) + + describe('the service', () => { + it('builds the service under the lowercase sensor UUID with the spec version, active on and no zone, and gives an adopted one the defaults', () => { + const { management, service, active, zones } = harness() + + expect(service.UUID).toBe(Service.CameraMotionZones.UUID) + expect(service.subtype).toBe(FIRST) + expect(service.getCharacteristic(Characteristic.Version).value).toBe(CAMERA_SPECIFICATION_VERSION) + expect(active.value).toBe(Characteristic.Active.ACTIVE) + expect(decodeCameraZones(zones.value as string)).toEqual({ zoneDataVersion: 2, zoneData: [] }) + expect(management.serviceKey).toBe(`cameraCapabilities:motionZones:${FIRST}`) + expect(MotionZonesManagement.serviceKey(FIRST_VIDEO_SENSOR.uuid)).toBe(`cameraCapabilities:motionZones:${FIRST}`) + + const saved = new Service.CameraMotionZones('', FIRST) + saved.updateCharacteristic(Characteristic.Active, Characteristic.Active.INACTIVE) + saved.updateCharacteristic(Characteristic.CameraZones, TRIANGLE) + const adopted = harness(saved) + + expect(adopted.service).toBe(saved) + expect(adopted.active.value).toBe(Characteristic.Active.ACTIVE) + expect(adopted.zones.value).toBe(DEFAULT_ZONES) + expect(saved.getCharacteristic(Characteristic.Version).value).toBe(CAMERA_SPECIFICATION_VERSION) + expect(adopted.management.serialize()).toEqual(DEFAULT_STATE) + }) + }) + + describe('writes', () => { + // Each value a write is refused for, and the error class the decoder throws for the ones it cannot decode. + const refusals: { name: string, value: string, decoderError?: ErrorConstructor }[] = [ + { + name: 'a value without its zone data version', + value: Buffer.from([0x02, 0x00]).toString('base64'), + decoderError: TypeError, + }, + { + name: 'a zone data version other than 2', + value: encodeCameraZones({ zoneDataVersion: 1, zoneData: [] }), + decoderError: RangeError, + }, + { + name: 'a value whose framing is cut short', + value: Buffer.from([0x01, 0x05, 0x02]).toString('base64'), + decoderError: Error, + }, + { + name: 'a polygon of two vertices', + value: zonesValue(polygon(ZONE, [ + [0, 0], + [10, 10], + ])), + }, + { + name: 'a vertex beyond the sensor\'s width', + value: zonesValue(polygon(ZONE, [ + [0, 0], + [1921, 0], + [0, 10], + ])), + }, + { + name: 'a vertex beyond the sensor\'s height', + value: zonesValue(polygon(ZONE, [ + [0, 0], + [10, 0], + [0, 1081], + ])), + }, + { + name: 'an identifier repeated within the value', + value: zonesValue(polygon(ZONE, [ + [0, 0], + [100, 0], + [0, 100], + ]), polygon(ZONE, [ + [5, 5], + [50, 5], + [5, 50], + ])), + }, + ] + + it.each(refusals)('refuses $name with one warning, no delegate call and no save, a read answering the zones in force', async ({ value, decoderError }) => { + // The decoder throws the row's class for a value it cannot decode and nothing for one a rule refuses. + let thrown: unknown + + try { + decodeCameraZones(value) + } catch (error) { + thrown = error + } + + expect((thrown as Error | undefined)?.constructor).toBe(decoderError) + + const { management, motionZones, saves, zones } = harness() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + await expect(zones.handleSetRequest(value, buildEmitterConnection())).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain(FIRST) + expect(motionZones).not.toHaveBeenCalled() + expect(zones.value).toBe(DEFAULT_ZONES) + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(saves).not.toHaveBeenCalled() + expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES) + }) + + const accepted: { name: string, value: string }[] = [ + { + name: 'an empty zone list', + value: encodeCameraZones({ zoneDataVersion: 2, zoneData: [] }), + }, + { + name: 'a zone data entry with no polygons', + value: zonesValue(), + }, + { + name: 'a vertex at exactly the sensor\'s width and height', + value: zonesValue(polygon(ZONE, [ + [0, 0], + [1920, 0], + [1920, 1080], + ])), + }, + ] + + it.each(accepted)('accepts $name, telling the delegate once, then setting the value and saving once', async ({ value }) => { + const { management, motionZones, saves, zones } = harness() + + await zones.handleSetRequest(value, buildEmitterConnection()) + + expect(motionZones.mock.calls).toEqual([ + [ + { active: true, zoneData: decodeCameraZones(value).zoneData }, + 'write', + expect.any(AbortSignal), + ], + ]) + expect(zones.value).toBe(value) + expect(management.serialize()).toEqual({ active: true, zones: value }) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('tells the delegate the zones in force and active off at a write of active 0, then sets it and saves once', async () => { + const { management, motionZones, saves, active, zones } = harness() + await zones.handleSetRequest(TRIANGLE, buildEmitterConnection()) + motionZones.mockClear() + saves.mockClear() + + await active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()) + + expect(motionZones.mock.calls).toEqual([ + [ + { active: false, zoneData: TRIANGLE_DATA }, + 'write', + expect.any(AbortSignal), + ], + ]) + expect(active.value).toBe(Characteristic.Active.INACTIVE) + expect(management.serialize()).toEqual({ active: false, zones: TRIANGLE }) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('fails a write the delegate rejects, logging it once and keeping the zones in force, which a read answers', async () => { + const { management, motionZones, saves, zones } = harness() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + motionZones.mockRejectedValueOnce(new Error('The detector failed.')) + + await expect(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining(`The motionZones function failed to apply a write of the motion zones of video sensor ${FIRST}: Error: The detector failed.`), + ], + ]) + expect(zones.value).toBe(DEFAULT_ZONES) + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(saves).not.toHaveBeenCalled() + expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES) + expect(unhandled).toEqual([]) + }) + + it('fails a write the delegate never settles at the delegate call bound with one warning, and runs the next write', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { management, motionZones, saves, active, zones } = harness() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + motionZones.mockReturnValueOnce(deferred().promise) + + const write = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT - 1) + + expect(write.answer).toBeUndefined() + + await vi.advanceTimersByTimeAsync(1) + + expect(write.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain(FIRST) + expect(warn.mock.calls[0][0]).toContain(`within ${DELEGATE_CALL_TIMEOUT / 1000} seconds`) + expect(zones.value).toBe(DEFAULT_ZONES) + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(saves).not.toHaveBeenCalled() + expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES) + + await active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()) + + expect(motionZones).toHaveBeenCalledTimes(2) + expect(management.serialize()).toEqual({ active: false, zones: DEFAULT_ZONES }) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('hands the delegate a zones write and an active write behind it in arrival order, the second seeing the first\'s zones', async () => { + const { motionZones, active, zones } = harness() + const held = deferred() + motionZones.mockReturnValueOnce(held.promise) + + const first = zones.handleSetRequest(TRIANGLE, buildEmitterConnection()) + const second = active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()) + await settle() + + expect(motionZones).toHaveBeenCalledTimes(1) + + held.resolve() + await first + await second + + expect(motionZones.mock.calls).toEqual([ + [ + { active: true, zoneData: TRIANGLE_DATA }, + 'write', + expect.any(AbortSignal), + ], + [ + { active: false, zoneData: TRIANGLE_DATA }, + 'write', + expect.any(AbortSignal), + ], + ]) + }) + + it('saves nothing for an accepted write once the state-change delegate is cleared', async () => { + const { management, saves, zones } = harness() + management.setupStateChangeDelegate(undefined) + + await zones.handleSetRequest(TRIANGLE, buildEmitterConnection()) + + expect(management.serialize()).toEqual({ active: true, zones: TRIANGLE }) + expect(saves).not.toHaveBeenCalled() + }) + + it('applies a write whose delegate settles after the accessory would have answered it as timed out and inside the bound', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { motionZones, saves, zones } = harness() + const held = deferred() + motionZones.mockReturnValueOnce(held.promise) + + // The accessory answers a write it is still waiting on as timed out once its warning and its timeout after the warning have passed. + const write = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await vi.advanceTimersByTimeAsync(10 * 1000) + + expect(write.answer).toBeUndefined() + + held.resolve() + await vi.advanceTimersByTimeAsync(0) + + expect(write.answer).toBe('resolved') + expect(zones.value).toBe(TRIANGLE) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('applies a write whose connection closes while the delegate holds it and saves once', async () => { + const { motionZones, saves, zones } = harness() + const connection = buildEmitterConnection() + const held = deferred() + motionZones.mockReturnValueOnce(held.promise) + + const write = answerOf(zones.handleSetRequest(TRIANGLE, connection)) + await settle() + connection.emit(HAPConnectionEvent.CLOSED) + held.resolve() + await settle() + + expect(write.answer).toBe('resolved') + expect(zones.value).toBe(TRIANGLE) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('refuses a write behind a held one at once, before the held write settles, with no delegate call', async () => { + const { motionZones, zones } = harness() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const held = deferred() + motionZones.mockReturnValueOnce(held.promise) + + const first = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await settle() + const refused = answerOf(zones.handleSetRequest(zonesValue(polygon(ZONE, [ + [0, 0], + [10, 10], + ])), buildEmitterConnection())) + await settle() + + expect(refused.answer).toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(first.answer).toBeUndefined() + expect(motionZones).toHaveBeenCalledTimes(1) + + held.resolve() + await settle() + + expect(first.answer).toBe('resolved') + }) + + it('gives a write queued behind one the delegate holds for most of the bound its own whole bound, counted from its delegate call', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { management, motionZones, saves, active, zones } = harness() + const firstHeld = deferred() + const secondHeld = deferred() + motionZones.mockReturnValueOnce(firstHeld.promise).mockReturnValueOnce(secondHeld.promise) + + const first = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + const second = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())) + await vi.advanceTimersByTimeAsync(25 * 1000) + firstHeld.resolve() + await vi.advanceTimersByTimeAsync(0) + + expect(first.answer).toBe('resolved') + expect(motionZones).toHaveBeenCalledTimes(2) + + // The second write arrived with the first, and a bound counted from its arrival would have cut it here. + await vi.advanceTimersByTimeAsync(10 * 1000) + + expect(second.answer).toBeUndefined() + + secondHeld.resolve() + await vi.advanceTimersByTimeAsync(0) + + expect(second.answer).toBe('resolved') + expect(management.serialize()).toEqual({ active: false, zones: TRIANGLE }) + expect(saves).toHaveBeenCalledTimes(2) + }) + }) + + describe('owner surface', () => { + it('restores a valid slice without a save, telling the delegate unawaited, and keeps the defaults with one warning for a slice it refuses', async () => { + const { management, motionZones, saves, active, zones } = harness() + motionZones.mockReturnValueOnce(deferred().promise) + const slice: MotionZonesManagementState = { active: false, zones: TRIANGLE } + + management.deserialize(slice) + + expect(active.value).toBe(Characteristic.Active.INACTIVE) + expect(zones.value).toBe(TRIANGLE) + expect(management.serialize()).toEqual(slice) + expect(saves).not.toHaveBeenCalled() + expect(motionZones.mock.calls).toEqual([ + [ + { active: false, zoneData: TRIANGLE_DATA }, + 'restore', + expect.any(AbortSignal), + ], + ]) + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + for (const refused of [ + { active: 'false', zones: TRIANGLE }, + { + active: true, + zones: Buffer.from([0x01, 0x05, 0x02]).toString('base64'), + }, + { + active: true, + zones: zonesValue(polygon(ZONE, [ + [0, 0], + [2000, 0], + [0, 10], + ])), + }, + ]) { + const restored = harness() + warn.mockClear() + + restored.management.deserialize(refused as unknown as MotionZonesManagementState) + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain(FIRST) + expect(restored.management.serialize()).toEqual(DEFAULT_STATE) + expect(restored.active.value).toBe(Characteristic.Active.ACTIVE) + expect(restored.zones.value).toBe(DEFAULT_ZONES) + expect(restored.saves).not.toHaveBeenCalled() + expect(restored.motionZones.mock.calls).toEqual([ + [ + { active: true, zoneData: [] }, + 'restore', + expect.any(AbortSignal), + ], + ]) + } + + const failing = harness() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + failing.motionZones.mockRejectedValueOnce(new Error('The detector failed to restore.')) + + failing.management.deserialize(slice) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining(`The motionZones function failed to apply the restored motion zones of video sensor ${FIRST}: Error: The detector failed to restore.`), + ], + ]) + expect(unhandled).toEqual([]) + }) + + it('keeps the defaults with one warning for saved zones that are not canonical base64, though the bytes they decode to hold zones it accepts', () => { + const { management, motionZones, saves, active, zones } = harness() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + // A line feed after the triangle's value, which Node's decoder skips: only the canonical check refuses it. + management.deserialize({ active: false, zones: `${TRIANGLE}\n` }) + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain(FIRST) + expect(warn.mock.calls[0][0]).toContain('not canonical base64') + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(active.value).toBe(Characteristic.Active.ACTIVE) + expect(zones.value).toBe(DEFAULT_ZONES) + expect(saves).not.toHaveBeenCalled() + expect(motionZones.mock.calls).toEqual([ + [ + { active: true, zoneData: [] }, + 'restore', + expect.any(AbortSignal), + ], + ]) + }) + + it('puts the defaults in force at a factory reset, saving once and telling the delegate, whose rejection is logged once', async () => { + const { management, motionZones, saves, active, zones } = harness() + await zones.handleSetRequest(TRIANGLE, buildEmitterConnection()) + await active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()) + motionZones.mockClear() + saves.mockClear() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + motionZones.mockRejectedValueOnce(new Error('The detector failed to reset.')) + + management.handleFactoryReset() + await settle() + + expect(active.value).toBe(Characteristic.Active.ACTIVE) + expect(zones.value).toBe(DEFAULT_ZONES) + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(saves).toHaveBeenCalledTimes(1) + expect(motionZones.mock.calls).toEqual([ + [ + { active: true, zoneData: [] }, + 'reset', + expect.any(AbortSignal), + ], + ]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining(`The motionZones function failed to apply the reset motion zones of video sensor ${FIRST}: Error: The detector failed to reset.`), + ], + ]) + expect(unhandled).toEqual([]) + }) + + it('fails a held write, a write queued behind it and a later write at a destroy, each without a further delegate call, destroyed twice', async () => { + const { management, motionZones, saves, active, zones } = harness() + const held = deferred() + motionZones.mockReturnValueOnce(held.promise) + + const first = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + const queued = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())) + await settle() + management.destroy() + await settle() + const later = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())) + await settle() + + expect(first.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(queued.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(later.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(motionZones).toHaveBeenCalledTimes(1) + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(saves).not.toHaveBeenCalled() + expect(() => management.destroy()).not.toThrow() + }) + + it('fails a held write and a write queued behind it at a factory reset, the defaults standing, and applies a write that arrives after it', async () => { + const { management, motionZones, active, zones } = harness() + const held = deferred() + motionZones.mockReturnValueOnce(held.promise) + + const first = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + const queued = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())) + await settle() + management.handleFactoryReset() + await settle() + + expect(first.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(queued.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(motionZones.mock.calls.map(([, reason]) => reason)).toEqual([ + 'write', + 'reset', + ]) + expect(zones.value).toBe(DEFAULT_ZONES) + expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES) + expect(await active.handleGetRequest()).toBe(Characteristic.Active.ACTIVE) + + held.resolve() + await settle() + + expect(management.serialize()).toEqual(DEFAULT_STATE) + + await active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()) + + expect(motionZones).toHaveBeenCalledTimes(3) + expect(management.serialize()).toEqual({ active: false, zones: DEFAULT_ZONES }) + }) + + // The depths run from a reset that lands while the write still waits on the call, through the turns its wait takes to resume, to one that lands after it. + const resetDepths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + it.each(resetDepths)('keeps the defaults at a factory reset hung at depth %i on a zones write\'s delegate call, which hears the reset last', async (depth) => { + const { management, motionZones, zones } = await writeWithResetAfterSettling(depth) + + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES) + expect(motionZones.mock.calls.map(([, reason]) => reason)).toEqual([ + 'write', + 'reset', + ]) + }) + + it('fails a zones write whose delegate call settled when a factory reset ran before the write\'s turn resumed, saving the reset alone', async () => { + const { answer, management, saves } = await writeWithResetAfterSettling(3) + + expect(answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(saves).toHaveBeenCalledTimes(1) + }) + + it('fails a held active write and a camera zones write queued behind it at a factory reset, the default zones standing', async () => { + const { management, motionZones, active, zones } = harness() + const held = deferred() + motionZones.mockReturnValueOnce(held.promise) + + const first = answerOf(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())) + const queued = answerOf(zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await settle() + management.handleFactoryReset() + held.resolve() + await settle() + + expect(first.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(queued.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(management.serialize()).toEqual(DEFAULT_STATE) + expect(await zones.handleGetRequest()).toBe(DEFAULT_ZONES) + expect(motionZones.mock.calls.map(([, reason]) => reason)).toEqual([ + 'write', + 'reset', + ]) + }) + }) + + describe('a call\'s signal', () => { + // The listeners the management's current generation holds on its abort signal. + function generationListeners(management: MotionZonesManagement): number { + // @ts-expect-error: private access + return getEventListeners(management.generation.signal, 'abort').length + } + + // Each way a row ends a management: a factory reset and a destroy. + const ENDS: ((management: MotionZonesManagement) => void)[] = [ + management => management.handleFactoryReset(), + management => management.destroy(), + ] + + it('hands a write\'s call a signal of its own, aborted while the call is unsettled at its bound, a factory reset and a destroy, each failing the write, ' + + 'and never once the call settled, a rejection after the abort writing no line', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + + // A call still unsettled at its bound. + const bounded = harness() + const boundedCall = deferred() + bounded.motionZones.mockReturnValueOnce(boundedCall.promise) + const boundedWrite = answerOf(bounded.zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await settle() + const boundedSignal = bounded.motionZones.mock.calls[0][2] + + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT - 1) + + expect(boundedSignal.aborted).toBe(false) + + await vi.advanceTimersByTimeAsync(1) + boundedCall.reject(new Error('The detector stopped.')) + await settle() + + expect(boundedSignal.aborted).toBe(true) + expect(boundedWrite.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(warn).toHaveBeenCalledTimes(1) + + // A call still unsettled at a factory reset and at a destroy, the reset's own call of the function finding the write's signal aborted already and + // handed a signal of its own, which is not aborted. + const abortedAtResetCall: boolean[] = [] + const resetCallSignals: [aborted: boolean, isTheWrites: boolean][] = [] + + for (const end of ENDS) { + const built = harness() + built.motionZones.mockReturnValueOnce(deferred().promise) + const write = answerOf(built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await settle() + const signal = built.motionZones.mock.calls[0][2] + + built.motionZones.mockImplementationOnce(async (_zones, _reason, own) => { + abortedAtResetCall.push(signal.aborted) + resetCallSignals.push([own.aborted, own === signal]) + }) + + expect(signal.aborted).toBe(false) + + end(built.management) + await settle() + + expect(signal.aborted).toBe(true) + expect(write.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + expect(abortedAtResetCall).toEqual([true]) + expect(resetCallSignals).toEqual([ + [false, false], + ]) + + // A call that settles, by its value and by its rejection, before its bound, a factory reset or a destroy. + const settlings: ((call: Deferred) => void)[] = [ + call => call.resolve(), + call => call.reject(new Error('The detector failed.')), + ] + + for (const settles of settlings) { + const built = harness() + const call = deferred() + built.motionZones.mockReturnValueOnce(call.promise) + const write = built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection()).catch(() => undefined) + await settle() + const signal = built.motionZones.mock.calls[0][2] + + settles(call) + await write + await settle() + + expect(generationListeners(built.management)).toBe(0) + + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT) + built.management.handleFactoryReset() + built.management.destroy() + + expect(signal.aborted).toBe(false) + } + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining(`The motionZones function failed to apply a write of the motion zones of video sensor ${FIRST}: Error: The detector failed.`), + ], + ]) + expect(unhandled).toEqual([]) + }) + + it('hands a restore\'s and a reset\'s call a signal of its own, which neither a later factory reset nor a destroy aborts, pending or settled, logging ' + + 'each rejection', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const built = harness() + const restoreCall = deferred() + const resetCall = deferred() + built.motionZones.mockReturnValueOnce(restoreCall.promise).mockReturnValueOnce(resetCall.promise) + + built.management.deserialize(DEFAULT_STATE) + built.management.handleFactoryReset() + built.management.handleFactoryReset() + built.management.destroy() + const [restoreSignal, resetSignal] = built.motionZones.mock.calls.map(([, , signal]) => signal) + + expect([restoreSignal.aborted, resetSignal.aborted]).toEqual([false, false]) + + restoreCall.reject(new Error('The detector stopped restoring.')) + resetCall.reject(new Error('The detector stopped resetting.')) + await settle() + + expect([restoreSignal.aborted, resetSignal.aborted]).toEqual([false, false]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining(`The motionZones function failed to apply the restored motion zones of video sensor ${FIRST}: Error: The detector stopped ` + + 'restoring.'), + ], + [ + expect.stringContaining(`The motionZones function failed to apply the reset motion zones of video sensor ${FIRST}: Error: The detector stopped ` + + 'resetting.'), + ], + ]) + + const settled = harness() + settled.management.deserialize(DEFAULT_STATE) + await settle() + settled.management.handleFactoryReset() + await settle() + settled.management.handleFactoryReset() + await settle() + settled.management.destroy() + + expect(settled.motionZones.mock.calls.map(([, , signal]) => signal.aborted)).toEqual([false, false, false]) + expect(unhandled).toEqual([]) + }) + + it('puts no listener on the generation\'s signal while a write\'s, a restore\'s and a reset\'s call are pending', async () => { + const built = harness() + built.motionZones.mockReturnValueOnce(deferred().promise).mockReturnValueOnce(deferred().promise).mockReturnValueOnce(deferred().promise) + + built.management.deserialize(DEFAULT_STATE) + built.management.handleFactoryReset() + const write = answerOf(built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await settle() + + expect(built.motionZones.mock.calls.map(([, reason]) => reason)).toEqual([ + 'restore', + 'reset', + 'write', + ]) + expect(write.answer).toBeUndefined() + expect(generationListeners(built.management)).toBe(0) + }) + + it.each([ + { end: 'a factory reset' }, + { end: 'a destroy' }, + ])('aborts a write\'s signal at $end the sensor\'s function sets off inside its own call, before it returns, the write failing and its rejection ' + + 'writing no line', async ({ end }) => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const built = harness() + const call = deferred() + // What the write's signal reads as the reset's own call of the function is made, and as the reset or the destroy returns inside the write's call. + const read: { atResetCall?: boolean, atReturn?: boolean } = {} + + built.motionZones.mockImplementationOnce(async (_zones, _reason, signal) => { + if (end === 'a factory reset') { + built.motionZones.mockImplementationOnce(async () => { + read.atResetCall = signal.aborted + }) + built.management.handleFactoryReset() + } else { + built.management.destroy() + } + + read.atReturn = signal.aborted + + return call.promise + }) + + const write = answerOf(built.zones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await settle() + call.reject(new Error('The detector was stopped.')) + await settle() + + expect({ + answer: write.answer, + errors: error.mock.calls, + read, + }).toEqual({ + answer: HAPStatus.SERVICE_COMMUNICATION_FAILURE, + errors: [], + read: (end === 'a factory reset') + ? { atResetCall: true, atReturn: true } + : { atReturn: true }, + }) + expect(unhandled).toEqual([]) + }) + }) + + describe('camera controller', () => { + const CAPABILITIES_KEY = 'cameraCapabilities:cameraCapabilities' + const GLOBAL_KEY = 'cameraCapabilities:globalOperatingMode' + const REMOVED_SENSOR = { + ...SECOND_VIDEO_SENSOR, + uuid: 'D3000003-0000-4000-8000-000000000003', + } + const REMOVED = REMOVED_SENSOR.uuid.toLowerCase() + const key = (family: string, sensorUUID: string): string => `cameraCapabilities:${family}:${sensorUUID}` + + // The cameras a row builds, removed after it. No policy listener or management outlives its row. + const cameras: CameraController[] = [] + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + }) + + function cameraOf(options: CameraControllerOptions): CameraController { + const camera = new CameraController(options) + + cameras.push(camera) + return camera + } + + // The two-sensor camera's options with zones on the given sensors, by default every one, each through the function given for it. + function zonedOptions(sensorUUIDs = [FIRST, SECOND], first = motionZonesFunction(), second = motionZonesFunction()): CameraControllerCapabilitiesOptions { + return twoSensorCameraOptions({ + first: sensorUUIDs.includes(FIRST) + ? first + : undefined, + second: sensorUUIDs.includes(SECOND) + ? second + : undefined, + }) + } + + // The given options with the block's webrtc member added. + function withWebRTC(options: CameraControllerCapabilitiesOptions): CameraControllerCapabilitiesOptions { + return { + ...options, + cameraCapabilities: { + ...options.cameraCapabilities!, + webrtc: webRTCStreamingOptions(), + }, + } + } + + // A camera's services, constructed and configured as a first run of the accessory configures them. + function configured(camera: CameraController): CameraControllerServiceMap { + const map = camera.constructServices() + camera.configureServices() + + return map + } + + function zonesKeys(map: CameraControllerServiceMap): string[] { + return Object.keys(map).filter(candidate => candidate.startsWith('cameraCapabilities:motionZones:') && map[candidate] !== undefined) + } + + function zonesOf(map: CameraControllerServiceMap, sensorUUID: string): CameraMotionZones { + return map[key('motionZones', sensorUUID)] as CameraMotionZones + } + + // Each multi-tier and WebRTC stream service's linked services, read as the map keys they stand under. + function streamLinks(map: CameraControllerServiceMap): Record { + const keyOf = (service: unknown): string | undefined => Object.keys(map).find(candidate => map[candidate] === service) + + return Object.fromEntries(Object.keys(map) + .filter(candidate => candidate.startsWith('cameraCapabilities:multiTierStream:') || candidate.startsWith('cameraCapabilities:webRTCStream:')) + .map(candidate => [ + candidate, + map[candidate]!.linkedServices.map(linked => keyOf(linked)!), + ])) + } + + it('builds every configuration from the sensor list it validated, whatever the plugin changes in its list afterward', () => { + const options = zonedOptions([FIRST]) + const camera = cameraOf(options) + const [first, second] = options.cameraCapabilities!.videoSensors + + second.motionZones = motionZonesFunction() + delete first.motionZones + + expect(zonesKeys(configured(camera))).toEqual([ + key('motionZones', FIRST), + ]) + + camera.handleControllerRemoved() + + expect(zonesKeys(configured(camera))).toEqual([ + key('motionZones', FIRST), + ]) + }) + + it('constructs one zones service per listed sensor in registry order whatever the list\'s order, none for an unlisted sensor and none without the member', () => { + const map = configured(cameraOf(zonedOptions([SECOND, FIRST]))) + + expect(zonesKeys(map)).toEqual([ + key('motionZones', FIRST), + key('motionZones', SECOND), + ]) + + for (const sensorUUID of [FIRST, SECOND]) { + expect(zonesOf(map, sensorUUID).UUID).toBe(Service.CameraMotionZones.UUID) + expect(zonesOf(map, sensorUUID).subtype).toBe(sensorUUID) + } + + expect(zonesKeys(configured(cameraOf(zonedOptions([SECOND]))))).toEqual([ + key('motionZones', SECOND), + ]) + expect(zonesKeys(configured(cameraOf(twoSensorCameraOptions())))).toEqual([]) + }) + + it('gives a sensor with a motionZones function a zones service and one without none, and calls the function with the zones, the reason and a signal ' + + 'and no receiver at a write, a restore and a reset', async () => { + const motionZones = motionZonesFunction() + const camera = cameraOf(zonedOptions([FIRST], motionZones)) + const map = configured(camera) + + expect(zonesKeys(map)).toEqual([ + key('motionZones', FIRST), + ]) + + await zonesOf(map, FIRST).getCharacteristic(Characteristic.CameraZones).handleSetRequest(TRIANGLE, buildEmitterConnection()) + camera.deserialize({ + streamManagements: [], + motionZonesManagements: { + [FIRST]: { active: false, zones: TRIANGLE }, + }, + }) + camera.handleFactoryReset() + + expect(motionZones.mock.calls).toEqual([ + [ + { active: true, zoneData: TRIANGLE_DATA }, + 'write', + expect.any(AbortSignal), + ], + [ + { active: false, zoneData: TRIANGLE_DATA }, + 'restore', + expect.any(AbortSignal), + ], + [ + { active: true, zoneData: [] }, + 'reset', + expect.any(AbortSignal), + ], + ]) + expect(motionZones.mock.contexts).toEqual([undefined, undefined, undefined]) + }) + + it('leads a constructed map with the block, the zones keys after the webrtc keys, then every key outside the block', () => { + const map = cameraOf(withWebRTC(zonedOptions())).constructServices() + + expect(Object.keys(map)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + key('multiTierStream', FIRST), + key('multiTierStream', SECOND), + key('webRTCStream', FIRST), + key('webRTCStream', SECOND), + key('motionZones', FIRST), + key('motionZones', SECOND), + 'cameraCapabilities:cameraBufferManagement', + 'cameraCapabilities:cameraKeyManagement', + 'cameraCapabilities:cameraClientCertificateManagement', + 'microphone', + 'speaker', + 'motionService', + 'occupancyService', + 'cameraEventRecordingManagement', + 'cameraOperatingMode', + 'dataStreamTransportManagement', + ]) + expect(map.speaker).toBeUndefined() + }) + + it('links each zones service to its sensor\'s multi-tier stream service alone, leaving the stream services\' links as a camera without zones has them', () => { + const zoned = configured(cameraOf(withWebRTC(zonedOptions()))) + const plain = configured(cameraOf(withWebRTC(twoSensorCameraOptions()))) + + for (const sensorUUID of [FIRST, SECOND]) { + expect(zonesOf(zoned, sensorUUID).linkedServices).toEqual([zoned[key('multiTierStream', sensorUUID)]]) + } + + expect(streamLinks(zoned)).toEqual(streamLinks(plain)) + expect(Object.keys(streamLinks(zoned))).toHaveLength(4) + }) + + it('adopts each saved zones service, creates a missing one and sweeps a removed sensor\'s key at a restore', () => { + const motionZones = motionZonesFunction() + const saved = savedMapOf(cameraOf(capabilitiesCameraOptions({ + videoSensors: [ + { ...FIRST_VIDEO_SENSOR, motionZones }, + { ...REMOVED_SENSOR, motionZones }, + ], + streaming: idleStreaming(), + }))) + const adopted = saved[key('motionZones', FIRST)] + + const restored = cameraOf(zonedOptions([FIRST, SECOND], motionZones, motionZones)).initWithServices(saved)! + + expect(restored).toBe(saved) + expect(restored[key('motionZones', FIRST)]).toBe(adopted) + expect(restored[key('motionZones', SECOND)]!.UUID).toBe(Service.CameraMotionZones.UUID) + expect(restored[key('motionZones', REMOVED)]).toBeUndefined() + expect(zonesKeys(restored)).toEqual([ + key('motionZones', FIRST), + key('motionZones', SECOND), + ]) + }) + + it('serializes and restores each sensor\'s zones slice, carries a removed sensor\'s and a record without the block, and drops it at a reset', async () => { + expect(cameraOf(zonedOptions()).serialize()!.motionZonesManagements).toBeUndefined() + + const camera = cameraOf(zonedOptions()) + const map = configured(camera) + await zonesOf(map, FIRST).getCharacteristic(Characteristic.CameraZones).handleSetRequest(TRIANGLE, buildEmitterConnection()) + + expect(camera.serialize()!.motionZonesManagements).toEqual({ + [FIRST]: { active: true, zones: TRIANGLE }, + [SECOND]: DEFAULT_STATE, + }) + + const restored = cameraOf(zonedOptions([FIRST])) + const restoredMap = configured(restored) + restored.deserialize({ + streamManagements: [], + motionZonesManagements: { + [FIRST]: { active: false, zones: TRIANGLE }, + [SECOND]: { active: false, zones: DEFAULT_ZONES }, + }, + }) + + expect(zonesOf(restoredMap, FIRST).getCharacteristic(Characteristic.CameraZones).value).toBe(TRIANGLE) + expect(restored.serialize()!.motionZonesManagements).toEqual({ + [FIRST]: { active: false, zones: TRIANGLE }, + [SECOND]: { active: false, zones: DEFAULT_ZONES }, + }) + + restored.handleFactoryReset() + + expect(restored.serialize()!.motionZonesManagements).toEqual({ + [FIRST]: DEFAULT_STATE, + }) + + const plain = cameraOf(createCameraControllerOptions()) + const record = { + [SECOND]: { active: false, zones: TRIANGLE }, + } + plain.deserialize({ + streamManagements: [], + motionZonesManagements: record, + }) + + expect(plain.serialize()!.motionZonesManagements).toEqual(record) + + plain.handleFactoryReset() + + expect(plain.serialize()!.motionZonesManagements).toBeUndefined() + + // A record or a slice that is no plain object restores nothing and throws nothing. + for (const motionZonesManagements of [ + [], + { [FIRST]: null }, + ]) { + expect(() => restored.deserialize({ + streamManagements: [], + motionZonesManagements: motionZonesManagements as unknown as Record, + })).not.toThrow() + } + + expect(restored.serialize()!.motionZonesManagements).toEqual({ + [FIRST]: DEFAULT_STATE, + }) + }) + + it('hands the state-change delegate to every zones management, which is how each one\'s accepted write saves the camera', async () => { + const camera = cameraOf(zonedOptions()) + const map = configured(camera) + const saves = vi.fn() + camera.setupStateChangeDelegate(saves) + + await zonesOf(map, FIRST).getCharacteristic(Characteristic.CameraZones).handleSetRequest(TRIANGLE, buildEmitterConnection()) + await zonesOf(map, SECOND).getCharacteristic(Characteristic.Active).handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection()) + + expect(saves).toHaveBeenCalledTimes(2) + + camera.setupStateChangeDelegate(undefined) + await zonesOf(map, SECOND).getCharacteristic(Characteristic.Active).handleSetRequest(Characteristic.Active.ACTIVE, buildEmitterConnection()) + + expect(saves).toHaveBeenCalledTimes(2) + }) + + it('resets every zones management at a factory reset, telling each, and fails a held write at a removal that clears the managements', async () => { + const first = motionZonesFunction() + const second = motionZonesFunction() + const camera = cameraOf(zonedOptions([FIRST, SECOND], first, second)) + const map = configured(camera) + const firstZones = zonesOf(map, FIRST).getCharacteristic(Characteristic.CameraZones) + await firstZones.handleSetRequest(TRIANGLE, buildEmitterConnection()) + first.mockClear() + + camera.handleFactoryReset() + + expect(firstZones.value).toBe(DEFAULT_ZONES) + + for (const motionZones of [first, second]) { + expect(motionZones.mock.calls).toEqual([ + [ + { active: true, zoneData: [] }, + 'reset', + expect.any(AbortSignal), + ], + ]) + } + + const held = deferred() + first.mockReturnValueOnce(held.promise) + const write = answerOf(firstZones.handleSetRequest(TRIANGLE, buildEmitterConnection())) + await settle() + + camera.handleControllerRemoved() + await settle() + + expect(write.answer).toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + // @ts-expect-error: private access + expect(camera.motionZonesManagements.size).toBe(0) + }) + + it('fails a write to a removed camera\'s zones service without a delegate call', async () => { + const motionZones = motionZonesFunction() + const camera = cameraOf(zonedOptions([FIRST, SECOND], motionZones)) + const active = zonesOf(configured(camera), FIRST).getCharacteristic(Characteristic.Active) + + camera.handleControllerRemoved() + motionZones.mockClear() + + await expect(active.handleSetRequest(Characteristic.Active.INACTIVE, buildEmitterConnection())).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(motionZones).not.toHaveBeenCalled() + }) + + it('reports no update and keeps every zones key at a restore of an unchanged zoned map', () => { + const motionZones = motionZonesFunction() + const saved = savedMapOf(cameraOf(withWebRTC(zonedOptions([FIRST, SECOND], motionZones, motionZones)))) + const order = Object.keys(saved) + + expect(cameraOf(withWebRTC(zonedOptions([FIRST, SECOND], motionZones, motionZones))).initWithServices(saved)).toBeUndefined() + expect(Object.keys(saved)).toEqual(order) + expect(zonesKeys(saved)).toEqual([ + key('motionZones', FIRST), + key('motionZones', SECOND), + ]) + }) + }) +}) diff --git a/src/lib/camera/MultiTierStreamManagement.spec.ts b/src/lib/camera/MultiTierStreamManagement.spec.ts new file mode 100644 index 000000000..8623fc78a --- /dev/null +++ b/src/lib/camera/MultiTierStreamManagement.spec.ts @@ -0,0 +1,6781 @@ +import type { Socket } from 'node:dgram' +import type { Mock } from 'vitest' + +import type { ScriptedTierDelegate } from '../../test-utils/cameraFixtures.js' +import type { SampleFixture, WrittenFrame } from '../../test-utils/mp4Fixtures.js' +import type { RTPVectorStream } from '../../test-utils/rtpVectors.js' +import type { Deferred } from '../../test-utils/settle.js' +import type { KeepingSink } from '../../test-utils/talkbackSink.js' +import type { CameraControllerServiceMap, CameraLiveView, CameraRecordingEnd } from '../controller/index.js' +import type { AccessoryInformation, CameraGlobalOperatingMode, CameraMultiTierRTPStreamManagement } from '../definitions/index.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { RTPStreamingControlRequest, RTPStreamingControlResponse } from './capabilities/rtpStreaming.js' +import type { SetupEndpointsResponse, SRTPParameters } from './capabilities/setupEndpoints.js' +import type { CameraDebugEvent } from './diagnostics/debugChannels.js' +import type { CameraProblem } from './diagnostics/problems.js' +import type { MultiTierStreamManagementOptions, MultiTierStreamManagementState } from './MultiTierStreamManagement.js' +import type { StreamingEnabledChange } from './OperatingModePolicy.js' +import type { RecordingPacket } from './RecordingManagement.js' +import type { + CameraVideoSensor, + MultiTierStreamingDelegate, + SensorStreamTiers, + StreamTierMedium, + TalkbackSink, + TierFrame, + TierStream, +} from './StreamingOptions.js' +import type { FrameConsumer, TierDemand, TierHolder } from './TierTable.js' +import type { WebRTCStreamManagementOptions } from './WebRTCStreamManagement.js' + +import { Buffer } from 'node:buffer' +import crypto from 'node:crypto' +import dgram from 'node:dgram' + +import tweetnacl from 'tweetnacl' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { + advanceAsync, + buildEmitterConnection, + capabilitiesCameraOptions, + createCameraControllerOptions, + disposableFor, + disposedOf, + endsOf, + frames, + handPublishedContext, + idleStreaming, + keepStreaming, + NUMBERED_ACCESSORY_UUID, + openingStamp, + pendingStart, + savedMapOf, + scriptedTierDelegate, + signalOf, + streamsOf, + tierSetOf, + videoSensor, + webRTCStreamingOptions, +} from '../../test-utils/cameraFixtures.js' +import { captureDebug, captureDebugEvents } from '../../test-utils/engineDebug.js' +import { HAPHTTPClient } from '../../test-utils/HAPHTTPClient.js' +import { + hvcC, + initializationSegment, + opusSampleEntry, + pictureSample, + soundSample, + TIER_STREAM_PARAMETER_SETS, + tierStreamFragment, + tierStreamInitialization, + visualSampleEntry, + withParameterSets, + writeTierFrame, +} from '../../test-utils/mp4Fixtures.js' +import { PairVerifyClient } from '../../test-utils/PairVerifyClient.js' +import { ReferenceSRTP } from '../../test-utils/ReferenceSRTP.js' +import { detachedReporter, problemsOf } from '../../test-utils/reporterFixtures.js' +import { nalUnit, RTP_VECTORS, tierFrameData, vectorFrameData } from '../../test-utils/rtpVectors.js' +import { deferred, fakeTimeoutSignals, settle, until } from '../../test-utils/settle.js' +import { keepingSink } from '../../test-utils/talkbackSink.js' +import { Accessory, AccessoryEventTypes, Categories, MDNSAdvertiser } from '../Accessory.js' +import { Bridge } from '../Bridge.js' +import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' +import { CameraController, CameraControllerEvents } from '../controller/index.js' +import { HAPStatus } from '../HAPServer.js' +import { AccessoryInfo, PermissionTypes } from '../model/AccessoryInfo.js' +import { Service, ServiceEventTypes } from '../Service.js' +import { awaitEventOnce } from '../util/promise-utils.js' +import * as uuid from '../util/uuid.js' +import { TierBuffer } from './buffer/CameraBuffer.js' +import { CameraSensorIntent, CameraSensorType, decodeCameraCapabilities } from './capabilities/cameraSensors.js' +import { decodeRTPStreamingControlResponse, encodeRTPStreamingControlRequest, RTPStreamingCommand, RTPStreamingStatus } from './capabilities/rtpStreaming.js' +import { decodeSetupEndpointsResponse, encodeSetupEndpointsRequest, SetupEndpointsStatus, SRTPCryptoSuites } from './capabilities/setupEndpoints.js' +import { encodeSupportedAudioStreamTiers, encodeSupportedVideoStreamTiers } from './capabilities/streamTiers.js' +import { GlobalOperatingMode } from './GlobalOperatingMode.js' +import { MultiTierStreamManagement } from './MultiTierStreamManagement.js' +import { OperatingModePolicy } from './OperatingModePolicy.js' +import { FrameCutter } from './rtp/FrameCutter.js' +import { SEQUENCE_RANGE } from './rtp/packetRules.js' +import { DELEGATE_CALL_TIMEOUT } from './session/settleWithin.js' +import { SRTPContext } from './srtp/SRTPContext.js' +import { bestStreamTier } from './StreamingOptions.js' +import { TierPacer } from './TierPacer.js' +import { TierHold, TierTable } from './TierTable.js' + +import '../definitions/index.js' + +const SENSOR_UUID = 'A1B2C3D4-0000-4000-8000-000000000001' +const SERVICE_KEY = 'cameraCapabilities:multiTierStream:a1b2c3d4-0000-4000-8000-000000000001' +const UNKNOWN_SESSION = 'e7f1c3a2-5b4d-4e6f-9a8b-0c1d2e3f4a5b' + +const SENSOR = videoSensor(SENSOR_UUID) + +// The fixture's tiers: video tiers 1 to 3 at payload type 99 and audio tier 1 at payload type 110. +const TIERS = tierSetOf(SENSOR) + +// The master keys and salts the controller writes for its own streams, and the SSRCs its Start names. +const CONTROLLER_KEYS: Record = { + video: { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: Buffer.alloc(16, 0x11), + masterSalt: Buffer.alloc(14, 0x22), + }, + audio: { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: Buffer.alloc(16, 0x33), + masterSalt: Buffer.alloc(14, 0x44), + }, +} +const CONTROLLER_SSRCS: Record = { video: 0xAABBCCDD, audio: 0x11223344 } + +// The RTCP packets a controller sends: a receiver report with one report block, a picture loss indication and a full intra request. +const RECEIVER_REPORT = '81c90007aabbccdd112233440000000000000064000000000000000000000000' +const PICTURE_LOSS = '81ce0002aabbccdd11223344' +const FULL_INTRA_REQUEST = '84ce0004aabbccdd000000001122334407000000' + +interface Harness { + delegate: ScriptedTierDelegate + policy: OperatingModePolicy + global: CameraGlobalOperatingMode + management: MultiTierStreamManagement + service: CameraMultiTierRTPStreamManagement + table: TierTable + changes: StreamingEnabledChange[] +} + +// The controller's end of a session's media: one socket per medium on loopback port 0, each recording every datagram the accessory sends it. +interface Endpoint { + sockets: Record + ports: Record + received: Record +} + +type Prepared = Extract & { sessionIdentifier: string } + +// The managements and sockets a row creates, ended and closed after it. +const managements: MultiTierStreamManagement[] = [] +const sockets: Socket[] = [] + +/* A management over a policy that projects the camera's state through a Camera Global Operating Mode service alone: HomeKit Camera Active has one + * projection, configured as the camera controller configures it unless a row configures it itself. Its tier table is built from the delegate and the tiers + * a row hands it, the fixture's by default, as the camera controller builds a sensor's table, and a row's delegate reaches every demand call. It holds the + * specification's floor of five sessions unless a row hands its own bound, as the camera controller hands the bound its options boundary defaulted, and + * reads the Speaker unmuted unless a row hands its own reader. + */ +function harness(options: Partial> & { + configure?: boolean + service?: CameraMultiTierRTPStreamManagement + tiers?: SensorStreamTiers +} = {}): Harness { + const scripted = scriptedTierDelegate() + const { configure = true, delegate = scripted, reporter = detachedReporter(), service, speakerMuted = () => false, tiers = TIERS, ...overrides } = options + const policy = new OperatingModePolicy() + const global = new GlobalOperatingMode(policy).service + const changes: StreamingEnabledChange[] = [] + const table = new TierTable(delegate, tiers, tier => new TierBuffer(tier), reporter) + const management = new MultiTierStreamManagement({ + delegate, + table, + maxSessions: 5, + onStreamingEnabledChange: change => changes.push(change), + reporter, + speakerMuted, + ...overrides, + }, policy, service) + + managements.push(management) + + if (configure) { + management.configureServices() + } + + return { + delegate: scripted, + policy, + global, + management, + service: management.getService(), + table, + changes, + } +} + +// The UDP sockets the process holds open. +function udpSockets(): number { + return process.getActiveResourcesInfo().filter(name => name === 'UDPWrap').length +} + +async function endpoint(): Promise { + const bound = async (): Promise => new Promise((resolve) => { + const socket = dgram.createSocket('udp4') + sockets.push(socket) + socket.bind(0, '127.0.0.1', () => resolve(socket)) + }) + const video = await bound() + const audio = await bound() + const received: Record = { video: [], audio: [] } + + video.on('message', datagram => received.video.push(datagram)) + audio.on('message', datagram => received.audio.push(datagram)) + + return { + sockets: { video, audio }, + ports: { video: video.address().port, audio: audio.address().port }, + received, + } +} + +function setupRequest(from: Endpoint, sessionIdentifier: string, keys: Record = CONTROLLER_KEYS): string { + return encodeSetupEndpointsRequest({ + sessionIdentifier, + controllerAddress: { + addressVersion: 'ipv4', + address: '127.0.0.1', + videoRTPPort: from.ports.video, + audioRTPPort: from.ports.audio, + }, + videoSRTPParameters: keys.video, + audioSRTPParameters: keys.audio, + }) +} + +async function readSetupEndpoints(service: CameraMultiTierRTPStreamManagement, connection?: HAPConnection): Promise { + return service.getCharacteristic(Characteristic.SetupEndpoints).handleGetRequest(connection) +} + +// Writes Setup Endpoints for a new session and answers the write's own settlement, for a row that reads a write the management fails. +async function writeSetup(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, from: Endpoint): Promise { + return await service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(setupRequest(from, crypto.randomUUID()), connection) +} + +// Writes Setup Endpoints and reads the writer's answer back on its connection, as a hub does. +async function prepare(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, from: Endpoint, sessionIdentifier: string, request?: string): +Promise { + await service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(request ?? setupRequest(from, sessionIdentifier), connection) + + return decodeSetupEndpointsResponse(await readSetupEndpoints(service, connection) as string) +} + +async function control(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, request: RTPStreamingControlRequest): +Promise { + return decodeRTPStreamingControlResponse(await service.getCharacteristic(Characteristic.RTPStreamingControl) + .handleSetRequest(encodeRTPStreamingControlRequest(request), connection) as string) +} + +async function start(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, sessionIdentifier: string, videoTier = 1, audioTier = 1): +Promise { + return (await control(service, connection, { + sessionIdentifier, + command: RTPStreamingCommand.START, + videoTier, + videoSSRC: CONTROLLER_SSRCS.video, + audioTier, + audioSSRC: CONTROLLER_SSRCS.audio, + })).status +} + +async function end(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, sessionIdentifier: string): Promise { + return (await control(service, connection, { sessionIdentifier, command: RTPStreamingCommand.END })).status +} + +// The accessory's answer for a session the row prepares and starts, which every packet the controller receives is verified under. +async function streaming(service: CameraMultiTierRTPStreamManagement, connection: HAPConnection, from: Endpoint, videoTier = 1): Promise { + const sessionIdentifier = crypto.randomUUID() + const answer = await prepare(service, connection, from, sessionIdentifier) + + if (answer.status !== SetupEndpointsStatus.SUCCESS) { + throw new Error(`The Setup Endpoints answered status ${answer.status}.`) + } + + expect(await start(service, connection, sessionIdentifier, videoTier)).toBe(RTPStreamingStatus.SUCCESS) + + return answer as Prepared +} + +// The stream the delegate was handed for a video tier's demand, the latest when the tier had several. +function streamOf(delegate: ScriptedTierDelegate, tierId = 1): TierStream { + return streamsOf(delegate, tierId).at(-1)! +} + +// A holder that holds a tier on the table itself rather than through a session, with a route for a failed tier the row reads. +function scriptedHolder(): TierHolder & { tierFailed: Mock<() => void> } { + return { + tierFailed: vi.fn<() => void>(), + } +} + +// One frame a frame consumer took: the frame as handed over, a copy of its bytes at the hand-over, its timestamp and whether it opened a run. +interface TakenFrame { + readonly frame: TierFrame + readonly data: Buffer + readonly timestamp: number + readonly opensRun: boolean +} + +// A frame consumer that keeps each frame it takes, its bytes copied before the hand-over returns as the contract asks. +function scriptedFrameConsumer(): FrameConsumer & { taken: TakenFrame[] } { + const taken: TakenFrame[] = [] + + return { + taken, + take: (frame, timestamp, opensRun) => { + taken.push({ + frame, + data: Buffer.from(frame.data), + timestamp, + opensRun, + }) + }, + } +} + +// The ends of a video tier's demands: each release of the disposable a start registered, one at each end, a withdrawal's among them. +function endedCalls(delegate: ScriptedTierDelegate, tierId = 1): number { + return endsOf(delegate, tierId) +} + +// Each demand the delegate started has ended once, through the disposable its start registered on the very stream its start handed out, released once +// whether its start settled or was withdrawn while pending. +function expectEndsNameTheirStreams(delegate: ScriptedTierDelegate, demands: number): void { + const streams = streamsOf(delegate) + + expect([ + streams.length, + endsOf(delegate), + ]).toEqual([demands, demands]) + + for (const stream of streams) { + expect(disposedOf(delegate, stream)).toBe(1) + } +} + +// The vectors' HEVC stream, whose frames the rows write, cut at the 1228 octets a demand under the fixture's IPv6 connection cuts. +const HEVC = RTP_VECTORS.stream +const CUT = 1228 + +// The NAL unit header of an HEVC picture slice, TRAIL_R in the lowest temporal sub-layer, which a row's own units open with. +const SLICE = Buffer.from([0x02, 0x01]) + +// A frame of one vector frame's units, at a time in microseconds. +function vectorFrame(stream: RTPVectorStream, index: number, time = 0): TierFrame { + return { + data: vectorFrameData(stream.frames[index]), + time, + } +} + +// A frame of one HEVC slice of a given length, at a time in microseconds. +function sliceFrame(length: number, time = 0, discontinuity = false): WrittenFrame { + return { + data: tierFrameData([ + nalUnit(SLICE, length), + ]), + time, + discontinuity, + } +} + +// A frame written as a keyframe that opens its stream or its run, HEVC's parameter sets in band before its units: a consumer of the live pictures, which +// is sent no picture before a keyframe, is sent it first, and its demand raises no parameter-set problem. +function keyframeWithSets(frame: WrittenFrame): WrittenFrame { + return { + ...frame, + data: withParameterSets(frame.data), + keyframe: true, + } +} + +// A picture sample of a keyframe of one 300-octet slice, its parameter sets in band, which opens its stream or its run. +function keyframeSample(): SampleFixture { + return pictureSample(keyframeWithSets(sliceFrame(300)).data, true) +} + +// The payload of the one aggregation packet a keyframe of a slice of a given length cuts into with its parameter sets: the packet's header, and each unit +// behind its length in two octets. +function setsAggregated(length: number): number { + return 2 + TIER_STREAM_PARAMETER_SETS.reduce((total, unit) => total + 2 + unit.length, 0) + 2 + length +} + +// Each RTP packet a session's medium received, in the order it arrived and unprotected under the session's keys, its sender reports passed over. +function unprotected(answer: Prepared, from: Endpoint, medium: StreamTierMedium): Buffer[] { + const reference = new ReferenceSRTP(medium === 'video' + ? answer.videoSRTPParameters + : answer.audioSRTPParameters) + + return from.received[medium].filter(datagram => datagram[1] !== 200).map(datagram => reference.unprotect(datagram)!) +} + +// The payload a fragmentation unit carries after its three octets of headers at the vectors' size: a unit two octets of header longer than a whole +// number of them is cut into exactly that number of packets. +const FRAGMENT_PAYLOAD = CUT - 12 - 3 + +// A frame of one HEVC slice the cutter makes into exactly the given number of packets, at a time in microseconds. +function burstFrame(packets: number, time = 0): TierFrame { + return { + data: tierFrameData([ + nalUnit(SLICE, SLICE.length + packets * FRAGMENT_PAYLOAD), + ]), + time, + } +} + +// A keyframe the cutter makes into exactly the given number of packets, at a time in microseconds: an aggregation packet of its parameter sets, and the +// fragments of one slice after it. +function burstKeyframe(packets: number, time = 0): WrittenFrame { + return keyframeWithSets(burstFrame(packets - 1, time)) +} + +// One datagram an accessory's socket was handed: the view it was handed, a copy of the view's bytes at the send, and the send's completion, which reports +// no error or the one a row hands it. +interface HeldSend { + readonly view: Buffer + readonly sent: Buffer + readonly complete: () => void + readonly fail: (error: Error) => void +} + +// Holds every packet an accessory's socket is handed with a completion, rather than sending it. A row decides when each send completes and fills a +// sender's pool with sends in flight. A sender report, which takes no completion, is passed over. +function holdSends(socket: Socket): HeldSend[] { + const held: HeldSend[] = [] + + vi.spyOn(socket, 'send').mockImplementation(((view: Buffer, completion?: unknown) => { + if (typeof completion === 'function') { + held.push({ + view, + sent: Buffer.from(view), + complete: () => completion(null), + fail: error => completion(error), + }) + } + }) as unknown as Socket['send']) + + return held +} + +// Completes the first held sends in the order they were made, answering how many of their datagrams still held their bytes from the send at their completion. +function complete(held: HeldSend[], count = held.length): number { + let intact = 0 + + for (const send of held.splice(0, count)) { + intact += send.view.equals(send.sent) + ? 1 + : 0 + send.complete() + } + + return intact +} + +// Completes every send a socket holds, in the order they were made, answering the datagrams they sent. +function flush(held: HeldSend[]): Buffer[] { + const sent = held.map(send => send.sent) + + complete(held) + + return sent +} + +// Holds every packet each of a session's sockets is handed, as holdSends holds one socket's. +function heldSockets(sessionSockets: Record): Record { + return { + video: holdSends(sessionSockets.video), + audio: holdSends(sessionSockets.audio), + } +} + +// Whether a medium's packets, in the order a session sent them, carry sequence numbers that run on one at a time from the first, wrapping as RTP's do. +function unbroken(packets: readonly Buffer[]): boolean { + return packets.every((packet, index) => ((packet.readUInt16BE(2) - packets[0].readUInt16BE(2)) & 0xFFFF) === index) +} + +// A plain RTP packet: version 2, a payload type of 96 and an SSRC of its own, which a talkback row rewrites as a controller's. +function rtpPacket(sequence: number, payloadLength: number): Buffer { + const packet = Buffer.alloc(12 + payloadLength) + packet[0] = 0x80 + packet[1] = 96 + packet.writeUInt16BE(sequence, 2) + packet.writeUInt32BE((sequence * 3000) >>> 0, 4) + packet.writeUInt32BE(0x01020304, 8) + + for (let octet = 12; octet < packet.length; octet++) { + packet[octet] = (octet * 7 + sequence) & 0xFF + } + + return packet +} + +// Sends a datagram, already protected, from the controller's socket for a medium to the accessory's port for it. +function sendDatagram(from: Endpoint, answer: Prepared, medium: StreamTierMedium, packet: Buffer): void { + const port = medium === 'video' + ? answer.accessoryAddress.videoRTPPort + : answer.accessoryAddress.audioRTPPort + + from.sockets[medium].send(packet, port, '127.0.0.1') +} + +// A plain talkback packet as a controller sends it: by default the fixture's audio payload type, 110, and the SSRC the controller's Start names for audio. +function talkbackPacket(sequence: number, { payloadType = 110, ssrc = CONTROLLER_SSRCS.audio } = {}): Buffer { + const packet = rtpPacket(sequence, 40) + packet[1] = payloadType + packet.writeUInt32BE(ssrc, 8) + + return packet +} + +// The accessory's sockets for the session a row prepared last, as a createSocket spy saw them made: its last two, video then audio. +function accessorySockets(createSocket: { mock: { results: { value: unknown }[] } }): Record { + const [video, audio] = createSocket.mock.results.slice(-2).map(result => result.value as Socket) + + return { video, audio } +} + +// The mocks are restored before the real timers return, which is why a row that spies on a mock timer leaves the real one in place for the rows after it. +afterEach(async () => { + vi.restoreAllMocks() + vi.useRealTimers() + + await Promise.all(managements.splice(0).map(async management => management.destroy())) + await Promise.all(sockets.splice(0).map(async socket => new Promise(resolve => socket.close(() => resolve())))) + // A closed socket leaves the process's resources a turn or two after its close callback: the next row reads its base only once every one has gone, and a + // socket a row leaves open holds this hook until it fails. + await until(() => udpSockets() === 0) +}) + +// Lets two turns of the event loop run, which a closed socket takes to leave the process's resources after its close callback returns. +async function released(): Promise { + await settle() + await settle() +} + +describe('multiTierStreamManagement', () => { + describe('construction and status active', () => { + it('builds the service under its sensor with streaming enabled and its static characteristics, and adopts a saved one with its streaming enabled', () => { + const { management, service } = harness() + + expect(service.UUID).toBe(Service.CameraMultiTierRTPStreamManagement.UUID) + expect(service.subtype).toBe(SENSOR_UUID.toLowerCase()) + expect(management.serviceKey).toBe(SERVICE_KEY) + expect(MultiTierStreamManagement.serviceKey(SENSOR_UUID)).toBe(SERVICE_KEY) + expect(service.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true) + expect(service.getCharacteristic(Characteristic.SensorUUID).value).toBe(uuid.write(SENSOR_UUID).toString('base64')) + expect(service.getCharacteristic(Characteristic.SupportedVideoStreamTiers).value).toBe(encodeSupportedVideoStreamTiers(TIERS.videoStreamTiers)) + expect(service.getCharacteristic(Characteristic.SupportedAudioStreamTiers).value).toBe(encodeSupportedAudioStreamTiers(TIERS.audioStreamTiers)) + expect(service.getCharacteristic(Characteristic.SupportedRTPConfiguration).value).toBe('AgEA') + expect(service.getCharacteristic(Characteristic.SetupEndpoints).props).toMatchObject({ transient: true, sensitive: true }) + expect(service.getCharacteristic(Characteristic.RTPStreamingControl).props.transient).toBe(true) + + const saved = new Service.CameraMultiTierRTPStreamManagement('', 'saved') + saved.updateCharacteristic(Characteristic.StreamingEnabled, false) + const adopted = harness({ service: saved }) + + expect(adopted.service).toBe(saved) + expect(saved.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(false) + expect(saved.getCharacteristic(Characteristic.SupportedRTPConfiguration).value).toBe('AgEA') + }) + + it('writes status active from the policy at writeStatusActive, on for a camera that is on and off for one turned off before it, its configure services ' + + 'writing none', () => { + const on = harness() + const saved = new Service.CameraMultiTierRTPStreamManagement('', 'saved') + saved.updateCharacteristic(Characteristic.StatusActive, true) + const off = harness({ configure: false, service: saved }) + const read = (): unknown[] => [on, off].map(({ service }) => service.getCharacteristic(Characteristic.StatusActive).value) + off.global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + + off.management.configureServices() + + const configured = read() + + on.management.writeStatusActive() + off.management.writeStatusActive() + + expect([ + configured, + read(), + ]).toEqual([ + [false, true], + [true, false], + ]) + }) + + it('reads status active through the policy and refuses a start for a direct assignment the derivation never hears', async () => { + const { global, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const sessionIdentifier = crypto.randomUUID() + expect(await prepare(service, connection, from, sessionIdentifier)).toMatchObject({ status: SetupEndpointsStatus.SUCCESS }) + + global.getCharacteristic(Characteristic.HomeKitCameraActive).value = Characteristic.HomeKitCameraActive.OFF + + expect(await start(service, connection, sessionIdentifier)).toBe(RTPStreamingStatus.ERROR) + await expect(service.getCharacteristic(Characteristic.StatusActive).handleGetRequest()).resolves.toBe(false) + }) + }) + + describe('setup endpoints', () => { + it('answers success with the accessory\'s address, its two bound ports, its own keys and two 32-bit SSRCs, for the writer\'s read alone', async () => { + const { service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const sessionIdentifier = crypto.randomUUID() + + const answer = await prepare(service, connection, from, sessionIdentifier) + + expect(answer).toMatchObject({ + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier, + accessoryAddress: { addressVersion: 'ipv4', address: '127.0.0.1' }, + }) + + const { accessoryAddress, audioSRTPParameters, audioSSRC, videoSRTPParameters, videoSSRC } = answer as Prepared + + expect(accessoryAddress.videoRTPPort).toBeGreaterThan(0) + expect(accessoryAddress.audioRTPPort).toBeGreaterThan(0) + expect(accessoryAddress.videoRTPPort).not.toBe(accessoryAddress.audioRTPPort) + for (const parameters of [videoSRTPParameters, audioSRTPParameters]) { + expect(parameters.cryptoSuite).toBe(SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80) + expect(parameters.masterKey).toHaveLength(16) + expect(parameters.masterSalt).toHaveLength(14) + expect(parameters.masterKey.equals(CONTROLLER_KEYS.video.masterKey)).toBe(false) + } + for (const ssrc of [videoSSRC, audioSSRC]) { + expect(Number.isInteger(ssrc) && ssrc >= 0 && ssrc < 0x100000000).toBe(true) + } + expect(videoSSRC).not.toBe(audioSSRC) + await expect(readSetupEndpoints(service, buildEmitterConnection())).resolves.toBe('AgEC') + await expect(readSetupEndpoints(service)).resolves.toBe('AgEC') + }) + + it('answers error naming the session for a refused suite, a short key, status active off and no local address, binding nothing', async () => { + const { service } = harness() + const from = await endpoint() + const createSocket = vi.spyOn(dgram, 'createSocket') + const refusedAs = async (connection: HAPConnection, request: string, sessionIdentifier: string): Promise => { + expect(await prepare(service, connection, from, sessionIdentifier, request)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier }) + } + + const suite = crypto.randomUUID() + await refusedAs(buildEmitterConnection(), setupRequest(from, suite, { + ...CONTROLLER_KEYS, + video: { ...CONTROLLER_KEYS.video, cryptoSuite: SRTPCryptoSuites.AES_CM_256_HMAC_SHA1_80 }, + }), suite) + + const key = crypto.randomUUID() + await refusedAs(buildEmitterConnection(), setupRequest(from, key, { + ...CONTROLLER_KEYS, + audio: { + ...CONTROLLER_KEYS.audio, + masterKey: Buffer.alloc(15, 0x33), + }, + }), key) + + const addressless = buildEmitterConnection() + vi.spyOn(addressless, 'getLocalAddress').mockImplementation(() => { + throw new Error('The interface has no IPv4 address.') + }) + const local = crypto.randomUUID() + await refusedAs(addressless, setupRequest(from, local), local) + + service.updateCharacteristic(Characteristic.StreamingEnabled, false) + const disabled = crypto.randomUUID() + await refusedAs(buildEmitterConnection(), setupRequest(from, disabled), disabled) + + expect(createSocket).not.toHaveBeenCalled() + }) + + it('answers busy once prepared sessions over five connections fill the service, and admits a sixth at a maxSessions of 6', async () => { + const from = await endpoint() + const sessionIdentifier = crypto.randomUUID() + const filled = async (service: CameraMultiTierRTPStreamManagement): Promise => { + for (let index = 0; index < 5; index++) { + expect(await prepare(service, buildEmitterConnection(), from, crypto.randomUUID())).toMatchObject({ status: SetupEndpointsStatus.SUCCESS }) + } + } + + const { service } = harness() + await filled(service) + + expect(await prepare(service, buildEmitterConnection(), from, sessionIdentifier)).toEqual({ status: SetupEndpointsStatus.BUSY, sessionIdentifier }) + + const wider = harness({ maxSessions: 6 }) + await filled(wider.service) + + expect(await prepare(wider.service, buildEmitterConnection(), from, sessionIdentifier)).toMatchObject({ status: SetupEndpointsStatus.SUCCESS }) + }) + + it('answers error to another connection naming a held identifier, and unknown session identifier to its start and its end', async () => { + const { service } = harness() + const from = await endpoint() + const owner = buildEmitterConnection() + const other = buildEmitterConnection() + const sessionIdentifier = crypto.randomUUID() + await prepare(service, owner, from, sessionIdentifier) + + expect(await prepare(service, other, from, sessionIdentifier)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier }) + expect(await start(service, other, sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(await end(service, other, sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(await start(service, owner, sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('replaces a connection\'s prepared session at its next write, closing its sockets, and refuses a streaming session\'s identifier', async () => { + const { service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const first = crypto.randomUUID() + const second = crypto.randomUUID() + + const replaced = await prepare(service, connection, from, first) + const again = await prepare(service, connection, from, first) + await released() + + expect(again).toMatchObject({ status: SetupEndpointsStatus.SUCCESS, sessionIdentifier: first }) + expect(again).not.toEqual(replaced) + expect(udpSockets()).toBe(base + 2) + + expect(await prepare(service, connection, from, second)).toMatchObject({ status: SetupEndpointsStatus.SUCCESS }) + await released() + + expect(udpSockets()).toBe(base + 2) + expect(await start(service, connection, first)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(await start(service, connection, second)).toBe(RTPStreamingStatus.SUCCESS) + expect(await prepare(service, connection, from, second)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier: second }) + }) + + it('ends a prepared session at the prepare timeout and releases its answer, and never a started one', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const base = udpSockets() + const idle = buildEmitterConnection() + const active = buildEmitterConnection() + const abandoned = crypto.randomUUID() + await prepare(service, idle, from, abandoned) + const started = await streaming(service, active, from) + + // The started session's tier hands over pictures through the wait, which keeps its demand inside its silence bounds. + await keepStreaming([ + streamOf(delegate), + ], 59999, { advance: advanceAsync }) + + expect(decodeSetupEndpointsResponse(await readSetupEndpoints(service, idle) as string)).toMatchObject({ status: SetupEndpointsStatus.SUCCESS }) + + await vi.advanceTimersByTimeAsync(1) + await until(() => udpSockets() === base + 2) + + await expect(readSetupEndpoints(service, idle)).resolves.toBe('AgEC') + expect(await start(service, idle, abandoned)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(await end(service, active, started.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + await until(() => udpSockets() === base) + }) + + it('refuses an undecodable write to either control point and a plugin\'s write with invalid value in request, holding nothing', async () => { + const { service } = harness() + const connection = buildEmitterConnection() + + for (const type of [Characteristic.SetupEndpoints, Characteristic.RTPStreamingControl]) { + const characteristic = service.getCharacteristic(type) + const plugin = encodeRTPStreamingControlRequest({ sessionIdentifier: UNKNOWN_SESSION, command: RTPStreamingCommand.END }) + + await expect(characteristic.handleSetRequest('AAAA', connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + await expect(characteristic.handleSetRequest(plugin)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + await expect(readSetupEndpoints(service, connection)).resolves.toBe('AgEC') + await expect(service.getCharacteristic(Characteristic.RTPStreamingControl).handleGetRequest(connection)).resolves.toBe('') + expect(connection.listenerCount('closed')).toBe(0) + }) + + it('writes the key and salt lengths in its debug events and never their bytes, in a sentence or in any detail', async () => { + const { service } = harness() + const from = await endpoint() + const events = captureDebugEvents('HAP-NodeJS:Camera:MultiTier') + const answer = await prepare(service, buildEmitterConnection(), from, crypto.randomUUID()) + const { audioSRTPParameters, videoSRTPParameters } = answer as Prepared + + // Each debug event is read whole, its sentence and every detail it carries, as a subscriber of the channel hears it. + const written = events.map(event => JSON.stringify(event)) + + expect(events.map(({ sentence }) => sentence).join('\n')).toContain('controller key lengths 16 and 16 and salt lengths 14 and 14') + + for (const event of written) { + for (const secret of [ + CONTROLLER_KEYS.video.masterKey, + CONTROLLER_KEYS.video.masterSalt, + CONTROLLER_KEYS.audio.masterKey, + CONTROLLER_KEYS.audio.masterSalt, + videoSRTPParameters.masterKey, + videoSRTPParameters.masterSalt, + audioSRTPParameters.masterKey, + audioSRTPParameters.masterSalt, + ]) { + expect(event).not.toContain(secret.toString('hex')) + expect(event).not.toContain(secret.toString('base64')) + } + + expect(event).not.toContain('"type":"Buffer"') + } + }) + }) + + describe('start and the tier demands', () => { + it('starts one demand for the video tier a Start joins, its picture and its sound alike, calling the delegate with the sensor, the tier and the ' + + 'stream', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + await streaming(service, buildEmitterConnection(), from) + + expect(delegate.tierDemandStarted.mock.calls).toEqual([ + [ + streamOf(delegate), + expect.any(AbortSignal), + ], + ]) + expect(streamOf(delegate).tier).toMatchObject({ + id: 1, + sensorUUID: SENSOR_UUID.toLowerCase(), + }) + expect(streamOf(delegate).statistics().consumers).toBe(2) + + // The plugin writes a keyframe, which the first session is sent, before a second session's Start joins the same demand. + writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300))) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 1) + await streaming(service, buildEmitterConnection(), from) + + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + }) + + it('calls the delegate once for each video tier a consumer raises, picture or sound, with the stream its demand hands out, and never for the audio tier', + async () => { + const { delegate, table } = harness() + const tiers = [ + ...table.videoTiers.values(), + ] + const holds = tiers.map((tier, index) => table.joinFrames(tier, index === 0 + ? 'audio' + : 'video', scriptedHolder(), scriptedFrameConsumer())) + + expect(tiers.length).toBeGreaterThan(1) + expect(delegate.tierDemandStarted.mock.calls).toEqual(tiers.map(({ demand }) => [ + demand, + expect.any(AbortSignal), + ])) + expect(streamsOf(delegate).map(({ tier }) => [tier.sensorUUID, tier.id])).toEqual(tiers.map(({ tierId }) => [ + SENSOR_UUID.toLowerCase(), + tierId, + ])) + + for (const hold of holds) { + hold.release() + } + + await settle() + }) + + it('cuts a demand\'s frames at the size the listening family decides, a 1300-octet unit whole under IPv4 and in two fragments under the default', async () => { + const unit = nalUnit(SLICE, 1300) + + for (const [family, types] of [ + [ + 'IPv4', + [1], + ], + [ + 'IPv6', + [49, 49], + ], + ] as const) { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, family === 'IPv4' + ? buildEmitterConnection('IPv4') + : buildEmitterConnection(), from) + + // The stream opens on a keyframe of one aggregation packet, and the unit's frame a frame's length after it is the one the row reads. + writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300))) + writeTierFrame(streamOf(delegate), 'video', { + data: tierFrameData([unit]), + time: 33333, + }) + await vi.advanceTimersByTimeAsync(34) + await until(() => from.received.video.length === 1 + types.length) + await settle() + + const packets = unprotected(answer, from, 'video').slice(1) + + // A single NAL unit packet carries the unit with its own header, and a fragmentation unit carries the bytes after that header behind three octets. + const data = packets.map(packet => packet.subarray(types.length === 1 + ? 14 + : 15)) + + expect({ + family, + types: packets.map(packet => (packet[12] >> 1) & 0x3F), + }).toEqual({ family, types }) + expect(Buffer.concat(data).equals(unit.subarray(SLICE.length))).toBe(true) + } + }) + + it('sends the session whose Start raises a demand the stream written inside its tierDemandStarted, timed and counted, throwing nothing from the write', + async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const moment = performance.now() + const thrown: unknown[] = [] + // A fragment of one picture sample of a 300-octet slice at a decode time, each run's first a keyframe carrying its parameter sets. + const picture = (decodeTime: bigint, keyframe = false): Buffer => tierStreamFragment({ + picture: [ + keyframe + ? keyframeSample() + : pictureSample(sliceFrame(300).data), + ], + pictureTime: decodeTime, + }) + + delegate.tierDemandStarted.mockImplementationOnce(async (stream) => { + const now = vi.spyOn(performance, 'now').mockReturnValue(moment) + + try { + stream.write(tierStreamInitialization()) + stream.write(picture(0n, true)) + } catch (error) { + thrown.push(error) + } finally { + now.mockRestore() + } + }) + + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + const opening = vi.spyOn(performance, 'now').mockReturnValue(moment) + + await vi.advanceTimersByTimeAsync(0) + opening.mockRestore() + + // A sample one interval after the first, five seconds later, is placed by its time's distance from the first, and the sample after a discontinuity at + // that moment at the moment's own timestamp: the reopened run stands 450000 ticks after the first sample, and the later sample one interval after it. + const later = vi.spyOn(performance, 'now').mockReturnValue(moment + 5000) + stream.write(picture(3000n)) + stream.discontinuity() + stream.write(picture(0n, true)) + await vi.advanceTimersByTimeAsync(0) + later.mockRestore() + await until(() => from.received.video.length === 3) + + const [inside, placed, reopened] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4)) + + expect(thrown).toEqual([]) + expect([(placed - inside) >>> 0, (reopened - inside) >>> 0]).toEqual([3000, 450000]) + expect(stream.statistics()).toEqual({ + packets: 3, + bytes: 2 * (12 + setsAggregated(300)) + (12 + 300), + drops: 0, + consumers: 2, + }) + }) + + it('sends the session whose Start raises a demand the picture and the sound its plugin writes inside tierDemandStarted, in a turn after the Start\'s ' + + 'joins', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + + delegate.tierDemandStarted.mockImplementationOnce(async (stream) => { + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + ], + sound: [ + soundSample(Buffer.alloc(60, 0x78)), + ], + })) + }) + + const answer = await streaming(service, buildEmitterConnection(), from) + + // Nothing is sent inside the plugin's call: the pacer sends the picture and the sound in its own turn. + expect(streamOf(delegate).statistics().packets).toBe(0) + + await vi.advanceTimersByTimeAsync(0) + await until(() => (from.received.video.length === 1) && (from.received.audio.length === 1)) + + expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).length)).toEqual([ + setsAggregated(300), + ]) + expect(unprotected(answer, from, 'audio').map(packet => packet.subarray(12))).toEqual([ + Buffer.alloc(60, 0x78), + ]) + }) + + it('answers busy for a demand whose start rejects or never settles, the refused stream ignoring every write with no end sent, and one cut at its bound ' + + 'withdrawn and ended once', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const refused = crypto.randomUUID() + await prepare(service, connection, from, refused) + delegate.tierDemandStarted.mockImplementation(async () => { + throw new Error('The encoder is busy.') + }) + + expect(await start(service, connection, refused)).toBe(RTPStreamingStatus.BUSY) + await settle() + + // A stream of one picture sample and one sound sample larger than a payload, which a live demand would send and count as dropped. + const refusedStream = streamOf(delegate) + refusedStream.write(tierStreamInitialization()) + refusedStream.write(tierStreamFragment({ + picture: [ + pictureSample(sliceFrame(300).data), + ], + sound: [ + soundSample(Buffer.alloc(CUT)), + ], + })) + + expect(endedCalls(delegate)).toBe(0) + expect(refusedStream.statistics()).toEqual({ + packets: 0, + bytes: 0, + drops: 0, + consumers: 0, + }) + + delegate.tierDemandStarted.mockReset() + const pending = pendingStart(delegate) + const cut = start(service, connection, refused) + await vi.advanceTimersByTimeAsync(29999) + + expect(warn).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + + expect(await cut).toBe(RTPStreamingStatus.BUSY) + await settle() + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('did not settle tierDemandStarted for the video tier 1') + expect(endedCalls(delegate)).toBe(1) + expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(true) + + // The withdrawal released what the start registered, and its later settling releases nothing more. + pending.resolve() + await settle() + + expect(disposedOf(delegate, streamOf(delegate))).toBe(1) + }) + + it('waits the delegate call bound for a start that never settles, answering the Start nothing before it, then answers busy with one warning', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + await prepare(service, connection, from, identifier) + delegate.tierDemandStarted.mockImplementation(async () => new Promise(() => undefined)) + + let answered = false + const cut = start(service, connection, identifier).then((status) => { + answered = true + + return status + }) + await vi.advanceTimersByTimeAsync(29999) + + expect(answered).toBe(false) + expect(warn).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + + expect(await cut).toBe(RTPStreamingStatus.BUSY) + await settle() + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('did not settle tierDemandStarted for the video tier 1') + }) + + it('answers busy at the bound for a start that never settles, withdrawing the one demand it waited on for both media with one warning and ending it once', + async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + await prepare(service, connection, from, identifier) + const pending = pendingStart(delegate) + + const cut = start(service, connection, identifier) + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT) + + expect(await cut).toBe(RTPStreamingStatus.BUSY) + await settle() + expect(warn).toHaveBeenCalledTimes(1) + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + expect(endedCalls(delegate)).toBe(1) + expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(true) + + // The withdrawal released what the start registered, and its later settling releases nothing more. + pending.resolve() + await settle() + + expect(disposedOf(delegate, streamOf(delegate))).toBe(1) + }) + + it('answers busy at 30 seconds from the start\'s call, and nothing before, to a Start that joins at 20 seconds a pending demand whose earlier Start\'s ' + + 'session closed at 10 seconds, with the demand\'s one warning and no other line, its session left prepared', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service } = harness() + const earlierEndpoint = await endpoint() + const laterEndpoint = await endpoint() + const earlier = buildEmitterConnection() + const later = buildEmitterConnection() + const earlierIdentifier = crypto.randomUUID() + const laterIdentifier = crypto.randomUUID() + await prepare(service, earlier, earlierEndpoint, earlierIdentifier) + await prepare(service, later, laterEndpoint, laterIdentifier) + pendingStart(delegate) + + // The earlier Start raises the demand and waits on it until its connection closes at 10 seconds, which leaves the demand ending. + const leaving = start(service, earlier, earlierIdentifier) + await vi.advanceTimersByTimeAsync(10000) + earlier.emit('closed') + + expect(await leaving).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + + await vi.advanceTimersByTimeAsync(10000) + + let answered = false + const joining = start(service, later, laterIdentifier).then((status) => { + answered = true + + return status + }) + await vi.advanceTimersByTimeAsync(9999) + await settle() + + expect([answered, warn.mock.calls.length]).toEqual([false, 0]) + + await vi.advanceTimersByTimeAsync(1) + await settle() + + expect(answered).toBe(true) + expect(await joining).toBe(RTPStreamingStatus.BUSY) + expect(warn.mock.calls).toEqual([ + [ + `MultiTierStreamingDelegate did not settle tierDemandStarted for the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" within 30 ` + + 'seconds: the demand is withdrawn and every join waiting on it is refused.', + ], + ]) + expect(error).not.toHaveBeenCalled() + + // The session stays prepared, and a Start retried on it raises a new demand, which starts. + expect(await start(service, later, laterIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + + it('ends a demand whose last session leaves while its start is pending ' + + 'once the start resolves or rejects, releasing what the start registered once', async () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + + for (const outcome of ['resolves', 'rejects'] as const) { + const connection = buildEmitterConnection() + const sessionIdentifier = crypto.randomUUID() + await prepare(service, connection, from, sessionIdentifier) + const pending = pendingStart(delegate) + + const starting = start(service, connection, sessionIdentifier) + await settle() + connection.emit('closed') + + expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + await settle() + expect(disposedOf(delegate, streamOf(delegate))).toBe(0) + expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(false) + + if (outcome === 'resolves') { + pending.resolve() + } else { + pending.reject(new Error('The video encoder failed to start.')) + } + await settle() + + // A start that resolves ends its demand, and one that rejects is refused, each releasing once what the start registered. + expect({ + outcome, + ended: disposedOf(delegate, streamOf(delegate)), + }).toEqual({ + outcome, + ended: 1, + }) + } + }) + + it('withdraws a demand whose start never settles at a reset or a destroy with one debug event and no warning or problem, and ends it no more at a later ' + + 'reset or destroy', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + for (const ending of ['reset', 'destroy'] as const) { + const { problems, reporter } = problemsOf() + const { delegate, management, service } = harness({ reporter }) + const from = await endpoint() + const connection = buildEmitterConnection() + const sessionIdentifier = crypto.randomUUID() + await prepare(service, connection, from, sessionIdentifier) + const pending = pendingStart(delegate) + const events = captureDebugEvents('HAP-NodeJS:Camera:Tier') + warn.mockClear() + + // The Start waits on its tier's demand, whose start never settles, until the reset or the destroy ends its session. + const starting = start(service, connection, sessionIdentifier) + await settle() + + if (ending === 'reset') { + management.handleFactoryReset() + } else { + await management.destroy() + } + + // The library withdraws the start for its own reasons, the plugin having done nothing wrong, which is why it writes a debug event and raises no problem. + const withdrawn = (): CameraDebugEvent[] => events.filter(({ kind }) => kind === 'start-withdrawn') + + expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect({ + ending, + ended: endedCalls(delegate), + problems: problems.length, + warnings: warn.mock.calls.length, + withdrawn: withdrawn().length, + }).toEqual({ + ending, + ended: 1, + problems: 0, + warnings: 0, + withdrawn: 1, + }) + expect(withdrawn().map(({ sensorUUID, sentence, tierId }) => ({ + sensorUUID, + sentence, + tierId, + }))).toEqual([ + { + sensorUUID: SENSOR_UUID.toLowerCase(), + sentence: `The library withdrew the pending start of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" when its service ended ` + + 'every session: the demand is withdrawn and every join waiting on it is refused.', + tierId: 1, + }, + ]) + + management.handleFactoryReset() + await management.destroy() + await settle() + + expect({ + ending, + ended: endedCalls(delegate), + problems: problems.length, + warnings: warn.mock.calls.length, + withdrawn: withdrawn().length, + }).toEqual({ + ending, + ended: 1, + problems: 0, + warnings: 0, + withdrawn: 1, + }) + + // The withdrawal released what the start registered, and its later settling releases nothing more. + pending.resolve() + await settle() + + expect(disposedOf(delegate, streamOf(delegate))).toBe(1) + } + }) + + it('releases what a streaming session\'s tier registered once, in its demand\'s end, at a reset that ends the session', async () => { + const { delegate, management, service, table } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + + await streaming(service, connection, from) + + const stream = streamOf(delegate) + const tier = table.videoTiers.get(1)! + const inside: unknown[] = [] + + // A cleanup registered once the start settled, which reads where the release runs: the demand ended while its tier still holds it. + stream.defer(() => { + inside.push([(stream as TierDemand).state, tier.demand === stream]) + }) + management.handleFactoryReset() + await settle() + management.handleFactoryReset() + await settle() + + expect([ + inside, + disposedOf(delegate, stream), + tier.demand, + ]).toEqual([ + [ + [ + 'ended', + true, + ], + ], + 1, + undefined, + ]) + }) + + it('hands each demand\'s end the stream its start received, at its last consumer\'s leave and at a withdrawal', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, management, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expectEndsNameTheirStreams(delegate, 1) + + // A second Start waits on video tier 2, whose start never settles, until a reset withdraws that demand. + const waiting = crypto.randomUUID() + await prepare(service, connection, from, waiting) + const pending = pendingStart(delegate) + const starting = start(service, connection, waiting, 2) + await settle() + management.handleFactoryReset() + + // The reset's withdrawal is the library's own, which is why it prints no warning. + expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(warn).not.toHaveBeenCalled() + expectEndsNameTheirStreams(delegate, 2) + + // The withdrawal released what the start registered, and its later settling releases nothing more. + pending.resolve() + await settle() + + expect(disposedOf(delegate, streamOf(delegate, 2))).toBe(1) + }) + + it('keeps a busy start\'s joins off its session, which is why its prepare timeout leaves another session\'s tier alone, and joins anew at a retried ' + + 'start', async () => { + // The steady clock is faked beside the timers, which keeps the pacer on the clock the other session's kept stream keeps step with. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const other = await endpoint() + const busy = buildEmitterConnection() + const busyIdentifier = crypto.randomUUID() + await prepare(service, busy, from, busyIdentifier) + const rejectOnce = (): void => { + delegate.tierDemandStarted.mockImplementationOnce(async () => { + throw new Error('The encoder is busy.') + }) + } + + rejectOnce() + expect(await start(service, busy, busyIdentifier)).toBe(RTPStreamingStatus.BUSY) + await settle() + + const streamer = buildEmitterConnection() + const streamed = await streaming(service, streamer, other) + const endedBefore = endedCalls(delegate) + // The other session's tier hands over pictures that are no keyframe through the busy session's prepare timeout, which keeps its demand inside its + // silence bounds and sends the session nothing before the keyframe after. + await keepStreaming([ + streamOf(delegate), + ], 60000, { advance: advanceAsync }) + await settle() + + writeTierFrame(streamOf(delegate), 'video', { + ...vectorFrame(HEVC, 0, 60000000), + keyframe: true, + }) + await vi.advanceTimersByTimeAsync(0) + await until(() => other.received.video.length === 1) + + expect(endedCalls(delegate)).toBe(endedBefore) + expect(await end(service, streamer, streamed.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + await settle() + + const retried = buildEmitterConnection() + const retriedIdentifier = crypto.randomUUID() + await prepare(service, retried, from, retriedIdentifier) + rejectOnce() + + expect(await start(service, retried, retriedIdentifier)).toBe(RTPStreamingStatus.BUSY) + expect(await start(service, retried, retriedIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + + const endedRetried = endedCalls(delegate) + expect(await end(service, retried, retriedIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + await settle() + + expect(endedCalls(delegate) - endedRetried).toBe(1) + }) + + it('keeps a demand whose only session left while its start was pending for a session that joins it, which it starts and serves with no end sent', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const leavingEndpoint = await endpoint() + const joiningEndpoint = await endpoint() + const closing = buildEmitterConnection() + const joining = buildEmitterConnection() + const left = crypto.randomUUID() + const joined = crypto.randomUUID() + const pending = deferred() + await prepare(service, closing, leavingEndpoint, left) + const answer = await prepare(service, joining, joiningEndpoint, joined) as Prepared + pendingStart(delegate, pending) + + // The first Start waits on its tier's demand until its connection closes, which leaves the demand with no session while its start is still pending. + const leaving = start(service, closing, left) + await settle() + closing.emit('closed') + + expect(await leaving).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + + const joiningStart = start(service, joining, joined) + await settle() + pending.resolve() + + expect(await joiningStart).toBe(RTPStreamingStatus.SUCCESS) + + const stream = streamOf(delegate) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300))) + await vi.advanceTimersByTimeAsync(0) + await until(() => joiningEndpoint.received.video.length === 1) + + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + expect(endedCalls(delegate)).toBe(0) + expect(unprotected(answer, joiningEndpoint, 'video')).toHaveLength(1) + expect(stream.statistics()).toMatchObject({ packets: 1, consumers: 2 }) + }) + + it('ends a session waiting on a demand whose stream fails after its start returned a pending promise, and ends the demand once its start settles', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + const pending = deferred() + await prepare(service, connection, from, identifier) + pendingStart(delegate, pending) + + const starting = start(service, connection, identifier) + await settle() + streamOf(delegate).fail('The encoder crashed.') + + expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + await settle() + expect(endedCalls(delegate)).toBe(0) + + pending.resolve() + await settle() + + expect(endedCalls(delegate)).toBe(1) + expect(warn).toHaveBeenCalledOnce() + }) + + it('logs a rejected tierDemandStarted once under its sentence', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + await prepare(service, connection, from, identifier) + delegate.tierDemandStarted.mockImplementationOnce(async () => { + throw new Error('The video encoder is busy.') + }) + + expect(await start(service, connection, identifier)).toBe(RTPStreamingStatus.BUSY) + await settle() + + expect(error).toHaveBeenCalledOnce() + expect(String(error.mock.calls[0][0])).toMatch(/^MultiTierStreamingDelegate failed to start a tier demand: /) + }) + + it('refuses a demand whose tierDemandStarted throws in the calling turn as a rejection refuses it, answering busy and logging the throw once', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + await prepare(service, connection, from, identifier) + delegate.tierDemandStarted.mockImplementationOnce(() => { + throw new Error('The video encoder is busy.') + }) + + expect(await start(service, connection, identifier)).toBe(RTPStreamingStatus.BUSY) + await settle() + + const stream = streamOf(delegate) + writeTierFrame(stream, 'video', sliceFrame(300)) + await vi.advanceTimersByTimeAsync(0) + + expect(error).toHaveBeenCalledOnce() + expect(String(error.mock.calls[0][0])).toMatch(/^MultiTierStreamingDelegate failed to start a tier demand: /) + expect(stream.statistics()).toEqual({ + packets: 0, + bytes: 0, + drops: 0, + consumers: 0, + }) + expect(endedCalls(delegate)).toBe(0) + }) + + it('leaves no sender of a session whose Start is answered busy on its tier, none on its media, and the tier another session streams as it was', async () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, management, service } = harness() + const streamingEndpoint = await endpoint() + const refusedEndpoint = await endpoint() + await streaming(service, buildEmitterConnection(), streamingEndpoint) + const connection = buildEmitterConnection() + const refused = crypto.randomUUID() + await prepare(service, connection, refusedEndpoint, refused) + + // The refused Start raises video tier 2, whose start rejects, beside tier 1, which the first session streams. + delegate.tierDemandStarted.mockImplementationOnce(async () => { + throw new Error('The second encoder is busy.') + }) + + expect(await start(service, connection, refused, 2)).toBe(RTPStreamingStatus.BUSY) + + // @ts-expect-error: private access + const { media } = management.sessions.get(refused) + + expect(streamOf(delegate, 1).statistics().consumers).toBe(2) + expect(streamOf(delegate, 2).statistics().consumers).toBe(0) + expect([media.video.sender, media.audio.sender]).toEqual([undefined, undefined]) + }) + + it('sends a session waiting on its pending video demand each frame the plugin writes during the wait, and streams it on once the demand starts', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + const pending = deferred() + const answer = await prepare(service, connection, from, identifier) as Prepared + pendingStart(delegate, pending) + + const starting = start(service, connection, identifier) + await settle() + const stream = streamOf(delegate) + + expect(stream.statistics().consumers).toBe(2) + + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0))) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 1) + pending.resolve() + + expect(await starting).toBe(RTPStreamingStatus.SUCCESS) + + // Written at the first frame's moment, the frame a frame's length later is due that length after it. + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(34) + await until(() => from.received.video.length === 2) + + expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).length)).toEqual([ + setsAggregated(300), + 300, + ]) + expect(stream.statistics()).toMatchObject({ packets: 2, consumers: 2 }) + }) + + it('ends the session whose Start raised a demand its plugin fails inside tierDemandStarted, answering the Start unknown', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const base = udpSockets() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + await prepare(service, connection, from, identifier) + delegate.tierDemandStarted.mockImplementationOnce((stream) => { + stream.use(disposableFor(delegate, stream)) + stream.fail('The encoder failed to open.') + }) + + expect(await start(service, connection, identifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + await settle() + await until(() => udpSockets() === base) + + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + expect(warn).toHaveBeenCalledOnce() + expect(endedCalls(delegate)).toBe(1) + expect(await end(service, connection, identifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + }) + + it('tells of no view for a Start answered busy, unknown session identifier or error, nor as each of those sessions ends', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const views: string[] = [] + const { delegate, service } = harness({ + onLiveViewEnded: () => views.push('ended'), + onLiveViewStarted: () => views.push('started'), + }) + const from = await endpoint() + const base = udpSockets() + // Each session prepared on a connection of its own, which holds one prepared session at a time. + const sessions = Array.from({ length: 3 }, () => ({ + connection: buildEmitterConnection(), + identifier: crypto.randomUUID(), + })) + const [busy, unknown, refused] = sessions + + for (const { connection, identifier } of sessions) { + await prepare(service, connection, from, identifier) + } + + // A demand whose start rejects answers busy, one whose plugin fails its stream inside its start answers unknown, and a Start naming a video tier the + // sensor does not offer answers error. + delegate.tierDemandStarted.mockImplementationOnce(async () => { + throw new Error('The encoder is busy.') + }) + + expect(await start(service, busy.connection, busy.identifier)).toBe(RTPStreamingStatus.BUSY) + + await settle() + delegate.tierDemandStarted.mockImplementationOnce((stream) => { + stream.fail('The encoder failed to open.') + }) + + expect(await start(service, unknown.connection, unknown.identifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(await start(service, refused.connection, refused.identifier, 9)).toBe(RTPStreamingStatus.ERROR) + + for (const { connection, identifier } of sessions) { + await end(service, connection, identifier) + } + + await settle() + await until(() => udpSockets() === base) + + expect(views).toEqual([]) + }) + }) + + describe('the tier stream', () => { + it('sends each of two sessions at home on two tiers the sound of its own tier\'s stream under the audio tier\'s payload type, and none of the other\'s', + async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const firstEndpoint = await endpoint() + const secondEndpoint = await endpoint() + const first = await streaming(service, buildEmitterConnection(), firstEndpoint, 1) + const second = await streaming(service, buildEmitterConnection(), secondEndpoint, 2) + + writeTierFrame(streamOf(delegate, 1), 'audio', { + data: Buffer.alloc(60, 1), + time: 0, + }) + writeTierFrame(streamOf(delegate, 2), 'audio', { + data: Buffer.alloc(60, 2), + time: 0, + }) + await vi.advanceTimersByTimeAsync(0) + await until(() => firstEndpoint.received.audio.length === 1 && secondEndpoint.received.audio.length === 1) + await settle() + + for (const [answer, from, tag] of [ + [first, firstEndpoint, 1], + [second, secondEndpoint, 2], + ] as const) { + const packets = unprotected(answer, from, 'audio') + + expect(packets.map(packet => packet.subarray(12).toString('hex'))).toEqual([ + Buffer.alloc(60, tag).toString('hex'), + ]) + expect(packets.map(packet => packet[1] & 0x7F)).toEqual([110]) + } + }) + + it('sends a stream with no Opus track as a tier without sound, its picture sent and nothing failed or warned', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const stream = streamOf(delegate) + + // A fragment carrying a run of a second track beside the picture, which a stream with no Opus track does not describe. + stream.write(tierStreamInitialization({ sound: false })) + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + ], + sound: [ + soundSample(Buffer.alloc(60, 7)), + ], + })) + await until(() => from.received.video.length === 1) + await settle() + + expect(from.received.audio).toEqual([]) + expect(warn).not.toHaveBeenCalled() + expect(stream.statistics()).toEqual({ + packets: 1, + bytes: 12 + setsAggregated(300), + drops: 0, + consumers: 2, + }) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('counts both media in the stream\'s statistics: each packet of picture and of sound sent, their bytes, and each sample of either dropped', async () => { + const { delegate, service } = harness() + const from = await endpoint() + await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + pictureSample(Buffer.from('0000000a0201', 'hex')), + ], + sound: [ + soundSample(Buffer.alloc(60, 7)), + soundSample(Buffer.alloc(0)), + ], + })) + await until(() => from.received.video.length === 1 && from.received.audio.length === 1) + + expect(stream.statistics()).toEqual({ + packets: 2, + bytes: (12 + setsAggregated(300)) + (12 + 60), + drops: 2, + consumers: 2, + }) + }) + + it('fails the tier with one warning, every session on it ending, for a stream the library refuses: one with no video track, one whose video track has ' + + 'a timescale of 0, and one holding a malformed box', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const opus = { + handler: 'soun', + id: 2, + sampleEntry: opusSampleEntry(), + timescale: 48000, + } + const refusals: [Buffer[], string][] = [ + [ + [ + initializationSegment(opus), + ], + 'The stream\'s initialization segment holds no video track.', + ], + [ + [ + initializationSegment({ + handler: 'vide', + id: 1, + sampleEntry: visualSampleEntry('hvc1', 64, 36, hvcC([])), + timescale: 0, + }, opus), + ], + 'The stream\'s initialization segment holds no video track.', + ], + [ + [ + tierStreamInitialization(), + Buffer.from('0000000466726565', 'hex'), + ], + 'The stream holds a malformed box, whose size is under its header\'s.', + ], + ] + + for (const [chunks, reason] of refusals) { + const { delegate, service } = harness() + const from = await endpoint() + const base = udpSockets() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + + warn.mockClear() + + for (const chunk of chunks) { + streamOf(delegate).write(chunk) + } + + await settle() + await until(() => udpSockets() === base) + + expect(warn.mock.calls).toEqual([ + [`The library refused the stream of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" (${reason}), and every session on the tier ends.`], + ]) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(endedCalls(delegate)).toBe(1) + } + }) + + it('fails the tier with one warning carrying the reader\'s sentence, every session on it ending, for a stream whose sound repeats a decode time', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const base = udpSockets() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const stream = streamOf(delegate) + + // A fragment and one a frame after it, whose sound stands at the decode time of the first one's. + stream.write(tierStreamInitialization()) + + for (const pictureTime of [0n, 3000n]) { + stream.write(tierStreamFragment({ + picture: [ + pictureSample(sliceFrame(300).data), + ], + pictureTime, + sound: [ + soundSample(Buffer.alloc(60, 7)), + ], + })) + } + + await settle() + await until(() => udpSockets() === base) + + expect(warn.mock.calls).toEqual([ + [`The library refused the stream of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" (The stream's audio track's decode times do ` + + 'not rise: a sample is timed at or before the one before it.), and every session on the tier ends.'], + ]) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(endedCalls(delegate)).toBe(1) + }) + + it('opens a new run of times for both media at the stream\'s discontinuity, each at its own rate', async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + const moment = performance.now() + // A fragment of one picture sample and one sound sample at the decode times given, its picture a keyframe where it opens a run. + const fragment = (pictureTime: bigint, soundTime: bigint, keyframe = false): Buffer => tierStreamFragment({ + picture: [ + keyframe + ? keyframeSample() + : pictureSample(sliceFrame(300).data), + ], + pictureTime, + sound: [ + soundSample(Buffer.alloc(60, 7)), + ], + soundTime, + }) + // Each medium's packets' timestamps, less its first. + const steps = (medium: StreamTierMedium): number[] => { + const timestamps = unprotected(answer, from, medium).map(packet => packet.readUInt32BE(4)) + + return timestamps.slice(1).map(timestamp => (timestamp - timestamps[0]) >>> 0) + } + + // Five seconds after the first samples, a sample of each medium one step on keeps its run, and after the discontinuity each medium's next sample + // opens a run of its own at that moment's timestamp at its own rate. + const now = vi.spyOn(performance, 'now').mockReturnValue(moment) + stream.write(tierStreamInitialization()) + stream.write(fragment(0n, 0n, true)) + await vi.advanceTimersByTimeAsync(0) + now.mockReturnValue(moment + 5000) + stream.write(fragment(3000n, 960n)) + stream.discontinuity() + stream.write(fragment(0n, 0n, true)) + await vi.advanceTimersByTimeAsync(0) + now.mockRestore() + await until(() => from.received.video.length === 3 && from.received.audio.length === 3) + + expect(steps('video')).toEqual([3000, 5000 * 90]) + expect(steps('audio')).toEqual([960, 5000 * 48]) + }) + + it('places a picture and a sound written a fragment after it on one run, each at its presentation time\'s distance from the run\'s origin at its own ' + + 'rate, whatever its arrival', async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const origin = performance.now() + const made = vi.spyOn(performance, 'now').mockReturnValue(origin) + const { delegate, service } = harness() + made.mockRestore() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + + // A fragment of a keyframe alone decoded at 1 s arrives a second after the clock's making, and half a second later a fragment of the next picture and + // a sound presented at 1.02 s. + const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000) + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + ], + pictureTime: 90000n, + })) + await vi.advanceTimersByTimeAsync(0) + now.mockReturnValue(origin + 1500) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(sliceFrame(300).data), + ], + pictureTime: 93000n, + sound: [ + soundSample(Buffer.alloc(60, 7)), + ], + soundTime: 48960n, + })) + await vi.advanceTimersByTimeAsync(0) + now.mockRestore() + await until(() => from.received.video.length === 2 && from.received.audio.length === 1) + + const [picture, next] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4)) + const [sound] = unprotected(answer, from, 'audio').map(packet => packet.readUInt32BE(4)) + + // The run opened at the first picture's arrival, a second into the clock: the clock's offset stands 90,000 ticks before that picture, and the + // sound stands 20 ms of its own ticks after the second the run opened at, not at its own arrival half a second later. + expect((next - picture) >>> 0).toBe(3000) + expect((picture - 90000) >>> 0).toBe((sound - 48000 - 960) >>> 0) + }) + + it('sends a view at home no sound while the camera\'s Microphone is muted and its picture all the while, and unmuted the next sound at the timestamp the ' + + 'clock gives it, unmarked, as if none were withheld', async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const origin = performance.now() + const made = vi.spyOn(performance, 'now').mockReturnValue(origin) + const { delegate, service, table } = harness() + made.mockRestore() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + + table.muteMicrophone(true) + + // A second after the clock's making, a fragment of a keyframe decoded at 1 s with sounds presented with it and 20 ms after it opens the run, the run's + // first sound among those the mute holds back, and once the mute is off a fragment of the next picture and a sound presented at 1.04 s. + const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000) + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + ], + pictureTime: 90000n, + sound: [ + soundSample(Buffer.alloc(60, 1)), + soundSample(Buffer.alloc(60, 2)), + ], + soundTime: 48000n, + })) + await vi.advanceTimersByTimeAsync(0) + now.mockReturnValue(origin + 1500) + await vi.advanceTimersByTimeAsync(20) + await until(() => from.received.video.length === 1) + table.muteMicrophone(false) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(sliceFrame(300).data), + ], + pictureTime: 93000n, + sound: [ + soundSample(Buffer.alloc(60, 3)), + ], + soundTime: 49920n, + })) + // The sound falls due by its own decode time, 7 ms after the fragment's picture. + now.mockReturnValue(origin + 1510) + await vi.advanceTimersByTimeAsync(10) + now.mockRestore() + await until(() => from.received.video.length === 2 && from.received.audio.length === 1) + await settle() + + const [picture] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4)) + const sounds = unprotected(answer, from, 'audio') + + // The sound sent is the one written once the mute was off, 40 ms of its own ticks after the second the run opened at, and it carries no marker, since + // the run's first sound was placed as the mute held it back. + expect(sounds.map(packet => packet.subarray(12))).toEqual([ + Buffer.alloc(60, 3), + ]) + expect((picture - 90000) >>> 0).toBe((sounds[0].readUInt32BE(4) - 48000 - 1920) >>> 0) + expect(sounds[0][1] & 0x80).toBe(0) + }) + + it('opens each later run at a mark, an initialization segment and a forward jump past the highest timestamp placed for each medium, at one moment ' + + 'for picture and sound, and marks each run\'s first sound where a picture opened the run', async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. Its + // origin is a whole millisecond, which is why the last run's latest samples fall due exactly 60 ms after its first picture: on a fractional origin that sum can + // round up, which arms the pacer's timer a millisecond past the row's 60 ms step and leaves them unsent. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const origin = Math.ceil(performance.now()) + const made = vi.spyOn(performance, 'now').mockReturnValue(origin) + const { delegate, service } = harness() + made.mockRestore() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + // A run's fragment: pictures decoded a frame apart from the decode time given, the first a keyframe, each presented two frames after its decode time, + // and sounds a packet apart from that decode time, each presented before the first picture. + const run = (decodeTime: bigint): Buffer => tierStreamFragment({ + picture: [0, 1].map(index => ({ + ...(index === 0 + ? keyframeSample() + : pictureSample(sliceFrame(300).data)), + compositionOffset: 6000, + })), + pictureTime: decodeTime, + sound: [0, 1, 2, 3].map(index => soundSample(Buffer.alloc(60, index + 1))), + soundTime: decodeTime * 48000n / 90000n, + }) + + // Every run arrives in one moment, a second into the clock: the first, one after a mark, one after a new initialization segment, and one whose decode + // times leap ten seconds ahead with no mark. + const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000) + stream.write(tierStreamInitialization()) + stream.write(run(0n)) + stream.discontinuity() + stream.write(run(0n)) + stream.write(tierStreamInitialization()) + stream.write(run(0n)) + stream.write(run(900000n)) + await vi.advanceTimersByTimeAsync(0) + + // The ended runs leave at once, and the last run's later samples at their decode times' distance from its first picture, the latest 60 ms on. + now.mockReturnValue(origin + 1060) + await vi.advanceTimersByTimeAsync(60) + now.mockRestore() + await until(() => from.received.video.length === 8 && from.received.audio.length === 16) + + const sounds = unprotected(answer, from, 'audio') + // Each timestamp less the clock's offset, which the first run, opened a second into the clock, places its first picture two frames past. + const offset = (unprotected(answer, from, 'video')[0].readUInt32BE(4) - 90000 - 6000) >>> 0 + const ticks = (packets: Buffer[]): number[] => packets.map(packet => (packet.readUInt32BE(4) - offset) >>> 0) + const pictureRuns = [0, 2, 4, 6].map(first => ticks(unprotected(answer, from, 'video')).slice(first, first + 2)) + const soundRuns = [0, 4, 8, 12].map(first => ticks(sounds).slice(first, first + 4)) + + // Each run's samples stand past every earlier one of their medium, and the moment each run opened at, read from its first picture less its two frames + // and from its first sound, is one moment for picture and sound to within a tick. + for (const runs of [pictureRuns, soundRuns]) { + expect(runs.slice(1).every((samples, index) => Math.min(...samples) > Math.max(...runs.slice(0, index + 1).flat()))).toBe(true) + } + + expect(pictureRuns.map(([first], index) => Math.abs((first - 6000) / 90 - soundRuns[index][0] / 48) < 1 / 48)).toEqual([true, true, true, true]) + expect(sounds.map(packet => (packet[1] & 0x80) !== 0)).toEqual([0, 1, 2, 3].flatMap(() => [true, false, false, false])) + }) + + it('lets a sound timed before its run\'s origin go and counts it, places a picture timed before the origin of a run a sound opened at that run\'s ' + + 'opening, and sends that run\'s sound with no picture written', async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const origin = performance.now() + const made = vi.spyOn(performance, 'now').mockReturnValue(origin) + const { delegate, service } = harness() + made.mockRestore() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + + // A second into the clock, a run a keyframe decoded at 1 s opens, whose fragment carries a sound timed 20 ms before that keyframe and one timed with + // it. + const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000) + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + ], + pictureTime: 90000n, + sound: [ + soundSample(Buffer.alloc(60, 1)), + soundSample(Buffer.alloc(60, 2)), + ], + soundTime: 47040n, + })) + await vi.advanceTimersByTimeAsync(0) + + // A second later, after a mark, sounds timed from 5 s open a run, and a keyframe decoded at 4.9 s follows them. + now.mockReturnValue(origin + 2000) + stream.discontinuity() + stream.write(tierStreamFragment({ + sound: [ + soundSample(Buffer.alloc(60, 3)), + soundSample(Buffer.alloc(60, 4)), + ], + soundTime: 240000n, + })) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.audio.length === 3) + + const sentAlone = from.received.video.length + + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + ], + pictureTime: 441000n, + })) + await vi.advanceTimersByTimeAsync(0) + now.mockRestore() + await until(() => from.received.video.length === 2) + + const offset = (unprotected(answer, from, 'video')[0].readUInt32BE(4) - 90000) >>> 0 + const ticks = (medium: StreamTierMedium): number[] => unprotected(answer, from, medium).map(packet => (packet.readUInt32BE(4) - offset) >>> 0) + + expect([sentAlone, stream.statistics().drops]).toEqual([1, 1]) + expect([ + ticks('video'), + ticks('audio'), + ]).toEqual([ + [90000, 180000], + [48000, 96000, 96960], + ]) + }) + + it('sends a picture sample with a composition offset, written through the TierStream, at its decode time plus that offset, read from its packets\' RTP ' + + 'timestamp beside samples with none', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + + // Pictures decoded 3000 ticks apart from zero from a keyframe, the second presented 6000 ticks after its decode time, each one packet. + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + { + ...pictureSample(sliceFrame(300).data), + compositionOffset: 6000, + }, + pictureSample(sliceFrame(300).data), + ], + })) + // The fragment's later pictures leave at their decode times' distance from its first, the last two frames on. + await vi.advanceTimersByTimeAsync(67) + await until(() => from.received.video.length === 3) + + const timestamps = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4)) + + expect(timestamps.slice(1).map(timestamp => (timestamp - timestamps[0]) >>> 0)).toEqual([9000, 6000]) + }) + + it('makes no frame form for a half no consumer is joined to, a keyframe copied for none, and places its run all the same', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, table } = harness() + const tier = table.videoTiers.get(1)! + const sound = scriptedFrameConsumer() + const picture = scriptedFrameConsumer() + + expect(await table.joinFrames(tier, 'audio', scriptedHolder(), sound).answer()).toBe('started') + + const stream = streamOf(delegate) + + stream.write(tierStreamInitialization({ + parameterSets: [32, 33, 34].map(type => nalUnit(Buffer.from([type << 1, 0x01]), 12)), + })) + + // A keyframe of the picture, which no consumer takes, beside a sound sample, which one does: the frame form of the keyframe is the one copy a whole + // fragment's reading would make. + const fragment = tierStreamFragment({ + picture: [ + pictureSample(sliceFrame(300).data, true), + ], + sound: [ + soundSample(Buffer.alloc(60, 7)), + ], + }) + const concat = vi.spyOn(Buffer, 'concat') + stream.write(fragment) + await vi.advanceTimersByTimeAsync(0) + + expect(concat).not.toHaveBeenCalled() + expect(sound.taken).toHaveLength(1) + + concat.mockRestore() + table.joinFrames(tier, 'video', scriptedHolder(), picture) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(sliceFrame(300).data), + ], + pictureTime: 3000n, + })) + await vi.advanceTimersByTimeAsync(34) + + // The picture's consumer joins behind the keyframe the pacer released to no one: its opening hands it that keyframe first, at the next picture's + // release, with the run-opening flag unset, which a live release alone carries. + expect(picture.taken.map(({ frame, opensRun }) => [frame.time, opensRun])).toEqual([ + [0, false], + [33333, false], + ]) + }) + + it('writes the debug event of a withdrawn demand naming its video tier, and no warning', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, management, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + await streaming(service, connection, from) + + // A second Start waits on video tier 2, whose start never settles, until a reset withdraws its demand. + const waiting = crypto.randomUUID() + await prepare(service, connection, from, waiting) + delegate.tierDemandStarted.mockImplementationOnce(async () => new Promise(() => undefined)) + const lines = captureDebug('HAP-NodeJS:Camera:Tier') + const starting = start(service, connection, waiting, 2) + await settle() + management.handleFactoryReset() + + expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(lines.filter(line => line.startsWith('The library withdrew'))).toEqual([ + `The library withdrew the pending start of the video tier 2 of the video sensor "${SENSOR_UUID.toLowerCase()}" when its service ended every ` + + 'session: the demand is withdrawn and every join waiting on it is refused.', + ]) + expect(warn).not.toHaveBeenCalled() + }) + }) + + describe('a view at home of a shared sensor', () => { + // The fixture's sensor with its audio shared: its sound tier is the tier the camera records, its best, tier 1, and every other tier's Opus is ignored. + const SHARED_TIERS = tierSetOf(videoSensor(SENSOR_UUID, { + audio: { + bitrate: 24, + source: 'shared', + }, + })) + + // Scripts the first start of the video tier given to wait on the deferred it answers, every other start starting at once as the scripted delegate's does. + function pendingFirstStart(delegate: ScriptedTierDelegate, tierId: number, pending: Deferred = deferred()): Deferred { + const started = delegate.tierDemandStarted.getMockImplementation()! + let pended = false + + delegate.tierDemandStarted.mockImplementation(async (stream, signal) => { + await started(stream, signal) + + if ((stream.tier.id === tierId) && !pended) { + pended = true + await pending.promise + } + }) + + return pending + } + + it('starts both tiers\' demands for a Start of a tier other than the sound tier, answers it once its own tier has started while the sound tier\'s ' + + 'start is pending, and sends its session the sound tier\'s sound and none of its own tier\'s', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service, table } = harness({ tiers: SHARED_TIERS }) + const pending = pendingFirstStart(delegate, 1) + const from = await endpoint() + const connection = buildEmitterConnection() + const sessionIdentifier = crypto.randomUUID() + const answer = await prepare(service, connection, from, sessionIdentifier) as Prepared + let status: RTPStreamingStatus | undefined + + void start(service, connection, sessionIdentifier, 2).then((answered) => { + status = answered + }) + await until(() => status !== undefined) + + expect(status).toBe(RTPStreamingStatus.SUCCESS) + expect(streamsOf(delegate).map(stream => stream.tier.id)).toEqual([2, 1]) + expect(table.videoTiers.get(1)!.demand!.waiting).toBe(true) + + // Each tier's stream carries a sound of its own, which only the sound tier's reaches the session. + for (const tierId of [1, 2]) { + writeTierFrame(streamOf(delegate, tierId), 'audio', { + data: Buffer.alloc(60, tierId), + time: 0, + }) + } + + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.audio.length === 1) + await settle() + + expect(unprotected(answer, from, 'audio').map(packet => packet.subarray(12))).toEqual([ + Buffer.alloc(60, 1), + ]) + + pending.resolve() + + expect(await end(service, connection, sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('joins a Start of the sound tier once for both media, as a Start of a tier joins it on a sensor whose tiers each carry their own sound', async () => { + const joins = vi.spyOn(TierTable.prototype, 'join') + const { service } = harness({ tiers: SHARED_TIERS }) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from, 1) + + expect(joins.mock.calls.map(call => ({ + media: call[3], + tierId: call[0].tierId, + }))).toEqual([ + { + media: ['video', 'audio'], + tierId: 1, + }, + ]) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it.each([ + { cause: 'a refusal' }, + { cause: 'a cut at its bound' }, + ])('streams a view of another tier on with its own pictures and no sound after $cause of the sound tier\'s start, and sends it none when another ' + + 'holder raises the sound tier again', async ({ cause }) => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service, table } = harness({ tiers: SHARED_TIERS }) + const pending = pendingFirstStart(delegate, 1) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from, 2) + const soundTier = table.videoTiers.get(1)! + + expect(streamsOf(delegate).map(stream => stream.tier.id)).toEqual([2, 1]) + + // The view's own tier hands over pictures that are no keyframe through the sound tier's bound, which keeps its demand inside its silence bounds and + // sends the view nothing before its keyframe below. + if (cause === 'a refusal') { + pending.reject(new Error('The sound encoder is busy.')) + await settle() + } else { + await keepStreaming([ + streamOf(delegate, 2), + ], DELEGATE_CALL_TIMEOUT, { advance: advanceAsync }) + } + + // The sound tier's start is told of as that tier's own problem, a rejection's or the bound's, and its demand has ended. + const reported = [ + ...error.mock.calls, + ...warn.mock.calls, + ].map(([line]) => String(line)) + + expect(reported).toEqual([ + expect.stringMatching((cause === 'a refusal') + ? /^MultiTierStreamingDelegate failed to start a tier demand: / + : /did not settle tierDemandStarted for the video tier 1 /), + ]) + expect(soundTier.demand).toBeUndefined() + + // Another holder raises the sound tier again, whose stream writes a sound, and the view's own tier writes a keyframe, timed past every picture it + // handed over through the bound. + const raised = table.hold(soundTier, scriptedHolder()) + + writeTierFrame(streamOf(delegate, 1), 'audio', { + data: Buffer.alloc(60, 1), + time: 0, + }) + writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets(sliceFrame(300, DELEGATE_CALL_TIMEOUT * 1000))) + await vi.advanceTimersByTimeAsync(0) + await until(() => unprotected(answer, from, 'video').length === 1) + await settle() + + expect(unprotected(answer, from, 'audio')).toEqual([]) + expect(endsOf(delegate, 2)).toBe(0) + + raised.release() + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('streams a view of another tier on silent once the sound tier\'s stream fails mid-view, and ends the sound tier\'s demand once, at the release its ' + + 'other holder makes', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service, table } = harness({ tiers: SHARED_TIERS }) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from, 2) + const other = table.hold(table.videoTiers.get(1)!, scriptedHolder()) + + writeTierFrame(streamOf(delegate, 1), 'audio', { + data: Buffer.alloc(60, 1), + time: 0, + }) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.audio.length === 1) + + streamOf(delegate, 1).fail('The sound encoder crashed.') + await settle() + + expect(endsOf(delegate, 1)).toBe(0) + + // The view's own tier streams on, its keyframe sent. + writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets(sliceFrame(300))) + await vi.advanceTimersByTimeAsync(0) + await until(() => unprotected(answer, from, 'video').length === 1) + + other.release() + await settle() + + expect(endsOf(delegate, 1)).toBe(1) + expect(unprotected(answer, from, 'audio')).toHaveLength(1) + expect(warn).toHaveBeenCalledOnce() + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([1, 1]) + }) + + it('releases a view\'s sound at its Start where the sound\'s tier holds a demand that failed already and another holder still keeps: the tier ends ' + + 'as that holder releases and a later holder raises a demand of its own', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service, table } = harness({ tiers: SHARED_TIERS }) + const soundTier = table.videoTiers.get(1)! + // Another holder keeps the sound's tier past its failure, and the failed demand stands until that holder releases. + const other = table.hold(soundTier, scriptedHolder()) + + await settle() + streamOf(delegate, 1).fail('The sound encoder crashed.') + await settle() + + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from, 2) + + other.release() + await settle() + + expect(endsOf(delegate, 1)).toBe(1) + + // A later holder of the sound's tier, as the recorded tier's keeper asking again, raises a demand of its own. + const later = table.hold(soundTier, scriptedHolder()) + + await settle() + + expect(streamsOf(delegate, 1)).toHaveLength(2) + + later.release() + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('releases both holds of a view of another tier at its End, each tier\'s demand ending once', async () => { + const { delegate, service } = harness({ tiers: SHARED_TIERS }) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from, 2) + + expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([0, 0]) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + await settle() + + expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([1, 1]) + }) + + it('releases both joins of a session that ends while its Start of another tier waits on that tier\'s pending start', async () => { + const { delegate, service } = harness({ tiers: SHARED_TIERS }) + const pending = pendingFirstStart(delegate, 2) + const from = await endpoint() + const closing = buildEmitterConnection() + const sessionIdentifier = crypto.randomUUID() + await prepare(service, closing, from, sessionIdentifier) + + const starting = start(service, closing, sessionIdentifier, 2) + await settle() + + expect(streamsOf(delegate).map(stream => stream.tier.id)).toEqual([2, 1]) + + closing.emit('closed') + + expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + await settle() + + // The sound tier, started at once, ends with its one join released, and the view's own tier ends as its pending start settles. + expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([1, 0]) + + pending.resolve() + await settle() + + expect([1, 2].map(tierId => endsOf(delegate, tierId))).toEqual([1, 1]) + }) + + it('answers a keyframe request of a view of another tier from that tier\'s buffer, writing one keyframe-request debug event of outcome answered for ' + + 'that tier', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP') + const { delegate, service } = harness({ tiers: SHARED_TIERS }) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from, 2) + const events = captureDebugEvents('HAP-NodeJS:Camera:MultiTier') + + // The view holds its own tier for its picture and the sound tier for its sound. + expect(streamsOf(delegate).map(stream => stream.tier.id)).toEqual([2, 1]) + + writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets(sliceFrame(300))) + await vi.advanceTimersByTimeAsync(0) + await until(() => unprotected(answer, from, 'video').length === 1) + + // The request opens the view again from the keyframe, which a live picture written after the turn a millisecond on hands it. + sendDatagram(from, answer, 'video', new ReferenceSRTP(CONTROLLER_KEYS.video).protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))) + await until(() => unprotect.mock.calls.length === 1) + await vi.advanceTimersByTimeAsync(1) + writeTierFrame(streamOf(delegate, 2), 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(200) + await until(() => unprotected(answer, from, 'video').length >= 2) + + const [live, opened] = unprotected(answer, from, 'video') + + expect(events.filter(({ kind }) => kind === 'keyframe-request').map(({ outcome, tierId }) => ({ outcome, tierId }))).toEqual([ + { outcome: 'answered', tierId: 2 }, + ]) + expect(opened.subarray(12)).toEqual(live.subarray(12)) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('sends a view of another tier no sound of the sound tier while the camera\'s Microphone is muted, no consumer taking that tier\'s picture, and its ' + + 'sound again once unmuted', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service, table } = harness({ tiers: SHARED_TIERS }) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from, 2) + + expect(table.videoTiers.get(1)!.demand!.halves.video.joined).toBe(0) + + table.muteMicrophone(true) + writeTierFrame(streamOf(delegate, 1), 'audio', { + data: Buffer.alloc(60, 1), + time: 0, + }) + await vi.advanceTimersByTimeAsync(500) + await settle() + + expect(from.received.audio).toEqual([]) + + table.muteMicrophone(false) + writeTierFrame(streamOf(delegate, 1), 'audio', { + data: Buffer.alloc(60, 2), + time: 20000, + }) + await vi.advanceTimersByTimeAsync(500) + await until(() => from.received.audio.length === 1) + + expect(unprotected(answer, from, 'audio').map(packet => packet.subarray(12))).toEqual([ + Buffer.alloc(60, 2), + ]) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + }) + + describe('holds on the tier table', () => { + it('answers cut to both holders waiting on one pending demand when its bound withdraws it, though the delegate\'s start resolves after', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, table } = harness() + const pending = deferred() + pendingStart(delegate, pending) + const tier = table.videoTiers.get(1)! + const first = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()) + const second = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()) + const answers = Promise.all([ + first.answer(), + second.answer(), + ]) + + expect([first.waiting, second.waiting]).toEqual([true, true]) + + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT) + pending.resolve() + + expect(await answers).toEqual(['cut', 'cut']) + expect(warn).toHaveBeenCalledOnce() + expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(true) + + // The withdrawal released what the start registered, and its later settling releases nothing more. + await settle() + + expect(disposedOf(delegate, streamOf(delegate))).toBe(1) + + first.release() + second.release() + await settle() + + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + expect(disposedOf(delegate, streamOf(delegate))).toBe(1) + }) + + it('answers refused to a join into a failed demand, and calls the route of a consumer waiting on the demand once when its stream fails', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, table } = harness() + const pending = deferred() + pendingStart(delegate, pending) + const tier = table.videoTiers.get(1)! + const waitingHolder = scriptedHolder() + const waiting = table.joinFrames(tier, 'video', waitingHolder, scriptedFrameConsumer()) + const answer = waiting.answer() + + streamOf(delegate).fail('The encoder crashed.') + streamOf(delegate).fail('The encoder crashed again.') + + expect(waitingHolder.tierFailed).toHaveBeenCalledOnce() + expect(await answer).toBe('refused') + + // The failed demand stands until its last join releases, and a join into it in the meantime is answered as refused, even once its start resolves. + const late = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()) + pending.resolve() + + expect(await late.answer()).toBe('refused') + expect(late.started).toBe(false) + expect(warn).toHaveBeenCalledOnce() + + waiting.release() + late.release() + await settle() + + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + expect(endedCalls(delegate)).toBe(1) + }) + + it('hands a frame consumer joining a tier whose start is pending every frame written during the wait, and answers it started once the start resolves', + async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, table } = harness() + const pending = deferred() + pendingStart(delegate, pending) + const consumer = scriptedFrameConsumer() + const hold = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer) + const answer = hold.answer() + const stream = streamOf(delegate) + + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0))) + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(34) + + expect(hold.waiting).toBe(true) + expect(consumer.taken.map(({ frame }) => frame.time)).toEqual([0, 33333]) + expect(stream.statistics().consumers).toBe(1) + + pending.resolve() + + expect(await answer).toBe('started') + + hold.release() + await settle() + }) + + it('answers refused to a frame consumer joining a tier whose start rejects, sends no demand end and hands it no frame written after', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, table } = harness() + delegate.tierDemandStarted.mockImplementationOnce(async () => { + throw new Error('The video encoder is busy.') + }) + const consumer = scriptedFrameConsumer() + const hold = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer) + + expect(await hold.answer()).toBe('refused') + + writeTierFrame(streamOf(delegate), 'video', sliceFrame(300)) + await vi.advanceTimersByTimeAsync(0) + hold.release() + await settle() + + expect(consumer.taken).toEqual([]) + expect(endedCalls(delegate)).toBe(0) + }) + + it('answers refused to a frame consumer joining a demand whose stream has failed, and ends the demand once at its last release', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, table } = harness() + const tier = table.videoTiers.get(1)! + const first = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()) + + expect(await first.answer()).toBe('started') + + streamOf(delegate).fail('The encoder crashed.') + const late = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()) + + expect(await late.answer()).toBe('refused') + expect(late.started).toBe(false) + + first.release() + await settle() + + expect(endedCalls(delegate)).toBe(0) + + late.release() + await settle() + + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + expect(endedCalls(delegate)).toBe(1) + expect(warn).toHaveBeenCalledOnce() + }) + + it('calls the route of each of two frame consumers joining one pending demand once when its stream fails, and answers each refused', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, table } = harness() + const pending = deferred() + pendingStart(delegate, pending) + const tier = table.videoTiers.get(1)! + const holders = [ + scriptedHolder(), + scriptedHolder(), + ] + const holds = holders.map(holder => table.joinFrames(tier, 'video', holder, scriptedFrameConsumer())) + const answers = Promise.all(holds.map(async hold => hold.answer())) + + streamOf(delegate).fail('The encoder crashed.') + + expect(holders.map(({ tierFailed }) => tierFailed.mock.calls.length)).toEqual([1, 1]) + expect(await answers).toEqual(['refused', 'refused']) + + pending.resolve() + + for (const hold of holds) { + hold.release() + } + + await settle() + + expect(endedCalls(delegate)).toBe(1) + }) + + it('answers cut to both of two frame consumers joining one pending demand when its bound withdraws it, though the start resolves after', + async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, table } = harness() + const pending = deferred() + pendingStart(delegate, pending) + const tier = table.videoTiers.get(1)! + const holds = [ + table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()), + table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()), + ] + const answers = Promise.all(holds.map(async hold => hold.answer())) + + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT) + pending.resolve() + + expect(await answers).toEqual(['cut', 'cut']) + expect(warn).toHaveBeenCalledOnce() + + for (const hold of holds) { + hold.release() + } + + await settle() + + // The withdrawal aborted the start's signal once and released what the start registered, and its later settling released nothing more. + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + expect(signalOf(delegate, streamOf(delegate)).aborted).toBe(true) + expect(disposedOf(delegate, streamOf(delegate))).toBe(1) + }) + }) + + describe('fan-out', () => { + it('sends each session the packets ffmpeg cuts written frames into as SRTP under its own key, SSRC and the tier\'s payload type, numbered on', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const firstEndpoint = await endpoint() + const secondEndpoint = await endpoint() + const first = await streaming(service, buildEmitterConnection(), firstEndpoint) + const second = await streaming(service, buildEmitterConnection(), secondEndpoint) + const stream = streamOf(delegate) + const cuts = [ + ...HEVC.frames[0].cuts[CUT], + ...HEVC.frames[1].cuts[CUT], + ] + + writeTierFrame(stream, 'video', { + ...vectorFrame(HEVC, 0, 0), + keyframe: true, + }) + writeTierFrame(stream, 'video', vectorFrame(HEVC, 1, 66667)) + await vi.advanceTimersByTimeAsync(67) + await until(() => firstEndpoint.received.video.length === cuts.length && secondEndpoint.received.video.length === cuts.length) + + for (const [answer, from] of [ + [first, firstEndpoint], + [second, secondEndpoint], + ] as const) { + const packets = unprotected(answer, from, 'video') + + expect(packets.map(packet => packet.subarray(12).toString('hex'))).toEqual(cuts) + expect(packets.map(packet => packet[1])).toEqual(cuts.map(() => 0x80 | 99)) + expect(packets.map(packet => packet.readUInt32BE(8))).toEqual(cuts.map(() => answer.videoSSRC)) + expect(packets.map(packet => (packet.readUInt16BE(2) - packets[0].readUInt16BE(2)) & 0xFFFF)).toEqual(cuts.map((_cut, index) => index)) + } + + expect(stream.statistics()).toEqual({ + packets: 2 * cuts.length, + bytes: 2 * cuts.reduce((total, cut) => total + 12 + cut.length / 2, 0), + drops: 0, + consumers: 4, + }) + expect(firstEndpoint.received.audio).toEqual([]) + }) + + it('drops and counts a malformed sample of the stream, a picture whose unit runs past its end and a sound of no octets, throwing nothing, and sends ' + + 'every session the next', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const firstEndpoint = await endpoint() + const secondEndpoint = await endpoint() + const base = udpSockets() + const firstConnection = buildEmitterConnection() + const secondConnection = buildEmitterConnection() + const first = await streaming(service, firstConnection, firstEndpoint) + const second = await streaming(service, secondConnection, secondEndpoint) + const stream = streamOf(delegate) + + // A picture whose unit's length runs past its end and a sound of no octets, each in a fragment of its own. + expect(() => { + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(Buffer.from('0000000a0201', 'hex')), + ], + })) + stream.write(tierStreamFragment({ + sound: [ + soundSample(Buffer.alloc(0)), + ], + })) + }).not.toThrow() + + expect(stream.statistics()).toEqual({ + packets: 0, + bytes: 0, + drops: 2, + consumers: 4, + }) + + // The next picture is the stream's keyframe, which every session is sent first. + stream.write(tierStreamFragment({ + picture: [ + pictureSample(vectorFrame(HEVC, 0).data, true), + ], + pictureTime: 3000n, + })) + await vi.advanceTimersByTimeAsync(0) + await until(() => firstEndpoint.received.video.length === 1 && secondEndpoint.received.video.length === 1) + + for (const [answer, from] of [ + [first, firstEndpoint], + [second, secondEndpoint], + ] as const) { + expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).toString('hex'))).toEqual(HEVC.frames[0].cuts[CUT]) + } + + expect(stream.statistics()).toEqual({ + packets: 2, + bytes: 2 * (12 + HEVC.frames[0].cuts[CUT][0].length / 2), + drops: 2, + consumers: 4, + }) + expect(await end(service, firstConnection, first.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(await end(service, secondConnection, second.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + await until(() => udpSockets() === base) + }) + + it('grows a sender\'s pool for a frame of 300 packets and three of 700 written in one turn, which leave in three, sending each whole with every datagram ' + + 'intact at its completion', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const held = holdSends(accessorySockets(createSocket).video) + const stream = streamOf(delegate) + const frames = [300, 400, 200, 100] + const sent: Buffer[] = [] + + writeTierFrame(stream, 'video', burstKeyframe(frames[0], 0)) + await vi.advanceTimersByTimeAsync(0) + sent.push(...held.map(send => send.sent)) + + expect(complete(held)).toBe(frames[0]) + + for (const [index, packets] of frames.slice(1).entries()) { + writeTierFrame(stream, 'video', burstFrame(packets, (index + 1) * 66667)) + } + + // Written in one turn, each frame leaves at its time's distance from the first, with no send completing between them. + await vi.advanceTimersByTimeAsync(200) + sent.push(...held.map(send => send.sent)) + + expect(complete(held)).toBe(1000 - frames[0]) + + // Every packet goes out under the session's key and the tier's payload type, numbered on, the marker on each frame's last packet, and each frame's + // fragments carry its slice, the keyframe's after the aggregation packet of its parameter sets. + const reference = new ReferenceSRTP(answer.videoSRTPParameters) + const packets = sent.map(datagram => reference.unprotect(datagram)!) + const ends = frames.map((_count, index) => frames.slice(0, index + 1).reduce((total, count) => total + count, 0) - 1) + const fragments = frames.map((count, index) => (index === 0) + ? count - 1 + : count) + + expect(packets.map(packet => packet[1] & 0x7F)).toEqual(packets.map(() => TIERS.videoStreamTiers.payloadType)) + expect(packets.every((packet, index) => ((packet.readUInt16BE(2) - packets[0].readUInt16BE(2)) & 0xFFFF) === index)).toBe(true) + expect(packets.flatMap((packet, index) => (packet[1] & 0x80) === 0 + ? [] + : [index])).toEqual(ends) + expect((packets[0][12] >> 1) & 0x3F).toBe(48) + expect(fragments.map((count, index) => Buffer.concat(packets.slice(ends[index] + 1 - count, ends[index] + 1).map(packet => packet.subarray(15))) + .equals(burstFrame(count).data.subarray(4 + SLICE.length)))).toEqual(frames.map(() => true)) + expect(stream.statistics()).toMatchObject({ packets: 1000, drops: 0 }) + }) + + it('keeps every datagram in flight intact and completing in order when its pool grows with its ring\'s oldest buffer the hundred-and-first', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const from = await endpoint() + await streaming(service, buildEmitterConnection(), from) + const held = holdSends(accessorySockets(createSocket).video) + const stream = streamOf(delegate) + + writeTierFrame(stream, 'video', burstKeyframe(100, 0)) + await vi.advanceTimersByTimeAsync(0) + + expect(complete(held)).toBe(100) + + // The burst grows the pool past the ring's end, and the frame after part of it completes takes the buffers those completions free. + writeTierFrame(stream, 'video', burstFrame(450, 66667)) + await vi.advanceTimersByTimeAsync(67) + + expect(held).toHaveLength(450) + expect(complete(held, 200)).toBe(200) + + writeTierFrame(stream, 'video', burstFrame(100, 133333)) + await vi.advanceTimersByTimeAsync(67) + + expect(held).toHaveLength(350) + expect(complete(held)).toBe(350) + expect(stream.statistics()).toMatchObject({ packets: 650, drops: 0 }) + }) + + it('grows a video sender\'s pool for a burst of 300 packets in one allocation of as many buffers again as it holds, 256 buffers\' octets', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const from = await endpoint() + await streaming(service, buildEmitterConnection(), from) + const held = holdSends(accessorySockets(createSocket).video) + const stream = streamOf(delegate) + // The stream's initialization segment and the burst's fragment are built before the spy, which reads the release's allocations alone. + const burst = tierStreamFragment({ + picture: [ + pictureSample(burstKeyframe(300).data, true), + ], + }) + + stream.write(tierStreamInitialization()) + + const alloc = vi.spyOn(Buffer, 'alloc') + + stream.write(burst) + await vi.advanceTimersByTimeAsync(0) + + // Each pooled buffer holds the largest packet the demand cuts and its SRTP tag. + expect(alloc.mock.calls).toEqual([ + [256 * (CUT + 10)], + ]) + expect(complete(held)).toBe(300) + }) + + it('counts each send whose completion reports an error, logging the first at debug and the rest as a count at the end, and streams on', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const held = holdSends(accessorySockets(createSocket).video) + const stream = streamOf(delegate) + const lines = captureDebug('HAP-NodeJS:Camera:MultiTier') + + writeTierFrame(stream, 'video', burstKeyframe(3)) + await vi.advanceTimersByTimeAsync(0) + + for (const send of held.splice(0)) { + send.fail(Object.assign(new Error('send EHOSTUNREACH 127.0.0.1'), { code: 'EHOSTUNREACH' })) + } + + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(34) + + expect(held).toHaveLength(1) + expect(complete(held)).toBe(1) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(lines.filter(line => line.includes('failed to send a packet: send EHOSTUNREACH'))).toHaveLength(1) + expect(lines.filter(line => line.includes('failed to send 2 more packets.'))).toHaveLength(1) + expect(stream.statistics()).toMatchObject({ packets: 4, drops: 0 }) + }) + + it('refuses and counts each packet a burst sends past its pool\'s ceiling, and sends a later frame whole', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const from = await endpoint() + await streaming(service, buildEmitterConnection(), from) + const held = holdSends(accessorySockets(createSocket).video) + const stream = streamOf(delegate) + + writeTierFrame(stream, 'video', burstKeyframe(2100, 0)) + await vi.advanceTimersByTimeAsync(0) + + expect(held).toHaveLength(2048) + expect(stream.statistics()).toMatchObject({ packets: 2048, drops: 2100 - 2048 }) + expect(complete(held)).toBe(2048) + + writeTierFrame(stream, 'video', burstFrame(10, 66667)) + await vi.advanceTimersByTimeAsync(67) + + expect(held).toHaveLength(10) + expect(complete(held)).toBe(10) + expect(stream.statistics()).toMatchObject({ packets: 2058, drops: 2100 - 2048 }) + }) + + it('numbers each packet a session\'s sender refuses at its pool\'s ceiling, and that session reads a gap of exactly the refused packets, while a session ' + + 'beside it with room reads its numbering unbroken', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const first = await endpoint() + const second = await endpoint() + const firstAnswer = await streaming(service, buildEmitterConnection(), first) + const firstHeld = holdSends(accessorySockets(createSocket).video) + const secondAnswer = await streaming(service, buildEmitterConnection(), second) + const secondHeld = holdSends(accessorySockets(createSocket).video) + const stream = streamOf(delegate) + const firstSent: Buffer[] = [] + const secondSent: Buffer[] = [] + + // A keyframe of 2000 packets fills most of each session's pool, and the second session's sends complete while the first session's stay in flight. + writeTierFrame(stream, 'video', burstKeyframe(2000, 0)) + await vi.advanceTimersByTimeAsync(0) + secondSent.push(...flush(secondHeld)) + + // A burst of 100 meets the first session's pool at its ceiling after 48 packets, which means its sender refuses the 52 after them, while the second session + // has room for all of them. A burst of 3 once every send has completed reaches each session whole. + writeTierFrame(stream, 'video', burstFrame(100, 66667)) + await vi.advanceTimersByTimeAsync(67) + firstSent.push(...flush(firstHeld)) + secondSent.push(...flush(secondHeld)) + writeTierFrame(stream, 'video', burstFrame(3, 133333)) + await vi.advanceTimersByTimeAsync(67) + firstSent.push(...flush(firstHeld)) + secondSent.push(...flush(secondHeld)) + + // Each packet a session sent, in order, unprotected under its keys. + const read = (answer: Prepared, sent: Buffer[]): Buffer[] => { + const reference = new ReferenceSRTP(answer.videoSRTPParameters) + + return sent.map(datagram => reference.unprotect(datagram)!) + } + const firstPackets = read(firstAnswer, firstSent) + const secondPackets = read(secondAnswer, secondSent) + + expect(stream.statistics()).toMatchObject({ drops: 52 }) + expect(firstPackets.map(packet => (packet.readUInt16BE(2) - firstPackets[0].readUInt16BE(2)) & 0xFFFF)).toEqual([ + ...Array.from({ length: 2048 }, (_packet, index) => index), + 2100, + 2101, + 2102, + ]) + expect([ + secondPackets.length, + unbroken(secondPackets), + ]).toEqual([2103, true]) + }) + }) + + describe('a view opening from the buffer', () => { + const MEDIA: readonly StreamTierMedium[] = ['video', 'audio'] + + it('hands a session joining a running tier its opening across turns, more packets than its video pool\'s ceiling with none refused, its sound joining ' + + 'the live releases, while the session streaming beside it reads its numbering unbroken', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const first = await endpoint() + const second = await endpoint() + const firstAnswer = await streaming(service, buildEmitterConnection(), first) + const firstHeld = heldSockets(accessorySockets(createSocket)) + const firstSent: Record = { video: [], audio: [] } + const stream = streamOf(delegate) + + // A keyframe of 1300 packets and pictures of 500 behind it, past the 2048 a video pool holds, and 140 sounds of 20 ms, past the 128 a sound pool + // holds, each released to the first session, whose sends complete as each step ends. + writeTierFrame(stream, 'video', { + ...burstFrame(1300, 0), + keyframe: true, + }) + writeTierFrame(stream, 'video', burstFrame(500, 66667)) + writeTierFrame(stream, 'video', burstFrame(500, 133333)) + + for (let index = 0; index < 140; index++) { + writeTierFrame(stream, 'audio', { + data: Buffer.alloc(60, 0x78), + time: index * 20000, + }) + } + + for (let step = 0; step < 60; step++) { + await vi.advanceTimersByTimeAsync(50) + + for (const medium of MEDIA) { + firstSent[medium].push(...flush(firstHeld[medium])) + } + } + + expect([firstSent.video.length, firstSent.audio.length]).toEqual([2300, 140]) + + const secondAnswer = await streaming(service, buildEmitterConnection(), second) + const secondHeld = heldSockets(accessorySockets(createSocket)) + const secondSent: Record = { video: [], audio: [] } + + // The opening takes its start in its first turn, a millisecond after the join, past every picture placed, which means it hands nothing before a live picture + // moves the edge. The sound joins the live releases, sent none of the sound the buffer kept. + await vi.advanceTimersByTimeAsync(1) + + expect([secondHeld.video.length, secondHeld.audio.length]).toEqual([0, 0]) + + // A live picture moves the edge past the whole stretch, and its release reaches each session: the opening's turn hands the keyframe and the next + // picture, and the turns after it hand nothing while no send completes. + writeTierFrame(stream, 'video', sliceFrame(300, 3000000)) + await vi.advanceTimersByTimeAsync(1) + + expect([secondHeld.video.length, secondHeld.audio.length]).toEqual([1800, 0]) + + await vi.advanceTimersByTimeAsync(5) + + expect(secondHeld.video).toHaveLength(1800) + + for (const medium of MEDIA) { + secondSent[medium].push(...flush(secondHeld[medium])) + } + + await vi.advanceTimersByTimeAsync(20) + + for (const medium of MEDIA) { + firstSent[medium].push(...flush(firstHeld[medium])) + secondSent[medium].push(...flush(secondHeld[medium])) + } + + const read = (answer: Prepared, medium: StreamTierMedium, sent: Buffer[]): Buffer[] => { + const reference = new ReferenceSRTP(medium === 'video' + ? answer.videoSRTPParameters + : answer.audioSRTPParameters) + + return sent.map(datagram => reference.unprotect(datagram)!) + } + + expect(stream.statistics()).toMatchObject({ drops: 0 }) + + for (const [answer, sent, sounds] of [ + [firstAnswer, firstSent, 140], + [secondAnswer, secondSent, 0], + ] as const) { + const video = read(answer, 'video', sent.video) + const audio = read(answer, 'audio', sent.audio) + + expect([video.length, audio.length]).toEqual([2301, sounds]) + expect([ + unbroken(video), + unbroken(audio), + ]).toEqual([true, true]) + } + }) + + it('numbers each session\'s packets from a start of its own, and a session streaming beside one that opens reads its numbering unbroken', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const first = await endpoint() + const second = await endpoint() + const firstAnswer = await streaming(service, buildEmitterConnection(), first) + const stream = streamOf(delegate) + + writeTierFrame(stream, 'video', { + ...burstFrame(3, 0), + keyframe: true, + }) + writeTierFrame(stream, 'video', burstFrame(2, 33333)) + await vi.advanceTimersByTimeAsync(50) + + // The second session opens on the keyframe and the picture after it while a live picture reaches each session. + const secondAnswer = await streaming(service, buildEmitterConnection(), second) + + writeTierFrame(stream, 'video', burstFrame(2, 66667)) + await vi.advanceTimersByTimeAsync(50) + writeTierFrame(stream, 'video', burstFrame(2, 100000)) + await vi.advanceTimersByTimeAsync(50) + await until(() => (first.received.video.length === 9) && (second.received.video.length === 9)) + + for (const [answer, from] of [ + [firstAnswer, first], + [secondAnswer, second], + ] as const) { + expect(unbroken(unprotected(answer, from, 'video'))).toBe(true) + } + }) + + it('numbers a session\'s packets on across frames from the start its sender holds, wrapping from 65535 to 0', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, management, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + // @ts-expect-error: private access + const { media } = management.sessions.get(answer.sessionIdentifier) + + // The sender's start stands three short of the range's end, and its fourth packet wraps. + media.video.sender.sequence = SEQUENCE_RANGE - 3 + + writeTierFrame(stream, 'video', burstKeyframe(4, 0)) + writeTierFrame(stream, 'video', burstFrame(1, 33333)) + await vi.advanceTimersByTimeAsync(50) + await until(() => from.received.video.length === 5) + + expect(unprotected(answer, from, 'video').map(packet => packet.readUInt16BE(2))).toEqual([ + SEQUENCE_RANGE - 3, + SEQUENCE_RANGE - 2, + SEQUENCE_RANGE - 1, + 0, + 1, + ]) + }) + + it('sends a session behind the live releases its first sender report at its first report moment after its first packet, its opening still behind', + async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const first = await endpoint() + const second = await endpoint() + + await streaming(service, buildEmitterConnection(), first) + + const firstHeld = heldSockets(accessorySockets(createSocket)) + const stream = streamOf(delegate) + + writeTierFrame(stream, 'video', { + ...burstFrame(1300, 0), + keyframe: true, + }) + writeTierFrame(stream, 'video', burstFrame(1000, 66667)) + await vi.advanceTimersByTimeAsync(50) + flush(firstHeld.video) + await vi.advanceTimersByTimeAsync(50) + flush(firstHeld.video) + + // The second session's room takes the keyframe and not the picture after it: it stays behind past its first report's moment, 2.5 seconds after + // its Start, and a live picture written after its join moves the edge, whose release hands it the keyframe, its first packets. + await streaming(service, buildEmitterConnection(), second) + + const secondSockets = accessorySockets(createSocket) + const secondHeld = heldSockets(secondSockets) + const reports = (): number => vi.mocked(secondSockets.video.send).mock.calls.filter(([, completion]) => typeof completion !== 'function').length + + writeTierFrame(stream, 'video', sliceFrame(300, 200000)) + await vi.advanceTimersByTimeAsync(2499) + + expect(secondHeld.video).toHaveLength(1300) + expect(reports()).toBe(0) + + await vi.advanceTimersByTimeAsync(1) + + expect(secondHeld.video).toHaveLength(1300) + expect(reports()).toBe(1) + }) + + it('sends a session behind the live releases a frame of its opening larger than its sender\'s pool at once, the packets past the pool\'s ceiling ' + + 'counted as drops, then the frame after it, with no turn left to run', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, management, service, table } = harness() + const from = await endpoint() + + // The library alone holds the tier while a keyframe of 2100 packets, past the 2048 a video pool holds, and a picture of 10 behind it fall due, which is why + // nothing is sent before the session joins. + table.hold(table.videoTiers.get(1)!, scriptedHolder()) + await settle() + + const stream = streamOf(delegate) + + writeTierFrame(stream, 'video', { + ...burstFrame(2100, 0), + keyframe: true, + }) + writeTierFrame(stream, 'video', burstFrame(10, 33333)) + await vi.advanceTimersByTimeAsync(50) + + const answer = await streaming(service, buildEmitterConnection(), from) + const held = heldSockets(accessorySockets(createSocket)) + // @ts-expect-error: private access + const { media } = management.sessions.get(answer.sessionIdentifier) + const released = vi.spyOn(TierPacer.prototype, 'release') + + expect([media.video.sender.capacity, media.audio.sender.capacity]).toEqual([2048, 128]) + + // A live picture written after the join moves the edge past the stretch at 67 ms, and that turn sends the keyframe's packets to the pool's ceiling + // and counts the rest as drops, and the picture behind it waits for room, which the turn after the sends complete hands it with the live picture. + writeTierFrame(stream, 'video', sliceFrame(300, 66667)) + await vi.advanceTimersByTimeAsync(17) + + expect(held.video).toHaveLength(2048) + expect(stream.statistics().drops).toBe(52) + + flush(held.video) + await vi.advanceTimersByTimeAsync(1) + + expect(held.video).toHaveLength(11) + + flush(held.video) + released.mockClear() + await vi.advanceTimersByTimeAsync(1000) + + expect(released).not.toHaveBeenCalled() + }) + + it.each([ + { ending: 'reset' }, + { ending: 'destroy' }, + ])('ends a session\'s opening at a $ending, sending it nothing after and throwing nothing from a turn', async ({ ending }) => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, management, service } = harness() + const first = await endpoint() + const second = await endpoint() + + await streaming(service, buildEmitterConnection(), first) + + const firstHeld = heldSockets(accessorySockets(createSocket)) + const stream = streamOf(delegate) + + writeTierFrame(stream, 'video', { + ...burstFrame(1300, 0), + keyframe: true, + }) + writeTierFrame(stream, 'video', burstFrame(1000, 66667)) + await vi.advanceTimersByTimeAsync(50) + flush(firstHeld.video) + await vi.advanceTimersByTimeAsync(50) + flush(firstHeld.video) + await streaming(service, buildEmitterConnection(), second) + + const secondHeld = heldSockets(accessorySockets(createSocket)) + + // A live picture written after the join moves the edge at 200 ms, which starts the opening before the ending, its room taking the keyframe alone. + writeTierFrame(stream, 'video', sliceFrame(300, 200000)) + await vi.advanceTimersByTimeAsync(105) + + expect(secondHeld.video).toHaveLength(1300) + + if (ending === 'reset') { + management.handleFactoryReset() + } else { + await management.destroy() + } + + await until(() => endedCalls(delegate) === 1) + flush(secondHeld.video) + await vi.advanceTimersByTimeAsync(1000) + await settle() + + expect(secondHeld.video).toHaveLength(0) + }) + + it('opens the picture of the one session whose controller reports a lost picture again from the latest keyframe released, past every timestamp its tier ' + + 'has placed, while its sound and a session beside it take the live releases alone', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const createSocket = vi.spyOn(dgram, 'createSocket') + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP') + const { delegate, service } = harness() + const first = await endpoint() + const second = await endpoint() + const firstAnswer = await streaming(service, buildEmitterConnection(), first) + const firstHeld = heldSockets(accessorySockets(createSocket)) + const secondAnswer = await streaming(service, buildEmitterConnection(), second) + const secondHeld = heldSockets(accessorySockets(createSocket)) + const stream = streamOf(delegate) + const sent: Record<'first' | 'second', Record> = { + first: { video: [], audio: [] }, + second: { video: [], audio: [] }, + } + // Completes every send each session's sockets hold, keeping the datagrams sent. + const collect = (): void => { + for (const medium of MEDIA) { + sent.first[medium].push(...flush(firstHeld[medium])) + sent.second[medium].push(...flush(secondHeld[medium])) + } + } + // A medium's packets a session was sent, unprotected under its keys, each read by its timestamp or its length. + const read = (answer: Prepared, medium: StreamTierMedium, datagrams: Buffer[]): Buffer[] => { + const reference = new ReferenceSRTP(medium === 'video' + ? answer.videoSRTPParameters + : answer.audioSRTPParameters) + + return datagrams.map(datagram => reference.unprotect(datagram)!) + } + // A sound of 20 ms, which each session takes live. + const sound = (time: number): void => writeTierFrame(stream, 'audio', { + data: Buffer.alloc(60, 0x78), + time, + }) + + // A keyframe and a picture after it, each one packet of a length of its own, and a sound beside each, which each session takes live. + writeTierFrame(stream, 'video', { + ...sliceFrame(300, 0), + keyframe: true, + }) + sound(0) + writeTierFrame(stream, 'video', sliceFrame(301, 33333)) + sound(20000) + await vi.advanceTimersByTimeAsync(50) + collect() + + // The first session's controller reports a lost picture, and a picture written after the turn a millisecond on moves the live edge past the stretch. + sendDatagram(first, firstAnswer, 'video', new ReferenceSRTP(CONTROLLER_KEYS.video).protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))) + await until(() => unprotect.mock.calls.length === 1) + writeTierFrame(stream, 'video', sliceFrame(302, 66667)) + sound(40000) + await vi.advanceTimersByTimeAsync(50) + collect() + + const stamp = (packet: Buffer): number => packet.readUInt32BE(4) + const firstVideo = read(firstAnswer, 'video', sent.first.video) + const secondVideo = read(secondAnswer, 'video', sent.second.video) + const highest = stamp(secondVideo[1]) + + // The first session is sent the keyframe and the picture after it live, and then the stretch again from that keyframe with the picture written after + // the request, each one millisecond past the highest picture placed before the request's turn plus its distance from the keyframe over fifty, at 90 kHz. + expect(firstVideo.map(packet => packet.length)).toEqual([ + ...secondVideo.slice(0, 2), + ...secondVideo, + ].map(packet => packet.length)) + expect(firstVideo.slice(2).map(stamp)).toEqual([0, 100 / 3, 200 / 3].map(distance => openingStamp(highest, distance) % 0x100000000)) + expect(read(firstAnswer, 'audio', sent.first.audio).map(stamp)).toEqual(read(secondAnswer, 'audio', sent.second.audio).map(stamp)) + expect(sent.first.audio).toHaveLength(3) + }) + + it('stamps the answer to a lost picture at home over a stretch past the heaviest maximum at the speed that holds its burst to fifty times it', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP') + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const held = heldSockets(accessorySockets(createSocket)) + const stream = streamOf(delegate) + const sent: Buffer[] = [] + // Completes every send the session's sockets hold, keeping the picture's datagrams. + const collect = (): void => { + sent.push(...flush(held.video)) + flush(held.audio) + } + // A heavy keyframe and a light picture after it, whose octets, read as a second, run past the heaviest maximum. + const keyframe = { + ...sliceFrame(780946, 0), + keyframe: true, + } + const picture = sliceFrame(296, 33333) + const rate = (keyframe.data.length + picture.data.length) * 8 / 1000 + + writeTierFrame(stream, 'video', keyframe) + writeTierFrame(stream, 'video', picture) + await vi.advanceTimersByTimeAsync(50) + collect() + + // The controller reports a lost picture, and a picture written after the turn a millisecond on moves the live edge past the stretch. + sendDatagram(from, answer, 'video', new ReferenceSRTP(CONTROLLER_KEYS.video).protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))) + await until(() => unprotect.mock.calls.length === 1) + writeTierFrame(stream, 'video', sliceFrame(302, 66667)) + await vi.advanceTimersByTimeAsync(50) + collect() + + // Each frame's timestamp once, in the order its packets were sent: the keyframe and the picture live, and then the answer's stretch. + const reference = new ReferenceSRTP(answer.videoSRTPParameters) + const stamps = sent.map(datagram => reference.unprotect(datagram)!.readUInt32BE(4)).filter((stamp, index, all) => stamp !== all[index - 1]) + + expect(rate).toBe(6250) + expect(stamps.slice(2)).toEqual([0, 100 / 3, 200 / 3].map(distance => openingStamp(stamps[1], distance, 50 * 5000 / rate) % 0x100000000)) + }) + + it('passes by a request while a session\'s own opening waits on its room, the opening running on unrestarted, and answers one once the session is level', + async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const createSocket = vi.spyOn(dgram, 'createSocket') + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP') + const { delegate, service } = harness() + const first = await endpoint() + const second = await endpoint() + const reference = new ReferenceSRTP(CONTROLLER_KEYS.video) + + await streaming(service, buildEmitterConnection(), first) + + const firstHeld = heldSockets(accessorySockets(createSocket)) + const stream = streamOf(delegate) + + writeTierFrame(stream, 'video', { + ...burstFrame(1300, 0), + keyframe: true, + }) + writeTierFrame(stream, 'video', burstFrame(1000, 66667)) + await vi.advanceTimersByTimeAsync(50) + flush(firstHeld.video) + await vi.advanceTimersByTimeAsync(50) + flush(firstHeld.video) + + // The second session's room takes the keyframe and not the picture after it, which a live picture written after its join moves the edge to. + const secondAnswer = await streaming(service, buildEmitterConnection(), second) + const secondHeld = heldSockets(accessorySockets(createSocket)) + + writeTierFrame(stream, 'video', sliceFrame(300, 200000)) + await vi.advanceTimersByTimeAsync(105) + + expect(secondHeld.video).toHaveLength(1300) + + // A request while the opening waits on its room is passed by: the turn after the sends complete hands the opening on with the picture after the + // keyframe and the live picture, and no keyframe again. + sendDatagram(second, secondAnswer, 'video', reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))) + await until(() => unprotect.mock.calls.length === 1) + flush(secondHeld.video) + await vi.advanceTimersByTimeAsync(1) + + expect(secondHeld.video).toHaveLength(1001) + + // A request once the session is level is answered: a live picture written after the turn a millisecond on moves the edge, and the session is sent the + // keyframe again. + flush(secondHeld.video) + sendDatagram(second, secondAnswer, 'video', reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))) + await until(() => unprotect.mock.calls.length === 2) + await vi.advanceTimersByTimeAsync(1) + writeTierFrame(stream, 'video', sliceFrame(301, 400000)) + await vi.advanceTimersByTimeAsync(200) + + expect(secondHeld.video).toHaveLength(1300) + }) + + it('writes one debug line for each authenticated picture loss indication, naming the session, its video tier and what the request came to', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP') + const { delegate, service } = harness() + const first = await endpoint() + const second = await endpoint() + const reference = new ReferenceSRTP(CONTROLLER_KEYS.video) + // A controller's picture loss indication on a session's video socket, waited on until the session has read it. + const request = async (from: Endpoint, answer: Prepared): Promise => { + const read = unprotect.mock.calls.length + + sendDatagram(from, answer, 'video', reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))) + await until(() => unprotect.mock.calls.length > read) + } + // Each session streams video tier 3, an identifier no sensor's audio tier carries. The tier a line names is told apart from the audio tier's. + const firstAnswer = await streaming(service, buildEmitterConnection(), first, 3) + const lines = captureDebug('HAP-NodeJS:Camera:MultiTier') + + // The first session asks before the stream writes a keyframe. The second, started once the keyframe is released, asks while its opening waits on a + // live picture nobody writes. The first then asks twice. + await request(first, firstAnswer) + writeTierFrame(streamOf(delegate, 3), 'video', { + ...sliceFrame(300, 0), + keyframe: true, + }) + await vi.advanceTimersByTimeAsync(50) + const secondAnswer = await streaming(service, buildEmitterConnection(), second, 3) + await vi.advanceTimersByTimeAsync(1) + await request(second, secondAnswer) + await request(first, firstAnswer) + await request(first, firstAnswer) + + // Each request's session and what it came to, in the order they were made. + const asked: [Prepared, string][] = [ + [firstAnswer, 'no keyframe kept'], + [secondAnswer, 'in an opening'], + [firstAnswer, 'answered'], + [firstAnswer, 'answered from this keyframe already'], + ] + + expect(lines.filter(line => line.includes('takes a keyframe request')).map(line => line.slice(line.indexOf('Multi-tier session')))).toEqual( + asked.map(([answer, outcome]) => `Multi-tier session ${answer.sessionIdentifier} takes a keyframe request on video tier 3: ${outcome}.`), + ) + }) + }) + + describe('session ends', () => { + it('ends a session and its tier\'s demand, ignores a stale stream, logs a throwing demand end, and answers no such stream and unknown', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(service, connection, from) + const firstStream = streamOf(delegate) + delegate.disposals.get(firstStream)!.mockImplementationOnce(() => { + throw new Error('The encoder would not stop.') + }) + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + await settle() + await until(() => udpSockets() === base) + + await expect(readSetupEndpoints(service, connection)).resolves.toBe('AgEC') + expect(endedCalls(delegate)).toBe(1) + expect(error.mock.calls.filter(([line]) => String(line).startsWith('MultiTierStreamingDelegate failed to end a tier demand: '))).toHaveLength(1) + + const next = await endpoint() + const later = await streaming(service, buildEmitterConnection(), next) + const secondStream = streamOf(delegate) + firstStream.write(tierStreamInitialization()) + firstStream.write(tierStreamFragment({ + picture: [ + pictureSample(vectorFrame(HEVC, 1).data), + ], + })) + writeTierFrame(secondStream, 'video', { + ...vectorFrame(HEVC, 0), + keyframe: true, + }) + await vi.advanceTimersByTimeAsync(0) + await until(() => next.received.video.length === 1) + await settle() + + expect(secondStream).not.toBe(firstStream) + expect(next.received.video).toHaveLength(1) + expect(unprotected(later, next, 'video').map(packet => packet.subarray(12).toString('hex'))).toEqual(HEVC.frames[0].cuts[CUT]) + expect(firstStream.statistics()).toEqual({ + packets: 0, + bytes: 0, + drops: 0, + consumers: 0, + }) + expect(secondStream.statistics().packets).toBe(1) + + const prepared = crypto.randomUUID() + await prepare(service, connection, from, prepared) + + expect(await end(service, connection, prepared)).toBe(RTPStreamingStatus.NO_SUCH_STREAM) + expect(await start(service, connection, prepared)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(await end(service, connection, UNKNOWN_SESSION)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + }) + + it('ends every session of a closing connection, closing its sockets, ending its demands, releasing its answers and removing its listeners', async () => { + const { delegate, service } = harness() + const from = await endpoint() + const closing = buildEmitterConnection() + const listeners = closing.listenerCount('closed') + const base = udpSockets() + await streaming(service, closing, from) + await prepare(service, closing, from, crypto.randomUUID()) + + closing.emit('closed') + await settle() + await until(() => udpSockets() === base) + + expect(endedCalls(delegate)).toBe(1) + expect(closing.listenerCount('closed')).toBe(listeners) + }) + + it('ends every session and releases every answer, a sessionless busy among them, when the camera or the service\'s streaming enabled turns off', async () => { + for (const turnOff of [ + (h: Harness): void => { + h.global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + }, + (h: Harness): void => { + h.service.updateCharacteristic(Characteristic.StreamingEnabled, false) + }, + ]) { + const h = harness({ maxSessions: 1 }) + const from = await endpoint() + const base = udpSockets() + const owner = buildEmitterConnection() + const refused = buildEmitterConnection() + const answer = await streaming(h.service, owner, from) + const busy = crypto.randomUUID() + expect(await prepare(h.service, refused, from, busy)).toEqual({ status: SetupEndpointsStatus.BUSY, sessionIdentifier: busy }) + + turnOff(h) + await settle() + await until(() => udpSockets() === base) + + expect(h.service.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + await expect(readSetupEndpoints(h.service, refused)).resolves.toBe('AgEC') + await expect(readSetupEndpoints(h.service, owner)).resolves.toBe('AgEC') + expect(await start(h.service, owner, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(await prepare(h.service, owner, from, busy)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier: busy }) + } + }) + + it('ends every session and releases every answer before a state-change delegate that throws at streaming enabled off', async () => { + const { management, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(service, connection, from) + management.setupStateChangeDelegate(() => { + throw new Error('The state could not be saved.') + }) + + await expect(service.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection())).rejects.toBeDefined() + await settle() + await until(() => udpSockets() === base) + + await expect(readSetupEndpoints(service, connection)).resolves.toBe('AgEC') + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + }) + + it('ends every session on a tier its stream fails, with one warning', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const base = udpSockets() + const first = buildEmitterConnection() + const second = buildEmitterConnection() + const firstAnswer = await streaming(service, first, from) + const secondAnswer = await streaming(service, second, from) + const stream = streamOf(delegate) + + stream.fail('The encoder crashed.') + stream.fail('The encoder crashed again.') + await settle() + await until(() => udpSockets() === base) + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toBe(`The plugin failed the stream of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" (The encoder ` + + 'crashed.), and every session on the tier ends.') + expect(await end(service, first, firstAnswer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(await end(service, second, secondAnswer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(endedCalls(delegate)).toBe(1) + }) + + it('clears each medium\'s sender as a streaming session ends', async () => { + const { management, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + // @ts-expect-error: private access + const { media } = management.sessions.get(answer.sessionIdentifier) + + expect([media.video.sender, media.audio.sender].every(sender => sender !== undefined)).toBe(true) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect([media.video.sender, media.audio.sender]).toEqual([undefined, undefined]) + }) + + it('warns nothing and ends no session for a stale stream\'s fail after its demand ended, a later session on the tier streaming on', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service } = harness() + const from = await endpoint() + const next = await endpoint() + const ending = buildEmitterConnection() + const later = buildEmitterConnection() + const ended = await streaming(service, ending, from) + const stale = streamOf(delegate) + + expect(await end(service, ending, ended.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + + const answer = await streaming(service, later, next) + stale.fail('The stopped encoder crashed.') + await settle() + writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300))) + await vi.advanceTimersByTimeAsync(0) + await until(() => next.received.video.length === 1) + + expect(warn).not.toHaveBeenCalled() + expect(unprotected(answer, next, 'video')).toHaveLength(1) + expect(await end(service, later, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('throws nothing from a frame written at every turn while a streaming session\'s exit runs', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, management, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + const thrown: unknown[] = [] + let exited = false + // Each frame a frame's length after the one before it: the stream's decode times rise. + let time = 0 + const write = (): void => { + try { + writeTierFrame(stream, 'video', sliceFrame(300, time)) + time += 33333 + } catch (error) { + thrown.push(error) + } + } + + /* A frame goes in at each of the exit's microtask turns, and at each turn of the event loop between them, and the mock clock moves on a frame's + * length at each: a frame falls due in a turn of the pacer's, until the whole exit has resolved. The exit's steps after its first run within one + * drain of the microtask and tick queues, a socket's close completing on a tick, which means a pacer's turn falls between them only where the clock moves at a + * microtask turn. + */ + const exiting = management.endSession(answer.sessionIdentifier).then(() => { + exited = true + }) + const running = (): boolean => !exited + + while (running()) { + for (let step = 0; step < 50 && running(); step++) { + write() + vi.advanceTimersByTime(33.333) + await Promise.resolve() + } + + write() + await vi.advanceTimersByTimeAsync(33.333) + await settle() + } + + await exiting + + expect(thrown).toEqual([]) + expect(logged.mock.calls.filter(([line]) => String(line).includes('consumer of the'))).toEqual([]) + expect(stream.statistics().consumers).toBe(0) + }) + + it('throws nothing from a frame written at every turn while a session waiting on its pending demand exits', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const logged = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, management, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + const pending = deferred() + await prepare(service, connection, from, identifier) + pendingStart(delegate, pending) + + const starting = start(service, connection, identifier) + await settle() + const stream = streamOf(delegate) + const thrown: unknown[] = [] + let exited = false + // Each frame a frame's length after the one before it: the stream's decode times rise. + let time = 0 + const write = (): void => { + try { + writeTierFrame(stream, 'video', sliceFrame(300, time)) + time += 33333 + } catch (error) { + thrown.push(error) + } + } + + expect(stream.statistics().consumers).toBe(2) + + // A frame goes in at each of the exit's microtask turns, and at each turn of the event loop between them, and the mock clock moves on a frame's + // length at each: a frame falls due in a turn of the pacer's, until the exit and the Start it cut have resolved, as the streaming exit's row reads. + const exiting = Promise.all([ + management.endSession(identifier), + starting, + ]).then(() => { + exited = true + }) + const running = (): boolean => !exited + + while (running()) { + for (let step = 0; step < 50 && running(); step++) { + write() + vi.advanceTimersByTime(33.333) + await Promise.resolve() + } + + write() + await vi.advanceTimersByTimeAsync(33.333) + await settle() + } + + await exiting + pending.resolve() + + expect(thrown).toEqual([]) + expect(logged.mock.calls.filter(([line]) => String(line).includes('consumer of the'))).toEqual([]) + expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(stream.statistics().consumers).toBe(0) + }) + + it('ends a session whose socket reports an error, with one debug line, the emit throwing nothing', async () => { + const createSocket = vi.spyOn(dgram, 'createSocket') + const { service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(service, connection, from) + const { video } = accessorySockets(createSocket) + const lines = captureDebug('HAP-NodeJS:Camera:MultiTier') + + expect(() => video.emit('error', Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' }))).not.toThrow() + + // The lines the emit wrote, read apart from those the session's end writes as the row waits on it. + const emitted = lines.length + + await settle() + await until(() => udpSockets() === base) + + expect(lines.slice(0, emitted).filter(line => line.includes('reports an error'))).toHaveLength(1) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + }) + + it.each([ + { ending: 'reset' }, + { ending: 'destroy' }, + ])('sends nothing a tier\'s pacer still holds after a $ending, and leaves it no timer to run', async ({ ending }) => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, management, service } = harness() + const from = await endpoint() + + await streaming(service, buildEmitterConnection(), from) + + const stream = streamOf(delegate) + const released = vi.spyOn(TierPacer.prototype, 'release') + + // A keyframe sent at once and the next picture, written in the same moment, held a frame's length behind it when the session ends. + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0))) + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 1) + + if (ending === 'reset') { + management.handleFactoryReset() + } else { + await management.destroy() + } + + await until(() => endedCalls(delegate) === 1) + released.mockClear() + await vi.advanceTimersByTimeAsync(1000) + await settle() + + expect(released).not.toHaveBeenCalled() + expect(stream.statistics().packets).toBe(1) + expect(from.received.video).toHaveLength(1) + }) + }) + + describe('rtcp', () => { + it('reads authenticated reports for liveness and keyframe requests, and drops a tampered and a replayed one', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP') + const timeout = vi.spyOn(globalThis, 'setTimeout') + // The hold's entry each keyframe request the session reads goes to. + const requests = vi.spyOn(TierHold.prototype, 'answerKeyframeRequest') + const { service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.video) + const arrived = async (count: number): Promise => until(() => unprotect.mock.calls.length === count) + const livenessWindows = (): number => timeout.mock.calls.filter(([, delay]) => delay === 25000).length + + sendDatagram(from, answer, 'video', reference.protectRTCP(Buffer.from(RECEIVER_REPORT, 'hex'))) + await arrived(1) + + expect(livenessWindows()).toBe(1) + expect(requests).not.toHaveBeenCalled() + + const pictureLoss = reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')) + sendDatagram(from, answer, 'video', pictureLoss) + await arrived(2) + sendDatagram(from, answer, 'video', reference.protectRTCP(Buffer.from(FULL_INTRA_REQUEST, 'hex'))) + await arrived(3) + + expect(requests).toHaveBeenCalledTimes(2) + + const tampered = reference.protectRTCP(Buffer.from(PICTURE_LOSS, 'hex')) + tampered[10] ^= 0x01 + sendDatagram(from, answer, 'video', tampered) + sendDatagram(from, answer, 'video', pictureLoss) + await arrived(5) + + expect(requests).toHaveBeenCalledTimes(2) + expect(livenessWindows()).toBe(1) + + // A picture loss indication that authenticates on the audio socket asks for nothing. + sendDatagram(from, answer, 'audio', new ReferenceSRTP(CONTROLLER_KEYS.audio).protectRTCP(Buffer.from(PICTURE_LOSS, 'hex'))) + await arrived(6) + + expect(requests).toHaveBeenCalledTimes(2) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('ends a session silent for the liveness window after one report, and keeps one that never reported at twice the window', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotectRTCP') + const { delegate, service } = harness() + const from = await endpoint() + const reporting = buildEmitterConnection() + const silent = buildEmitterConnection() + const reported = await streaming(service, reporting, from) + const quiet = await streaming(service, silent, from) + + // The sessions' one tier hands over pictures through each wait, which keeps its demand inside its silence bounds and leaves the liveness window + // alone to end a session. + sendDatagram(from, reported, 'audio', new ReferenceSRTP(CONTROLLER_KEYS.audio).protectRTCP(Buffer.from(RECEIVER_REPORT, 'hex'))) + await until(() => unprotect.mock.calls.length === 1) + await keepStreaming([ + streamOf(delegate), + ], 25000, { advance: advanceAsync }) + + expect(await end(service, reporting, reported.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + + await keepStreaming([ + streamOf(delegate), + ], 25000, { advance: advanceAsync, from: 25000000 }) + + expect(await end(service, silent, quiet.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('sends a video sender report at 2.5 seconds with its SSRC and counts, none for silent audio, and wraps the NTP seconds in 2036', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const reports = (): Buffer[] => from.received.video.filter(datagram => datagram[1] === 200) + + // One keyframe of a 300-octet slice and its parameter sets, which goes as one aggregation packet. + writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300))) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 1) + await vi.advanceTimersByTimeAsync(2499) + await settle() + + expect(reports()).toEqual([]) + + await vi.advanceTimersByTimeAsync(1) + await until(() => reports().length === 1) + + const reference = new ReferenceSRTP(answer.videoSRTPParameters) + const report = reference.unprotectRTCP(reports()[0])! + + expect(report).toHaveLength(28) + expect(report.subarray(0, 4).toString('hex')).toBe('80c80006') + expect(report.readUInt32BE(4)).toBe(answer.videoSSRC) + expect(report.readUInt32BE(20)).toBe(1) + expect(report.readUInt32BE(24)).toBe(setsAggregated(300)) + expect(from.received.audio).toEqual([]) + + // The clock answers 2036 only while the next report's timer fires, because the test runner reads Date.now too. + const in2036 = Date.UTC(2036, 1, 8) + const now = vi.spyOn(Date, 'now').mockReturnValue(in2036) + await vi.advanceTimersByTimeAsync(7000) + now.mockRestore() + await until(() => reports().length >= 2) + + expect(reference.unprotectRTCP(reports()[1])!.readUInt32BE(8)).toBe((Math.floor(in2036 / 1000) + 2208988800) % 0x100000000) + expect(from.received.audio).toEqual([]) + }) + + it('writes the video sender report\'s NTP fraction from the milliseconds past the clock\'s second', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const reports = (): Buffer[] => from.received.video.filter(datagram => datagram[1] === 200) + + writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300))) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 1) + + // The clock answers three milliseconds past a second only while the report's timer fires, because the test runner reads Date.now too. + const now = vi.spyOn(Date, 'now').mockReturnValue(Date.UTC(2036, 1, 8) + 3) + await vi.advanceTimersByTimeAsync(2500) + now.mockRestore() + await until(() => reports().length === 1) + + // Three milliseconds are three thousandths of the fraction word's 2^32, floored. + expect(new ReferenceSRTP(answer.videoSRTPParameters).unprotectRTCP(reports()[0])!.readUInt32BE(12)).toBe(0x00C49BA5) + }) + + it('writes the video sender report\'s RTP timestamp as the last frame\'s, advanced by the time since its write at the clock\'s rate', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + const reports = (): Buffer[] => from.received.video.filter(datagram => datagram[1] === 200) + + // The steady clock moves only as the row advances it: the frames are written 1460 and 1500 milliseconds into the session, a second before its first + // report at 2.5 seconds. + await vi.advanceTimersByTimeAsync(1460) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0))) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(40) + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 2) + await vi.advanceTimersByTimeAsync(1000) + await until(() => reports().length === 1) + + const reference = new ReferenceSRTP(answer.videoSRTPParameters) + const [first, last] = from.received.video.filter(datagram => datagram[1] !== 200).map(datagram => reference.unprotect(datagram)!.readUInt32BE(4)) + + expect((last - first) >>> 0).toBe(3000) + expect(reference.unprotectRTCP(reports()[0])!.readUInt32BE(16)).toBe((last + 1000 * 90) >>> 0) + }) + + it('advances a report\'s RTP timestamp by the steady time since the write when the time of day steps back an hour, stating that time\'s NTP time', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const reports = (): Buffer[] => from.received.video.filter(datagram => datagram[1] === 200) + + await vi.advanceTimersByTimeAsync(1500) + writeTierFrame(streamOf(delegate), 'video', keyframeWithSets(sliceFrame(300))) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 1) + + // The time of day stands an hour behind only while the report's timer fires, a second of the steady clock after the write, because the test runner + // reads Date.now too. + const stepped = Date.now() - 3600 * 1000 + const now = vi.spyOn(Date, 'now').mockReturnValue(stepped) + await vi.advanceTimersByTimeAsync(1000) + now.mockRestore() + await until(() => reports().length === 1) + + const reference = new ReferenceSRTP(answer.videoSRTPParameters) + const [placed] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4)) + const report = reference.unprotectRTCP(reports()[0])! + + expect(report.readUInt32BE(16)).toBe((placed + 1000 * 90) >>> 0) + expect(report.readUInt32BE(8)).toBe((Math.floor(stepped / 1000) + 2208988800) % 0x100000000) + }) + }) + + describe('frame consumers', () => { + it('hands a frame consumer beside a session every frame the session is sent, whole with its flags, timestamp and run, and no malformed one', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service, table } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const consumer = scriptedFrameConsumer() + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer) + const stream = streamOf(delegate) + const keyframe: TierFrame = { + ...sliceFrame(300, 0), + keyframe: true, + } + // The run the discontinuity opens starts on a keyframe as the first run does. + const frames = [ + keyframe, + sliceFrame(300, 33333), + { + data: Buffer.from('0000000a0201', 'hex'), + time: 66667, + }, + { + ...sliceFrame(300, 0, true), + keyframe: true, + }, + ] + + for (const frame of frames) { + writeTierFrame(stream, 'video', frame) + } + + // The discontinuity ends the run before the turn, which is why its frames leave at once with the run opened after it. + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 3) + + const timestamps = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4)) + + expect(consumer.taken.map(({ frame }) => [frame.time, frame.keyframe === true])).toEqual([frames[0], frames[1], frames[3]].map(({ keyframe, time }) => [ + time, + keyframe === true, + ])) + expect(consumer.taken.map(({ data }) => data.equals(sliceFrame(300).data))).toEqual([true, true, true]) + expect(consumer.taken.map(({ timestamp }) => timestamp >>> 0)).toEqual(timestamps) + expect(consumer.taken.map(({ opensRun }) => opensRun)).toEqual([true, false, true]) + expect(stream.statistics()).toMatchObject({ packets: 3, drops: 1 }) + }) + + it('raises a demand for a frame consumer alone, hands it frames and cuts none, and ends the demand once at its release', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const cut = vi.spyOn(FrameCutter.prototype, 'cut') + const { delegate, table } = harness() + const consumer = scriptedFrameConsumer() + const hold = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer) + + expect(await hold.answer()).toBe('started') + + const stream = streamOf(delegate) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0))) + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(34) + + expect(consumer.taken).toHaveLength(2) + expect(cut).not.toHaveBeenCalled() + expect(stream.statistics()).toEqual({ + packets: 0, + bytes: 0, + drops: 0, + consumers: 1, + }) + + hold.release() + hold.release() + await settle() + + expect(delegate.tierDemandStarted).toHaveBeenCalledOnce() + expect(endedCalls(delegate)).toBe(1) + }) + + it('counts a session once for each medium it takes and a frame consumer once on one demand, three consumers', async () => { + const { delegate, service, table } = harness() + await streaming(service, buildEmitterConnection(), await endpoint()) + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), scriptedFrameConsumer()) + + expect(streamOf(delegate).statistics().consumers).toBe(3) + }) + + it('calls a frame consumer\'s route once and ends the session beside it when the tier\'s stream fails', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service, table } = harness() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, await endpoint()) + const holder = scriptedHolder() + table.joinFrames(table.videoTiers.get(1)!, 'video', holder, scriptedFrameConsumer()) + + streamOf(delegate).fail('The encoder crashed.') + streamOf(delegate).fail('The encoder crashed again.') + await settle() + + expect(holder.tierFailed).toHaveBeenCalledOnce() + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + }) + + it('logs a frame consumer\'s throwing hand-over once and ends it through its route, the write throwing nothing and the next consumer taking the frame', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, table } = harness() + const tier = table.videoTiers.get(1)! + const throwingHolder = scriptedHolder() + const throwing = table.joinFrames(tier, 'video', throwingHolder, { + take: () => { + throw new Error('The sealer failed.') + }, + }) + const next = scriptedFrameConsumer() + table.joinFrames(tier, 'video', scriptedHolder(), next) + + expect(await throwing.answer()).toBe('started') + + const stream = streamOf(delegate) + + expect(() => writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0)))).not.toThrow() + expect(() => writeTierFrame(stream, 'video', sliceFrame(300, 33333))).not.toThrow() + await vi.advanceTimersByTimeAsync(34) + expect(error).toHaveBeenCalledOnce() + expect(String(error.mock.calls[0][0])).toMatch(/^A frame consumer of the picture of the video tier 1 of the video sensor ".+" failed to take a frame, and it /) + expect(throwingHolder.tierFailed).toHaveBeenCalledOnce() + expect(next.taken).toHaveLength(2) + }) + + it('completes the walk past a frame consumer whose hand-over ends its own holder, and passes it over once its release has run', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, table } = harness() + const tier = table.videoTiers.get(1)! + const after = [ + scriptedFrameConsumer(), + scriptedFrameConsumer(), + ] + const ended = scriptedFrameConsumer() + + // The consumer's way out of its own hand-over is its holder's end, which releases its hold in a later turn. + const ending: TierHold = table.joinFrames(tier, 'video', scriptedHolder(), { + take: (frame, timestamp, opensRun) => { + ended.take(frame, timestamp, opensRun) + void Promise.resolve().then(() => ending.release()) + }, + }) + + for (const consumer of after) { + table.joinFrames(tier, 'video', scriptedHolder(), consumer) + } + + expect(await ending.answer()).toBe('started') + + const stream = streamOf(delegate) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0))) + await vi.advanceTimersByTimeAsync(0) + + expect([ + ended.taken.length, + ...after.map(({ taken }) => taken.length), + ]).toEqual([1, 1, 1]) + + await settle() + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(34) + + expect([ + ended.taken.length, + ...after.map(({ taken }) => taken.length), + ]).toEqual([1, 2, 2]) + }) + + it('hands a frame consumer joining a video tier another consumer streams none of the frames released before its join, counting in consumers from ' + + 'it', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, table } = harness() + const tier = table.videoTiers.get(1)! + const streamer = scriptedFrameConsumer() + const consumer = scriptedFrameConsumer() + // A sound of the tier's stream at a time in microseconds. + const sound = (time: number): WrittenFrame => ({ + data: Buffer.alloc(60, 0x78), + time, + }) + + // Each consumer takes the tier's sound, which joins the live releases at once: its join alone decides what it is handed, where a consumer of the + // picture opens from the keyframe the buffer keeps. + expect(await table.joinFrames(tier, 'audio', scriptedHolder(), streamer).answer()).toBe('started') + + const stream = streamOf(delegate) + writeTierFrame(stream, 'audio', sound(0)) + writeTierFrame(stream, 'audio', sound(33333)) + await vi.advanceTimersByTimeAsync(34) + + expect(stream.statistics().consumers).toBe(1) + + table.joinFrames(tier, 'audio', scriptedHolder(), consumer) + + expect(consumer.taken).toEqual([]) + expect(stream.statistics().consumers).toBe(2) + + writeTierFrame(stream, 'audio', sound(66667)) + await vi.advanceTimersByTimeAsync(34) + + expect(consumer.taken.map(({ frame }) => frame.time)).toEqual([66667]) + expect(streamer.taken.map(({ frame }) => frame.time)).toEqual([0, 33333, 66667]) + }) + + it('hands a frame consumer carrying a member named send every frame through its join, and sends it no packet', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, table } = harness() + const send = vi.fn<(packet: Buffer, octets: number, now: number) => boolean>(() => true) + const consumer = { + ...scriptedFrameConsumer(), + send, + } + + expect(await table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer).answer()).toBe('started') + + const stream = streamOf(delegate) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0))) + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(34) + + expect(consumer.taken.map(({ frame }) => frame.time)).toEqual([0, 33333]) + expect(send).not.toHaveBeenCalled() + expect(stream.statistics()).toMatchObject({ packets: 0, consumers: 1 }) + }) + + it('hands a frame consumer raising a demand the stream written inside its tierDemandStarted', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, table } = harness() + const tier = table.videoTiers.get(1)! + const raiser = scriptedFrameConsumer() + + delegate.tierDemandStarted.mockImplementationOnce(async (stream) => { + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + keyframeSample(), + ], + })) + }) + + expect(await table.joinFrames(tier, 'video', scriptedHolder(), raiser).answer()).toBe('started') + await vi.advanceTimersByTimeAsync(0) + expect(raiser.taken.map(({ frame }) => frame.time)).toEqual([0]) + }) + }) + + describe('frame timing', () => { + it('times a first frame at one moment alike on two video tiers, each at its rate on the sensor\'s one clock, and a tier\'s sound two seconds after its ' + + 'picture two seconds of the sound\'s ticks later on the picture\'s run', async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. Its + // origin is a whole millisecond, which is why the sound's due moment stands exactly two seconds after its picture's: on a fractional origin that sum can round + // up, which arms the pacer's timer a millisecond past the row's two-second step and leaves the sound unsent. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const origin = Math.ceil(performance.now()) + const made = vi.spyOn(performance, 'now').mockReturnValue(origin) + const { delegate, service } = harness() + made.mockRestore() + const firstEndpoint = await endpoint() + const secondEndpoint = await endpoint() + const first = await streaming(service, buildEmitterConnection(), firstEndpoint, 1) + const second = await streaming(service, buildEmitterConnection(), secondEndpoint, 2) + + // Each tier's first frame, its keyframe, arrives a second after the management was made. + const now = vi.spyOn(performance, 'now').mockReturnValue(origin + 1000) + writeTierFrame(streamOf(delegate, 1), 'video', keyframeWithSets(sliceFrame(300, 5000000))) + writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets(sliceFrame(200, 9000000))) + writeTierFrame(streamOf(delegate), 'audio', { + data: Buffer.alloc(80, 0x78), + time: 7000000, + }) + await vi.advanceTimersByTimeAsync(0) + + // The sound, in a fragment of its own, falls due on its picture's schedule two seconds after that picture, and the steady clock stands half a second + // past that as the pacer releases it: its release stands apart from its presentation's distance and only one run places it two seconds on. + now.mockReturnValue(origin + 3500) + await vi.advanceTimersByTimeAsync(2000) + now.mockRestore() + await until(() => firstEndpoint.received.video.length === 1 && secondEndpoint.received.video.length === 1 && firstEndpoint.received.audio.length === 1) + + const [videoOne] = unprotected(first, firstEndpoint, 'video').map(packet => packet.readUInt32BE(4)) + const [videoTwo] = unprotected(second, secondEndpoint, 'video').map(packet => packet.readUInt32BE(4)) + const [audio] = unprotected(first, firstEndpoint, 'audio').map(packet => packet.readUInt32BE(4)) + + // Tier 1's picture opens its demand's one run, and the sound written in the same moment and timed two seconds after it stands two seconds of its + // ticks after that moment. + expect(videoTwo).toBe(videoOne) + expect((videoOne - 90000) >>> 0).toBe((audio - 48000 - 2 * 48000) >>> 0) + }) + + it('places a frame written after a malformed one at its own moment, which the malformed frame never moved', async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + const moment = performance.now() + + // A frame placed at its own moment, three seconds in, stands seventeen seconds of ticks before a discontinuity placed at twenty seconds in. Had the + // malformed frame at time zero opened the run, the frame timed ten seconds would stand ten seconds in, and the two only ten seconds of ticks apart. + const now = vi.spyOn(performance, 'now').mockReturnValue(moment) + writeTierFrame(stream, 'video', { + data: Buffer.from('0000000a0201', 'hex'), + time: 0, + }) + now.mockReturnValue(moment + 3000) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 10000000))) + await vi.advanceTimersByTimeAsync(0) + now.mockReturnValue(moment + 20000) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 10000000, true))) + await vi.advanceTimersByTimeAsync(0) + now.mockRestore() + await until(() => from.received.video.length === 2) + + const [placed, reopened] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4)) + + expect((reopened - placed) >>> 0).toBe(17000 * 90) + expect(stream.statistics().drops).toBe(1) + }) + + it('keeps a frame in its run when the time of day steps back an hour before it, and opens a later discontinuity at its steady moment\'s timestamp', async () => { + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone, each turn at the moment the spy holds. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const stream = streamOf(delegate) + const steady = performance.now() + const day = Date.now() + + // The clocks answer each write's moments only while it runs, because the test runner reads each clock: the time of day steps back an hour between the first + // two writes, while the steady clock moves forty milliseconds, and the discontinuity comes five seconds of the steady clock after that. + const now = vi.spyOn(performance, 'now').mockReturnValue(steady) + const time = vi.spyOn(Date, 'now').mockReturnValue(day) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0))) + await vi.advanceTimersByTimeAsync(0) + now.mockReturnValue(steady + 40) + time.mockReturnValue(day - 3600 * 1000) + writeTierFrame(stream, 'video', sliceFrame(300, 33333)) + await vi.advanceTimersByTimeAsync(0) + now.mockReturnValue(steady + 5040) + writeTierFrame(stream, 'video', keyframeWithSets(sliceFrame(300, 0, true))) + await vi.advanceTimersByTimeAsync(0) + now.mockRestore() + time.mockRestore() + await until(() => from.received.video.length === 3) + + const [first, second, reopened] = unprotected(answer, from, 'video').map(packet => packet.readUInt32BE(4)) + + expect((second - first) >>> 0).toBe(3000) + expect((reopened - first) >>> 0).toBe(5040 * 90) + }) + + it('keeps one run for sixty frames of a 30 fps source written in one turn, each frame\'s packet 3000 ticks after the one before, warning nothing', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const held = holdSends(accessorySockets(createSocket).video) + const stream = streamOf(delegate) + + // Each frame stands 33,333 or 33,334 microseconds after the one before, as a source's clock rounds a thirtieth of a second, and the last nearly two + // seconds after the first, a keyframe. + for (let frame = 0; frame < 60; frame++) { + const picture = sliceFrame(300, Math.round(frame * 1000000 / 30)) + + writeTierFrame(stream, 'video', (frame === 0) + ? keyframeWithSets(picture) + : picture) + } + + await vi.advanceTimersByTimeAsync(1967) + + const reference = new ReferenceSRTP(answer.videoSRTPParameters) + const timestamps = held.map(send => reference.unprotect(send.sent)!.readUInt32BE(4)) + + expect(complete(held)).toBe(60) + expect(timestamps.slice(1).map((timestamp, index) => (timestamp - timestamps[index]) >>> 0)).toEqual(timestamps.slice(1).map(() => 3000)) + expect(warn).not.toHaveBeenCalled() + }) + }) + + describe('keyframe parameter sets', () => { + // A keyframe of the parameter sets whose types it is given, each a synthetic unit opening with its type's NAL unit header, and an IDR picture slice. + function keyframeOf(types: readonly number[], time = 0): TierFrame { + return { + data: tierFrameData([ + ...types.map(type => nalUnit(Buffer.from([type << 1, 0x01]), 12)), + nalUnit(Buffer.from([0x26, 0x01]), 300), + ]), + keyframe: true, + time, + } + } + + // The RTP payloads a cutter at the default packet size makes of a frame, as hex. + function payloadsOf(frame: TierFrame): string[] { + const cutter = new FrameCutter('video', Buffer.alloc(CUT)) + const payloads: string[] = [] + + cutter.cut(frame.data, 0, true) + + for (let packet = cutter.next(); packet !== undefined; packet = cutter.next()) { + payloads.push(packet.subarray(12).toString('hex')) + } + + return payloads + } + + const sentence = `The stream of the video tier 1 of the video sensor "${SENSOR_UUID.toLowerCase()}" carries a keyframe without its video, sequence and ` + + 'picture parameter sets, in its sample or its initialization segment, which a viewer needs to decode it, and the keyframe is sent as it stands.' + + it('sends a session and hands a frame consumer a keyframe without its sequence parameter set as written, warning once for the demand', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service, table } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const consumer = scriptedFrameConsumer() + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer) + const stream = streamOf(delegate) + const lacking = keyframeOf([32, 34]) + + writeTierFrame(stream, 'video', lacking) + await vi.advanceTimersByTimeAsync(0) + + expect(warn.mock.calls).toEqual([ + [sentence], + ]) + + writeTierFrame(stream, 'video', keyframeOf([32, 34], 33333)) + await vi.advanceTimersByTimeAsync(34) + await until(() => from.received.video.length === 2 * payloadsOf(lacking).length) + + expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).toString('hex'))).toEqual([ + ...payloadsOf(lacking), + ...payloadsOf(lacking), + ]) + expect(consumer.taken.map(({ data }) => data.equals(lacking.data))).toEqual([true, true]) + expect(warn).toHaveBeenCalledOnce() + }) + + it('warns nothing for a keyframe carrying all three sets, a frame not marked a keyframe or an audio frame', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, table } = harness() + + expect(await table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), scriptedFrameConsumer()).answer()).toBe('started') + expect(await table.joinFrames(table.videoTiers.get(1)!, 'audio', scriptedHolder(), scriptedFrameConsumer()).answer()).toBe('started') + + writeTierFrame(streamOf(delegate), 'video', keyframeOf([32, 33, 34])) + writeTierFrame(streamOf(delegate), 'video', { + ...keyframeOf([], 33333), + keyframe: false, + }) + writeTierFrame(streamOf(delegate), 'audio', { + data: Buffer.from([0xFC, 0x01]), + keyframe: true, + time: 0, + }) + await vi.advanceTimersByTimeAsync(34) + + expect(warn).not.toHaveBeenCalled() + }) + + it('reads a stream\'s keyframe with the parameter sets its initialization segment carries, sending them in it and warning nothing, and warns once for ' + + 'a keyframe whose segment and sample hold none', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, table } = harness() + const sets = [32, 33, 34].map(type => nalUnit(Buffer.from([type << 1, 0x01]), 12)) + const slice = nalUnit(Buffer.from([0x26, 0x01]), 300) + const consumers = [1, 2].map(() => scriptedFrameConsumer()) + + for (const [index, consumer] of consumers.entries()) { + expect(await table.joinFrames(table.videoTiers.get(index + 1)!, 'video', scriptedHolder(), consumer).answer()).toBe('started') + } + + for (const [tierId, parameterSets] of [ + [1, sets], + [2, []], + ] as const) { + streamOf(delegate, tierId).write(tierStreamInitialization({ parameterSets })) + streamOf(delegate, tierId).write(tierStreamFragment({ + picture: [ + pictureSample(tierFrameData([slice]), true), + ], + })) + } + + await vi.advanceTimersByTimeAsync(0) + + expect(consumers.map(({ taken }) => taken.map(({ data }) => data.toString('hex')))).toEqual([ + [ + tierFrameData([...sets, slice]).toString('hex'), + ], + [ + tierFrameData([slice]).toString('hex'), + ], + ]) + expect(warn.mock.calls).toEqual([ + [ + sentence.replace('video tier 1', 'video tier 2'), + ], + ]) + }) + + it('sends a session each parameter set once in the packets of a keyframe that holds them over a stream whose initialization segment carries them too, ' + + 'and hands a frame consumer the keyframe as its sample holds it', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, service, table } = harness() + const from = await endpoint() + const answer = await streaming(service, buildEmitterConnection(), from) + const consumer = scriptedFrameConsumer() + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer) + const stream = streamOf(delegate) + const holding = keyframeOf([32, 33, 34]) + + stream.write(tierStreamInitialization({ + parameterSets: [32, 33, 34].map(type => nalUnit(Buffer.from([type << 1, 0x01]), 12)), + })) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(holding.data, true), + ], + })) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === payloadsOf(holding).length) + + expect(unprotected(answer, from, 'video').map(packet => packet.subarray(12).toString('hex'))).toEqual(payloadsOf(holding)) + expect(consumer.taken.map(({ data }) => data.toString('hex'))).toEqual([ + holding.data.toString('hex'), + ]) + expect(warn).not.toHaveBeenCalled() + }) + + it('warns again for the first such keyframe of a new demand of the tier', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, table } = harness() + const tier = table.videoTiers.get(1)! + const first = table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()) + + expect(await first.answer()).toBe('started') + + writeTierFrame(streamOf(delegate), 'video', keyframeOf([33, 34])) + writeTierFrame(streamOf(delegate), 'video', keyframeOf([33, 34], 33333)) + await vi.advanceTimersByTimeAsync(34) + first.release() + await settle() + + expect(await table.joinFrames(tier, 'video', scriptedHolder(), scriptedFrameConsumer()).answer()).toBe('started') + + writeTierFrame(streamOf(delegate), 'video', keyframeOf([33, 34])) + await vi.advanceTimersByTimeAsync(0) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + expect(warn.mock.calls).toEqual([ + [sentence], + [sentence], + ]) + }) + }) + + describe('talkback', () => { + it('writes each authenticated talkback packet whole to one sink, each in its own datagram\'s buffer with the tag behind it, and ends the sink at End', async () => { + const { delegate, service } = harness() + const { packets, release, start: startSink } = keepingSink() + delegate.talkbackStarted.mockImplementation(startSink) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + // The first packet carries the marker bit above its payload type, as a talkspurt's first packet does. + const plain = [ + talkbackPacket(1, { payloadType: 0x80 | 110 }), + talkbackPacket(2), + talkbackPacket(3), + ] + const sent = plain.map(packet => reference.protect(packet)) + + // Each packet goes through the controller's socket, and each kept buffer is the one Node handed the session for its datagram. + for (const [index, datagram] of sent.entries()) { + sendDatagram(from, answer, 'audio', datagram) + await until(() => packets.length === index + 1) + } + + expect(delegate.talkbackStarted.mock.calls.map(([talker]) => talker.sensorUUID)).toEqual([ + SENSOR_UUID.toLowerCase(), + ]) + expect(packets).toEqual(plain) + expect(new Set(packets.map(packet => packet.buffer)).size).toBe(packets.length) + + for (const [index, packet] of packets.entries()) { + expect(packet.byteOffset).toBe(0) + expect(Buffer.from(packet.buffer, packet.length)).toEqual(sent[index].subarray(packet.length)) + } + + expect(release).not.toHaveBeenCalled() + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(release).toHaveBeenCalledOnce() + }) + + it('drops talkback before Start, tampered, of another SSRC or payload type, too short, on the video socket or replayed, logging a refusal once', async () => { + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const { sink, packets } = keepingSink() + delegate.talkbackStarted.mockReturnValue(sink) + const from = await endpoint() + const connection = buildEmitterConnection() + const identifier = crypto.randomUUID() + await prepare(service, connection, from, identifier) + const { video, audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + const videoReference = new ReferenceSRTP(CONTROLLER_KEYS.video) + + audio.emit('message', reference.protect(talkbackPacket(1))) + + expect(await start(service, connection, identifier)).toBe(RTPStreamingStatus.SUCCESS) + + const tampered = reference.protect(talkbackPacket(2)) + tampered[20] ^= 0x01 + const otherSSRC = reference.protect(talkbackPacket(3, { ssrc: 0x55667788 })) + const otherPayloadType = reference.protect(talkbackPacket(4, { payloadType: 111 })) + const short = Buffer.from([0x80, 110, 0, 5]) + const videoUnderVideoKey = videoReference.protect(talkbackPacket(6)) + const videoUnderAudioKey = reference.protect(talkbackPacket(7)) + const accepted = reference.protect(talkbackPacket(8)) + // The replay is taken before the accepted packet is handed over, because the session unprotects that packet in its own buffer. + const replay = Buffer.from(accepted) + const lines = captureDebug('HAP-NodeJS:Camera:MultiTier') + + audio.emit('message', tampered) + audio.emit('message', otherSSRC) + audio.emit('message', otherPayloadType) + audio.emit('message', short) + video.emit('message', videoUnderVideoKey) + video.emit('message', videoUnderAudioKey) + audio.emit('message', accepted) + audio.emit('message', replay) + + expect(await end(service, connection, identifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(packets).toEqual([ + talkbackPacket(8), + ]) + expect(delegate.talkbackStarted).toHaveBeenCalledOnce() + expect(lines.filter(line => line.includes('drops a talkback datagram'))).toHaveLength(1) + expect(lines.filter(line => line.includes('dropped 1 more talkback datagram'))).toHaveLength(1) + }) + + it('unprotects and drops talkback while the camera\'s Speaker is muted, starting no sink and keeping a started one, writes a packet first seen ' + + 'unmuted, and refuses one that arrived muted and arrives again as a replay', async () => { + let muted = true + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotect') + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness({ + speakerMuted: () => muted, + }) + const { packets, release, start: startSink } = keepingSink() + delegate.talkbackStarted.mockImplementation(startSink) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const { audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + const sent = [1, 2, 3].map(sequence => reference.protect(talkbackPacket(sequence))) + const tampered = reference.protect(talkbackPacket(4)) + const lines = captureDebug('HAP-NodeJS:Camera:MultiTier') + + tampered[20] ^= 0x01 + unprotect.mockClear() + + // Each datagram is handed over as a copy, since the session unprotects one it reads in its own buffer. A packet that arrived muted can arrive again. + audio.emit('message', Buffer.from(sent[0])) + + expect([delegate.talkbackStarted.mock.calls.length, unprotect.mock.calls.length]).toEqual([0, 1]) + + audio.emit('message', tampered) + + expect(lines.filter(line => line.includes('drops a talkback datagram'))).toHaveLength(1) + + muted = false + audio.emit('message', Buffer.from(sent[0])) + audio.emit('message', Buffer.from(sent[1])) + muted = true + audio.emit('message', Buffer.from(sent[2])) + + expect(packets).toEqual([ + talkbackPacket(2), + ]) + expect(release).not.toHaveBeenCalled() + expect(delegate.talkbackStarted).toHaveBeenCalledOnce() + expect(unprotect).toHaveBeenCalledTimes(5) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(release).toHaveBeenCalledOnce() + expect(lines.filter(line => line.includes('drops a talkback datagram'))).toHaveLength(1) + expect(lines.filter(line => line.includes('dropped 1 more talkback datagram'))).toHaveLength(1) + }) + + it('follows the controller\'s SRTP index through a mute of more than half the sequence range, writing each packet after it in order to the sink the ' + + 'first packet started', async () => { + let muted = false + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness({ + speakerMuted: () => muted, + }) + const { packets, start: startSink } = keepingSink() + delegate.talkbackStarted.mockImplementation(startSink) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const { audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + // One packet past half the sequence range, which an index estimate from the first packet cannot bridge. A session that read none of the muted + // packets would read the next one under the wrong rollover counter. + const mutedPackets = 0x8000 + 1 + const unmuted = [2, 3, 4].map(offset => mutedPackets + offset) + + audio.emit('message', reference.protect(talkbackPacket(1))) + muted = true + + for (let sequence = 2; sequence < 2 + mutedPackets; sequence++) { + audio.emit('message', reference.protect(talkbackPacket(sequence))) + } + + muted = false + + for (const sequence of unmuted) { + audio.emit('message', reference.protect(talkbackPacket(sequence))) + } + + expect(packets).toEqual([1, ...unmuted].map(sequence => talkbackPacket(sequence))) + expect(delegate.talkbackStarted).toHaveBeenCalledOnce() + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + }) + + it('declines talkback for a delegate without talkbackStarted, one that answers undefined and one that throws, unprotecting and asking once', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotect') + const createSocket = vi.spyOn(dgram, 'createSocket') + const { tierDemandStarted } = scriptedTierDelegate() + const answering = scriptedTierDelegate() + const throwing = scriptedTierDelegate() + throwing.talkbackStarted.mockImplementation(() => { + throw new Error('The decoder would not start.') + }) + + const delegates: MultiTierStreamingDelegate[] = [ + { tierDemandStarted }, + answering, + throwing, + ] + + for (const delegate of delegates) { + const { service } = harness({ delegate }) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const { audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + unprotect.mockClear() + + audio.emit('message', reference.protect(talkbackPacket(1))) + audio.emit('message', reference.protect(talkbackPacket(2))) + + expect(unprotect).toHaveBeenCalledOnce() + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + } + + expect([answering.talkbackStarted.mock.calls.length, throwing.talkbackStarted.mock.calls.length]).toEqual([1, 1]) + expect(error.mock.calls.filter(([line]) => String(line).startsWith('MultiTierStreamingDelegate failed to start talkback: '))).toHaveLength(1) + }) + + it('writes synchronously to a sink whose write and whose talker\'s cleanup throw, logging the first failed write, the disposal and a count of the rest, ' + + 'and answers End', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + // The sink is a decoder class's instance, registered on its talker as it is answered, and its throwing disposal is the talker's cleanup. + const sink = { + [Symbol.dispose]: vi.fn<() => void>(() => { + throw new Error('The decoder would not close.') + }), + write: vi.fn(() => { + throw new Error('The decoder is full.') + }), + } + delegate.talkbackStarted.mockImplementation(talker => talker.use(sink)) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const { audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + + for (const sequence of [1, 2, 3]) { + expect(() => audio.emit('message', reference.protect(talkbackPacket(sequence)))).not.toThrow() + expect(sink.write).toHaveBeenCalledTimes(sequence) + } + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(sink[Symbol.dispose]).toHaveBeenCalledOnce() + expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual([ + 'TalkbackSink failed to write a packet', + `MultiTierStreamingDelegate failed to end the talkback of multi-tier session ${answer.sessionIdentifier}`, + `TalkbackSink failed 2 more writes before multi-tier session ${answer.sessionIdentifier} ended.`, + ]) + }) + + it('ends a sink once, after its last write, at End, at its connection\'s close and at destroy, and writes it nothing after', async () => { + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, management, service } = harness() + const sinks: KeepingSink[] = [] + delegate.talkbackStarted.mockImplementation((talker) => { + const kept = keepingSink() + sinks.push(kept) + + return kept.start(talker) + }) + const from = await endpoint() + const ending = buildEmitterConnection() + const closing = buildEmitterConnection() + const destroyed = buildEmitterConnection() + const sessions: { answer: Prepared, talk: (sequence: number) => boolean }[] = [] + + for (const connection of [ending, closing, destroyed]) { + const answer = await streaming(service, connection, from) + const { audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + const talk = (sequence: number): boolean => audio.emit('message', reference.protect(talkbackPacket(sequence))) + + talk(1) + talk(2) + sessions.push({ answer, talk }) + } + + expect(await end(service, ending, sessions[0].answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + closing.emit('closed') + await settle() + await management.destroy() + + for (const [index, { release, sink }] of sinks.entries()) { + sessions[index].talk(3) + + expect(sink.write).toHaveBeenCalledTimes(2) + expect(release).toHaveBeenCalledOnce() + expect(release.mock.invocationCallOrder[0]).toBeGreaterThan(Math.max(...sink.write.mock.invocationCallOrder)) + } + + expect(sinks).toHaveLength(sessions.length) + }) + + it('gives each streaming session a sink of its own, written only its own controller\'s talkback', async () => { + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const sinks: KeepingSink[] = [] + delegate.talkbackStarted.mockImplementation(() => { + const kept = keepingSink() + sinks.push(kept) + + return kept.sink + }) + const from = await endpoint() + const first = await streaming(service, buildEmitterConnection(), from) + const firstSockets = accessorySockets(createSocket) + const second = await streaming(service, buildEmitterConnection(), from) + const secondSockets = accessorySockets(createSocket) + const firstReference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + const secondReference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + + firstSockets.audio.emit('message', firstReference.protect(talkbackPacket(1))) + secondSockets.audio.emit('message', secondReference.protect(talkbackPacket(10))) + firstSockets.audio.emit('message', firstReference.protect(talkbackPacket(2))) + + expect(first.sessionIdentifier).not.toBe(second.sessionIdentifier) + expect(delegate.talkbackStarted).toHaveBeenCalledTimes(2) + expect(sinks.map(({ packets }) => packets)).toEqual([ + [ + talkbackPacket(1), + talkbackPacket(2), + ], + [ + talkbackPacket(10), + ], + ]) + }) + + it('neither arms nor restarts the liveness window with talkback: a session silent in RTCP after one report ends and one that only talks streams on', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + const sinks: KeepingSink[] = [] + delegate.talkbackStarted.mockImplementation((talker) => { + const kept = keepingSink() + sinks.push(kept) + + return kept.start(talker) + }) + const from = await endpoint() + const reporting = buildEmitterConnection() + const talking = buildEmitterConnection() + const reported = await streaming(service, reporting, from) + const reportedSockets = accessorySockets(createSocket) + const talked = await streaming(service, talking, from) + const talkedSockets = accessorySockets(createSocket) + const reportedReference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + const talkedReference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + + // The sessions' one tier hands over pictures through each wait, which keeps its demand inside its silence bounds and leaves the liveness window + // alone to end a session. + reportedSockets.audio.emit('message', reportedReference.protectRTCP(Buffer.from(RECEIVER_REPORT, 'hex'))) + await keepStreaming([ + streamOf(delegate), + ], 20000, { advance: advanceAsync }) + reportedSockets.audio.emit('message', reportedReference.protect(talkbackPacket(1))) + talkedSockets.audio.emit('message', talkedReference.protect(talkbackPacket(1))) + await keepStreaming([ + streamOf(delegate), + ], 5000, { advance: advanceAsync, from: 20000000 }) + + expect(await end(service, reporting, reported.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + + await keepStreaming([ + streamOf(delegate), + ], 25000, { advance: advanceAsync, from: 25000000 }) + + expect(await end(service, talking, talked.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(sinks).toHaveLength(2) + expect(sinks.map(({ release }) => release.mock.calls.length)).toEqual([1, 1]) + }) + + it('starts no talkback in an exit, ends at once a sink whose delegate ended the session, and ends inside its write a sink that fails its stream', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const unprotect = vi.spyOn(SRTPContext.prototype, 'unprotect') + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, management, service } = harness() + const from = await endpoint() + + // A datagram emitted in the turn the session's exit begins, while its listeners still stand. + const exiting = await streaming(service, buildEmitterConnection(), from) + const exitingSockets = accessorySockets(createSocket) + const exited = management.endSession(exiting.sessionIdentifier) + exitingSockets.audio.emit('message', new ReferenceSRTP(CONTROLLER_KEYS.audio).protect(talkbackPacket(1))) + await exited + + expect(unprotect).not.toHaveBeenCalled() + expect(delegate.talkbackStarted).not.toHaveBeenCalled() + + // A delegate whose call ends the session before it answers a sink. + const ended = await streaming(service, buildEmitterConnection(), from) + const endedSockets = accessorySockets(createSocket) + const endedSink = keepingSink() + delegate.talkbackStarted.mockImplementationOnce((talker) => { + void management.endSession(ended.sessionIdentifier) + + return endedSink.start(talker) + }) + + expect(() => endedSockets.audio.emit('message', new ReferenceSRTP(CONTROLLER_KEYS.audio).protect(talkbackPacket(1)))).not.toThrow() + expect(endedSink.release).toHaveBeenCalledOnce() + expect(endedSink.sink.write).not.toHaveBeenCalled() + + // A sink whose write fails its tier's stream, which ends the session inside that write. + const failingConnection = buildEmitterConnection() + const failing = await streaming(service, failingConnection, from) + const failingSockets = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + const calls: string[] = [] + const failingSink = { + write: vi.fn(() => { + calls.push('write') + streamOf(delegate).fail('The decoder failed.') + calls.push('write returns') + }), + } + delegate.talkbackStarted.mockImplementationOnce((talker) => { + talker.defer(() => calls.push('release')) + + return failingSink + }) + + failingSockets.audio.emit('message', reference.protect(talkbackPacket(1))) + failingSockets.audio.emit('message', reference.protect(talkbackPacket(2))) + await settle() + + expect(await end(service, failingConnection, failing.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect(calls).toEqual(['write', 'release', 'write returns']) + }) + + it('counts each rejection of an async write as a failed write, logging the first and a count of the rest, and answers End with none left unhandled', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + let writes = 0 + // A plain async write rather than a mock, because a mock's own tracking of the promise it returns would handle the rejection the session must handle. + const sink: TalkbackSink = { + write: async () => { + writes++ + throw new Error('The decoder is full.') + }, + } + delegate.talkbackStarted.mockReturnValue(sink) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const { audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + // The listener collects each rejection no handler takes during the row, any of which would end a Homebridge process. + const unhandled: unknown[] = [] + const collect = (reason: unknown): void => { + unhandled.push(reason) + } + + process.on('unhandledRejection', collect) + + try { + audio.emit('message', reference.protect(talkbackPacket(1))) + audio.emit('message', reference.protect(talkbackPacket(2))) + await settle() + + expect(writes).toBe(2) + expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual(['TalkbackSink failed to write a packet']) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + await settle() + } finally { + process.off('unhandledRejection', collect) + } + + expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual([ + 'TalkbackSink failed to write a packet', + `TalkbackSink failed 1 more write before multi-tier session ${answer.sessionIdentifier} ended.`, + ]) + expect(unhandled).toEqual([]) + }) + + it('declines an answer whose then cannot be read, throwing nothing from the socket, logging one line and neither asking again nor writing it', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const createSocket = vi.spyOn(dgram, 'createSocket') + const { sink, packets } = keepingSink() + const { delegate, service } = harness() + const dispose = vi.fn<() => void>() + // A sink whose then getter throws, which means the read that asks whether the answer is a promise is the read that throws. + const unreadable = { + [Symbol.dispose]: dispose, + write: sink.write, + get then(): never { + throw new Error('The answer cannot be read.') + }, + } + delegate.talkbackStarted.mockReturnValue(unreadable as unknown as TalkbackSink) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const { audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + + expect(() => audio.emit('message', reference.protect(talkbackPacket(1)))).not.toThrow() + expect(() => audio.emit('message', reference.protect(talkbackPacket(2)))).not.toThrow() + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + + expect(delegate.talkbackStarted).toHaveBeenCalledOnce() + expect(packets).toEqual([]) + expect(sink.write).not.toHaveBeenCalled() + expect(dispose).not.toHaveBeenCalled() + expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual(['MultiTierStreamingDelegate failed to start talkback']) + }) + + it('counts the rejection of a thenable a write returns that is no promise as a failed write, logging the first and a count of the rest', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const createSocket = vi.spyOn(dgram, 'createSocket') + const { delegate, service } = harness() + // Every write answers a thenable that rejects as its then is called and is no Promise, which means only a read of then reaches its rejection. + const rejecting = { + then: (_resolved: unknown, rejected: (reason: unknown) => void) => rejected(new Error('The decoder is full.')), + } + const sink: TalkbackSink = { + write: (() => rejecting) as unknown as TalkbackSink['write'], + } + delegate.talkbackStarted.mockReturnValue(sink) + const from = await endpoint() + const connection = buildEmitterConnection() + const answer = await streaming(service, connection, from) + const { audio } = accessorySockets(createSocket) + const reference = new ReferenceSRTP(CONTROLLER_KEYS.audio) + + audio.emit('message', reference.protect(talkbackPacket(1))) + audio.emit('message', reference.protect(talkbackPacket(2))) + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(error.mock.calls.map(([line]) => String(line).split(':')[0])).toEqual([ + 'TalkbackSink failed to write a packet', + `TalkbackSink failed 1 more write before multi-tier session ${answer.sessionIdentifier} ended.`, + ]) + }) + }) + + describe('owner surface', () => { + it('serializes, restores and resets streaming enabled, ends every session at a reset or destroy run twice, and ignores an unknown session', async () => { + const { management, service } = harness() + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + + expect(management.serialize()).toEqual({ streamingEnabled: true }) + + management.deserialize({ streamingEnabled: false }) + + expect(management.serialize()).toEqual({ streamingEnabled: false }) + + management.deserialize({ streamingEnabled: 'on' } as unknown as { streamingEnabled: boolean }) + + expect(management.serialize()).toEqual({ streamingEnabled: false }) + + management.handleFactoryReset() + const answer = await streaming(service, connection, from) + management.handleFactoryReset() + management.handleFactoryReset() + await settle() + await until(() => udpSockets() === base) + + expect(management.serialize()).toEqual({ streamingEnabled: true }) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + await expect(management.endSession(UNKNOWN_SESSION)).resolves.toBeUndefined() + + await streaming(service, connection, from) + await Promise.all([ + management.destroy(), + management.destroy(), + ]) + await until(() => udpSockets() === base) + + const sessionIdentifier = crypto.randomUUID() + expect(await prepare(service, connection, from, sessionIdentifier)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier }) + }) + + it('reports each change of streaming enabled with the sensor, views at home, the value and the reason', async () => { + const { changes, management, service } = harness() + const streamingEnabled = service.getCharacteristic(Characteristic.StreamingEnabled) + + await streamingEnabled.handleSetRequest(false, buildEmitterConnection()) + streamingEnabled.updateValue(true) + management.deserialize({ streamingEnabled: false }) + management.handleFactoryReset() + + expect(changes).toEqual([ + { + reason: 'write', + sensorUUID: SENSOR_UUID.toLowerCase(), + value: false, + where: 'home', + }, + { + reason: 'update', + sensorUUID: SENSOR_UUID.toLowerCase(), + value: true, + where: 'home', + }, + { + reason: 'restore', + sensorUUID: SENSOR_UUID.toLowerCase(), + value: false, + where: 'home', + }, + { + reason: 'reset', + sensorUUID: SENSOR_UUID.toLowerCase(), + value: true, + where: 'home', + }, + ]) + }) + }) + + describe('over paired connections', () => { + const serverUsername = 'CA:FE:00:00:00:03' + const clientUsername = 'CA:FE:00:00:00:04' + + let accessory: Accessory + let accessoryInfo: AccessoryInfo + let clients: HAPHTTPClient[] + let clientInfo: { username: string, privateKey: Buffer, publicKey: Buffer } + + beforeEach(() => { + accessoryInfo = AccessoryInfo.create(serverUsername) + // @ts-expect-error: private access + accessoryInfo.setupID = Accessory._generateSetupID() + accessoryInfo.displayName = 'Camera' + accessoryInfo.category = Categories.IP_CAMERA + accessoryInfo.pincode = '031-45-154' + accessoryInfo.save = vi.fn() + + const clientKeyPair = tweetnacl.sign.keyPair() + clientInfo = { + username: clientUsername, + privateKey: Buffer.from(clientKeyPair.secretKey), + publicKey: Buffer.from(clientKeyPair.publicKey), + } + accessoryInfo.addPairedClient(clientUsername, clientInfo.publicKey, PermissionTypes.ADMIN) + + // The published accessory loads the paired record above in place of a stored one, as the legacy stream's paired rows do. + vi.spyOn(AccessoryInfo, 'load').mockReturnValue(accessoryInfo) + accessory = new Accessory('Camera', uuid.generate('multi-tier stream management over paired connections')) + clients = [] + }) + + afterEach(async () => { + for (const client of clients) { + client.destroy() + } + await accessory.destroy() + }) + + it('prepares, starts, streams to and ends a session for a paired controller, its answer read on its connection and its start in the write response', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + const { delegate, service } = harness() + accessory.addService(service) + const listening: Promise<[port: number, hostname: string]> = awaitEventOnce(accessory, AccessoryEventTypes.LISTENING) + await accessory.publish({ + username: serverUsername, + pincode: accessoryInfo.pincode, + category: Categories.IP_CAMERA, + advertiser: MDNSAdvertiser.BONJOUR, + port: 0, + }) + const [port] = await listening + + const client = new HAPHTTPClient('127.0.0.1', port) + await client.connect() + clients.push(client) + client.enableEncryption(await new PairVerifyClient(client).sendPairVerify({ + username: serverUsername, + publicKey: Buffer.from(accessoryInfo.signPk), + }, clientInfo)) + + const from = await endpoint() + const sessionIdentifier = crypto.randomUUID() + const setupEndpoints = { aid: accessory.aid!, iid: service.getCharacteristic(Characteristic.SetupEndpoints).iid! } + const streamingControl = { aid: accessory.aid!, iid: service.getCharacteristic(Characteristic.RTPStreamingControl).iid! } + const command = async (request: RTPStreamingControlRequest): Promise => { + const response = await client.sendCharacteristicWrite({ + characteristics: [ + { + ...streamingControl, + value: encodeRTPStreamingControlRequest(request), + r: true, + }, + ], + }) + + return decodeRTPStreamingControlResponse((response.body!.characteristics[0] as { value: string }).value) + } + + await client.sendCharacteristicWrite({ + characteristics: [ + { + ...setupEndpoints, + value: setupRequest(from, sessionIdentifier), + }, + ], + }) + const [read] = (await client.sendCharacteristicRead([setupEndpoints])).body.characteristics + const answer = decodeSetupEndpointsResponse((read as { value: string }).value) as Prepared + + expect(answer.status).toBe(SetupEndpointsStatus.SUCCESS) + expect(await command({ + sessionIdentifier, + command: RTPStreamingCommand.START, + videoTier: 2, + videoSSRC: CONTROLLER_SSRCS.video, + audioTier: 1, + audioSSRC: CONTROLLER_SSRCS.audio, + })).toEqual({ sessionIdentifier, status: RTPStreamingStatus.SUCCESS }) + + // One keyframe of a slice of 1000 octets and its parameter sets, which goes as one aggregation packet at either family's size, the slice its last unit. + const unit = nalUnit(SLICE, 1000) + writeTierFrame(streamOf(delegate, 2), 'video', keyframeWithSets({ + data: tierFrameData([unit]), + time: 0, + })) + await vi.advanceTimersByTimeAsync(0) + await until(() => from.received.video.length === 1) + + const plain = new ReferenceSRTP(answer.videoSRTPParameters).unprotect(from.received.video[0])! + + expect(plain.readUInt32BE(8)).toBe(answer.videoSSRC) + expect(plain.subarray(12)).toHaveLength(setsAggregated(1000)) + expect(plain.subarray(plain.length - unit.length).equals(unit)).toBe(true) + expect(await command({ sessionIdentifier, command: RTPStreamingCommand.END })).toEqual({ sessionIdentifier, status: RTPStreamingStatus.SUCCESS }) + }) + }) + + describe('camera controller wiring', () => { + const GLOBAL_KEY = 'cameraCapabilities:globalOperatingMode' + const CAPABILITIES_KEY = 'cameraCapabilities:cameraCapabilities' + // The HKSV3 recording management's keys, the last of the block's. + const RECORDING_KEYS = [ + 'cameraCapabilities:cameraBufferManagement', + 'cameraCapabilities:cameraKeyManagement', + 'cameraCapabilities:cameraClientCertificateManagement', + ] + const SECOND_SENSOR = videoSensor('B0000002-0000-4000-8000-000000000002', { intent: CameraSensorIntent.PACKAGE }) + const SECOND_KEY = 'cameraCapabilities:multiTierStream:b0000002-0000-4000-8000-000000000002' + const REMOVED_SENSOR = { + ...SECOND_SENSOR, + uuid: 'C0000003-0000-4000-8000-000000000003', + } + const REMOVED_KEY = 'cameraCapabilities:multiTierStream:c0000003-0000-4000-8000-000000000003' + // Each sensor's WebRTC stream service key, which every camera with the block holds after the multi-tier keys. + const WEBRTC_KEY = 'cameraCapabilities:webRTCStream:a1b2c3d4-0000-4000-8000-000000000001' + const SECOND_WEBRTC_KEY = 'cameraCapabilities:webRTCStream:b0000002-0000-4000-8000-000000000002' + + // The cameras a row builds, removed after it. The global hook's wait for the sockets covers their sessions too. + const cameras: CameraController[] = [] + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + }) + + // A camera with the camera capabilities block over the given sensors and streaming options, by default the fixture's with its no-op delegate, which + // records from its camera buffer. + function wiredCamera(sensors: readonly CameraVideoSensor[] = [SENSOR, SECOND_SENSOR], streamingOptions = idleStreaming()): CameraController { + const camera = new CameraController(capabilitiesCameraOptions({ + videoSensors: [...sensors], + streaming: streamingOptions, + })) + + cameras.push(camera) + return camera + } + + // A wired camera's services, constructed and configured as a first run of the accessory configures them, and the camera handed a published context. + function configured(camera: CameraController): CameraControllerServiceMap { + const map = camera.constructServices() + camera.configureServices() + handPublishedContext(camera) + + return map + } + + function multiTierServiceOf(map: CameraControllerServiceMap, key: string): CameraMultiTierRTPStreamManagement { + return map[key] as CameraMultiTierRTPStreamManagement + } + + function prefixedKeys(map: CameraControllerServiceMap): string[] { + return Object.keys(map).filter(key => key.startsWith('cameraCapabilities:') && map[key] !== undefined) + } + + // The tier table a wired camera built a video sensor's management with. + function tableOf(camera: CameraController, sensorUUID: string): TierTable { + // @ts-expect-error: private access + return camera.multiTierStreamManagements.get(sensorUUID.toLowerCase()).table + } + + it('gives each video sensor\'s management a tier table of its own, built for that sensor', () => { + const camera = wiredCamera() + const map = configured(camera) + const tables = [SENSOR, SECOND_SENSOR].map(sensor => tableOf(camera, sensor.uuid)) + + expect(tables[0]).not.toBe(tables[1]) + expect(tables.map(table => table.sensorUUID)).toEqual([SENSOR, SECOND_SENSOR].map(sensor => sensor.uuid.toLowerCase())) + expect(tables.map(table => MultiTierStreamManagement.serviceKey(table.streamTiers.sensorUUID))).toEqual([SERVICE_KEY, SECOND_KEY]) + expect([SERVICE_KEY, SECOND_KEY].map(key => multiTierServiceOf(map, key).getCharacteristic(Characteristic.SupportedVideoStreamTiers).value)) + .toEqual(tables.map(table => encodeSupportedVideoStreamTiers(table.streamTiers.videoStreamTiers))) + }) + + it('answers a sensor\'s best tier: the most pixels, the higher target bitrate between two of one size, and the earlier advertised between two of both', + () => { + // The best tier's identifier among tiers of the widths and bitrates given, each at 16 by 9 and identified by its place from 1. + const bestOf = (...tiers: (readonly [number, number])[]): number | undefined => bestStreamTier(tiers.map(([width, targetAverageBitrate], index) => ({ + ...TIERS.videoStreamTiers.tiers[0], + height: width * 9 / 16, + identifier: index + 1, + targetAverageBitrate, + width, + })))?.identifier + + expect(bestOf([1280, 768], [1920, 1000], [1920, 1700], [640, 180])).toBe(3) + expect(bestOf([1920, 1700], [1920, 1700])).toBe(1) + expect(bestOf([640, 180], [1280, 768])).toBe(2) + expect(bestOf()).toBeUndefined() + }) + + it('holds a sensor\'s tiers in their advertised order, each carrying the very stream tier object the sensor\'s WebRTC service is handed', () => { + const sensors = [SENSOR, SECOND_SENSOR] + const camera = new CameraController(capabilitiesCameraOptions({ + videoSensors: sensors, + streaming: idleStreaming(), + webrtc: webRTCStreamingOptions(), + })) + cameras.push(camera) + const handed = vi.spyOn(camera as unknown as { webRTCStreamManagementOptions: () => WebRTCStreamManagementOptions[] }, 'webRTCStreamManagementOptions') + + configured(camera) + + const webRTCOptions = handed.mock.results.at(-1)!.value as WebRTCStreamManagementOptions[] + + expect(webRTCOptions.map(options => options.sensorUUID)).toEqual(sensors.map(sensor => sensor.uuid.toLowerCase())) + + for (const { audioStreamTiers, sensorUUID, videoStreamTiers } of webRTCOptions) { + const table = tableOf(camera, sensorUUID) + const videoTiers = Array.from(table.videoTiers.values()) + + expect(Array.from(table.videoTiers.keys())).toEqual(videoStreamTiers.tiers.map(tier => tier.identifier)) + expect(videoTiers).toHaveLength(videoStreamTiers.tiers.length) + + for (const [index, tier] of videoTiers.entries()) { + expect(tier.advertised).toBe(videoStreamTiers.tiers[index]) + } + + expect(table.audioTier.advertised).toBe(audioStreamTiers.tiers[0]) + } + }) + + it('constructs one multi-tier stream service per video sensor under its key after the capabilities key, and none without the block', () => { + const map = wiredCamera().constructServices() + + expect(prefixedKeys(map)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + SERVICE_KEY, + SECOND_KEY, + WEBRTC_KEY, + SECOND_WEBRTC_KEY, + ...RECORDING_KEYS, + ]) + expect(map[SERVICE_KEY]!.UUID).toBe(Service.CameraMultiTierRTPStreamManagement.UUID) + expect(map[SERVICE_KEY]!.subtype).toBe(SENSOR_UUID.toLowerCase()) + expect(prefixedKeys(new CameraController(createCameraControllerOptions()).constructServices())).toEqual([]) + }) + + it('keys each sensor\'s service and advertises its configuration in the plugin\'s order, the first Primary, for a camera given its package sensor first', + () => { + const map = wiredCamera([SECOND_SENSOR, SENSOR]).constructServices() + const decoded = decodeCameraCapabilities(map[CAPABILITIES_KEY]!.getCharacteristic(Characteristic.CameraCapabilitiesData).value as string) + + expect(prefixedKeys(map)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + SECOND_KEY, + SERVICE_KEY, + SECOND_WEBRTC_KEY, + WEBRTC_KEY, + ...RECORDING_KEYS, + ]) + expect(decoded.cameraSensors.map(({ sensorIntent, sensorType, sensorUUID }) => ({ sensorIntent, sensorType, sensorUUID }))).toEqual([ + { + sensorIntent: CameraSensorIntent.PACKAGE, + sensorType: CameraSensorType.PRIMARY, + sensorUUID: SECOND_SENSOR.uuid.toLowerCase(), + }, + { + sensorIntent: CameraSensorIntent.MAIN, + sensorType: CameraSensorType.GENERIC, + sensorUUID: SENSOR_UUID.toLowerCase(), + }, + ]) + }) + + it('constructs every service in the order the accessory adds them, the block first, and links each sensor after the data stream service', () => { + const map = wiredCamera().constructServices() + + expect(Object.keys(map)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + SERVICE_KEY, + SECOND_KEY, + WEBRTC_KEY, + SECOND_WEBRTC_KEY, + ...RECORDING_KEYS, + 'microphone', + 'speaker', + 'motionService', + 'occupancyService', + 'cameraEventRecordingManagement', + 'cameraOperatingMode', + 'dataStreamTransportManagement', + ]) + expect(map.speaker).toBeUndefined() + expect(map.cameraEventRecordingManagement!.linkedServices).toEqual([ + map.dataStreamTransportManagement, + map.motionService, + map.occupancyService, + ]) + }) + + it('adopts each saved sensor service, creates a missing one and deletes a removed sensor\'s at a restore, keeping every claimed key', () => { + const saved = savedMapOf(wiredCamera([SENSOR, REMOVED_SENSOR])) + const adopted = saved[SERVICE_KEY] + + const restored = wiredCamera().initWithServices(saved)! + + expect(restored[SERVICE_KEY]).toBe(adopted) + expect(restored[SECOND_KEY]!.UUID).toBe(Service.CameraMultiTierRTPStreamManagement.UUID) + expect(restored[REMOVED_KEY]).toBeUndefined() + expect(prefixedKeys(restored)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + SERVICE_KEY, + SECOND_KEY, + WEBRTC_KEY, + SECOND_WEBRTC_KEY, + ...RECORDING_KEYS, + ]) + }) + + it('builds each configuration from the streaming options it validated, whatever the plugin changes in its options object afterward', async () => { + const streamingOptions = idleStreaming() + const sensors = [ + videoSensor(SENSOR_UUID), + SECOND_SENSOR, + ] + const camera = wiredCamera(sensors, streamingOptions) + configured(camera) + const videoStreamTiers = encodeSupportedVideoStreamTiers(TIERS.videoStreamTiers) + + // The plugin drops the second sensor, changes the first's tier in place and sets a session bound validation refuses, then reconfigures. + sensors.pop() + sensors[0].tiers[0].bitrate = 1000 + streamingOptions.maxSessions = 0 + camera.handleControllerRemoved() + + const map = configured(camera) + const service = multiTierServiceOf(map, SERVICE_KEY) + const from = await endpoint() + + expect(prefixedKeys(map)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + SERVICE_KEY, + SECOND_KEY, + WEBRTC_KEY, + SECOND_WEBRTC_KEY, + ...RECORDING_KEYS, + ]) + expect(service.getCharacteristic(Characteristic.SupportedVideoStreamTiers).value).toBe(videoStreamTiers) + expect(await prepare(service, buildEmitterConnection(), from, crypto.randomUUID())).toMatchObject({ status: SetupEndpointsStatus.SUCCESS }) + }) + + it('serializes and restores each sensor\'s slice, carries a removed sensor\'s and a record without the block, and drops it at a reset', () => { + const SENSOR_SLICE = SENSOR_UUID.toLowerCase() + const SECOND_SLICE = SECOND_SENSOR.uuid.toLowerCase() + + expect(wiredCamera().serialize()!.multiTierStreamManagements).toBeUndefined() + + const camera = wiredCamera() + configured(camera) + + expect(camera.serialize()!.multiTierStreamManagements).toEqual({ + [SENSOR_SLICE]: { streamingEnabled: true }, + [SECOND_SLICE]: { streamingEnabled: true }, + }) + + const restored = wiredCamera([SENSOR]) + const map = configured(restored) + restored.deserialize({ + streamManagements: [], + multiTierStreamManagements: { + [SENSOR_SLICE]: { streamingEnabled: false }, + [SECOND_SLICE]: { streamingEnabled: false }, + }, + }) + + expect(multiTierServiceOf(map, SERVICE_KEY).getCharacteristic(Characteristic.StreamingEnabled).value).toBe(false) + expect(restored.serialize()!.multiTierStreamManagements).toEqual({ + [SENSOR_SLICE]: { streamingEnabled: false }, + [SECOND_SLICE]: { streamingEnabled: false }, + }) + + restored.handleFactoryReset() + + expect(restored.serialize()!.multiTierStreamManagements).toEqual({ + [SENSOR_SLICE]: { streamingEnabled: true }, + }) + + const plain = new CameraController(createCameraControllerOptions()) + const record = { + [SECOND_SLICE]: { streamingEnabled: false }, + } + plain.deserialize({ + streamManagements: [], + multiTierStreamManagements: record, + }) + + expect(plain.serialize()!.multiTierStreamManagements).toEqual(record) + + plain.handleFactoryReset() + + expect(plain.serialize()!.multiTierStreamManagements).toBeUndefined() + + // A record that is no plain object, or a slice that is none, restores nothing and throws nothing. + expect(() => restored.deserialize({ + streamManagements: [], + multiTierStreamManagements: [] as unknown as Record, + })).not.toThrow() + expect(() => restored.deserialize({ + streamManagements: [], + multiTierStreamManagements: { [SENSOR_SLICE]: null } as unknown as Record, + })).not.toThrow() + expect(restored.serialize()!.multiTierStreamManagements).toEqual({ + [SENSOR_SLICE]: { streamingEnabled: true }, + }) + }) + + it('ends every multi-tier service\'s sessions and turns its status active off at camera off, and one service\'s alone at its streaming enabled', async () => { + const map = configured(wiredCamera()) + const first = multiTierServiceOf(map, SERVICE_KEY) + const second = multiTierServiceOf(map, SECOND_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const firstAnswer = await streaming(first, connection, from) + const secondAnswer = await streaming(second, connection, from) + + second.updateCharacteristic(Characteristic.StreamingEnabled, false) + await settle() + await until(() => udpSockets() === base + 2) + + expect(first.getCharacteristic(Characteristic.StatusActive).value).toBe(true) + expect(second.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + expect(await end(second, connection, secondAnswer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + + map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + await settle() + await until(() => udpSockets() === base) + + expect(first.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + expect(await end(first, connection, firstAnswer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + }) + + it.each([ + { + back: (camera: CameraController): void => camera.updateSourceState('available'), + leave: (camera: CameraController): void => camera.updateSourceState('away'), + leaving: 'its source stated away', + }, + { + back: (camera: CameraController): void => handPublishedContext(camera), + leave: (camera: CameraController): void => camera.handleAccessoryContext({ + accessoryInformation: new Service.AccessoryInformation('Camera') as AccessoryInformation, + accessoryUUID: NUMBERED_ACCESSORY_UUID, + published: false, + }), + leaving: 'its accessory not published', + }, + ])('fails a setup endpoints write with the communication failure while the camera is out of service, $leaving, binding no socket and moving no ' + + 'status active, answers error while it is switched off as well, and success once it is back and switched on', async ({ back, leave }) => { + const camera = wiredCamera() + const map = configured(camera) + const service = multiTierServiceOf(map, SERVICE_KEY) + const statusActive = service.getCharacteristic(Characteristic.StatusActive) + const from = await endpoint() + const connection = buildEmitterConnection() + const createSocket = vi.spyOn(dgram, 'createSocket') + const moves: unknown[] = [] + + statusActive.on(CharacteristicEventTypes.CHANGE, ({ newValue }) => moves.push(newValue)) + leave(camera) + + await expect(writeSetup(service, connection, from)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await expect(readSetupEndpoints(service, connection)).resolves.toBe('AgEC') + await expect(statusActive.handleGetRequest()).resolves.toBe(true) + expect(createSocket).not.toHaveBeenCalled() + expect(moves).toEqual([]) + + const switchedOff = crypto.randomUUID() + + map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + + expect(await prepare(service, connection, from, switchedOff)).toEqual({ status: SetupEndpointsStatus.ERROR, sessionIdentifier: switchedOff }) + + back(camera) + map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON) + + expect(await prepare(service, connection, from, crypto.randomUUID())).toMatchObject({ status: SetupEndpointsStatus.SUCCESS }) + }) + + it('fails a setup endpoints write with the communication failure for a camera stated away while its sockets bind, leaving no socket open', async () => { + const camera = wiredCamera() + const service = multiTierServiceOf(configured(camera), SERVICE_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const localAddress = connection.getLocalAddress.bind(connection) + + // The camera leaves service after the write's first check, as its sockets are about to bind. + vi.spyOn(connection, 'getLocalAddress').mockImplementation((addressVersion) => { + camera.updateSourceState('away') + + return localAddress(addressVersion) + }) + + await expect(writeSetup(service, connection, from)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await until(() => udpSockets() === base) + }) + + it('publishes one debug event of a setup endpoints write failed while the camera is out of service and no answer\'s, and neither for one refused ' + + 'while it is switched off as well', async () => { + const camera = wiredCamera() + const map = configured(camera) + const service = multiTierServiceOf(map, SERVICE_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const events = captureDebugEvents('HAP-NodeJS:Camera:MultiTier') + + camera.updateSourceState('away') + await expect(writeSetup(service, connection, from)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + + const failed = events.splice(0) + + map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + await prepare(service, connection, from, crypto.randomUUID()) + + expect(failed).toEqual([ + { + accessoryUUID: NUMBERED_ACCESSORY_UUID, + kind: 'setup-out-of-service', + sentence: 'Setup Endpoints fails with the communication failure while the camera is out of service.', + }, + ]) + expect(events.map(({ kind }) => kind)).toEqual(['setup-refused', 'write-answered']) + }) + + it('ends every session and withdraws nothing at a user\'s switch-off of a published camera, the pending start of its kept tier left pending with its ' + + 'signal unaborted until it settles', async () => { + const delegate = scriptedTierDelegate() + const pending = pendingStart(delegate) + const camera = wiredCamera([ + { + ...SENSOR, + tiers: SENSOR.tiers.map(tier => ({ ...tier, keepRunning: tier.id === 3 })), + }, + ], { delegate }) + const map = configured(camera) + const service = multiTierServiceOf(map, SERVICE_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(service, connection, from) + const kept = streamOf(delegate, 3) + const withdraw = vi.spyOn(TierTable.prototype, 'withdraw') + + map[GLOBAL_KEY]!.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + await settle() + await until(() => udpSockets() === base) + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + expect([ + withdraw.mock.calls.length, + signalOf(delegate, kept).aborted, + disposedOf(delegate, kept), + ]).toEqual([0, false, 0]) + + // The kept tier's keeper released it, and its start's settling ends its demand, releasing what the start registered. + pending.resolve() + await settle() + + expect([ + signalOf(delegate, kept).aborted, + disposedOf(delegate, kept), + ]).toEqual([false, 1]) + }) + + it('emits a streaming enabled change naming its sensor and views at home for a write, a restore and a reset, beside each webrtc service\'s change ' + + 'from away at the reset', async () => { + const camera = wiredCamera() + const map = configured(camera) + const changes: StreamingEnabledChange[] = [] + camera.on(CameraControllerEvents.STREAMING_ENABLED_CHANGED, change => changes.push(change)) + + await map[SECOND_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection()) + camera.deserialize({ + streamManagements: [], + multiTierStreamManagements: { + [SENSOR_UUID.toLowerCase()]: { streamingEnabled: false }, + }, + }) + camera.handleFactoryReset() + + expect(changes).toEqual([ + { + reason: 'write', + sensorUUID: SECOND_SENSOR.uuid.toLowerCase(), + value: false, + where: 'home', + }, + { + reason: 'restore', + sensorUUID: SENSOR_UUID.toLowerCase(), + value: false, + where: 'home', + }, + { + reason: 'reset', + sensorUUID: SENSOR_UUID.toLowerCase(), + value: true, + where: 'home', + }, + { + reason: 'reset', + sensorUUID: SECOND_SENSOR.uuid.toLowerCase(), + value: true, + where: 'home', + }, + { + reason: 'reset', + sensorUUID: SENSOR_UUID.toLowerCase(), + value: true, + where: 'away', + }, + { + reason: 'reset', + sensorUUID: SECOND_SENSOR.uuid.toLowerCase(), + value: true, + where: 'away', + }, + ]) + }) + + it('ends a multi-tier session at a force-stop of its identifier and ignores an identifier no session holds', async () => { + const camera = wiredCamera() + const service = multiTierServiceOf(configured(camera), SERVICE_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(service, connection, from) + + expect(() => camera.forceStopStreamingSession(UNKNOWN_SESSION)).not.toThrow() + await settle() + + expect(udpSockets()).toBe(base + 2) + + camera.forceStopStreamingSession(answer.sessionIdentifier) + await settle() + await until(() => udpSockets() === base) + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + }) + + it('ends every session and leaves no policy listener on a removed service at a reset and a removal, the second run throwing nothing', async () => { + const camera = wiredCamera() + const map = configured(camera) + const service = multiTierServiceOf(map, SERVICE_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(service, connection, from) + + camera.handleFactoryReset() + camera.handleControllerRemoved() + + expect(() => { + camera.handleFactoryReset() + camera.handleControllerRemoved() + }).not.toThrow() + await settle() + await until(() => udpSockets() === base) + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + + // Each characteristic keeps only its service's own change listener, the legacy stream's Active and each multi-tier and WebRTC Streaming Enabled + // their class's as well, and no service keeps a configuration listener. + const streamServices = [Service.CameraMultiTierRTPStreamManagement.UUID, Service.CameraWebRTCStreamManagement.UUID] + + for (const removed of Object.values(map).filter(candidate => candidate !== undefined)) { + expect(removed.listenerCount(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE)).toBe(0) + + for (const characteristic of removed.characteristics) { + const ownedByClass = (removed.UUID === Service.CameraRTPStreamManagement.UUID && characteristic.UUID === Characteristic.Active.UUID) + || (streamServices.includes(removed.UUID) && characteristic.UUID === Characteristic.StreamingEnabled.UUID) + + expect(characteristic.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(ownedByClass ? 2 : 1) + } + } + }) + + it('sends each demand of a removed camera its end, naming its own stream, before the next camera\'s first start of that tier', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const delegate = scriptedTierDelegate() + const streamingOptions = { delegate } + const removed = wiredCamera([SENSOR], streamingOptions) + const removedService = multiTierServiceOf(configured(removed), SERVICE_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + + // Video tier 1 starts for one session, and a second session's Start waits on video tier 2, whose start never settles. + await streaming(removedService, connection, from) + const waiting = crypto.randomUUID() + await prepare(removedService, connection, from, waiting) + delegate.tierDemandStarted.mockImplementationOnce(async () => new Promise(() => undefined)) + const starting = start(removedService, connection, waiting, 2) + await settle() + const removedStarts = delegate.tierDemandStarted.mock.calls.length + const aborted = vi.fn<() => void>() + + signalOf(delegate, streamOf(delegate, 2)).addEventListener('abort', aborted) + + // The next camera's sessions are prepared and started at once, with no wait for the removed camera's sessions to end. + removed.handleControllerRemoved() + const next = multiTierServiceOf(configured(wiredCamera([SENSOR], streamingOptions)), SERVICE_KEY) + await streaming(next, connection, from) + await streaming(next, connection, from, 2) + + expect(await starting).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + + const streams = streamsOf(delegate) + const [settledStream, pendingStream] = streams + + expect(streams.map(({ tier }) => tier.id)).toEqual([1, 2, 1, 2]) + expect(streams.map(({ tier }) => tier.sensorUUID)).toEqual(Array.from({ length: 4 }).fill(SENSOR_UUID.toLowerCase())) + + // The settled start's end is the release of what it registered, bound to its own stream, and the pending start's, which registered nothing, is the + // abort of its signal, each before the next camera's first start of that tier. + expect([ + disposedOf(delegate, settledStream), + signalOf(delegate, settledStream).aborted, + ]).toEqual([1, false]) + expect([ + disposedOf(delegate, pendingStream), + aborted.mock.calls.length, + ]).toEqual([0, 1]) + + for (const [stream, end] of [ + [settledStream, delegate.disposals.get(settledStream)!.mock.invocationCallOrder[0]], + [pendingStream, aborted.mock.invocationCallOrder[0]], + ] as const) { + const nextStart = streams.findIndex((candidate, index) => (index >= removedStarts) && (candidate.tier.id === stream.tier.id)) + + expect(end).toBeLessThan(delegate.tierDemandStarted.mock.invocationCallOrder[nextStart]) + } + }) + + it('hands the state-change delegate to every multi-tier management, which is how each one\'s streaming enabled saves the camera', async () => { + const camera = wiredCamera() + const map = configured(camera) + const saves = vi.fn() + camera.setupStateChangeDelegate(saves) + + await map[SERVICE_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection()) + await map[SECOND_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection()) + + expect(saves).toHaveBeenCalledTimes(2) + + camera.setupStateChangeDelegate(undefined) + map[SECOND_KEY]!.updateCharacteristic(Characteristic.StreamingEnabled, true) + + expect(saves).toHaveBeenCalledTimes(2) + }) + + it('tells of a view at home once as its Start is answered and once as its session ends, naming the sensor, the session and the tier', async () => { + const camera = wiredCamera() + const service = multiTierServiceOf(configured(camera), SECOND_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const events: (readonly [string, CameraLiveView])[] = [] + camera.on(CameraControllerEvents.LIVE_VIEW_STARTED, view => events.push(['started', view])) + camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, view => events.push(['ended', view])) + + // A session prepared and ended without a Start is no view. + const prepared = crypto.randomUUID() + await prepare(service, connection, from, prepared) + + expect(await end(service, connection, prepared)).toBe(RTPStreamingStatus.NO_SUCH_STREAM) + expect(events).toEqual([]) + + const answer = await streaming(service, connection, from, 2) + const view: CameraLiveView = { + sensorUUID: SECOND_SENSOR.uuid.toLowerCase(), + sessionIdentifier: answer.sessionIdentifier, + tierId: 2, + where: 'home', + } + + expect(events).toStrictEqual([ + ['started', view], + ]) + + // A second Start of the streaming session is refused and tells of nothing. + expect(await start(service, connection, answer.sessionIdentifier, 2)).toBe(RTPStreamingStatus.ERROR) + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + expect(events).toStrictEqual([ + ['started', view], + ['ended', view], + ]) + + await settle() + await until(() => udpSockets() === base) + + expect(events).toHaveLength(2) + }) + + it('tells a removed camera\'s listeners of the end of each view at home in the removal\'s own turn, before the controller drops them', async () => { + const camera = wiredCamera() + const service = multiTierServiceOf(configured(camera), SERVICE_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(service, connection, from) + const ended = vi.fn<(view: CameraLiveView) => void>() + camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, ended) + + camera.handleControllerRemoved() + + expect(ended.mock.calls).toStrictEqual([ + [ + { + sensorUUID: SENSOR_UUID.toLowerCase(), + sessionIdentifier: answer.sessionIdentifier, + tierId: 1, + where: 'home', + }, + ], + ]) + expect(camera.listenerCount(CameraControllerEvents.LIVE_VIEW_ENDED)).toBe(0) + + await settle() + await until(() => udpSockets() === base) + + expect(ended).toHaveBeenCalledOnce() + }) + + it('logs each live-view listener that throws, calls the next listener, answers the Start and ends the session all the same', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = wiredCamera() + const service = multiTierServiceOf(configured(camera), SERVICE_KEY) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const heard: string[] = [] + const failing = (): void => { + throw new Error('The listener failed.') + } + camera.on(CameraControllerEvents.LIVE_VIEW_STARTED, failing) + camera.on(CameraControllerEvents.LIVE_VIEW_STARTED, () => heard.push('started')) + camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, failing) + camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, () => heard.push('ended')) + + const answer = await streaming(service, connection, from) + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.SUCCESS) + + await settle() + await until(() => udpSockets() === base) + + expect(heard).toEqual(['started', 'ended']) + expect(error.mock.calls.map(([line]) => String(line).split(': ')[0])).toEqual([ + '[Camera] A listener of the camera controller\'s live-view-started event failed', + '[Camera] A listener of the camera controller\'s live-view-ended event failed', + ]) + }) + + describe('as it leaves service', () => { + const USERNAME = 'CA:FE:00:00:00:05' + const BRIDGE_USERNAME = 'CA:FE:00:00:00:06' + // The first sensor's tier the camera keeps running, whose first start stays pending, and the tier it records. + const KEPT_TIER = 3 + const RECORDED_TIER = 1 + + // What every row reads once the camera has left service: each of its tiers ended, its recording cancelled with the end marker, its view at home + // ended while each Status Active stays on, since the user's switches alone move it, and the kept tier's pending start withdrawn with a debug line, + // its signal aborted, and no warning. + const ENDED = { + alerts: [], + recording: [ + ['cancelled'], + { + data: Buffer.alloc(1), + isLast: true, + }, + ], + registrations: [1, 1], + session: RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + signal: true, + statusActive: [true, true], + warnings: [], + withdrawn: [ + `The library withdrew the pending start of the video tier ${KEPT_TIER} of the video sensor "${SENSOR_UUID.toLowerCase()}" as the camera went ` + + 'out of service: every join waiting on it is refused.', + ], + } + + // The accessories a row publishes or bridges, destroyed after it. No server, record or context outlives its row. + const accessories: Accessory[] = [] + + afterEach(async () => { + for (const accessory of accessories.splice(0)) { + await accessory.destroy() + } + }) + + // How a row's camera leaves service and how it comes back, once it is in service. + interface ServicePath { + readonly back: () => Promise + readonly leave: () => Promise + } + + // A camera serving as it leaves service: its accessory and path, the stream of its kept tier and of its recorded tier, the recording + // open on the recorded tier and its view at home on it, and what it raised, ended and wrote meanwhile. + interface Serving { + readonly accessory: Accessory + readonly alerts: CameraProblem[] + readonly answer: Prepared + readonly base: number + readonly connection: HAPConnection + readonly delegate: ScriptedTierDelegate + readonly ends: CameraRecordingEnd[] + readonly kept: TierStream + readonly lines: string[] + readonly packets: RecordingPacket[] + readonly path: ServicePath + readonly pending: Deferred + readonly recorded: TierStream + readonly services: CameraMultiTierRTPStreamManagement[] + readonly warn: Mock + } + + // Publishes an accessory through the advertiser the suite mocks, and nothing is announced. + async function publish(accessory: Accessory, username = USERNAME): Promise { + if (!accessories.includes(accessory)) { + accessories.push(accessory) + } + + await accessory.publish({ + advertiser: MDNSAdvertiser.BONJOUR, + category: Categories.CAMERA, + pincode: '031-45-154', + username, + }) + } + + // The accessory published alone, leaving service at its unpublish and coming back at its publish. + async function alone(accessory: Accessory): Promise { + await publish(accessory) + + return { + back: async () => publish(accessory), + leave: async () => accessory.unpublish(), + } + } + + // The accessory bridged to a published bridge, leaving service as it is taken off the bridge and coming back as it is put back. + async function bridged(accessory: Accessory): Promise { + const bridge = new Bridge('Bridge', uuid.generate('a bridge its camera leaves')) + + await publish(bridge, BRIDGE_USERNAME) + accessories.push(accessory) + bridge.addBridgedAccessory(accessory) + + return { + back: async () => { + bridge.addBridgedAccessory(accessory) + }, + leave: async () => { + bridge.removeBridgedAccessory(accessory) + }, + } + } + + // The accessory published alone, its camera leaving service as its source is stated away and coming back as it is stated available. + async function stated(accessory: Accessory, camera: CameraController): Promise { + await publish(accessory) + + return { + back: async () => { + camera.updateSourceState('available') + }, + leave: async () => { + camera.updateSourceState('away') + }, + } + } + + // A camera on an accessory of its own, configured there: its first sensor's tier 3 marked keepRunning, whose first start, that tier's, stays + // pending, and its first sensor's tier 1 recorded with no prebuffer. + function keptCamera(): { accessory: Accessory, camera: CameraController, delegate: ScriptedTierDelegate, pending: Deferred } { + const delegate = scriptedTierDelegate() + const pending = pendingStart(delegate) + const camera = new CameraController(capabilitiesCameraOptions({ + recording: { prebuffer: 0 }, + streaming: { delegate }, + videoSensors: [ + { + ...SENSOR, + tiers: SENSOR.tiers.map(tier => ({ ...tier, keepRunning: tier.id === KEPT_TIER })), + }, + SECOND_SENSOR, + ], + })) + const accessory = new Accessory('Camera', uuid.generate('a camera leaving service')) + + cameras.push(camera) + accessory.configureController(camera) + + return { accessory, camera, delegate, pending } + } + + // The kept camera with recording on, put in service by the path given, its recorded tier written a ready buffer, a recording opened on it and a view + // at home started on it, the problems heard on its accessory's channel and its recording ends kept, the tiers' debug log captured and every warning + // held. + async function serving(enter: (accessory: Accessory, camera: CameraController) => Promise): Promise { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const lines = captureDebug('HAP-NodeJS:Camera:Tier') + const { accessory, camera, delegate, pending } = keptCamera() + const recordingManagement = camera.recordingManagement! + const { problems: alerts } = problemsOf(accessory.UUID) + const ends: CameraRecordingEnd[] = [] + const packets: RecordingPacket[] = [] + + camera.on(CameraControllerEvents.RECORDING_ENDED, end => ends.push(end)) + recordingManagement.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + + const path = await enter(accessory, camera) + const recorded = streamOf(delegate, RECORDED_TIER) + + recorded.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + frames(recorded, 0, 1) + + const recording = recordingManagement.delegate.handleRecordingStreamRequest(1) + + void (async () => { + for await (const packet of recording) { + packets.push(packet) + } + })() + frames(recorded, 1, 45) + + const services = accessory.services.filter(service => service.UUID === Service.CameraMultiTierRTPStreamManagement.UUID) + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(services[0] as CameraMultiTierRTPStreamManagement, connection, from, RECORDED_TIER) + + return { + accessory, + alerts, + answer, + base, + connection, + delegate, + ends, + kept: streamOf(delegate, KEPT_TIER), + lines, + packets, + path, + pending, + recorded, + services: services as CameraMultiTierRTPStreamManagement[], + warn, + } + } + + function statusActiveOf(services: readonly CameraMultiTierRTPStreamManagement[]): unknown[] { + return services.map(service => service.getCharacteristic(Characteristic.StatusActive).value) + } + + // What the camera ended once it left service and the view's exit has settled, in the shape of the readings every row expects. + async function endedBy(served: Serving): Promise> { + await settle() + await until(() => udpSockets() === served.base) + await settle() + + return { + alerts: served.alerts, + recording: [ + served.ends.map(({ outcome }) => outcome), + served.packets.at(-1), + ], + registrations: [served.kept, served.recorded].map(stream => disposedOf(served.delegate, stream)), + session: await end(served.services[0], served.connection, served.answer.sessionIdentifier), + signal: signalOf(served.delegate, served.kept).aborted, + statusActive: statusActiveOf(served.services), + warnings: served.warn.mock.calls, + withdrawn: served.lines.filter(line => line.startsWith('The library withdrew')), + } + } + + it.each([ + ['its accessory is unpublished and published again', alone], + ['its accessory is taken off its published bridge and put back', bridged], + ['its source is stated away and then available', stated], + ] as const)('ends its kept and recorded tiers, its recording and its view at home, withdrawing its kept tier\'s pending start with no warning, as ' + + '%s, and raises each tier it holds afresh with no alert once back', async (_path, enter) => { + const served = await serving(enter) + + await served.path.leave() + + expect(await endedBy(served)).toEqual(ENDED) + + const before = streamsOf(served.delegate).length + + await served.path.back() + await settle() + + expect([ + streamsOf(served.delegate).slice(before).map(({ tier }) => tier.id), + served.alerts, + statusActiveOf(served.services), + ]).toEqual([ + [KEPT_TIER, RECORDED_TIER], + [], + [true, true], + ]) + + served.pending.resolve() + }) + + it.each([ + ['standing alone', alone], + ['bridged', bridged], + ] as const)('ends its kept and recorded tiers, its recording and its view at home, withdrawing its kept tier\'s pending start with no warning, at ' + + 'the destroy of its accessory %s', async (_path, enter) => { + const served = await serving(enter) + + await served.accessory.destroy() + + expect(await endedBy(served)).toEqual(ENDED) + + served.pending.resolve() + }) + + it('calls tierDemandStarted no more at its removal from its published accessory than it did as the accessory was published, its kept tier\'s ' + + 'start still pending, and writes no warning', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { accessory, camera, delegate, pending } = keptCamera() + + await alone(accessory) + await settle() + + const published = delegate.tierDemandStarted.mock.calls.length + + accessory.removeController(camera) + await settle() + + expect([ + published, + delegate.tierDemandStarted.mock.calls.length, + warn.mock.calls, + ]).toEqual([1, 1, []]) + + pending.resolve() + }) + + /* Whether the keeper's raise at the statement of available joins the demand the ending view still holds or raises the tier afresh follows the order + * of the session's release and the raise, which is why the row counts no start: it reads the tier running once the view's exit has settled, and every start + * matched by an end once a later away has ended it. + */ + it('ends a view at home on its kept tier and holds the tier running once the view\'s exit has settled, its source stated away and then available in ' + + 'one turn, and ends the tier at a later away, the plugin hearing as many ends of the tier as starts', async () => { + const { accessory, camera, delegate, pending } = keptCamera() + const running = (): number => streamsOf(delegate, KEPT_TIER).length - endsOf(delegate, KEPT_TIER) + + pending.resolve() + await alone(accessory) + + const service = accessory.getServiceById(Service.CameraMultiTierRTPStreamManagement, SENSOR_UUID.toLowerCase()) as CameraMultiTierRTPStreamManagement + const from = await endpoint() + const connection = buildEmitterConnection() + const base = udpSockets() + const answer = await streaming(service, connection, from, KEPT_TIER) + + camera.updateSourceState('away') + camera.updateSourceState('available') + await settle() + await until(() => udpSockets() === base) + await settle() + + const held = running() + + expect(await end(service, connection, answer.sessionIdentifier)).toBe(RTPStreamingStatus.UNKNOWN_SESSION_IDENTIFIER) + + camera.updateSourceState('away') + await settle() + + expect([ + held, + running(), + ]).toEqual([1, 0]) + }) + }) + }) +}) diff --git a/src/lib/camera/RTPStreamManagement.spec.ts b/src/lib/camera/RTPStreamManagement.spec.ts index d5787d558..222e981a1 100644 --- a/src/lib/camera/RTPStreamManagement.spec.ts +++ b/src/lib/camera/RTPStreamManagement.spec.ts @@ -1,198 +1,91 @@ import type { MockInstance } from 'vitest' -import type { - CameraRecordingOptions, - RecordingPacket, -} from '../camera/index.js' -import type { - CameraControllerOptions, - CameraRecordingDelegate, - CameraStreamingDelegate, - PrepareStreamCallback, -} from '../controller/index.js' +import type { CameraControllerOptions, PrepareStreamCallback } from '../controller/index.js' import type { HAPConnection } from '../util/eventedhttp.js' -import type { - CameraStreamingOptions, - RTPStreamManagement, -} from './RTPStreamManagement.js' +import type { CameraStreamingOptions, PrepareStreamRequest, PrepareStreamResponse } from './RTPStreamManagement.js' import { Buffer } from 'node:buffer' -import util from 'node:util' +import { format } from 'node:util' import createDebug from 'debug' +import tweetnacl from 'tweetnacl' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { Accessory } from '../Accessory.js' import { - AudioBitrate, - AudioRecordingCodecType, - AudioRecordingSamplerate, + buildMockConnection, + buildSetupEndpointsTlv, + createCameraControllerOptions, + MockDelegate, + mockRecordingOptions, + mockStreamingOptions, + SETUP_ENDPOINTS_DISABLED_SUITE, + SETUP_ENDPOINTS_HUB_ANSWER, + SETUP_ENDPOINTS_HUB_REQUEST, + SETUP_ENDPOINTS_NARROW_PORTS, +} from '../../test-utils/cameraFixtures.js' +import { HAPHTTPClient } from '../../test-utils/HAPHTTPClient.js' +import { PairVerifyClient } from '../../test-utils/PairVerifyClient.js' +import { Accessory, AccessoryEventTypes, Categories, MDNSAdvertiser } from '../Accessory.js' +import { AudioStreamingCodecType, AudioStreamingSamplerate, - H264Level, - H264Profile, - MediaContainerType, - VideoCodecType, } from '../camera/index.js' import { Characteristic } from '../Characteristic.js' -import { - CameraController, -} from '../controller/index.js' +import { CameraController } from '../controller/index.js' import { HAPStatus } from '../HAPServer.js' +import { AccessoryInfo, PermissionTypes } from '../model/AccessoryInfo.js' import { IdentifierCache } from '../model/IdentifierCache.js' +import { awaitEventOnce } from '../util/promise-utils.js' import * as tlv from '../util/tlv.js' import * as uuid from '../util/uuid.js' +import { decodeSetupEndpointsResponse, encodeSetupEndpointsRequest, SetupEndpointsStatus } from './capabilities/setupEndpoints.js' import RTPProxy from './RTPProxy.js' -import { - SRTPCryptoSuites, -} from './RTPStreamManagement.js' +import { RTPStreamManagement, SRTPCryptoSuites, StreamRequestTypes } from './RTPStreamManagement.js' import '../definitions/index.js' -class MockDelegate implements CameraStreamingDelegate, CameraRecordingDelegate { - handleSnapshotRequest(): void { - throw new Error('Unsupported!') - } - - handleStreamRequest(): void { - throw new Error('Unsupported!') - } - - prepareStream(): void { - throw new Error('Unsupported!') - } - - async* handleRecordingStreamRequest(): AsyncGenerator { - yield { - data: Buffer.alloc(64, 0), - isLast: true, - } - } - - closeRecordingStream(): void {} - - updateRecordingActive(): void {} - - updateRecordingConfiguration(): void {} +// The keys and salts of the hub request and of the hub answer, each run of bytes counting up from its first. +const HUB_REQUEST_KEYS = { + videoKey: Buffer.from('0102030405060708090a0b0c0d0e0f10', 'hex'), + videoSalt: Buffer.from('1112131415161718191a1b1c1d1e', 'hex'), + audioKey: Buffer.from('2122232425262728292a2b2c2d2e2f30', 'hex'), + audioSalt: Buffer.from('3132333435363738393a3b3c3d3e', 'hex'), } - -const baseStreamingOptions: CameraStreamingOptions = { - supportedCryptoSuites: [SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80], - video: { - codec: { - profiles: [H264Profile.BASELINE, H264Profile.MAIN, H264Profile.HIGH], - levels: [H264Level.LEVEL3_1, H264Level.LEVEL3_2, H264Level.LEVEL4_0], - }, - resolutions: [ - [1920, 1080, 30], - [1280, 720, 30], - [320, 240, 15], - ], - }, - audio: { - twoWayAudio: true, - codecs: [ - { - type: AudioStreamingCodecType.AAC_ELD, - samplerate: AudioStreamingSamplerate.KHZ_24, - }, - ], - }, +const HUB_ANSWER_KEYS = { + videoKey: Buffer.from('a1a2a3a4a5a6a7a8a9aaabacadaeafb0', 'hex'), + videoSalt: Buffer.from('b1b2b3b4b5b6b7b8b9babbbcbdbe', 'hex'), + audioKey: Buffer.from('c1c2c3c4c5c6c7c8c9cacbcccdcecfd0', 'hex'), + audioSalt: Buffer.from('d1d2d3d4d5d6d7d8d9dadbdcddde', 'hex'), } -const baseRecordingOptions: CameraRecordingOptions = { - prebufferLength: 4000, - mediaContainerConfiguration: [ - { - type: MediaContainerType.FRAGMENTED_MP4, - fragmentLength: 8000, - }, - ], +// The session the hub request names. +const HUB_SESSION = 'a1b2c3d4-0000-4000-8000-0000000000b1' + +// The prepared stream the hub answer encodes: its ports, SSRCs, keys and salts. +const HUB_PREPARE_RESPONSE: PrepareStreamResponse = { video: { - type: VideoCodecType.H264, - parameters: baseStreamingOptions.video.codec, - resolutions: baseStreamingOptions.video.resolutions, + port: 51010, + ssrc: 0x0A0B0C0D, + srtp_key: HUB_ANSWER_KEYS.videoKey, + srtp_salt: HUB_ANSWER_KEYS.videoSalt, }, audio: { - codecs: [ - { - type: AudioRecordingCodecType.AAC_ELD, - audioChannels: 1, - bitrateMode: AudioBitrate.VARIABLE, - samplerate: AudioRecordingSamplerate.KHZ_48, - }, - ], + port: 51012, + ssrc: 0x0E0F1011, + srtp_key: HUB_ANSWER_KEYS.audioKey, + srtp_salt: HUB_ANSWER_KEYS.audioSalt, }, } -function buildControllerOptions(streamingOptions: CameraStreamingOptions): CameraControllerOptions { - const delegate = new MockDelegate() - return { - cameraStreamCount: 2, - delegate, - streamingOptions, - recording: { - options: baseRecordingOptions, - delegate, - }, - sensors: { motion: true, occupancy: true }, - } +// The delegate answers each preparation with the hub answer's ports, SSRCs, keys and salts. +function answerWithHubAnswer(): MockInstance { + return vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(((_request: unknown, callback: PrepareStreamCallback) => { + callback(undefined, HUB_PREPARE_RESPONSE) + }) as () => void) } -// matches the private enums in RTPStreamManagement.ts -const SetupEndpointsTypes = { - SESSION_ID: 0x01, - CONTROLLER_ADDRESS: 0x03, - VIDEO_SRTP_PARAMETERS: 0x04, - AUDIO_SRTP_PARAMETERS: 0x05, -} as const -const AddressTypes = { - ADDRESS_VERSION: 0x01, - ADDRESS: 0x02, - VIDEO_RTP_PORT: 0x03, - AUDIO_RTP_PORT: 0x04, -} as const -const SRTPParametersTypes = { - SRTP_CRYPTO_SUITE: 0x01, - MASTER_KEY: 0x02, - MASTER_SALT: 0x03, -} as const - -function buildSetupEndpointsTlv(withPorts = true, sessionId = '11111111-1111-1111-1111-111111111111'): string { - const addressTlv = withPorts - ? tlv.encode( - AddressTypes.ADDRESS_VERSION, 0x00, // IPV4 - AddressTypes.ADDRESS, '127.0.0.1', - AddressTypes.VIDEO_RTP_PORT, tlv.writeUInt16(5000), - AddressTypes.AUDIO_RTP_PORT, tlv.writeUInt16(5001), - ) - : tlv.encode( - AddressTypes.ADDRESS_VERSION, 0x00, // IPV4 - AddressTypes.ADDRESS, '127.0.0.1', - ) - const srtpTlv = tlv.encode( - SRTPParametersTypes.SRTP_CRYPTO_SUITE, SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, - SRTPParametersTypes.MASTER_KEY, Buffer.alloc(16), - SRTPParametersTypes.MASTER_SALT, Buffer.alloc(14), - ) - const payload = tlv.encode( - SetupEndpointsTypes.SESSION_ID, uuid.write(sessionId), - SetupEndpointsTypes.CONTROLLER_ADDRESS, addressTlv, - SetupEndpointsTypes.VIDEO_SRTP_PARAMETERS, srtpTlv, - SetupEndpointsTypes.AUDIO_SRTP_PARAMETERS, srtpTlv, - ) - return payload.toString('base64') -} - -function buildMockConnection(): HAPConnection { - return { - localAddress: '127.0.0.1', - getLocalAddress: vi.fn().mockReturnValue('127.0.0.1'), - setMaxListeners: vi.fn(), - getMaxListeners: vi.fn().mockReturnValue(10), - on: vi.fn(), - removeListener: vi.fn(), - } as unknown as HAPConnection +function buildControllerOptions(streamingOptions: CameraStreamingOptions): CameraControllerOptions { + return createCameraControllerOptions(mockRecordingOptions, streamingOptions) } function prepareOk(_request: unknown, callback: PrepareStreamCallback) { @@ -245,7 +138,7 @@ describe('RTPStreamManagement', () => { describe('streaming options shared by all streams', () => { it('should leave the lists of the plugin alone', () => { const options: CameraStreamingOptions = { - ...baseStreamingOptions, + ...mockStreamingOptions, supportedCryptoSuites: [], audio: { codecs: [], @@ -268,7 +161,7 @@ describe('RTPStreamManagement', () => { { type: AudioStreamingCodecType.OPUS, samplerate: AudioStreamingSamplerate.KHZ_24 }, ] const options: CameraStreamingOptions = { - ...baseStreamingOptions, + ...mockStreamingOptions, audio: { codecs }, } @@ -287,7 +180,7 @@ describe('RTPStreamManagement', () => { let controller: CameraController beforeEach(() => { - controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions)) controller.constructServices() controller.configureServices() }) @@ -332,25 +225,56 @@ describe('RTPStreamManagement', () => { describe('debug output', () => { it('should not contain the SRTP keys of a stream', () => { - const controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + const controller = new CameraController(buildControllerOptions(mockStreamingOptions)) controller.constructServices() controller.configureServices() const rtp = controller.streamManagements[0] as RTPStreamManagement vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(() => undefined) + // Each stream's key and salt is a run of bytes no other field of the request holds, so finding one in the output can only mean it was printed. + const request = encodeSetupEndpointsRequest({ + sessionIdentifier: '11111111-1111-1111-1111-111111111111', + controllerAddress: { + addressVersion: 'ipv4', + address: '127.0.0.1', + videoRTPPort: 5000, + audioRTPPort: 5001, + }, + videoSRTPParameters: { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: HUB_REQUEST_KEYS.videoKey, + masterSalt: HUB_REQUEST_KEYS.videoSalt, + }, + audioSRTPParameters: { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: HUB_REQUEST_KEYS.audioKey, + masterSalt: HUB_REQUEST_KEYS.audioSalt, + }, + }) const namespaces = createDebug.disable() createDebug.enable('HAP-NodeJS:Camera:RTPStreamManagement') const lines: string[] = [] const log = vi.spyOn(createDebug, 'log').mockImplementation((...args: unknown[]) => { - lines.push(util.format(...args)) + lines.push(format(...args)) }) try { // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), vi.fn(), buildMockConnection()) + rtp.handleSetupEndpoints(request, vi.fn(), buildMockConnection()) const output = lines.join('\n') expect(output).toContain('11111111-1111-1111-1111-111111111111') // the line with the session was written - expect(output).not.toContain('Master') + // Every form a debug line could print a secret in: hex, the spaced hex of a buffer's inspection, base64, the raw bytes and the decimal bytes. + for (const secret of Object.values(HUB_REQUEST_KEYS)) { + for (const form of [ + secret.toString('hex'), + [...secret].map(byte => byte.toString(16).padStart(2, '0')).join(' '), + secret.toString('base64'), + secret.toString('latin1'), + [...secret].join(','), + ]) { + expect(output).not.toContain(form) + } + } expect(output).not.toContain(' { describe('debug output of the accessory', () => { it('should not contain the SetupEndpoints value of a write, which holds the SRTP keys', async () => { const accessory = new Accessory('Cam', uuid.generate('srtp keys in the accessory debug log')) - const controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + const controller = new CameraController(buildControllerOptions(mockStreamingOptions)) accessory.configureController(controller) accessory._identifierCache = new IdentifierCache('AA:BB:CC:DD:EE:FF') accessory._assignIDs(accessory._identifierCache) @@ -376,7 +300,7 @@ describe('RTPStreamManagement', () => { createDebug.enable('HAP-NodeJS:*') const lines: string[] = [] const log = vi.spyOn(createDebug, 'log').mockImplementation((...args: unknown[]) => { - lines.push(util.format(...args)) + lines.push(format(...args)) }) try { // @ts-expect-error: private method access @@ -401,7 +325,7 @@ describe('RTPStreamManagement', () => { describe('a failed reconfigure', () => { it('should tell the delegate to stop the stream of the session it gives up', () => { - const controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + const controller = new CameraController(buildControllerOptions(mockStreamingOptions)) controller.constructServices() controller.configureServices() const rtp = controller.streamManagements[0] as RTPStreamManagement @@ -449,10 +373,10 @@ describe('RTPStreamManagement', () => { beforeEach(() => { const proxyOptions: CameraStreamingOptions = { - ...baseStreamingOptions, + ...mockStreamingOptions, proxy: true, } - controller = new CameraController(buildControllerOptions(proxyOptions)) + controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, proxyOptions)) controller.constructServices() controller.configureServices() }) @@ -497,17 +421,17 @@ describe('RTPStreamManagement', () => { expect(error!.message).toBe('socket creation failed') }) - it('should set setupEndpointsResponse to ERROR status when proxy setup rejects', async () => { + it('answers a read with an ERROR status when proxy setup rejects', async () => { setupSpy = vi.spyOn(RTPProxy.prototype, 'setup') .mockImplementation(() => Promise.reject(new Error('bind failed'))) const rtp = controller.streamManagements[0] as RTPStreamManagement - await new Promise((resolve) => { - // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), () => resolve(), buildMockConnection()) - }) + const setupEndpoints = rtp.service.getCharacteristic(Characteristic.SetupEndpoints) + const connection = buildMockConnection() - const response = (rtp as any).setupEndpointsResponse as string + await expect(setupEndpoints.handleSetRequest(buildSetupEndpointsTlv(), connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + + const response = await setupEndpoints.handleGetRequest(connection) as string const decoded = tlv.decode(Buffer.from(response, 'base64')) // SetupEndpointsResponseTypes.STATUS = 0x02; SetupEndpointsStatus.ERROR = 0x02 expect(decoded[0x02].readUInt8(0)).toBe(0x02) @@ -519,7 +443,7 @@ describe('RTPStreamManagement', () => { beforeEach(() => { controller = new CameraController(buildControllerOptions({ - ...baseStreamingOptions, + ...mockStreamingOptions, proxy: true, })) controller.constructServices() @@ -568,7 +492,7 @@ describe('RTPStreamManagement', () => { let controller: CameraController beforeEach(() => { - controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions)) controller.constructServices() controller.configureServices() }) @@ -592,11 +516,10 @@ describe('RTPStreamManagement', () => { expect(rtp.sessionIdentifier).toBeUndefined() // the next valid request must not be answered with BUSY - await new Promise((resolve) => { - // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), () => resolve(), buildMockConnection()) - }) - const decoded = tlv.decode(Buffer.from((rtp as any).setupEndpointsResponse as string, 'base64')) + const setupEndpoints = rtp.service.getCharacteristic(Characteristic.SetupEndpoints) + const connection = buildMockConnection() + await expect(setupEndpoints.handleSetRequest(buildSetupEndpointsTlv(), connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + const decoded = tlv.decode(Buffer.from(await setupEndpoints.handleGetRequest(connection) as string, 'base64')) // SetupEndpointsResponseTypes.STATUS = 0x02; SetupEndpointsStatus.BUSY = 0x01 expect(decoded[0x02].readUInt8(0)).not.toBe(0x01) }) @@ -606,7 +529,7 @@ describe('RTPStreamManagement', () => { let controller: CameraController beforeEach(() => { - controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + controller = new CameraController(buildControllerOptions(mockStreamingOptions)) controller.constructServices() controller.configureServices() }) @@ -639,19 +562,13 @@ describe('RTPStreamManagement', () => { const connectionA = buildMockConnection() const connectionB = buildMockConnection() - await new Promise((resolve) => { - // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionA), () => resolve(), connectionA) - }) + await characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionA), connectionA) const responseA = await read(connectionA) // SetupEndpointsResponseTypes: SESSION_ID = 0x01, STATUS = 0x02; SetupEndpointsStatus: SUCCESS = 0x00, BUSY = 0x01 expect(uuid.unparse(responseA[0x01])).toBe(sessionA) expect(responseA[0x02].readUInt8(0)).toBe(0x00) - const callbackB = vi.fn() - // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionB), callbackB, connectionB) - expect(callbackB).toHaveBeenCalledExactlyOnceWith() + await expect(characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionB), connectionB)).resolves.toBeUndefined() // the controller which asked reads the answer for its own request, like before const responseB = await read(connectionB) @@ -661,13 +578,12 @@ describe('RTPStreamManagement', () => { // the session which holds the stream still has its response expect(await read(connectionA)).toEqual(responseA) - expect(tlv.decode(Buffer.from(rtp.setupEndpointsResponse, 'base64'))).toEqual(responseA) expect(await read(connectionB)).toEqual(responseB) // once the stream is free again, everybody reads the default response, like before // @ts-expect-error: private method access rtp.handleSessionClosed() - const idle = tlv.decode(Buffer.from(rtp.setupEndpointsResponse, 'base64')) + const idle = await read(buildMockConnection()) expect(await read(connectionB)).toEqual(idle) expect(await read(connectionA)).toEqual(idle) }) @@ -677,7 +593,7 @@ describe('RTPStreamManagement', () => { let controller: CameraController beforeEach(() => { - controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions)) controller.constructServices() controller.configureServices() }) @@ -727,28 +643,31 @@ describe('RTPStreamManagement', () => { prepareCallbacks.push(callback) } vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(prepareStream as () => void) + const characteristic = rtp.getService().getCharacteristic(Characteristic.SetupEndpoints) + const answers = async (connections: HAPConnection[]) => Promise.all(connections.map(async connection => characteristic.handleGetRequest(connection))) const sessionA = '11111111-1111-1111-1111-111111111111' const sessionB = '22222222-2222-2222-2222-222222222222' + const connectionA = buildMockConnection() + const connectionB = buildMockConnection() const callbackA = vi.fn() const callbackB = vi.fn() - // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionA), callbackA, buildMockConnection()) + // each write goes through the characteristic, which holds the answer its connection reads + characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionA), connectionA).then(() => callbackA(), callbackA) await vi.waitFor(() => expect(prepareCallbacks).toHaveLength(1)) // @ts-expect-error: private method access rtp.handleSessionClosed() // e.g. the HAP connection closed while the delegate is still preparing - // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(true, sessionB), callbackB, buildMockConnection()) + characteristic.handleSetRequest(buildSetupEndpointsTlv(true, sessionB), connectionB).then(() => callbackB(), callbackB) await vi.waitFor(() => expect(prepareCallbacks).toHaveLength(2)) - const responseBefore = (rtp as any).setupEndpointsResponse + const answersBefore = await answers([connectionA, connectionB]) answer(prepareCallbacks[0]) // the late answer for the first session - expect(callbackA).toHaveBeenCalledExactlyOnceWith(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await vi.waitFor(() => expect(callbackA).toHaveBeenCalledExactlyOnceWith(HAPStatus.SERVICE_COMMUNICATION_FAILURE)) expect(callbackB).not.toHaveBeenCalled() expect(rtp.sessionIdentifier).toEqual(sessionB) expect(rtp.streamStatus).toBe(1) // StreamingStatus.IN_USE - expect((rtp as any).setupEndpointsResponse).toBe(responseBefore) + expect(await answers([connectionA, connectionB])).toEqual(answersBefore) }) it('should answer with an error when a delayed response is missing the audio info', async () => { @@ -766,33 +685,375 @@ describe('RTPStreamManagement', () => { } vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(prepareStream as () => void) + const setupEndpoints = rtp.service.getCharacteristic(Characteristic.SetupEndpoints) + const connection = buildMockConnection() const errors: Error[] = [] const onUncaught = (error: Error) => errors.push(error) process.on('uncaughtException', onUncaught) - try { - const error = await new Promise((resolve, reject) => { - setTimeout(() => reject(new Error('SetupEndpoints callback was never called')), 500) - // @ts-expect-error: private method access - rtp.handleSetupEndpoints(buildSetupEndpointsTlv(), err => resolve(err as Error | undefined), buildMockConnection()) - }) + // The write must settle: a callback the management never calls fails the row rather than its timeout. + let timer: ReturnType | undefined + const neverAnswered = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error('SetupEndpoints callback was never called')), 500) + }) - expect(error).toBeInstanceOf(Error) + try { + await expect(Promise.race([ + setupEndpoints.handleSetRequest(buildSetupEndpointsTlv(), connection), + neverAnswered, + ])) + .rejects + .toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) } finally { + clearTimeout(timer) process.off('uncaughtException', onUncaught) } expect(errors).toEqual([]) expect(rtp.streamStatus).toBe(0) // StreamingStatus.AVAILABLE - const decoded = tlv.decode(Buffer.from((rtp as any).setupEndpointsResponse as string, 'base64')) + const decoded = tlv.decode(Buffer.from(await setupEndpoints.handleGetRequest(connection) as string, 'base64')) // SetupEndpointsResponseTypes.STATUS = 0x02; SetupEndpointsStatus.ERROR = 0x02 expect(decoded[0x02].readUInt8(0)).toBe(0x02) }) }) + describe('handleSetupEndpoints over the setup endpoints codec', () => { + const ACCESSORY_ADDRESS = '192.0.2.130' + + let controller: CameraController + let rtp: RTPStreamManagement + let prepareStream: MockInstance + + beforeEach(() => { + controller = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions)) + controller.constructServices() + controller.configureServices() + rtp = controller.streamManagements[0] + prepareStream = answerWithHubAnswer() + }) + + afterEach(() => { + vi.restoreAllMocks() + controller.handleFactoryReset() + }) + + // A connection whose local address is the accessory address the answer names. + function hubConnection(): HAPConnection { + return { + ...buildMockConnection(), + localAddress: ACCESSORY_ADDRESS, + getLocalAddress: vi.fn().mockReturnValue(ACCESSORY_ADDRESS), + } as unknown as HAPConnection + } + + async function writeSetupEndpoints(value: string, connection: HAPConnection = hubConnection()): Promise { + await rtp.service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(value, connection) + } + + async function readSetupEndpoints(connection: HAPConnection): Promise { + return rtp.service.getCharacteristic(Characteristic.SetupEndpoints).handleGetRequest(connection) + } + + it('answers a hub request with the hub answer and prepares its stream', async () => { + const connection = hubConnection() + await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST, connection) + + await expect(readSetupEndpoints(connection)).resolves.toBe(SETUP_ENDPOINTS_HUB_ANSWER) + expect(prepareStream).toHaveBeenCalledTimes(1) + expect(prepareStream.mock.calls[0][0]).toEqual({ + sessionID: HUB_SESSION, + sourceAddress: ACCESSORY_ADDRESS, + targetAddress: '192.0.2.19', + addressVersion: 'ipv4', + video: { + port: 50010, + srtpCryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + srtp_key: HUB_REQUEST_KEYS.videoKey, + srtp_salt: HUB_REQUEST_KEYS.videoSalt, + }, + audio: { + port: 50012, + srtpCryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + srtp_key: HUB_REQUEST_KEYS.audioKey, + srtp_salt: HUB_REQUEST_KEYS.audioSalt, + }, + } satisfies PrepareStreamRequest) + }) + + it('answers a second request while busy and an error once the session ends', async () => { + const first = hubConnection() + const second = hubConnection() + const neverWrote = hubConnection() + await writeSetupEndpoints(buildSetupEndpointsTlv(), first) + await writeSetupEndpoints(buildSetupEndpointsTlv(), second) + + expect(decodeSetupEndpointsResponse(await readSetupEndpoints(first) as string)).toMatchObject({ + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier: '11111111-1111-1111-1111-111111111111', + }) + await expect(readSetupEndpoints(second)).resolves.toBe('ARARERERERERERERERERERERAgEB') + + rtp.forceStop() + + await expect(readSetupEndpoints(first)).resolves.toBe('AgEC') + await expect(readSetupEndpoints(second)).resolves.toBe('AgEC') + await expect(readSetupEndpoints(neverWrote)).resolves.toBe('AgEC') + }) + + it('releases a held answer at a factory reset, its writer then reading an error, and another at destroy the same way', async () => { + vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined) + const reset = hubConnection() + const destroyed = hubConnection() + + await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST, reset) + await expect(readSetupEndpoints(reset)).resolves.toBe(SETUP_ENDPOINTS_HUB_ANSWER) + + rtp.handleFactoryReset() + + await expect(readSetupEndpoints(reset)).resolves.toBe('AgEC') + + // The reset ended the session with one STOP. The next writer prepares anew and holds a success answer. + await writeSetupEndpoints(buildSetupEndpointsTlv(), destroyed) + expect(decodeSetupEndpointsResponse(await readSetupEndpoints(destroyed) as string)).toMatchObject({ + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier: '11111111-1111-1111-1111-111111111111', + }) + + rtp.destroy() + + await expect(readSetupEndpoints(destroyed)).resolves.toBe('AgEC') + }) + + it('holds no answer from a prepare that settles after the stream turns off: its writer reads an error then and once the stream is back on', async () => { + const handleStreamRequest = vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined) + const connection = hubConnection() + const prepared = new Promise((resolve) => { + prepareStream.mockImplementationOnce((_request: unknown, callback: PrepareStreamCallback) => resolve(callback)) + }) + const written = rtp.service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(SETUP_ENDPOINTS_HUB_REQUEST, connection) + const answer = await prepared + + rtp.service.updateCharacteristic(Characteristic.Active, false) + answer(undefined, HUB_PREPARE_RESPONSE) + + expect(handleStreamRequest).not.toHaveBeenCalled() + await expect(written).resolves.toBeUndefined() + await expect(readSetupEndpoints(connection)).resolves.toBe('AgEC') + // The session ends with one STOP, sent once the prepare callback has returned, and its close listener stays the connection's only one, because the + // late answer holds nothing. + expect(rtp.streamStatus).toBe(0) + expect(handleStreamRequest).toHaveBeenCalledTimes(1) + expect(handleStreamRequest).toHaveBeenCalledWith({ sessionID: HUB_SESSION, type: StreamRequestTypes.STOP }, expect.any(Function)) + expect(connection.on).toHaveBeenCalledTimes(1) + + rtp.service.updateCharacteristic(Characteristic.Active, true) + + await expect(readSetupEndpoints(connection)).resolves.toBe('AgEC') + + const second = hubConnection() + await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST, second) + + await expect(readSetupEndpoints(second)).resolves.toBe(SETUP_ENDPOINTS_HUB_ANSWER) + }) + + it('tells the delegate stop once for a live session at a force-stop and never for a stream without one', async () => { + const handleStreamRequest = vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined) + + rtp.forceStop() + + expect(handleStreamRequest).not.toHaveBeenCalled() + + await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST) + rtp.forceStop() + rtp.forceStop() + + expect(handleStreamRequest).toHaveBeenCalledTimes(1) + expect(handleStreamRequest).toHaveBeenCalledWith({ sessionID: HUB_SESSION, type: StreamRequestTypes.STOP }, expect.any(Function)) + expect(rtp.streamStatus).toBe(0) + }) + + it('tells the delegate stop once for a live session at a factory reset', async () => { + const handleStreamRequest = vi.spyOn(MockDelegate.prototype, 'handleStreamRequest').mockImplementation(() => undefined) + await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST) + + rtp.handleFactoryReset() + rtp.handleFactoryReset() + + expect(handleStreamRequest).toHaveBeenCalledTimes(1) + expect(handleStreamRequest).toHaveBeenCalledWith({ sessionID: HUB_SESSION, type: StreamRequestTypes.STOP }, expect.any(Function)) + expect(rtp.streamStatus).toBe(0) + }) + + it('prepares a stream from one-byte ports and an ipv6 address', async () => { + await writeSetupEndpoints(SETUP_ENDPOINTS_NARROW_PORTS) + + expect(prepareStream).toHaveBeenCalledTimes(1) + expect(prepareStream.mock.calls[0][0]).toMatchObject({ + targetAddress: 'fe80::1', + addressVersion: 'ipv6', + video: { port: 80 }, + audio: { port: 81 }, + }) + }) + + it('prepares a stream under the disabled suite with zero-length keys and salts', async () => { + await writeSetupEndpoints(SETUP_ENDPOINTS_DISABLED_SUITE) + + const { audio, video } = prepareStream.mock.calls[0][0] as PrepareStreamRequest + for (const source of [video, audio]) { + expect(source.srtp_key).toEqual(Buffer.alloc(0)) + expect(source.srtp_salt).toEqual(Buffer.alloc(0)) + } + }) + + it('logs the length of each key and salt and never their bytes', async () => { + const previousNamespaces = createDebug.disable() + const originalLog = createDebug.log + const messages: string[] = [] + + createDebug.enable('HAP-NodeJS:Camera:RTPStreamManagement') + createDebug.log = (...args: unknown[]) => { + messages.push(format(...args)) + } + + try { + await writeSetupEndpoints(SETUP_ENDPOINTS_HUB_REQUEST) + } finally { + createDebug.log = originalLog + createDebug.enable(previousNamespaces) + } + + const output = messages.join('\n') + expect(output).not.toContain(' { + // The value a management advertises for a streaming configuration's suites, the video options shared and the suites the row's own. + function advertised(srtp: { srtp: boolean } | { supportedCryptoSuites: SRTPCryptoSuites[] }): string { + return new RTPStreamManagement(0, { video: mockStreamingOptions.video, ...srtp } as CameraStreamingOptions, new MockDelegate()).supportedRTPConfiguration + } + + it('advertises AgEA for srtp, AgEC without it and for an empty suite list, and both suites delimited', () => { + expect(advertised({ srtp: true })).toBe('AgEA') + expect(advertised({ srtp: false })).toBe('AgEC') + expect(advertised({ supportedCryptoSuites: [] })).toBe('AgEC') + expect(advertised({ + supportedCryptoSuites: [SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, SRTPCryptoSuites.NONE], + })).toBe('AgEAAAACAQI=') + }) + }) + + describe('setup endpoints over paired connections', () => { + const serverUsername = 'CA:FE:00:00:00:01' + const clientUsername = 'CA:FE:00:00:00:02' + + let accessory: Accessory + let accessoryInfo: AccessoryInfo + let camera: CameraController + let clients: HAPHTTPClient[] + let clientInfo: { username: string, privateKey: Buffer, publicKey: Buffer } + + beforeEach(async () => { + accessoryInfo = AccessoryInfo.create(serverUsername) + // @ts-expect-error: private access + accessoryInfo.setupID = Accessory._generateSetupID() + accessoryInfo.displayName = 'Camera' + accessoryInfo.category = Categories.IP_CAMERA + accessoryInfo.pincode = '031-45-154' + accessoryInfo.save = vi.fn() + + const clientKeyPair = tweetnacl.sign.keyPair() + clientInfo = { + username: clientUsername, + privateKey: Buffer.from(clientKeyPair.secretKey), + publicKey: Buffer.from(clientKeyPair.publicKey), + } + accessoryInfo.addPairedClient(clientUsername, clientInfo.publicKey, PermissionTypes.ADMIN) + + // The published accessory loads the paired record above in place of a stored one, as the published switch service of the Accessory spec does. + vi.spyOn(AccessoryInfo, 'load').mockReturnValue(accessoryInfo) + answerWithHubAnswer() + + accessory = new Accessory('Camera', uuid.generate('setup endpoints over paired connections')) + camera = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions)) + accessory.configureController(camera) + clients = [] + }) + + afterEach(async () => { + for (const client of clients) { + client.destroy() + } + await accessory.destroy() + vi.restoreAllMocks() + }) + + // A connection that pair-verifies with the published accessory, as a hub's does, and keeps its encrypted session. + async function pairedClient(port: number): Promise { + const client = new HAPHTTPClient('127.0.0.1', port) + await client.connect() + clients.push(client) + client.enableEncryption(await new PairVerifyClient(client).sendPairVerify({ + username: serverUsername, + publicKey: Buffer.from(accessoryInfo.signPk), + }, clientInfo)) + + return client + } + + it('answers the writer\'s read with its own answer and another paired connection\'s read with an error', async () => { + const listening: Promise<[port: number, hostname: string]> = awaitEventOnce(accessory, AccessoryEventTypes.LISTENING) + await accessory.publish({ + username: serverUsername, + pincode: accessoryInfo.pincode, + category: Categories.IP_CAMERA, + advertiser: MDNSAdvertiser.BONJOUR, + port: 0, + }) + const [port] = await listening + + const writer = await pairedClient(port) + const other = await pairedClient(port) + const id = { + aid: accessory.aid!, + iid: camera.streamManagements[0].service.getCharacteristic(Characteristic.SetupEndpoints).iid!, + } + + await writer.sendCharacteristicWrite({ + characteristics: [ + { ...id, value: SETUP_ENDPOINTS_HUB_REQUEST }, + ], + }) + + // A read's value, or the empty string for a read the accessory refused, which no row expects. + const read = async (client: HAPHTTPClient): Promise => { + const [data] = (await client.sendCharacteristicRead([id])).body.characteristics + + return 'value' in data + ? data.value as string + : '' + } + + expect(decodeSetupEndpointsResponse(await read(writer))).toMatchObject({ + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier: HUB_SESSION, + }) + expect(await read(other)).toBe('AgEC') + }) + }) + describe('a late error answer of a session which already ended', () => { it('should leave the next session alone when the stop of an ended session fails late', async () => { - const controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + const controller = new CameraController(buildControllerOptions(mockStreamingOptions)) controller.constructServices() controller.configureServices() const rtp = controller.streamManagements[0] as RTPStreamManagement @@ -825,7 +1086,7 @@ describe('RTPStreamManagement', () => { }) it('should leave the next session alone when the start of an ended session fails late', async () => { - const controller = new CameraController(buildControllerOptions(baseStreamingOptions)) + const controller = new CameraController(buildControllerOptions(mockStreamingOptions)) controller.constructServices() controller.configureServices() const rtp = controller.streamManagements[0] as RTPStreamManagement @@ -867,7 +1128,7 @@ describe('RTPStreamManagement', () => { describe('handleSetupEndpoints in proxy mode for a camera without audio', () => { it('should answer the setup instead of failing on the missing audio response', async () => { const options: CameraStreamingOptions = { - ...baseStreamingOptions, + ...mockStreamingOptions, proxy: true, audio: { codecs: [] }, } diff --git a/src/lib/camera/RTPStreamManagement.ts b/src/lib/camera/RTPStreamManagement.ts index a4c3c13d3..e239cc479 100644 --- a/src/lib/camera/RTPStreamManagement.ts +++ b/src/lib/camera/RTPStreamManagement.ts @@ -1,9 +1,11 @@ import type { CharacteristicValue } from '../../types.js' import type { CharacteristicSetCallback } from '../Characteristic.js' -import type { CameraStreamingDelegate, ResourceRequestReason } from '../controller/CameraController.js' -import type { StateChangeDelegate } from '../controller/Controller.js' +import type { CameraStreamingDelegate } from '../controller/CameraController.js' +import type { ControllerServiceMap, StateChangeDelegate } from '../controller/Controller.js' import type { CameraRTPStreamManagement } from '../definitions/index.js' import type { HAPConnection } from '../util/eventedhttp.js' +import type { SetupEndpointsRequest } from './capabilities/setupEndpoints.js' +import type { ResourceRequestReason } from './StreamingOptions.js' import assert from 'node:assert' import { Buffer } from 'node:buffer' @@ -20,11 +22,23 @@ import { errorMessage } from '../util/errors.js' import { HAPConnectionEvent } from '../util/eventedhttp.js' import { HapStatusError } from '../util/hapStatusError.js' import { once } from '../util/once.js' +import { callDelegate, logDelegateRejection } from '../util/promise-utils.js' import * as tlv from '../util/tlv.js' import * as uuid from '../util/uuid.js' +import { + decodeSetupEndpointsRequest, + encodeSetupEndpointsResponse, + SETUP_ENDPOINTS_ERROR, + SetupEndpointsStatus, + SRTPCryptoSuites, +} from './capabilities/setupEndpoints.js' +import { encodeSupportedRTPConfiguration } from './capabilities/supportedRtpConfiguration.js' import RTPProxy from './RTPProxy.js' const debug = createDebug('HAP-NodeJS:Camera:RTPStreamManagement') + +// The start of every stream's key in the camera's service map, which the stream's index ends. +const SERVICE_KEY_PREFIX = 'streamManagement' // ---------------------------------- TLV DEFINITIONS START ---------------------------------- enum StreamingStatusTypes { @@ -152,61 +166,7 @@ export enum AudioSamplerate { // ---------- -enum SupportedRTPConfigurationTypes { - SRTP_CRYPTO_SUITE = 0x02, -} - -/** - * @group Camera - */ -export enum SRTPCryptoSuites { // public API - AES_CM_128_HMAC_SHA1_80 = 0x00, - AES_CM_256_HMAC_SHA1_80 = 0x01, - NONE = 0x02, -} - -// ---------- - -enum SetupEndpointsTypes { - SESSION_ID = 0x01, - CONTROLLER_ADDRESS = 0x03, - VIDEO_SRTP_PARAMETERS = 0x04, - AUDIO_SRTP_PARAMETERS = 0x05, -} - -enum AddressTypes { - ADDRESS_VERSION = 0x01, - ADDRESS = 0x02, - VIDEO_RTP_PORT = 0x03, - AUDIO_RTP_PORT = 0x04, -} - -enum IPAddressVersion { - IPV4 = 0x00, - IPV6 = 0x01, -} - -enum SRTPParametersTypes { - SRTP_CRYPTO_SUITE = 0x01, - MASTER_KEY = 0x02, // 16 bytes for AES_CM_128_HMAC_SHA1_80; 32 bytes for AES_256_CM_HMAC_SHA1_80 - MASTER_SALT = 0x03, // 14 bytes -} - -enum SetupEndpointsResponseTypes { - SESSION_ID = 0x01, - STATUS = 0x02, - ACCESSORY_ADDRESS = 0x03, - VIDEO_SRTP_PARAMETERS = 0x04, - AUDIO_SRTP_PARAMETERS = 0x05, - VIDEO_SSRC = 0x06, - AUDIO_SSRC = 0x07, -} - -enum SetupEndpointsStatus { - SUCCESS = 0x00, - BUSY = 0x01, - ERROR = 0x02, -} +export { SRTPCryptoSuites } from './capabilities/setupEndpoints.js' // ---------- @@ -575,12 +535,6 @@ export class RTPStreamManagement { private ipVersion?: 'ipv4' | 'ipv6' // ip version for the current session selectedConfiguration = '' // base64 representation of the currently selected configuration - setupEndpointsResponse = '' // response of the SetupEndpoints Characteristic - /** - * The BUSY answers for the connections which asked for a stream while another session held it. - * They are kept apart from {@link setupEndpointsResponse}, which belongs to the session which holds the stream. - */ - private busySetupEndpointsResponses = new WeakMap() /** * @private @@ -592,18 +546,16 @@ export class RTPStreamManagement { videoProxy?: RTPProxy /** - * A RTPStreamManagement is considered disabled if `HomeKitCameraActive` is set to false. - * We use a closure based approach to retrieve the value of this characteristic. - * The characteristic is managed by the RecordingManagement. + * Answers whether streaming is disabled, when the owner of the operating mode supplies it. Without it, the management reads its own `Active`. */ - private readonly disabledThroughOperatingMode?: () => boolean + private readonly streamingDisabled?: () => boolean constructor( id: number, options: CameraStreamingOptions, delegate: CameraStreamingDelegate, service?: CameraRTPStreamManagement, - disabledThroughOperatingMode?: () => boolean, + streamingDisabled?: () => boolean, ) { this.id = id this.delegate = delegate @@ -626,7 +578,11 @@ export class RTPStreamManagement { throw new Error('Video parameters cannot be undefined in options') } - this.supportedRTPConfiguration = RTPStreamManagement._supportedRTPConfiguration(this.supportedCryptoSuites) + if (this.supportedCryptoSuites.length === 1 && this.supportedCryptoSuites[0] === SRTPCryptoSuites.NONE) { + debug('Client claims it doesn\'t support SRTP. The stream may stop working with future iOS releases.') + } + + this.supportedRTPConfiguration = encodeSupportedRTPConfiguration(this.supportedCryptoSuites) this.supportedVideoStreamConfiguration = RTPStreamManagement._supportedVideoStreamConfiguration(options.video) this.supportedAudioStreamConfiguration = this._supportedAudioStreamConfiguration(options.audio) @@ -635,14 +591,68 @@ export class RTPStreamManagement { this.service = service || this.constructService(id) this.setupServiceHandlers() - this.resetSetupEndpointsResponse() this.resetSelectedStreamConfiguration() - this.disabledThroughOperatingMode = disabledThroughOperatingMode + this.streamingDisabled = streamingDisabled + } + + /** + * The key a stream's service carries in the camera's service map. + * @param index - The stream's index. + * @returns `streamManagement` followed by the index. + * @private + */ + static serviceKey(index: number): string { + return `${SERVICE_KEY_PREFIX}${index}` + } + + /** + * Reconciles the stream services of a restored service map: a stream below the count is adopted from its saved service or created and inserted, and + * every saved stream whose index is at or past the count is deleted, whatever gaps the saved indexes leave. The map keeps no stream the camera does + * not run, none at all for a count of 0. + * @param serviceMap - The camera's service map, changed in place. + * @param count - The number of streams the camera runs. + * @param create - Builds a stream's management over its saved service, or over a new one when it is given none. + * @returns Whether the map changed. + * @private + */ + static reconcile(serviceMap: ControllerServiceMap, count: number, create: (index: number, service?: CameraRTPStreamManagement) => RTPStreamManagement): boolean { + let modified = false + + for (let i = 0; i < count; i++) { + const key = RTPStreamManagement.serviceKey(i) + const saved = serviceMap[key] + + if (saved) { + create(i, saved) + } else { + serviceMap[key] = create(i).getService() + modified = true + } + } + + // A saved key is a stream's when it is the key of its own index, which is why the walk reads every key the map holds rather than stopping at a gap. + for (const key of Object.keys(serviceMap)) { + const index = Number(key.slice(SERVICE_KEY_PREFIX.length)) + + if (key.startsWith(SERVICE_KEY_PREFIX) && (index >= count) && (key === RTPStreamManagement.serviceKey(index))) { + delete serviceMap[key] + modified = true + } + } + + return modified } + /** + * Ends the stream's session: a live session's delegate is told STOP for the stream it prepared, and a stream without one releases what it holds. + */ public forceStop(): void { - this.handleSessionClosed() + if (this.activeConnection) { + this._handleStopStream() + } else { + this.handleSessionClosed() + } } getService(): CameraRTPStreamManagement { @@ -650,17 +660,23 @@ export class RTPStreamManagement { } handleFactoryReset(): void { + // A reset ends a live session first and tells its delegate STOP for the stream it prepared, and no session outlives the reset in use. + if (this.activeConnection) { + this._handleStopStream() + } + this.resetSelectedStreamConfiguration() - this.resetSetupEndpointsResponse() + this.releaseSetupEndpointsAnswers() this.service.updateCharacteristic(Characteristic.Active, true) - // on a factory reset the assumption is that all connections were already terminated and thus "_handleStopStream" was already called } public destroy(): void { if (this.activeConnection) { this._handleStopStream() } + + this.releaseSetupEndpointsAnswers() } private constructService(id: number): CameraRTPStreamManagement { @@ -678,8 +694,15 @@ export class RTPStreamManagement { // the active characteristic might not be present on some older configurations. this.service.setCharacteristic(Characteristic.Active, true) } + // The release comes before the state-change delegate, whose throw would otherwise leave a disabled stream's answers held. this.service.getCharacteristic(Characteristic.Active) - .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.()) + .on(CharacteristicEventTypes.CHANGE, () => { + if (this.streamingIsDisabled()) { + this.releaseSetupEndpointsAnswers() + } + + this.stateChangeDelegate?.() + }) .setProps({ adminOnlyAccess: [Access.WRITE], }) @@ -690,7 +713,6 @@ export class RTPStreamManagement { this.service.setCharacteristic(Characteristic.SupportedAudioStreamConfiguration, this.supportedAudioStreamConfiguration) this._updateStreamStatus(StreamingStatus.AVAILABLE) // reset streaming status to available - this.service.setCharacteristic(Characteristic.SetupEndpoints, this.setupEndpointsResponse) // reset SetupEndpoints to default this.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration) .on(CharacteristicEventTypes.GET, (callback) => { @@ -707,17 +729,11 @@ export class RTPStreamManagement { }) .on(CharacteristicEventTypes.SET, this._handleSelectedStreamConfigurationWrite.bind(this)) + // Setup Endpoints is transient and sensitive by its definition: a writer's answer is held for it and served ahead of this listener, which every + // other read reaches. this.service.getCharacteristic(Characteristic.SetupEndpoints) - .on(CharacteristicEventTypes.GET, (callback, _context, connection) => { - if (this.streamingIsDisabled()) { - callback(null, tlv.encode( - SetupEndpointsResponseTypes.STATUS, SetupEndpointsStatus.ERROR, - ).toString('base64')) - return - } - - // a connection which was told that the stream is busy reads that answer, everybody else the one of the session - callback(null, (connection && this.busySetupEndpointsResponses.get(connection)) ?? this.setupEndpointsResponse) + .on(CharacteristicEventTypes.GET, (callback) => { + callback(null, SETUP_ENDPOINTS_ERROR) }) .on(CharacteristicEventTypes.SET, (value, callback, _context, connection) => { if (!connection) { @@ -731,7 +747,8 @@ export class RTPStreamManagement { private handleSessionClosed(): void { // called when the streaming was ended or aborted and needs to be cleaned up this.resetSelectedStreamConfiguration() - this.resetSetupEndpointsResponse() + // The class runs one session at a time. Every answer it holds names this session or a Busy this session caused, and none outlives it. + this.releaseSetupEndpointsAnswers() if (this.activeConnection) { this.activeConnection.removeListener(HAPConnectionEvent.CLOSED, this.activeConnectionClosedListener) @@ -754,21 +771,15 @@ export class RTPStreamManagement { } private streamingIsDisabled(callback?: CharacteristicSetCallback): boolean { - if (!this.service.getCharacteristic(Characteristic.Active).value) { - if (callback) { - callback(new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE)) - } - return true - } + const disabled = this.streamingDisabled + ? this.streamingDisabled() + : !this.service.getCharacteristic(Characteristic.Active).value - if (this.disabledThroughOperatingMode?.()) { - if (callback) { - callback(new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE)) - } - return true + if (disabled && callback) { + callback(new HapStatusError(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE)) } - return false + return disabled } private _handleSelectedStreamConfigurationWrite(value: CharacteristicValue, callback: CharacteristicSetCallback): void { @@ -1003,7 +1014,7 @@ export class RTPStreamManagement { audio: audioInfo, } - this.delegate.handleStreamRequest(request, error => callback(error)) + this.forwardStreamRequest(request, callback) } private handleReconfigureStream(videoConfiguration: Record, callback: CharacteristicSetCallback): void { @@ -1038,7 +1049,7 @@ export class RTPStreamManagement { video: reconfiguredVideoInfo, } - this.delegate.handleStreamRequest(request, error => callback(error)) + this.forwardStreamRequest(request, callback) } private _handleStopStream(callback?: CharacteristicSetCallback): void { @@ -1049,9 +1060,18 @@ export class RTPStreamManagement { this.handleSessionClosed() - this.delegate.handleStreamRequest(request, error => callback - ? callback(error) - : undefined) + this.forwardStreamRequest(request, callback) + } + + // A stream request that answers a write leaves a synchronous throw to the write's handler, which answers HomeKit with the failure, and logs a rejection, + // which nothing awaits. A stop at a closed connection or a teardown answers no write, and callDelegate takes its throw as well. + private forwardStreamRequest(request: StreamingRequest, callback?: CharacteristicSetCallback): void { + const failure = `CameraStreamingDelegate failed to handle a ${request.type} stream request` + if (callback) { + logDelegateRejection(this.delegate.handleStreamRequest(request, error => callback(error)), failure) + } else { + callDelegate(() => this.delegate.handleStreamRequest(request, () => undefined), failure) + } } private handleSetupEndpoints(value: CharacteristicValue, callback: CharacteristicSetCallback, connection: HAPConnection): void { @@ -1059,37 +1079,20 @@ export class RTPStreamManagement { return } - let request: ReturnType + let request: SetupEndpointsRequest try { // parse and check every field before changing any state, so a malformed request can't leave the stream stuck as busy - request = this.parseSetupEndpointsRequest(value) + request = decodeSetupEndpointsRequest(value as string) } catch (error) { debug('Failed to parse SetupEndpoints request: %s', errorMessage(error)) callback(HAPStatus.INVALID_VALUE_IN_REQUEST) return } - const { - sessionIdentifier, - addressVersion, - controllerAddress, - targetVideoPort, - targetAudioPort, - videoCryptoSuite, - videoMasterKey, - videoMasterSalt, - audioCryptoSuite, - audioMasterKey, - audioMasterSalt, - } = request + const { sessionIdentifier, controllerAddress, videoSRTPParameters, audioSRTPParameters } = request if (this.streamStatus !== StreamingStatus.AVAILABLE) { - // only the connection which asked reads this answer: the response of the session which holds the stream stays - this.busySetupEndpointsResponses.set(connection, tlv.encode( - SetupEndpointsResponseTypes.SESSION_ID, uuid.write(sessionIdentifier), - SetupEndpointsResponseTypes.STATUS, SetupEndpointsStatus.BUSY, - ).toString('base64')) - callback() + callback(undefined, encodeSetupEndpointsResponse({ status: SetupEndpointsStatus.BUSY, sessionIdentifier })) return } @@ -1103,37 +1106,39 @@ export class RTPStreamManagement { this.sessionIdentifier = sessionIdentifier this._updateStreamStatus(StreamingStatus.IN_USE) + // The keys and salts are secrets and a debug log is often shared in public, which is why the line names each one's length and never its bytes. debug( 'Session: ', sessionIdentifier, - '\nControllerAddress: ', controllerAddress, - '\nVideoPort: ', targetVideoPort, - '\nAudioPort: ', targetAudioPort, - '\nVideo Crypto: ', videoCryptoSuite, - '\nAudio Crypto: ', audioCryptoSuite, - // the SRTP master keys and salts are left out on purpose: debug logs get posted in public + '\nControllerAddress: ', controllerAddress.address, + '\nVideoPort: ', controllerAddress.videoRTPPort, + '\nAudioPort: ', controllerAddress.audioRTPPort, + '\nVideo Crypto: ', videoSRTPParameters.cryptoSuite, + '\nVideo Master Key Length: ', videoSRTPParameters.masterKey.length, + '\nVideo Master Salt Length: ', videoSRTPParameters.masterSalt.length, + '\nAudio Crypto: ', audioSRTPParameters.cryptoSuite, + '\nAudio Master Key Length: ', audioSRTPParameters.masterKey.length, + '\nAudio Master Salt Length: ', audioSRTPParameters.masterSalt.length, ) const prepareRequest: PrepareStreamRequest = { sessionID: sessionIdentifier, sourceAddress: connection.localAddress, - targetAddress: controllerAddress, - addressVersion: addressVersion === IPAddressVersion.IPV6 - ? 'ipv6' - : 'ipv4', + targetAddress: controllerAddress.address, + addressVersion: controllerAddress.addressVersion, video: { // if suite is NONE, keys and salts are zero-length - port: targetVideoPort, + port: controllerAddress.videoRTPPort, - srtpCryptoSuite: videoCryptoSuite, - srtp_key: videoMasterKey, - srtp_salt: videoMasterSalt, + srtpCryptoSuite: videoSRTPParameters.cryptoSuite, + srtp_key: videoSRTPParameters.masterKey, + srtp_salt: videoSRTPParameters.masterSalt, }, audio: { - port: targetAudioPort, + port: controllerAddress.audioRTPPort, - srtpCryptoSuite: audioCryptoSuite, - srtp_key: audioMasterKey, - srtp_salt: audioMasterSalt, + srtpCryptoSuite: audioSRTPParameters.cryptoSuite, + srtp_key: audioSRTPParameters.masterKey, + srtp_salt: audioSRTPParameters.masterSalt, }, } @@ -1144,9 +1149,7 @@ export class RTPStreamManagement { if (this.requireProxy) { try { - prepareRequest.targetAddress = connection.getLocalAddress(addressVersion === IPAddressVersion.IPV6 - ? 'ipv6' - : 'ipv4') // ip versions must be the same + prepareRequest.targetAddress = connection.getLocalAddress(controllerAddress.addressVersion) // ip versions must be the same } catch (error) { // the stream is marked as in use by now: free it and answer, or it stays blocked until the connection closes debug(`Could not find the local address for the RTP proxy: ${errorMessage(error)}`) @@ -1158,8 +1161,8 @@ export class RTPStreamManagement { } this.videoProxy = videoProxy = new RTPProxy({ - outgoingAddress: controllerAddress, - outgoingPort: targetVideoPort, + outgoingAddress: controllerAddress.address, + outgoingPort: controllerAddress.videoRTPPort, outgoingSSRC: crypto.randomBytes(4).readUInt32LE(0), // videoSSRC disabled: false, }) @@ -1168,8 +1171,8 @@ export class RTPStreamManagement { if (!this.disableAudioProxy) { this.audioProxy = audioProxy = new RTPProxy({ - outgoingAddress: controllerAddress, - outgoingPort: targetAudioPort, + outgoingAddress: controllerAddress.address, + outgoingPort: controllerAddress.audioRTPPort, outgoingSSRC: crypto.randomBytes(4).readUInt32LE(0), // audioSSRC disabled: this.videoOnly, }) @@ -1196,7 +1199,9 @@ export class RTPStreamManagement { prepareRequest.audio.proxy_rtcp = audioProxy.incomingRTCPPort() } - this.delegate.prepareStream(prepareRequest, once((error?: Error, response?: PrepareStreamResponse) => { + // A throw from the delegate reaches the catch below, which answers the write, and the rejection of the promise an async delegate returns, which nothing + // awaits, is logged. + logDelegateRejection(this.delegate.prepareStream(prepareRequest, once((error?: Error, response?: PrepareStreamResponse) => { if (this.sessionIdentifier !== sessionIdentifier) { // The session ended while the delegate was preparing it (e.g. the connection closed), and another one // may have started since. This answer must not touch that one. @@ -1207,7 +1212,8 @@ export class RTPStreamManagement { if (error || !response) { debug(`PrepareStream request encountered an error: ${error ? error.message : undefined}`) - this.handleSessionClosed() // resets the SetupEndpoints answer to a plain error + + this.handleSessionClosed() // an answer with neither an error nor a response must not tell the controller that the setup worked callback(error ?? HAPStatus.SERVICE_COMMUNICATION_FAILURE) } else { @@ -1216,75 +1222,28 @@ export class RTPStreamManagement { } catch (error) { // the delegate usually calls back asynchronously, so nothing up the stack would catch this debug(`Failed to build the SetupEndpoints response from the PrepareStreamResponse: ${errorMessage(error)}`) - this.handleSessionClosed() // resets the SetupEndpoints answer to a plain error + + this.handleSessionClosed() callback(error instanceof Error ? error : new Error(String(error))) } } - })) - }).catch((error: Error) => { - debug(`RTP proxy setup failed: ${error.message}`) + })), 'CameraStreamingDelegate failed to prepare a stream') + }).catch((error: Error | undefined) => { + debug(`RTP proxy setup failed: ${errorMessage(error)}`) + + // As above: the answer for a session that is no longer current leaves the current session alone. if (this.sessionIdentifier !== sessionIdentifier) { - callback(HAPStatus.SERVICE_COMMUNICATION_FAILURE) // as above: not the current session anymore + callback(HAPStatus.SERVICE_COMMUNICATION_FAILURE) return } - this.handleSessionClosed() // resets the SetupEndpoints answer to a plain error + + this.handleSessionClosed() callback(error) }) } - private parseSetupEndpointsRequest(value: CharacteristicValue) { - const data = Buffer.from(value as string, 'base64') - const objects = tlv.decode(data) - - const sessionIdentifier = uuid.unparse(objects[SetupEndpointsTypes.SESSION_ID]) - - // Address - const targetAddressPayload = objects[SetupEndpointsTypes.CONTROLLER_ADDRESS] - const processedAddressInfo = tlv.decode(targetAddressPayload) - const addressVersion = processedAddressInfo[AddressTypes.ADDRESS_VERSION].readUInt8(0) - const controllerAddress = processedAddressInfo[AddressTypes.ADDRESS].toString('utf8') - const targetVideoPort = processedAddressInfo[AddressTypes.VIDEO_RTP_PORT].readUInt16LE(0) - const targetAudioPort = processedAddressInfo[AddressTypes.AUDIO_RTP_PORT].readUInt16LE(0) - - // Video SRTP Params - const videoSRTPPayload = objects[SetupEndpointsTypes.VIDEO_SRTP_PARAMETERS] - const processedVideoInfo = tlv.decode(videoSRTPPayload) - const videoCryptoSuite: SRTPCryptoSuites = processedVideoInfo[SRTPParametersTypes.SRTP_CRYPTO_SUITE].readUInt8(0) - const videoMasterKey = processedVideoInfo[SRTPParametersTypes.MASTER_KEY] - const videoMasterSalt = processedVideoInfo[SRTPParametersTypes.MASTER_SALT] - - // Audio SRTP Params - const audioSRTPPayload = objects[SetupEndpointsTypes.AUDIO_SRTP_PARAMETERS] - const processedAudioInfo = tlv.decode(audioSRTPPayload) - const audioCryptoSuite: SRTPCryptoSuites = processedAudioInfo[SRTPParametersTypes.SRTP_CRYPTO_SUITE].readUInt8(0) - const audioMasterKey = processedAudioInfo[SRTPParametersTypes.MASTER_KEY] - const audioMasterSalt = processedAudioInfo[SRTPParametersTypes.MASTER_SALT] - - // if the suite is NONE, keys and salts are zero-length - if (videoCryptoSuite !== SRTPCryptoSuites.NONE && (!videoMasterKey || !videoMasterSalt)) { - throw new Error('Video SRTP master key or salt is missing') - } - if (audioCryptoSuite !== SRTPCryptoSuites.NONE && (!audioMasterKey || !audioMasterSalt)) { - throw new Error('Audio SRTP master key or salt is missing') - } - - return { - sessionIdentifier, - addressVersion, - controllerAddress, - targetVideoPort, - targetAudioPort, - videoCryptoSuite, - videoMasterKey, - videoMasterSalt, - audioCryptoSuite, - audioMasterKey, - audioMasterSalt, - } - } - private generateSetupEndpointResponse( connection: HAPConnection, identifier: StreamSessionIdentifier, @@ -1402,38 +1361,37 @@ export class RTPStreamManagement { } this.ipVersion = addressVersion // we need to save this in order to calculate some default mtu values later - const accessoryAddress = tlv.encode( - AddressTypes.ADDRESS_VERSION, addressVersion === 'ipv4' - ? IPAddressVersion.IPV4 - : IPAddressVersion.IPV6, - AddressTypes.ADDRESS, address, - AddressTypes.VIDEO_RTP_PORT, tlv.writeUInt16(videoPort), - AddressTypes.AUDIO_RTP_PORT, tlv.writeUInt16(audioPort), - ) - - const videoSRTPParameters = tlv.encode( - SRTPParametersTypes.SRTP_CRYPTO_SUITE, videoCryptoSuite, - SRTPParametersTypes.MASTER_KEY, videoSRTPKey, - SRTPParametersTypes.MASTER_SALT, videoSRTPSalt, - ) - - const audioSRTPParameters = tlv.encode( - SRTPParametersTypes.SRTP_CRYPTO_SUITE, audioCryptoSuite, - SRTPParametersTypes.MASTER_KEY, audioSRTPKey, - SRTPParametersTypes.MASTER_SALT, audioSRTPSalt, - ) + // A prepare that settles while streaming is disabled holds no answer: its writer's read answers the Error TLV as every read while disabled does, and no + // answer carrying the accessory's keys outlives the release the disable ran. The force-stop it queues ends the session, whose slot would otherwise stay in + // use until its connection closes, and runs a microtask later so the delegate's prepare callback returns before its STOP arrives. + if (this.streamingIsDisabled()) { + callback() + queueMicrotask(() => this.forceStop()) + return + } - this.busySetupEndpointsResponses.delete(connection) // it reads the response of its session from now on - this.setupEndpointsResponse = tlv.encode( - SetupEndpointsResponseTypes.SESSION_ID, uuid.write(identifier), - SetupEndpointsResponseTypes.STATUS, SetupEndpointsStatus.SUCCESS, - SetupEndpointsResponseTypes.ACCESSORY_ADDRESS, accessoryAddress, - SetupEndpointsResponseTypes.VIDEO_SRTP_PARAMETERS, videoSRTPParameters, - SetupEndpointsResponseTypes.AUDIO_SRTP_PARAMETERS, audioSRTPParameters, - SetupEndpointsResponseTypes.VIDEO_SSRC, tlv.writeUInt32(videoSSRC), - SetupEndpointsResponseTypes.AUDIO_SSRC, tlv.writeUInt32(audioSSRC), - ).toString('base64') - callback() + callback(undefined, encodeSetupEndpointsResponse({ + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier: identifier, + accessoryAddress: { + addressVersion, + address, + videoRTPPort: videoPort, + audioRTPPort: audioPort, + }, + videoSRTPParameters: { + cryptoSuite: videoCryptoSuite, + masterKey: videoSRTPKey, + masterSalt: videoSRTPSalt, + }, + audioSRTPParameters: { + cryptoSuite: audioCryptoSuite, + masterKey: audioSRTPKey, + masterSalt: audioSRTPSalt, + }, + videoSSRC, + audioSSRC, + })) } private _updateStreamStatus(status: StreamingStatus): void { @@ -1444,14 +1402,6 @@ export class RTPStreamManagement { ).toString('base64')) } - private static _supportedRTPConfiguration(supportedCryptoSuites: SRTPCryptoSuites[]): string { - if (supportedCryptoSuites.length === 1 && supportedCryptoSuites[0] === SRTPCryptoSuites.NONE) { - debug('Client claims it doesn\'t support SRTP. The stream may stop working with future iOS releases.') - } - - return tlv.encode(SupportedRTPConfigurationTypes.SRTP_CRYPTO_SUITE, supportedCryptoSuites).toString('base64') - } - private static _supportedVideoStreamConfiguration(videoOptions: VideoStreamingOptions): string { if (!videoOptions.codec) { throw new Error('Video codec cannot be undefined') @@ -1620,12 +1570,9 @@ export class RTPStreamManagement { ).toString('base64') } - private resetSetupEndpointsResponse(): void { - this.busySetupEndpointsResponses = new WeakMap() // every connection reads the default response again - this.setupEndpointsResponse = tlv.encode( - SetupEndpointsResponseTypes.STATUS, SetupEndpointsStatus.ERROR, - ).toString('base64') - this.service.updateCharacteristic(Characteristic.SetupEndpoints, this.setupEndpointsResponse) + // Releases the Setup Endpoints answer every connection holds, at each boundary that ends or bounds the answers a session made. + private releaseSetupEndpointsAnswers(): void { + this.service.getCharacteristic(Characteristic.SetupEndpoints).releaseTransientAnswers() } private resetSelectedStreamConfiguration(): void { diff --git a/src/lib/camera/RecordingManagement.spec.ts b/src/lib/camera/RecordingManagement.spec.ts index e430c776c..5ef860526 100644 --- a/src/lib/camera/RecordingManagement.spec.ts +++ b/src/lib/camera/RecordingManagement.spec.ts @@ -1,28 +1,183 @@ -import type { - CameraRecordingConfiguration, - RecordingPacket, -} from './RecordingManagement.js' +import type { Mock, MockInstance } from 'vitest' + +import type { CameraControllerServiceMap, CameraRecordingDelegate, CameraStreamingDelegate } from '../controller/index.js' +import type { AccessoryInformation } from '../definitions/index.js' +import type { BufferRecorder, RecordingAdmission } from './recording/BufferRecorder.js' +import type { CameraRecordingConfiguration, RecordingManagementState, RecordingPacket } from './RecordingManagement.js' +import type { CameraSnapshotRequest } from './StreamingOptions.js' import { Buffer } from 'node:buffer' -import { EventEmitter } from 'node:events' +import crypto from 'node:crypto' import process from 'node:process' +import { ReadableStream } from 'node:stream/web' +import { format } from 'node:util' -import { describe, expect, it, vi } from 'vitest' +import createDebug from 'debug' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { + bufferCamera, + createCameraControllerOptions, + FIRST_VIDEO_SENSOR, + frames, + handPublishedContext, + MockDelegate, + mockRecordingOptions, + mockStreamingOptions, + NUMBERED_ACCESSORY_UUID, +} from '../../test-utils/cameraFixtures.js' +import { DataStreamClient } from '../../test-utils/dataStreamClient.js' +import { captureDebug } from '../../test-utils/engineDebug.js' +import { skeletonPackets, TIER_STREAM_PARAMETER_SETS, tierStreamInitialization } from '../../test-utils/mp4Fixtures.js' +import { problemsOf, REPORTER_ACCESSORY_UUID } from '../../test-utils/reporterFixtures.js' +import { deferred, settle } from '../../test-utils/settle.js' import { Characteristic } from '../Characteristic.js' -import { MockDelegate, mockRecordingOptions } from '../controller/CameraController.spec.js' +import { CameraController, ResourceRequestReason } from '../controller/index.js' +import { + DataStreamManagement, + HDSConnectionError, + HDSConnectionErrorType, + HDSProtocolError, + HDSProtocolSpecificErrorReason, + HDSStatus, + Protocols, + Topics, +} from '../datastream/index.js' import { HAPStatus } from '../HAPServer.js' +import { Service, ServiceEventTypes } from '../Service.js' import { HapStatusError } from '../util/hapStatusError.js' +import { onCameraProblem } from './diagnostics/problems.js' +import { OperatingModePolicy } from './OperatingModePolicy.js' +import { ServedRecording, ServedRecordings } from './recording/ServedRecording.js' import { AudioRecordingCodecType, AudioRecordingSamplerate, EventTriggerOption, MediaContainerType, + PacketDataType, RecordingManagement, } from './RecordingManagement.js' import { AudioBitrate, H264Level, H264Profile, VideoCodecType } from './RTPStreamManagement.js' +const SELECTED_CONFIGURATION = 'AR0BBKAPAAACCAEAAAAAAAAAAwsBAQACBgEEoA8AAAIkAQEAAhIBAQECAQIDBNAHAAAEBKAPAAADCwECsAQCAkAGAwEYAxQBAQACDwEBAQIBAAMBAwQEQAAAAA==' +const OPEN_RECORDING = { + reason: 'motion', + streamId: 1, + target: 'controller', + type: 'ipcamera.recording', +} +const MAX_CHUNK = 0x40000 + +type RecordingRequest = CameraRecordingDelegate['handleRecordingStreamRequest'] + +// A delegate whose recording is the row's own, every call it hears a spy. +type RecordingDelegate = MockDelegate & { + acknowledgeStream: Mock> + closeRecordingStream: Mock + handleRecordingStreamRequest: Mock +} + +function recordingDelegate(record: RecordingRequest): RecordingDelegate { + return Object.assign(new MockDelegate(), { + acknowledgeStream: vi.fn>(), + closeRecordingStream: vi.fn(), + handleRecordingStreamRequest: vi.fn(record), + }) +} + +// A standalone camera that records: a configuration selected and recording switched on, each through its characteristic, its management made with the +// capabilities a row hands, and none otherwise. +function recordingCamera(delegate: CameraRecordingDelegate, capabilities?: ConstructorParameters[5]): RecordingManagement { + const management = new RecordingManagement(mockRecordingOptions, delegate, new Set([EventTriggerOption.MOTION]), undefined, undefined, capabilities) + + management.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + + return management +} + +function packet(length: number, isLast = false): RecordingPacket { + return { + data: crypto.randomBytes(length), + isLast, + } +} + +function aborted(signal: AbortSignal): Promise { + return new Promise(resolve => signal.addEventListener('abort', () => resolve(), { once: true })) +} + +function open(client: DataStreamClient, streamId = 1, overrides: Record = {}): number { + return client.request(Protocols.DATA_SEND, Topics.OPEN, { + ...OPEN_RECORDING, + streamId, + ...overrides, + }) +} + +function acknowledge(client: DataStreamClient, streamId = 1): void { + client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId }) +} + +function hubClose(client: DataStreamClient, streamId: number, reason: HDSProtocolSpecificErrorReason): void { + client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason, streamId }) +} + +// The status an open was answered with, and the reason a refusal carries. +function answer(client: DataStreamClient, id: number): { reason?: number, status?: number } { + const written = client.answerTo(id) + + return { reason: written?.message.status, status: written?.header.status } +} + +function dataEvents(client: DataStreamClient): Record[] { + return client.events(Protocols.DATA_SEND, Topics.DATA) +} + +function closeEvents(client: DataStreamClient): Record[] { + return client.events(Protocols.DATA_SEND, Topics.CLOSE) +} + +// Each data event's chunk as the hub reads it: its metadata and whether it ends the stream. +function chunks(client: DataStreamClient): Record[] { + return dataEvents(client).map(({ endOfStream, packets: [{ metadata }], streamId }) => ({ endOfStream, metadata, streamId })) +} + +function signalOf(delegate: RecordingDelegate, call = 0): AbortSignal { + return delegate.handleRecordingStreamRequest.mock.calls[call][1]! +} + +function recordingStreamOf(management: RecordingManagement): unknown { + // @ts-expect-error: private access + return management.recordingStream +} + describe('RecordingManagement', () => { + it('leaves each sensor\'s status active at the policy\'s camera state when it restores a legacy layout without one', () => { + const policy = new OperatingModePolicy() + const management = new RecordingManagement(mockRecordingOptions, new MockDelegate(), new Set([EventTriggerOption.MOTION]), undefined, policy) + const sensor = new Service.MotionSensor('', '') + const legacyLayout = { + configurationHash: { algorithm: 'sha256' as const, hash: '' }, + recordingAudioActive: false, + eventSnapshotsActive: true, + periodicSnapshotsActive: true, + } + sensor.setCharacteristic(Characteristic.StatusActive, false) + management.sensorServices.push(sensor) + + management.deserialize(legacyLayout) + + expect(sensor.getCharacteristic(Characteristic.StatusActive).value).toBe(true) + + management.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + sensor.setCharacteristic(Characteristic.StatusActive, true) + management.deserialize(legacyLayout) + + expect(policy.homeKitCameraActive).toBe(false) + expect(sensor.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + }) + it('handleSelectedCameraRecordingConfiguration', () => { const base64Input = 'AR0BBKAPAAACCAEAAAAAAAAAAwsBAQACBgEEoA8AAAIkAQEAAhIBAQECAQIDBNAHAAAEBKAPAAADCwECsAQCAkAGAwEYAxQBAQACDwEBAQIBAAMBAwQEQAAAAA==' @@ -104,235 +259,159 @@ describe('RecordingManagement', () => { }) describe('dataSend open', () => { - function managementReadyToRecord(delegate = new MockDelegate()): RecordingManagement { - const management = new RecordingManagement( - mockRecordingOptions, - delegate, - new Set([EventTriggerOption.MOTION, EventTriggerOption.DOORBELL]), - ) - const internals = management as any - internals.recordingActive = true - internals.selectedConfiguration = {} - internals.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value = true - return management - } + afterEach(() => { + vi.restoreAllMocks() + }) - function fakeConnection(sendResponse: () => void) { - return Object.assign(new EventEmitter(), { - remoteAddress: '127.0.0.1', - sendResponse: vi.fn(sendResponse), - sendEvent: vi.fn(), - addProtocolHandler: vi.fn(() => true), - removeProtocolHandler: vi.fn(), - isConsideredClosed: () => false, - }) + // A recording that yields one packet and then holds until the row releases it. + function heldRecording(): { delegate: RecordingDelegate, release: () => void } { + const held = deferred() + + return { + delegate: recordingDelegate(async function* () { + yield packet(10) + await held.promise + }), + release: () => held.resolve(), + } } it('should free the stream instead of rejecting when the open response can not be sent', async () => { const unhandled: unknown[] = [] const onUnhandled = (reason: unknown) => unhandled.push(reason) process.on('unhandledRejection', onUnhandled) - const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) try { - const management = managementReadyToRecord() - const connection = fakeConnection(() => { + const management = recordingCamera(recordingDelegate(async function* () { + yield packet(10, true) + })) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const sendResponse = vi.spyOn(client.connection, 'sendResponse').mockImplementationOnce(() => { throw new Error('Cannot send message on closing/closed socket!') }) - ;(management as any).handleDataSendOpen(connection, 1, { - streamId: 5, - type: 'ipcamera.recording', - target: 'controller', - reason: 'record', - }) - await new Promise(resolve => setTimeout(resolve, 10)) + open(client, 5) + await settle() - expect(connection.sendResponse).toHaveBeenCalledTimes(1) + expect(sendResponse).toHaveBeenCalledTimes(1) expect(unhandled).toEqual([]) - expect((management as any).recordingStream).toBeUndefined() // the next open is not answered with "busy" + expect(recordingStreamOf(management)).toBeUndefined() // the next open is not answered with "busy" } finally { process.off('unhandledRejection', onUnhandled) - error.mockRestore() } }) it('should signal the end of the stream when the last packet has no data', async () => { - class EmptyLastPacketDelegate extends MockDelegate { - override async* handleRecordingStreamRequest(): AsyncGenerator { - yield { - data: Buffer.alloc(100, 1), - isLast: false, - } - yield { - data: Buffer.alloc(0), - isLast: false, - } // skipped, without using up a sequence number - yield { - data: Buffer.alloc(50, 2), - isLast: false, - } - yield { - data: Buffer.alloc(0), - isLast: true, - } + const management = recordingCamera(recordingDelegate(async function* () { + yield { + data: Buffer.alloc(100, 1), + isLast: false, } - } - const management = managementReadyToRecord(new EmptyLastPacketDelegate()) - const connection = fakeConnection(() => undefined) + yield { + data: Buffer.alloc(0), + isLast: false, + } // skipped, without using up a sequence number + yield { + data: Buffer.alloc(50, 2), + isLast: false, + } + yield { + data: Buffer.alloc(0), + isLast: true, + } + })) + const client = await DataStreamClient.connect(management.dataStreamManagement) - ;(management as any).handleDataSendOpen(connection, 1, { - streamId: 5, - type: 'ipcamera.recording', - target: 'controller', - reason: 'record', - }) - await new Promise(resolve => setTimeout(resolve, 10)) + open(client, 5) + await settle() - const events = connection.sendEvent.mock.calls.map(call => ({ - length: call[2].packets[0].data.length, - sequenceNumber: call[2].packets[0].metadata.dataSequenceNumber, - endOfStream: call[2].endOfStream, - })) - expect(events).toEqual([ + expect(dataEvents(client).map(({ endOfStream, packets: [{ data, metadata }] }) => ({ + length: data.length, + sequenceNumber: metadata.dataSequenceNumber, + endOfStream, + }))).toEqual([ { length: 100, sequenceNumber: 1, endOfStream: false }, { length: 50, sequenceNumber: 2, endOfStream: false }, { length: 0, sequenceNumber: 3, endOfStream: true }, ]) - ;(management as any).recordingStream?.close(0) + acknowledge(client, 5) }) it('should ignore an acknowledgment for another stream', async () => { - class WaitingDelegate extends MockDelegate { - acknowledgeStream = vi.fn() - - override async* handleRecordingStreamRequest(): AsyncGenerator { - yield { - data: Buffer.alloc(10, 1), - isLast: false, - } - await new Promise(resolve => setTimeout(resolve, 1000)) // still recording - } - } - const delegate = new WaitingDelegate() - const management = managementReadyToRecord(delegate) - const connection = fakeConnection(() => undefined) + const { delegate, release } = heldRecording() + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) - ;(management as any).handleDataSendOpen(connection, 1, { - streamId: 5, - type: 'ipcamera.recording', - target: 'controller', - reason: 'record', - }) - await new Promise(resolve => setTimeout(resolve, 10)) - const stream = (management as any).recordingStream + open(client, 5) + await settle() + const stream = recordingStreamOf(management) - stream.handleDataSendAck({ streamId: 999, endOfStream: true }) + acknowledge(client, 999) expect(delegate.acknowledgeStream).not.toHaveBeenCalled() - expect((management as any).recordingStream).toBe(stream) + expect(recordingStreamOf(management)).toBe(stream) - stream.handleDataSendAck({ streamId: 5, endOfStream: true }) + acknowledge(client, 5) expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(5) - expect((management as any).recordingStream).toBeUndefined() + expect(recordingStreamOf(management)).toBeUndefined() + release() }) it('should not keep the process alive while it waits for the home hub to close a finished stream', async () => { - class FinishedDelegate extends MockDelegate { - override async* handleRecordingStreamRequest(): AsyncGenerator { - yield { - data: Buffer.alloc(10, 1), - isLast: true, - } - } - } - const management = managementReadyToRecord(new FinishedDelegate()) - const connection = fakeConnection(() => undefined) + const management = recordingCamera(recordingDelegate(async function* () { + yield packet(10, true) + })) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const timers = vi.spyOn(globalThis, 'setTimeout') - ;(management as any).handleDataSendOpen(connection, 1, { - streamId: 5, - type: 'ipcamera.recording', - target: 'controller', - reason: 'record', - }) - await new Promise(resolve => setTimeout(resolve, 10)) - const stream = (management as any).recordingStream + open(client, 5) + await settle() - expect(stream.closingTimeout.hasRef()).toBe(false) - stream.close(0) + // The close wait is the 12 second timer the finished stream armed, read through the handle setTimeout answered. + const closeWait = timers.mock.calls.findLastIndex(([, delay]) => delay === 12000) + + expect(closeWait).toBeGreaterThanOrEqual(0) + expect((timers.mock.results[closeWait].value as ReturnType).hasRef()).toBe(false) + acknowledge(client, 5) }) it('should not keep the process alive while it waits for the generator of a closed stream', async () => { - let finish = (): void => undefined - class WaitingDelegate extends MockDelegate { - override async* handleRecordingStreamRequest(): AsyncGenerator { - yield { - data: Buffer.alloc(10, 1), - isLast: false, - } - await new Promise(resolve => finish = resolve) // still recording - } - } - const management = managementReadyToRecord(new WaitingDelegate()) - const connection = fakeConnection(() => undefined) + const { delegate, release } = heldRecording() + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) - ;(management as any).handleDataSendOpen(connection, 1, { - streamId: 5, - type: 'ipcamera.recording', - target: 'controller', - reason: 'record', - }) - await new Promise(resolve => setTimeout(resolve, 10)) - const stream = (management as any).recordingStream + open(client, 5) + await settle() + const stream = recordingStreamOf(management) as { generatorTimeout?: ReturnType } - stream.close(0) - expect(stream.generatorTimeout.hasRef()).toBe(false) - finish() - await new Promise(resolve => setTimeout(resolve, 10)) + hubClose(client, 5, HDSProtocolSpecificErrorReason.NORMAL) + expect(stream.generatorTimeout?.hasRef()).toBe(false) + release() + await settle() }) it('should hand a close reason which is not a number to the delegate as a missing reason', async () => { - class WaitingDelegate extends MockDelegate { - override closeRecordingStream = vi.fn() - - override async* handleRecordingStreamRequest(): AsyncGenerator { - yield { - data: Buffer.alloc(10, 1), - isLast: false, - } - await new Promise(resolve => setTimeout(resolve, 1000)) // still recording - } - } - const delegate = new WaitingDelegate() - const management = managementReadyToRecord(delegate) - const connection = fakeConnection(() => undefined) + const { delegate, release } = heldRecording() + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) - ;(management as any).handleDataSendOpen(connection, 1, { - streamId: 5, - type: 'ipcamera.recording', - target: 'controller', - reason: 'record', - }) - await new Promise(resolve => setTimeout(resolve, 10)) - - ;(management as any).recordingStream.handleDataSendClose({ streamId: 5, reason: 'because' }) + open(client, 5) + await settle() + client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason: 'because', streamId: 5 }) expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(5, undefined) - expect((management as any).recordingStream).toBeUndefined() + expect(recordingStreamOf(management)).toBeUndefined() + release() }) - it('should reject an open without a numeric stream id', () => { - const management = managementReadyToRecord() - const connection = fakeConnection(() => undefined) - - ;(management as any).handleDataSendOpen(connection, 1, { - streamId: 'five', - type: 'ipcamera.recording', - target: 'controller', - }) + it('should reject an open without a numeric stream id', async () => { + const management = recordingCamera(recordingDelegate(async function* () { + yield packet(10, true) + })) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const id = open(client, 1, { streamId: 'five' }) - expect(connection.sendResponse).toHaveBeenCalledExactlyOnceWith('dataSend', 'open', 1, 6, { - status: 5, - }) - expect((management as any).recordingStream).toBeUndefined() + expect(answer(client, id)).toEqual({ reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(client.written.filter(({ header }) => header.response !== undefined && header.id === id)).toHaveLength(1) + expect(recordingStreamOf(management)).toBeUndefined() }) }) @@ -400,4 +479,2154 @@ describe('RecordingManagement', () => { + 'MBGAAAAwsBArAEAgJABgMBDwAAAwsBAjgEAgKgBQMBDwAAAwsBAsADAgIABQMBDwAAAwsBAgADAgIABAMBDw==') expect(supportedAudio).toEqual('AQ4BAQACCQEBAQIBAAMBAw==') }) + + describe('a recording management without the legacy recording options', () => { + const CONFIGURATION_CHARACTERISTICS = [ + Characteristic.SupportedCameraRecordingConfiguration, + Characteristic.SupportedVideoRecordingConfiguration, + Characteristic.SupportedAudioRecordingConfiguration, + Characteristic.SelectedCameraRecordingConfiguration, + ] + + // The cameras a row builds, removed after it. No stream or policy outlives its row. + const cameras: CameraController[] = [] + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + + vi.restoreAllMocks() + }) + + function slim(delegate: CameraRecordingDelegate = new MockDelegate(), policy?: OperatingModePolicy): RecordingManagement { + return new RecordingManagement(undefined, delegate, new Set([EventTriggerOption.MOTION]), undefined, policy) + } + + function configurationCharacteristics(service: Service): boolean[] { + return CONFIGURATION_CHARACTERISTICS.map(type => service.testCharacteristic(type)) + } + + it('builds its recording service with Active and Recording Audio Active and none of the configuration characteristics', () => { + const management = slim() + + expect(management.options).toBeUndefined() + expect(management.recordingManagementService.characteristics.map(({ UUID }) => UUID)).toEqual([ + Characteristic.Active.UUID, + Characteristic.RecordingAudioActive.UUID, + ]) + expect(configurationCharacteristics(management.recordingManagementService)).toEqual([false, false, false, false]) + }) + + it('removes the configuration characteristics from an adopted recording service that carries them, each raising the service\'s configuration change', async () => { + const legacy = new RecordingManagement(mockRecordingOptions, new MockDelegate(), new Set([EventTriggerOption.MOTION])) + const { recordingManagementService, operatingModeService } = legacy + // Each configuration change is read with the configuration characteristics the service still holds at it, and each removal's own change shows. + const heldAtChange: number[] = [] + + recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + await settle() + legacy.destroy() + recordingManagementService.on(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE, () => { + heldAtChange.push(configurationCharacteristics(recordingManagementService).filter(Boolean).length) + }) + + const management = new RecordingManagement(undefined, new MockDelegate(), new Set([EventTriggerOption.MOTION]), { + dataStreamManagement: new DataStreamManagement(legacy.dataStreamManagement.getService()), + operatingMode: operatingModeService, + recordingManagement: recordingManagementService, + }) + + expect(configurationCharacteristics(management.recordingManagementService)).toEqual([false, false, false, false]) + expect(heldAtChange).toEqual(expect.arrayContaining([3, 2, 1, 0])) + expect(management.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + }) + + it('serves a recording with none selected, the open\'s other checks standing', async () => { + const delegate = recordingDelegate(async function* () { + yield packet(100, true) + }) + const management = slim(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const refused = open(client) + + await settle() + + expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + + management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + await settle() + + const served = open(client) + + await settle() + + expect(answer(client, served)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }) + expect(delegate.handleRecordingStreamRequest).toHaveBeenCalledExactlyOnceWith(1, expect.any(AbortSignal)) + expect(chunks(client).map(({ endOfStream }) => endOfStream)).toEqual([true]) + + acknowledge(client) + + expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1) + }) + + it('answers an open its capabilities\' admit refuses with the refusal\'s reason, telling the delegate nothing and holding no stream, and serves one it ' + + 'admits through the admission\'s serving function, while a management whose capabilities hold no admit asks its delegate', async () => { + const { reporter } = problemsOf() + const capabilities = { + feed: new ServedRecordings({ reporter, sensorUUID: FIRST_VIDEO_SENSOR.uuid }), + reporter, + } + const serve = vi.fn(async function* (signal?: AbortSignal): AsyncGenerator { + await aborted(signal!) + }) + const answers: RecordingAdmission[] = [ + { admitted: false, reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED }, + { admitted: false, reason: HDSProtocolSpecificErrorReason.BUSY }, + { admitted: true, serve }, + ] + const admit = vi.fn<(streamId: number) => RecordingAdmission>(() => answers.shift()!) + const delegate = recordingDelegate(async function* () { + yield packet(100, true) + }) + const updateRecordingActive = vi.spyOn(delegate, 'updateRecordingActive') + const management = new RecordingManagement(undefined, delegate, new Set([EventTriggerOption.MOTION]), undefined, undefined, { ...capabilities, admit }) + + // Active is assigned directly: the policy reads recording allowed and the delegate has heard nothing of it before an open the management lets + // through. + management.recordingManagementService.getCharacteristic(Characteristic.Active).value = Characteristic.Active.ACTIVE + + const client = await DataStreamClient.connect(management.dataStreamManagement) + const refusals = [ + open(client, 1), + open(client, 2), + ] + + await settle() + + expect(refusals.map(id => answer(client, id))).toEqual([ + { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + { reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + ]) + expect(updateRecordingActive).not.toHaveBeenCalled() + expect(recordingStreamOf(management)).toBeUndefined() + + const admitted = open(client, 3) + + await settle() + + expect(answer(client, admitted)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }) + expect(admit.mock.calls).toEqual([ + [1], + [2], + [3], + ]) + expect(updateRecordingActive.mock.calls).toEqual([ + [true], + ]) + expect(serve).toHaveBeenCalledExactlyOnceWith(expect.any(AbortSignal)) + + const [signal] = serve.mock.calls[0] + + expect(signal!.aborted).toBe(false) + + hubClose(client, 3, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + expect(signal!.aborted).toBe(true) + expect(delegate.handleRecordingStreamRequest).not.toHaveBeenCalled() + + const asked = recordingDelegate(async function* () { + yield packet(100, true) + }) + const plain = new RecordingManagement(undefined, asked, new Set([EventTriggerOption.MOTION]), undefined, undefined, capabilities) + + plain.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + + const plainClient = await DataStreamClient.connect(plain.dataStreamManagement) + const served = open(plainClient) + + await settle() + + expect(answer(plainClient, served)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }) + expect(asked.handleRecordingStreamRequest).toHaveBeenCalledExactlyOnceWith(1, expect.any(AbortSignal)) + + acknowledge(plainClient) + }) + + it('saves no recording state', () => { + expect(slim().serialize()).toBeUndefined() + }) + + it('reports recording Active to its delegate and never a configuration, its factory reset\'s report included', async () => { + const delegate = new MockDelegate() + const updateRecordingActive = vi.spyOn(delegate, 'updateRecordingActive') + const updateRecordingConfiguration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const management = slim(delegate) + + management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + await settle() + management.handleFactoryReset() + + expect(updateRecordingActive.mock.calls).toEqual([ + [true], + [false], + ]) + expect(updateRecordingConfiguration).not.toHaveBeenCalled() + }) + + it('restores the operating mode, the sensors\' Status Active and recording Active, reading neither a stored configuration hash nor a selection', () => { + const delegate = new MockDelegate() + const updateRecordingActive = vi.spyOn(delegate, 'updateRecordingActive') + const updateRecordingConfiguration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const policy = new OperatingModePolicy() + const management = slim(delegate, policy) + const sensor = new Service.MotionSensor('', '') + + management.sensorServices.push(sensor) + management.deserialize({ + configurationHash: { algorithm: 'sha256', hash: 'a hash of the options the camera gave before' }, + selectedConfiguration: SELECTED_CONFIGURATION, + }, { + eventSnapshotsActive: false, + homeKitCameraActive: false, + periodicSnapshotsActive: true, + recordingActive: true, + recordingAudioActive: true, + }) + + expect(management.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + expect(management.recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive).value).toBe(Characteristic.RecordingAudioActive.ENABLE) + expect(management.operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive).value).toBe(Characteristic.EventSnapshotsActive.DISABLE) + expect(policy.homeKitCameraActive).toBe(false) + expect(sensor.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + expect(updateRecordingActive.mock.calls).toEqual([ + [true], + ]) + expect(updateRecordingConfiguration).not.toHaveBeenCalled() + expect(configurationCharacteristics(management.recordingManagementService)).toEqual([false, false, false, false]) + + // A state with no configuration hash, which no camera with the options writes, restores as well. + expect(() => management.deserialize({} as RecordingManagementState)).not.toThrow() + }) + }) + + describe('a recording over a data stream connection', () => { + beforeEach(() => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('answers the open, then sends each packet in chunks of 256 KiB labeled by position, numbered and sized as the hub reads them', async () => { + const packets = [ + packet(MAX_CHUNK + 1), + packet(MAX_CHUNK), + packet(100, true), + ] + const delegate = recordingDelegate(async function* () { + yield* packets + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const id = open(client) + + await settle() + + expect(client.written[1]).toEqual({ + header: { + id, + protocol: Protocols.DATA_SEND, + response: Topics.OPEN, + status: HDSStatus.SUCCESS, + }, + message: { status: HDSStatus.SUCCESS }, + }) + expect(chunks(client)).toEqual([ + { + metadata: { + dataChunkSequenceNumber: 1, + dataSequenceNumber: 1, + dataTotalSize: MAX_CHUNK + 1, + dataType: PacketDataType.MEDIA_INITIALIZATION, + isLastDataChunk: false, + }, + streamId: 1, + }, + { + endOfStream: false, + metadata: { + dataChunkSequenceNumber: 2, + dataSequenceNumber: 1, + dataType: PacketDataType.MEDIA_FRAGMENT, + isLastDataChunk: true, + }, + streamId: 1, + }, + { + endOfStream: false, + metadata: { + dataChunkSequenceNumber: 1, + dataSequenceNumber: 2, + dataTotalSize: MAX_CHUNK, + dataType: PacketDataType.MEDIA_FRAGMENT, + isLastDataChunk: true, + }, + streamId: 1, + }, + { + endOfStream: true, + metadata: { + dataChunkSequenceNumber: 1, + dataSequenceNumber: 3, + dataTotalSize: 100, + dataType: PacketDataType.MEDIA_FRAGMENT, + isLastDataChunk: true, + }, + streamId: 1, + }, + ]) + + const sent = dataEvents(client).map(({ packets: [{ data }] }) => data) + + expect(Buffer.concat(sent.slice(0, 2))).toEqual(packets[0].data) + expect(sent[2]).toEqual(packets[1].data) + expect(sent[3]).toEqual(packets[2].data) + }) + + it('sends each packet of a muxer\'s recording byte for byte on a camera without the capabilities block', async () => { + const packets = skeletonPackets() + const delegate = recordingDelegate(async function* () { + yield { data: packets[0], isLast: false } + yield { data: packets[1], isLast: false } + yield { data: packets[2], isLast: true } + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + expect(dataEvents(client).map(({ packets: [{ data }] }) => data)).toEqual(packets) + }) + + it('writes its own producer reference time box before each fragment, with a capability camera\'s box writing turned on', async () => { + const [muxed, first, muxedSecond] = skeletonPackets() + // The skeleton's packets without the muxer's own producer reference time boxes, as the library's recorder writes none. + const initialization = muxed.subarray(0, muxed.length - 32) + const second = muxedSecond.subarray(32) + const delegate = recordingDelegate(async function* () { + yield { data: initialization, isLast: false } + yield { data: first, isLast: false } + yield { data: second, isLast: true } + }) + const management = recordingCamera(delegate) + + // @ts-expect-error: private access + management.producerReferenceTime = true + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-12T00:00:00.000Z')) + + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + const sent = dataEvents(client).map(({ packets: [{ data }] }) => data as Buffer) + + expect(sent[0]).toEqual(initialization) + expect(sent[1].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f8000000000000000000000000000') + expect(sent[1].subarray(32)).toEqual(first) + expect(sent[2].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f800410666666000000000000f3d8') + expect(sent[2].subarray(32)).toEqual(second) + expect(chunks(client).map(({ metadata }) => metadata)).toEqual(sent.map((data, index) => ({ + dataChunkSequenceNumber: 1, + dataSequenceNumber: index + 1, + dataTotalSize: data.length, + dataType: index === 0 + ? PacketDataType.MEDIA_INITIALIZATION + : PacketDataType.MEDIA_FRAGMENT, + isLastDataChunk: true, + }))) + }) + + it('closes a recording as an unexpected failure at a fragment before any initialization segment, with a capability camera\'s box writing turned on', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const [, first] = skeletonPackets() + const delegate = recordingDelegate(async function* () { + yield { data: first, isLast: false } + }) + const management = recordingCamera(delegate) + + // @ts-expect-error: private access + management.producerReferenceTime = true + + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + expect(dataEvents(client)).toEqual([]) + expect(closeEvents(client)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 1 }, + ]) + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: Error: ' + + 'The recording yielded a media fragment before any initialization segment.'), + ], + ]) + }) + + it('sends nothing for an empty packet, which takes no sequence number, ends the stream at once at an empty last packet, and closes it as cancelled once the ' + + 'hub has left it open 12 seconds', async () => { + const delegate = recordingDelegate(async function* () { + yield packet(100) + yield packet(0) + yield packet(100) + yield packet(0, true) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + expect(chunks(client).map(({ endOfStream, metadata }) => ({ endOfStream, sequence: (metadata as { dataSequenceNumber: number }).dataSequenceNumber }))) + .toEqual([ + { endOfStream: false, sequence: 1 }, + { endOfStream: false, sequence: 2 }, + { endOfStream: true, sequence: 3 }, + ]) + + vi.advanceTimersByTime(12000) + + expect(closeEvents(client)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 1 }, + ]) + }) + + it('stamps and serves each packet with data on a stamping camera, an empty packet taking no sequence number and an empty last packet ending the stream ' + + 'at once with no data', async () => { + const [muxed, first, muxedSecond] = skeletonPackets() + // The skeleton's packets without the muxer's own producer reference time boxes, as the library's recorder writes none. + const initialization = muxed.subarray(0, muxed.length - 32) + const second = muxedSecond.subarray(32) + const delegate = recordingDelegate(async function* () { + yield { data: initialization, isLast: false } + yield { data: first, isLast: false } + yield packet(0) + yield { data: second, isLast: false } + yield packet(0, true) + }) + const { reporter } = problemsOf() + const management = recordingCamera(delegate, { + feed: new ServedRecordings({ reporter, sensorUUID: FIRST_VIDEO_SENSOR.uuid }), + reporter, + }) + const served = vi.spyOn(ServedRecording.prototype, 'add') + + // @ts-expect-error: private access + management.producerReferenceTime = true + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-11-12T00:00:00.000Z')) + + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + const sent = dataEvents(client).map(({ packets: [{ data }] }) => data as Buffer) + + expect(chunks(client).map(({ endOfStream, metadata }) => ({ endOfStream, sequence: (metadata as { dataSequenceNumber: number }).dataSequenceNumber }))) + .toEqual([ + { endOfStream: false, sequence: 1 }, + { endOfStream: false, sequence: 2 }, + { endOfStream: false, sequence: 3 }, + { endOfStream: true, sequence: 4 }, + ]) + expect(sent[1].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f8000000000000000000000000000') + expect(sent[1].subarray(32)).toEqual(first) + expect(sent[2].subarray(0, 32).toString('hex')).toBe('00000020707266740100001800000001ee9f800410666666000000000000f3d8') + expect(sent[2].subarray(32)).toEqual(second) + expect(sent[3]).toHaveLength(0) + expect(served.mock.calls.map(([written]) => written.bytes)).toEqual(sent) + }) + + it('tells the delegate of the hub\'s acknowledgement alone, aborts nothing and frees the camera', async () => { + const delegate = recordingDelegate(async function* () { + yield packet(100, true) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + acknowledge(client) + + expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1) + expect(delegate.closeRecordingStream).not.toHaveBeenCalled() + expect(signalOf(delegate).aborted).toBe(false) + + const next = open(client, 2) + + await settle() + + expect(answer(client, next).status).toBe(HDSStatus.SUCCESS) + }) + + it('ignores an acknowledgement naming another stream, after its loop and while it runs', async () => { + const finished = recordingDelegate(async function* () { + yield packet(100, true) + }) + const first = recordingCamera(finished) + const firstClient = await DataStreamClient.connect(first.dataStreamManagement) + + open(firstClient) + await settle() + acknowledge(firstClient, 99) + vi.advanceTimersByTime(12000) + + expect(finished.acknowledgeStream).not.toHaveBeenCalled() + expect(closeEvents(firstClient)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 1 }, + ]) + expect(finished.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.CANCELLED) + + const held = deferred() + const running = recordingDelegate(async function* () { + yield packet(100) + await held.promise + yield packet(100, true) + }) + const second = recordingCamera(running) + const secondClient = await DataStreamClient.connect(second.dataStreamManagement) + + open(secondClient) + await settle() + acknowledge(secondClient, 99) + held.resolve() + await settle() + + expect(running.acknowledgeStream).not.toHaveBeenCalled() + expect(signalOf(running).aborted).toBe(false) + expect(chunks(secondClient).map(({ endOfStream }) => endOfStream)).toEqual([false, true]) + }) + + it('stops a recording at the hub\'s close: the delegate told its reason while the camera is busy, its signal aborted and no packet sent after', async () => { + let reached = 0 + let released = false + const delegate = recordingDelegate(async function* (_streamId, signal) { + try { + yield packet(100) + await aborted(signal!) + reached++ + yield packet(100) + reached++ + yield packet(100, true) + } finally { + released = true + } + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const atCall: unknown[] = [] + + delegate.closeRecordingStream.mockImplementation(() => { + atCall.push({ aborted: signalOf(delegate).aborted, busy: recordingStreamOf(management) !== undefined }) + }) + + open(client) + await settle() + hubClose(client, 99, HDSProtocolSpecificErrorReason.TIMEOUT) + await settle() + + expect(delegate.closeRecordingStream).not.toHaveBeenCalled() + + hubClose(client, 1, HDSProtocolSpecificErrorReason.TIMEOUT) + await settle() + + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.TIMEOUT) + expect(atCall).toEqual([ + { aborted: true, busy: true }, + ]) + expect(released).toBe(true) + expect(reached).toBe(1) + expect(dataEvents(client)).toHaveLength(1) + expect(answer(client, open(client, 2)).status).toBe(HDSStatus.SUCCESS) + }) + + it('stops a recording when its connection closes: the delegate told with no reason while the camera is busy, its signal aborted', async () => { + const delegate = recordingDelegate(async function* (_streamId, signal) { + yield packet(100) + await aborted(signal!) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const other = await DataStreamClient.connect(management.dataStreamManagement) + const atCall: unknown[] = [] + + delegate.closeRecordingStream.mockImplementation(() => { + atCall.push({ aborted: signalOf(delegate).aborted, busy: recordingStreamOf(management) !== undefined }) + }) + + open(client) + await settle() + client.closeSocket() + await settle() + + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, undefined) + expect(atCall).toEqual([ + { aborted: true, busy: true }, + ]) + expect(answer(other, open(other)).status).toBe(HDSStatus.SUCCESS) + }) + + it('reports a delegate\'s throw at a stream\'s close as the library\'s failure on the channel of a camera whose management holds its reporter, and logs ' + + 'it where the management holds none', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { problems, reporter } = problemsOf() + const failure = new Error('The delegate failed to close the recording.') + // A recording that waits for its close, whose delegate throws as it is told of it. + const closing = (): RecordingDelegate => { + const delegate = recordingDelegate(async function* (_streamId, signal) { + await aborted(signal!) + }) + + delegate.closeRecordingStream.mockImplementation(() => { + throw failure + }) + + return delegate + } + const reporting = recordingCamera(closing(), { + feed: new ServedRecordings({ reporter, sensorUUID: FIRST_VIDEO_SENSOR.uuid }), + reporter, + }) + const legacy = recordingCamera(closing()) + const sentence = '[HDS 192.0.2.1] CameraRecordingDelegate failed to handle closing the stream 1: Error: The delegate failed to close the recording.' + + for (const management of [reporting, legacy]) { + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + } + + expect(problems.map(problem => ({ ...problem, sentence: problem.sentence.split('\n')[0] }))).toEqual([ + { + accessoryUUID: REPORTER_ACCESSORY_UUID, + error: failure, + kind: 'library-failure', + level: 'error', + sentence, + }, + ]) + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([sentence]) + }) + + it('closes a recording with not allowed at a write of HomeKit Camera Active off, the close sent before the delegate hears it', async () => { + const delegate = recordingDelegate(async function* (_streamId, signal) { + yield packet(100) + await aborted(signal!) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const atCall: unknown[] = [] + + delegate.closeRecordingStream.mockImplementation(() => { + atCall.push({ + busy: recordingStreamOf(management) !== undefined, + closes: closeEvents(client), + }) + }) + + open(client) + await settle() + management.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).setValue(Characteristic.HomeKitCameraActive.OFF) + + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.NOT_ALLOWED) + expect(atCall).toEqual([ + { + busy: true, + closes: [ + { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, streamId: 1 }, + ], + }, + ]) + }) + + it('closes a finished recording the hub does not acknowledge as cancelled 12 seconds after its loop, warning of one that ends without its last packet', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const marked = recordingDelegate(async function* () { + yield packet(100, true) + }) + const unmarked = recordingDelegate(async function* () { + yield packet(100) + }) + + for (const delegate of [marked, unmarked]) { + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + vi.advanceTimersByTime(11999) + + expect(closeEvents(client)).toEqual([]) + expect(delegate.closeRecordingStream).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + + expect(closeEvents(client)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 1 }, + ]) + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.CANCELLED) + expect(signalOf(delegate).aborted).toBe(false) + } + + expect(warn.mock.calls).toEqual([ + ['[HDS 192.0.2.1] Delegate finished streaming for 1 without setting RecordingPacket.isLast. Can\'t notify Controller about endOfStream!'], + ]) + }) + + it('logs a delegate still running 10 seconds after its recording closed, and not one that settles at its signal', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const held = deferred() + const ignoring = recordingDelegate(async function* () { + yield packet(100) + await held.promise + }) + const settling = recordingDelegate(async function* (_streamId, signal) { + yield packet(100) + await aborted(signal!) + }) + const first = recordingCamera(ignoring) + const firstClient = await DataStreamClient.connect(first.dataStreamManagement) + + open(firstClient) + await settle() + hubClose(firstClient, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + vi.advanceTimersByTime(9999) + + expect(error).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + + expect(error.mock.calls).toEqual([ + [ + '[HDS %s] Recording download stream %d is still awaiting generator although stream was closed 10s ago! ' + + 'This is a programming mistake by the camera implementation which prevents freeing up resources.', + '192.0.2.1', + 1, + ], + ]) + + held.resolve() + error.mockClear() + + const second = recordingCamera(settling) + const secondClient = await DataStreamClient.connect(second.dataStreamManagement) + + open(secondClient) + await settle() + hubClose(secondClient, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + vi.advanceTimersByTime(10000) + + expect(error).not.toHaveBeenCalled() + }) + + it('closes a recording whose delegate throws with the reason it names, as an unexpected failure, or at 12 seconds for a closed socket', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const throwing = (failure: Error): RecordingDelegate => recordingDelegate(async function* () { + yield packet(100) + throw failure + }) + const named = throwing(new HDSProtocolError(HDSProtocolSpecificErrorReason.TIMEOUT)) + const unexpected = throwing(new Error('The recording failed.')) + const closedSocket = throwing(new HDSConnectionError('The socket closed.', HDSConnectionErrorType.CLOSED_SOCKET)) + + for (const [delegate, reason] of [ + [named, HDSProtocolSpecificErrorReason.TIMEOUT], + [unexpected, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + ] as const) { + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + expect(closeEvents(client)).toEqual([ + { reason, streamId: 1 }, + ]) + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, reason) + } + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: Error: The recording failed.'), + ], + ]) + error.mockClear() + + const management = recordingCamera(closedSocket) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + vi.advanceTimersByTime(11999) + + expect(closeEvents(client)).toEqual([]) + expect(closedSocket.closeRecordingStream).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + + expect(closeEvents(client)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 1 }, + ]) + expect(closedSocket.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.CANCELLED) + expect(error).not.toHaveBeenCalled() + expect(warn).not.toHaveBeenCalled() + }) + + it('leaves a running recording to its socket\'s close at destroy, telling the delegate nothing until then and reading no later frame', async () => { + const delegate = recordingDelegate(async function* (_streamId, signal) { + yield packet(100) + await aborted(signal!) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + management.destroy() + + expect(client.socket.end).toHaveBeenCalledTimes(1) + expect(delegate.closeRecordingStream).not.toHaveBeenCalled() + + acknowledge(client) + + expect(delegate.acknowledgeStream).not.toHaveBeenCalled() + + client.closeSocket() + + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, undefined) + }) + + it('keeps a running recording through a factory reset', async () => { + const held = deferred() + const delegate = recordingDelegate(async function* () { + yield packet(100) + await held.promise + yield packet(100, true) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + management.handleFactoryReset() + held.resolve() + await settle() + + expect(dataEvents(client)).toHaveLength(2) + expect(closeEvents(client)).toEqual([]) + expect(delegate.closeRecordingStream).not.toHaveBeenCalled() + }) + + it('writes every chunk of a packet to a socket that reports a full buffer before it pulls the next packet', async () => { + const writesAtPull: number[] = [] + let client: DataStreamClient | undefined + const delegate = recordingDelegate(async function* () { + yield packet(3 * MAX_CHUNK) + writesAtPull.push(client!.socket.write.mock.calls.length) + yield packet(100, true) + }) + const management = recordingCamera(delegate) + + client = await DataStreamClient.connect(management.dataStreamManagement) + client.socket.write.mockReturnValue(false) + + const before = client.socket.write.mock.calls.length + + open(client) + await settle() + + // The open's answer, then the packet's three chunks. + expect(writesAtPull).toEqual([before + 4]) + }) + + it('releases the delegate\'s recording at the break that follows its last packet', async () => { + let released = false + const delegate = recordingDelegate(async function* () { + try { + yield packet(100, true) + yield packet(100) + } finally { + released = true + } + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + expect(released).toBe(true) + }) + + it('answers each open on a running recording\'s own connection by the open\'s checks, the recording running on', async () => { + const delegate = recordingDelegate(async function* (_streamId, signal) { + yield packet(100) + await aborted(signal!) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + const second = open(client, 2) + const snapshot = open(client, 3, { type: 'ipcamera.snapshot' }) + + management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.INACTIVE) + await settle() + + const switchedOff = open(client, 4) + + expect([second, snapshot, switchedOff].map(id => answer(client, id))).toEqual([ + { reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + ]) + expect(recordingStreamOf(management)).toBeDefined() + expect(delegate.closeRecordingStream).not.toHaveBeenCalled() + }) + + it('refuses an open as not allowed unless recording is active and the camera is on, and lets one through with both', async () => { + const answers: unknown[] = [] + + for (const recordingActive of [false, true]) { + for (const cameraActive of [false, true]) { + const management = recordingCamera(recordingDelegate(async function* () { + yield packet(100, true) + })) + + management.recordingManagementService.getCharacteristic(Characteristic.Active) + .setValue(recordingActive ? Characteristic.Active.ACTIVE : Characteristic.Active.INACTIVE) + management.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive) + .setValue(cameraActive ? Characteristic.HomeKitCameraActive.ON : Characteristic.HomeKitCameraActive.OFF) + + const client = await DataStreamClient.connect(management.dataStreamManagement) + + answers.push(answer(client, open(client))) + } + } + + const notAllowed = { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR } + + expect(answers).toEqual([ + notAllowed, + notAllowed, + notAllowed, + { reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }, + ]) + }) + + it('refuses an open by the first check it fails: target, recording allowed, busy, configuration, a later check failing too where it can', async () => { + const delegate = recordingDelegate(async function* (_streamId, signal) { + yield packet(100) + await aborted(signal!) + }) + const management = recordingCamera(delegate) + const recording = await DataStreamClient.connect(management.dataStreamManagement) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const refused = (overrides: Record = {}): { reason?: number, status?: number } => answer(client, open(client, 2, overrides)) + const specificError = (reason: HDSProtocolSpecificErrorReason): { reason: number, status: number } => ({ + reason, + status: HDSStatus.PROTOCOL_SPECIFIC_ERROR, + }) + + open(recording) + await settle() + + // A factory reset clears the configuration and switches recording off, and leaves the recording running. + management.handleFactoryReset() + + expect(refused({ target: 'accessory' })).toEqual(specificError(HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE)) + expect(refused()).toEqual(specificError(HDSProtocolSpecificErrorReason.NOT_ALLOWED)) + + management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + await settle() + + expect(refused()).toEqual(specificError(HDSProtocolSpecificErrorReason.BUSY)) + + // HomeKit Camera Active off closes the running recording. + management.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).setValue(Characteristic.HomeKitCameraActive.OFF) + + expect(refused()).toEqual(specificError(HDSProtocolSpecificErrorReason.NOT_ALLOWED)) + + management.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).setValue(Characteristic.HomeKitCameraActive.ON) + + expect(refused()).toEqual(specificError(HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION)) + }) + + it('lets a stream go from its route and the camera at a delegate\'s synchronous throw, and a route go from the management at its connection\'s close', async () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + + const delegate = recordingDelegate(() => { + throw new Error('The recording could not start.') + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + // @ts-expect-error: private access + const routes: Map }> = management.routes + + expect(routes.get(client.connection)?.streams.size).toBe(0) + expect(recordingStreamOf(management)).toBeUndefined() + + client.closeSocket() + + expect(routes.size).toBe(0) + }) + + it('serves a second recording on one connection after the first, its acknowledgement its own', async () => { + const delegate = recordingDelegate(async function* () { + yield packet(100, true) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + acknowledge(client) + + expect(answer(client, open(client, 9, { type: 'ipcamera.snapshot' }))).toEqual({ + reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, + status: HDSStatus.PROTOCOL_SPECIFIC_ERROR, + }) + + open(client, 2) + await settle() + acknowledge(client, 2) + vi.advanceTimersByTime(12000) + + expect(delegate.acknowledgeStream.mock.calls).toEqual([ + [1], + [2], + ]) + expect(closeEvents(client)).toEqual([]) + }) + + it('closes a recording as an unexpected failure when its release at the last packet throws, after the end was sent', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const delegate = recordingDelegate(async function* () { + try { + yield packet(100, true) + } finally { + // eslint-disable-next-line no-unsafe-finally + throw new Error('The recording could not be released.') + } + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + const topics = client.written.slice(2).map(({ header, message }) => [header.event, message.endOfStream ?? message.reason]) + + expect(topics).toEqual([ + [Topics.DATA, true], + [Topics.CLOSE, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE], + ]) + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: Error: The recording could not be released.'), + ], + ]) + }) + + it('keeps the error of a recording\'s packet over the error of its release', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const delegate = recordingDelegate(async function* () { + try { + yield undefined as unknown as RecordingPacket + } finally { + // eslint-disable-next-line no-unsafe-finally + throw new Error('The recording could not be released.') + } + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: TypeError: '), + ], + ]) + expect(error.mock.calls[0][0]).not.toContain('The recording could not be released.') + expect(closeEvents(client)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 1 }, + ]) + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE) + }) + + it('streams a synchronous recording, an array or a generator of promised packets, as it streams a generator', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const array = recordingDelegate(() => [ + packet(100), + packet(100, true), + ] as unknown as AsyncGenerator) + const promised = recordingDelegate(function* () { + yield Promise.resolve(packet(100)) + yield Promise.resolve(packet(100, true)) + } as unknown as RecordingRequest) + + for (const delegate of [array, promised]) { + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + acknowledge(client) + + expect(chunks(client).map(({ endOfStream, metadata }) => [(metadata as { dataSequenceNumber: number }).dataSequenceNumber, endOfStream])) + .toEqual([ + [1, false], + [2, true], + ]) + expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1) + } + + expect(error).not.toHaveBeenCalled() + expect(warn).not.toHaveBeenCalled() + }) + }) + + describe('a recording\'s timers', () => { + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('leaves no timer holding the process once a recording closes at the hub\'s acknowledgement, the hub\'s close or the connection\'s close', async () => { + const finished = recordingDelegate(async function* () { + yield packet(100) + yield packet(100, true) + }) + // Parked on its signal: each close comes while the loop runs and arms the watchdog the loop's exit clears. + const parked = recordingDelegate(async function* (_streamId, signal) { + yield packet(100) + await aborted(signal!) + }) + const closes: [RecordingDelegate, (client: DataStreamClient) => void][] = [ + [ + finished, + client => acknowledge(client), + ], + [ + parked, + client => hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL), + ], + [ + parked, + client => client.closeSocket(), + ], + ] + + // The fake clock, installed after the connect, counts each timer armed through the global setTimeout from then on, referenced or not, and none armed + // through Node's own timers, as the runner's are. The count at the close reads the recording's timers alone. + for (const [delegate, close] of closes) { + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + + const before = vi.getTimerCount() + + open(client) + await settle() + close(client) + await settle() + + expect(vi.getTimerCount()).toBe(before) + vi.useRealTimers() + } + }) + }) + + describe('a recording\'s failures that reach the process', () => { + // The listener collects each rejection no handler takes during a row, any of which would end a Homebridge process, and Vitest reports none of them while + // it stands. + const unhandled: unknown[] = [] + const collect = (reason: unknown): void => { + unhandled.push(reason) + } + + // The debug lines of the data stream server, whose dispatch reports a handler that throws, and of the recording management, which reports a failed + // return of a closed recording. + const logged: string[] = [] + let enabled: string + let log: (...args: unknown[]) => void + + beforeEach(() => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + unhandled.length = 0 + logged.length = 0 + process.on('unhandledRejection', collect) + enabled = createDebug.disable() + log = (createDebug as unknown as { log: typeof log }).log; + (createDebug as unknown as { log: typeof log }).log = (...args: unknown[]) => { + logged.push(format(...args)) + } + createDebug.enable('HAP-NodeJS:DataStream:Server,HAP-NodeJS:Camera:RecordingManagement') + }) + + afterEach(() => { + (createDebug as unknown as { log: typeof log }).log = log + createDebug.disable() + + if (enabled) { + createDebug.enable(enabled) + } + + process.off('unhandledRejection', collect) + vi.useRealTimers() + vi.restoreAllMocks() + }) + + // An answer whose iterator is an object of its own with no return: it hands one packet and then waits for the row. + function iterableWithoutReturn(held: Promise): AsyncGenerator { + return { + [Symbol.asyncIterator]: () => { + let sent = false + + return { + next: async (): Promise> => { + if (!sent) { + sent = true + + return { + done: false, + value: packet(100), + } + } + + await held + + return { done: true, value: undefined } + }, + } + }, + } as unknown as AsyncGenerator + } + + // An answer that is its own iterator, handing one packet and then waiting, with the return the row gives it. + function selfIterator(onReturn: () => unknown): AsyncGenerator { + let sent = false + const iterator = { + [Symbol.asyncIterator]: () => iterator, + next: async (): Promise> => { + if (!sent) { + sent = true + + return { + done: false, + value: packet(100), + } + } + + return new Promise(() => undefined) + }, + return: onReturn, + } + + return iterator as unknown as AsyncGenerator + } + + it('ends a stream whose open\'s answer finds its connection closing, with no close event, nothing told to the delegate and nothing unhandled', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const delegate = recordingDelegate(async function* () { + yield packet(100, true) + }) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const other = await DataStreamClient.connect(management.dataStreamManagement) + + management.dataStreamManagement.onEventMessage('test', 'shut', connection => connection.close()) + client.send(client.eventFrame('test', 'shut'), client.requestFrame(Protocols.DATA_SEND, Topics.OPEN, OPEN_RECORDING)) + await settle() + + expect(unhandled).toEqual([]) + expect(delegate.handleRecordingStreamRequest).not.toHaveBeenCalled() + expect(recordingStreamOf(management)).toBeUndefined() + + client.closeSocket() + + expect(closeEvents(client)).toEqual([]) + expect(delegate.closeRecordingStream).not.toHaveBeenCalled() + expect(answer(other, open(other)).status).toBe(HDSStatus.SUCCESS) + expect(warn).not.toHaveBeenCalled() + expect(error).not.toHaveBeenCalled() + }) + + describe('a recording whose answer is not a generator', () => { + it('frees the camera with the delegate told at the hub\'s close, the library\'s close and the connection\'s close of an iterator with no return', async () => { + const held = deferred() + const delegate = recordingDelegate(() => iterableWithoutReturn(held.promise)) + const hub = recordingCamera(delegate) + const hubClient = await DataStreamClient.connect(hub.dataStreamManagement) + + open(hubClient) + await settle() + hubClose(hubClient, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + expect(answer(hubClient, open(hubClient, 2)).status).toBe(HDSStatus.SUCCESS) + + const library = recordingCamera(delegate) + const libraryClient = await DataStreamClient.connect(library.dataStreamManagement) + + open(libraryClient) + await settle() + + await expect(library.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).handleSetRequest(Characteristic.HomeKitCameraActive.OFF)) + .resolves + .toBeUndefined() + expect(closeEvents(libraryClient)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, streamId: 1 }, + ]) + expect(recordingStreamOf(library)).toBeUndefined() + + const connection = recordingCamera(delegate) + const connectionClient = await DataStreamClient.connect(connection.dataStreamManagement) + const other = await DataStreamClient.connect(connection.dataStreamManagement) + + open(connectionClient) + await settle() + + expect(() => connectionClient.closeSocket()).not.toThrow() + expect(answer(other, open(other)).status).toBe(HDSStatus.SUCCESS) + expect(delegate.closeRecordingStream.mock.calls).toEqual([ + [1, HDSProtocolSpecificErrorReason.NORMAL], + [1, HDSProtocolSpecificErrorReason.NOT_ALLOWED], + [1, undefined], + ]) + expect(logged.join('\n')).not.toContain('TypeError') + expect(unhandled).toEqual([]) + }) + + it('frees the camera with the delegate told at an iterator whose next rejects and at a delegate answering a promise, closing as unexpected', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const rejecting = recordingDelegate(() => ({ + [Symbol.asyncIterator]: () => ({ + next: async (): Promise> => { + throw new Error('The recording failed.') + }, + }), + }) as unknown as AsyncGenerator) + const promising = recordingDelegate((async () => packet(100, true)) as unknown as RecordingRequest) + + for (const delegate of [rejecting, promising]) { + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + expect(closeEvents(client)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 1 }, + ]) + expect(recordingStreamOf(management)).toBeUndefined() + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE) + } + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: Error: The recording failed.'), + ], + [ + expect.stringContaining('[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: TypeError: '), + ], + ]) + expect(unhandled).toEqual([]) + }) + + it('frees the camera with the delegate told at the hub\'s close of an iterator whose return throws, answers a plain object or rejects', async () => { + const throwing = recordingDelegate(() => selfIterator(() => { + throw new Error('The recording could not stop.') + })) + const plain = recordingDelegate(() => selfIterator(() => ({ done: true, value: undefined }))) + const rejecting = recordingDelegate(() => selfIterator(async () => { + throw new Error('The recording could not stop.') + })) + + for (const [delegate, failed] of [ + [throwing, true], + [plain, false], + [rejecting, true], + ] as const) { + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + logged.length = 0 + open(client) + await settle() + hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.NORMAL) + expect(answer(client, open(client, 2)).status).toBe(HDSStatus.SUCCESS) + expect(logged.join('\n').includes('Error while closing the recording of stream 1: Error: The recording could not stop.')).toBe(failed) + } + + expect(unhandled).toEqual([]) + }) + + it('takes one iterator from a recording that makes a fresh one at each call, and asks that one to stop at the hub\'s close', async () => { + let made = 0 + let returned = 0 + const delegate = recordingDelegate(() => ({ + [Symbol.asyncIterator]: () => { + let sent = false + + made++ + + return { + next: async (): Promise> => { + if (!sent) { + sent = true + + return { + done: false, + value: packet(100), + } + } + + return new Promise(() => undefined) + }, + return: async (): Promise> => { + returned++ + + return { done: true, value: undefined } + }, + } + }, + }) as unknown as AsyncGenerator) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + expect(made).toBe(1) + expect(returned).toBe(1) + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.NORMAL) + expect(unhandled).toEqual([]) + }) + + it('streams an answer whose async iterator method reads undefined or null by its iterator, and closes at a non-object with the library\'s sentence', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + + for (const method of [undefined, null]) { + const synchronous = recordingDelegate(() => ({ + [Symbol.asyncIterator]: method, + * [Symbol.iterator]() { + yield packet(100) + yield packet(100, true) + }, + }) as unknown as AsyncGenerator) + const management = recordingCamera(synchronous) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + acknowledge(client) + + expect(chunks(client).map(({ endOfStream }) => endOfStream)).toEqual([false, true]) + expect(synchronous.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1) + } + + for (const value of [undefined, 'a recording']) { + const delegate = recordingDelegate(() => value as unknown as AsyncGenerator) + const refused = recordingCamera(delegate) + const refusedClient = await DataStreamClient.connect(refused.dataStreamManagement) + + open(refusedClient) + await settle() + + expect(closeEvents(refusedClient)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 1 }, + ]) + expect(recordingStreamOf(refused)).toBeUndefined() + expect(delegate.closeRecordingStream).toHaveBeenCalledExactlyOnceWith(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE) + } + + const sentence = '[HDS 192.0.2.1] Encountered unexpected error for recording stream 1: TypeError: ' + + 'The recording delegate answered a value that is neither an async iterable nor an iterable.' + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining(sentence), + ], + [ + expect.stringContaining(sentence), + ], + ]) + expect(unhandled).toEqual([]) + }) + + // The delegate is typed against the interface with no cast, and the spec typecheck reads whether the interface takes an async iterable that is no + // generator. + it('streams a recording a delegate answers as a readable stream, an async iterable that is no generator', async () => { + const delegate = recordingDelegate(() => new ReadableStream({ + start(controller) { + controller.enqueue(packet(100)) + controller.enqueue(packet(100, true)) + controller.close() + }, + })) + const management = recordingCamera(delegate) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + acknowledge(client) + + expect(chunks(client).map(({ endOfStream }) => endOfStream)).toEqual([false, true]) + expect(delegate.acknowledgeStream).toHaveBeenCalledExactlyOnceWith(1) + expect(recordingStreamOf(management)).toBeUndefined() + expect(unhandled).toEqual([]) + }) + }) + }) + + describe('a snapshot over a data stream connection', () => { + const PICTURE = crypto.randomBytes(1000) + + // The cameras a row builds, removed after it. No stream or policy outlives its row. + const cameras: CameraController[] = [] + + beforeEach(() => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + }) + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + + vi.restoreAllMocks() + vi.useRealTimers() + }) + + type SnapshotHandler = CameraStreamingDelegate['handleSnapshotRequest'] + + type SnapshotDelegate = RecordingDelegate & { handleSnapshotRequest: Mock } + + type SnapshotFunction = (request: CameraSnapshotRequest, signal: AbortSignal) => Promise + + // The calls of a camera's recording delegate a row reads, each a spy. + type RecordingCalls = { [Method in 'acknowledgeStream' | 'closeRecordingStream' | 'handleRecordingStreamRequest']: MockInstance } + + /* A recording camera, handed a published context, its recording switched on and its services kept, whose snapshots are answered with the row's + * picture, each call a spy. With the capabilities block the block's snapshot function answers them, the camera keeping the legacy delegate its fixture + * gives, and it records from its camera buffer, whose recorded tier holds a keyframe so its recorder serves a recording. A legacy camera, when the row + * asks for one, answers them through its delegate's handler and records through that delegate, whose recording yields an initialization segment and + * then waits on its signal. The delegate is handed to no camera with the block, and the function to no legacy camera. + */ + function snapshotCamera(capabilities = true, picture = PICTURE): { + camera: CameraController + delegate: SnapshotDelegate + management: RecordingManagement + map: CameraControllerServiceMap + recording: RecordingCalls + snapshot: Mock + } { + const delegate: SnapshotDelegate = Object.assign(recordingDelegate(async function* (_streamId, signal) { + yield { data: skeletonPackets()[0], isLast: false } + await aborted(signal!) + }), { + handleSnapshotRequest: vi.fn((_request, callback) => callback(undefined, picture)), + }) + const snapshot = vi.fn(async () => picture) + const buffered = bufferCamera({ prebuffer: 0 }) + const camera = new CameraController(capabilities + ? { + ...buffered.options, + cameraCapabilities: { ...buffered.options.cameraCapabilities, snapshot }, + } + : createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + cameras.push(camera) + + const map = camera.constructServices() + + camera.configureServices() + handPublishedContext(camera) + + const management = camera.recordingManagement! + + if (!capabilities) { + management.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + + return { + camera, + delegate, + management, + map, + recording: delegate, + snapshot, + } + } + + const recorder = management.delegate as BufferRecorder + + management.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + buffered.stream().write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + frames(buffered.stream(), 0, 1) + + return { + camera, + delegate, + management, + map, + recording: { + acknowledgeStream: vi.spyOn(recorder, 'acknowledgeStream'), + closeRecordingStream: vi.spyOn(recorder, 'closeRecordingStream'), + handleRecordingStreamRequest: vi.spyOn(recorder, 'handleRecordingStreamRequest'), + }, + snapshot, + } + } + + function openSnapshot(client: DataStreamClient, streamId = 2, metadata: Record = { imageHeight: 360, imageWidth: 640, reason: 1 }): number { + return client.request(Protocols.DATA_SEND, Topics.OPEN, { + metadata, + reason: 'snapshot', + streamId, + target: 'controller', + type: 'ipcamera.snapshot', + }) + } + + function streamEvents(client: DataStreamClient, topic: string, streamId = 2): Record[] { + return client.events(Protocols.DATA_SEND, topic).filter(event => event.streamId === streamId) + } + + it('waits for the hub\'s acknowledgement of a sent snapshot on a timer that keeps no process alive', async () => { + const { management } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + const timers = vi.spyOn(globalThis, 'setTimeout') + + openSnapshot(client) + await settle() + + // The wait is the 12 second timer the sent snapshot armed, read through the handle setTimeout answered. + const wait = timers.mock.calls.findLastIndex(([, delay]) => delay === 12000) + + expect(streamEvents(client, Topics.DATA)).toHaveLength(1) + expect(wait).toBeGreaterThanOrEqual(0) + expect((timers.mock.results[wait].value as ReturnType).hasRef()).toBe(false) + }) + + it('answers a snapshot open with one data event carrying no data type while a recording runs on the same connection', async () => { + const { management, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + const id = openSnapshot(client) + + await settle() + + expect(answer(client, id)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }) + expect(snapshot).toHaveBeenCalledExactlyOnceWith({ + height: 360, + keyframe: expect.objectContaining({ height: 36, width: 64 }), + reason: ResourceRequestReason.EVENT, + sensorUUID: FIRST_VIDEO_SENSOR.uuid.toLowerCase(), + width: 640, + }, expect.any(AbortSignal)) + expect(streamEvents(client, Topics.DATA)).toEqual([ + { + endOfStream: true, + packets: [ + { + data: PICTURE, + metadata: { + dataChunkSequenceNumber: 1, + dataSequenceNumber: 1, + dataTotalSize: PICTURE.length, + isLastDataChunk: true, + }, + }, + ], + streamId: 2, + }, + ]) + expect(recordingStreamOf(management)).toBeDefined() + }) + + it('sends a picture above 256 KiB in chunks of one data sequence, the last alone ending it', async () => { + const picture = crypto.randomBytes(MAX_CHUNK + 100) + const { management } = snapshotCamera(true, picture) + const client = await DataStreamClient.connect(management.dataStreamManagement) + + openSnapshot(client) + await settle() + + expect(streamEvents(client, Topics.DATA).map(({ endOfStream, packets: [{ data, metadata }] }) => ({ endOfStream, length: data.length, metadata }))).toEqual([ + { + endOfStream: undefined, + length: MAX_CHUNK, + metadata: { + dataChunkSequenceNumber: 1, + dataSequenceNumber: 1, + dataTotalSize: picture.length, + isLastDataChunk: false, + }, + }, + { + endOfStream: true, + length: 100, + metadata: { dataChunkSequenceNumber: 2, dataSequenceNumber: 1, isLastDataChunk: true }, + }, + ]) + }) + + it('serves a snapshot while the global service allows streaming, and refuses one while its Streaming Enabled reads off', async () => { + const { management, map, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + + openSnapshot(client) + await settle() + + expect(streamEvents(client, Topics.DATA)).toHaveLength(1) + + map['cameraCapabilities:globalOperatingMode']!.updateCharacteristic(Characteristic.StreamingEnabled, false) + + const refused = openSnapshot(client, 3) + + await settle() + + expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(streamEvents(client, Topics.DATA, 3)).toEqual([]) + expect(snapshot).toHaveBeenCalledTimes(1) + }) + + it('refuses a snapshot of a camera out of service as busy over the data stream and with the communication failure over the resource request, ' + + 'calling no snapshot function and writing why to the debug log', async () => { + const { camera, management, snapshot } = snapshotCamera() + // The capture begins after the camera's setup, and it reads every line the channel writes from there on. + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + const accessoryInformation = new Service.AccessoryInformation() as AccessoryInformation + + // The camera's accessory is unpublished: its context reads not published, under the name the data stream's refusal reads. + accessoryInformation.setCharacteristic(Characteristic.Name, 'Front Door') + camera.handleAccessoryContext({ + accessoryInformation, + accessoryUUID: 'b1b2c3d4-0000-4000-8000-000000000002', + published: false, + username: undefined, + }) + + const client = await DataStreamClient.connect(management.dataStreamManagement) + const refused = openSnapshot(client) + + await settle() + + expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(streamEvents(client, Topics.DATA)).toEqual([]) + await expect(camera.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(snapshot).not.toHaveBeenCalled() + expect(lines).toEqual([ + '[Front Door] Rejecting snapshot as the camera is out of service.', + '[Front Door] Rejecting snapshot as the camera is out of service.', + ]) + }) + + it('refuses a snapshot of a camera whose source is stated away as busy over the data stream and with the communication failure over the resource ' + + 'request, calling no snapshot function, and refuses its recording in the answer to the hub\'s open as busy, raising no alert and telling of no ' + + 'recording, as it does for a camera out of service', async () => { + const { camera, management, snapshot } = snapshotCamera() + // The capture begins after the camera's setup, and it reads every line the channel writes from there on. + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + const told: string[] = [] + const problems = onCameraProblem(NUMBERED_ACCESSORY_UUID, ({ kind }) => told.push(kind)) + + onTestFinished(() => { + problems[Symbol.dispose]() + }) + camera.on('recording-started', () => told.push('recording-started')) + camera.on('recording-ended', () => told.push('recording-ended')) + camera.updateSourceState('away') + + const client = await DataStreamClient.connect(management.dataStreamManagement) + const refused = openSnapshot(client) + const recordingRefused = open(client) + + await settle() + + expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + await expect(camera.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(snapshot).not.toHaveBeenCalled() + expect(streamEvents(client, Topics.DATA, 2)).toEqual([]) + expect(answer(client, recordingRefused)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(streamEvents(client, Topics.DATA, 1)).toEqual([]) + expect(told).toEqual([]) + expect(lines.map(line => line.slice(line.indexOf('] ') + 2))).toEqual([ + 'Rejecting snapshot as the camera is out of service.', + 'Rejecting snapshot as the camera is out of service.', + ]) + }) + + it('hands the snapshot function a request\'s reason 0 as periodic, 1 as an event and any other value as none', async () => { + const { management, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + + for (const [streamId, reason] of [ + [2, 0], + [3, 1], + [4, 7], + ]) { + openSnapshot(client, streamId, { imageHeight: 720, imageWidth: 1280, reason }) + } + + await settle() + + expect(snapshot.mock.calls.map(([{ height, reason, width }]) => ({ height, reason, width }))).toEqual([ + { height: 720, reason: ResourceRequestReason.PERIODIC, width: 1280 }, + { height: 720, reason: ResourceRequestReason.EVENT, width: 1280 }, + { height: 720, reason: undefined, width: 1280 }, + ]) + }) + + it('ends a snapshot at the hub\'s ack, sending nothing more, and closes one the hub leaves unacknowledged as cancelled twelve seconds after its send', async () => { + const { management } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + + openSnapshot(client) + openSnapshot(client, 3) + await settle() + client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId: 2 }) + await vi.advanceTimersByTimeAsync(11999) + + expect(client.events(Protocols.DATA_SEND, Topics.CLOSE)).toEqual([]) + + await vi.advanceTimersByTimeAsync(1) + + expect(client.events(Protocols.DATA_SEND, Topics.CLOSE)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 3 }, + ]) + }) + + it('closes a snapshot whose function rejects as an unexpected failure, sending no picture and logging the rejection once', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { management, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + + snapshot.mockRejectedValue(new Error('The camera has no picture.')) + openSnapshot(client) + await settle() + + expect(streamEvents(client, Topics.DATA)).toEqual([]) + expect(streamEvents(client, Topics.CLOSE)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 2 }, + ]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('The snapshot function failed: Error: The camera has no picture.'), + ], + ]) + }) + + it.each([ + [ + 'no size', + { reason: 1 }, + ], + [ + 'a width of zero', + { imageHeight: 360, imageWidth: 0, reason: 1 }, + ], + [ + 'a negative height', + { imageHeight: -360, imageWidth: 640, reason: 1 }, + ], + [ + 'a fractional width', + { imageHeight: 360, imageWidth: 640.5, reason: 1 }, + ], + [ + 'a height that is no number', + { imageHeight: 'tall', imageWidth: 640, reason: 1 }, + ], + ])('refuses a snapshot open naming %s as an unexpected failure, joining no stream and fetching nothing', async (_name, metadata) => { + const { management, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + const refused = openSnapshot(client, 2, metadata) + + await settle() + + expect(answer(client, refused)).toEqual({ reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(snapshot).not.toHaveBeenCalled() + expect(streamEvents(client, Topics.DATA)).toEqual([]) + + // The refused open left no stream under its ID. An open naming the same ID with a valid size is served. + const served = openSnapshot(client) + + await settle() + + expect(answer(client, served)).toEqual({ reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }) + }) + + it('closes a snapshot whose function answers an empty picture as an unexpected failure, naming the camera in its error', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { camera, management } = snapshotCamera(true, Buffer.alloc(0)) + const accessoryInformation = new Service.AccessoryInformation() as AccessoryInformation + + accessoryInformation.setCharacteristic(Characteristic.Name, 'Front Door') + camera.handleAccessoryContext({ + accessoryInformation, + accessoryUUID: 'b1b2c3d4-0000-4000-8000-000000000002', + published: true, + username: undefined, + }) + + const client = await DataStreamClient.connect(management.dataStreamManagement) + + openSnapshot(client) + await settle() + + expect(streamEvents(client, Topics.DATA)).toEqual([]) + expect(streamEvents(client, Topics.CLOSE)).toEqual([ + { reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, streamId: 2 }, + ]) + expect(error.mock.calls).toEqual([ + ['[Front Door] The snapshot function answered no picture, and the snapshot failed.'], + ]) + }) + + it('refuses a legacy camera\'s snapshot open as an unexpected failure, a type it does not serve, fetching nothing', async () => { + const { delegate, management } = snapshotCamera(false) + const client = await DataStreamClient.connect(management.dataStreamManagement) + const id = openSnapshot(client) + + await settle() + + expect(answer(client, id)).toEqual({ reason: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(delegate.handleSnapshotRequest).not.toHaveBeenCalled() + }) + + it('aborts a pending snapshot function\'s signal at the hub\'s close, the connection\'s close or the destroy, which closes it as cancelled, and ' + + 'discards the picture arriving after, sending none', async () => { + for (const close of ['hub', 'connection', 'destroy'] as const) { + const { management, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + const answered = deferred() + + snapshot.mockImplementation(async () => await answered.promise) + openSnapshot(client) + await settle() + + const [[, signal]] = snapshot.mock.calls + const closers = { + connection: () => client.closeSocket(), + destroy: () => management.destroy(), + hub: () => hubClose(client, 2, HDSProtocolSpecificErrorReason.NORMAL), + } + + expect(signal.aborted).toBe(false) + + closers[close]() + await settle() + + expect(signal.aborted).toBe(true) + + answered.resolve(PICTURE) + await settle() + + expect(streamEvents(client, Topics.DATA)).toEqual([]) + expect(streamEvents(client, Topics.CLOSE)).toEqual(close === 'destroy' + ? [ + { reason: HDSProtocolSpecificErrorReason.CANCELLED, streamId: 2 }, + ] + : []) + } + }) + + it('keeps a pending snapshot function\'s signal unaborted and its stream open through a factory reset and then its source stated away, and aborts it ' + + 'at the hub\'s close, logging none of its later rejection and leaving the camera no pending call and no timer', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { camera, management, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + const answered = deferred() + + snapshot.mockImplementation(async () => await answered.promise) + openSnapshot(client) + await settle() + + const [[, signal]] = snapshot.mock.calls + + camera.handleFactoryReset() + await settle() + + expect(signal.aborted).toBe(false) + // @ts-expect-error: private access + expect(management.snapshotStreams.size).toBe(1) + + camera.updateSourceState('away') + await settle() + + expect(signal.aborted).toBe(false) + // @ts-expect-error: private access + expect(management.snapshotStreams.size).toBe(1) + + hubClose(client, 2, HDSProtocolSpecificErrorReason.NORMAL) + await settle() + + expect(signal.aborted).toBe(true) + + answered.reject(new Error('The camera answered after the hub had gone.')) + await settle() + + expect(error).not.toHaveBeenCalled() + // @ts-expect-error: private access + expect(camera.snapshotCalls.size).toBe(0) + expect(vi.getTimerCount()).toBe(0) + }) + + it('keeps an answered snapshot function\'s signal unaborted through the close of its stream after the picture, by the hub\'s ack, the hub\'s close ' + + 'or the twelve-second wait', async () => { + for (const close of ['ack', 'hub', 'wait'] as const) { + const { management, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + + openSnapshot(client) + await settle() + + const [[, signal]] = snapshot.mock.calls + const closers = { + ack: async () => client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId: 2 }), + hub: async () => hubClose(client, 2, HDSProtocolSpecificErrorReason.NORMAL), + wait: async () => await vi.advanceTimersByTimeAsync(12000), + } + + expect(streamEvents(client, Topics.DATA)).toHaveLength(1) + + await closers[close]() + await settle() + + // @ts-expect-error: private access + expect(management.snapshotStreams.size).toBe(0) + expect(signal.aborted).toBe(false) + } + }) + + // An ack ends the recording a later close would name, which is why the ack and the close each reach it in a case of their own. + it.each([ + { + called: 'acknowledgeStream' as const, + hub: (client: DataStreamClient): void => acknowledge(client), + kind: 'ack', + with: [1], + }, + { + called: 'closeRecordingStream' as const, + hub: (client: DataStreamClient): void => hubClose(client, 1, HDSProtocolSpecificErrorReason.NORMAL), + kind: 'close', + with: [1, HDSProtocolSpecificErrorReason.NORMAL], + }, + ])('refuses as busy a snapshot open naming the running recording\'s stream, whose $kind still reaches the recording', async ({ called, hub, with: args }) => { + const { management, recording, snapshot } = snapshotCamera() + const client = await DataStreamClient.connect(management.dataStreamManagement) + + open(client) + await settle() + + const id = openSnapshot(client, 1) + + await settle() + + expect(answer(client, id)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(snapshot).not.toHaveBeenCalled() + + hub(client) + await settle() + + expect(recording[called]).toHaveBeenCalledExactlyOnceWith(...args) + expect(recordingStreamOf(management)).toBeUndefined() + }) + + it('refuses as busy a recording open naming a held snapshot\'s stream, starting no recording, the picture still sent under its ID', async () => { + const { management, snapshot } = snapshotCamera() + const admit = vi.spyOn(management.delegate as BufferRecorder, 'admit') + const client = await DataStreamClient.connect(management.dataStreamManagement) + const answered = deferred() + + snapshot.mockImplementation(async () => await answered.promise) + openSnapshot(client, 1) + await settle() + + const id = open(client) + + await settle() + + expect(answer(client, id)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(admit).not.toHaveBeenCalled() + expect(recordingStreamOf(management)).toBeUndefined() + + answered.resolve(PICTURE) + await settle() + + expect(streamEvents(client, Topics.DATA, 1)).toEqual([ + { + endOfStream: true, + packets: [ + { + data: PICTURE, + metadata: { + dataChunkSequenceNumber: 1, + dataSequenceNumber: 1, + dataTotalSize: PICTURE.length, + isLastDataChunk: true, + }, + }, + ], + streamId: 1, + }, + ]) + }) + }) }) diff --git a/src/lib/camera/RecordingManagement.ts b/src/lib/camera/RecordingManagement.ts index 1f11217a9..6f8e171bd 100644 --- a/src/lib/camera/RecordingManagement.ts +++ b/src/lib/camera/RecordingManagement.ts @@ -1,5 +1,5 @@ import type { CharacteristicValue } from '../../types.js' -import type { CameraRecordingDelegate, StateChangeDelegate } from '../controller/index.js' +import type { CameraControllerServiceMap, CameraRecordingDelegate, StateChangeDelegate } from '../controller/index.js' import type { DataStreamConnection, DataStreamProtocolHandler, @@ -8,20 +8,26 @@ import type { RequestHandler, } from '../datastream/index.js' import type { CameraOperatingMode, CameraRecordingManagement } from '../definitions/index.js' +/* global NodeJS */ +import type { DelegateFailureReport } from '../util/promise-utils.js' +import type { CameraReporter, DebugWriter } from './diagnostics/CameraReporter.js' import type { VideoCodecType } from './index.js' +import type { OperatingModeState } from './OperatingModePolicy.js' +import type { RecordingAdmission } from './recording/BufferRecorder.js' +import type { ServedRecording, ServedRecordings } from './recording/ServedRecording.js' import type { H264CodecParameters, H264Level, H264Profile, Resolution } from './RTPStreamManagement.js' +import type { SnapshotFetchRequest, SnapshotRefusal } from './StreamingOptions.js' -/* global NodeJS */ import { Buffer } from 'node:buffer' import crypto from 'node:crypto' import { EventEmitter } from 'node:events' import createDebug from 'debug' -import { Access, Characteristic, CharacteristicEventTypes } from '../Characteristic.js' +import { Access, Characteristic } from '../Characteristic.js' +import { DataStreamManagement } from '../datastream/DataStreamManagement.js' import { DataStreamConnectionEvent, - DataStreamManagement, HDSConnectionError, HDSConnectionErrorType, HDSProtocolError, @@ -29,19 +35,41 @@ import { HDSStatus, Protocols, Topics, -} from '../datastream/index.js' +} from '../datastream/DataStreamServer.js' import { HAPStatus } from '../HAPServer.js' import { Service } from '../Service.js' +import { DisposableStack } from '../util/disposableStack.js' import { errorMessage, errorStack } from '../util/errors.js' import { HapStatusError } from '../util/hapStatusError.js' +import { callDelegate, logDelegateFailure, logDelegateRejection } from '../util/promise-utils.js' import * as tlv from '../util/tlv.js' +import { debugChannel } from './diagnostics/debugChannels.js' import { AudioBitrate } from './index.js' +import { OperatingModePolicy } from './OperatingModePolicy.js' +import { ProducerReferenceTimeWriter } from './recording/ProducerReferenceTimeWriter.js' +import { isPictureSize, ResourceRequestReason } from './StreamingOptions.js' const debug = createDebug('HAP-NodeJS:Camera:RecordingManagement') const hksvDebug = createDebug('HAP-NodeJS:HKSV') +// The channel of a camera's debug events under the management's debug name, which a camera with the capabilities block publishes its snapshots' events on. +const RECORDING_MANAGEMENT_DEBUG = debugChannel('HAP-NodeJS:Camera:RecordingManagement') + +// A data event carries at most 256 KiB of a packet, inside the 1 KiB to 900 KiB a hub takes. +const MAX_CHUNK = 0x40000 + +// A stream that has sent all it has waits this long for the hub's ack or close before it closes itself as cancelled. +const CLOSE_WAIT = 12000 + +// The reason a snapshot open is refused with over the data stream for each cause the camera's snapshot gate answers. +const SNAPSHOT_OPEN_REFUSALS: Readonly> = { + 'not allowed': HDSProtocolSpecificErrorReason.NOT_ALLOWED, + 'out of service': HDSProtocolSpecificErrorReason.BUSY, +} + /** - * Describes options passed to the {@link RecordingManagement}. + * Describes options passed to the {@link RecordingManagement}: the legacy recording configurations a camera offers for a HomeKit controller to select. + * A camera with the camera capabilities block gives none, recording from its camera buffer with no configuration selected. * * @group Camera */ @@ -62,12 +90,14 @@ export interface CameraRecordingOptions { * which derives the {@link EventTriggerOption}s from application state. * * {@link EventTriggerOption}s are derived automatically as follows: - * {@link EventTriggerOption.MOTION} is enabled when a {@link Service.MotionSensor} is configured (via {@link CameraControllerOptions.sensors}). + * {@link EventTriggerOption.MOTION} is enabled when a {@link Service.MotionSensor} is configured (via the `sensors` option of {@link CameraControllerOptions}). * {@link EventTriggerOption.DOORBELL} is enabled when the {@link DoorbellController} is used. * * Note: This property is **ADDITIVE**. Meaning if the {@link CameraController} decides to add * a certain {@link EventTriggerOption} it will still do so. This option can only be used to * add **additional** {@link EventTriggerOption}s! + * + * The triggers are advertised in the supported recording configuration these options describe. A camera that gives no options advertises none. */ overrideEventTriggerOptions?: EventTriggerOption[] @@ -320,7 +350,8 @@ type DataSendDataEvent = { packets: { data: Buffer metadata: { - dataType: PacketDataType + // A recording's packets carry their type, and a snapshot's carry none. + dataType?: PacketDataType dataSequenceNumber: number isLastDataChunk: boolean dataChunkSequenceNumber: number @@ -354,6 +385,37 @@ export interface RecordingManagementServices { dataStreamManagement: DataStreamManagement } +/** + * What the camera controller hands the recording management of a camera with the camera capabilities block, whose recordings carry the library's + * producer reference time box. + * @private + */ +interface RecordingManagementCapabilities { + /** + * The recorder's decision on a recording open, asked once the open passes the management's own checks and before the open is answered: a refusal is + * the open's answer with its reason, and an admission's serving function serves the stream in place of the delegate's request. Without it, an open + * passing those checks is answered success and the stream asks the delegate. + */ + readonly admit?: (streamId: number) => RecordingAdmission + /** + * The recordings the camera serves, which each recording stream adds to and the camera's HKSV3 clips upload from. + */ + readonly feed: ServedRecordings + /** + * The camera's reporter, through which a failed call of the recording delegate, the library's own recorder, is the library's failure. + */ + readonly reporter: CameraReporter + /** + * The camera's snapshots over the data stream: the cause for which its gate refuses one, read at each open with the request's reason and undefined + * where the gate lets it through, and the fetch of one picture at the size a hub asks, with the request's reason when it names one and the snapshot + * stream's signal, which every close of the stream aborts. Without it, a snapshot open meets the recording's checks as on any other camera. + */ + readonly snapshot?: { + readonly refusal: (reason: ResourceRequestReason | undefined) => SnapshotRefusal | undefined + readonly fetch: (request: SnapshotFetchRequest & { readonly signal: AbortSignal }) => Promise + } +} + /** * @group Camera */ @@ -376,40 +438,51 @@ export interface RecordingManagementState { selectedConfiguration?: string /** - * Service `CameraRecordingManagement`; Characteristic `Active` + * The operating mode of a layout that keeps it beside the recording state. `deserialize` reads these fields when the camera's state carries no + * operating-mode slice, and `serialize` never writes them. */ - recordingActive: boolean + recordingActive?: boolean /** - * Service `CameraRecordingManagement`; Characteristic `RecordingAudioActive` + * See {@link RecordingManagementState.recordingActive}. */ - recordingAudioActive: boolean - + recordingAudioActive?: boolean /** - * Service `CameraOperatingMode`; Characteristic `EventSnapshotsActive` + * See {@link RecordingManagementState.recordingActive}. */ - eventSnapshotsActive: boolean + eventSnapshotsActive?: boolean /** - * Service `CameraOperatingMode`; Characteristic `HomeKitCameraActive` + * See {@link RecordingManagementState.recordingActive}. */ - homeKitCameraActive: boolean + homeKitCameraActive?: boolean /** - * Service `CameraOperatingMode`; Characteristic `PeriodicSnapshotsActive` + * See {@link RecordingManagementState.recordingActive}. */ - periodicSnapshotsActive: boolean + periodicSnapshotsActive?: boolean +} + +// The camera, video and audio recording configurations a camera supports, each base64 TLV8 as its Supported characteristic carries it. +interface SupportedRecordingConfiguration { + readonly audio: string + readonly camera: string + readonly video: string } /** * @group Camera */ export class RecordingManagement { - readonly options: CameraRecordingOptions + /** + * The legacy recording options the plugin gave, absent on a camera with the camera capabilities block, which records from its camera buffer. + */ + readonly options?: CameraRecordingOptions + readonly delegate: CameraRecordingDelegate private stateChangeDelegate?: StateChangeDelegate - private readonly supportedCameraRecordingConfiguration: string - private readonly supportedVideoRecordingConfiguration: string - private readonly supportedAudioRecordingConfiguration: string + // The supported recording configurations the options describe. A management without options has none, which means it also has no selection for a hub to write, + // no configuration hash in its stored state and no open handler check that a configuration is selected. + private readonly supportedConfiguration?: SupportedRecordingConfiguration /** * 32 bit mask of enabled {@link EventTriggerOption}s. @@ -420,6 +493,11 @@ export class RecordingManagement { readonly operatingModeService: CameraOperatingMode readonly dataStreamManagement: DataStreamManagement + /** + * The operating-mode policy this management binds its characteristics to and forwards its state-change delegate to. + */ + private readonly operatingMode: OperatingModePolicy + /** * The currently active recording stream. * Any camera only supports one stream at a time. @@ -445,18 +523,61 @@ export class RecordingManagement { sensorServices: Service[] = [] /** - * Defines if recording is enabled for this recording management. + * The recording state last reported to the delegate. A write that leaves it unchanged reports nothing. */ - private recordingActive = false + private reportedRecordingActive = false + + // Whether each recording stream writes a producer reference time box before every fragment. It is on exactly for a camera with the capabilities block, + // and every other camera's recording goes out as its delegate yields it. + private producerReferenceTime: boolean + + // The recordings a camera with the capabilities block serves. Each recording stream adds to them what its writer read. + private readonly feed?: ServedRecordings + + // The recorder's decision a camera with the capabilities block asks before it answers a recording open, which carries the stream's serving function. + private readonly admit?: RecordingManagementCapabilities['admit'] + // Where every guarded call of the delegate reports its failure, its stream's close among them: the camera's reporter on a camera with the capabilities + // block, whose delegate is the library's own recorder, and the console otherwise. + private readonly report: DelegateFailureReport + + // The snapshots a camera with the capabilities block answers over the data stream, the camera's reporter, which the capabilities carry beside them and + // which every snapshot's debug event goes through, and each open snapshot stream. + private readonly snapshot?: RecordingManagementCapabilities['snapshot'] + + private readonly reporter?: CameraReporter + + private readonly snapshotStreams = new Set() + + // What destroy releases: every open snapshot stream, then the data stream management, then the open request handler. The characteristic handlers die + // with their service or are replaced by the next management over it, and the policy releases its subscriptions when it is disposed itself. + private readonly stack = new DisposableStack() + + // The dataSend route of each data stream connection that has passed an open's checks, which leaves the table when its connection closes. + private readonly routes = new Map() + + /** + * The camera controller alone constructs the management, which is why the constructor is left out of the documentation, along with the policy and the + * capabilities it takes. + * @hidden + */ constructor( - options: CameraRecordingOptions, + options: CameraRecordingOptions | undefined, delegate: CameraRecordingDelegate, eventTriggerOptions: Set, services?: RecordingManagementServices, + operatingMode: OperatingModePolicy = new OperatingModePolicy(), + capabilities?: RecordingManagementCapabilities, ) { this.options = options this.delegate = delegate + this.operatingMode = operatingMode + this.producerReferenceTime = capabilities !== undefined + this.feed = capabilities?.feed + this.admit = capabilities?.admit + this.report = capabilities?.reporter.sink('library-failure') ?? logDelegateFailure + this.snapshot = capabilities?.snapshot + this.reporter = capabilities?.reporter const recordingServices = services || this.constructService() this.recordingManagementService = recordingServices.recordingManagement @@ -468,15 +589,66 @@ export class RecordingManagement { this.eventTriggerOptions |= option // OR } - this.supportedCameraRecordingConfiguration = this._supportedCameraRecordingConfiguration(options) - this.supportedVideoRecordingConfiguration = this._supportedVideoRecordingConfiguration(options.video) - this.supportedAudioRecordingConfiguration = this._supportedAudioStreamConfiguration(options.audio) + if (options) { + const camera = this._supportedCameraRecordingConfiguration(options) + const video = this._supportedVideoRecordingConfiguration(options.video) + const audio = this._supportedAudioStreamConfiguration(options.audio) + + this.supportedConfiguration = { audio, camera, video } + } this.setupServiceHandlers() + this.stack.adopt(this.dataStreamManagement, dataStreamManagement => dataStreamManagement.destroy()) + + // Every open snapshot stream closes as cancelled, and a picture still being fetched is discarded with nothing sent. + this.stack.defer(() => { + for (const stream of this.snapshotStreams) { + stream.close(HDSProtocolSpecificErrorReason.CANCELLED) + } + }) hksvDebug('RecordingManagement created (eventTriggers=0x%s)', this.eventTriggerOptions.toString(16)) } + /** + * Reconciles the recording services of a restored service map. They form one set: the management is built over the saved services only when all of them + * are saved, and otherwise over a new set written under every key. A camera that does not record deletes each saved recording service. + * @param serviceMap - The camera's service map, changed in place. + * @param create - Builds the management over the given services, or over new ones when it is given none, and is absent for a camera that does not record. + * @returns Whether the map changed. + * @private + */ + static reconcile(serviceMap: CameraControllerServiceMap, create?: (services?: RecordingManagementServices) => RecordingManagement): boolean { + if (!create) { + let modified = false + + for (const key of ['cameraEventRecordingManagement', 'cameraOperatingMode', 'dataStreamTransportManagement'] as const) { + if (serviceMap[key]) { + delete serviceMap[key] + modified = true + } + } + + return modified + } + + const { cameraEventRecordingManagement, cameraOperatingMode, dataStreamTransportManagement } = serviceMap + if (cameraEventRecordingManagement && cameraOperatingMode && dataStreamTransportManagement) { + create({ + recordingManagement: cameraEventRecordingManagement, + operatingMode: cameraOperatingMode, + dataStreamManagement: new DataStreamManagement(dataStreamTransportManagement), + }) + return false + } + + const management = create() + serviceMap.cameraEventRecordingManagement = management.recordingManagementService + serviceMap.cameraOperatingMode = management.operatingModeService + serviceMap.dataStreamTransportManagement = management.dataStreamManagement.getService() + return true + } + private constructService(): RecordingManagementServices { const recordingManagement = new Service.CameraRecordingManagement('', '') recordingManagement.setCharacteristic(Characteristic.Active, false) @@ -498,66 +670,93 @@ export class RecordingManagement { } private setupServiceHandlers() { - // update the current configuration values to the current state. - this.recordingManagementService.setCharacteristic(Characteristic.SupportedCameraRecordingConfiguration, this.supportedCameraRecordingConfiguration) - this.recordingManagementService.setCharacteristic(Characteristic.SupportedVideoRecordingConfiguration, this.supportedVideoRecordingConfiguration) - this.recordingManagementService.setCharacteristic(Characteristic.SupportedAudioRecordingConfiguration, this.supportedAudioRecordingConfiguration) - - this.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration) - .onGet(this.handleSelectedCameraRecordingConfigurationRead.bind(this)) - .onSet(this.handleSelectedCameraRecordingConfigurationWrite.bind(this)) - .setProps({ - adminOnlyAccess: [Access.WRITE], - }) + const { supportedConfiguration } = this + + if (supportedConfiguration) { + // update the current configuration values to the current state. + this.recordingManagementService.setCharacteristic(Characteristic.SupportedCameraRecordingConfiguration, supportedConfiguration.camera) + this.recordingManagementService.setCharacteristic(Characteristic.SupportedVideoRecordingConfiguration, supportedConfiguration.video) + this.recordingManagementService.setCharacteristic(Characteristic.SupportedAudioRecordingConfiguration, supportedConfiguration.audio) + + this.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration) + .onGet(this.handleSelectedCameraRecordingConfigurationRead.bind(this)) + .onSet(this.handleSelectedCameraRecordingConfigurationWrite.bind(this)) + .setProps({ + adminOnlyAccess: [Access.WRITE], + }) + } else { + // A service adopted from a camera that gave the options before drops the configuration characteristics, and the camera advertises no configuration + // it does not offer. Each removal raises the service's configuration change, which moves the accessory's configuration number at its next publish. + for (const type of [ + Characteristic.SupportedCameraRecordingConfiguration, + Characteristic.SupportedVideoRecordingConfiguration, + Characteristic.SupportedAudioRecordingConfiguration, + Characteristic.SelectedCameraRecordingConfiguration, + ]) { + const characteristic = this.recordingManagementService.characteristics.find(candidate => candidate.UUID === type.UUID) + + if (characteristic) { + this.recordingManagementService.removeCharacteristic(characteristic) + } + } + } this.recordingManagementService.getCharacteristic(Characteristic.Active) .onSet((value) => { - if (!!value === this.recordingActive) { + const active = !!value + if (active === this.reportedRecordingActive) { return // skip delegate call if state didn't change! } - this.recordingActive = !!value - hksvDebug('Active onSet: recordingActive -> %s', this.recordingActive) - this.delegate.updateRecordingActive(this.recordingActive) - }) - .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.()) - .setProps({ - adminOnlyAccess: [Access.WRITE], + hksvDebug('Active onSet: recordingActive -> %s', active) + // A write reports here rather than through reportRecordingActive, because a synchronous throw belongs to the write's handler, which answers HomeKit + // with the failure and stores nothing. The report is recorded before the delegate hears it, as reportRecordingActive records it: a delegate that + // writes Active from inside its call is told once. The catch puts back the report recorded before this write, and a retry of the same value + // reaches the delegate again. A rejection, which nothing awaits, goes to the management's failure report. + const previous = this.reportedRecordingActive + this.reportedRecordingActive = active + try { + logDelegateRejection(this.delegate.updateRecordingActive(active), 'CameraRecordingDelegate failed to update state at a write of Active', undefined, + this.report) + } catch (error) { + this.reportedRecordingActive = previous + throw error + } }) - this.recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive) - .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.()) + // The policy marks its admin-only fields as it binds them: every projection of a field carries the mark. + this.operatingMode.bindRecording(this.recordingManagementService, this.operatingModeService) + this.operatingMode.subscribe('homeKitCameraActive', (active) => { + for (const service of this.sensorServices) { + service.setCharacteristic(Characteristic.StatusActive, active) + } - this.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive) - .on(CharacteristicEventTypes.CHANGE, (change) => { - for (const service of this.sensorServices) { - service.setCharacteristic(Characteristic.StatusActive, !!change.newValue) - } + if (!active && this.recordingStream) { + this.recordingStream.close(HDSProtocolSpecificErrorReason.NOT_ALLOWED) + } + }) - if (!change.newValue && this.recordingStream) { - this.recordingStream.close(HDSProtocolSpecificErrorReason.NOT_ALLOWED) - } + // A write that reaches Active around its onSet handler, a plugin's update among them, reports here, and the delegate hears each change once. + this.operatingMode.subscribe('recordingActive', (active) => { + if (active === this.reportedRecordingActive) { + return + } - this.stateChangeDelegate?.() - }) - .setProps({ - adminOnlyAccess: [Access.WRITE], - }) + hksvDebug('Active change: recordingActive -> %s', active) + this.reportRecordingActive(active, 'after an update of Active') + }) - this.operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive) - .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.()) - .setProps({ - adminOnlyAccess: [Access.WRITE], - }) + const open = this.handleDataSendOpen.bind(this) - this.operatingModeService.getCharacteristic(Characteristic.PeriodicSnapshotsActive) - .on(CharacteristicEventTypes.CHANGE, () => this.stateChangeDelegate?.()) - .setProps({ - adminOnlyAccess: [Access.WRITE], - }) + this.dataStreamManagement.onRequestMessage(Protocols.DATA_SEND, Topics.OPEN, open) + this.stack.defer(() => this.dataStreamManagement.removeRequestHandler(Protocols.DATA_SEND, Topics.OPEN, open)) + } - this.dataStreamManagement - .onRequestMessage(Protocols.DATA_SEND, Topics.OPEN, this.handleDataSendOpen.bind(this)) + // The report is recorded before the delegate hears it. A delegate that fails is told once, and callDelegate hands its failure to the management's + // failure report rather than letting it reach the caller that carried the change. + private reportRecordingActive(active: boolean, occasion: string): void { + this.reportedRecordingActive = active + callDelegate(() => this.delegate.updateRecordingActive(active), `CameraRecordingDelegate failed to update state ${occasion}`, this.report) } private handleDataSendOpen(connection: DataStreamConnection, id: number, message: HDSMessage) { @@ -576,6 +775,11 @@ export class RecordingManagement { return } + if (this.snapshot && target === 'controller' && type === 'ipcamera.snapshot') { + this.handleSnapshotOpen(connection, id, message, this.snapshot, this.reporter!) + return + } + if (target !== 'controller' || type !== 'ipcamera.recording') { debug('[HDS %s] Received data send with unexpected target: %s or type: %d. Rejecting...', connection.remoteAddress, target, type) @@ -585,16 +789,9 @@ export class RecordingManagement { return } - if (!this.recordingActive) { - hksvDebug('[HDS %s] rejecting DATA_SEND OPEN: recordingActive=false', connection.remoteAddress) - connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { - status: HDSProtocolSpecificErrorReason.NOT_ALLOWED, - }) - return - } - - if (!this.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value) { - hksvDebug('[HDS %s] rejecting DATA_SEND OPEN: HomeKitCameraActive=false', connection.remoteAddress) + if (!this.operatingMode.recordingAllowed()) { + hksvDebug('[HDS %s] rejecting DATA_SEND OPEN: recording is not allowed (recordingActive=%s HomeKitCameraActive=%s)', + connection.remoteAddress, this.operatingMode.recordingActive, this.operatingMode.homeKitCameraActive) connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { status: HDSProtocolSpecificErrorReason.NOT_ALLOWED, }) @@ -611,7 +808,8 @@ export class RecordingManagement { return } - if (!this.selectedConfiguration) { + // A camera without the legacy options offers no configuration to select, and its recording is served with none selected. + if (this.supportedConfiguration && !this.selectedConfiguration) { hksvDebug('[HDS %s] rejecting DATA_SEND OPEN: no selectedConfiguration (homebridge#3928)', connection.remoteAddress) connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { status: HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION, @@ -619,16 +817,146 @@ export class RecordingManagement { return } + // A recording never takes a stream ID the connection's route holds, a snapshot's among them, and the held stream is left as it is. + if (this.routes.get(connection)?.holds(streamId)) { + debug('[HDS %s] Rejecting DATA_SEND OPEN of recording stream %d as the connection already runs a stream with that ID.', connection.remoteAddress, streamId) + connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { + status: HDSProtocolSpecificErrorReason.BUSY, + }) + return + } + + // A camera with the capabilities block asks its recorder last, once every check of the management's own has passed. The plugin's shouldRecord is + // called only for an open nothing else refuses. The recorder decides once, before the answer: a refusal is the open's answer with its reason, which means no + // stream opens and no data event follows, and an admission carries the function the stream serves the recording through. + const admission = this.admit?.(streamId) + + if (admission?.admitted === false) { + connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { + status: admission.reason, + }) + return + } + + // A camera can pass every check above before the delegate hears that recording is active, a camera whose accessory has not reported its restore + // complete among them, which is why the first request it lets through tells the delegate first, before the recording it asks for starts. + if (!this.reportedRecordingActive) { + hksvDebug('[HDS %s] DATA_SEND OPEN: recordingActive -> true before the first recording', connection.remoteAddress) + this.reportRecordingActive(true, 'before a recording request') + } + debug('[HDS %s] HDS DATA_SEND Open with reason \'%s\'.', connection.remoteAddress, reason) + const route = this.routeOf(connection) // eslint-disable-next-line ts/no-use-before-define - this.recordingStream = new CameraRecordingStream(connection, this.delegate, id, streamId) - this.recordingStream.on(CameraRecordingStreamEvents.CLOSED, () => { + const stream = new CameraRecordingStream(connection, this.delegate, id, streamId, this.producerReferenceTime, this.report, this.feed, admission?.serve) + + // The stream joins its route and becomes the camera's recording before it starts: a close during its start, such as one a delegate's synchronous + // throw causes, clears both. + route.add(stream) + this.recordingStream = stream + stream.on(CameraRecordingStreamEvents.CLOSED, () => { debug('[HDS %s] Removing active recording session from recording management!', connection.remoteAddress) this.recordingStream = undefined }) - this.recordingStream.startStreaming() + stream.startStreaming() + } + + /* A snapshot open on a camera with the capabilities block, whose metadata names the picture's size and the request's reason, read once and handed to the + * camera's gate and its fetch alike. It is refused while the camera's gate refuses, as not allowed while streaming is not allowed or the kind its reason + * names is switched off and as busy while the camera is out of service, then as busy when it names a stream ID the connection's route holds, the held + * stream left as it is, and as an unexpected failure, the open's status for a fault no other status names, when its width or height is not a positive + * whole number. Otherwise a snapshot stream joins the route, answers the open and sends the picture its fetch brings. + */ + private handleSnapshotOpen( + connection: DataStreamConnection, + id: number, + message: Record, + snapshot: NonNullable, + reporter: CameraReporter, + ): void { + const streamId: number = message.streamId + const metadata: Record = message.metadata ?? {} + const reason = snapshotReason(metadata.reason) + const refusal = snapshot.refusal(reason) + + // Each refusal's debug event names the cause the gate answered: a sentence never names a cause the gate did not read. + if (refusal !== undefined) { + if (refusal === 'out of service') { + reporter.debug(RECORDING_MANAGEMENT_DEBUG, 'snapshot-open-out-of-service', () => ({ + remoteAddress: connection.remoteAddress, + sentence: `[HDS ${connection.remoteAddress}] Rejecting DATA_SEND OPEN of snapshot stream ${streamId} as the camera is out of service.`, + streamId, + })) + } else { + reporter.debug(RECORDING_MANAGEMENT_DEBUG, 'snapshot-open-not-allowed', () => ({ + remoteAddress: connection.remoteAddress, + sentence: `[HDS ${connection.remoteAddress}] Rejecting DATA_SEND OPEN of snapshot stream ${streamId} as snapshots are not allowed.`, + streamId, + })) + } + + connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { + status: SNAPSHOT_OPEN_REFUSALS[refusal], + }) + return + } + + if (this.routes.get(connection)?.holds(streamId)) { + reporter.debug(RECORDING_MANAGEMENT_DEBUG, 'snapshot-open-busy', () => ({ + remoteAddress: connection.remoteAddress, + sentence: `[HDS ${connection.remoteAddress}] Rejecting DATA_SEND OPEN of snapshot stream ${streamId} as the connection already runs a stream with ` + + 'that ID.', + streamId, + })) + connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { + status: HDSProtocolSpecificErrorReason.BUSY, + }) + return + } + + const width = Number(metadata.imageWidth) + const height = Number(metadata.imageHeight) + + if (!isPictureSize(width, height)) { + reporter.debug(RECORDING_MANAGEMENT_DEBUG, 'snapshot-open-size-refused', () => ({ + remoteAddress: connection.remoteAddress, + sentence: `[HDS ${connection.remoteAddress}] Rejecting DATA_SEND OPEN of snapshot stream ${streamId} as it names no valid picture size.`, + streamId, + })) + connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, id, HDSStatus.PROTOCOL_SPECIFIC_ERROR, { + status: HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE, + }) + return + } + + const stream = new CameraSnapshotStream(connection, id, streamId, reporter) + + this.routeOf(connection).add(stream) + this.snapshotStreams.add(stream) + stream.on(CameraRecordingStreamEvents.CLOSED, () => this.snapshotStreams.delete(stream)) + stream.start(async signal => await snapshot.fetch({ + height, + reason, + signal, + width, + })) + } + + // The connection's route, made at the first open on the connection that passes the checks. The connection's dataSend handler is claimed once. + private routeOf(connection: DataStreamConnection): DataSendRoute { + let route = this.routes.get(connection) + + if (route === undefined) { + route = new DataSendRoute(connection, { + onClosed: () => this.routes.delete(connection), + open: (id, message) => this.handleDataSendOpen(connection, id, message), + }) + this.routes.set(connection, route) + } + + return route } private handleSelectedCameraRecordingConfigurationRead(): string { @@ -653,13 +981,23 @@ export class RecordingManagement { !!this.stateChangeDelegate, value.length) - this.selectedConfiguration = { - parsed: configuration, - base64: value, - } - if (changed) { - this.delegate.updateRecordingConfiguration(this.selectedConfiguration.parsed) + // The configuration is recorded before the delegate hears it, which is why a delegate that writes it from inside its call is told once. A synchronous throw + // belongs to the write's handler, which answers HomeKit with the failure and stores nothing. The catch puts back the configuration recorded before + // this write, the write saves nothing and a retry reaches the delegate again. A rejection, which nothing awaits, goes to the management's failure + // report. + const previous = this.selectedConfiguration + this.selectedConfiguration = { + parsed: configuration, + base64: value, + } + try { + logDelegateRejection(this.delegate.updateRecordingConfiguration(configuration), + 'CameraRecordingDelegate failed to update state at a write of the selected recording configuration', undefined, this.report) + } catch (error) { + this.selectedConfiguration = previous + throw error + } // notify controller storage about updated values! this.stateChangeDelegate?.() @@ -844,86 +1182,100 @@ export class RecordingManagement { ).toString('base64') } - private computeConfigurationHash(algorithm = 'sha256'): string { + private computeConfigurationHash(supportedConfiguration: SupportedRecordingConfiguration, algorithm = 'sha256'): string { const configurationHash = crypto.createHash(algorithm) - configurationHash.update(this.supportedCameraRecordingConfiguration) - configurationHash.update(this.supportedVideoRecordingConfiguration) - configurationHash.update(this.supportedAudioRecordingConfiguration) + configurationHash.update(supportedConfiguration.camera) + configurationHash.update(supportedConfiguration.video) + configurationHash.update(supportedConfiguration.audio) return configurationHash.digest().toString('hex') } /** + * The recording state the camera stores: the configuration hash and the selection, or none for a management without the legacy options, whose + * recording Active the operating mode's slice keeps. * @private */ serialize(): RecordingManagementState | undefined { + const { supportedConfiguration } = this + + if (!supportedConfiguration) { + return undefined + } + return { configurationHash: { algorithm: 'sha256', - hash: this.computeConfigurationHash('sha256'), + hash: this.computeConfigurationHash(supportedConfiguration, 'sha256'), }, selectedConfiguration: this.selectedConfiguration?.base64, - - recordingActive: this.recordingActive, - recordingAudioActive: !!this.recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive).value, - - eventSnapshotsActive: !!this.operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive).value, - homeKitCameraActive: !!this.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value, - periodicSnapshotsActive: !!this.operatingModeService.getCharacteristic(Characteristic.PeriodicSnapshotsActive).value, } } /** * @private */ - deserialize(serialized: RecordingManagementState): void { + deserialize(serialized: RecordingManagementState, operatingMode?: OperatingModeState): void { let changedState = false - - // we only restore the `selectedConfiguration` if our supported configuration hasn't changed. - const currentConfigurationHash = this.computeConfigurationHash(serialized.configurationHash.algorithm) - - hksvDebug('deserialize: hasSavedSelectedConfig=%s savedHash=%s currentHash=%s hashMatch=%s recordingActive=%s', - !!serialized.selectedConfiguration, - serialized.configurationHash?.hash?.slice(0, 12), - currentConfigurationHash.slice(0, 12), - currentConfigurationHash === serialized.configurationHash?.hash, - serialized.recordingActive) - - if (serialized.selectedConfiguration) { - if (currentConfigurationHash === serialized.configurationHash.hash) { - this.selectedConfiguration = { - base64: serialized.selectedConfiguration, - parsed: this.parseSelectedConfiguration(serialized.selectedConfiguration), + // A state without the operating-mode slice keeps the operating mode in the recording state's own fields. Every writer of that layout writes the fields + // other than recording active, while an older library that restored the slice holds recording active undefined until Active is next written, and JSON + // drops it from the layout that library saves. + const state = operatingMode ?? serialized as RecordingManagementState & Omit + const { supportedConfiguration } = this + + // A management without the options has no configuration to select. It reads neither the stored hash nor the stored selection, which a camera that + // gave the options before leaves, and restores the rest of the state below. + if (supportedConfiguration) { + // we only restore the `selectedConfiguration` if our supported configuration hasn't changed. + const currentConfigurationHash = this.computeConfigurationHash(supportedConfiguration, serialized.configurationHash.algorithm) + + hksvDebug('deserialize: hasSavedSelectedConfig=%s savedHash=%s currentHash=%s hashMatch=%s recordingActive=%s', + !!serialized.selectedConfiguration, + serialized.configurationHash?.hash?.slice(0, 12), + currentConfigurationHash.slice(0, 12), + currentConfigurationHash === serialized.configurationHash?.hash, + state.recordingActive) + + if (serialized.selectedConfiguration) { + if (currentConfigurationHash === serialized.configurationHash.hash) { + this.selectedConfiguration = { + base64: serialized.selectedConfiguration, + parsed: this.parseSelectedConfiguration(serialized.selectedConfiguration), + } + } else { + hksvDebug('deserialize: discarding saved selectedConfiguration — supportedConfiguration hash changed since last run') + changedState = true } - } else { - hksvDebug('deserialize: discarding saved selectedConfiguration — supportedConfiguration hash changed since last run') - changedState = true } } - this.recordingActive = serialized.recordingActive - this.recordingManagementService.updateCharacteristic(Characteristic.Active, serialized.recordingActive) - this.recordingManagementService.updateCharacteristic(Characteristic.RecordingAudioActive, serialized.recordingAudioActive) + // The delegate hears a stored recording state only when it differs from the last report, which is why the last report is read here, before the block below records + // the stored state as reported to keep Active's write from reporting ahead of the configuration replay. + const lastReported = this.reportedRecordingActive - this.operatingModeService.updateCharacteristic(Characteristic.EventSnapshotsActive, serialized.eventSnapshotsActive) - this.operatingModeService.updateCharacteristic(Characteristic.PeriodicSnapshotsActive, serialized.periodicSnapshotsActive) + // A layout without recording active leaves Active as it stands and reports nothing here. The delegate hears of it once the camera's restore + // completes, or at the first recording request on a camera no accessory reaches. The policy's restore leaves every field a layout lacks as it stands. + if (state.recordingActive !== undefined) { + this.reportedRecordingActive = state.recordingActive + } - this.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, serialized.homeKitCameraActive) + this.operatingMode.restore(state) for (const service of this.sensorServices) { - service.setCharacteristic(Characteristic.StatusActive, serialized.homeKitCameraActive) + service.setCharacteristic(Characteristic.StatusActive, this.operatingMode.homeKitCameraActive) } - try { - if (this.selectedConfiguration) { - hksvDebug('deserialize: replaying updateRecordingConfiguration to delegate') - this.delegate.updateRecordingConfiguration(this.selectedConfiguration.parsed) - } else { - hksvDebug('deserialize: no selectedConfiguration to restore') - } - if (serialized.recordingActive) { - this.delegate.updateRecordingActive(serialized.recordingActive) - } - } catch (error) { - console.error(`Failed to properly initialize CameraRecordingDelegate from persistent storage: ${errorStack(error) ?? errorMessage(error)}`) + if (this.selectedConfiguration) { + hksvDebug('deserialize: replaying updateRecordingConfiguration to delegate') + const configuration = this.selectedConfiguration.parsed + callDelegate(() => this.delegate.updateRecordingConfiguration(configuration), 'Failed to properly initialize CameraRecordingDelegate from persistent storage', + this.report) + } else { + hksvDebug('deserialize: no selectedConfiguration to restore') + } + + // The report follows the configuration replay, the order the delegate's contract documents, and callDelegate keeps a replay that fails from skipping it. + if (state.recordingActive !== undefined && state.recordingActive !== lastReported) { + hksvDebug('deserialize: recordingActive -> %s', state.recordingActive) + this.reportRecordingActive(state.recordingActive, 'after a restore') } if (changedState) { @@ -936,33 +1288,44 @@ export class RecordingManagement { */ setupStateChangeDelegate(delegate?: StateChangeDelegate): void { this.stateChangeDelegate = delegate + this.operatingMode.setupStateChangeDelegate(delegate) + } + + /** + * Reports the recording state to the delegate once the camera's restore has completed, when it differs from the state last reported. A recording + * Active the camera adopted from the accessory cache with no stored record reaches the delegate before the first recording request. + * @private + */ + handleRestoreComplete(): void { + const active = this.operatingMode.recordingActive + + if (active === this.reportedRecordingActive) { + return + } + + hksvDebug('handleRestoreComplete: recordingActive -> %s', active) + this.reportRecordingActive(active, 'after the camera\'s restore') } destroy(): void { - this.dataStreamManagement.destroy() + this.stack.dispose() } handleFactoryReset(): void { hksvDebug('handleFactoryReset: clearing selectedConfiguration and resetting recording state') this.selectedConfiguration = undefined - this.recordingActive = false // updateCharacteristic below does not run the set handler which keeps this in step - this.recordingManagementService.updateCharacteristic(Characteristic.Active, false) - this.recordingManagementService.updateCharacteristic(Characteristic.RecordingAudioActive, false) - - this.operatingModeService.updateCharacteristic(Characteristic.EventSnapshotsActive, true) - this.operatingModeService.updateCharacteristic(Characteristic.PeriodicSnapshotsActive, true) - - this.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, true) + this.reportedRecordingActive = false + this.operatingMode.reset() for (const service of this.sensorServices) { service.setCharacteristic(Characteristic.StatusActive, true) } - try { - // notifying the delegate about the updated state - this.delegate.updateRecordingActive(false) - this.delegate.updateRecordingConfiguration(undefined) - } catch (error) { - console.error(`CameraRecordingDelegate failed to update state after handleFactoryReset: ${errorStack(error) ?? errorMessage(error)}`) + // Each call is guarded on its own: a delegate that fails at the first still hears the second. A management without the options never selects a + // configuration, and its delegate hears no configuration call, the reset's included. + this.reportRecordingActive(false, 'after handleFactoryReset') + + if (this.supportedConfiguration) { + callDelegate(() => this.delegate.updateRecordingConfiguration(undefined), 'CameraRecordingDelegate failed to update state after handleFactoryReset', this.report) } } } @@ -985,51 +1348,206 @@ declare interface CameraRecordingStream { emit(event: 'closed'): boolean } +// A delegate's recording as for await accepts it: an async iterable, or a synchronous iterable whose values the language awaits. +type Recording = AsyncIterable | Iterable> + +type RecordingIterator = AsyncIterator | Iterator> + +// The library's one sentence for an answer it cannot consume as a recording, whatever the answer's shape. +const NOT_A_RECORDING = 'The recording delegate answered a value that is neither an async iterable nor an iterable.' + +/* Takes a recording's iterator once, as for await takes it, and answers it with an iterable that hands that same iterator back. The loop consumes and + * closes the recording exactly as the language would the recording itself while the stream holds the iterator for a close from outside the loop. Each + * iterator method is read as for await reads it, a method that reads undefined or null being absent: the async method is taken when present and the + * synchronous one otherwise. A primitive answer is refused before either is read, because a string, which for await would iterate by character, is no + * recording, and an answer with neither method, a promise among them, is refused too, each inside the loop's error handling. + */ +function holdRecording(recording: unknown): { iterable: Recording, iterator: RecordingIterator } { + if (recording === null || (typeof recording !== 'object' && typeof recording !== 'function')) { + throw new TypeError(NOT_A_RECORDING) + } + + const asyncIterator = (recording as Partial>)[Symbol.asyncIterator] + + if (asyncIterator != null) { + const iterator = asyncIterator.call(recording) + + return { + iterable: { + [Symbol.asyncIterator]: () => iterator, + }, + iterator, + } + } + + const syncIterator = (recording as Partial>>)[Symbol.iterator] + + if (syncIterator != null) { + const iterator = syncIterator.call(recording) + + return { + iterable: { + [Symbol.iterator]: () => iterator, + }, + iterator, + } + } + + throw new TypeError(NOT_A_RECORDING) +} + +// A stream a connection's route holds by its ID: a recording or a snapshot, each told the hub's ack and close and its connection's close, and each +// announcing its own close. +interface RoutedStream { + readonly streamId: number + acknowledge: (message: Record) => void + connectionClosed: () => void + hubClose: (message: Record) => void + on: (event: CameraRecordingStreamEvents.CLOSED, listener: () => void) => unknown +} + +// A data stream snapshot request's reason as a resource request names it: 0 periodic, 1 an event, and any other value none. +function snapshotReason(reason: unknown): ResourceRequestReason | undefined { + switch (reason) { + case ResourceRequestReason.PERIODIC: + return ResourceRequestReason.PERIODIC + + case ResourceRequestReason.EVENT: + return ResourceRequestReason.EVENT + + default: + return undefined + } +} + +/* One data stream connection's dataSend handler, made at the first open on the connection that passes the open's checks. Its open goes to the + * management's open handler. Every open on the connection meets the same checks whatever runs there, and an ack or a close goes to the stream it + * names, a stream the route does not hold being ignored. It holds its streams by ID, each until it closes, and never two under one ID, because every open + * naming an ID it holds is refused as busy. The route ends with its connection: it tells each stream the connection closed, releases its handler and its + * listener, and leaves the management's table. + */ +class DataSendRoute implements DataStreamProtocolHandler { + readonly eventHandler: Record + readonly requestHandler: Record + + private readonly streams = new Map() + + private readonly stack = new DisposableStack() + + constructor(connection: DataStreamConnection, { onClosed, open }: { onClosed: () => void, open: RequestHandler }) { + this.eventHandler = { + [Topics.ACK]: message => this.streamNamed(message)?.acknowledge(message), + [Topics.CLOSE]: message => this.streamNamed(message)?.hubClose(message), + } + this.requestHandler = { + [Topics.OPEN]: open, + } + + connection.addProtocolHandler(Protocols.DATA_SEND, this) + this.stack.defer(() => connection.removeProtocolHandler(Protocols.DATA_SEND, this)) + + const closed = (): void => { + for (const stream of Array.from(this.streams.values())) { + stream.connectionClosed() + } + + this.stack.dispose() + onClosed() + } + + connection.on(DataStreamConnectionEvent.CLOSED, closed) + this.stack.defer(() => connection.removeListener(DataStreamConnectionEvent.CLOSED, closed)) + } + + holds(streamId: number): boolean { + return this.streams.has(streamId) + } + + // Holds a stream until it closes, under an ID no stream the route holds carries: it replaces nothing. + add(stream: RoutedStream): void { + this.streams.set(stream.streamId, stream) + stream.on(CameraRecordingStreamEvents.CLOSED, () => this.streams.delete(stream.streamId)) + } + + // The stream a hub's ack or close names, which only a numeric stream ID can name. + private streamNamed(message: HDSMessage): RoutedStream | undefined { + return typeof message.streamId === 'number' + ? this.streams.get(message.streamId) + : undefined + } +} + /** * A `CameraRecordingStream` represents an ongoing stream request for a HomeKit Secure Video recording. * A single camera can only support one ongoing recording at a time. * * @group Camera */ -class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHandler { +class CameraRecordingStream extends EventEmitter { readonly connection: DataStreamConnection readonly delegate: CameraRecordingDelegate readonly hdsRequestId: number readonly streamId: number - private abortController?: AbortController - private closed = false - eventHandler?: Record = { - [Topics.CLOSE]: this.handleDataSendClose.bind(this), - [Topics.ACK]: this.handleDataSendAck.bind(this), - } + // What the stream releases when it closes: the loop's abort while the loop runs, or the close wait's timer after it, and the end of the recording it + // serves. The stream is closed exactly when its stack is disposed, which only the close routine does. + private readonly stack = new DisposableStack() - requestHandler?: Record = undefined + // The loop's abort controller while the loop runs. The loop's exit clears it, and the abort deferred on the stack reaches only a loop still running. + private loop?: AbortController - private readonly closeListener: () => void - - private generator?: AsyncGenerator + // The iterator of the delegate's recording while the loop consumes it, which a close from outside the loop asks to stop. + private iterator?: RecordingIterator /** - * This timeout is used to detect non-returning generators. - * When we signal the delegate that it is being closed its generator must return within 10s. + * The watchdog armed at a close while the loop still holds the recording's iterator, which uncovers a recording that never settles once it is asked to + * stop: the held iterator must settle before the watchdog fires. */ private generatorTimeout?: NodeJS.Timeout - /** - * This timer is used to check if the stream is properly closed when we expect it to do so. - * When we expect a close signal from the remote, we wait 12s for it. Otherwise, we abort and close it ourselves. - * This ensures memory is freed, and that we recover fast from erroneous states. - */ - private closingTimeout?: NodeJS.Timeout - constructor(connection: DataStreamConnection, delegate: CameraRecordingDelegate, requestId: number, streamId: number) { + // The stream's producer reference time writer on a camera with the capabilities block, which each packet passes before it is chunked. + private readonly writer?: ProducerReferenceTimeWriter + + // The recording the stream serves on a camera with the capabilities block, begun with the stream and ended at its close. + private readonly served?: ServedRecording + + // Where the guarded call of the delegate at the stream's close reports its failure, its management's. + private readonly report: DelegateFailureReport + + // The serving function of the recorder's admission on a camera with the capabilities block, which the stream calls in place of the delegate's request. + private readonly serve?: Extract['serve'] + + constructor( + connection: DataStreamConnection, + delegate: CameraRecordingDelegate, + requestId: number, + streamId: number, + producerReferenceTime: boolean, + report: DelegateFailureReport, + feed?: ServedRecordings, + serve?: Extract['serve'], + ) { super() this.connection = connection this.delegate = delegate this.hdsRequestId = requestId this.streamId = streamId + this.report = report + this.serve = serve + + if (producerReferenceTime) { + this.writer = new ProducerReferenceTimeWriter() + } + + if (feed) { + const served = feed.begin() + + this.served = served + this.stack.defer(() => served.end()) + } + } - this.connection.on(DataStreamConnectionEvent.CLOSED, this.closeListener = this.handleDataStreamConnectionClosed.bind(this)) - this.connection.addProtocolHandler(Protocols.DATA_SEND, this) + private get closed(): boolean { + return this.stack.disposed } startStreaming() { @@ -1038,8 +1556,21 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa } private async _startStreaming() { - // 256 KiB (1KiB to 900 KiB) - const maxChunk = 0x40000 + debug('[HDS %s] Sending DATA_SEND OPEN response for streamId %d', this.connection.remoteAddress, this.streamId) + + // A connection closed earlier in the same read refuses the answer. The stream then ends through the close routine without sending the hub a close, + // which the closing connection could not carry, and with nothing told to the delegate, which was never asked for the recording, an admission's serving + // function left uncalled with it. + try { + this.connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, this.hdsRequestId, HDSStatus.SUCCESS, { + status: HDSStatus.SUCCESS, + }) + } catch (error) { + debug('[HDS %s] Could not answer the open of recording stream %d: %s', this.connection.remoteAddress, this.streamId, errorMessage(error)) + this.handleClosed() + + return + } // The first buffer which we receive from the generator is always the `mediaInitialization` packet (mp4 `moov` box). let initialization = true @@ -1049,25 +1580,33 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa let lastFragmentWasMarkedLast = false try { - // Inside the try: nobody waits for this method, so an error thrown here (e.g. the connection is - // closing already) would be an unhandled rejection, and the stream would be left marked as recording. - debug('[HDS %s] Sending DATA_SEND OPEN response for streamId %d', this.connection.remoteAddress, this.streamId) - this.connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, this.hdsRequestId, HDSStatus.SUCCESS, { - status: HDSStatus.SUCCESS, - }) + this.loop = new AbortController() + this.stack.defer(() => this.loop?.abort()) - this.abortController = new AbortController() - this.generator = this.delegate.handleRecordingStreamRequest(this.streamId, this.abortController.signal) + const recording = holdRecording(this.serve + ? this.serve(this.loop.signal) + : this.delegate.handleRecordingStreamRequest(this.streamId, this.loop.signal)) - for await (const packet of this.generator) { + this.iterator = recording.iterator + + 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) break } - const fragment = packet.data - if (fragment.length === 0 && !packet.isLast) { - continue // nothing to send, and no sequence number is used up + // An empty packet that is not the last has nothing to send and uses up no sequence number. + if (packet.data.length === 0 && !packet.isLast) { + 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()) + const fragment = written?.bytes ?? packet.data + + if (written !== undefined) { + this.served?.add(written) } let offset = 0 @@ -1078,7 +1617,7 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa break } - const data = fragment.subarray(offset, offset + maxChunk) + const data = fragment.subarray(offset, offset + MAX_CHUNK) offset += data.length // see https://github.com/Supereg/secure-video-specification#42-binary-data @@ -1126,8 +1665,13 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa + 'Can\'t notify Controller about endOfStream!') } } catch (error) { + // The loop has already closed the recording as far as the language does, through its break or its error: the close below asks nothing more of + // its iterator. + this.iterator = undefined + if (this.closed) { - console.warn(`[HDS ${this.connection.remoteAddress}] Encountered unexpected error on already closed recording stream ${this.streamId}: ${errorStack(error) ?? errorMessage(error)}`) + const thrown = errorStack(error) ?? errorMessage(error) + console.warn(`[HDS ${this.connection.remoteAddress}] Encountered unexpected error on already closed recording stream ${this.streamId}: ${thrown}`) } else { let closeReason = HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE @@ -1139,7 +1683,9 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa debug('[HDS %s] Exited recording stream due to closed HDS socket: stream id %d.', this.connection.remoteAddress, this.streamId) return // execute finally and then exit (we want to skip the `sendEvent` below) } else { - console.error(`[HDS ${this.connection.remoteAddress}] Encountered unexpected error for recording stream ${this.streamId}: ${errorStack(error) ?? errorMessage(error)}`) + console.error( + `[HDS ${this.connection.remoteAddress}] Encountered unexpected error for recording stream ${this.streamId}: ${errorStack(error) ?? errorMessage(error)}`, + ) } // call close to go through standard close routine! @@ -1147,8 +1693,8 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa } return } finally { - this.abortController = undefined - this.generator = undefined + this.loop = undefined + this.iterator = undefined if (this.generatorTimeout) { clearTimeout(this.generatorTimeout) @@ -1165,14 +1711,11 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa debug('[HDS %s] Finished DATA_SEND transmission for stream %d!', this.connection.remoteAddress, this.streamId) } - private handleDataSendAck(message: HDSMessage) { + // The hub's ack, which its route hands the stream it names. + acknowledge(message: HDSMessage): void { const streamId = message.streamId const endOfStream = message.endOfStream - if (streamId !== this.streamId) { - return // an acknowledgment for another stream, like handleDataSendClose checks - } - // The HomeKit Controller will send a DATA_SEND ACK if we set the `endOfStream` flag in the last packet // of our DATA_SEND DATA packet. // In my testing the session is then considered complete and the HomeKit controller will close the HDS Connection after 5 seconds. @@ -1182,62 +1725,54 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa this.handleClosed(() => this.delegate.acknowledgeStream?.(this.streamId)) } - private handleDataSendClose(message: HDSMessage) { + // The hub's close, which its route hands the stream it names. + hubClose(message: HDSMessage): void { // see https://github.com/Supereg/secure-video-specification#43-close - const streamId = message.streamId // a reason which is not a number is handled like a missing one const reason: HDSProtocolSpecificErrorReason | undefined = typeof message.reason === 'number' ? message.reason : undefined - if (streamId !== this.streamId) { - return - } - + // The route hands a stream the closes that name it alone, which is why the stream's own ID is the close's. debug('[HDS %s] Received DATA_SEND CLOSE for streamId %d with reason %s', - this.connection.remoteAddress, streamId, reason !== undefined + this.connection.remoteAddress, this.streamId, reason !== undefined ? HDSProtocolSpecificErrorReason[reason] : reason) - this.handleClosed(() => this.delegate.closeRecordingStream(streamId, reason)) + this.handleClosed(() => this.delegate.closeRecordingStream(this.streamId, reason)) } - private handleDataStreamConnectionClosed() { + // The close of the stream's connection, which its route hands each stream it holds. + connectionClosed(): void { debug('[HDS %s] The HDS connection of the stream %d closed.', this.connection.remoteAddress, this.streamId) this.handleClosed(() => this.delegate.closeRecordingStream(this.streamId, undefined)) } - private handleClosed(closure: () => void): void { + /* The one close routine, which every close takes, its first step disposing the stack, which is why it runs once. The stack releases what the stream holds: the + * loop's abort, which lets a delegate with abortable work stop at once rather than yield to a closed stream, or the close wait's timer once the loop + * has exited, and the end of the recording it serves. Then the recording is asked to stop if the loop still runs, the delegate hears the close, unless + * the stream ends before the delegate was asked for anything, and the route and the management let the stream go. + */ + private handleClosed(closure?: () => void): void { if (this.closed) { return } - this.closed = true - - // Signal the delegate's generator to stop immediately. This allows delegates with abortable async operations (e.g. pacing delays) to interrupt them and - // return without yielding to a closed stream. - this.abortController?.abort() - - if (this.closingTimeout) { - clearTimeout(this.closingTimeout) - this.closingTimeout = undefined - } + this.stack.dispose() - this.connection.removeProtocolHandler(Protocols.DATA_SEND, this) - this.connection.removeListener(DataStreamConnectionEvent.CLOSED, this.closeListener) + if (this.iterator) { + const iterator = this.iterator - if (this.generator) { - // Signal the generator to terminate via the async generator protocol. The return is queued and takes effect - // after the generator's current await completes. Combined with the AbortSignal above, this ensures the - // generator terminates promptly even if the delegate doesn't check the signal. We catch rejections - // to prevent unhandled promise warnings if the generator's cleanup throws. - void this.generator.return(undefined).catch((error: Error) => - debug('[HDS %s] Error while closing recording generator for stream %d: %s', - this.connection.remoteAddress, this.streamId, error.stack ?? String(error))) + /* Ask the recording to stop through its iterator's optional return. A generator queues the return until its current await completes, and with the + * abort above it stops promptly even when the delegate ignores the signal. Whatever the return does, throw, reject, answer a plain value or be + * absent, settles this one promise, whose rejection is logged. The close always reaches the delegate's call and frees the camera. + */ + void new Promise(resolve => resolve(iterator.return?.())).catch((error: Error | undefined) => + debug('[HDS %s] Error while closing the recording of stream %d: %s', + this.connection.remoteAddress, this.streamId, error?.stack ?? String(error))) - // when this variable is defined, the generator hasn't returned yet. - // we start a timeout to uncover potential programming mistakes where we await forever and can't free resources. + // While the iterator is held, the loop has not exited, which is why the watchdog uncovers a recording that awaits forever and never frees its resources. this.generatorTimeout = setTimeout(() => { console.error('[HDS %s] Recording download stream %d is still awaiting generator although stream was closed 10s ago! ' + 'This is a programming mistake by the camera implementation which prevents freeing up resources.', this.connection.remoteAddress, this.streamId) @@ -1245,10 +1780,8 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa this.generatorTimeout.unref() // only reports a mistake, so it must not keep the process alive } - try { - closure() - } catch (error) { - console.error(`[HDS ${this.connection.remoteAddress}] CameraRecordingDelegate failed to handle closing the stream ${this.streamId}: ${errorStack(error) ?? errorMessage(error)}`) + if (closure) { + callDelegate(closure, `[HDS ${this.connection.remoteAddress}] CameraRecordingDelegate failed to handle closing the stream ${this.streamId}`, this.report) } this.emit(CameraRecordingStreamEvents.CLOSED) @@ -1277,19 +1810,211 @@ class CameraRecordingStream extends EventEmitter implements DataStreamProtocolHa this.handleClosed(() => this.delegate.closeRecordingStream(this.streamId, reason)) } + // Once the loop has exited, the hub has the close wait to acknowledge or close the stream before the stream closes itself as cancelled, and an exchange + // that fails still frees the camera. Its clear is on the stack: the timer never fires after a close. private kickOffCloseTimeout(): void { - if (this.closingTimeout) { - clearTimeout(this.closingTimeout) + const closingTimeout = setTimeout(() => { + debug('[HDS %s] Recording stream %d took longer than expected to fully close. Force closing now!', this.connection.remoteAddress, this.streamId) + this.close(HDSProtocolSpecificErrorReason.CANCELLED) + }, CLOSE_WAIT) + + // The wait only frees a stream the hub left open, which is no reason to keep the process alive. + closingTimeout.unref() + this.stack.defer(() => clearTimeout(closingTimeout)) + } +} + +/* One snapshot a hub asks over a data stream connection, on a camera with the capabilities block. It answers the open, fetches the picture and sends it + * as one data sequence of chunks carrying no data type, the last ending the stream, then waits for the hub's ack or close, closing itself as cancelled + * once the wait passes; a failed fetch closes it as an unexpected failure. Its one close routine runs once whatever closes it, the hub, its connection, + * its own wait or the management's destroy, and a picture that arrives after the close is discarded with nothing sent. + */ +class CameraSnapshotStream extends EventEmitter { + readonly streamId: number + + private readonly connection: DataStreamConnection + + private readonly requestId: number + + // The camera's reporter's debug events on the management's debug name. + private readonly debug: DebugWriter + + // What the stream releases when it closes, the fetch's signal, which it aborts, and the wait for the hub once the picture is sent. The stream is closed + // exactly when its stack is disposed. + private readonly stack = new DisposableStack() + + constructor(connection: DataStreamConnection, requestId: number, streamId: number, reporter: CameraReporter) { + super() + this.connection = connection + this.requestId = requestId + this.streamId = streamId + this.debug = reporter.writer(RECORDING_MANAGEMENT_DEBUG) + } + + private get closed(): boolean { + return this.stack.disposed + } + + /* Answers the open, then sends the picture the fetch brings, or closes as an unexpected failure when the fetch fails. The fetch is handed a signal of the + * stream's own, whose abort the stack holds: every close aborts it, and a fetch still waiting on the picture hears that no hub waits on it. + */ + start(fetch: (signal: AbortSignal) => Promise): void { + try { + this.connection.sendResponse(Protocols.DATA_SEND, Topics.OPEN, this.requestId, HDSStatus.SUCCESS, { + status: HDSStatus.SUCCESS, + }) + } catch (error) { + this.debug('snapshot-open-unanswered', () => { + const message = errorMessage(error) + + return { + message, + remoteAddress: this.connection.remoteAddress, + sentence: `[HDS ${this.connection.remoteAddress}] Could not answer the open of snapshot stream ${this.streamId}: ${message}`, + streamId: this.streamId, + } + }) + this.handleClosed() + + return } - this.closingTimeout = setTimeout(() => { + const fetching = new AbortController() + + this.stack.defer(() => fetching.abort()) + + void fetch(fetching.signal).then(picture => this.send(picture), (error) => { if (this.closed) { return } - debug('[HDS %s] Recording stream %d took longer than expected to fully close. Force closing now!', this.connection.remoteAddress, this.streamId) + this.debug('snapshot-fetch-failed', () => { + const message = errorMessage(error) + + return { + message, + remoteAddress: this.connection.remoteAddress, + sentence: `[HDS ${this.connection.remoteAddress}] The snapshot of stream ${this.streamId} could not be fetched: ${message}`, + streamId: this.streamId, + } + }) + this.close(HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE) + }) + } + + // Sends the picture as chunks of one data sequence and waits for the hub, unless the stream closed while the picture was fetched. + private send(picture: Buffer): void { + if (this.closed) { + this.debug('snapshot-discarded', () => ({ + remoteAddress: this.connection.remoteAddress, + sentence: `[HDS ${this.connection.remoteAddress}] Discarding the snapshot of stream ${this.streamId}, which closed while its picture was fetched.`, + streamId: this.streamId, + })) + + return + } + + try { + for (let offset = 0, dataChunkSequenceNumber = 1; offset < picture.length; dataChunkSequenceNumber++) { + const data = picture.subarray(offset, offset + MAX_CHUNK) + + offset += data.length + + const last = offset >= picture.length + const event: DataSendDataEvent = { + streamId: this.streamId, + packets: [ + { + data, + metadata: { + dataSequenceNumber: 1, + dataChunkSequenceNumber, + isLastDataChunk: last, + dataTotalSize: dataChunkSequenceNumber === 1 + ? picture.length + : undefined, + }, + }, + ], + endOfStream: last || undefined, + } + + this.connection.sendEvent(Protocols.DATA_SEND, Topics.DATA, event) + } + } catch (error) { + this.debug('snapshot-send-failed', () => { + const message = errorMessage(error) + + return { + message, + remoteAddress: this.connection.remoteAddress, + sentence: `[HDS ${this.connection.remoteAddress}] Could not send the snapshot of stream ${this.streamId}: ${message}`, + streamId: this.streamId, + } + }) + this.handleClosed() + + return + } + + const wait = setTimeout(() => { + this.debug('snapshot-unacknowledged', () => ({ + remoteAddress: this.connection.remoteAddress, + sentence: `[HDS ${this.connection.remoteAddress}] Snapshot stream ${this.streamId} was not acknowledged in time. Closing it now.`, + streamId: this.streamId, + })) this.close(HDSProtocolSpecificErrorReason.CANCELLED) - }, 12000) - this.closingTimeout.unref() + }, CLOSE_WAIT) + + // The wait only frees a stream the hub left open, which is no reason to keep the process alive. + wait.unref() + this.stack.defer(() => clearTimeout(wait)) + } + + // The hub's ack, which its route hands the stream it names. + acknowledge(): void { + this.handleClosed() + } + + // The hub's close, which its route hands the stream it names. + hubClose(): void { + this.handleClosed() + } + + // The close of the stream's connection, which its route hands each stream it holds. + connectionClosed(): void { + this.handleClosed() + } + + // Closes the stream from the camera's side, telling the hub its reason while the connection stands. + close(reason: HDSProtocolSpecificErrorReason): void { + if (this.closed) { + return + } + + this.debug('snapshot-closed', () => ({ + reason: HDSProtocolSpecificErrorReason[reason], + remoteAddress: this.connection.remoteAddress, + sentence: `[HDS ${this.connection.remoteAddress}] Snapshot stream ${this.streamId} was closed with reason ${HDSProtocolSpecificErrorReason[reason]}.`, + streamId: this.streamId, + })) + + if (!this.connection.isConsideredClosed()) { + this.connection.sendEvent(Protocols.DATA_SEND, Topics.CLOSE, { + streamId: this.streamId, + reason, + }) + } + + this.handleClosed() + } + + private handleClosed(): void { + if (this.closed) { + return + } + + this.stack.dispose() + this.emit(CameraRecordingStreamEvents.CLOSED) } } diff --git a/src/lib/camera/SensorRegistry.spec.ts b/src/lib/camera/SensorRegistry.spec.ts new file mode 100644 index 000000000..c787cc019 --- /dev/null +++ b/src/lib/camera/SensorRegistry.spec.ts @@ -0,0 +1,370 @@ +import type { CameraControllerOptions, CameraControllerState } from '../controller/index.js' +import type { SensorConfiguration } from './capabilities/cameraSensors.js' +import type { CameraVideoSensor } from './StreamingOptions.js' +import type { WebRTCStreamingOptions } from './WebRTCStreamManagement.js' + +import { describe, expect, it } from 'vitest' + +import { + capabilitiesCameraOptions, + idleStreaming, + savedMapOf, + videoSensor, + webRTCStreamingOptions, +} from '../../test-utils/cameraFixtures.js' +import { Characteristic } from '../Characteristic.js' +import { CameraController, DoorbellController } from '../controller/index.js' +import { HAPStatus } from '../HAPServer.js' +import { Service } from '../Service.js' +import { CameraSensorIntent, CameraSensorType, decodeCameraCapabilities } from './capabilities/cameraSensors.js' +import { CameraVideoQuality } from './capabilities/streamTiers.js' +import { SensorRegistry } from './SensorRegistry.js' + +import '../definitions/index.js' + +const SENSOR_A_UUID = 'A1B2C3D4-0000-4000-8000-000000000001' +const SENSOR_A: SensorConfiguration = { + sensorDimensions: { width: 1920, height: 1080 }, + sensorUUID: SENSOR_A_UUID, + sensorType: CameraSensorType.PRIMARY, + sensorIntent: CameraSensorIntent.MAIN, + videoStreamCapabilities: [ + { + identifier: 'c0000001-0000-4000-8000-000000000001', + videoQuality: CameraVideoQuality.HIGH, + width: 1920, + height: 1080, + framesPerSecond: 30, + averageBitRate: 2000, + peakBitRate: 2500, + }, + ], +} + +// The camera rows' entry at the registry rows' first sensor UUID. +const ENTRY_A = videoSensor(SENSOR_A_UUID) + +const SENSOR_B: SensorConfiguration = { + sensorDimensions: { width: 640, height: 480 }, + sensorUUID: 'b0000002-0000-4000-8000-000000000002', + sensorType: CameraSensorType.GENERIC, + sensorIntent: CameraSensorIntent.PACKAGE, + videoStreamCapabilities: [ + { + identifier: 'c0000002-0000-4000-8000-000000000002', + videoQuality: CameraVideoQuality.LOW, + width: 640, + height: 480, + framesPerSecond: 15, + averageBitRate: 300, + peakBitRate: 400, + }, + { + identifier: 'c0000003-0000-4000-8000-000000000003', + videoQuality: CameraVideoQuality.LOW, + width: 320, + height: 240, + framesPerSecond: 15, + averageBitRate: 150, + peakBitRate: 200, + }, + ], +} + +describe('sensorRegistry', () => { + it('lists the Primary sensor\'s UUID and configuration first for a Generic sensor given first', () => { + const registry = new SensorRegistry([SENSOR_B, SENSOR_A]) + + expect(registry.sensorUUIDs).toEqual(['a1b2c3d4-0000-4000-8000-000000000001', 'b0000002-0000-4000-8000-000000000002']) + expect(decodeCameraCapabilities(registry.advertise().getCharacteristic(Characteristic.CameraCapabilitiesData).value as string)).toEqual({ + version: 1, + cameraSensors: [ + { + ...SENSOR_A, + sensorUUID: SENSOR_A.sensorUUID.toLowerCase(), + }, + SENSOR_B, + ], + }) + }) + + it('keeps the plugin\'s order among several Primary sensors and among the rest, whatever their types, and with no Primary sensor at all', () => { + const secondPrimary: SensorConfiguration = { + ...SENSOR_A, + sensorUUID: 'a2000003-0000-4000-8000-000000000003', + } + const unknown: SensorConfiguration = { + ...SENSOR_B, + sensorUUID: 'c0000004-0000-4000-8000-000000000004', + sensorType: CameraSensorType.UNKNOWN, + sensorIntent: CameraSensorIntent.UNKNOWN, + } + // The sensors a registry advertises in its Camera Capabilities value, in the value's order, which states the order apart from the registry's UUIDs. + const advertisedOf = (registry: SensorRegistry): SensorConfiguration[] => + decodeCameraCapabilities(registry.advertise().getCharacteristic(Characteristic.CameraCapabilitiesData).value as string).cameraSensors + const configurationsOf = (sensors: SensorConfiguration[]): SensorConfiguration[] => sensors.map(sensor => ({ + ...sensor, + sensorUUID: sensor.sensorUUID.toLowerCase(), + })) + const uuidsOf = (sensors: SensorConfiguration[]): string[] => sensors.map(sensor => sensor.sensorUUID.toLowerCase()) + + const mixed = new SensorRegistry([ + SENSOR_B, + secondPrimary, + unknown, + SENSOR_A, + ]) + const expected = [ + secondPrimary, + SENSOR_A, + SENSOR_B, + unknown, + ] + + expect(mixed.sensorUUIDs).toEqual(uuidsOf(expected)) + expect(advertisedOf(mixed)).toEqual(configurationsOf(expected)) + + const unlabelled = new SensorRegistry([unknown, SENSOR_B]) + + expect(unlabelled.sensorUUIDs).toEqual(uuidsOf([unknown, SENSOR_B])) + expect(advertisedOf(unlabelled)).toEqual(configurationsOf([unknown, SENSOR_B])) + }) + + it('names each fault by the plugin\'s index and finds the first in the plugin\'s order when a Primary sensor is given later', () => { + const unencodable = (sensor: SensorConfiguration): SensorConfiguration => ({ + ...sensor, + sensorDimensions: { + ...sensor.sensorDimensions, + width: 70000, + }, + }) + + expect(() => new SensorRegistry([ + SENSOR_B, + { + ...SENSOR_A, + sensorUUID: 'front door', + }, + SENSOR_A, + ])).toThrow(new TypeError('The video sensor at index 1 has the sensor UUID "front door", which is not a UUID.')) + expect(() => new SensorRegistry([SENSOR_B, SENSOR_A, SENSOR_B])).toThrow(new TypeError( + 'The video sensors at index 0 and index 2 share the sensor UUID "b0000002-0000-4000-8000-000000000002", but each sensor needs its own.', + )) + expect(() => new SensorRegistry([ + unencodable(SENSOR_B), + unencodable(SENSOR_A), + ])).toThrow(new TypeError('The video sensor "b0000002-0000-4000-8000-000000000002" has a configuration that Camera Capabilities cannot encode.')) + }) + + it('refuses a sensor UUID that is not a UUID', () => { + const refuse = (): SensorRegistry => new SensorRegistry([ + SENSOR_A, + { + ...SENSOR_B, + sensorUUID: 'front door', + }, + ]) + + expect(refuse).toThrow(TypeError) + expect(refuse).toThrow(new TypeError('The video sensor at index 1 has the sensor UUID "front door", which is not a UUID.')) + }) + + it('refuses two sensors that share a UUID in any case', () => { + const refuse = (): SensorRegistry => new SensorRegistry([ + SENSOR_A, + SENSOR_B, + { + ...SENSOR_B, + sensorUUID: SENSOR_A.sensorUUID.toLowerCase(), + }, + ]) + + expect(refuse).toThrow(TypeError) + expect(refuse).toThrow(new TypeError( + 'The video sensors at index 0 and index 2 share the sensor UUID "a1b2c3d4-0000-4000-8000-000000000001", but each sensor needs its own.', + )) + }) + + it('refuses a configuration Camera Capabilities cannot encode', () => { + const refuse = (): SensorRegistry => new SensorRegistry([ + { + ...SENSOR_A, + sensorDimensions: { + ...SENSOR_A.sensorDimensions, + width: 70000, + }, + }, + ]) + + expect(refuse).toThrow(TypeError) + expect(refuse).toThrow(new TypeError('The video sensor "a1b2c3d4-0000-4000-8000-000000000001" has a configuration that Camera Capabilities cannot encode.')) + expect(refuse).toThrow(expect.objectContaining({ + cause: expect.any(RangeError), + })) + }) + + it('answers each sensor\'s dimensions for its UUID in either case and none for an unknown one, whatever the plugin changes afterward', () => { + const first: SensorConfiguration = { + ...SENSOR_A, + sensorDimensions: { ...SENSOR_A.sensorDimensions }, + } + const second: SensorConfiguration = { + ...SENSOR_B, + sensorDimensions: { ...SENSOR_B.sensorDimensions }, + } + const registry = new SensorRegistry([first, second]) + + expect(registry.sensorDimensions(first.sensorUUID.toUpperCase())).toEqual({ width: 1920, height: 1080 }) + expect(registry.sensorDimensions(first.sensorUUID.toLowerCase())).toEqual({ width: 1920, height: 1080 }) + expect(registry.sensorDimensions(second.sensorUUID.toUpperCase())).toEqual({ width: 640, height: 480 }) + expect(registry.sensorDimensions('e0000009-0000-4000-8000-000000000009')).toBeUndefined() + + first.sensorDimensions.width = 1 + second.sensorDimensions = { width: 2, height: 2 } + + expect(registry.sensorDimensions(first.sensorUUID)).toEqual({ width: 1920, height: 1080 }) + expect(registry.sensorDimensions(second.sensorUUID)).toEqual({ width: 640, height: 480 }) + }) + + describe('camera controller', () => { + const minimal = { + delegate: { + handleSnapshotRequest: (): void => undefined, + prepareStream: (): void => undefined, + handleStreamRequest: (): void => undefined, + }, + streamingOptions: { + supportedCryptoSuites: [], + video: { + codec: { + profiles: [], + levels: [], + }, + resolutions: [], + }, + }, + } + + it('throws the registry\'s TypeError from the camera and doorbell constructors', () => { + const options = capabilitiesCameraOptions({ + videoSensors: [ + ENTRY_A, + videoSensor('front door'), + ], + streaming: idleStreaming(), + }) + + expect(() => new CameraController(options)).toThrow(TypeError) + expect(() => new DoorbellController(options)).toThrow(TypeError) + }) + + it('writes no video sensor inventory, and drops the one a stored record holds at the next save, on a camera with the block and on one without it', + () => { + // A record an earlier run stored, which held the inventory beside the camera's other state. + const stored = { + streamManagements: [], + sensorRegistry: { + sensorUUIDs: [ + SENSOR_A_UUID.toLowerCase(), + ], + capabilityHash: { + algorithm: 'sha256', + hash: 'fb9bc463fd4db3cd9c1d5bf303b93633a577f8b4a207f8aaec58d63369aea94f', + }, + }, + } as CameraControllerState + const block = new CameraController(capabilitiesCameraOptions({ + videoSensors: [ENTRY_A], + streaming: idleStreaming(), + })) + const legacy = new CameraController(minimal) + + expect(block.serialize()).not.toHaveProperty('sensorRegistry') + + for (const camera of [block, legacy]) { + camera.deserialize(stored) + + expect(camera.serialize()).not.toHaveProperty('sensorRegistry') + } + + expect(Object.keys(JSON.parse(JSON.stringify(legacy.serialize())))).toEqual(['streamManagements']) + }) + }) + + describe('camera capabilities advertisement', () => { + const CAMERA_CAPABILITIES = 'cameraCapabilities:cameraCapabilities' + + function withSensors(sensors: CameraVideoSensor[], webrtc?: WebRTCStreamingOptions): CameraControllerOptions { + return capabilitiesCameraOptions({ + videoSensors: sensors, + streaming: idleStreaming(), + webrtc, + }) + } + + it('advertises the specification version and a value carrying the data version and every sensor', () => { + const service = new SensorRegistry([SENSOR_A, SENSOR_B]).advertise() + + expect(service.getCharacteristic(Characteristic.Version).value).toBe('17.99') + expect(decodeCameraCapabilities(service.getCharacteristic(Characteristic.CameraCapabilitiesData).value as string)).toEqual({ + version: 1, + cameraSensors: [ + { + ...SENSOR_A, + sensorUUID: SENSOR_A.sensorUUID.toLowerCase(), + }, + SENSOR_B, + ], + }) + }) + + it('overwrites an adopted service\'s cached version and value', () => { + const saved = new Service.CameraCapabilities('', '') + saved.setCharacteristic(Characteristic.Version, '1.0') + saved.setCharacteristic(Characteristic.CameraCapabilitiesData, 'AQEA') + const registry = new SensorRegistry([SENSOR_A]) + + expect(registry.advertise(saved)).toBe(saved) + expect(saved.getCharacteristic(Characteristic.Version).value).toBe('17.99') + expect(saved.getCharacteristic(Characteristic.CameraCapabilitiesData).value) + .toBe(registry.advertise().getCharacteristic(Characteristic.CameraCapabilitiesData).value) + }) + + it('constructs the camera capabilities service under its prefixed key and adopts a saved one', () => { + const saved = savedMapOf(new CameraController(withSensors([ENTRY_A]))) + const service = saved[CAMERA_CAPABILITIES] + + expect(service!.UUID).toBe(Service.CameraCapabilities.UUID) + expect(new CameraController(withSensors([ENTRY_A])).initWithServices(saved)).toBeUndefined() + expect(saved[CAMERA_CAPABILITIES]).toBe(service) + }) + + it('reads the camera capabilities service\'s manually disabled as an operating-mode projection', async () => { + const camera = new CameraController(withSensors([ENTRY_A])) + const map = camera.constructServices() + camera.configureServices() + + map[CAMERA_CAPABILITIES]!.getCharacteristic(Characteristic.ManuallyDisabled).updateValue(1) + + expect(camera.serialize()!.operatingMode!.manuallyDisabled).toBe(true) + await expect(camera.handleSnapshotRequest(360, 640, 'Camera')).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + }) + + it('keeps every claimed key and deletes an unclaimed prefixed key', () => { + const saved = savedMapOf(new CameraController(withSensors([ENTRY_A], webRTCStreamingOptions()))) + saved['cameraCapabilities:retired'] = new Service.CameraCapabilities('', '') + + const restored = new CameraController(withSensors([ENTRY_A], webRTCStreamingOptions())).initWithServices(saved) + + expect(Object.keys(restored!).filter(key => key.startsWith('cameraCapabilities:'))).toEqual([ + CAMERA_CAPABILITIES, + 'cameraCapabilities:globalOperatingMode', + 'cameraCapabilities:multiTierStream:a1b2c3d4-0000-4000-8000-000000000001', + 'cameraCapabilities:webRTCStream:a1b2c3d4-0000-4000-8000-000000000001', + 'cameraCapabilities:cameraBufferManagement', + 'cameraCapabilities:cameraKeyManagement', + 'cameraCapabilities:cameraClientCertificateManagement', + ]) + }) + }) +}) diff --git a/src/lib/camera/StreamingOptions.spec.ts b/src/lib/camera/StreamingOptions.spec.ts new file mode 100644 index 000000000..3f9c67e8a --- /dev/null +++ b/src/lib/camera/StreamingOptions.spec.ts @@ -0,0 +1,714 @@ +import type { CameraCapabilitiesOptions, CameraControllerOptions } from '../controller/index.js' +import type { CameraVideoSensor, CameraVideoTier, MultiTierStreamingOptions } from './StreamingOptions.js' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { capabilitiesCameraOptions, idleStreaming, savedMapOf, videoSensor } from '../../test-utils/cameraFixtures.js' +import { captureDebug, captureDebugEvents } from '../../test-utils/engineDebug.js' +import { Characteristic } from '../Characteristic.js' +import { CameraController, DoorbellController } from '../controller/index.js' +import * as uuid from '../util/uuid.js' +import { CameraSensorIntent, CameraSensorType, decodeCameraCapabilities } from './capabilities/cameraSensors.js' +import { + CameraVideoQuality, + decodeSupportedAudioStreamTiers, + decodeSupportedVideoStreamTiers, + TieredAudioBitDepth, + TieredAudioCodecType, + TieredAudioSampleRate, + TieredVideoCodecType, +} from './capabilities/streamTiers.js' +import { MultiTierStreamManagement } from './MultiTierStreamManagement.js' +import { SensorRegistry } from './SensorRegistry.js' +import { validateVideoSensors } from './StreamingOptions.js' + +import '../definitions/index.js' + +const SENSOR_A = videoSensor('a1b2c3d4-0000-4000-8000-000000000001') +const SENSOR_B = videoSensor('b0000002-0000-4000-8000-000000000002') + +function withCapabilities(videoSensors: CameraVideoSensor[], streaming: MultiTierStreamingOptions = idleStreaming(), strict?: boolean): CameraControllerOptions { + return capabilitiesCameraOptions({ + videoSensors, + streaming, + strict, + }) +} + +// The first sensor with its tiers changed by the row. +function tiersWith(change: (tiers: CameraVideoTier[]) => CameraVideoTier[]): CameraVideoSensor { + return { + ...SENSOR_A, + tiers: change(SENSOR_A.tiers), + } +} + +// A sensor whose audio states the source given. +function sourced(sensor: CameraVideoSensor, source: CameraVideoSensor['audio']['source']): CameraVideoSensor { + return { + ...sensor, + audio: { ...sensor.audio, source }, + } +} + +// A sensor marked recorded on the tier of the identifier given. +function recordedOn(sensor: CameraVideoSensor, tierId: number): CameraVideoSensor { + return { + ...sensor, + tiers: sensor.tiers.map(tier => ({ ...tier, recorded: tier.id === tierId })), + } +} + +// The second sensor advertising its tiers smallest first, its identifiers reversed: its best tier is its last, tier 3. +const SMALLEST_FIRST: CameraVideoSensor = { + ...SENSOR_B, + tiers: SENSOR_B.tiers.map(tier => ({ ...tier, id: 4 - tier.id })).reverse(), +} + +/* The cases of a sensor's sound, each named short enough to print whole in a title: the sensors a camera states, the one whose tier set a row reads, by its + * index, the source and the sound tier the options boundary settles on that set, and the tiers whose settled entry reads that their stream must carry the + * sensor's sound. A lesser tier is one that is not its sensor's best. The case of a sensor that is not the recorded sensor marks the first sensor recorded + * on its tier 2, which means the second sensor's best tier is neither its first nor the one whose identifier the recorded tier carries. + */ +const SOUND_CASES: { + readonly name: string + readonly sensors: CameraVideoSensor[] + readonly read: number + readonly audioSource: 'shared' | 'tier' + readonly soundTierId: number + readonly sounding: number[] +}[] = [ + { + audioSource: 'tier', + name: 'states no source', + read: 0, + sensors: [SENSOR_A], + soundTierId: 1, + sounding: [1, 2, 3], + }, + { + audioSource: 'tier', + name: 'states \'tier\'', + read: 0, + sensors: [ + sourced(SENSOR_A, 'tier'), + ], + soundTierId: 1, + sounding: [1, 2, 3], + }, + { + audioSource: 'shared', + name: 'is shared and recorded, none marked', + read: 0, + sensors: [ + sourced(SENSOR_A, 'shared'), + ], + soundTierId: 1, + sounding: [1], + }, + { + audioSource: 'shared', + name: 'is shared and marked on a lesser tier', + read: 0, + sensors: [ + recordedOn(sourced(SENSOR_A, 'shared'), 2), + ], + soundTierId: 2, + sounding: [2], + }, + { + audioSource: 'shared', + name: 'is shared and not the recorded sensor', + read: 1, + sensors: [ + recordedOn(SENSOR_A, 2), + sourced(SMALLEST_FIRST, 'shared'), + ], + soundTierId: 3, + sounding: [3], + }, + { + audioSource: 'tier', + name: 'states \'tier\', marked on a lesser tier', + read: 0, + sensors: [ + recordedOn(sourced(SENSOR_A, 'tier'), 2), + ], + soundTierId: 1, + sounding: [1, 2, 3], + }, +] + +interface MinimumOutcome { + debug: string[] + strict: unknown + warnings: unknown[][] +} + +// What a minimum does to a construction by default and then under strict: the lines it adds to the row's one capture of the camera controller's debug +// name, the warnings it prints and the error it throws under strict, which a minimum writes as one debug line, warns of never and throws as a TypeError. +function minimumOutcome(lines: string[], sensor: CameraVideoSensor, streaming: MultiTierStreamingOptions = idleStreaming()): MinimumOutcome { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const written = lines.length + const warned = warn.mock.calls.length + const construct = (strict?: boolean): CameraController => new CameraController(withCapabilities([sensor], streaming, strict)) + const outcome = (strict: unknown): MinimumOutcome => ({ + debug: lines.slice(written), + strict, + warnings: warn.mock.calls.slice(warned), + }) + + construct() + + try { + construct(true) + } catch (error) { + return outcome(error) + } + + return outcome(undefined) +} + +function minimum(sentence: string): MinimumOutcome { + return { + debug: [sentence], + strict: new TypeError(sentence), + warnings: [], + } +} + +// A configured camera's Camera Capabilities value, decoded. +function capabilitiesOf(camera: CameraController): ReturnType { + const service = savedMapOf(camera)[SensorRegistry.SERVICE_KEY]! + + return decodeCameraCapabilities(service.getCharacteristic(Characteristic.CameraCapabilitiesData).value as string) +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('multi-tier streaming options', () => { + it('constructs a camera with the fixture streaming and warns nothing', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + expect(() => new CameraController(withCapabilities([SENSOR_A, SENSOR_B]))).not.toThrow() + expect(warn).not.toHaveBeenCalled() + }) + + it('refuses a block without video sensors', () => { + const construct = (): CameraController => new CameraController(withCapabilities([])) + + expect(construct).toThrow(TypeError) + expect(construct).toThrow('The camera capabilities block lists no video sensors, but it needs at least one.') + }) + + it('refuses a videoSensors that is no array, a streaming that is no object, a streaming delegate without tierDemandStarted and an entry that is no ' + + 'object, naming its index, each in that order and before any sensor\'s UUID is read', () => { + // A camera whose block holds the members given in place of the fixture's, as an untyped caller can give them. + const construct = (members: Partial>) => (): CameraController => new CameraController( + capabilitiesCameraOptions({ + streaming: idleStreaming(), + videoSensors: [SENSOR_A], + ...members, + } as CameraCapabilitiesOptions), + ) + const videoSensors = new TypeError('The camera capabilities block has no videoSensors list, which states each video sensor.') + const streaming = new TypeError('The camera capabilities block has no streaming member, which states the multi-tier streaming delegate.') + const tierDemandStarted = new TypeError('The camera capabilities block\'s streaming delegate has no tierDemandStarted function, which starts each video ' + + 'tier\'s stream.') + + for (const members of [ + { videoSensors: undefined }, + { videoSensors: SENSOR_A }, + { streaming: undefined, videoSensors: 'sensors' }, + ]) { + expect(construct(members)).toThrow(videoSensors) + } + + for (const members of [ + { streaming: undefined }, + { streaming: null }, + { + streaming: 5, + videoSensors: [null], + }, + ]) { + expect(construct(members)).toThrow(streaming) + } + + for (const delegate of [ + undefined, + {}, + { tierDemandStarted: 'start' }, + ]) { + expect(construct({ + streaming: { delegate }, + })).toThrow(tierDemandStarted) + } + + expect(construct({ + streaming: { delegate: {} }, + videoSensors: [null], + })).toThrow(tierDemandStarted) + expect(construct({ + videoSensors: [null], + })).toThrow(new TypeError('The video sensor at index 0 is not an object.')) + expect(construct({ + videoSensors: [SENSOR_A, 7], + })).toThrow(new TypeError('The video sensor at index 1 is not an object.')) + expect(construct({ + videoSensors: [ + { ...SENSOR_A, uuid: 'not a UUID' }, + null, + ], + })).toThrow(new TypeError('The video sensor at index 1 is not an object.')) + }) + + it('refuses two video tiers sharing an identifier', () => { + const sensor = tiersWith(tiers => tiers.map(tier => ({ + ...tier, + id: Math.min(tier.id, 2), + }))) + const construct = (): CameraController => new CameraController(withCapabilities([sensor])) + + expect(construct).toThrow(TypeError) + expect(construct).toThrow('The video sensor "a1b2c3d4-0000-4000-8000-000000000001" has two tiers with the id 2.') + }) + + it('refuses a video sensor whose intent is not a sensor intent, and accepts it once its intent is one', () => { + const construct = (intent: CameraSensorIntent): CameraController => new CameraController(withCapabilities([ + { ...SENSOR_A, intent }, + ])) + + expect(() => construct(7 as CameraSensorIntent)) + .toThrow(new TypeError('The intent of the video sensor "a1b2c3d4-0000-4000-8000-000000000001", 7, is not a sensor intent.')) + + for (const intent of Object.values(CameraSensorIntent)) { + expect(() => construct(intent)).not.toThrow() + } + }) + + it('refuses a video tier whose quality is not a video quality, and accepts it once its quality is one', () => { + const construct = (quality: CameraVideoQuality): CameraController => new CameraController(withCapabilities([ + tiersWith(tiers => tiers.map(tier => tier.id === 2 + ? { ...tier, quality } + : tier)), + ])) + + expect(() => construct(7 as CameraVideoQuality)) + .toThrow(new TypeError('The quality of the tier 2 of the video sensor "a1b2c3d4-0000-4000-8000-000000000001", 7, is not a video quality.')) + expect(() => construct(CameraVideoQuality.MEDIUM)).not.toThrow() + }) + + it('refuses stream tiers the stream tier codec cannot encode, carrying the codec\'s error', () => { + const sensor = tiersWith(tiers => tiers.map(tier => ({ + ...tier, + frameRate: 300, + }))) + const construct = (): CameraController => new CameraController(withCapabilities([sensor])) + + expect(construct).toThrow(TypeError) + expect(construct).toThrow('The video sensor "a1b2c3d4-0000-4000-8000-000000000001" has tiers the stream tier codec cannot encode.') + expect(construct).toThrow(expect.objectContaining({ + cause: expect.any(RangeError), + })) + }) + + it('advertises each entry in the plugin\'s order, the first Primary and the rest Generic, with one capability for each tier and the values only the ' + + 'library fills in', () => { + const packageSensor = videoSensor('C3000003-0000-4000-8000-000000000003', { + dimensions: { width: 1280, height: 720 }, + intent: CameraSensorIntent.PACKAGE, + }) + const mainSensor = videoSensor('a1b2c3d4-0000-4000-8000-000000000001', { + audio: { bitrate: 32, packetTime: 40 }, + tiers: SENSOR_A.tiers.map(tier => tier.id === 2 + ? { ...tier, peakBitrate: 900 } + : tier), + }) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const camera = new CameraController(withCapabilities([packageSensor, mainSensor])) + const map = savedMapOf(camera) + const capabilityOf = (sensor: CameraVideoSensor, tier: CameraVideoTier, peakBitRate: number): object => ({ + identifier: uuid.generate(`${sensor.uuid.toLowerCase()}:${tier.id}`), + videoQuality: tier.quality, + width: tier.width, + height: tier.height, + framesPerSecond: tier.frameRate, + averageBitRate: tier.bitrate, + peakBitRate, + }) + + expect(capabilitiesOf(camera)).toEqual({ + version: 1, + cameraSensors: [ + { + sensorDimensions: { width: 1280, height: 720 }, + sensorUUID: 'c3000003-0000-4000-8000-000000000003', + sensorType: CameraSensorType.PRIMARY, + sensorIntent: CameraSensorIntent.PACKAGE, + videoStreamCapabilities: [ + capabilityOf(packageSensor, packageSensor.tiers[0], 1800), + capabilityOf(packageSensor, packageSensor.tiers[1], 800), + capabilityOf(packageSensor, packageSensor.tiers[2], 190), + ], + }, + { + sensorDimensions: { width: 1920, height: 1080 }, + sensorUUID: 'a1b2c3d4-0000-4000-8000-000000000001', + sensorType: CameraSensorType.GENERIC, + sensorIntent: CameraSensorIntent.MAIN, + videoStreamCapabilities: [ + capabilityOf(mainSensor, mainSensor.tiers[0], 1800), + capabilityOf(mainSensor, mainSensor.tiers[1], 900), + capabilityOf(mainSensor, mainSensor.tiers[2], 190), + ], + }, + ], + }) + + for (const [sensor, packetTime, bitrate] of [ + [packageSensor, 20, 24000], + [mainSensor, 40, 32000], + ] as const) { + const service = map[MultiTierStreamManagement.serviceKey(sensor.uuid)]! + + expect(decodeSupportedVideoStreamTiers(service.getCharacteristic(Characteristic.SupportedVideoStreamTiers).value as string)).toEqual({ + codec: TieredVideoCodecType.H265, + payloadType: 99, + tiers: sensor.tiers.map(tier => ({ + identifier: tier.id, + quality: tier.quality, + targetAverageBitrate: tier.bitrate, + width: tier.width, + height: tier.height, + frameRate: tier.frameRate, + })), + }) + expect(decodeSupportedAudioStreamTiers(service.getCharacteristic(Characteristic.SupportedAudioStreamTiers).value as string)).toEqual({ + codec: TieredAudioCodecType.OPUS, + payloadType: 110, + tiers: [ + { + identifier: 1, + targetAverageBitrate: bitrate, + sampleRate: TieredAudioSampleRate.KHZ_48, + bitDepth: TieredAudioBitDepth.BITS_16, + packetTime, + numberOfChannels: 1, + }, + ], + }) + } + }) + + it('advertises each tier\'s peak as given, or as its class\'s maximum where its bitrate is at or under it, or as its bitrate otherwise', () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const peaksOf = (tier: Partial): number[] => { + const sensor = tiersWith(tiers => tiers.map(candidate => candidate.id === 1 + ? { + ...candidate, + ...tier, + } + : candidate)) + + return capabilitiesOf(new CameraController(withCapabilities([sensor]))).cameraSensors[0].videoStreamCapabilities.map(({ peakBitRate }) => peakBitRate) + } + + expect(peaksOf({})[0]).toBe(1800) + expect(peaksOf({ bitrate: 2000 })[0]).toBe(2000) + expect(peaksOf({ bitrate: 900, height: 500, width: 1000 })[0]).toBe(900) + expect(peaksOf({ peakBitrate: 2500 })[0]).toBe(2500) + }) + + it('refuses each entry the boundary cannot state with a TypeError naming its member, warning nothing, a UUID that is no UUID ahead of every other', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const a = 'a1b2c3d4-0000-4000-8000-000000000001' + const b = 'b0000002-0000-4000-8000-000000000002' + const recordedFirst = (sensor: CameraVideoSensor): CameraVideoSensor => ({ + ...sensor, + tiers: sensor.tiers.map(tier => ({ ...tier, recorded: tier.id === 1 })), + }) + const unencodable = tiersWith(tiers => tiers.map(tier => ({ ...tier, frameRate: 300 }))) + const cases: [CameraVideoSensor[], string][] = [ + [ + [ + { ...SENSOR_A, tiers: undefined as unknown as CameraVideoTier[] }, + ], + `The tiers of the video sensor "${a}" are missing or empty, but each sensor takes at least one.`, + ], + [ + [ + { ...SENSOR_A, tiers: [] }, + ], + `The tiers of the video sensor "${a}" are missing or empty, but each sensor takes at least one.`, + ], + [ + [ + tiersWith(tiers => [ + ...tiers, + { ...tiers[0] }, + ]), + ], + `The video sensor "${a}" has two tiers with the id 1.`, + ], + [ + [ + recordedFirst(SENSOR_A), + recordedFirst(SENSOR_B), + ], + `The tier 1 of the video sensor "${b}" is marked recorded beside the tier 1 of the video sensor "${a}", but a camera records one tier.`, + ], + [ + [ + tiersWith(tiers => tiers.map(tier => ({ ...tier, peakBitrate: tier.bitrate - 100 }))), + ], + `The peakBitrate of the tier 1 of the video sensor "${a}", 1600 kbps, is below its bitrate of 1700 kbps.`, + ], + [ + [ + { ...SENSOR_A, motionZones: 'zones' as unknown as CameraVideoSensor['motionZones'] }, + ], + `The motionZones of the video sensor "${a}" is not a function.`, + ], + [ + [ + tiersWith(tiers => tiers.map(tier => ({ ...tier, keepRunning: 'yes' as unknown as boolean }))), + ], + `The keepRunning of the tier 1 of the video sensor "${a}" is not a boolean.`, + ], + [ + [ + tiersWith(tiers => tiers.map(tier => ({ ...tier, recorded: 1 as unknown as boolean }))), + ], + `The recorded of the tier 1 of the video sensor "${a}" is not a boolean.`, + ], + [ + [ + { ...SENSOR_A, audio: undefined as unknown as CameraVideoSensor['audio'] }, + ], + `The video sensor "${a}" has no audio, which each sensor states with its bitrate.`, + ], + [ + [ + { ...SENSOR_A, audio: {} as CameraVideoSensor['audio'] }, + ], + `The audio of the video sensor "${a}" has no bitrate, which each sensor's audio states.`, + ], + [ + [ + sourced(SENSOR_A, 'every' as unknown as CameraVideoSensor['audio']['source']), + ], + `The audio of the video sensor "${a}" takes a source of 'shared' or 'tier', but every is neither.`, + ], + [ + [ + { ...SENSOR_A, dimensions: undefined as unknown as CameraVideoSensor['dimensions'] }, + ], + `The video sensor "${a}" has no dimensions, which each sensor states with its width and height.`, + ], + [ + [ + { ...SENSOR_A, dimensions: null as unknown as CameraVideoSensor['dimensions'] }, + ], + `The video sensor "${a}" has no dimensions, which each sensor states with its width and height.`, + ], + [ + [ + tiersWith(tiers => [null as unknown as CameraVideoTier, ...tiers]), + ], + `The tiers of the video sensor "${a}" hold an entry at index 0 that is not an object.`, + ], + [ + [ + tiersWith(tiers => [ + tiers[0], + 7 as unknown as CameraVideoTier, + ...tiers.slice(1), + ]), + ], + `The tiers of the video sensor "${a}" hold an entry at index 1 that is not an object.`, + ], + [ + [unencodable], + `The video sensor "${a}" has tiers the stream tier codec cannot encode.`, + ], + [ + [ + { ...SENSOR_A, tiers: [] }, + { ...SENSOR_B, uuid: undefined as unknown as string }, + ], + 'The video sensor at index 1 has the sensor UUID "undefined", which is not a UUID.', + ], + ] + + for (const [sensors, sentence] of cases) { + expect(() => new CameraController(withCapabilities(sensors))).toThrow(new TypeError(sentence)) + } + + expect(() => new CameraController(withCapabilities([unencodable]))).toThrow(expect.objectContaining({ + cause: expect.any(RangeError), + })) + expect(warn).not.toHaveBeenCalled() + }) + + it.each(SOUND_CASES)('settles on its tier set the source and the sound tier of a sensor that $name', ({ audioSource, read, sensors, soundTierId }) => { + const { tierSets } = validateVideoSensors(sensors, idleStreaming(), false) + + expect({ audioSource: tierSets[read].audioSource, soundTierId: tierSets[read].soundTierId }).toEqual({ audioSource, soundTierId }) + }) + + it.each(SOUND_CASES)('freezes on each settled entry of a sensor that $name whether its stream must carry the sensor\'s sound', ({ read, sensors, sounding }) => { + const { tiers } = validateVideoSensors(sensors, idleStreaming(), false).tierSets[read] + const entries = Array.from(tiers.values(), entry => ({ + frozen: Object.isFrozen(entry), + sound: entry.sound, + tierId: entry.id, + })) + + expect(entries).toEqual(Array.from(tiers.keys(), tierId => ({ + frozen: true, + sound: sounding.includes(tierId), + tierId, + }))) + }) + + it('writes a debug line and no warning for fewer than three video tiers, and throws it under strict', () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + + expect(minimumOutcome(lines, tiersWith(tiers => tiers.slice(0, 2)))) + .toEqual(minimum('The video sensor "a1b2c3d4-0000-4000-8000-000000000001" offers 2 video stream tiers, but the specification requires at least three.')) + }) + + it('names a single video tier in the singular in its minimum', () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + + expect(minimumOutcome(lines, tiersWith(tiers => tiers.slice(0, 1)))) + .toEqual(minimum('The video sensor "a1b2c3d4-0000-4000-8000-000000000001" offers 1 video stream tier, but the specification requires at least three.')) + }) + + it('publishes a minimum as a below-minimum debug event carrying no accessory UUID, since the camera holds no accessory while it is built', () => { + const events = captureDebugEvents('HAP-NodeJS:Camera:Controller') + const sensor = tiersWith(tiers => tiers.slice(0, 2)) + + expect(() => new CameraController(withCapabilities([sensor]))).not.toThrow() + expect(events).toStrictEqual([ + { + kind: 'below-minimum', + sentence: 'The video sensor "a1b2c3d4-0000-4000-8000-000000000001" offers 2 video stream tiers, but the specification requires at least three.', + }, + ]) + }) + + it('writes a debug line and no warning for an opus audio tier at a packet time of 40 ms as one not at 48 kHz with a 20 ms packet time and one channel, ' + + 'and throws it under strict', () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + + expect(minimumOutcome(lines, { + ...SENSOR_A, + audio: { bitrate: 24, packetTime: 40 }, + })).toEqual(minimum(`The audio stream tier 1 of the video sensor "${SENSOR_A.uuid}" is not at 48 kHz with a 20 ms packet time and one channel.`)) + }) + + it('writes a debug line and no warning for a highest tier without both a 4K and a 2K tier, and throws it under strict', () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + + expect(minimumOutcome(lines, tiersWith(tiers => [ + { + bitrate: 4500, + frameRate: 30, + height: 2160, + id: 4, + quality: CameraVideoQuality.HIGHEST, + width: 3840, + }, + ...tiers, + ]))).toEqual(minimum('The video sensor "a1b2c3d4-0000-4000-8000-000000000001" offers a Highest video stream tier without both a 4K and a 2K tier.')) + }) + + it('writes a debug line and no warning for a video tier above its resolution\'s maximum bitrate, and throws it under strict', () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + + expect(minimumOutcome(lines, tiersWith(tiers => tiers.map(tier => tier.id === 1 + ? { ...tier, bitrate: 1900 } + : tier)))) + .toEqual(minimum(`The video stream tier 1 of the video sensor "${SENSOR_A.uuid}" targets 1900 kbps, above the specification's maximum of 1800 kbps.`)) + }) + + it('refuses a maxSessions that is not a positive integer whatever the switch', () => { + for (const maxSessions of [0, 2.5, Number.NaN]) { + const construct = (strict?: boolean): CameraController => new CameraController(withCapabilities([SENSOR_A], { + ...idleStreaming(), + maxSessions, + }, strict)) + + expect(() => construct()).toThrow(new TypeError(`The multi-tier streaming takes a maxSessions that is a positive integer, but ${maxSessions} is not one.`)) + expect(() => construct(true)).toThrow(TypeError) + } + }) + + it('writes a debug line and no warning for a maxSessions below five, and throws it under strict, and does neither at five or by default', () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + const neither = { debug: [], strict: undefined, warnings: [] } + + expect(minimumOutcome(lines, SENSOR_A, { + ...idleStreaming(), + maxSessions: 5, + })).toEqual(neither) + expect(minimumOutcome(lines, SENSOR_A)).toEqual(neither) + expect(minimumOutcome(lines, SENSOR_A, { + ...idleStreaming(), + maxSessions: 4, + })) + .toEqual(minimum('The multi-tier streaming holds at most 4 sessions per video sensor, but the specification requires at least five.')) + }) + + it('names a maxSessions of one in the singular in its minimum', () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + + expect(minimumOutcome(lines, SENSOR_A, { + ...idleStreaming(), + maxSessions: 1, + })) + .toEqual(minimum('The multi-tier streaming holds at most 1 session per video sensor, but the specification requires at least five.')) + }) + + it('reads the minimums once every refusal has passed, which is why a camera below one with a bad prebuffer throws the prebuffer\'s refusal, under strict too, ' + + 'and writes no minimum', () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const construct = (strict: boolean) => (): CameraController => new CameraController(capabilitiesCameraOptions({ + recording: { prebuffer: -1 }, + streaming: idleStreaming(), + strict, + videoSensors: [ + tiersWith(tiers => tiers.slice(0, 2)), + ], + })) + const refusal = new TypeError('The prebuffer of the camera capabilities block\'s recording option, -1, is not a whole number of milliseconds from 0 to ' + + '30000.') + + expect(construct(false)).toThrow(refusal) + expect(construct(true)).toThrow(refusal) + expect(lines).toEqual([]) + expect(warn).not.toHaveBeenCalled() + }) + + it('throws the registry\'s sentence before validating the streaming options', () => { + const construct = (): CameraController => new CameraController(withCapabilities([ + { ...SENSOR_A, tiers: [] }, + videoSensor('front door'), + ])) + + expect(construct).toThrow(TypeError) + expect(construct).toThrow('The video sensor at index 1 has the sensor UUID "front door", which is not a UUID.') + }) + + it('validates the streaming options from the doorbell constructor', () => { + const construct = (): DoorbellController => new DoorbellController(withCapabilities([])) + + expect(construct).toThrow(TypeError) + expect(construct).toThrow('The camera capabilities block lists no video sensors, but it needs at least one.') + }) +}) diff --git a/src/lib/camera/StreamingOptions.ts b/src/lib/camera/StreamingOptions.ts index 34e8f1f86..5470fe623 100644 --- a/src/lib/camera/StreamingOptions.ts +++ b/src/lib/camera/StreamingOptions.ts @@ -641,6 +641,24 @@ export interface MultiTierStreamingOptions { maxSessions?: number } +/** + * The reason a hub gives for a resource request, which a plugin reads through `api.hap`, as in `hap.ResourceRequestReason.EVENT`. + * + * @group Camera + */ +export enum ResourceRequestReason { + /** + * The reason describes periodic resource requests. + * In the example of camera image snapshots those are the typical preview images every 10 seconds. + */ + PERIODIC = 0, + /** + * The resource request is the result of some event. + * In the example of camera image snapshots, requests are made due to e.g. a motion event or similar. + */ + EVENT = 1, +} + /** * The newest keyframe of a video sensor's best running tier, as a movie of that one picture. The library keeps the movie and hands the same one again * while that keyframe is the newest, which is why a plugin reads its bytes and never changes them. @@ -666,6 +684,59 @@ export interface CameraKeyframe { readonly age: number } +/** + * One snapshot a hub asks of a camera with the camera capabilities block, as the block's snapshot function is handed it, over the data stream or a + * resource request alike. + * + * @group Camera + */ +export interface CameraSnapshotRequest { + /** + * The picture's width in pixels, a positive whole number. + */ + readonly width: number + /** + * The picture's height in pixels, a positive whole number. + */ + readonly height: number + /** + * The reason the hub gives for the snapshot, where it gives one. + */ + readonly reason?: ResourceRequestReason + /** + * The UUID of the video sensor the snapshot shows, the camera's first, in lowercase. + */ + readonly sensorUUID: string + /** + * The newest keyframe of that sensor's best running tier, as the camera controller's `latestKeyframe` answers it, where the library holds one. + */ + readonly keyframe?: CameraKeyframe +} + +/** + * The part of a snapshot's request that each of the library's fetches of a picture carries, the asked size and the hub's reason, a type of the library's + * own that the camera barrel does not name. + */ +export type SnapshotFetchRequest = Pick + +/** + * Why the snapshot gate of a camera with the camera capabilities block refuses a snapshot, a cause each path answers with a status of its own: + * `not allowed` while streaming is not allowed or the user switched off the kind the request names, and `out of service` while the camera is out of + * service. A type of the library's own that the camera barrel does not name. + */ +export type SnapshotRefusal = 'not allowed' | 'out of service' + +/** + * Whether a snapshot's asked size is one a picture can have, a width and a height that are each a positive whole number of pixels. A camera with the camera + * capabilities block refuses a snapshot of any other size before its snapshot function is called, over the data stream and a resource request alike. + * @param width - The asked width. + * @param height - The asked height. + * @returns Whether the width and the height are each a positive whole number. + */ +export function isPictureSize(width: number, height: number): boolean { + return [width, height].every(size => Number.isInteger(size) && (size > 0)) +} + /** * What the options boundary answers for a camera's video sensors, each sensor in the plugin's order. */ diff --git a/src/lib/camera/TierPacer.spec.ts b/src/lib/camera/TierPacer.spec.ts new file mode 100644 index 000000000..f7c35f80c --- /dev/null +++ b/src/lib/camera/TierPacer.spec.ts @@ -0,0 +1,4645 @@ +import type { Mock, MockInstance } from 'vitest' + +import type { ScriptedTierDelegate } from '../../test-utils/cameraFixtures.js' +import type { Deferred } from '../../test-utils/settle.js' +import type { CameraReporter } from './diagnostics/CameraReporter.js' +import type { CameraProblem } from './diagnostics/problems.js' +import type { Mp4StreamSample } from './mp4/Mp4StreamReader.js' +import type { CameraKeyframe, MultiTierStreamingDelegate, SensorStreamTiers, StreamTierMedium, TierStream } from './StreamingOptions.js' +import type { KeyframeAnswer, PacketConsumer, StartAnswer, Tier, TierDemand, TierHold, TierHolder } from './TierTable.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + disposableFor, + disposedOf, + endsOf, + FIRST_VIDEO_SENSOR, + openingStamp, + pendingStart, + scriptedTierDelegate, + signalOf, + streamsOf, + tierSetOf, +} from '../../test-utils/cameraFixtures.js' +import { buildEmitterConnection } from '../../test-utils/connectionFixtures.js' +import { captureDebug } from '../../test-utils/engineDebug.js' +import { + pictureSample, + soundSample, + TIER_STREAM_PARAMETER_SETS, + tierPicture, + tierStreamFragment, + tierStreamInitialization, +} from '../../test-utils/mp4Fixtures.js' +import { detachedReporter, problemsOf } from '../../test-utils/reporterFixtures.js' +import { deferred, fakeTimeoutSignals, settle } from '../../test-utils/settle.js' +import { TierBuffer } from './buffer/CameraBuffer.js' +import { Mp4StreamReader } from './mp4/Mp4StreamReader.js' +import { ClockRun } from './rtp/RTPClock.js' +import { DELEGATE_CALL_TIMEOUT } from './session/settleWithin.js' +import { bestStreamTier } from './StreamingOptions.js' +import { TierPacer } from './TierPacer.js' +import { DemandHalf, TierTable } from './TierTable.js' + +// The fixture's tiers of its first video sensor. +const TIERS = tierSetOf(FIRST_VIDEO_SENSOR) + +// The ticks of a millisecond on the picture's 90 kHz track and on the sound's 48 kHz track. +const PICTURE_TICKS = 90 +const SOUND_TICKS = 48 + +// One Opus packet of 20 ms, its table-of-contents octet stating that length. +const SOUND = Buffer.from([0xFC, 0x01, 0x02]) + +// A fragment of a tier's stream, every time and length in milliseconds: its pictures from a decode time, each of the length given and of the octets given, +// the picture fixture's own where a row gives none, the first a keyframe carrying its parameter sets when asked, and its sounds of 20 ms each from a decode +// time of their own. +interface FragmentFixture { + readonly keyframe?: boolean + readonly octets?: number + readonly pictureAt?: number + readonly pictures?: readonly number[] + readonly soundAt?: number + readonly sounds?: number +} + +function fragment({ keyframe = false, octets, pictureAt = 0, pictures = [], soundAt = 0, sounds = 0 }: FragmentFixture): Buffer { + return tierStreamFragment({ + picture: pictures.map((length, index) => ({ + ...tierPicture({ inBand: true, keyframe: keyframe && (index === 0), octets }), + duration: Math.round(length * PICTURE_TICKS), + })), + pictureTime: BigInt(Math.round(pictureAt * PICTURE_TICKS)), + sound: Array.from({ length: sounds }, () => soundSample(SOUND)), + soundTime: BigInt(Math.round(soundAt * SOUND_TICKS)), + }) +} + +// What the debug event of a demand a reset withdrew says became of it. +const WITHDRAWAL = 'when its service ended every session: the demand is withdrawn and every join waiting on it is refused' + +// One frame a viewer was handed: the moment of its release, in milliseconds from the row's start, its time in milliseconds, whether it opened a run, and +// the timestamp it was handed at, whole. +interface Release { + readonly at: number + readonly opensRun: boolean + readonly time: number + readonly timestamp: number +} + +interface Rig { + readonly delegate: ScriptedTierDelegate + readonly table: TierTable + // The fixture's video tier 1, whose buffer the table made. + readonly tier: Tier + // The stream the delegate was handed for the tier's latest demand. + readonly stream: () => TierStream + // Moves the mock clock to a moment of the row's own timeline, in milliseconds from its start, each timer due by then running at its own moment. + readonly at: (moment: number) => Promise + // Joins a viewer that keeps every frame of a medium it is handed, with the moment of its release. + readonly view: (medium?: StreamTierMedium) => { readonly hold: TierHold, readonly holder: TierHolder & { tierFailed: Mock<() => void> }, readonly releases: Release[] } +} + +function scriptedHolder(): TierHolder & { tierFailed: Mock<() => void> } { + return { + tierFailed: vi.fn<() => void>(), + } +} + +// A table of the fixture's tiers on mock timers, each video tier holding a buffer, whose timeline starts at the moment it is made, reporting to a scripted +// delegate unless a row hands one of its own, made from the fixture's tier set unless a row hands one of its own, and reporting its problems through a +// reporter of no camera unless a row hands one of its own. +function rig(delegate: ScriptedTierDelegate = scriptedTierDelegate(), tiers: SensorStreamTiers = TIERS, reporter: CameraReporter = detachedReporter()): Rig { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const table = new TierTable(delegate, tiers, options => new TierBuffer(options), reporter) + const tier = table.videoTiers.get(1)! + const zero = performance.now() + + return { + at: async (moment) => { + await vi.advanceTimersByTimeAsync(zero + moment - performance.now()) + }, + delegate, + stream: () => delegate.tierDemandStarted.mock.calls.at(-1)![0], + table, + tier, + view: (medium = 'video') => { + const holder = scriptedHolder() + const releases: Release[] = [] + const hold = table.joinFrames(tier, medium, holder, { + take: (frame, timestamp, opensRun) => { + releases.push({ + at: performance.now() - zero, + opensRun, + time: Math.round(frame.time / 1000), + timestamp, + }) + }, + }) + + return { hold, holder, releases } + }, + } +} + +/* The start delays a viewer's pictures read over fragments of one picture each, as Mp4FrameFeed's asking rows read them: each fragment arrives at a moment + * of the row's own timeline with a picture of the length given, each in milliseconds, its decode time the sum of the lengths before it since the stream's + * last initialization segment, which a fragment written as null stands for, and each run's first picture a keyframe, which the viewer is sent first. Each + * delay is the picture's release less its fragment's arrival. + */ +async function delaysOver(arrivals: readonly (readonly [number, number] | null)[]): Promise { + const { at, stream, view } = rig() + const { releases } = view() + const arrived: number[] = [] + let decoded = 0 + let moment = 0 + + stream().write(tierStreamInitialization()) + + for (const arrival of arrivals) { + if (arrival === null) { + stream().write(tierStreamInitialization()) + decoded = 0 + continue + } + + const [time, length] = arrival + + moment = time + await at(moment) + stream().write(fragment({ + keyframe: decoded === 0, + pictureAt: decoded, + pictures: [length], + })) + arrived.push(moment) + decoded += length + } + + await at(moment + 1000) + + expect(releases).toHaveLength(arrived.length) + + return releases.map(({ at: released }, index) => released - arrived[index]) +} + +// A session at home as the table sees it, one packet consumer of a medium joined through a holder of its own: its consumer, whose room a row sets and each +// packet sent takes one of, and the timestamp of each packet it was sent. +interface Session { + readonly consumer: PacketConsumer & { free: number } + readonly hold: TierHold + readonly holder: TierHolder & { tierFailed: Mock<() => void> } + readonly stamps: number[] +} + +// One medium's half of a session at home: its packet consumer and the timestamp of each packet it was sent. +type SessionHalf = Pick + +function sessionHalf(free: number): SessionHalf { + const stamps: number[] = [] + const consumer = { + capacity: Number.POSITIVE_INFINITY, + free, + send: (packet: Buffer): boolean => { + stamps.push(packet.readUInt32BE(4)) + consumer.free-- + + return true + }, + } + + return { consumer, stamps } +} + +function session(table: TierTable, tier: Tier, free: number, medium: StreamTierMedium = 'video'): Session { + const holder = scriptedHolder() + const half = sessionHalf(free) + const hold = table.join(tier, holder, buildEmitterConnection(), [medium], () => half.consumer) + + return { + ...half, + hold, + holder, + } +} + +// A session at home of the picture and the sound, joined in one step through a holder of its own, each half's room given. +function sessionOfBoth(table: TierTable, tier: Tier, free: Readonly>): Record { + const halves = { + audio: sessionHalf(free.audio), + video: sessionHalf(free.video), + } + + table.join(tier, scriptedHolder(), buildEmitterConnection(), ['video', 'audio'], medium => halves[medium].consumer) + + return halves +} + +// A frame consumer of a medium, the picture unless the row names the sound, joined before a row writes anything, which keeps the time in milliseconds of +// each frame it is handed by the timestamp the frame was placed at. A row reads a session's packets by the frames they carry. A frame consumer is handed +// that timestamp whole and a packet carries it in 32 bits, which is why each is kept as a packet carries it, whatever offset the sensor's clock drew. +function placements(table: TierTable, tier: Tier, medium: StreamTierMedium = 'video'): Map { + const placed = new Map() + + table.joinFrames(tier, medium, scriptedHolder(), { + take: (frame, timestamp) => { + placed.set(timestamp % 0x100000000, Math.round(frame.time / 1000)) + }, + }) + + return placed +} + +// The timestamp a placements consumer recorded for the picture of a time, in milliseconds, as a packet carries it. +function stampOf(placed: ReadonlyMap, time: number): number { + return [...placed].find(([, placedTime]) => placedTime === time)![0] +} + +// The highest timestamp a viewer of the live releases was handed by a moment of the row's timeline, the highest its tier's picture was placed at by then. +function highestBy(live: readonly Release[], moment: number): number { + return Math.max(...live.filter(({ at }) => at <= moment).map(({ timestamp }) => timestamp)) +} + +// The moment of the first release a viewer of the live releases was handed whose timestamp stands at or above a given one, the turn whose release the live +// edge first reaches that timestamp in. +function reachedAt(live: readonly Release[], timestamp: number): number | undefined { + return live.find(release => release.timestamp >= timestamp)?.at +} + +/* The pictures of an opening of a stream of pictures a thirtieth of a second apart, from the keyframe of the index given to the picture before the other + * index given, as the rule hands them to a viewer of the picture: each at its timestamp past the highest placed as the opening took its keyframe, in the + * turn whose release first reaches that timestamp, and with the run-opening flag unset. + */ +function stretch(live: readonly Release[], highest: number, from: number, to: number): Release[] { + return Array.from({ length: to - from }, (_picture, index) => { + const timestamp = openingStamp(highest, index * 100 / 3) + + return { + at: reachedAt(live, timestamp)!, + opensRun: false, + time: Math.round((from + index) * 100 / 3), + timestamp, + } + }) +} + +afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() +}) + +describe('tierPacer', () => { + describe('the rule of Mp4FrameFeed', () => { + it('holds each fragment\'s first picture to a target that rises at once to a later arrival, and holds the fragments after it as it falls', async () => { + // A 500 ms picture on its own time, then a 600 ms picture arriving 100 ms late, which raises the target to 100 at once, and then 500 ms pictures on + // their own time again, each held to the target as it falls 1 ms in each half second between arrivals. + expect(await delaysOver([ + [0, 500], + [600, 600], + [1100, 500], + [1600, 500], + ])).toEqual([0, 0, 99, 98]) + }) + + it('lets the target fall 2 ms for each second between arrivals and never below the arrival in hand', async () => { + // A picture arriving 100 ms late raises the target to 100. The next two, on their own time a second apart, are held to 98 and 96. The one after + // arrives 95 ms late, above the 94 the target would fall to, which means it is held to nothing and sets 95. The next is held to 93. + expect(await delaysOver([ + [100, 1100], + [1100, 1000], + [2100, 905], + [3100, 1095], + [4100, 1000], + ])).toEqual([0, 98, 96, 0, 93]) + }) + + it('holds no picture of a stall past the ceiling, and holds the next to the ceiling, 200 ms above the floor, less a second\'s fall', async () => { + expect(await delaysOver([ + [0, 1000], + [1500, 1500], + [2500, 1000], + ])).toEqual([0, 0, 198]) + }) + + it('fades a target the ceiling holds back to the arrivals\' own lateness at its rate of fall', async () => { + const delays = await delaysOver([ + [0, 1000], + [1200, 1200], + ...Array.from({ length: 100 }, (_, second): [number, number] => [2200 + 1000 * second, 1000]), + ]) + + expect(delays).toEqual([ + 0, + 0, + ...Array.from({ length: 100 }, (_, second) => 198 - 2 * second), + ]) + }) + + it.each([ + { counted: 'still sets the floor', delay: 50, gap: 1999 }, + { counted: 'has left the floor\'s window', delay: 149, gap: 2000 }, + ])('reads an arrival $gap ms before the newest as one that $counted', async ({ delay, gap }) => { + // A picture on its own time, then a stall the gap after it, 299 ms late at 1999 ms and 300 ms late at 2000 ms, and half a second on a picture 149 or + // 150 ms late, held to the target the stall left less half a second's fall. + expect(await delaysOver([ + [0, 1700], + [gap, 650], + [gap + 500, 500], + ])).toEqual([0, 0, delay]) + }) + + it('starts the target, the floor and the run\'s first decode time afresh at an initialization segment', async () => { + // A second-long picture on its own time; half a second later a new initialization segment and a picture 500 ms late on the new stream's time; and a + // second after it a picture 50 ms less late, held to the first one's lateness less a second's fall. A rule kept across the segment would hold the + // target to the ceiling above the first arrival, and the last picture would be held to nothing. + expect(await delaysOver([ + [0, 1000], + null, + [500, 1050], + [1500, 1000], + ])).toEqual([0, 0, 48]) + }) + + it('starts the floor afresh at an initialization segment after a quiet gap', async () => { + expect(await delaysOver([ + [0, 100], + null, + [1050, 550], + [1550, 550], + ])).toEqual([0, 0, 49]) + }) + + it('reads every fragment the plugin\'s stream delivers into the target and the floor, a hold of 99.5 ms read at the next whole millisecond', async () => { + // The third picture arrives 400 ms early, which puts that lateness in the floor and holds the target to the ceiling 200 ms above it. A second later + // the fourth, 300 ms early, is held to that target less a second's fall. The fifth arrives past the ceiling. The sixth, 300 ms early again, is + // held to the ceiling the third's lateness still sets, less a quarter second's fall. + expect(await delaysOver([ + [0, 1000], + [1100, 1000], + [1600, 900], + [2600, 200], + [3100, 550], + [3350, 500], + ])).toEqual([0, 0, 200, 98, 0, 100]) + }) + }) + + describe('the schedule', () => { + it('sends a fragment\'s later pictures at their decode times\' distance from its first, its sound at its own distance or at its start, and what a ' + + 'fragment has left at the next fragment\'s start', async () => { + const { at, stream, view } = rig() + const pictures = view('video').releases + const sounds = view('audio').releases + + // A keyframe with its sound on their own time. A second later, 900 ms late, a fragment of pictures a frame apart from 1.1 s with sound from 1.08 s, the + // first sound timed before the fragment's first picture; and 50 ms after it, the next fragment, whose start falls before the last of those pictures is + // due. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictureAt: 1000, + pictures: [100], + soundAt: 1000, + sounds: 1, + })) + await at(1000) + stream().write(fragment({ + pictureAt: 1100, + pictures: [100 / 3, 100 / 3, 100 / 3], + soundAt: 1080, + sounds: 4, + })) + await at(1050) + stream().write(fragment({ + pictureAt: 1200, + pictures: [100], + })) + await at(2000) + + expect(pictures.map(({ at: released, time }) => [time, released])).toEqual([ + [1000, 0], + [1100, 1000], + [1133, 1034], + [1167, 1050], + [1200, 1050], + ]) + expect(sounds.map(({ at: released, time }) => [time, released])).toEqual([ + [1000, 0], + [1080, 1000], + [1100, 1000], + [1120, 1020], + [1140, 1040], + ]) + }) + + it('releases nothing of a fragment written in pieces before its end, and holds the fragment after it to the target its end\'s arrival set', async () => { + const { at, stream, view } = rig() + const { releases } = view() + const spread = fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + soundAt: 100 / 3, + sounds: 1, + }) + + // A fragment of a keyframe whole at 0 ms, one whose picture arrives whole at 33 ms and whose sound, the rest of it, at 133 ms, and one whole at 140 ms. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(33) + stream().write(spread.subarray(0, spread.length - SOUND.length)) + await at(132) + + expect(releases.map(({ at: released }) => released)).toEqual([0]) + + await at(133) + stream().write(spread.subarray(spread.length - SOUND.length)) + await at(140) + stream().write(fragment({ + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + await at(1000) + + // The spread fragment's end arrived 99.7 ms late: the next picture, arriving 73.3 ms late 7 ms after it, is held to that target less what it + // falls in those 7 ms, and leaves at 166.3 ms. + expect(releases.map(({ at: released }) => released)).toEqual([0, 133, 167]) + }) + + it.each([ + { end: 'an initialization segment', marked: false }, + { end: 'a mark inside a fragment\'s media', marked: true }, + ])('starts the rule afresh at $end, what the ended run left leaving first in the next turn and none of it lost', async ({ marked }) => { + const { at, stream, view } = rig() + const { releases } = view() + const cut = fragment({ + pictureAt: 1000, + pictures: [1000 / 3, 1000 / 3], + }) + + // A fragment of pictures a third of a second apart from a keyframe, whose last is due at 667 ms when its run ends at 500 ms. With the mark, the next + // fragment has handed on its first picture alone when the plugin marks the discontinuity inside its media data. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [1000 / 3, 1000 / 3, 1000 / 3], + })) + + if (marked) { + await at(400) + stream().write(cut.subarray(0, cut.length - tierPicture().data.length)) + } + + await at(500) + + if (marked) { + stream().discontinuity() + } else { + stream().write(tierStreamInitialization()) + } + + // The new run opens with a keyframe 500 ms late on its own time, and a second later a picture 50 ms less late is held to that lateness less a second's + // fall. + stream().write(fragment({ + keyframe: true, + pictures: [1050], + })) + await at(1500) + stream().write(fragment({ + pictureAt: 1050, + pictures: [1000], + })) + await at(3000) + + expect(releases.map(({ at: released, opensRun, time }) => [time, released, opensRun])).toEqual([ + [0, 0, true], + [333, 334, false], + [667, 500, false], + ...(marked + ? [ + [1000, 500, false], + ] + : []), + [0, 500, true], + [1050, 1548, false], + ]) + }) + + it('sends a viewer the samples a mark inside a fragment\'s media cuts and what their run has left in the next turn after the mark, with nothing ' + + 'written after it, and opens a run at a fragment written later', async () => { + const { at, stream, view } = rig() + const { releases } = view() + const cut = fragment({ + pictureAt: 1000, + pictures: [1000 / 3, 1000 / 3], + }) + + // A fragment of pictures a third of a second apart from a keyframe, whose last is due at 667 ms; the next fragment's first picture handed on at 400 + // ms; and a mark inside that fragment's media data at 500 ms, after which the stream writes nothing until 2 s, when the next run opens on a keyframe. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [1000 / 3, 1000 / 3, 1000 / 3], + })) + await at(400) + stream().write(cut.subarray(0, cut.length - tierPicture().data.length)) + await at(500) + stream().discontinuity() + await at(1500) + + expect(releases.map(({ at: released, opensRun, time }) => [time, released, opensRun])).toEqual([ + [0, 0, true], + [333, 334, false], + [667, 500, false], + [1000, 500, false], + ]) + + await at(2000) + stream().write(fragment({ + keyframe: true, + pictures: [1000 / 3], + })) + await at(2100) + + expect(releases.slice(4).map(({ at: released, opensRun, time }) => [time, released, opensRun])).toEqual([ + [0, 2000, true], + ]) + }) + + it('sends a viewer what its run has left in the next turn after an initialization segment, with nothing written after it', async () => { + const { at, stream, view } = rig() + const { releases } = view() + + // A fragment of pictures a third of a second apart from a keyframe, whose last is due at 667 ms when a new initialization segment ends its run at 500 + // ms. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [1000 / 3, 1000 / 3, 1000 / 3], + })) + await at(500) + stream().write(tierStreamInitialization()) + await at(600) + + expect(releases.map(({ at: released, time }) => [time, released])).toEqual([ + [0, 0], + [333, 334], + [667, 500], + ]) + }) + + it('holds a fragment whose start falls before the leaving of the fragment before it to that leaving, its later pictures due from there', async () => { + const { at, stream, view } = rig() + const { releases } = view() + + // A keyframe of 100 ms arriving 100 ms late raises the target to 100, and a fragment of three pictures a tick apart, on its own time in the same moment, + // leaves at 200 ms. The next fragment, a tick after them, arrives at 199 ms 99 ms late: its start, 199.8 ms, falls before that leaving, and its + // second picture, 1.1 ms after its first, is due 1.1 ms after 200 ms, at the turn of 202 ms. + stream().write(tierStreamInitialization()) + await at(100) + stream().write(fragment({ + keyframe: true, + pictures: [100], + })) + stream().write(fragment({ + pictureAt: 100, + pictures: [1 / 90, 1 / 90, 1 / 90], + })) + await at(199) + stream().write(fragment({ + pictureAt: 9003 / 90, + pictures: [1.1, 1.1], + })) + await at(1000) + + expect(releases.map(({ at: released, time }) => [time, released])).toEqual([ + [0, 100], + [100, 200], + [100, 200], + [100, 200], + [100, 200], + [101, 202], + ]) + }) + + it('reads no fragment of sound alone into the rule, sending its sound on the schedule of the last fragment of its run that held a picture, or in the ' + + 'next turn before any picture of its run', async () => { + const { at, stream, view } = rig() + const pictures = view('video').releases + const sounds = view('audio').releases + + // A stream cut by duration: a first fragment of a keyframe alone; a fragment of sound alone 30 ms late; and a picture with its sound on its own time. + // Read into the rule, the late fragment of sound would hold the next picture about 23 ms. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(30) + stream().write(fragment({ soundAt: 0, sounds: 2 })) + await at(40) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + soundAt: 40, + sounds: 1, + })) + await at(100) + + // A discontinuity, and a run that opens with a fragment of sound alone, sent in the next turn, and a keyframe after it. + stream().discontinuity() + stream().write(fragment({ soundAt: 1000, sounds: 1 })) + await at(110) + stream().write(fragment({ + keyframe: true, + pictureAt: 1000, + pictures: [100 / 3], + })) + await at(1000) + + expect(pictures.map(({ at: released, time }) => [time, released])).toEqual([ + [0, 0], + [33, 40], + [1000, 110], + ]) + expect(sounds.map(({ at: released, opensRun, time }) => [time, released, opensRun])).toEqual([ + [0, 30, true], + [20, 30, false], + [40, 47, false], + [1000, 100, true], + ]) + }) + }) + + describe('a restart the plugin marks', () => { + it('ends the demand\'s run once at a restart that opens with a fragment of sound alone where the buffer holds no run of sound, and hands a viewer ' + + 'joining before the restart\'s keyframe is released no keyframe of the run before it', async () => { + const { at, stream, view } = rig() + const ends = vi.spyOn(ClockRun.prototype, 'end') + + view() + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(100) + + // The stream carried no sound before the restart, which opens with a fragment of sound alone, sent in the next turn, and a keyframe written later. + stream().discontinuity() + stream().write(fragment({ sounds: 1 })) + await at(110) + + const late = view() + + await at(120) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(300) + + expect(ends).toHaveBeenCalledOnce() + expect(late.releases.map(({ at: released, opensRun, time }) => [time, released, opensRun])).toEqual([ + [0, 120, true], + ]) + }) + + it('ends the buffer\'s run at the first sample its format check lets through after a restart whose first sample it refuses', async () => { + const { at, stream, tier, view } = rig() + const told: string[] = [] + + view() + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(100) + tier.buffer.takePlace({ + displaced: () => undefined, + ending: () => { + told.push('end') + }, + taken: ({ time }) => { + told.push(`picture ${Math.round(time / 1000)}`) + }, + }) + + // The restart's first fragment opens with a picture whose lengths do not tile it, which the format check refuses, and a picture after it. + stream().discontinuity() + stream().write(tierStreamFragment({ + picture: [ + pictureSample(Buffer.alloc(3, 0xA5)), + tierPicture(), + ], + })) + + expect(told).toEqual(['end', 'picture 33']) + expect(tier.buffer.samples).toEqual([]) + }) + }) + + describe('viewers and the timer', () => { + it('arms no timer while no viewer is joined, letting go each sample as it falls due, and arms one for a viewer that joins', async () => { + const { at, stream, table, tier, view } = rig() + // The demand's silence clock, which runs from its first picture beside whatever timer the pacer arms. + const silence = 1 + + // A picture let go as it falls due while the library alone holds the tier, and a keyframe that falls due after a viewer joins, its first picture. + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3], + })) + stream().write(fragment({ + keyframe: true, + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + + expect(vi.getTimerCount()).toBe(silence) + + await at(10) + const { releases } = view() + + expect(vi.getTimerCount()).toBe(silence + 1) + + await at(100) + + expect(releases.map(({ at: released, time }) => [time, released])).toEqual([ + [33, 34], + ]) + expect(vi.getTimerCount()).toBe(silence) + }) + + it('lets each sample of a tier only the library holds go at a fragment\'s end as it falls due: a viewer that joins later is handed the next picture ' + + 'where a run opened at the first fragment\'s arrival places it', async () => { + const { at, stream, table, tier } = rig() + const zero = performance.now() + const stamps: number[] = [] + + // Pictures a third of a second long on their own time: the first two, neither a keyframe, arrive while the library alone holds the tier, which is why a viewer + // joining at 500 ms joins the live releases. The third, a keyframe, arrives after the join. + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [1000 / 3], + })) + await at(1000 / 3) + stream().write(fragment({ + pictureAt: 1000 / 3, + pictures: [1000 / 3], + })) + await at(500) + table.joinFrames(tier, 'video', scriptedHolder(), { + take: (_frame, timestamp) => { + stamps.push(timestamp) + }, + }) + await at(2000 / 3) + stream().write(fragment({ + keyframe: true, + pictureAt: 2000 / 3, + pictures: [1000 / 3], + })) + await at(1000) + + expect(stamps).toEqual([ + tier.context.clock.timestamp('video', zero) + 60000, + ]) + }) + + it('paces a viewer joining a tier the library has held by the target the arrivals before its join set, a late one among them', async () => { + const { at, stream, table, tier, view } = rig() + + // A second-long picture on its own time and a picture 100 ms late while the library alone holds the tier, neither a keyframe, then a viewer, and a + // keyframe on its own time, held to the late one's target less 0.9 s of fall. + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [1000], + })) + await at(1100) + stream().write(fragment({ + pictureAt: 1000, + pictures: [1000], + })) + await at(1500) + const { releases } = view() + await at(2000) + stream().write(fragment({ + keyframe: true, + pictureAt: 2000, + pictures: [1000], + })) + await at(3000) + + expect(releases.map(({ at: released, time }) => [time, released])).toEqual([ + [2000, 2099], + ]) + }) + + it('sends a viewer joining a tier the library has held no sample that fell due before its join', async () => { + const { at, stream, table, tier, view } = rig() + + // Pictures that are no keyframe, each with its sound, fall due while the library alone holds the tier, and a keyframe with its sound arrives after a + // viewer of the picture and the sound joins. The sound, which waits for no keyframe, reads what the join let go as the picture does. + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3], + sounds: 1, + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + soundAt: 100 / 3, + sounds: 1, + })) + await at(50) + const pictures = view('video').releases + const sounds = view('audio').releases + await at(60) + stream().write(fragment({ + keyframe: true, + pictureAt: 200 / 3, + pictures: [100 / 3], + soundAt: 200 / 3, + sounds: 1, + })) + await at(1000) + + expect({ + pictures: pictures.map(({ time }) => time), + sounds: sounds.map(({ time }) => time), + }).toEqual({ + pictures: [67], + sounds: [67], + }) + }) + + it('leaves a sample that fell due before a viewer joins beside one already joined to the turn that releases it, which sends it to both', async () => { + const { at, stream, view } = rig() + const first = view('audio') + + // Pictures a third of a second apart from a keyframe, with sounds of 20 ms from the first picture's time, and a second viewer of the sound, which joins + // the live releases at once, joining in the moment the first sound falls due as it arrives and before the pacer's turn that releases it. A viewer of + // the picture joining in that moment would open from the keyframe that has fallen due, which is why the sound is the medium the turn alone decides. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [1000 / 3, 1000 / 3, 1000 / 3], + sounds: 3, + })) + const second = view('audio') + await at(1000) + + expect([first, second].map(({ releases }) => releases.map(({ at: released, time }) => [time, released]))).toEqual([ + [ + [0, 0], + [20, 20], + [40, 40], + ], + [ + [0, 0], + [20, 20], + [40, 40], + ], + ]) + }) + + it('takes off a packet consumer whose send throws in a release, ending its holder alone, logging it once and throwing nothing from the turn', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { at, stream, table, tier } = rig() + const throwing = scriptedHolder() + const sending = scriptedHolder() + const sent: number[] = [] + const send = vi.fn((): boolean => { + throw new Error('The session\'s socket failed.') + }) + + table.join(tier, throwing, buildEmitterConnection(), ['video'], () => ({ + capacity: Number.POSITIVE_INFINITY, + free: Number.POSITIVE_INFINITY, + send, + })) + table.join(tier, sending, buildEmitterConnection(), ['video'], () => ({ + capacity: Number.POSITIVE_INFINITY, + free: Number.POSITIVE_INFINITY, + send: (packet) => { + sent.push(packet.length) + + return true + }, + })) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(100) + + expect(send).toHaveBeenCalledOnce() + expect(sent).toHaveLength(2) + expect(throwing.tierFailed).toHaveBeenCalledOnce() + expect(sending.tierFailed).not.toHaveBeenCalled() + expect(error).toHaveBeenCalledOnce() + expect(error.mock.calls[0][0]).toContain('A packet consumer of the picture of the video tier 1') + }) + + it('sends a viewer nothing after its hold\'s release, and leaves no timer after the demand\'s end', async () => { + const { at, delegate, stream, table, tier, view } = rig() + const library = table.hold(tier, scriptedHolder()) + const { hold, releases } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(10) + hold.release() + + // The pacer arms nothing for the library's hold, and the one timer left is the demand's silence clock, which the demand's end stops. + expect(vi.getTimerCount()).toBe(1) + + await at(100) + library.release() + await at(200) + + expect(releases.map(({ time }) => time)).toEqual([0]) + expect(endsOf(delegate)).toBe(1) + expect(vi.getTimerCount()).toBe(0) + }) + + it.each([ + { end: 'a withdrawal of its pending start' }, + { end: 'a start refused after a write inside' }, + ])('leaves no timer and no place on the tier\'s buffer after $end', async ({ end }) => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { at, delegate, stream, table, tier, view } = rig() + const pending = deferred() + const fragmentEnds = vi.spyOn(TierPacer.prototype, 'fragmentEnd') + + delegate.tierDemandStarted.mockImplementationOnce(async (written) => { + written.write(tierStreamInitialization()) + written.write(fragment({ + pictures: [100 / 3], + })) + written.write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + + if (end.startsWith('a withdrawal')) { + return pending.promise + } + + throw new Error('The plugin refused the tier.') + }) + + const { hold, releases } = view() + const first = stream() + + if (end.startsWith('a withdrawal')) { + table.withdraw('so the row withdraws it') + } + + await settle() + + expect(tier.demand).toBeUndefined() + expect(vi.getTimerCount()).toBe(0) + + await at(100) + hold.release() + + // A later demand on the tier finds no place of the pacer before it on the tier's buffer, and that pacer is told of nothing more. + view() + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3], + })) + + expect(stream()).not.toBe(first) + expect(fragmentEnds.mock.contexts).toHaveLength(3) + expect(fragmentEnds.mock.contexts[2]).not.toBe(fragmentEnds.mock.contexts[0]) + expect(releases).toEqual([]) + }) + + it('releases nothing from its demand\'s failure on, letting go what waits, and keeps nothing the plugin writes after its own fail', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { at, stream, tier, view } = rig() + const { holder, releases } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + keyframe: true, + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(10) + stream().fail('a synthetic failure') + stream().write(fragment({ + keyframe: true, + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + + expect(vi.getTimerCount()).toBe(0) + + await at(200) + + expect(holder.tierFailed).toHaveBeenCalledOnce() + expect(releases.map(({ time }) => time)).toEqual([0]) + expect(tier.buffer.samples.map(({ time }) => Math.round(time / 1000))).toEqual([33]) + }) + }) + + describe('a viewer\'s first picture', () => { + /* A viewer of the picture from away and one at home, a frame consumer and a session's packet consumer joined in one moment, and what each was handed + * by the time of each picture in milliseconds: the frame consumer's frames by their own times, and the session's packets, one a picture, by the time of + * the picture the demand placed at each packet's timestamp, live or in the opening the frame consumer was handed. + */ + function viewers({ table, tier, view }: Rig): () => { readonly frames: number[], readonly packets: number[] } { + const place = vi.spyOn(ClockRun.prototype, 'place') + const away = view() + const home = session(table, tier, Number.POSITIVE_INFINITY) + + return () => { + const times = new Map() + + for (const [index, [medium, time]] of place.mock.calls.entries()) { + const timestamp = place.mock.results[index].value + + if ((medium === 'video') && (timestamp !== undefined)) { + times.set(timestamp >>> 0, Math.round(time / 1000)) + } + } + + for (const { time, timestamp } of away.releases) { + times.set(timestamp >>> 0, time) + } + + return { + frames: away.releases.map(({ time }) => time), + packets: home.stamps.map(stamp => times.get(stamp)!), + } + } + } + + it('hands a viewer joined before the stream\'s first write, whose first pictures are no keyframe, the first keyframe first and every picture after ' + + 'it', async () => { + const live = rig() + const { at, stream } = live + const handed = viewers(live) + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3, 100 / 3], + })) + stream().write(fragment({ + keyframe: true, + pictureAt: 200 / 3, + pictures: [100 / 3, 100 / 3], + })) + await at(1000) + + expect(handed()).toEqual({ + frames: [67, 100], + packets: [67, 100], + }) + }) + + it('hands a viewer joining once the stream\'s first keyframe has arrived none of the pictures before it the pacer has yet to release', async () => { + const held = rig() + const { at, stream, table, tier } = held + + // While the library alone holds the tier, its first picture falls due as it arrives and opens the run, and the keyframe arrives behind pictures + // the pacer still holds when the viewers join. + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3, 100 / 3, 100 / 3, 100 / 3], + })) + stream().write(fragment({ + keyframe: true, + pictureAt: 400 / 3, + pictures: [100 / 3, 100 / 3], + })) + await at(10) + const handed = viewers(held) + await at(1000) + + expect(handed()).toEqual({ + frames: [133, 167], + packets: [133, 167], + }) + }) + + it.each([ + { restart: 'a mark', start: 0 }, + { restart: 'an initialization segment', start: 0 }, + { restart: 'a jump', start: 10000 }, + ])('hands a live viewer none of a restart\'s pictures before its keyframe at $restart, and every picture from that keyframe on', async ({ restart, start }) => { + const live = rig() + const { at, stream } = live + const handed = viewers(live) + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3, 100 / 3], + })) + await at(100) + + if (restart === 'a mark') { + stream().discontinuity() + } else if (restart === 'an initialization segment') { + stream().write(tierStreamInitialization()) + } + + // The restart's run opens on pictures that are no keyframe, behind the keyframe the viewers were sent in the run before. + stream().write(fragment({ + pictureAt: start, + pictures: [100 / 3, 100 / 3], + })) + stream().write(fragment({ + keyframe: true, + pictureAt: start + 200 / 3, + pictures: [100 / 3, 100 / 3], + })) + await at(1000) + + const restarted = [start + 200 / 3, start + 100].map(time => Math.round(time)) + + expect(handed()).toEqual({ + frames: [0, 33, ...restarted], + packets: [0, 33, ...restarted], + }) + }) + + it('hands a viewer joining in the middle of a run whose buffer keeps no keyframe the pacer has released none of the run\'s pictures before its next ' + + 'keyframe', async () => { + const held = rig() + const { at, stream, table, tier } = held + + // While the library alone holds the tier, a run of pictures that are no keyframe, the second still held when the viewers join, and the next keyframe + // after the join. + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3, 100 / 3], + })) + await at(20) + const handed = viewers(held) + await at(50) + stream().write(fragment({ + keyframe: true, + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + await at(1000) + + expect(handed()).toEqual({ + frames: [67], + packets: [67], + }) + }) + + it('sends a viewer of both media each sound the pacer releases while its picture waits for a keyframe', async () => { + const { at, stream, table, tier, view } = rig() + const away = view('audio').releases + + view('video') + + const home = sessionOfBoth(table, tier, { audio: Number.POSITIVE_INFINITY, video: Number.POSITIVE_INFINITY }) + + // Pictures that are no keyframe with their sounds, and a keyframe and more sounds after them, which means each viewer's picture waits through the first sounds. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3, 100 / 3], + sounds: 3, + })) + stream().write(fragment({ + keyframe: true, + pictureAt: 200 / 3, + pictures: [100 / 3], + soundAt: 60, + sounds: 2, + })) + await at(1000) + + expect(away.map(({ time }) => time)).toEqual([0, 20, 40, 60, 80]) + expect(home.audio.stamps).toEqual(away.map(({ timestamp }) => timestamp >>> 0)) + }) + + it('hands a viewer opened from the buffer and level with the live releases each live picture after its opening, none withheld', async () => { + const held = rig() + const { at, stream, table, tier } = held + + // A keyframe and the pictures after it fall due while the library alone holds the tier. The viewers open from that keyframe, and more pictures + // follow live once their openings are level. + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3, 100 / 3, 100 / 3], + })) + await at(80) + const handed = viewers(held) + await at(100) + stream().write(fragment({ + pictureAt: 100, + pictures: [100 / 3, 100 / 3], + })) + await at(1000) + + expect(handed()).toEqual({ + frames: [0, 33, 67, 100, 133], + packets: [0, 33, 67, 100, 133], + }) + }) + + it('answers a viewer waiting for its first keyframe whose request lands in the turn that keyframe falls due from it, and hands it every live picture ' + + 'once its opening is level, none withheld', async () => { + const { at, stream, table, tier, view } = rig() + + // While the library alone holds the tier, pictures that are no keyframe arrive. The viewer joins and waits, and its request comes in the turn the keyframe + // arrives, which falls due on its arrival: the answer opens it from that keyframe before the keyframe's own live release. + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3, 100 / 3], + })) + await at(50) + const viewer = view() + await at(200 / 3) + stream().write(fragment({ + keyframe: true, + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + const answer = viewer.hold.answerKeyframeRequest() + await at(100) + stream().write(fragment({ + pictureAt: 100, + pictures: [100 / 3, 100 / 3, 100 / 3], + })) + await at(1000) + + expect({ + answer, + handed: viewer.releases.map(({ time }) => time), + }).toEqual({ + answer: 'answered', + handed: [67, 100, 133, 167], + }) + }) + + it('hands a live viewer no picture of a restart whose run a fragment of sound alone opens before that run\'s keyframe', async () => { + const { at, stream, view } = rig() + const viewer = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3, 100 / 3], + })) + await at(100) + + // The mark's run opens on sound: its first pictures, which are no keyframe, are the picture half's first of a run it did not open. + stream().discontinuity() + stream().write(fragment({ + soundAt: 0, + sounds: 2, + })) + await at(110) + stream().write(fragment({ + pictureAt: 40, + pictures: [100 / 3, 100 / 3], + })) + stream().write(fragment({ + keyframe: true, + pictureAt: 40 + 200 / 3, + pictures: [100 / 3], + })) + await at(1000) + + expect(viewer.releases.map(({ time }) => time)).toEqual([0, 33, 107]) + }) + }) + + describe('a shared sensor\'s sound', () => { + // The fixture's first video sensor with its audio shared: its sound tier is the tier the camera records, its best, tier 1. + const SHARED_TIERS = tierSetOf({ + ...FIRST_VIDEO_SENSOR, + audio: { + ...FIRST_VIDEO_SENSOR.audio, + source: 'shared', + }, + }) + + it('hands a consumer of the sound of a tier other than the sound tier nothing while that tier\'s stream carries Opus, its buffer describing no sound ' + + 'and its statistics counting none, and a consumer of the sound tier\'s sound each sound', async () => { + const { at, delegate, table, view } = rig(scriptedTierDelegate(), SHARED_TIERS) + const sounds = view('audio').releases + const other = table.videoTiers.get(2)! + const ignored: number[] = [] + + table.joinFrames(other, 'audio', scriptedHolder(), { + take: (frame) => { + ignored.push(Math.round(frame.time / 1000)) + }, + }) + + const home = session(table, other, Number.POSITIVE_INFINITY, 'audio') + + await at(0) + + // Each tier's stream carries a keyframe, the pictures after it and the sounds beside them, its own Opus track among its tracks. + for (const tierId of [1, 2]) { + const stream = streamsOf(delegate, tierId)[0] + + stream.write(tierStreamInitialization()) + stream.write(fragment({ + keyframe: true, + pictures: [100 / 3, 100 / 3, 100 / 3], + sounds: 5, + })) + } + + await at(1000) + + expect(sounds.map(({ time }) => time)).toEqual([0, 20, 40, 60, 80]) + expect(table.videoTiers.get(1)!.buffer.tracks?.audio).toBeDefined() + expect(ignored).toEqual([]) + expect(home.stamps).toEqual([]) + expect(other.buffer.tracks?.video).toBeDefined() + expect(other.buffer.tracks?.audio).toBeUndefined() + expect(streamsOf(delegate, 2)[0].statistics()).toEqual({ + bytes: 0, + consumers: 2, + drops: 0, + packets: 0, + }) + }) + + it('raises one stream-fault problem for a demand of the sound tier whose stream carries no Opus track, none at a second such initialization segment ' + + 'of that demand, and one again for its next demand', async () => { + const { problems, reporter } = problemsOf() + const delegate = scriptedTierDelegate() + const table = new TierTable(delegate, SHARED_TIERS, options => new TierBuffer(options), reporter) + const soundTier = table.videoTiers.get(1)! + const silent = tierStreamInitialization({ sound: false }) + const { sensorUUID } = SHARED_TIERS + const fault = expect.objectContaining({ + kind: 'stream-fault', + level: 'warning', + sensorUUID, + sentence: `The stream of the video tier 1 of the video sensor "${sensorUUID}" carries no Opus track, though every view of its sensor takes its sound ` + + 'from that stream: no view of its sensor and no recording of the tier has sound.', + tierId: 1, + }) + const first = table.hold(soundTier, scriptedHolder()) + + await settle() + streamsOf(delegate, 1)[0].write(silent) + streamsOf(delegate, 1)[0].write(silent) + + expect(problems).toEqual([fault]) + + first.release() + table.hold(soundTier, scriptedHolder()) + await settle() + streamsOf(delegate, 1)[1].write(silent) + + expect(problems).toEqual([fault, fault]) + }) + + it.each([ + { tier: 'the shared sensor\'s other tier', tierId: 2, tiers: SHARED_TIERS }, + { tier: 'a tier of a sensor stating \'tier\'', tierId: 1, tiers: TIERS }, + ])('raises no problem for $tier whose stream carries no Opus track', async ({ tierId, tiers }) => { + const { problems, reporter } = problemsOf() + const delegate = scriptedTierDelegate() + const table = new TierTable(delegate, tiers, options => new TierBuffer(options), reporter) + + table.hold(table.videoTiers.get(tierId)!, scriptedHolder()) + await settle() + streamsOf(delegate, tierId)[0].write(tierStreamInitialization({ sound: false })) + await settle() + + expect(problems).toEqual([]) + }) + }) + + describe('a view opening from the buffer', () => { + it('opens a viewer joining a tier viewers hold, or one only the library has held, from the latest keyframe released, up to the first picture the pacer ' + + 'holds, then sends it each release', async () => { + for (const held of ['a viewer', 'the library'] as const) { + const { at, stream, table, tier, view } = rig() + const zero = performance.now() + + if (held === 'a viewer') { + view() + } else { + table.hold(tier, scriptedHolder()) + } + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + await at(50) + const { releases } = view() + await at(100) + + // The keyframe and the picture after it fell due before the join. The opening takes its start past the second picture's timestamp in the pacer's + // turn a millisecond on, and the last picture's release reaches every picture of the stretch, which the opening hands with that last picture, + // each at its distance from the keyframe over the opening's speed and with the run-opening flag unset. + const highest = tier.context.clock.timestamp('video', zero) + Math.round(100 / 3 * PICTURE_TICKS) + + expect({ + held, + releases: releases.map(({ at: released, opensRun, time, timestamp }) => [time, released, opensRun, timestamp]), + }).toEqual({ + held, + releases: [0, 100 / 3, 200 / 3].map(time => [ + Math.round(time), + 67, + false, + openingStamp(highest, time), + ]), + }) + } + }) + + it('joins a viewer finding a keyframe whose release has not fallen due to the live releases, and sends it that keyframe at its release', + async () => { + const { at, stream, view } = rig() + + view() + stream().write(tierStreamInitialization()) + + // A second-long picture on its own time and one 100 ms late raise the target, and a keyframe on its own time is held 98 ms past its arrival. + stream().write(fragment({ + pictures: [1000], + })) + await at(1100) + stream().write(fragment({ + pictureAt: 1000, + pictures: [1000], + })) + await at(2000) + stream().write(fragment({ + keyframe: true, + pictureAt: 2000, + pictures: [1000], + })) + await at(2050) + const { releases } = view() + await at(2200) + + expect(releases.map(({ at: released, time }) => [time, released])).toEqual([ + [2000, 2099], + ]) + }) + + it('hands a frame consumer joining a tier whose buffer keeps seconds of pictures since its latest keyframe released those pictures across the live ' + + 'releases that follow, each at the opening\'s timestamp for it and in the turn whose release first reaches that timestamp', async () => { + const { at, stream, view } = rig() + const live = view() + // A picture a thirtieth of a second long, written at its own time, the stream's first and the one at a second each a keyframe. + const picture = async (index: number): Promise => { + await at(index * 100 / 3) + stream().write(fragment({ + keyframe: (index === 0) || (index === 30), + pictureAt: index * 100 / 3, + pictures: [100 / 3], + })) + } + + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 90; index++) { + await picture(index) + } + + await at(2980) + const { releases } = view() + + for (let index = 90; index < 93; index++) { + await picture(index) + } + + await at(3100) + + // The stretch from the keyframe is nearly two seconds: the release at 3000 ms reaches its earlier part alone and the one after it the rest, the + // pictures released by then among them, past which the consumer is level and is handed the live releases. + const opened = stretch(live.releases, highestBy(live.releases, 2981), 30, 92) + + expect(releases).toEqual([ + ...opened, + ...live.releases.slice(92), + ]) + expect([ + ...new Set(opened.map(({ at: released }) => Math.round(released))), + ]).toEqual([3000, 3034]) + }) + + it('joins a frame consumer of the sound to the live releases while one of the picture opens behind, and the sound meets the pictures at the live edge', + async () => { + const { at, stream, table, tier, view } = rig() + + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 10; index++) { + await at(index * 100) + stream().write(fragment({ + keyframe: index === 0, + pictureAt: index * 100, + pictures: [100], + soundAt: index * 100, + sounds: 5, + })) + } + + await at(950) + const pictures = view() + const sounds = view('audio') + await at(1000) + stream().write(fragment({ + pictureAt: 1000, + pictures: [100], + soundAt: 1000, + sounds: 5, + })) + await at(1100) + + // The pictures open from the keyframe at the release of the picture written after the join, the stretch with it, and the sound takes only what + // falls due from its join on, the sounds from 960 ms. + expect(pictures.releases.map(({ at: released, time }) => [time, released])).toEqual(Array.from({ length: 11 }, (_picture, index) => [index * 100, 1000])) + expect(sounds.releases.map(({ at: released, time }) => [time, released])).toEqual([ + [960, 960], + [980, 980], + [1000, 1000], + [1020, 1020], + [1040, 1040], + [1060, 1060], + [1080, 1080], + ]) + }) + + it('opens a viewer of a tier with a prebuffer from its latest keyframe released, not from the head the prebuffer holds', async () => { + const { at, stream, table, tier, view } = rig() + + table.hold(tier, scriptedHolder()) + tier.buffer.span = 5000 + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 3; index++) { + await at(index * 1000) + stream().write(fragment({ + keyframe: true, + pictureAt: index * 1000, + pictures: [1000], + })) + } + + await at(2500) + const { releases } = view() + await at(3000) + stream().write(fragment({ + pictureAt: 3000, + pictures: [1000], + })) + await at(3100) + + // The picture written after the join moves the live edge, whose release hands the opening its keyframe and that picture. + expect(Math.round(tier.buffer.head!.time / 1000)).toBe(0) + expect(releases.map(({ at: released, time }) => [time, released])).toEqual([ + [2000, 3000], + [3000, 3000], + ]) + }) + + it('hands each of two viewers opening in one turn every picture of its opening once, and each release after it once', async () => { + const { at, stream, table, tier, view } = rig() + + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + await at(50) + const views = [ + view(), + view(), + ] + await at(100) + + // Each opening takes its start in the turn a millisecond after the joins, and the release of the last picture reaches the whole stretch. + for (const { releases } of views) { + expect(releases.map(({ at: released, time }) => [time, released])).toEqual([ + [0, 67], + [33, 67], + [67, 67], + ]) + } + }) + + it('carries a session behind the live releases on from the new head keyframe once its release has fallen due as the head moves past its own', async () => { + const { at, stream, table, tier } = rig() + const placed = placements(table, tier) + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(50) + + // A session with no room stays behind, and a keyframe on its own time moves the head past the session's keyframe and falls due as it arrives. + const behind = session(table, tier, 0) + + await at(67) + stream().write(fragment({ + keyframe: true, + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + await at(70) + + expect(behind.stamps).toEqual([]) + + // The opening took its start afresh past the new keyframe as it carried on to it: the picture written after it moves the live edge past the keyframe and itself. + behind.consumer.free = 10 + await at(100) + stream().write(fragment({ + pictureAt: 100, + pictures: [100 / 3], + })) + await at(110) + + expect(behind.stamps).toEqual([200 / 3, 100].map(time => openingStamp(stampOf(placed, 67), time - 200 / 3) % 0x100000000)) + }) + + it('keeps a session behind the live releases as the head moves past its keyframe to one not yet released, sending it nothing until that keyframe\'s ' + + 'release, and opens it from that keyframe given room before it', async () => { + const { at, stream, table, tier } = rig() + const placed = placements(table, tier) + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(50) + + // A session with no room stays behind, and a keyframe timed ahead of its arrival moves the head past the session's keyframe before it falls due at + // 67 ms. + const behind = session(table, tier, 0) + + await at(55) + stream().write(fragment({ + keyframe: true, + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + await at(60) + behind.consumer.free = 10 + await at(66) + + expect(behind.stamps).toEqual([]) + + // The opening takes its start afresh past the new keyframe in the turn of its release: the picture written after it moves the live edge past the + // keyframe and itself. + await at(100) + stream().write(fragment({ + pictureAt: 100, + pictures: [100 / 3], + })) + await at(110) + + expect(behind.stamps).toEqual([200 / 3, 100].map(time => openingStamp(stampOf(placed, 67), time - 200 / 3) % 0x100000000)) + }) + + it('sends a session of both media handed its keyframe alone no later picture of the stretch it opened on once the head moves to a keyframe not yet ' + + 'released, its sound joining the live releases, and opens its picture from that keyframe at its release', async () => { + const { at, stream, table, tier } = rig() + const pictures = placements(table, tier) + const sounds = placements(table, tier, 'audio') + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + sounds: 2, + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + soundAt: 40, + sounds: 1, + })) + await at(45) + + // The session's picture has room for its keyframe alone and its sound for nothing, which a live release sends all the same. A picture of the stretch + // timed ahead of its arrival falls due at 67 ms with a sound at 80 ms and moves the live edge to the keyframe alone, and a keyframe timed ahead of its + // arrival moves the head past the session's keyframe and falls due at 100 ms with its sounds. + const behind = sessionOfBoth(table, tier, { audio: 0, video: 1 }) + + await at(50) + stream().write(fragment({ + pictureAt: 200 / 3, + pictures: [100 / 3], + soundAt: 80, + sounds: 1, + })) + await at(70) + stream().write(fragment({ + keyframe: true, + pictureAt: 100, + pictures: [100 / 3], + soundAt: 100, + sounds: 2, + })) + await at(75) + behind.video.consumer.free = 10 + behind.audio.consumer.free = 10 + + // A picture written after the new keyframe moves the live edge to it. + await at(110) + stream().write(fragment({ + pictureAt: 400 / 3, + pictures: [100 / 3], + })) + await at(200) + + expect(behind.video.stamps).toEqual([ + openingStamp(stampOf(pictures, 33), 0) % 0x100000000, + openingStamp(stampOf(pictures, 100), 0) % 0x100000000, + openingStamp(stampOf(pictures, 100), 100 / 3) % 0x100000000, + ]) + expect(behind.audio.stamps.map(stamp => sounds.get(stamp))).toEqual([80, 100, 120]) + }) + + it('runs no turn a millisecond on for a session waiting for the next keyframe\'s release, its turns at the samples\' due moments alone', async () => { + const { at, stream, table, tier, view } = rig() + const zero = performance.now() + + view() + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(50) + + // The session's opening takes its start in the turn a millisecond after its join, at 51 ms, and is handed nothing, since no picture is released after + // that turn before the head moves past its keyframe. A picture of its stretch falls due at 67 ms, and a keyframe timed ahead of its arrival moves the + // head past the session's keyframe at 56 ms and falls due at 100 ms. The session waits for that keyframe's release and runs no turn of its own. + session(table, tier, 1) + await at(55) + stream().write(fragment({ + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + await at(56) + stream().write(fragment({ + keyframe: true, + pictureAt: 100, + pictures: [100 / 3], + })) + await at(57) + + const turns: number[] = [] + + while (performance.now() - zero < 100) { + await vi.advanceTimersToNextTimerAsync() + turns.push(Math.round(performance.now() - zero)) + } + + expect(turns).toEqual([67, 100]) + }) + + it('sends a session nothing after it leaves between two turns of its opening, nor after a failure, and at a mark until the restart\'s first keyframe opens it', + async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + for (const cut of ['a leave', 'a failure', 'a mark'] as const) { + const { at, stream, table, tier } = rig() + const placed = placements(table, tier) + + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 3; index++) { + stream().write(fragment({ + keyframe: index === 0, + pictureAt: index * 100 / 3, + pictures: [100 / 3], + })) + } + + await at(90) + + // The session's room takes one picture until the row gives it more, and a picture timed ahead of its arrival moves the live edge at 100 ms. + const behind = session(table, tier, 1) + const opened = openingStamp(stampOf(placed, 67), 0) % 0x100000000 + + await at(95) + stream().write(fragment({ + pictureAt: 100, + pictures: [100 / 3], + })) + await at(101) + + expect(behind.stamps).toEqual([opened]) + + if (cut === 'a leave') { + behind.hold.release() + } else if (cut === 'a failure') { + stream().fail('a synthetic failure') + } else { + stream().discontinuity() + stream().write(fragment({ + pictureAt: 1000, + pictures: [100 / 3], + })) + } + + behind.consumer.free = 10 + await at(110) + + // What the session was sent while it waits through a restart. + let waiting: number[] | undefined + let reopened: number[] = [] + + if (cut === 'a mark') { + // The restart opens with pictures that are no keyframe, through which the session is sent nothing, and its first keyframe opens the session + // at its release, its timestamps starting afresh, which the picture written after it moves the live edge to. + await at(150) + stream().write(fragment({ + pictureAt: 1000 + 100 / 3, + pictures: [100 / 3], + })) + await at(200) + waiting = [...behind.stamps] + stream().write(fragment({ + keyframe: true, + pictureAt: 1000 + 200 / 3, + pictures: [100 / 3], + })) + await at(250) + stream().write(fragment({ + pictureAt: 1100, + pictures: [100 / 3], + })) + await at(400) + reopened = [0, 100 / 3].map(distance => openingStamp(stampOf(placed, 1067), distance) % 0x100000000) + } + + expect({ + cut, + waiting, + sent: behind.stamps, + failed: behind.holder.tierFailed.mock.calls.length, + }).toEqual({ + cut, + waiting: (cut === 'a mark') + ? [opened] + : undefined, + sent: [opened, ...reopened], + failed: (cut === 'a failure') + ? 1 + : 0, + }) + // The pacer leaves no timer, and the demand's silence clock stands while it serves the viewer it keeps, a failure stopping it. + expect(vi.getTimerCount()).toBe((cut === 'a failure') + ? 0 + : 1) + } + }) + + it('keeps a session of both media handed part of its stretch behind, sending its picture nothing more once a ceiling leaves the buffer no keyframe, ' + + 'however many turns pass, while its sound joins the live releases, and opens its picture from the next keyframe at its release', async () => { + const { at, stream, table, tier } = rig() + const pictures = placements(table, tier) + const sounds = placements(table, tier, 'audio') + // A fragment of one picture that is no keyframe, half a second long, and its sound, written at its own time. + const picture = async (time: number): Promise => { + await at(time) + stream().write(fragment({ + pictureAt: time, + pictures: [500], + soundAt: time, + sounds: 1, + })) + } + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [500], + sounds: 1, + })) + await picture(500) + await picture(1000) + await at(1050) + + // The session's picture is handed the keyframe alone of the three pictures released, at the release of the first picture written after its join, + // and its sound joins the live releases. The picture of 10.5 seconds carries the buffer past its reach ceiling, which drops every sample, the + // session's keyframe among them. + const behind = sessionOfBoth(table, tier, { audio: 0, video: 1 }) + const opened = openingStamp(stampOf(pictures, 1000), 0) % 0x100000000 + + for (let time = 1500; time <= 10500; time += 500) { + await picture(time) + } + + expect(tier.buffer.samples).toEqual([]) + + behind.video.consumer.free = 10 + behind.audio.consumer.free = 10 + + // More than a second passes after the drop, the turns of its pictures reading the session's opening. + for (let time = 11000; time <= 12000; time += 500) { + await picture(time) + } + + await at(12100) + + // Each sound the session was sent from its join on, by its time in milliseconds. + const sent = (until: number): number[] => Array.from({ length: (until - 1500) / 500 + 1 }, (_sound, index) => 1500 + index * 500) + + expect([ + behind.video.stamps, + behind.audio.stamps.map(stamp => sounds.get(stamp)), + ]).toEqual([ + [opened], + sent(12000), + ]) + + // The next keyframe opens the picture at its release, its timestamps starting afresh, and the picture written after it moves the live edge past the + // keyframe and itself. + await at(12500) + stream().write(fragment({ + keyframe: true, + pictureAt: 12500, + pictures: [500], + soundAt: 12500, + sounds: 1, + })) + await picture(13000) + await at(13100) + + expect([ + behind.video.stamps, + behind.audio.stamps.map(stamp => sounds.get(stamp)), + ]).toEqual([ + [ + opened, + ...[0, 500].map(distance => openingStamp(stampOf(pictures, 12500), distance) % 0x100000000), + ], + sent(13000), + ]) + }) + + it('takes off a packet consumer and a frame consumer that each throw in an opening, ending each holder alone, logging each once, handing the ' + + 'consumers beside them their openings and throwing nothing from the turn', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { at, stream, table, tier, view } = rig() + const placed = placements(table, tier) + const packets = scriptedHolder() + const frames = scriptedHolder() + + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 3; index++) { + stream().write(fragment({ + keyframe: index === 0, + pictureAt: index * 100 / 3, + pictures: [100 / 3], + })) + } + + await at(100) + + // Each consumer joins behind the live releases, a throwing one of each kind before one that takes what it is handed. + table.join(tier, packets, buildEmitterConnection(), ['video'], () => ({ + capacity: Number.POSITIVE_INFINITY, + free: Number.POSITIVE_INFINITY, + send: () => { + throw new Error('The session\'s socket failed.') + }, + })) + table.joinFrames(tier, 'video', frames, { + take: () => { + throw new Error('The engine\'s session failed.') + }, + }) + + const beside = session(table, tier, 10) + const { releases } = view() + + // A picture written after the joins moves the live edge to every opening's stretch. + await at(150) + stream().write(fragment({ + pictureAt: 150, + pictures: [100 / 3], + })) + + await expect(at(200)).resolves.toBeUndefined() + + expect([packets.tierFailed.mock.calls.length, frames.tierFailed.mock.calls.length]).toEqual([1, 1]) + expect(error.mock.calls.map(([line]) => String(line).split(' of the ')[0])).toEqual(['A packet consumer', 'A frame consumer']) + expect(beside.stamps).toEqual([0, 100 / 3, 200 / 3, 150].map(time => openingStamp(stampOf(placed, 67), time) % 0x100000000)) + expect(releases.map(({ time }) => time)).toEqual([0, 33, 67, 150]) + }) + + it('opens nothing for a session joining a failed demand its viewers still hold, sending it nothing', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { at, stream, table, tier, view } = rig() + const { holder } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(50) + stream().fail('a synthetic failure') + + expect(holder.tierFailed).toHaveBeenCalledOnce() + + const late = session(table, tier, 10) + const frames = view() + await at(200) + + expect(await late.hold.answer()).toBe('refused') + expect(late.stamps).toEqual([]) + expect(frames.releases).toEqual([]) + }) + + it('stamps a view\'s opening past the highest timestamp its tier has placed, at home and from away, each picture at its distance from the keyframe ' + + 'over the opening\'s speed and handed once the live edge reaches it, the first live picture after it standing above them all', async () => { + const { at, stream, table, tier, view } = rig() + const zero = performance.now() + const live = view() + const sent: { readonly at: number, readonly stamp: number }[] = [] + // A picture a tenth of a second long written at its own time, the first a keyframe and the third presented 50 ms after its decode time. + const picture = async (index: number): Promise => { + await at(index * 100) + stream().write(tierStreamFragment({ + picture: [ + { + ...tierPicture({ inBand: true, keyframe: index === 0 }), + compositionOffset: (index === 2) + ? 50 * PICTURE_TICKS + : 0, + duration: 100 * PICTURE_TICKS, + }, + ], + pictureTime: BigInt(index * 100 * PICTURE_TICKS), + })) + } + + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 4; index++) { + await picture(index) + } + + await at(350) + table.join(tier, scriptedHolder(), buildEmitterConnection(), ['video'], () => ({ + capacity: Number.POSITIVE_INFINITY, + free: Number.POSITIVE_INFINITY, + send: (packet) => { + sent.push({ + at: performance.now() - zero, + stamp: packet.readUInt32BE(4), + }) + + return true + }, + })) + + const { releases } = view() + + await picture(4) + await picture(5) + await at(600) + + // Each opening takes its start in its turn a millisecond after the joins, past the picture released at 300 ms, and the release at 400 ms reaches its + // whole stretch, that picture with it, which is why each consumer is handed the stretch in that turn and then the live releases. + const highest = highestBy(live.releases, 351) + const opened = [0, 100, 250, 300, 400].map((time): Release => { + const timestamp = openingStamp(highest, time) + + return { + at: reachedAt(live.releases, timestamp)!, + opensRun: false, + time, + timestamp, + } + }) + const following = live.releases[5] + + expect(releases).toEqual([...opened, following]) + expect(sent).toEqual([...opened, following].map(({ at: released, timestamp }) => ({ at: released, stamp: timestamp % 0x100000000 }))) + expect(releases.slice(0, opened.length).every(({ at: released, timestamp }) => timestamp <= highestBy(live.releases, released))).toBe(true) + expect(following.timestamp).toBeGreaterThan(Math.max(...opened.map(({ timestamp }) => timestamp))) + }) + + it('joins the sound of a session of both media and a frame consumer of the sound to the live releases at once while the session\'s picture opens, ' + + 'sending each its sound from its join on and none of the sound the buffer kept', async () => { + const { at, stream, table, tier, view } = rig() + const pictures = placements(table, tier) + const sounds = placements(table, tier, 'audio') + + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 10; index++) { + await at(index * 100) + stream().write(fragment({ + keyframe: index === 0, + pictureAt: index * 100, + pictures: [100], + soundAt: index * 100, + sounds: 5, + })) + } + + await at(950) + const both = sessionOfBoth(table, tier, { audio: 100, video: 100 }) + const frames = view('audio') + await at(1000) + stream().write(fragment({ + pictureAt: 1000, + pictures: [100], + soundAt: 1000, + sounds: 5, + })) + await at(1100) + + // The sound falls due 20 ms apart, which means each consumer of it is sent the sound from 960 ms, the first to fall due after the joins. The session's + // picture opens from the keyframe at the release of the picture written after the joins. + const fromJoin = [960, 980, 1000, 1020, 1040, 1060, 1080] + + expect(both.audio.stamps.map(stamp => sounds.get(stamp))).toEqual(fromJoin) + expect(frames.releases.map(({ time }) => time)).toEqual(fromJoin) + expect(both.video.stamps).toEqual(Array.from({ length: 11 }, (_picture, index) => openingStamp(stampOf(pictures, 900), index * 100) % 0x100000000)) + }) + + it('carries an opening on from a keyframe that arrives inside it on a tier with no prebuffer, at that keyframe\'s release, its timestamps starting ' + + 'afresh past the highest timestamp placed then and no picture of the older stretch sent after it', async () => { + const { at, stream, view } = rig() + const live = view() + // A picture a thirtieth of a second long, written at its own time, the first and the one at two seconds keyframes. + const picture = async (index: number): Promise => { + await at(index * 100 / 3) + stream().write(fragment({ + keyframe: (index % 60) === 0, + pictureAt: index * 100 / 3, + pictures: [100 / 3], + })) + } + + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 59; index++) { + await picture(index) + } + + await at(1950) + const { releases } = view() + + for (let index = 59; index < 63; index++) { + await picture(index) + } + + await at(2100) + + // The release at 1967 ms reaches the earlier part of the opening's stretch alone. The keyframe at two seconds moves the buffer's head past the + // opening's keyframe as it arrives: the opening carries on from it at its release, its start taken past that keyframe's own timestamp, and the + // picture after it moves the live edge past the keyframe and itself. + const older = stretch(live.releases, highestBy(live.releases, 1951), 0, 60).filter(({ at: released }) => released < 2000) + const carried = highestBy(live.releases, live.releases.find(({ time }) => time === 2000)!.at) + const newer = [0, 100 / 3].map((distance): Release => { + const timestamp = openingStamp(carried, distance) + + return { + at: reachedAt(live.releases, timestamp)!, + opensRun: false, + time: Math.round(2000 + distance), + timestamp, + } + }) + + expect(older.length).toBeGreaterThan(0) + expect(releases).toEqual([ + ...older, + ...newer, + live.releases[62], + ]) + }) + + it('opens a view again from the restart\'s keyframe at its release after a mark inside its opening, sending nothing of the old run after the mark, its ' + + 'timestamps starting afresh past the highest timestamp placed then and each above every one it was sent before', async () => { + const { at, stream, view } = rig() + const live = view() + // A picture a thirtieth of a second long, written at its own time, the first a keyframe. + const picture = async (index: number): Promise => { + await at(index * 100 / 3) + stream().write(fragment({ + keyframe: index === 0, + pictureAt: index * 100 / 3, + pictures: [100 / 3], + })) + } + + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 59; index++) { + await picture(index) + } + + await at(1950) + const { releases } = view() + + // A picture whose release at 1967 ms reaches the earlier part of the opening's stretch alone, a mark after it, and a restart whose times fall back to + // half a second, its keyframe and a picture after it. + await picture(59) + await at(1980) + stream().discontinuity() + await at(1990) + stream().write(fragment({ + keyframe: true, + pictureAt: 500, + pictures: [100 / 3], + })) + await at(2030) + stream().write(fragment({ + pictureAt: 500 + 100 / 3, + pictures: [100 / 3], + })) + await at(2200) + + const older = stretch(live.releases, highestBy(live.releases, 1951), 0, 60).filter(({ at: released }) => released < 1980) + const restart = live.releases.findLast(({ time }) => time === 500)! + const carried = highestBy(live.releases, restart.at) + + expect(older.length).toBeGreaterThan(0) + expect(releases.map(({ at: released, time, timestamp }) => [time, timestamp, released >= 1980])).toEqual([ + ...older.map(({ time, timestamp }) => [time, timestamp, false]), + [ + 500, + openingStamp(carried, 0), + true, + ], + [ + 533, + openingStamp(carried, 100 / 3), + true, + ], + ]) + expect(releases.every(({ timestamp }, index) => (index === 0) || (timestamp > releases[index - 1].timestamp))).toBe(true) + }) + + it('runs one turn a millisecond after an opening is made and no other for a frame consumer\'s, its turns after it at the samples\' due moments alone, ' + + 'and a turn a millisecond on after each of a session\'s that its room holds back', async () => { + const opens = vi.spyOn(DemandHalf.prototype, 'open') + + for (const kind of ['frames', 'packets'] as const) { + const { at, stream, table, tier, view } = rig() + const zero = performance.now() + + opens.mockClear() + table.hold(tier, scriptedHolder()) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100], + })) + await at(100) + stream().write(fragment({ + pictureAt: 100, + pictures: [100], + })) + await at(150) + + // A frame consumer, or a session with room for one picture until the row gives it more at 205 ms, and pictures written at their own time, falling + // due at 200 and 300 ms. + const behind = (kind === 'packets') + ? session(table, tier, 1) + : view() + const { video } = tier.demand!.halves + + await at(200) + stream().write(fragment({ + pictureAt: 200, + pictures: [100], + })) + await at(205) + + if ('consumer' in behind) { + behind.consumer.free = 10 + } + + await at(300) + stream().write(fragment({ + pictureAt: 300, + pictures: [100], + })) + await at(400) + + // The moment of each turn that handed the picture's openings, read from the half's calls. + const turns = opens.mock.contexts.flatMap((half, index) => (half === video) + ? [ + Math.round(opens.mock.calls[index][0] - zero), + ] + : []) + + expect({ kind, turns }).toEqual({ + kind, + turns: (kind === 'packets') + ? [ + 151, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 300, + ] + : [151, 200, 300], + }) + } + }) + + it('opens a viewer joining a fresh demand between its first keyframe\'s due moment and the turn that releases it on finite timestamps, the first one ' + + 'millisecond past that keyframe\'s own', async () => { + const { at, stream, view } = rig() + const first = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + + // The keyframe has fallen due and the pacer's turn has not yet released it. The demand's run has placed no picture. + const second = view() + + await at(100 / 3) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(100) + + expect(second.releases.every(({ timestamp }) => Number.isFinite(timestamp))).toBe(true) + expect(second.releases.map(({ time, timestamp }) => [time, timestamp])).toEqual([ + [ + 0, + openingStamp(first.releases[0].timestamp, 0), + ], + [ + 33, + openingStamp(first.releases[0].timestamp, 100 / 3), + ], + ]) + }) + + it('hands an opening its keyframe in the turn that releases the first picture written after its join, one millisecond past the highest timestamp ' + + 'placed before that picture, and nothing while no picture follows its join', async () => { + for (const written of [true, false]) { + const { at, stream, view } = rig() + const live = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + stream().write(fragment({ + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(50) + const { releases } = view() + await at(60) + + if (written) { + stream().write(fragment({ + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + } + + await at(200) + + expect({ + written, + first: releases.slice(0, 1).map(({ at: released, time, timestamp }) => [time, released, timestamp]), + }).toEqual({ + written, + first: written + ? [ + [ + 0, + live.releases[2].at, + openingStamp(highestBy(live.releases, 50), 0), + ], + ] + : [], + }) + } + }) + }) + + describe('a viewer\'s keyframe request', () => { + it('opens nothing, adds nothing and throws nothing at a hold\'s keyframe entry after the hold\'s release, after its demand\'s failure, or for a ' + + 'consumer taken off after a throw whose hold is not yet released', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + + for (const cut of ['a release', 'a failure', 'a throw'] as const) { + const { at, stream, table, tier } = rig() + const take = vi.fn((): void => { + if (cut === 'a throw') { + throw new Error('The viewer\'s stream failed.') + } + }) + + table.hold(tier, scriptedHolder()) + + const hold = table.joinFrames(tier, 'video', scriptedHolder(), { take }) + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(50) + + if (cut === 'a release') { + hold.release() + } else if (cut === 'a failure') { + stream().fail('a synthetic failure') + } + + // The consumer took the keyframe live, or threw at it and was taken off, before the entry is called, and a picture written after it would move the + // live edge past an opening the entry made. + const consumers = tier.demand?.statistics().consumers + const taken = take.mock.calls.length + + expect(() => hold.answerKeyframeRequest()).not.toThrow() + + stream().write(fragment({ + pictureAt: 100, + pictures: [100 / 3], + })) + await at(200) + + expect({ cut, consumers: tier.demand?.statistics().consumers, taken: take.mock.calls.length - taken }).toEqual({ cut, consumers, taken: 0 }) + } + }) + + it('calls no requestKeyframe a delegate still carries at a picture join into a running tier whose buffer keeps no keyframe, at an opening whose ' + + 'keyframe the buffer lets go with none kept, or at a viewer\'s request with no keyframe released, each picture starting at the stream\'s next keyframe', + async () => { + for (const cut of ['a join', 'an opening', 'a request'] as const) { + // A delegate that still carries a requestKeyframe method, held as a plain object, since the delegate's interface names none. + const requestKeyframe = vi.fn<(sensorUUID: string, tierId: number) => void>() + const delegate = { + ...scriptedTierDelegate(), + requestKeyframe, + } + const { at, stream, table, tier, view } = rig(delegate) + let handed: number[] + let expected: number[] + + if (cut === 'an opening') { + // A session with room for one picture opens from a keyframe, which a picture timed ahead of its arrival moves the live edge to, and a mark + // whose restart opens with pictures that are no keyframe leaves the buffer none. The opening waits until the restart's keyframe opens it. + const placed = placements(table, tier) + + stream().write(tierStreamInitialization()) + + for (let index = 0; index < 3; index++) { + stream().write(fragment({ + keyframe: index === 0, + pictureAt: index * 100 / 3, + pictures: [100 / 3], + })) + } + + await at(90) + const behind = session(table, tier, 1) + await at(95) + stream().write(fragment({ + pictureAt: 100, + pictures: [100 / 3], + })) + await at(101) + stream().discontinuity() + stream().write(fragment({ + pictureAt: 1000, + pictures: [100 / 3], + })) + behind.consumer.free = 10 + await at(150) + stream().write(fragment({ + pictureAt: 1000 + 100 / 3, + pictures: [100 / 3], + })) + await at(200) + stream().write(fragment({ + keyframe: true, + pictureAt: 1000 + 200 / 3, + pictures: [100 / 3], + })) + await at(250) + stream().write(fragment({ + pictureAt: 1100, + pictures: [100 / 3], + })) + await at(400) + handed = behind.stamps + expected = [ + openingStamp(stampOf(placed, 67), 0) % 0x100000000, + ...[0, 100 / 3].map(distance => openingStamp(stampOf(placed, 1067), distance) % 0x100000000), + ] + } else { + // The library holds the tier, whose stream has started and written a picture that is no keyframe, let go as it falls due before the viewer + // joins, and the viewer, joined to the live releases, makes its request before the stream's next keyframe. + table.hold(tier, scriptedHolder()) + await settle() + stream().write(tierStreamInitialization()) + stream().write(fragment({ + pictures: [100 / 3], + })) + await at(10) + const { hold, releases } = view() + + if (cut === 'a request') { + hold.answerKeyframeRequest() + } + + await at(100 / 3) + stream().write(fragment({ + keyframe: true, + pictureAt: 100 / 3, + pictures: [100 / 3], + })) + await at(200 / 3) + stream().write(fragment({ + pictureAt: 200 / 3, + pictures: [100 / 3], + })) + await at(200) + handed = releases.map(({ time }) => time) + expected = [33, 67] + } + + expect({ cut, asked: requestKeyframe.mock.calls.length, handed }).toEqual({ cut, asked: 0, handed: expected }) + } + }) + + it('answers what each request came to: answered, answered from this keyframe already, in an opening, no keyframe kept, and stopped for a released ' + + 'hold, a hold with no picture join, a consumer taken off and a stopped pacer', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + + // A viewer of the live releases, joined while the buffer keeps nothing, a hold alone, a consumer of the picture that throws at the first picture it + // takes, which takes it off with its hold left unreleased, and a viewer whose hold is released. + const { at, stream, table, tier, view } = rig() + const live = view() + const alone = table.hold(tier, scriptedHolder()) + const thrown = table.joinFrames(tier, 'video', scriptedHolder(), { + take: () => { + throw new Error('The viewer\'s stream failed.') + }, + }) + const released = view() + + released.hold.release() + + const unkept = live.hold.answerKeyframeRequest() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(50) + + // A viewer that joins once the keyframe is released opens on it, and its opening waits on a live picture nobody writes: the buffer keeps a + // released keyframe neither it nor the consumer taken off was answered from. + const behind = view() + + await at(60) + + const answers = { + alone: alone.answerKeyframeRequest(), + behind: behind.hold.answerKeyframeRequest(), + live: [ + live.hold.answerKeyframeRequest(), + live.hold.answerKeyframeRequest(), + ], + released: released.hold.answerKeyframeRequest(), + thrown: thrown.answerKeyframeRequest(), + unkept, + } + + stream().fail('a synthetic failure') + + expect({ + ...answers, + failed: behind.hold.answerKeyframeRequest(), + }).toEqual({ + alone: 'stopped', + behind: 'in an opening', + failed: 'stopped', + live: [ + 'answered', + 'answered from this keyframe already', + ], + released: 'stopped', + thrown: 'stopped', + unkept: 'no keyframe kept', + }) + }) + }) + + describe('what a start registers and its signal', () => { + // The sentence a start's settled value other than undefined is logged under, and the one a failed cleanup is logged under. + const VALUE_LINE = `MultiTierStreamingDelegate answered tierDemandStarted for the video tier 1 of the video sensor "${TIERS.sensorUUID}" with a value, which the ` + + 'library does not read, and nothing is released for it.' + const END_FAILURE = 'MultiTierStreamingDelegate failed to end a tier demand: ' + + // The lines a log took under a sentence. + const linesUnder = (log: MockInstance, sentence: string): number => log.mock.calls.filter(([line]) => String(line).startsWith(sentence)).length + + // A start that answers a value, which the delegate's type refuses and a plugin written in JavaScript can still do. + const answering = (value: unknown): MultiTierStreamingDelegate['tierDemandStarted'] => (async () => value) as MultiTierStreamingDelegate['tierDemandStarted'] + + it('releases what a start registered once in the end its last hold\'s release makes, inside that release, the demand ended in the cleanup while its tier ' + + 'still holds it and its buffer keeps its sample, and nothing more at a later release or reset', async () => { + const { delegate, stream, table, tier, view } = rig() + const inside: unknown[] = [] + + delegate.tierDemandStarted.mockImplementationOnce(async (written) => { + written.defer(() => { + inside.push([(written as TierDemand).state, tier.demand === written, tier.buffer.samples.length]) + }) + }) + + const { hold } = view() + + await settle() + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + + expect(tier.buffer.samples).toHaveLength(1) + + hold.release() + + expect(inside).toEqual([ + [ + 'ended', + true, + 1, + ], + ]) + + await settle() + hold.release() + table.withdraw(WITHDRAWAL) + await settle() + + expect([inside.length, tier.demand, tier.buffer.samples.length]).toEqual([1, undefined, 0]) + }) + + it('releases what a pending start registered once its holds have all left and it settles, and nothing for an ending demand a join takes back until ' + + 'that join\'s release', async () => { + const { delegate, stream, view } = rig() + const read = (): [string, number] => [ + (stream() as TierDemand).state, + disposedOf(delegate, stream()), + ] + + // Every hold leaves while the start is pending, and the start then settles. + const ending = pendingStart(delegate) + + view().hold.release() + await settle() + + expect(read()).toEqual(['ending', 0]) + + ending.resolve() + await settle() + + expect(read()).toEqual(['ended', 1]) + + // An ending demand a join takes back, which starts and then ends at that join's release. + const pending = pendingStart(delegate) + + view().hold.release() + + const joining = view() + + pending.resolve() + await settle() + + expect(read()).toEqual(['started', 0]) + + joining.hold.release() + await settle() + + expect(read()).toEqual(['ended', 1]) + }) + + it.each([ + { refusal: 'rejects' }, + { refusal: 'throws' }, + ])('releases what a start registered before it $refusal once, in its refusal, the demand ended in the cleanup while its tier still holds it, and refuses ' + + 'its hold', async ({ refusal }) => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, stream, tier, view } = rig() + const inside: unknown[] = [] + const failing = deferred() + + // A start that throws does so in its own call, before any wait, and one that rejects does so once the row rejects its wait. + delegate.tierDemandStarted.mockImplementationOnce((written) => { + written.defer(() => { + inside.push([(written as TierDemand).state, tier.demand === written]) + }) + + if (refusal === 'throws') { + throw new Error('The encoder would not start.') + } + + return failing.promise + }) + + const { hold } = view() + + if (refusal === 'rejects') { + failing.reject(new Error('The encoder would not start.')) + } + + await settle() + + expect([ + inside, + hold.started, + (stream() as TierDemand).state, + tier.demand, + ]).toEqual([ + [ + [ + 'ended', + true, + ], + ], + false, + 'ended', + undefined, + ]) + }) + + it.each([ + { cut: 'its bound' }, + { cut: 'a reset' }, + ])('aborts a start still pending at $cut and then releases what it registered, in that one withdrawal, the abort before the release', async ({ cut }) => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { at, delegate, stream, table, view } = rig() + + fakeTimeoutSignals() + pendingStart(delegate) + view() + + const withdrawn = stream() + + await at(DELEGATE_CALL_TIMEOUT - 1) + + expect([ + disposedOf(delegate, withdrawn), + signalOf(delegate, withdrawn).aborted, + ]).toEqual([0, false]) + + if (cut === 'a reset') { + table.withdraw(WITHDRAWAL) + } else { + await at(DELEGATE_CALL_TIMEOUT) + } + + const [aborted] = delegate.aborts.get(withdrawn)!.mock.invocationCallOrder + const [released] = delegate.disposals.get(withdrawn)!.mock.invocationCallOrder + + expect([ + (withdrawn as TierDemand).state, + delegate.aborts.get(withdrawn)!.mock.calls.length, + disposedOf(delegate, withdrawn), + aborted < released, + ]).toEqual(['ended', 1, 1, true]) + }) + + it('releases in a microtask of its own what a start withdrawn while pending registers after, the line after the registration first, releases nothing ' + + 'more at its settling, and logs the value it settles with once', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, table, view } = rig() + const pending = deferred() + const order: string[] = [] + const early = vi.fn<() => void>(() => { + order.push('early released') + }) + const late = vi.fn<() => void>(() => { + order.push('late released') + }) + + delegate.tierDemandStarted.mockImplementationOnce((async (written: TierStream) => { + written.defer(early) + await pending.promise + written.defer(late) + order.push('late registered') + + return 7 + }) as unknown as MultiTierStreamingDelegate['tierDemandStarted']) + view() + table.withdraw(WITHDRAWAL) + + expect(order).toEqual(['early released']) + + pending.resolve() + await settle() + + expect([ + order, + early.mock.calls.length, + late.mock.calls.length, + error.mock.calls, + ]).toEqual([ + ['early released', 'late registered', 'late released'], + 1, + 1, + [ + [VALUE_LINE], + ], + ]) + }) + + it('releases nothing more for a start that rejects after its withdrawal released what it registered', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, stream, table, view } = rig() + const pending = pendingStart(delegate) + + view() + table.withdraw(WITHDRAWAL) + + expect(disposedOf(delegate, stream())).toBe(1) + + pending.reject(new Error('The encoder would not start.')) + await settle() + + expect([ + (stream() as TierDemand).state, + disposedOf(delegate, stream()), + ]).toEqual(['ended', 1]) + }) + + it.each([ + { cut: 'its bound' }, + { cut: 'a reset' }, + ])('releases once what a start withdrawn at $cut registered, its later settling releasing nothing more and touching no later start of the tier', async ({ cut }) => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { at, delegate, stream, table, tier, view } = rig() + + fakeTimeoutSignals() + + const pending = pendingStart(delegate) + const { hold } = view() + const withdrawn = stream() + + if (cut === 'a reset') { + table.withdraw(WITHDRAWAL) + } else { + await at(DELEGATE_CALL_TIMEOUT) + } + + hold.release() + + // A later start of the tier, made before the withdrawn start's answer arrives. + view() + await settle() + + const later = stream() + + expect(later).not.toBe(withdrawn) + + pending.resolve() + await settle() + + expect([ + (withdrawn as TierDemand).state, + disposedOf(delegate, withdrawn), + signalOf(delegate, withdrawn).aborted, + ]).toEqual(['ended', 1, true]) + expect([ + (later as TierDemand).state, + tier.demand, + disposedOf(delegate, later), + signalOf(delegate, later).aborted, + ]).toEqual(['started', later, 0, false]) + }) + + it('releases nothing at a stream\'s failure and what its start registered once the last of its holds releases', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, stream, view } = rig() + const first = view() + const second = view() + + await settle() + stream().fail('The encoder crashed.') + await settle() + + expect(disposedOf(delegate, stream())).toBe(0) + + first.hold.release() + await settle() + + expect(disposedOf(delegate, stream())).toBe(0) + + second.hold.release() + await settle() + + expect([ + (stream() as TierDemand).state, + disposedOf(delegate, stream()), + ]).toEqual(['ended', 1]) + }) + + it('logs a start\'s settled value of null, 7, a plain object or a disposable once each as its call\'s one argument, starts and serves each demand and ' + + 'releases nothing for the value, and logs nothing for a start that answers undefined', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { at, delegate, stream, view } = rig() + const dispose = vi.fn<() => void>() + let moment = 0 + + for (const answer of [ + null, + 7, + { encoder: 'running' }, + { [Symbol.dispose]: dispose }, + undefined, + ]) { + delegate.tierDemandStarted.mockImplementationOnce(answering(answer)) + + const { hold, releases } = view() + + await settle() + + expect(hold.started).toBe(true) + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + moment += 1000 + await at(moment) + + expect(releases).toHaveLength(1) + + hold.release() + await settle() + } + + expect([error.mock.calls, dispose.mock.calls.length]).toEqual([ + [ + [VALUE_LINE], + [VALUE_LINE], + [VALUE_LINE], + [VALUE_LINE], + ], + 0, + ]) + }) + + it('awaits a start\'s answer that has a then as the start\'s promise, logs the value it settles with once, and releases what the start registered at ' + + 'the demand\'s end', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, stream, view } = rig() + const settling = deferred() + + delegate.tierDemandStarted.mockImplementationOnce(((written: TierStream) => { + written.use(disposableFor(delegate, written)) + + return { + then: (settled: (value: unknown) => void): void => { + void settling.promise.then(() => settled(7)) + }, + } + }) as unknown as MultiTierStreamingDelegate['tierDemandStarted']) + + const { hold } = view() + + await settle() + + expect([hold.waiting, error.mock.calls.length]).toEqual([true, 0]) + + settling.resolve() + await settle() + + expect([ + hold.started, + error.mock.calls, + disposedOf(delegate, stream()), + ]).toEqual([ + true, + [ + [VALUE_LINE], + ], + 0, + ]) + + hold.release() + await settle() + + expect(disposedOf(delegate, stream())).toBe(1) + }) + + it('meets the ended demand in a cleanup that holds the same tier through the table, its hold settled and not serving, calling no start during the ' + + 'release, and still calls the older cleanup', async () => { + const { delegate, table, tier, view } = rig() + const inside: unknown[] = [] + const order: string[] = [] + + delegate.tierDemandStarted.mockImplementationOnce(async (written) => { + written.defer(() => { + order.push('older') + }) + written.defer(() => { + const held = table.hold(tier, scriptedHolder()) + + inside.push([held.waiting, held.started, delegate.tierDemandStarted.mock.calls.length]) + order.push('newer') + held.release() + }) + }) + + const { hold } = view() + + await settle() + hold.release() + + expect([ + inside, + order, + delegate.tierDemandStarted.mock.calls.length, + tier.demand, + ]).toEqual([ + [ + [ + false, + false, + 1, + ], + ], + ['newer', 'older'], + 1, + undefined, + ]) + }) + + it('logs a cleanup that throws and one that rejects once each, and starts and ends the tier\'s next demand as before', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, stream, view } = rig() + + delegate.tierDemandStarted.mockImplementationOnce(async (written) => { + written.defer(async () => { + throw new Error('The feed would not close.') + }) + written.defer(() => { + throw new Error('The encoder would not stop.') + }) + }) + + const first = view() + + await settle() + first.hold.release() + await settle() + + expect(linesUnder(error, END_FAILURE)).toBe(2) + + const { hold } = view() + + await settle() + + expect(hold.started).toBe(true) + + hold.release() + await settle() + + expect([ + disposedOf(delegate, stream()), + linesUnder(error, END_FAILURE), + error.mock.calls.length, + ]).toEqual([1, 2, 2]) + }) + + it('hands each demand\'s stream its tier\'s settled entry, its sensor\'s UUID in lowercase and frozen, the same object for two demands of one tier', + async () => { + const { stream, tier, view } = rig() + const first = view() + + await settle() + + const entry = stream().tier + + first.hold.release() + await settle() + view() + await settle() + + expect(entry).toEqual({ + ...TIERS.tiers.get(1), + sensorUUID: FIRST_VIDEO_SENSOR.uuid.toLowerCase(), + }) + expect(entry.sensorUUID).toBe(FIRST_VIDEO_SENSOR.uuid.toLowerCase()) + expect(Object.isFrozen(entry)).toBe(true) + expect(stream().tier).toBe(entry) + expect(entry).toBe(tier.entry) + }) + + it('aborts a pending start\'s signal once at a reset, its listener reading the demand ended and still its tier\'s and changing nothing by a write or a ' + + 'fail, and never a resolved or a rejected start\'s', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, stream, table, tier, view } = rig() + const inside: unknown[] = [] + + pendingStart(delegate) + + const { holder } = view() + const listener = vi.fn<() => void>(() => { + const written = stream() as TierDemand + const warned = warn.mock.calls.length + + written.write(tierStreamInitialization()) + written.write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + written.fail('The encoder crashed.') + inside.push([ + written.state, + tier.demand === written, + tier.buffer.samples.length, + warn.mock.calls.length - warned, + holder.tierFailed.mock.calls.length, + ]) + }) + + signalOf(delegate, stream()).addEventListener('abort', listener) + table.withdraw(WITHDRAWAL) + table.withdraw(WITHDRAWAL) + await settle() + + expect(listener).toHaveBeenCalledOnce() + expect(inside).toEqual([ + [ + 'ended', + true, + 0, + 0, + 0, + ], + ]) + + // A start that resolved and one that rejected, each through its demand's end, a reset and a destroy, each of which withdraws through the table. + for (const settles of ['resolves', 'rejects'] as const) { + if (settles === 'rejects') { + delegate.tierDemandStarted.mockImplementationOnce(async () => { + throw new Error('The plugin refused the tier.') + }) + } + + const { hold } = view() + + await settle() + hold.release() + table.withdraw(WITHDRAWAL) + table.withdraw(WITHDRAWAL) + await settle() + + expect({ settles, aborted: signalOf(delegate, stream()).aborted }).toEqual({ settles, aborted: false }) + } + }) + + it('logs a start that rejects before any withdrawal once, and one that rejects after its withdrawal not at all', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, table, view } = rig() + const failure = 'MultiTierStreamingDelegate failed to start a tier demand: ' + + for (const withdrawn of [false, true]) { + const pending = pendingStart(delegate) + const { hold } = view() + + if (withdrawn) { + table.withdraw(WITHDRAWAL) + } + + pending.reject(new Error('The encoder would not start.')) + await settle() + hold.release() + await settle() + + expect({ + withdrawn, + lines: linesUnder(error, failure), + }).toEqual({ withdrawn, lines: 1 }) + } + }) + }) + + describe('the start\'s bound', () => { + // The warning of a demand its start's bound withdrew. + const BOUND_WARNING = 'MultiTierStreamingDelegate did not settle tierDemandStarted for the video tier 1 of the video sensor ' + + `"${FIRST_VIDEO_SENSOR.uuid.toLowerCase()}" within 30 seconds: the demand is withdrawn and every join waiting on it is refused.` + + it('withdraws a start still pending 30 seconds from its call once, its signal aborted and each of two holds joined 20 seconds apart refused then and ' + + 'not before, and no start that resolves or rejects at 29 seconds', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { at, delegate, stream, view } = rig() + + fakeTimeoutSignals() + pendingStart(delegate) + + const answers: StartAnswer[] = [] + const first = view() + + void first.hold.answer().then(answer => answers.push(answer)) + await at(20000) + + const second = view() + + void second.hold.answer().then(answer => answers.push(answer)) + await at(29999) + + expect([answers, warn.mock.calls.length, signalOf(delegate, stream()).aborted]).toEqual([[], 0, false]) + + await at(30000) + + expect([ + answers, + warn.mock.calls.map(([line]) => line), + delegate.aborts.get(stream())!.mock.calls.length, + ]).toEqual([ + ['cut', 'cut'], + [BOUND_WARNING], + 1, + ]) + + first.hold.release() + second.hold.release() + await settle() + + // A start that resolves 29 seconds from its call and one that rejects then, each read past the moment its bound would fall. + let now = 30000 + + for (const settles of ['resolves', 'rejects'] as const) { + const pending = pendingStart(delegate) + const { hold } = view() + const settling = stream() + + now += 29000 + await at(now) + + if (settles === 'resolves') { + pending.resolve() + } else { + pending.reject(new Error('The encoder would not start.')) + } + + now += 2000 + await at(now) + + expect({ + settles, + started: hold.started, + warnings: warn.mock.calls.length, + aborted: signalOf(delegate, settling).aborted, + }).toEqual({ + settles, + started: settles === 'resolves', + warnings: 1, + aborted: false, + }) + + hold.release() + await settle() + } + }) + + it('withdraws at 30 seconds a pending start whose last hold left at 10 seconds, releasing at once what it registers after, and one whose stream ' + + 'failed while it was pending, its hold released, beside the failure\'s own warning', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { at, delegate, stream, view } = rig() + + fakeTimeoutSignals() + + // The start registers once its wait is over, which the row ends after the withdrawal. + const pending = deferred() + + delegate.tierDemandStarted.mockImplementationOnce(async (written) => { + await pending.promise + written.use(disposableFor(delegate, written)) + }) + + const left = view() + const ending = stream() as TierDemand + + await at(10000) + left.hold.release() + await at(29999) + + expect([ending.state, warn.mock.calls.length, signalOf(delegate, ending).aborted]).toEqual(['ending', 0, false]) + + await at(30000) + + expect([ + ending.state, + warn.mock.calls.map(([line]) => line), + signalOf(delegate, ending).aborted, + disposedOf(delegate, ending), + ]).toEqual([ + 'ended', + [BOUND_WARNING], + true, + 0, + ]) + + pending.resolve() + await settle() + + expect(disposedOf(delegate, ending)).toBe(1) + + // A start called at 30 seconds whose stream fails at 40 seconds, its hold released after the failure. + pendingStart(delegate) + + const failing = view() + const failed = stream() as TierDemand + + await at(40000) + failed.fail('The encoder crashed.') + failing.hold.release() + await at(59999) + + expect([failed.state, warn.mock.calls.length, signalOf(delegate, failed).aborted]).toEqual(['ending', 2, false]) + + await at(60000) + + expect([ + failed.state, + warn.mock.calls.slice(1).map(([line]) => line), + signalOf(delegate, failed).aborted, + ]).toEqual([ + 'ended', + [ + `The plugin failed the stream of ${failed.tierName} (The encoder crashed.), and every session on the tier ends.`, + BOUND_WARNING, + ], + true, + ]) + }) + + it('withdraws at 30 seconds from its call a demand a join at 20 seconds took back from ending at 10 seconds, refusing that join then and not at 50', + async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { at, delegate, stream, view } = rig() + + fakeTimeoutSignals() + pendingStart(delegate) + + const left = view() + + await at(10000) + left.hold.release() + await at(20000) + + const joining = view() + const answers: StartAnswer[] = [] + + void joining.hold.answer().then(answer => answers.push(answer)) + await at(29999) + + expect([answers, (stream() as TierDemand).state]).toEqual([[], 'starting']) + + await at(30000) + + expect([ + answers, + warn.mock.calls.map(([line]) => line), + ]).toEqual([ + ['cut'], + [BOUND_WARNING], + ]) + + await at(50000) + + expect([ + answers, + warn.mock.calls.length, + delegate.tierDemandStarted.mock.calls.length, + ]).toEqual([ + ['cut'], + 1, + 1, + ]) + }) + + it('withdraws a start pending at a reset with one debug event and no warning, and no second time as its bound passes after, with no second abort and ' + + 'no hold read as cut at its bound', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const lines = captureDebug('HAP-NodeJS:Camera:Tier') + const { at, delegate, stream, table, view } = rig() + + fakeTimeoutSignals() + pendingStart(delegate) + + const { hold } = view() + + await at(10000) + table.withdraw(WITHDRAWAL) + await at(40000) + + expect([ + warn.mock.calls.length, + lines.filter(line => line.startsWith('The library withdrew the pending start')).length, + delegate.aborts.get(stream())!.mock.calls.length, + await hold.answer(), + ]).toEqual([0, 1, 1, 'refused']) + }) + + it('answers each hold started for a started demand, refused for a rejected start, a failed stream and a withdrawal at a reset, and cut at the start\'s ' + + 'bound', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + + const answers: StartAnswer[] = [] + // Each way a pending start ends for the hold that waits on it, each over a table of its own, a stream failed while its start is pending among them. + const outcomes: ((rig: Rig, pending: Deferred) => Promise)[] = [ + async (_, pending) => pending.resolve(), + async (_, pending) => pending.reject(new Error('The encoder would not start.')), + async ({ stream }) => stream().fail('a synthetic failure'), + async ({ table }) => table.withdraw(WITHDRAWAL), + async ({ at }) => at(30000), + ] + + for (const outcome of outcomes) { + const built = rig() + + fakeTimeoutSignals() + + const pending = pendingStart(built.delegate) + const { hold } = built.view() + const answer = hold.answer() + + await outcome(built, pending) + answers.push(await answer) + pending.resolve() + hold.release() + await settle() + } + + expect(answers).toEqual([ + 'started', + 'refused', + 'refused', + 'refused', + 'cut', + ]) + }) + }) + + describe('the silence bounds', () => { + // The sentence of the stream-failed problem a silence of the fixture's video tier 1 raises, by its case. + const silenceOf = (silence: string): string => `The library ended the stream of the video tier 1 of the video sensor "${TIERS.sensorUUID.toLowerCase()}" ` + + `(${silence}), and every session on the tier ends.` + const LONG_GAP = silenceOf('no picture for 10 seconds') + const FIRST_PICTURE = silenceOf('no picture within 30 seconds of its start\'s settling') + const RECONNECT = silenceOf('no picture within 30 seconds of its source being stated reconnecting') + + // The problems a row's table raised, each by its kind and its sentence. + const told = (problems: readonly CameraProblem[]): string[][] => problems.map(({ kind, sentence }) => [kind, sentence]) + + it.each([ + { written: 'after its start settled' }, + { written: 'while its start is pending' }, + ])('fails a demand a viewer alone holds whose pictures, written $written, stop for 10 seconds, with one stream-failed problem and its holder\'s ' + + 'route called once, and the first join after the release raises a fresh demand', async ({ written }) => { + const { problems, reporter } = problemsOf() + const delegate = scriptedTierDelegate() + const pending = (written === 'while its start is pending') + ? pendingStart(delegate) + : undefined + const { at, stream, view } = rig(delegate, TIERS, reporter) + const { hold, holder } = view() + const answer = hold.answer() + + // The scripted start settles here, where the row does not hold it pending. + await settle() + + // A keyframe, a picture five seconds on that moves the clock on, and then nothing. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(5000) + stream().write(fragment({ + pictureAt: 5000, + pictures: [100 / 3], + })) + await at(14999) + + expect([problems, holder.tierFailed.mock.calls.length]).toEqual([[], 0]) + + await at(15000) + + // A demand whose start is still pending ends its waiting holder through its route, its answer read as refused. + expect([ + told(problems), + holder.tierFailed.mock.calls.length, + await answer, + ]).toEqual([ + [ + ['stream-failed', LONG_GAP], + ], + 1, + (written === 'while its start is pending') + ? 'refused' + : 'started', + ]) + + hold.release() + pending?.resolve() + await settle() + view() + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + + it('fails a started demand a viewer alone holds that hands over no picture within 30 seconds of its start\'s settling, with one stream-failed problem ' + + 'and its holder\'s route called once, and the first join after the release raises a fresh demand', async () => { + const { problems, reporter } = problemsOf() + const delegate = scriptedTierDelegate() + const start = pendingStart(delegate) + const { at, view } = rig(delegate, TIERS, reporter) + const { hold, holder } = view() + + // The start settles five seconds after its call, and the bound counts from its settling. + await at(5000) + start.resolve() + await at(34999) + + expect([problems, holder.tierFailed.mock.calls.length]).toEqual([[], 0]) + + await at(35000) + + expect([ + told(problems), + holder.tierFailed.mock.calls.length, + ]).toEqual([ + [ + ['stream-failed', FIRST_PICTURE], + ], + 1, + ]) + + hold.release() + await settle() + view() + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + + it('holds a demand a viewer alone holds for 30 seconds from a reconnect\'s statement, once, a second statement stretching nothing, and fails it then ' + + 'with the reconnect\'s sentence', async () => { + const { problems, reporter } = problemsOf() + const { at, stream, table, view } = rig(scriptedTierDelegate(), TIERS, reporter) + const { holder } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(5000) + table.sourceRecovering() + await at(10000) + table.sourceRecovering() + await at(34999) + + expect([problems, holder.tierFailed.mock.calls.length]).toEqual([[], 0]) + + await at(35000) + + expect([ + told(problems), + holder.tierFailed.mock.calls.length, + ]).toEqual([ + [ + ['stream-failed', RECONNECT], + ], + 1, + ]) + }) + + it('counts the long-gap time again from the first picture after a reconnect\'s statement', async () => { + const { problems, reporter } = problemsOf() + const { at, stream, table, view } = rig(scriptedTierDelegate(), TIERS, reporter) + const { holder } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(1000) + table.sourceRecovering() + await at(5000) + stream().write(fragment({ + pictureAt: 5000, + pictures: [100 / 3], + })) + await at(14999) + + expect([problems, holder.tierFailed.mock.calls.length]).toEqual([[], 0]) + + await at(15000) + + expect([ + told(problems), + holder.tierFailed.mock.calls.length, + ]).toEqual([ + [ + ['stream-failed', LONG_GAP], + ], + 1, + ]) + }) + + it('leaves a started demand that has handed over no picture to its first-sample bound at a reconnect\'s statement', async () => { + const { problems, reporter } = problemsOf() + const { at, table, view } = rig(scriptedTierDelegate(), TIERS, reporter) + + view() + await at(10000) + table.sourceRecovering() + await at(29999) + + expect(problems).toEqual([]) + + await at(30000) + + expect(told(problems)).toEqual([ + ['stream-failed', FIRST_PICTURE], + ]) + }) + + it('arms no clock at a reconnect\'s statement on a failed demand a viewer still holds, and raises nothing more past every bound', async () => { + const { problems, reporter } = problemsOf() + const { at, stream, table, view } = rig(scriptedTierDelegate(), TIERS, reporter) + const { holder } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await settle() + stream().fail('a synthetic failure') + + expect(vi.getTimerCount()).toBe(0) + + table.sourceRecovering() + + expect(vi.getTimerCount()).toBe(0) + + await at(70000) + + expect([ + problems.map(({ kind }) => kind), + holder.tierFailed.mock.calls.length, + ]).toEqual([ + ['stream-failed'], + 1, + ]) + }) + + it.each([ + { end: 'the plugin\'s fail' }, + { end: 'the last release' }, + { end: 'a withdrawal' }, + { end: 'a refused start' }, + { end: 'a fail inside a pending start that then resolves' }, + ])('runs no silence clock past $end, raising no stream-failed problem and calling no route past every bound', async ({ end }) => { + const { problems, reporter } = problemsOf() + const delegate = scriptedTierDelegate() + const pending = ['a withdrawal', 'a refused start', 'a fail inside a pending start that then resolves'].includes(end) + ? pendingStart(delegate) + : undefined + const { at, stream, table, view } = rig(delegate, TIERS, reporter) + const { hold, holder } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await settle() + + switch (end) { + case 'the plugin\'s fail': { + stream().fail('a synthetic failure') + break + } + + case 'the last release': { + hold.release() + break + } + + case 'a withdrawal': { + table.withdraw(WITHDRAWAL) + break + } + + case 'a refused start': { + pending!.reject(new Error('The encoder would not start.')) + break + } + + default: { + stream().fail('a synthetic failure') + pending!.resolve() + } + } + + await settle() + + const ended = [problems.length, holder.tierFailed.mock.calls.length] + + // Every timeout signal is real here, which is why each timer counted is a fake one the demand or its pacer armed. + expect(vi.getTimerCount()).toBe(0) + + await at(70000) + + expect([problems.length, holder.tierFailed.mock.calls.length]).toEqual(ended) + }) + + it('tells a tier\'s silence once however many of its demands fall silent, and again once the tier has handed over a picture', async () => { + const { problems, reporter } = problemsOf() + const { at, stream, view } = rig(scriptedTierDelegate(), TIERS, reporter) + const first = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(10000) + first.hold.release() + await settle() + + // A fresh demand of the tier that hands over nothing ends at its first-sample bound with no problem, its holder's route called. + const second = view() + + await at(40000) + second.hold.release() + await settle() + + const silent = [problems.length, second.holder.tierFailed.mock.calls.length] + + // A fresh demand that hands over a picture and then falls silent tells the tier's silence again. + view() + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictureAt: 40000, + pictures: [100 / 3], + })) + await at(50000) + + expect([ + silent, + told(problems), + ]).toEqual([ + [1, 1], + [ + ['stream-failed', LONG_GAP], + ['stream-failed', LONG_GAP], + ], + ]) + }) + + it('counts the first-sample bound, the long-gap time and a reconnect\'s hold each on a timer that keeps no process alive', async () => { + const { at, stream, table, view } = rig() + const timers = vi.spyOn(globalThis, 'setTimeout') + // The handles setTimeout answered for a delay, read in the order made. + const handles = (delay: number): ReturnType[] => timers.mock.calls.flatMap(([, made], index) => (made === delay) + ? [timers.mock.results[index].value as ReturnType] + : []) + + view() + await at(10) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictureAt: 10, + pictures: [100 / 3], + })) + table.sourceRecovering() + + expect(handles(30000).concat(handles(10000)).map(handle => handle.hasRef())).toEqual([false, false, false]) + }) + + it('fails a demand a viewer alone holds whose stream hands over sound and no picture for 10 seconds, its sound moving no clock on', async () => { + const { problems, reporter } = problemsOf() + const { at, stream, view } = rig(scriptedTierDelegate(), TIERS, reporter) + const { holder } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + sounds: 1, + })) + + // A fragment of sound alone each second after the picture, the last at 9 seconds. + for (let second = 1; second < 10; second++) { + await at(second * 1000) + stream().write(fragment({ + soundAt: second * 1000, + sounds: 1, + })) + } + + await at(9999) + + expect([problems, holder.tierFailed.mock.calls.length]).toEqual([[], 0]) + + await at(10000) + + expect([ + told(problems), + holder.tierFailed.mock.calls.length, + ]).toEqual([ + [ + ['stream-failed', LONG_GAP], + ], + 1, + ]) + }) + }) + + describe('the opening\'s speed', () => { + // The stream's octets in a tenth of a second at a rate in kilobits a second. + const tenthOf = (rate: number): number => rate * 1000 / 8 / 10 + + // Each timestamp a viewer was handed, as a packet carries it. + const stamps = (releases: readonly Release[]): number[] => releases.map(({ timestamp }) => timestamp % 0x100000000) + + /* A table whose stream is pictures a tenth of a second long, each of the octets given, from a keyframe at 0 through the picture at the last time given, + * each written in a fragment of its own at its own time, and where the row holds one, the last in a fragment with the picture after it, which the pacer + * holds a tenth of a second. A frame consumer of the live releases, joined first, records where each picture was placed. + */ + async function tenths(octets: number, last: number, held: boolean): Promise & { placed: Map }> { + const { at, stream, table, tier, view } = rig() + const placed = placements(table, tier) + + stream().write(tierStreamInitialization()) + + for (let time = 0; time <= last; time += 100) { + await at(time) + stream().write(fragment({ + keyframe: time === 0, + octets, + pictureAt: time, + pictures: (held && (time === last)) + ? [100, 100] + : [100], + })) + } + + return { at, placed, stream, view } + } + + it('stamps at fifty exactly an opening whose stretch from its released keyframe runs at 5000 kbit/s over two seconds, read to the first picture after ' + + 'it, and one at 1000', async () => { + for (const rate of [5000, 1000]) { + // Twenty pictures of one size, the picture at two seconds held as the viewer joins and handed in the opening once it is released. + const { at, placed, view } = await tenths(tenthOf(rate), 1900, true) + + await at(1950) + + const { releases } = view() + + await at(2100) + + expect({ + rate, + stamps: stamps(releases), + }).toEqual({ + rate, + stamps: Array.from({ length: 21 }, (_picture, index) => openingStamp(stampOf(placed, 1900), index * 100) % 0x100000000), + }) + } + }) + + it('stamps at fifty exactly an opening of a stream at 5000 kbit/s over two seconds where the pacer holds no picture, its stretch read to its last ' + + 'picture\'s decode time plus that picture\'s own duration', async () => { + const { at, placed, stream, view } = await tenths(tenthOf(5000), 1900, false) + + await at(1950) + + const { releases } = view() + + // The picture written after the opening's first turn moves the live edge past the stretch. + await at(2000) + stream().write(fragment({ + pictureAt: 2000, + pictures: [100], + })) + await at(2100) + + expect(stamps(releases)).toEqual(Array.from({ length: 21 }, (_picture, index) => openingStamp(stampOf(placed, 1900), index * 100) % 0x100000000)) + }) + + it('stamps at twenty an opening whose stretch runs at 12500 kbit/s over two seconds, fifty times 5000 over 12500', async () => { + const { at, placed, view } = await tenths(tenthOf(12500), 1900, true) + + await at(1950) + + const { releases } = view() + + await at(2100) + + // The held picture's own timestamp at twenty stands past the live edge its release moves, and the opening waits on it. + expect(stamps(releases)).toEqual(Array.from({ length: 20 }, (_picture, index) => openingStamp(stampOf(placed, 1900), index * 100, 20) % 0x100000000)) + }) + + it('reads a stretch of its keyframe alone as a second long, stamping one of 625000 octets at fifty and one of 1250000 at twenty-five', async () => { + for (const [octets, speed] of [ + [625000, 50], + [1250000, 25], + ]) { + const { at, stream, table, tier, view } = rig() + const placed = placements(table, tier) + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + octets, + pictures: [100], + })) + await at(50) + + const { releases } = view() + + // The picture written after the opening's first turn moves the live edge past the keyframe and is handed at the opening's speed. + await at(100) + stream().write(fragment({ + pictureAt: 100, + pictures: [100], + })) + await at(150) + + expect({ + octets, + stamps: stamps(releases), + }).toEqual({ + octets, + stamps: [0, 100].map(distance => openingStamp(stampOf(placed, 0), distance, speed) % 0x100000000), + }) + } + }) + + it('takes the speed of the heavy stretch of a newer keyframe an opening carries on to from a light one', async () => { + const { at, stream, table, tier, view } = rig() + const placed = placements(table, tier) + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100], + })) + await at(50) + + const { releases } = view() + + // A keyframe a second long at 12500 kbit/s moves the buffer's head past the opening's light keyframe, and the picture after it, which the pacer holds + // until its time, moves the live edge past the new stretch. + await at(1000) + stream().write(fragment({ + keyframe: true, + octets: tenthOf(12500) * 10, + pictureAt: 1000, + pictures: [1000, 100], + })) + await at(2100) + + expect(stamps(releases)).toEqual([0, 1000].map(distance => openingStamp(stampOf(placed, 1000), distance, 20) % 0x100000000)) + }) + + it('measures no picture the pacer still holds, stamping at fifty a keyframe at 5000 kbit/s read as a second ahead of heavy pictures held', async () => { + const { at, stream, table, tier, view } = rig() + const placed = placements(table, tier) + + // A keyframe and the pictures after it, each of the octets a second at 5000 kbit/s carries, in one fragment. The pacer holds each picture after the + // keyframe until its time. + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + octets: tenthOf(5000) * 10, + pictures: [100, 100, 100], + })) + await at(50) + + const { releases } = view() + + await at(150) + + expect(stamps(releases)).toEqual([0, 100].map(distance => openingStamp(stampOf(placed, 0), distance) % 0x100000000)) + }) + }) + + describe('a stream past twice its tier\'s peak', () => { + // The debug line a demand of the fixture's tier 1, whose peak is its class's maximum of 1800 kbps, writes for a stretch at a rate past twice it. + const pastPeak = (rate: number): string => `The stream of the video tier 1 of the video sensor "${TIERS.sensorUUID}" runs at ${rate} kbps over the stretch ` + + 'a view opens on, read over a second at least, past twice the peak of 1800 kbps its tier advertises.' + + it('writes one debug line naming both rates for a demand whose stretch runs past twice its tier\'s peak, none at its second opening and one for a new ' + + 'demand, and none for a stretch between the peak and twice it', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const lines = captureDebug('HAP-NodeJS:Camera:Tier') + const { at, stream, view } = rig() + + /* Raises a demand of the tier with a viewer of the live releases at a moment of the row's timeline, writes its stream a keyframe alone of the octets + * given, read as a second long, opens a viewer on it and then another, and ends the demand by releasing every hold. + */ + const openTwice = async (from: number, octets: number): Promise => { + const holds = [view().hold] + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + octets, + pictures: [100], + })) + await at(from + 50) + holds.push(view().hold) + await at(from + 60) + holds.push(view().hold) + await at(from + 70) + + for (const hold of holds) { + hold.release() + } + } + + /* Raises a demand of the tier with a viewer of the live releases, writes its stream a keyframe read as a second long at a rate within twice the peak, + * which a viewer opens on, and then a light picture, whose release moves the live edge past that opening so it is done, before a second later a + * keyframe at a rate past twice the peak, which a later viewer opens on, and answers the count of lines just before and just after that later opening. + */ + const openLighterThenHeavier = async (from: number): Promise => { + const holds = [view().hold] + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + octets: 375000, + pictures: [100], + })) + await at(from + 50) + holds.push(view().hold) + await at(from + 100) + stream().write(fragment({ + pictureAt: 100, + pictures: [100], + })) + await at(from + 1000) + stream().write(fragment({ + keyframe: true, + octets: 625000, + pictureAt: 1000, + pictures: [100], + })) + await at(from + 1050) + + const before = lines.length + + holds.push(view().hold) + await at(from + 1060) + + for (const hold of holds) { + hold.release() + } + + return [before, lines.length] + } + + /* Raises a demand of the tier with one viewer, joined before the stream writes a keyframe at a rate past twice the peak, which is why the viewer takes it live + * and no opening reads it. Answers what the viewer's keyframe request came to, the replay it opens being the demand's first stretch read. + */ + const answerOnce = async (from: number): Promise => { + const { hold } = view() + + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + octets: 625000, + pictures: [100], + })) + await at(from + 50) + + const answer = hold.answerKeyframeRequest() + + await at(from + 60) + hold.release() + + return answer + } + + await openTwice(0, 625000) + await openTwice(1000, 625000) + await openTwice(2000, 375000) + // A stretch past twice the tier's bitrate and within twice its peak. + await openTwice(3000, 437500) + + const later = await openLighterThenHeavier(4000) + const answer = await answerOnce(6000) + + // A camera not given strict warns of none of them. + expect({ + answer, + later, + lines, + warned: warn.mock.calls, + }).toEqual({ + answer: 'answered', + later: [2, 3], + lines: [ + pastPeak(5000), + pastPeak(5000), + pastPeak(5000), + pastPeak(5000), + ], + warned: [], + }) + }) + }) + + describe('the newest keyframe', () => { + // HEVC's video, sequence and picture parameter sets, which a row hands a stream's description or its keyframe some of. + const [VPS, SPS, PPS] = TIER_STREAM_PARAMETER_SETS + + // Starts a tier's stream: its initialization segment, whose description holds no parameter set, then a keyframe carrying its sets in band, of the + // octets given, which is how a row tells one tier's keyframe from another's. Answers the keyframe's octets. + function startStream(stream: TierStream, octets: number): Buffer { + const keyframe = tierPicture({ inBand: true, keyframe: true, octets }) + + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [keyframe], + })) + + return keyframe.data + } + + // The one sample of a keyframe's movie, as the stream reader reads the movie back. + function movieSample(movie: Buffer): Mp4StreamSample { + const samples: Mp4StreamSample[] = [] + + new Mp4StreamReader({ + fail: (reason) => { + throw new Error(reason) + }, + fragmentEnd: () => undefined, + sample: (sample) => { + samples.push(sample) + }, + tracks: () => undefined, + }).write(movie) + + expect(samples).toHaveLength(1) + + return samples[0] + } + + it('answers the newest keyframe of the best tier that serves, a lesser tier while the table\'s best tier is not running, and raises nothing for it', + async () => { + const { at, delegate, table } = rig() + const best = table.videoTiers.get(1)! + + table.hold(table.videoTiers.get(2)!, scriptedHolder()) + await at(0) + + const lesser = startStream(streamsOf(delegate, 2)[0], 120) + + expect(bestStreamTier(table.streamTiers.videoStreamTiers.tiers)).toBe(best.advertised) + expect(movieSample(table.latestKeyframe()!.movie).data).toEqual(lesser) + expect(best.demand).toBeUndefined() + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(1) + + table.hold(best, scriptedHolder()) + await at(0) + + const bestKeyframe = startStream(streamsOf(delegate, 1)[0], 140) + + expect(movieSample(table.latestKeyframe()!.movie).data).toEqual(bestKeyframe) + }) + + it('passes over a tier whose stream failed for the next tier that serves, and answers nothing and starts nothing while no tier runs', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + + const { at, delegate, table } = rig() + + expect(table.latestKeyframe()).toBeUndefined() + expect(delegate.tierDemandStarted).not.toHaveBeenCalled() + + const holds = [1, 2].map(tierId => table.hold(table.videoTiers.get(tierId)!, scriptedHolder())) + + await at(0) + + const best = startStream(streamsOf(delegate, 1)[0], 140) + const lesser = startStream(streamsOf(delegate, 2)[0], 120) + + expect(movieSample(table.latestKeyframe()!.movie).data).toEqual(best) + + streamsOf(delegate, 1)[0].fail('a synthetic failure') + + expect(movieSample(table.latestKeyframe()!.movie).data).toEqual(lesser) + + for (const hold of holds) { + hold.release() + } + + await at(100) + + expect(table.latestKeyframe()).toBeUndefined() + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + + it('answers a newer keyframe the pacer still holds in place of the latest keyframe released, before any viewer is handed it', async () => { + const { at, stream, table, view } = rig() + const { releases } = view() + + await at(0) + + const released = startStream(stream(), 100) + + await at(100) + + expect(releases).toHaveLength(1) + expect(movieSample(table.latestKeyframe()!.movie).data).toEqual(released) + + // A newer keyframe half a second on in the stream's time, written at once, which the pacer holds until its release falls due. + const newer = tierPicture({ inBand: true, keyframe: true, octets: 120 }) + + stream().write(tierStreamFragment({ + picture: [newer], + pictureTime: 45000n, + })) + await at(200) + + expect(releases).toHaveLength(1) + expect(movieSample(table.latestKeyframe()!.movie).data).toEqual(newer.data) + + await at(1000) + + expect(releases.map(({ time }) => time)).toEqual([0, 500]) + }) + + it('hands the same movie while one keyframe is the newest and a new one for a newer keyframe, with the stream\'s width and height and the keyframe\'s ' + + 'age by the steady clock', async () => { + const { at, stream, table, tier } = rig() + + table.hold(tier, scriptedHolder()) + await at(0) + startStream(stream(), 100) + + const first = table.latestKeyframe()! + + await at(250) + + const again = table.latestKeyframe()! + + expect(first).toMatchObject({ age: 0, height: 36, width: 64 }) + expect(again.movie).toBe(first.movie) + expect(again.age).toBe(250) + + const newer = tierPicture({ inBand: true, keyframe: true, octets: 120 }) + + stream().write(tierStreamFragment({ + picture: [newer], + pictureTime: 3000n, + })) + + const latest = table.latestKeyframe()! + + expect(latest.movie).not.toBe(first.movie) + expect(movieSample(latest.movie).data).toEqual(newer.data) + expect(latest.age).toBe(0) + }) + + it('writes a run\'s first keyframe that states no duration with its tier\'s frame interval in its track\'s timescale, and a keyframe that states one ' + + 'with its own', async () => { + const { at, delegate, table } = rig() + + // The fixture's third tier runs at 15 frames a second, an interval of 6000 ticks of the picture's 90 kHz track. + table.hold(table.videoTiers.get(3)!, scriptedHolder()) + await at(0) + + const stream = streamsOf(delegate, 3)[0] + + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + tierPicture({ inBand: true, keyframe: true, untimed: true }), + ], + })) + + expect(movieSample(table.latestKeyframe()!.movie).duration).toBe(6000) + + stream.write(tierStreamFragment({ + picture: [ + { + ...tierPicture({ inBand: true, keyframe: true }), + duration: 4500, + }, + ], + pictureTime: 6000n, + })) + + expect(movieSample(table.latestKeyframe()!.movie).duration).toBe(4500) + }) + + it.each([ + ['its description holding none and its keyframe carrying none in band', [], []], + [ + 'its description holding none and its keyframe carrying its sequence and picture parameter sets alone', + [], + [SPS, PPS], + ], + [ + 'its description holding its sequence and picture parameter sets and its keyframe carrying none', + [SPS, PPS], + [], + ], + ])('passes over a serving tier whose newest keyframe lacks a parameter set, %s, for the next tier that serves, and answers nothing while that ' + + 'tier alone serves, each lookup throwing nothing and writing no line', async (_, description, inBand) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const lines = captureDebug('HAP-NodeJS:*') + const { at, delegate, table } = rig() + const [, lesserHold] = [1, 2].map(tierId => table.hold(table.videoTiers.get(tierId)!, scriptedHolder())) + + await at(0) + + // The best tier's description and keyframe hold between them the parameter sets the case gives, which lack at least one. + const lacking = streamsOf(delegate, 1)[0] + + lacking.write(tierStreamInitialization({ parameterSets: description })) + lacking.write(tierStreamFragment({ + picture: [ + tierPicture({ inBand, keyframe: true, octets: 140 }), + ], + })) + + const lesser = startStream(streamsOf(delegate, 2)[0], 120) + + // A lookup's answer, read with the lines the lookup itself writes, which are none. + const lookup = (): CameraKeyframe | undefined => { + const written = lines.length + const answer = table.latestKeyframe() + + expect(lines).toHaveLength(written) + + return answer + } + + expect(movieSample(lookup()!.movie).data).toEqual(lesser) + + // Each pacer releases its keyframe, and the best tier's demand warns of its stream once. + await at(100) + + expect(movieSample(lookup()!.movie).data).toEqual(lesser) + + lesserHold.release() + await at(200) + + expect(table.videoTiers.get(1)!.demand?.serving).toBe(true) + expect(lookup()).toBeUndefined() + expect(warn.mock.calls).toEqual([ + [ + `The stream of the video tier 1 of the video sensor "${FIRST_VIDEO_SENSOR.uuid.toLowerCase()}" carries a keyframe without its video, ` + + 'sequence and picture parameter sets, in its sample or its initialization segment, which a viewer needs to decode it, and the keyframe is sent ' + + 'as it stands.', + ], + ]) + expect(error).not.toHaveBeenCalled() + }) + + it('answers a serving tier whose description holds its sequence and picture parameter sets and whose newest keyframe carries its video parameter set, ' + + 'its demand warning of nothing', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { at, delegate, table } = rig() + + table.hold(table.videoTiers.get(1)!, scriptedHolder()) + await at(0) + + const stream = streamsOf(delegate, 1)[0] + const keyframe = tierPicture({ + inBand: [VPS], + keyframe: true, + octets: 140, + }) + + stream.write(tierStreamInitialization({ + parameterSets: [SPS, PPS], + })) + stream.write(tierStreamFragment({ + picture: [keyframe], + })) + + expect(movieSample(table.latestKeyframe()!.movie).data).toEqual(keyframe.data) + + await at(100) + + expect(movieSample(table.latestKeyframe()!.movie).data).toEqual(keyframe.data) + expect(warn).not.toHaveBeenCalled() + }) + }) + + describe('its problems', () => { + // The failure a session's packet consumer throws as it is sent a picture. + const SEND_FAILURE = new Error('The session\'s socket failed.') + + it.each([ + { + fields: { sensorUUID: TIERS.sensorUUID, tierId: 1 }, + kind: 'stream-fault', + level: 'warning', + // A viewer opens on a keyframe read as a second long at a rate past twice the tier's peak, the camera given strict. + raise: async ({ at, stream, view }: Rig): Promise => { + view() + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + octets: 625000, + pictures: [100], + })) + await at(50) + view() + await at(60) + }, + site: 'a strict stretch past twice the peak', + strict: true, + }, + { + fields: { sensorUUID: TIERS.sensorUUID, tierId: 1 }, + kind: 'plugin-failure', + level: 'warning', + // A start that never settles, withdrawn at its bound. + raise: async ({ at, delegate, view }: Rig): Promise => { + fakeTimeoutSignals() + pendingStart(delegate) + view() + await at(30000) + }, + site: 'a start its bound withdraws', + strict: false, + }, + { + fields: { error: SEND_FAILURE, sensorUUID: TIERS.sensorUUID, tierId: 1 }, + kind: 'library-failure', + level: 'error', + // A session's packet consumer that throws at the first picture it is sent, taken off. + raise: async ({ at, stream, table, tier }: Rig): Promise => { + table.join(tier, scriptedHolder(), buildEmitterConnection(), ['video'], () => ({ + capacity: Number.POSITIVE_INFINITY, + free: Number.POSITIVE_INFINITY, + send: (): boolean => { + throw SEND_FAILURE + }, + })) + stream().write(tierStreamInitialization()) + stream().write(fragment({ + keyframe: true, + pictures: [100 / 3], + })) + await at(100) + }, + site: 'a consumer taken off as its send throws', + strict: false, + }, + ])('raises one problem of its kind and level with the demand\'s fields for $site', async ({ fields, kind, level, raise, strict }) => { + const { problems, reporter } = problemsOf() + + await raise(rig(scriptedTierDelegate(), { ...TIERS, strict }, reporter)) + + // Each problem is read whole, its sentence's wording aside, and a field it gains or loses is read too. + expect(problems).toEqual([ + { + ...fields, + accessoryUUID: expect.any(String), + kind, + level, + sentence: expect.any(String), + }, + ]) + }) + }) +}) diff --git a/src/lib/camera/WebRTCStreamManagement.spec.ts b/src/lib/camera/WebRTCStreamManagement.spec.ts new file mode 100644 index 000000000..350234269 --- /dev/null +++ b/src/lib/camera/WebRTCStreamManagement.spec.ts @@ -0,0 +1,3144 @@ +import type { Mock } from 'vitest' + +import type { WithUUID } from '../../types.js' +import type { CameraControllerOptions, CameraControllerServiceMap, CameraLiveView } from '../controller/index.js' +import type { CameraWebRTCStreamManagement } from '../definitions/index.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { SupportedAudioStreamTiersPayload, SupportedVideoStreamTiersPayload } from './capabilities/streamTiers.js' +import type { + SFrameKeyData, + SFrameKID, + WebRTCICECandidate, + WebRTCReofferResponse, + WebRTCSessionStatusResponse, + WebRTCSolicitOfferResponse, +} from './capabilities/webrtc.js' +import type { CameraReporter } from './diagnostics/CameraReporter.js' +import type { StreamGate, StreamingEnabledChange } from './OperatingModePolicy.js' +import type { CameraVideoSensor } from './StreamingOptions.js' +import type { + WebRTCOffer, + WebRTCReofferAnswer, + WebRTCStreamEngine, + WebRTCStreamingOptions, + WebRTCStreamManagementOptions, +} from './WebRTCStreamManagement.js' + +import { Buffer } from 'node:buffer' +import { getEventListeners } from 'node:events' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import * as hap from '../../index.js' +import { + buildEmitterConnection, + capabilitiesCameraOptions, + createCameraControllerOptions, + handPublishedContext, + idleStreaming, + NUMBERED_ACCESSORY_UUID, + NUMBERED_USERNAME, + numberedAccessory, + numbersOf, + restoredAccessory, + savedMapOf, + tierSetOf, + videoSensor, +} from '../../test-utils/cameraFixtures.js' +import { captureDebug, captureDebugEvents } from '../../test-utils/engineDebug.js' +import { detachedReporter, problemsOf } from '../../test-utils/reporterFixtures.js' +import { deferred, fakeTimeoutSignals, settle } from '../../test-utils/settle.js' +import { Accessory } from '../Accessory.js' +import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' +import { CameraController, CameraControllerEvents, DoorbellController } from '../controller/index.js' +import { HAPStatus } from '../HAPServer.js' +import { IdentifierCache } from '../model/IdentifierCache.js' +import { Service } from '../Service.js' +import * as tlv from '../util/tlv.js' +import * as uuid from '../util/uuid.js' +import { CameraSensorIntent } from './capabilities/cameraSensors.js' +import { + CameraVideoQuality, + decodeSupportedAudioStreamTiers, + decodeSupportedVideoStreamTiers, + TieredAudioBitDepth, + TieredAudioCodecType, + TieredAudioSampleRate, + TieredVideoCodecType, +} from './capabilities/streamTiers.js' +import { + decodeWebRTCReofferResponse, + decodeWebRTCSessionStatusResponse, + decodeWebRTCSolicitOfferResponse, + encodeWebRTCProvideAnswerRequest, + encodeWebRTCReofferRequest, + encodeWebRTCSolicitOfferRequest, + encodeWebRTCStreamingControlRequest, + encodeWebRTCUpdateSessionRequest, + WebRTCSolicitOfferStatus, + WebRTCStreamingCommand, + WebRTCStreamingStatus, +} from './capabilities/webrtc.js' +import * as webrtc from './capabilities/webrtc.js' +import { CommandQueue } from './session/CommandQueue.js' +import { ConnectionSessions } from './session/ConnectionSessions.js' +import { StreamingEnabledSwitch } from './session/StreamingEnabledSwitch.js' +import { TierTable } from './TierTable.js' +import { WebRTCEngine } from './webrtc/WebRTCEngine.js' +import { loadWerift } from './webrtc/werift.js' +import { WebRTCStreamManagement } from './WebRTCStreamManagement.js' + +// An uppercase sensor UUID, which lets the rows see the service's subtype and the offer request take its lowercase form. +const SENSOR_UUID = '7D3E0F9A-1B2C-4D5E-8F60-718293A4B5C6' +const UNKNOWN_SESSION = 'e7f1c3a2-5b4d-4e6f-9a8b-0c1d2e3f4a5b' +const SDP_ANSWER = 'v=0 answer' +const SDP_REOFFER = 'v=0 reoffer' + +// The reporter of no camera a harness's management reports through and hands the engine, unless a row hands its own. +const REPORTER = detachedReporter() + +const VIDEO_TIERS: SupportedVideoStreamTiersPayload = { + codec: TieredVideoCodecType.H265, + payloadType: 99, + tiers: [ + { + identifier: 1, + quality: CameraVideoQuality.HIGHEST, + targetAverageBitrate: 2000, + width: 1920, + height: 1080, + frameRate: 30, + }, + ], +} + +const AUDIO_TIERS: SupportedAudioStreamTiersPayload = { + codec: TieredAudioCodecType.OPUS, + payloadType: 111, + tiers: [ + { + identifier: 1, + targetAverageBitrate: 32000, + sampleRate: TieredAudioSampleRate.KHZ_48, + bitDepth: TieredAudioBitDepth.BITS_16, + packetTime: 20, + numberOfChannels: 1, + }, + ], +} + +const CANDIDATE: WebRTCICECandidate = { + candidate: 'candidate:1 1 udp 2130706431 192.168.1.10 50000 typ host', + sdpMid: '0', + sdpMLineIndex: 0, +} + +const OFFER: WebRTCOffer = { + sdpOffer: 'v=0 offer', + additionalCandidates: [CANDIDATE], +} + +const CONTROL_POINTS: WithUUID<{ new (): Characteristic }>[] = [ + Characteristic.WebRTCSolicitOffer, + Characteristic.WebRTCProvideAnswer, + Characteristic.WebRTCStreamingControl, + Characteristic.WebRTCReoffer, + Characteristic.WebRTCUpdateSession, +] + +type ScriptedEngine = { [Method in keyof WebRTCStreamEngine]: Mock } + +interface Harness { + engine: ScriptedEngine + gate: { reads: StreamGate } + management: WebRTCStreamManagement + service: CameraWebRTCStreamManagement +} + +// A scripted engine: every call is recorded and answers at once by default, and a row queues its own answers, such as a deferred promise for a slow call. +function scriptedEngine(): ScriptedEngine { + return { + createOffer: vi.fn(async () => ({ ...OFFER })), + acceptAnswer: vi.fn(async () => undefined), + reoffer: vi.fn(async () => ({ sdpAnswer: SDP_ANSWER })), + updateReceiveKeys: vi.fn(async () => undefined), + endSession: vi.fn(async () => undefined), + } +} + +// A management over a scripted engine and a stream gate a row sets, open by default, holding the specification's floor of six sessions unless a row +// hands its own bound, as the camera controller hands the bound it validated, and reporting through the rows' reporter of no camera unless a row hands its +// own. +function harness(options: Partial = {}, service?: CameraWebRTCStreamManagement): Harness { + const engine = scriptedEngine() + const gate: { reads: StreamGate } = { reads: 'open' } + const management = new WebRTCStreamManagement({ + engine, + reporter: REPORTER, + maxSessions: 6, + videoStreamTiers: VIDEO_TIERS, + audioStreamTiers: AUDIO_TIERS, + sensorUUID: SENSOR_UUID, + ...options, + }, () => gate.reads, service) + + return { + engine, + gate, + management, + service: management.getService(), + } +} + +function constructionError(options: Partial): unknown { + try { + harness(options) + } catch (error) { + return error + } + + return undefined +} + +async function write(service: CameraWebRTCStreamManagement, type: WithUUID<{ new (): Characteristic }>, value: string, connection?: HAPConnection): Promise { + return await service.getCharacteristic(type).handleSetRequest(value, connection) as string +} + +async function solicit(service: CameraWebRTCStreamManagement, connection: HAPConnection, sframeEnabled = false): Promise { + return decodeWebRTCSolicitOfferResponse(await write(service, Characteristic.WebRTCSolicitOffer, encodeWebRTCSolicitOfferRequest({ + options: { sframeEnabled }, + }), connection)) +} + +async function answer(service: CameraWebRTCStreamManagement, connection: HAPConnection, sessionIdentifier: string): Promise { + return decodeWebRTCSessionStatusResponse(await write(service, Characteristic.WebRTCProvideAnswer, encodeWebRTCProvideAnswerRequest({ + sessionIdentifier, + sdpAnswer: SDP_ANSWER, + additionalCandidates: [CANDIDATE], + }), connection)) +} + +async function end(service: CameraWebRTCStreamManagement, connection: HAPConnection, sessionIdentifier: string): Promise { + return decodeWebRTCSessionStatusResponse(await write(service, Characteristic.WebRTCStreamingControl, encodeWebRTCStreamingControlRequest({ + sessionIdentifier, + command: WebRTCStreamingCommand.END, + }), connection)) +} + +async function reoffer(service: CameraWebRTCStreamManagement, connection: HAPConnection, sessionIdentifier: string): Promise { + return decodeWebRTCReofferResponse(await write(service, Characteristic.WebRTCReoffer, encodeWebRTCReofferRequest({ + sessionIdentifier, + sdpOffer: SDP_REOFFER, + options: { sframeEnabled: true }, + }), connection)) +} + +async function updateSession( + service: CameraWebRTCStreamManagement, + connection: HAPConnection, + sessionIdentifier: string, + receiveKeysToAdd: SFrameKeyData[] = [ + { + key: Buffer.alloc(16, 0x11), + kid: 1n, + }, + ], + receiveKIDsToRemove: SFrameKID[] = [ + { kid: 2n }, + ], +): Promise { + return decodeWebRTCSessionStatusResponse(await write(service, Characteristic.WebRTCUpdateSession, encodeWebRTCUpdateSessionRequest({ + sessionIdentifier, + receiveKeysToAdd, + receiveKIDsToRemove, + }), connection)) +} + +// The identifier of a session a solicit opened; a solicit that opened none fails the row here. +function sessionOf(response: WebRTCSolicitOfferResponse): string { + if (response.status !== WebRTCSolicitOfferStatus.SUCCESS) { + throw new Error(`The solicit answered status ${response.status}.`) + } + + return response.sessionIdentifier +} + +// Solicits a session and answers its offer, which means the session is connected. +async function connect(service: CameraWebRTCStreamManagement, connection: HAPConnection): Promise { + const sessionIdentifier = sessionOf(await solicit(service, connection)) + expect(await answer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + + return sessionIdentifier +} + +function activeSessions(service: CameraWebRTCStreamManagement): unknown { + return service.getCharacteristic(Characteristic.WebRTCNumberOfActiveSessions).value +} + +/* Whether any of the targets is reachable from a management through its own objects, as the engine's suite walks the engine's: the management, its + * session table, its queue and its switch, the session the table holds under an identifier, and the plain values they hold. The service, a connection, + * a signal and the engine's recorded calls are the library's, the HAP server's and the row's own, and a function is never walked. + */ +function managementReaches(management: WebRTCStreamManagement, sessionIdentifier: string, targets: readonly unknown[]): boolean { + const seen = new Set() + const pending: unknown[] = [management] + const owned = (value: object): boolean => [ + Array.prototype, + CommandQueue.prototype, + ConnectionSessions.prototype, + Map.prototype, + Object.prototype, + Set.prototype, + StreamingEnabledSwitch.prototype, + WebRTCStreamManagement.prototype, + ].includes(Object.getPrototypeOf(value) as object) || ((value as { sessionIdentifier?: unknown }).sessionIdentifier === sessionIdentifier) + + while (pending.length > 0) { + const value = pending.pop() + + if (targets.includes(value)) { + return true + } + + if ((typeof value !== 'object') || (value === null) || seen.has(value) || !owned(value)) { + continue + } + + seen.add(value) + pending.push(...(value instanceof Map + ? value.values() + : Object.values(value))) + } + + return false +} + +// Each new value Number of Active Sessions reports, in order. +function countChanges(service: CameraWebRTCStreamManagement): unknown[] { + const values: unknown[] = [] + service.getCharacteristic(Characteristic.WebRTCNumberOfActiveSessions).on(CharacteristicEventTypes.CHANGE, ({ newValue }) => { + values.push(newValue) + }) + + return values +} + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('webRTCStreamManagement', () => { + describe('construction', () => { + it('builds a service keyed by the sensor UUID with its static characteristics and transient control points', () => { + const { management, service } = harness() + + expect(service).toBeInstanceOf(Service.CameraWebRTCStreamManagement) + expect(service.subtype).toBe(SENSOR_UUID.toLowerCase()) + expect(service.getCharacteristic(Characteristic.SensorUUID).value).toBe(uuid.write(SENSOR_UUID).toString('base64')) + expect(decodeSupportedVideoStreamTiers(service.getCharacteristic(Characteristic.WebRTCSupportedVideoStreamTiers).value as string)).toEqual(VIDEO_TIERS) + expect(decodeSupportedAudioStreamTiers(service.getCharacteristic(Characteristic.WebRTCSupportedAudioStreamTiers).value as string)).toEqual(AUDIO_TIERS) + expect(service.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true) + expect(activeSessions(service)).toBe(0) + expect(CONTROL_POINTS.map(type => service.getCharacteristic(type).props.transient)).toEqual([true, true, true, true, true]) + expect(CONTROL_POINTS.filter(type => service.getCharacteristic(type).props.sensitive)).toEqual([ + Characteristic.WebRTCSolicitOffer, + Characteristic.WebRTCReoffer, + Characteristic.WebRTCUpdateSession, + ]) + expect(management.serialize()).toEqual({ streamingEnabled: true }) + }) + + it('refuses a sensor UUID that is not a UUID with a type error naming the rule', () => { + const error = constructionError({ sensorUUID: 'not-a-uuid' }) + + expect(error).toBeInstanceOf(TypeError) + expect((error as TypeError).message).toBe('The WebRTC stream management takes a sensor UUID, but "not-a-uuid" is not one.') + }) + + it.each([ + { count: 0, tiers: [] }, + { + count: 2, + tiers: [AUDIO_TIERS.tiers[0], AUDIO_TIERS.tiers[0]], + }, + ])('refuses $count audio stream tiers with a type error naming the rule', ({ count, tiers }) => { + const error = constructionError({ + audioStreamTiers: { ...AUDIO_TIERS, tiers }, + }) + + expect(error).toBeInstanceOf(TypeError) + expect((error as TypeError).message).toBe(`The WebRTC stream management takes exactly one audio stream tier, but ${count} were supplied.`) + }) + + it('refuses stream tiers their characteristic cannot encode with a type error carrying the encoder\'s error', () => { + const error = constructionError({ + videoStreamTiers: { ...VIDEO_TIERS, payloadType: 256 }, + }) + + expect(error).toBeInstanceOf(TypeError) + expect((error as TypeError).message).toBe('The WebRTC stream management has stream tiers that WebRTC Supported Video or Audio Stream Tiers cannot encode.') + expect((error as TypeError).cause).toBeInstanceOf(RangeError) + }) + + it('adopts a saved service and serves its writes', async () => { + const saved = new Service.CameraWebRTCStreamManagement('', 'saved') + saved.updateCharacteristic(Characteristic.StreamingEnabled, true) + const { engine, service } = harness({}, saved) + const connection = buildEmitterConnection() + + expect(service).toBe(saved) + expect(service.subtype).toBe('saved') + expect(sessionOf(await solicit(service, connection))).toBe(engine.createOffer.mock.calls[0][0].sessionIdentifier) + expect(engine.createOffer.mock.calls[0][0].sensorUUID).toBe(SENSOR_UUID.toLowerCase()) + }) + + it('keeps the cached streaming enabled false of an adopted service', async () => { + const saved = new Service.CameraWebRTCStreamManagement('', 'saved') + saved.updateCharacteristic(Characteristic.StreamingEnabled, false) + const { engine, management, service } = harness({}, saved) + + expect(service.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(false) + expect(management.serialize()).toEqual({ streamingEnabled: false }) + expect(await solicit(service, buildEmitterConnection())).toEqual({ status: WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE }) + expect(engine.createOffer).not.toHaveBeenCalled() + }) + }) + + describe('solicit offer', () => { + it('answers a solicit without sframe with a fresh lowercase identifier and the delegate\'s offer', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const response = await solicit(service, connection) + const sessionIdentifier = sessionOf(response) + + expect(uuid.isValid(sessionIdentifier)).toBe(true) + expect(sessionIdentifier).toBe(sessionIdentifier.toLowerCase()) + expect(response).toEqual({ + status: WebRTCSolicitOfferStatus.SUCCESS, + sessionIdentifier, + sdpOffer: OFFER.sdpOffer, + additionalCandidates: OFFER.additionalCandidates, + }) + expect(engine.createOffer).toHaveBeenCalledExactlyOnceWith({ + options: { sframeEnabled: false }, + sessionIdentifier, + sensorUUID: SENSOR_UUID.toLowerCase(), + connection, + signal: expect.any(AbortSignal), + reporter: REPORTER, + }) + expect(activeSessions(service)).toBe(0) + }) + + it('answers a solicit of the empty value as a solicit without sframe, opening one session', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const response = decodeWebRTCSolicitOfferResponse(await write(service, Characteristic.WebRTCSolicitOffer, '', connection)) + const sessionIdentifier = sessionOf(response) + + expect(response).toEqual({ + status: WebRTCSolicitOfferStatus.SUCCESS, + sessionIdentifier, + sdpOffer: OFFER.sdpOffer, + additionalCandidates: OFFER.additionalCandidates, + }) + expect(engine.createOffer).toHaveBeenCalledExactlyOnceWith({ + options: { sframeEnabled: false }, + sessionIdentifier, + sensorUUID: SENSOR_UUID.toLowerCase(), + connection, + signal: expect.any(AbortSignal), + reporter: REPORTER, + }) + expect(await answer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(activeSessions(service)).toBe(1) + }) + + it('answers a solicit with sframe with the delegate\'s sframe configuration', async () => { + const { engine, service } = harness() + const sframeConfiguration = { + key: Buffer.alloc(16, 0x07), + kid: 2n ** 53n + 1n, + } + engine.createOffer.mockResolvedValueOnce({ ...OFFER, sframeConfiguration }) + const response = await solicit(service, buildEmitterConnection(), true) + + expect(response).toEqual({ + status: WebRTCSolicitOfferStatus.SUCCESS, + sessionIdentifier: sessionOf(response), + sdpOffer: OFFER.sdpOffer, + additionalCandidates: OFFER.additionalCandidates, + sframeConfiguration: { + key: Buffer.alloc(16, 0x07), + kid: 2n ** 53n + 1n, + }, + }) + expect(engine.createOffer.mock.calls[0][0].options).toEqual({ sframeEnabled: true }) + }) + + it('answers privacy mode active when the gate reads switched off, before capacity, with every slot full', async () => { + const { engine, gate, service } = harness() + const connection = buildEmitterConnection() + for (let index = 0; index < 6; index++) { + sessionOf(await solicit(service, connection)) + } + gate.reads = 'switched off' + + expect(await solicit(service, connection)).toEqual({ status: WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE }) + expect(engine.createOffer).toHaveBeenCalledTimes(6) + }) + + it('fails a solicit offer with the communication failure when the gate reads out of service, before capacity, with every slot full, calling no engine', + async () => { + const { engine, gate, service } = harness() + const connection = buildEmitterConnection() + for (let index = 0; index < 6; index++) { + sessionOf(await solicit(service, connection)) + } + gate.reads = 'out of service' + + await expect(solicit(service, connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(engine.createOffer).toHaveBeenCalledTimes(6) + }) + + it('publishes one debug event of a solicit offer failed while the camera is out of service and no answer\'s, and neither for one the gate refuses ' + + 'switched off', async () => { + const { gate, service } = harness() + const connection = buildEmitterConnection() + const events = captureDebugEvents('HAP-NodeJS:Camera:WebRTC') + + gate.reads = 'out of service' + await expect(solicit(service, connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + + const failed = events.splice(0) + + gate.reads = 'switched off' + await solicit(service, connection) + + expect(failed).toEqual([ + { + kind: 'offer-out-of-service', + sentence: 'Solicit Offer fails with the communication failure while the camera is out of service.', + }, + ]) + expect(events.map(({ kind }) => kind)).toEqual(['write-answered']) + }) + + it('ends every live session when streaming enabled turns false and answers privacy mode active after', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const connected = await connect(service, connection) + const offered = sessionOf(await solicit(service, connection)) + + await service.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, connection) + await settle() + + expect(engine.endSession.mock.calls).toEqual([ + [connected, REPORTER], + [offered, REPORTER], + ]) + expect(activeSessions(service)).toBe(0) + expect(await solicit(service, connection)).toEqual({ status: WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE }) + expect(engine.createOffer).toHaveBeenCalledTimes(2) + }) + + it('answers error when every slot is taken, without calling the delegate', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + for (let index = 0; index < 6; index++) { + sessionOf(await solicit(service, connection)) + } + + expect(await solicit(service, connection)).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + expect(engine.createOffer).toHaveBeenCalledTimes(6) + }) + + it('starts a second solicit\'s offer only once the first has settled', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const slow = deferred() + engine.createOffer.mockReturnValueOnce(slow.promise) + + const first = solicit(service, connection) + const second = solicit(service, connection) + await settle() + + expect(engine.createOffer).toHaveBeenCalledTimes(1) + + slow.resolve({ ...OFFER }) + sessionOf(await first) + sessionOf(await second) + + expect(engine.createOffer).toHaveBeenCalledTimes(2) + }) + + it('holds two solicits racing a slow delegate to the capacity', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + for (let index = 0; index < 5; index++) { + sessionOf(await solicit(service, connection)) + } + const slow = deferred() + engine.createOffer.mockReturnValueOnce(slow.promise) + + const first = solicit(service, connection) + const second = solicit(service, connection) + await settle() + slow.resolve({ ...OFFER }) + + sessionOf(await first) + expect(await second).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + expect(engine.createOffer).toHaveBeenCalledTimes(6) + }) + + it('keeps a stray session identifier from the delegate out of the responses', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const strayOffer = { ...OFFER, sessionIdentifier: UNKNOWN_SESSION } + const strayAnswer = { sdpAnswer: SDP_ANSWER, sessionIdentifier: UNKNOWN_SESSION, status: WebRTCStreamingStatus.BUSY } + engine.createOffer.mockResolvedValueOnce(strayOffer) + engine.reoffer.mockResolvedValueOnce(strayAnswer) + + const sessionIdentifier = sessionOf(await solicit(service, connection)) + expect(sessionIdentifier).toBe(engine.createOffer.mock.calls[0][0].sessionIdentifier) + expect(await answer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + + expect(await reoffer(service, connection, sessionIdentifier)).toEqual({ + sessionIdentifier, + status: WebRTCStreamingStatus.SUCCESS, + sdpAnswer: SDP_ANSWER, + }) + }) + }) + + describe('session commands', () => { + it('counts an accepted answer and notifies the count once', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const changes = countChanges(service) + const sessionIdentifier = sessionOf(await solicit(service, connection)) + + expect(changes).toEqual([]) + expect(await answer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(engine.acceptAnswer).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, { + sdpAnswer: SDP_ANSWER, + additionalCandidates: [CANDIDATE], + }) + expect(changes).toEqual([1]) + expect(activeSessions(service)).toBe(1) + }) + + it('answers an answer on an unknown session and on a connected one without calling the delegate', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + + expect(await answer(service, connection, UNKNOWN_SESSION)).toEqual({ + sessionIdentifier: UNKNOWN_SESSION, + status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + }) + + const sessionIdentifier = await connect(service, connection) + + expect(await answer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.BUSY }) + expect(engine.acceptAnswer).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, { + sdpAnswer: SDP_ANSWER, + additionalCandidates: [CANDIDATE], + }) + expect(activeSessions(service)).toBe(1) + }) + + it('answers reoffer and update session busy on an offered session, success on a connected one and unknown on an unknown one', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const offered = sessionOf(await solicit(service, connection)) + const connected = await connect(service, connection) + const sframeConfiguration = { + key: Buffer.alloc(16, 0x22), + kid: 5n, + } + engine.reoffer.mockResolvedValueOnce({ sdpAnswer: SDP_ANSWER, sframeConfiguration }) + + expect(await reoffer(service, connection, offered)).toEqual({ sessionIdentifier: offered, status: WebRTCStreamingStatus.BUSY }) + expect(await updateSession(service, connection, offered)).toEqual({ sessionIdentifier: offered, status: WebRTCStreamingStatus.BUSY }) + expect(engine.reoffer).not.toHaveBeenCalled() + expect(engine.updateReceiveKeys).not.toHaveBeenCalled() + + expect(await reoffer(service, connection, connected)).toEqual({ + sessionIdentifier: connected, + status: WebRTCStreamingStatus.SUCCESS, + sdpAnswer: SDP_ANSWER, + sframeConfiguration: { + key: Buffer.alloc(16, 0x22), + kid: 5n, + }, + }) + expect(engine.reoffer).toHaveBeenCalledExactlyOnceWith(connected, { + sdpOffer: SDP_REOFFER, + options: { sframeEnabled: true }, + }) + expect(await updateSession(service, connection, connected)).toEqual({ sessionIdentifier: connected, status: WebRTCStreamingStatus.SUCCESS }) + expect(engine.updateReceiveKeys).toHaveBeenCalledExactlyOnceWith(connected, { + receiveKeysToAdd: [ + { + key: Buffer.alloc(16, 0x11), + kid: 1n, + }, + ], + receiveKIDsToRemove: [ + { kid: 2n }, + ], + }, REPORTER) + + expect(await reoffer(service, connection, UNKNOWN_SESSION)).toEqual({ + sessionIdentifier: UNKNOWN_SESSION, + status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + }) + expect(await updateSession(service, connection, UNKNOWN_SESSION)).toEqual({ + sessionIdentifier: UNKNOWN_SESSION, + status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + }) + }) + + it('tells of no second view at a reoffer a connected session has answered', async () => { + const started: CameraLiveView[] = [] + const { service } = harness({ + onLiveViewStarted: view => started.push(view), + }) + const connection = buildEmitterConnection() + const sessionIdentifier = await connect(service, connection) + + expect(started).toHaveLength(1) + expect(await reoffer(service, connection, sessionIdentifier)).toMatchObject({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(started).toHaveLength(1) + }) + + it('answers a reoffer without options on a connected session as a reoffer without sframe', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const sessionIdentifier = await connect(service, connection) + // The Reoffer table's Session Identifier and SDP Offer items with no Options item, built by hand because the codec's encoder writes the Options its model + // requires. + const value = tlv.encode(0x01, uuid.write(sessionIdentifier), 0x02, SDP_REOFFER).toString('base64') + + expect(decodeWebRTCReofferResponse(await write(service, Characteristic.WebRTCReoffer, value, connection))).toEqual({ + sessionIdentifier, + status: WebRTCStreamingStatus.SUCCESS, + sdpAnswer: SDP_ANSWER, + }) + expect(engine.reoffer).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, { + sdpOffer: SDP_REOFFER, + options: { sframeEnabled: false }, + }) + }) + + it('ends a connected session on end, notifying the count, and an offered one without counting it', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const connected = await connect(service, connection) + const offered = sessionOf(await solicit(service, connection)) + const changes = countChanges(service) + + expect(await end(service, connection, connected)).toEqual({ sessionIdentifier: connected, status: WebRTCStreamingStatus.SUCCESS }) + expect(changes).toEqual([0]) + expect(await end(service, connection, offered)).toEqual({ sessionIdentifier: offered, status: WebRTCStreamingStatus.SUCCESS }) + expect(changes).toEqual([0]) + expect(engine.endSession.mock.calls).toEqual([ + [connected, REPORTER], + [offered, REPORTER], + ]) + expect(await end(service, connection, UNKNOWN_SESSION)).toEqual({ + sessionIdentifier: UNKNOWN_SESSION, + status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + }) + expect(engine.endSession).toHaveBeenCalledTimes(2) + }) + + it('ends a session once, aborting its signal, through an end and a later close', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const other = buildEmitterConnection() + const ended = await connect(service, connection) + const closed = await connect(service, other) + const [[endedRequest], [closedRequest]] = engine.createOffer.mock.calls + + await end(service, connection, ended) + + expect(endedRequest.signal.aborted).toBe(true) + expect(closedRequest.signal.aborted).toBe(false) + + connection.emit('closed') + await settle() + + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(ended, REPORTER) + + other.emit('closed') + await settle() + + expect(closedRequest.signal.aborted).toBe(true) + expect(engine.endSession.mock.calls).toEqual([ + [ended, REPORTER], + [closed, REPORTER], + ]) + expect(activeSessions(service)).toBe(0) + }) + + it('keeps every control point\'s value empty after its writes and answers a plain read empty, after a refused write too', async () => { + const { service } = harness() + const connection = buildEmitterConnection() + const sessionIdentifier = await connect(service, connection) + await reoffer(service, connection, sessionIdentifier) + await updateSession(service, connection, sessionIdentifier) + await end(service, connection, sessionIdentifier) + + for (const type of CONTROL_POINTS) { + const characteristic = service.getCharacteristic(type) + + expect(characteristic.value).toBe('') + await expect(characteristic.handleGetRequest()).resolves.toBe('') + await expect(characteristic.handleSetRequest('AQ==', connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(characteristic.value).toBe('') + await expect(characteristic.handleGetRequest()).resolves.toBe('') + } + }) + + it('answers a control point\'s last response to its writer\'s plain read and an empty TLV to another connection\'s, until the writer closes', async () => { + const { service } = harness() + const writer = buildEmitterConnection() + const other = buildEmitterConnection() + const solicitOffer = service.getCharacteristic(Characteristic.WebRTCSolicitOffer) + const request = encodeWebRTCSolicitOfferRequest({ + options: { sframeEnabled: false }, + }) + + const firstResponse = await write(service, Characteristic.WebRTCSolicitOffer, request, writer) + const lastResponse = await write(service, Characteristic.WebRTCSolicitOffer, request, writer) + + expect(lastResponse).not.toBe(firstResponse) + await expect(solicitOffer.handleGetRequest(writer)).resolves.toBe(lastResponse) + await expect(solicitOffer.handleGetRequest(other)).resolves.toBe('') + + writer.emit('closed') + await settle() + + await expect(solicitOffer.handleGetRequest(writer)).resolves.toBe('') + }) + + it('refuses a write without a connection, a malformed write and an unknown command as an invalid value', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const sessionIdentifier = await connect(service, connection) + const writes = [ + encodeWebRTCSolicitOfferRequest({ + options: { sframeEnabled: false }, + }), + encodeWebRTCProvideAnswerRequest({ sessionIdentifier, sdpAnswer: SDP_ANSWER, additionalCandidates: [] }), + encodeWebRTCStreamingControlRequest({ sessionIdentifier, command: WebRTCStreamingCommand.END }), + encodeWebRTCReofferRequest({ + sessionIdentifier, + sdpOffer: SDP_REOFFER, + options: { sframeEnabled: false }, + }), + encodeWebRTCUpdateSessionRequest({ sessionIdentifier, receiveKeysToAdd: [], receiveKIDsToRemove: [] }), + ] + + for (const [index, type] of CONTROL_POINTS.entries()) { + const characteristic = service.getCharacteristic(type) + + await expect(characteristic.handleSetRequest(writes[index])).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + await expect(characteristic.handleSetRequest('AQ==', connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + // Solicit Offer reads the empty value as a solicit without SFrame, which is why only the other control points refuse it. + for (const type of CONTROL_POINTS.filter(controlPoint => controlPoint !== Characteristic.WebRTCSolicitOffer)) { + await expect(service.getCharacteristic(type).handleSetRequest('', connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + const unknownCommand = encodeWebRTCStreamingControlRequest({ sessionIdentifier, command: 2 as WebRTCStreamingCommand }) + await expect(service.getCharacteristic(Characteristic.WebRTCStreamingControl).handleSetRequest(unknownCommand, connection)) + .rejects + .toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + + expect(engine.createOffer).toHaveBeenCalledTimes(1) + expect(engine.reoffer).not.toHaveBeenCalled() + expect(engine.updateReceiveKeys).not.toHaveBeenCalled() + expect(engine.endSession).not.toHaveBeenCalled() + expect(activeSessions(service)).toBe(1) + }) + + // Node's decoder reads the value as no bytes at all, which Solicit Offer would read as a solicit without SFrame. Only the canonical check refuses it. + it('refuses a solicit offer that is not canonical base64 as an invalid value, asking the engine for no offer and holding no answer', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const solicitOffer = service.getCharacteristic(Characteristic.WebRTCSolicitOffer) + + await expect(solicitOffer.handleSetRequest('!!!!', connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(engine.createOffer).not.toHaveBeenCalled() + await expect(solicitOffer.handleGetRequest(connection)).resolves.toBe('') + }) + + it('publishes an update of eight keys as one debug event whose sentence stays on one line, naming the key IDs and the key lengths', async () => { + const events = captureDebugEvents('HAP-NodeJS:Camera:WebRTC') + const { service } = harness() + const connection = buildEmitterConnection() + const sessionIdentifier = await connect(service, connection) + const ids = ['1', '2', '3', '4', '5', '6', '7', '8'] + const keys = ids.map(kid => ({ + key: Buffer.alloc(16, 0x11), + kid: BigInt(kid), + })) + + expect(await updateSession(service, connection, sessionIdentifier, keys, [])).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(events.filter(({ kind }) => kind === 'keys-updated')).toStrictEqual([ + { + added: ids, + kind: 'keys-updated', + lengths: [16, 16, 16, 16, 16, 16, 16, 16], + removed: [], + sentence: `Update Session for WebRTC session ${sessionIdentifier} adds key IDs [ '1', '2', '3', '4', '5', '6', '7', '8' ] ` + + '([ 16, 16, 16, 16, 16, 16, 16, 16 ] bytes) and removes key IDs [].', + sessionIdentifier, + }, + ]) + + await end(service, connection, sessionIdentifier) + }) + + it('hands the engine the very receive keys it decoded and holds none of them, zeroing none at the session\'s end and leaving the engine\'s keys ' + + 'untouched', async () => { + // The decoder is spied before the harness, because the class takes it when it wires its control points. The row reads the keys it decoded. + const decode = vi.spyOn(webrtc, 'decodeWebRTCUpdateSessionRequest') + const { engine, management, service } = harness() + const connection = buildEmitterConnection() + const offerKey = { + key: Buffer.alloc(16, 0x0E), + kid: 7n, + } + const answerKey = { + key: Buffer.alloc(16, 0x0F), + kid: 8n, + } + engine.createOffer.mockResolvedValueOnce({ ...OFFER, sframeConfiguration: offerKey }) + engine.reoffer.mockResolvedValueOnce({ sdpAnswer: SDP_ANSWER, sframeConfiguration: answerKey }) + const sessionIdentifier = await connect(service, connection) + await reoffer(service, connection, sessionIdentifier) + + expect(await updateSession(service, connection, sessionIdentifier, [ + { + key: Buffer.alloc(16, 0xAB), + kid: 1n, + }, + { + key: Buffer.alloc(32, 0xCD), + kid: 2n ** 53n + 1n, + }, + ])).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + + const decoded = decode.mock.results.filter(result => result.type === 'return').flatMap(({ value }) => value.receiveKeysToAdd.map(({ key }) => key)) + const handed = engine.updateReceiveKeys.mock.calls[0][1].receiveKeysToAdd.map(({ key }) => key) + + expect(decoded).toEqual([ + Buffer.alloc(16, 0xAB), + Buffer.alloc(32, 0xCD), + ]) + expect(handed).toHaveLength(decoded.length) + expect(handed.every((key, index) => key === decoded[index])).toBe(true) + expect(managementReaches(management, sessionIdentifier, [connection])).toBe(true) + expect(managementReaches(management, sessionIdentifier, decoded)).toBe(false) + + await end(service, connection, sessionIdentifier) + + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, REPORTER) + expect(decoded).toEqual([ + Buffer.alloc(16, 0xAB), + Buffer.alloc(32, 0xCD), + ]) + expect(offerKey.key).toEqual(Buffer.alloc(16, 0x0E)) + expect(answerKey.key).toEqual(Buffer.alloc(16, 0x0F)) + }) + + it('zeroes the decoded receive keys of an update session answered busy or unknown at once, without calling the delegate', async () => { + // No engine call carries these keys, which is why the row reads them from the decoder, spied before the harness because the class takes the decoder when it + // wires its control points. + const decode = vi.spyOn(webrtc, 'decodeWebRTCUpdateSessionRequest') + const { engine, service } = harness() + const connection = buildEmitterConnection() + const offered = sessionOf(await solicit(service, connection)) + + expect(await updateSession(service, connection, offered)).toEqual({ sessionIdentifier: offered, status: WebRTCStreamingStatus.BUSY }) + expect(await updateSession(service, connection, UNKNOWN_SESSION)).toEqual({ + sessionIdentifier: UNKNOWN_SESSION, + status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + }) + + const decoded = decode.mock.results.filter(result => result.type === 'return').flatMap(({ value }) => value.receiveKeysToAdd.map(({ key }) => key)) + + expect(decoded).toEqual([ + Buffer.alloc(16), + Buffer.alloc(16), + ]) + expect(engine.endSession).not.toHaveBeenCalled() + expect(engine.updateReceiveKeys).not.toHaveBeenCalled() + }) + + it('answers unknown session identifier to every command another connection writes naming a session, reaching no delegate method for it', async () => { + // The decoder is spied before the harness, because the class takes it when it wires its control points. The row reads the keys it decoded. + const decode = vi.spyOn(webrtc, 'decodeWebRTCUpdateSessionRequest') + const { engine, service } = harness() + const opener = buildEmitterConnection() + const other = buildEmitterConnection() + const sessionIdentifier = await connect(service, opener) + const unknown = { sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER } + + expect(await answer(service, other, sessionIdentifier)).toEqual(unknown) + expect(await end(service, other, sessionIdentifier)).toEqual(unknown) + expect(await reoffer(service, other, sessionIdentifier)).toEqual(unknown) + expect(await updateSession(service, other, sessionIdentifier)).toEqual(unknown) + expect(engine.acceptAnswer).toHaveBeenCalledTimes(1) + expect(engine.reoffer).not.toHaveBeenCalled() + expect(engine.updateReceiveKeys).not.toHaveBeenCalled() + expect(decode.mock.results.filter(result => result.type === 'return').flatMap(({ value }) => value.receiveKeysToAdd.map(({ key }) => key))).toEqual([ + Buffer.alloc(16), + ]) + expect(engine.endSession).not.toHaveBeenCalled() + expect(activeSessions(service)).toBe(1) + + expect(await end(service, opener, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, REPORTER) + }) + }) + + describe('teardown', () => { + it('ends every session of a closed connection and none of another', async () => { + const { engine, service } = harness() + const closing = buildEmitterConnection() + const other = buildEmitterConnection() + const connected = await connect(service, closing) + const offered = sessionOf(await solicit(service, closing)) + const survivor = await connect(service, other) + + closing.emit('closed') + await settle() + + expect(engine.endSession.mock.calls).toEqual([ + [connected, REPORTER], + [offered, REPORTER], + ]) + expect(activeSessions(service)).toBe(1) + expect(closing.listenerCount('closed')).toBe(0) + // The surviving session's listener, and the answers its Solicit Offer and Provide Answer hold. + expect(other.listenerCount('closed')).toBe(3) + expect(await reoffer(service, other, survivor)).toEqual({ sessionIdentifier: survivor, status: WebRTCStreamingStatus.SUCCESS, sdpAnswer: SDP_ANSWER }) + }) + + it('ends a session whose connection closes during its offer and answers its solicit with error', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const slow = deferred() + engine.createOffer.mockReturnValueOnce(slow.promise) + + const soliciting = solicit(service, connection) + await settle() + const [[request]] = engine.createOffer.mock.calls + connection.emit('closed') + await settle() + + expect(request.signal.aborted).toBe(true) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(request.sessionIdentifier, REPORTER) + + slow.resolve({ ...OFFER }) + + expect(await soliciting).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + expect(activeSessions(service)).toBe(0) + }) + + it('ends a session whose connection closes during its answer and answers unknown session identifier with the count 0', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const sessionIdentifier = sessionOf(await solicit(service, connection)) + const slow = deferred() + engine.acceptAnswer.mockReturnValueOnce(slow.promise) + + const answering = answer(service, connection, sessionIdentifier) + await settle() + connection.emit('closed') + await settle() + slow.resolve() + + expect(await answering).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER }) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, REPORTER) + expect(activeSessions(service)).toBe(0) + }) + + it('ends a session once when its connection closes during a reoffer, and during an update session', async () => { + const { engine, service } = harness() + const reoffering = buildEmitterConnection() + const updating = buildEmitterConnection() + const reoffered = await connect(service, reoffering) + const updated = await connect(service, updating) + const slowReoffer = deferred() + const slowUpdate = deferred() + engine.reoffer.mockReturnValueOnce(slowReoffer.promise) + engine.updateReceiveKeys.mockReturnValueOnce(slowUpdate.promise) + + const reofferResponse = reoffer(service, reoffering, reoffered) + await settle() + reoffering.emit('closed') + await settle() + slowReoffer.resolve({ sdpAnswer: SDP_ANSWER }) + + expect(await reofferResponse).toEqual({ sessionIdentifier: reoffered, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER }) + + const updateResponse = updateSession(service, updating, updated) + await settle() + updating.emit('closed') + await settle() + slowUpdate.resolve() + + expect(await updateResponse).toEqual({ sessionIdentifier: updated, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER }) + expect(engine.updateReceiveKeys.mock.calls[0][1].receiveKeysToAdd[0].key).toEqual(Buffer.alloc(16, 0x11)) + expect(engine.endSession.mock.calls).toEqual([ + [reoffered, REPORTER], + [updated, REPORTER], + ]) + expect(activeSessions(service)).toBe(0) + }) + + it('answers error to a solicit whose connection closed while it waited, without calling the delegate or adding a listener', async () => { + const { engine, service } = harness() + const first = buildEmitterConnection() + const closing = buildEmitterConnection() + const slow = deferred() + engine.createOffer.mockReturnValueOnce(slow.promise) + + const firstResponse = solicit(service, first) + const closingResponse = solicit(service, closing) + await settle() + closing.emit('closed') + slow.resolve({ ...OFFER }) + + sessionOf(await firstResponse) + expect(await closingResponse).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + expect(engine.createOffer).toHaveBeenCalledTimes(1) + expect(closing.listenerCount('closed')).toBe(0) + }) + + it('leaves no close listener on any connection after destroy', async () => { + const { engine, management, service } = harness() + const first = buildEmitterConnection() + const second = buildEmitterConnection() + const limit = first.getMaxListeners() + await connect(service, first) + sessionOf(await solicit(service, first)) + await connect(service, second) + + // The sessions' one listener, and the answers the Solicit Offer and Provide Answer hold. + expect(first.listenerCount('closed')).toBe(3) + expect(first.getMaxListeners()).toBe(limit + 3) + + await management.destroy() + + expect(first.listenerCount('closed')).toBe(0) + expect(second.listenerCount('closed')).toBe(0) + expect(first.getMaxListeners()).toBe(limit) + expect(second.getMaxListeners()).toBe(limit) + expect(engine.endSession).toHaveBeenCalledTimes(3) + expect(activeSessions(service)).toBe(0) + + for (const connection of [first, second]) { + for (const type of CONTROL_POINTS) { + await expect(service.getCharacteristic(type).handleGetRequest(connection)).resolves.toBe('') + } + } + }) + + it('ends a session once when destroy runs during an await, and answers a later write without the delegate or a session', async () => { + const { engine, management, service } = harness() + const connection = buildEmitterConnection() + const sessionIdentifier = sessionOf(await solicit(service, connection)) + const slow = deferred() + engine.acceptAnswer.mockReturnValueOnce(slow.promise) + + const answering = answer(service, connection, sessionIdentifier) + const soliciting = solicit(service, connection) + await settle() + await management.destroy() + slow.resolve() + + expect(await answering).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER }) + expect(await soliciting).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + expect(await end(service, connection, sessionIdentifier)).toEqual({ + sessionIdentifier, + status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + }) + expect(engine.createOffer).toHaveBeenCalledTimes(1) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, REPORTER) + // The answers the Provide Answer, Solicit Offer and Streaming Control writes hold, each answered after destroy and none a session. + expect(connection.listenerCount('closed')).toBe(3) + }) + + it('ends a session for the engine and every session for the owner', async () => { + const { engine, management, service } = harness() + const connection = buildEmitterConnection() + const engineEnded = await connect(service, connection) + const offered = sessionOf(await solicit(service, connection)) + const connected = await connect(service, connection) + + await management.endSession(engineEnded) + await management.endSession(engineEnded) + await management.endSession(UNKNOWN_SESSION) + + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(engineEnded, REPORTER) + expect(activeSessions(service)).toBe(1) + + await management.endAllSessions() + + expect(engine.endSession.mock.calls).toEqual([ + [engineEnded, REPORTER], + [offered, REPORTER], + [connected, REPORTER], + ]) + expect(activeSessions(service)).toBe(0) + expect(connection.listenerCount('closed')).toBe(0) + }) + + it('leaves one held answer and no session listener on the connection, and none on the signals, of sessions opened and ended in a loop', async () => { + const timeouts = vi.spyOn(AbortSignal, 'timeout') + const { engine, service } = harness() + const connection = buildEmitterConnection() + const limit = connection.getMaxListeners() + + for (let round = 0; round < 20; round++) { + const sessionIdentifier = round % 2 === 0 + ? await connect(service, connection) + : sessionOf(await solicit(service, connection)) + await end(service, connection, sessionIdentifier) + } + + // Each End's exit releases the round's other answers before the End's own is held, and the last End's answer is all that stays. + expect(connection.listenerCount('closed')).toBe(1) + expect(connection.getMaxListeners()).toBe(limit + 1) + expect(engine.createOffer.mock.calls.flatMap(([request]) => getEventListeners(request.signal, 'abort'))).toEqual([]) + expect(timeouts.mock.results.length).toBeGreaterThan(0) + expect(timeouts.mock.results.flatMap(({ value }) => getEventListeners(value as AbortSignal, 'abort'))).toEqual([]) + }) + + it('releases a writer\'s held solicit offer answer at its session\'s end, at streaming enabled off and at a factory reset, which ends its session', async () => { + const { engine, management, service } = harness() + const connection = buildEmitterConnection() + const solicitOffer = service.getCharacteristic(Characteristic.WebRTCSolicitOffer) + const request = encodeWebRTCSolicitOfferRequest({ + options: { sframeEnabled: false }, + }) + + const ended = await write(service, Characteristic.WebRTCSolicitOffer, request, connection) + + await expect(solicitOffer.handleGetRequest(connection)).resolves.toBe(ended) + + await end(service, connection, sessionOf(decodeWebRTCSolicitOfferResponse(ended))) + + await expect(solicitOffer.handleGetRequest(connection)).resolves.toBe('') + + const disabled = await write(service, Characteristic.WebRTCSolicitOffer, request, connection) + + await expect(solicitOffer.handleGetRequest(connection)).resolves.toBe(disabled) + + await service.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, connection) + await settle() + + await expect(solicitOffer.handleGetRequest(connection)).resolves.toBe('') + + management.handleFactoryReset() + const reset = await write(service, Characteristic.WebRTCSolicitOffer, request, connection) + + await expect(solicitOffer.handleGetRequest(connection)).resolves.toBe(reset) + + management.handleFactoryReset() + + await expect(solicitOffer.handleGetRequest(connection)).resolves.toBe('') + expect(engine.endSession).toHaveBeenCalledTimes(3) + expect(engine.endSession).toHaveBeenNthCalledWith(3, sessionOf(decodeWebRTCSolicitOfferResponse(reset)), REPORTER) + }) + + it('ends every session and tells the engine of each when streaming enabled turns off under a state-change delegate that throws', async () => { + const { engine, management, service } = harness() + const connection = buildEmitterConnection() + const connected = await connect(service, connection) + const offered = sessionOf(await solicit(service, connection)) + management.setupStateChangeDelegate(() => { + throw new Error('The state could not be saved.') + }) + + expect(() => service.getCharacteristic(Characteristic.StreamingEnabled).updateValue(false)).toThrow('The state could not be saved.') + await settle() + + expect(engine.endSession.mock.calls).toEqual([ + [connected, REPORTER], + [offered, REPORTER], + ]) + expect(activeSessions(service)).toBe(0) + expect(connection.listenerCount('closed')).toBe(0) + }) + }) + + describe('persistence', () => { + it('serializes, restores and factory resets streaming enabled, calling the state change delegate on each change', async () => { + const { management, service } = harness() + const stateChange = vi.fn() + const streamingEnabled = service.getCharacteristic(Characteristic.StreamingEnabled) + management.setupStateChangeDelegate(stateChange) + + management.deserialize({ streamingEnabled: false }) + + expect(streamingEnabled.value).toBe(false) + expect(management.serialize()).toEqual({ streamingEnabled: false }) + expect(stateChange).toHaveBeenCalledTimes(1) + + management.handleFactoryReset() + + expect(management.serialize()).toEqual({ streamingEnabled: true }) + expect(stateChange).toHaveBeenCalledTimes(2) + + await streamingEnabled.handleSetRequest(false, buildEmitterConnection()) + + expect(management.serialize()).toEqual({ streamingEnabled: false }) + expect(stateChange).toHaveBeenCalledTimes(3) + + management.setupStateChangeDelegate() + management.handleFactoryReset() + + expect(stateChange).toHaveBeenCalledTimes(3) + }) + }) + + describe('delegate failures', () => { + // The listener collects each rejection no handler takes during a row, any of which would end a Homebridge process. + const unhandled: unknown[] = [] + const collect = (reason: unknown): void => { + unhandled.push(reason) + } + + beforeEach(() => { + unhandled.length = 0 + process.on('unhandledRejection', collect) + }) + + afterEach(() => { + process.off('unhandledRejection', collect) + }) + + it('logs a rejected offer once, answers error and ends the session', async () => { + const { engine, service } = harness() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + engine.createOffer.mockRejectedValueOnce(new Error('The engine failed.')) + + expect(await solicit(service, buildEmitterConnection())).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('The WebRTC engine failed to create an offer: Error: The engine failed.'), + ], + ]) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(engine.createOffer.mock.calls[0][0].sessionIdentifier, REPORTER) + expect(unhandled).toEqual([]) + }) + + it('logs an offer that throws once, answers error and ends the session', async () => { + const { engine, service } = harness() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + engine.createOffer.mockImplementationOnce(() => { + throw new Error('The engine threw.') + }) + + expect(await solicit(service, buildEmitterConnection())).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('The WebRTC engine failed to create an offer: Error: The engine threw.'), + ], + ]) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(engine.createOffer.mock.calls[0][0].sessionIdentifier, REPORTER) + expect(unhandled).toEqual([]) + }) + + it('logs a rejected answer once, answers error and ends the session uncounted', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const sessionIdentifier = sessionOf(await solicit(service, connection)) + engine.acceptAnswer.mockRejectedValueOnce(new Error('The engine failed.')) + + expect(await answer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.ERROR }) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('The WebRTC engine failed to accept an answer: Error: The engine failed.'), + ], + ]) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, REPORTER) + expect(activeSessions(service)).toBe(0) + expect(unhandled).toEqual([]) + }) + + it('logs a rejected reoffer and a rejected key update once each, answers error and keeps the session', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const sessionIdentifier = await connect(service, connection) + engine.reoffer.mockRejectedValueOnce(new Error('The engine failed to reoffer.')) + engine.updateReceiveKeys.mockRejectedValueOnce(new Error('The engine failed to update.')) + + expect(await reoffer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.ERROR }) + expect(await updateSession(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.ERROR }) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('The WebRTC engine failed to answer a reoffer: Error: The engine failed to reoffer.'), + ], + [ + expect.stringContaining('The WebRTC engine failed to update the receive keys: Error: The engine failed to update.'), + ], + ]) + expect(engine.endSession).not.toHaveBeenCalled() + expect(activeSessions(service)).toBe(1) + expect(await reoffer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS, sdpAnswer: SDP_ANSWER }) + expect(unhandled).toEqual([]) + }) + + // A promise that rejects as the signal aborts, as an engine's call does once the session it serves ends. + async function rejectedAtEnd(signal: AbortSignal): Promise { + return await new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(new Error('The session ended.')), { once: true }) + }) + } + + // Each engine call on a live session, driven until it is pending, the engine rejecting it once the session's signal, which its offer request carries, + // aborts. Each driver answers the command whose call is pending. + const PENDING_CALLS: readonly [keyof WebRTCStreamEngine, (driven: Harness, connection: HAPConnection) => Promise<{ command: Promise }>][] = [ + [ + 'createOffer', + async ({ engine, service }, connection) => { + engine.createOffer.mockImplementationOnce(async ({ signal }) => await rejectedAtEnd(signal)) + + return { + command: solicit(service, connection), + } + }, + ], + [ + 'acceptAnswer', + async ({ engine, service }, connection) => { + const sessionIdentifier = sessionOf(await solicit(service, connection)) + const [[{ signal }]] = engine.createOffer.mock.calls + + engine.acceptAnswer.mockImplementationOnce(async () => await rejectedAtEnd(signal)) + + return { + command: answer(service, connection, sessionIdentifier), + } + }, + ], + [ + 'reoffer', + async ({ engine, service }, connection) => { + const sessionIdentifier = await connect(service, connection) + const [[{ signal }]] = engine.createOffer.mock.calls + + engine.reoffer.mockImplementationOnce(async () => await rejectedAtEnd(signal)) + + return { + command: reoffer(service, connection, sessionIdentifier), + } + }, + ], + [ + 'updateReceiveKeys', + async ({ engine, service }, connection) => { + const sessionIdentifier = await connect(service, connection) + const [[{ signal }]] = engine.createOffer.mock.calls + + engine.updateReceiveKeys.mockImplementationOnce(async () => await rejectedAtEnd(signal)) + + return { + command: updateSession(service, connection, sessionIdentifier), + } + }, + ], + ] + + it.each(PENDING_CALLS)('logs no failure of %s for a call the library cut by ending its session at a destroy, the engine rejecting it as the session ' + + 'ends', async (call, pending) => { + const driven = harness() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { command } = await pending(driven, buildEmitterConnection()) + + await settle() + + expect(driven.engine[call]).toHaveBeenCalledOnce() + + await driven.management.destroy() + await command + await settle() + + expect(error.mock.calls.filter(([line]) => String(line).startsWith('The WebRTC engine failed to'))).toEqual([]) + expect(driven.engine.endSession).toHaveBeenCalledOnce() + expect(unhandled).toEqual([]) + }) + + it('logs a rejected teardown once and still ends the session', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const sessionIdentifier = await connect(service, connection) + engine.endSession.mockRejectedValueOnce(new Error('The engine failed to end.')) + + expect(await end(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('The WebRTC engine failed to end a session: Error: The engine failed to end.'), + ], + ]) + expect(activeSessions(service)).toBe(0) + expect(unhandled).toEqual([]) + }) + + it('warns once, ends the session and answers error for an offer the solicit offer response cannot carry', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + engine.createOffer.mockResolvedValueOnce({ + ...OFFER, + additionalCandidates: [ + { ...CANDIDATE, sdpMLineIndex: 65536 }, + ], + }) + + expect(await solicit(service, connection)).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + await settle() + + const { sessionIdentifier } = engine.createOffer.mock.calls[0][0] + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('createOffer') + expect(warn.mock.calls[0][0]).toContain(sessionIdentifier) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, REPORTER) + expect(activeSessions(service)).toBe(0) + expect((await solicit(service, connection)).status).toBe(WebRTCSolicitOfferStatus.SUCCESS) + expect(unhandled).toEqual([]) + }) + + it('warns once and answers error, keeping the session, for a reoffer answer the reoffer response cannot carry', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const sessionIdentifier = await connect(service, connection) + engine.reoffer.mockResolvedValueOnce({ + sdpAnswer: SDP_ANSWER, + sframeConfiguration: { + key: Buffer.alloc(16, 0x22), + kid: 2n ** 64n, + }, + }) + + expect(await reoffer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.ERROR }) + await settle() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toContain('reoffer') + expect(warn.mock.calls[0][0]).toContain(sessionIdentifier) + expect(engine.endSession).not.toHaveBeenCalled() + expect(activeSessions(service)).toBe(1) + expect(await end(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(unhandled).toEqual([]) + }) + }) + + describe('bounded waits', () => { + beforeEach(() => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + fakeTimeoutSignals() + }) + + it('cuts an offer that does not settle at the delegate call bound with one warning, ends its session once and releases the queue', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const late = deferred() + engine.createOffer.mockReturnValueOnce(late.promise) + + const cut = solicit(service, connection) + const queued = solicit(service, connection) + await vi.advanceTimersByTimeAsync(29999) + const [[request]] = engine.createOffer.mock.calls + + expect(warn).not.toHaveBeenCalled() + expect(engine.createOffer).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(1) + + expect(warn.mock.calls).toEqual([ + [`The WebRTC engine did not settle createOffer for WebRTC session ${request.sessionIdentifier} within 30 seconds, and the session ends without it.`], + ]) + expect(request.signal.aborted).toBe(true) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(request.sessionIdentifier, REPORTER) + expect(await cut).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + + const sessionIdentifier = sessionOf(await queued) + late.resolve({ ...OFFER }) + await vi.advanceTimersByTimeAsync(0) + + expect(engine.createOffer).toHaveBeenCalledTimes(2) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(request.sessionIdentifier, REPORTER) + expect(await answer(service, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(await answer(service, connection, request.sessionIdentifier)).toEqual({ + sessionIdentifier: request.sessionIdentifier, + status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER, + }) + expect(activeSessions(service)).toBe(1) + expect(warn).toHaveBeenCalledTimes(1) + }) + + it('answers a solicit whose offer is cut at the delegate call bound only once its session\'s whole exit has resolved, its teardown included', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const teardown = deferred() + engine.createOffer.mockReturnValueOnce(deferred().promise) + engine.endSession.mockReturnValueOnce(teardown.promise) + + // The answer is recorded as it arrives rather than awaited. An answer that comes ahead of the exit fails an assertion instead of the row's timeout. + const answers: WebRTCSolicitOfferResponse[] = [] + void solicit(service, connection).then((response) => { + answers.push(response) + }) + await vi.advanceTimersByTimeAsync(29999) + await vi.advanceTimersByTimeAsync(1) + + expect(warn).toHaveBeenCalledTimes(1) + expect(engine.endSession).toHaveBeenCalledOnce() + expect(answers).toEqual([]) + + teardown.resolve() + await vi.advanceTimersByTimeAsync(0) + + expect(answers).toEqual([ + { status: WebRTCSolicitOfferStatus.ERROR }, + ]) + }) + + it('cuts an end whose teardown does not settle at the delegate call bound with one warning and releases the queue', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const sessionIdentifier = await connect(service, connection) + engine.endSession.mockReturnValueOnce(deferred().promise) + + // Each answer is recorded as it arrives rather than awaited: a wait the bound does not cut fails an assertion instead of the row's timeout. + const answers: { end?: WebRTCSessionStatusResponse, solicit?: WebRTCSolicitOfferResponse } = {} + void end(service, connection, sessionIdentifier).then((response) => { + answers.end = response + }) + void solicit(service, connection).then((response) => { + answers.solicit = response + }) + await vi.advanceTimersByTimeAsync(29999) + + expect(answers).toEqual({}) + expect(engine.createOffer).toHaveBeenCalledTimes(1) + expect(warn).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + + expect(answers.end).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(engine.createOffer).toHaveBeenCalledTimes(2) + expect(answers.solicit).toEqual({ + status: WebRTCSolicitOfferStatus.SUCCESS, + sessionIdentifier: engine.createOffer.mock.calls[1][0].sessionIdentifier, + sdpOffer: OFFER.sdpOffer, + additionalCandidates: OFFER.additionalCandidates, + }) + expect(warn.mock.calls).toEqual([ + [`The WebRTC engine did not settle endSession for WebRTC session ${sessionIdentifier} within 30 seconds, and the session ends without it.`], + ]) + }) + + it('ends an offered session whose answer has not arrived at the offer expiry with one warning, and never a connected one', async () => { + const { engine, service } = harness() + const connection = buildEmitterConnection() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const offered = sessionOf(await solicit(service, connection)) + const connected = await connect(service, connection) + const [, [connectedRequest]] = engine.createOffer.mock.calls + const changes = countChanges(service) + + await vi.advanceTimersByTimeAsync(59999) + + expect(warn).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + + expect(warn.mock.calls).toEqual([ + [`WebRTC session ${offered} had no answer to its offer accepted within 60 seconds. The session ends.`], + ]) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(offered, REPORTER) + expect(changes).toEqual([]) + expect(activeSessions(service)).toBe(1) + expect(connectedRequest.signal.aborted).toBe(false) + + await vi.advanceTimersByTimeAsync(10 * 60 * 1000) + + expect(warn).toHaveBeenCalledTimes(1) + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(offered, REPORTER) + expect(await reoffer(service, connection, connected)).toEqual({ sessionIdentifier: connected, status: WebRTCStreamingStatus.SUCCESS, sdpAnswer: SDP_ANSWER }) + expect(await answer(service, connection, offered)).toEqual({ sessionIdentifier: offered, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER }) + }) + + it.each([ + { + kind: 'view-failed', + // An offered session whose answer never arrives, ended at the offer's expiry. + raise: async ({ service }: Harness): Promise => { + const sessionIdentifier = sessionOf(await solicit(service, buildEmitterConnection())) + + await vi.advanceTimersByTimeAsync(60000) + + return sessionIdentifier + }, + site: 'a session its offer\'s expiry ends', + }, + { + kind: 'library-failure', + // An offer the engine never settles, cut at the delegate call bound. + raise: async ({ engine, service }: Harness): Promise => { + engine.createOffer.mockReturnValueOnce(deferred().promise) + + const cut = solicit(service, buildEmitterConnection()) + + await vi.advanceTimersByTimeAsync(30000) + await cut + + return engine.createOffer.mock.calls[0][0].sessionIdentifier + }, + site: 'an engine call cut at its bound', + }, + ])('raises one problem of its kind at the level warning naming the sensor and the session for $site', async ({ kind, raise }) => { + const { problems, reporter } = problemsOf() + const sessionIdentifier = await raise(harness({ reporter })) + + // Each problem is read whole, its sentence's wording aside, and a field it gains or loses is read too. + expect(problems).toEqual([ + { + accessoryUUID: expect.any(String), + kind, + level: 'warning', + sensorUUID: SENSOR_UUID.toLowerCase(), + sentence: expect.any(String), + sessionIdentifier, + }, + ]) + }) + }) + + describe('camera controller wiring', () => { + const GLOBAL_KEY = 'cameraCapabilities:globalOperatingMode' + const CAPABILITIES_KEY = 'cameraCapabilities:cameraCapabilities' + // The HKSV3 recording management's keys, the last of the block's. + const RECORDING_KEYS = [ + 'cameraCapabilities:cameraBufferManagement', + 'cameraCapabilities:cameraKeyManagement', + 'cameraCapabilities:cameraClientCertificateManagement', + ] + const FIRST_SENSOR = videoSensor('A1B2C3D4-0000-4000-8000-000000000001') + const FIRST_KEY = 'cameraCapabilities:webRTCStream:a1b2c3d4-0000-4000-8000-000000000001' + const FIRST_MULTI_TIER_KEY = 'cameraCapabilities:multiTierStream:a1b2c3d4-0000-4000-8000-000000000001' + const SECOND_SENSOR = videoSensor('B0000002-0000-4000-8000-000000000002', { intent: CameraSensorIntent.PACKAGE }) + const SECOND_KEY = 'cameraCapabilities:webRTCStream:b0000002-0000-4000-8000-000000000002' + const SECOND_MULTI_TIER_KEY = 'cameraCapabilities:multiTierStream:b0000002-0000-4000-8000-000000000002' + const REMOVED_SENSOR = { + ...SECOND_SENSOR, + uuid: 'C0000003-0000-4000-8000-000000000003', + } + const REMOVED_KEY = 'cameraCapabilities:webRTCStream:c0000003-0000-4000-8000-000000000003' + + // The cameras a row builds, removed after it. No session or policy listener outlives its row. + const cameras: CameraController[] = [] + // The scripted calls every camera's own engine answers through, each of the engine's methods spied on its class, the spies restored after each row. + let engine: ScriptedEngine + + beforeEach(() => { + // The engine's class as the contract types it: each spy hands the scripted call every argument the management hands the engine. + const contract: WebRTCStreamEngine = WebRTCEngine.prototype + + engine = scriptedEngine() + vi.spyOn(contract, 'createOffer').mockImplementation(engine.createOffer) + vi.spyOn(contract, 'acceptAnswer').mockImplementation(engine.acceptAnswer) + vi.spyOn(contract, 'reoffer').mockImplementation(engine.reoffer) + vi.spyOn(contract, 'updateReceiveKeys').mockImplementation(engine.updateReceiveKeys) + vi.spyOn(contract, 'endSession').mockImplementation(engine.endSession) + }) + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + }) + + // The options of a camera with the camera capabilities block over the given sensors and the webrtc member, which the camera's own engine serves, + // recording from its camera buffer. + function wiredOptions( + sensors: readonly CameraVideoSensor[] = [FIRST_SENSOR, SECOND_SENSOR], + streaming = idleStreaming(), + webrtc: WebRTCStreamingOptions = {}, + ): CameraControllerOptions { + return capabilitiesCameraOptions({ + videoSensors: [...sensors], + streaming, + webrtc, + }) + } + + // A camera built from those options. + function wiredCamera(...options: Parameters): CameraController { + const camera = new CameraController(wiredOptions(...options)) + + cameras.push(camera) + return camera + } + + // The reporter of a camera's configuration, which each of its managements reports through and hands the engine, read before a removal makes the next. + function reporterOf(camera: CameraController): CameraReporter { + // @ts-expect-error: private access + return camera.reporter + } + + // A camera with the camera capabilities block over the first and second sensors and no webrtc member. + function plainCamera(): CameraController { + const camera = new CameraController(capabilitiesCameraOptions({ + videoSensors: [FIRST_SENSOR, SECOND_SENSOR], + streaming: idleStreaming(), + })) + + cameras.push(camera) + return camera + } + + // A wired camera's services, constructed and configured as a first run of the accessory configures them, and the camera handed a published context. + function configured(camera: CameraController): CameraControllerServiceMap { + const map = camera.constructServices() + camera.configureServices() + handPublishedContext(camera) + + return map + } + + function webRTCServiceOf(map: CameraControllerServiceMap, key: string): CameraWebRTCStreamManagement { + return map[key] as CameraWebRTCStreamManagement + } + + function prefixedKeys(map: CameraControllerServiceMap): string[] { + return Object.keys(map).filter(key => key.startsWith('cameraCapabilities:') && map[key] !== undefined) + } + + // The block's services on an accessory in block order: the advertisement, the surface, each video sensor's multi-tier stream service, then each + // sensor's WebRTC stream service, each in the camera's sensor order, by default the first sensor's first, a sensor's found by its lowercase UUID. + function blockOf(accessory: Accessory, sensors: readonly CameraVideoSensor[] = [FIRST_SENSOR, SECOND_SENSOR]): Service[] { + const sensorUUIDs = sensors.map(sensor => sensor.uuid.toLowerCase()) + + return [ + accessory.getService(Service.CameraCapabilities)!, + accessory.getService(Service.CameraGlobalOperatingMode)!, + ...sensorUUIDs.map(sensorUUID => accessory.getServiceById(Service.CameraMultiTierRTPStreamManagement, sensorUUID)!), + ...sensorUUIDs.map(sensorUUID => accessory.getServiceById(Service.CameraWebRTCStreamManagement, sensorUUID)!), + ] + } + + /* The numbers an accessory held that a camera with the block keeps when it adopts the accessory's services: every one but those of the legacy streams + * and of the Speaker, which a camera with the block whose delegate takes no talkback builds none of, and those of the recording configuration's + * characteristics, which it removes from a recording service a camera with the legacy recording options saved. + */ + function keptBy(held: Record): Record { + const configuration = [ + Characteristic.SupportedCameraRecordingConfiguration, + Characteristic.SupportedVideoRecordingConfiguration, + Characteristic.SupportedAudioRecordingConfiguration, + Characteristic.SelectedCameraRecordingConfiguration, + ].map(({ UUID }) => `${Service.CameraRecordingManagement.UUID}|${UUID}`) + const removed = [Service.CameraRTPStreamManagement.UUID, Service.Speaker.UUID] + + return Object.fromEntries(Object.entries(held).filter(([id]) => !configuration.includes(id) && !removed.some(service => id.startsWith(service)))) + } + + // An accessory carrying the first camera, numbered, then restored carrying the second over the same cache: the numbers of the block the restore adds, in + // block order, every number the first numbering held, and every number the restored accessory holds. + function renumbered(first: CameraController, second: CameraController): { block: number[], held: Record, numbers: Record } { + const cache = new IdentifierCache(NUMBERED_USERNAME) + const saved = numberedAccessory(first, cache) + const held = numbersOf(saved) + const accessory = restoredAccessory(saved, second, cache) + + return { + block: blockOf(accessory).map(service => service.iid!), + held, + numbers: numbersOf(accessory), + } + } + + // A video sensor's multi-tier and WebRTC stream services on an accessory, found by the sensor's lowercase UUID. + function streamPairOf(accessory: Accessory, sensor: CameraVideoSensor): [Service, Service] { + const sensorUUID = sensor.uuid.toLowerCase() + + return [ + accessory.getServiceById(Service.CameraMultiTierRTPStreamManagement, sensorUUID)!, + accessory.getServiceById(Service.CameraWebRTCStreamManagement, sensorUUID)!, + ] + } + + // Each service's published links under its instance ID, undefined for a service that links none. + function publishedLinks(accessory: Accessory): Record { + const links: Record = {} + + for (const service of accessory.services) { + links[service.iid!] = service.internalHAPRepresentation().linked + } + + return links + } + + // The links a numbered recording camera publishes: the recording service's to the data stream service and to each sensor, and, when the camera pairs + // its stream services, each video sensor's multi-tier and WebRTC stream services' to each other. No other service links any. + function expectedLinks(accessory: Accessory, paired: boolean): Record { + const links: Record = {} + + for (const service of accessory.services) { + links[service.iid!] = undefined + } + + links[accessory.getService(Service.CameraRecordingManagement)!.iid!] = [ + accessory.getService(Service.DataStreamTransportManagement)!.iid!, + accessory.getService(Service.MotionSensor)!.iid!, + accessory.getService(Service.OccupancySensor)!.iid!, + ] + + if (!paired) { + return links + } + + for (const sensor of [FIRST_SENSOR, SECOND_SENSOR]) { + const [multiTier, webRTC] = streamPairOf(accessory, sensor) + links[multiTier.iid!] = [webRTC.iid!] + links[webRTC.iid!] = [multiTier.iid!] + } + + return links + } + + it('constructs one webrtc stream service per video sensor after the multi-tier keys, each with its own sensor\'s tiers, for a block without the ' + + 'webrtc member too, and none without the block', () => { + // The second sensor's tiers are the fixture's at another bitrate, and each service is seen to advertise its own sensor's tiers. + const second = { + ...SECOND_SENSOR, + tiers: SECOND_SENSOR.tiers.map(tier => ({ ...tier, bitrate: tier.bitrate - 100 })), + } + const map = wiredCamera([FIRST_SENSOR, second]).constructServices() + + expect(prefixedKeys(map)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + FIRST_MULTI_TIER_KEY, + SECOND_MULTI_TIER_KEY, + FIRST_KEY, + SECOND_KEY, + ...RECORDING_KEYS, + ]) + + for (const [key, sensor, tiers] of [ + [ + FIRST_KEY, + FIRST_SENSOR, + tierSetOf(FIRST_SENSOR), + ], + [ + SECOND_KEY, + SECOND_SENSOR, + tierSetOf(second), + ], + ] as const) { + const service = webRTCServiceOf(map, key) + const advertised = service.getCharacteristic(Characteristic.WebRTCSupportedVideoStreamTiers).value as string + + expect(service.UUID).toBe(Service.CameraWebRTCStreamManagement.UUID) + expect(service.subtype).toBe(sensor.uuid.toLowerCase()) + expect(service.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true) + expect(decodeSupportedVideoStreamTiers(advertised)).toEqual(tiers.videoStreamTiers) + } + + const legacy = new CameraController(createCameraControllerOptions()) + cameras.push(legacy) + + expect(prefixedKeys(plainCamera().constructServices()).filter(key => key.startsWith('cameraCapabilities:webRTCStream:'))).toEqual([FIRST_KEY, SECOND_KEY]) + expect(prefixedKeys(legacy.constructServices())).toEqual([]) + }) + + it('serves every sensor\'s webrtc sessions from the camera\'s one engine, each service held to the block\'s maxSessions', async () => { + const camera = new CameraController(wiredOptions([FIRST_SENSOR, SECOND_SENSOR], idleStreaming(), { maxSessions: 7 })) + cameras.push(camera) + const map = configured(camera) + const connection = buildEmitterConnection() + + for (const key of [FIRST_KEY, SECOND_KEY]) { + const service = webRTCServiceOf(map, key) + + for (let opened = 0; opened < 7; opened++) { + expect((await solicit(service, connection)).status).toBe(WebRTCSolicitOfferStatus.SUCCESS) + } + + expect(await solicit(service, connection)).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + } + + const engines = vi.mocked(WebRTCEngine.prototype.createOffer).mock.contexts + + expect(engines).toHaveLength(14) + expect(engines[0]).toBeInstanceOf(WebRTCEngine) + expect(new Set(engines).size).toBe(1) + }) + + it('refuses a webrtc member whose maxSessions is no integer from 1 to 255 at the constructor, in the management\'s sentence, and takes one below six ' + + 'with the specification\'s sentence as a debug line, which strict throws, each service held to it', async () => { + const lines = captureDebug('HAP-NodeJS:Camera:Controller') + const built = (maxSessions: number, strict?: boolean) => (): CameraController => new CameraController(capabilitiesCameraOptions({ + videoSensors: [FIRST_SENSOR], + streaming: idleStreaming(), + strict, + webrtc: { maxSessions }, + })) + const five = 'The WebRTC streaming holds at most 5 sessions per video sensor, but the specification requires at least six.' + const one = 'The WebRTC streaming holds at most 1 session per video sensor, but the specification requires at least six.' + + for (const maxSessions of [0, 1.5, 256]) { + for (const strict of [false, true]) { + expect(built(maxSessions, strict)).toThrow(new TypeError('The WebRTC stream management takes a maxSessions that is an integer from 1 to 255, but ' + + `${maxSessions} is not one.`)) + } + } + + expect(lines).toEqual([]) + expect(built(5, true)).toThrow(new TypeError(five)) + expect(lines).toEqual([]) + + built(5)() + + expect(lines).toEqual([five]) + + const camera = built(1)() + cameras.push(camera) + const service = webRTCServiceOf(configured(camera), FIRST_KEY) + const connection = buildEmitterConnection() + + expect(lines).toEqual([five, one]) + expect((await solicit(service, connection)).status).toBe(WebRTCSolicitOfferStatus.SUCCESS) + expect(await solicit(service, connection)).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + + built(6)() + + expect(lines).toEqual([five, one]) + }) + + it('refuses a voice that is neither value at the engine\'s constructor and the controller\'s, in one sentence, and reads an absent one as automatic', () => { + const endSession = async (): Promise => undefined + const speakerMuted = (): boolean => false + const tierTable = (): undefined => undefined + + for (const voice of ['loud', 1, 'wideband']) { + const sentence = `The WebRTC streaming takes a voice of 'automatic' or 'dependable', but ${voice} is neither.` + const made = (): WebRTCEngine => new WebRTCEngine({ + endSession, + speakerMuted, + tierTable, + voice: voice as WebRTCStreamingOptions['voice'], + }) + const built = (): CameraController => new CameraController(wiredOptions([FIRST_SENSOR], idleStreaming(), { + voice: voice as WebRTCStreamingOptions['voice'], + })) + + expect(made).toThrow(TypeError) + expect(made).toThrow(sentence) + expect(built).toThrow(TypeError) + expect(built).toThrow(sentence) + } + + expect(new WebRTCEngine({ endSession, speakerMuted, tierTable }).voice).toBe('automatic') + }) + + it('hands the engine a controller builds the block\'s voice, automatic when the block names none', async () => { + const connection = buildEmitterConnection() + + for (const [webrtc, voice] of [ + [ + { voice: 'dependable' }, + 'dependable', + ], + [{}, 'automatic'], + ] as const) { + const map = configured(wiredCamera([FIRST_SENSOR], idleStreaming(), webrtc)) + + vi.mocked(WebRTCEngine.prototype.createOffer).mockClear() + await solicit(webRTCServiceOf(map, FIRST_KEY), connection) + + expect(vi.mocked(WebRTCEngine.prototype.createOffer).mock.contexts.map(context => (context as WebRTCEngine).voice)).toEqual([voice]) + } + }) + + it('exports the block\'s type and the persisted state\'s type from the package root, and neither the management, the delegate nor any wire type ' + + 'or constant set', () => { + for (const name of [ + 'WebRTCStreamManagement', + 'WebRTCSolicitOfferStatus', + 'WebRTCStreamingCommand', + 'WebRTCStreamingStatus', + 'WebRTCEngine', + ]) { + expect(name in hap).toBe(false) + } + + // Each name below left the package's surface: naming it from the root is a type error, which the typecheck reads. + type Removed = [ + // @ts-expect-error: not exported from the package root. + hap.WebRTCStreamEngine, + // @ts-expect-error: not exported from the package root. + hap.WebRTCOfferRequest, + // @ts-expect-error: not exported from the package root. + hap.WebRTCOffer, + // @ts-expect-error: not exported from the package root. + hap.WebRTCAnswer, + // @ts-expect-error: not exported from the package root. + hap.WebRTCReoffer, + // @ts-expect-error: not exported from the package root. + hap.WebRTCReofferAnswer, + // @ts-expect-error: not exported from the package root. + hap.WebRTCReceiveKeysUpdate, + // @ts-expect-error: not exported from the package root. + hap.WebRTCStreamManagementOptions, + // @ts-expect-error: not exported from the package root. + hap.WebRTCStreamManagement, + // @ts-expect-error: not exported from the package root. + hap.SFrameKeyData, + // @ts-expect-error: not exported from the package root. + hap.SFrameKID, + // @ts-expect-error: not exported from the package root. + hap.WebRTCICECandidate, + // @ts-expect-error: not exported from the package root. + hap.WebRTCOfferOptions, + // @ts-expect-error: not exported from the package root. + hap.WebRTCProvideAnswerRequest, + // @ts-expect-error: not exported from the package root. + hap.WebRTCReofferRequest, + // @ts-expect-error: not exported from the package root. + hap.WebRTCReofferResponse, + // @ts-expect-error: not exported from the package root. + hap.WebRTCSessionStatusResponse, + // @ts-expect-error: not exported from the package root. + hap.WebRTCSolicitOfferRequest, + // @ts-expect-error: not exported from the package root. + hap.WebRTCSolicitOfferResponse, + // @ts-expect-error: not exported from the package root. + hap.WebRTCStreamingControlRequest, + // @ts-expect-error: not exported from the package root. + hap.WebRTCUpdateSessionRequest, + // @ts-expect-error: not exported from the package root. + hap.WebRTCSolicitOfferStatus, + // @ts-expect-error: not exported from the package root. + hap.WebRTCStreamingCommand, + // @ts-expect-error: not exported from the package root. + hap.WebRTCStreamingStatus, + ] + const removed: Removed | undefined = undefined + const block: hap.WebRTCStreamingOptions = { maxSessions: 6 } + + expect(removed).toBeUndefined() + expect(block).toEqual({ maxSessions: 6 }) + }) + + it('exports the talkback payload type and the sensor entries\' types from the package root, and neither the wire\'s types nor its constant sets', () => { + expect(hap.TALKBACK_PAYLOAD_TYPE).toBe(110) + + for (const name of [ + 'CameraSensorType', + 'TieredAudioBitDepth', + 'TieredAudioCodecType', + 'TieredAudioSampleRate', + 'TieredVideoCodecType', + 'BufferActivity', + 'BufferEventCommandType', + 'BufferUploadCommandType', + 'BufferUploadStopAction', + 'CameraBufferEventType', + 'CMAFError', + 'RTPStreamingCommand', + 'RTPStreamingStatus', + 'SetupEndpointsStatus', + ]) { + expect(name in hap).toBe(false) + } + + // Each name below left the package's surface: naming it from the root is a type error, which the typecheck reads. + type Removed = [ + // @ts-expect-error: not exported from the package root. + hap.BufferActivityCommandRequest, + // @ts-expect-error: not exported from the package root. + hap.BufferEventCommandRequest, + // @ts-expect-error: not exported from the package root. + hap.BufferEventCommandResponse, + // @ts-expect-error: not exported from the package root. + hap.BufferUploadCommandRequest, + // @ts-expect-error: not exported from the package root. + hap.BufferUploadCommandResponse, + // @ts-expect-error: not exported from the package root. + hap.CameraBufferEvent, + // @ts-expect-error: not exported from the package root. + hap.CameraRecordingPublishingPointPayload, + // @ts-expect-error: not exported from the package root. + hap.PublishingPointCertificate, + // @ts-expect-error: not exported from the package root. + hap.BufferActivity, + // @ts-expect-error: not exported from the package root. + hap.BufferEventCommandType, + // @ts-expect-error: not exported from the package root. + hap.BufferUploadCommandType, + // @ts-expect-error: not exported from the package root. + hap.BufferUploadStopAction, + // @ts-expect-error: not exported from the package root. + hap.CameraBufferEventType, + // @ts-expect-error: not exported from the package root. + hap.CMAFError, + // @ts-expect-error: not exported from the package root. + hap.CameraCapabilitiesPayload, + // @ts-expect-error: not exported from the package root. + hap.ContributingSensor, + // @ts-expect-error: not exported from the package root. + hap.ContributingSensorsPayload, + // @ts-expect-error: not exported from the package root. + hap.CameraClientCertificateRequest, + // @ts-expect-error: not exported from the package root. + hap.CameraClientCertificateStatusPayload, + // @ts-expect-error: not exported from the package root. + hap.CameraClientCSRRequest, + // @ts-expect-error: not exported from the package root. + hap.CameraClientCSRResponse, + // @ts-expect-error: not exported from the package root. + hap.CameraKeyIDPayload, + // @ts-expect-error: not exported from the package root. + hap.CameraKeyPayload, + // @ts-expect-error: not exported from the package root. + hap.RTPStreamingControlRequest, + // @ts-expect-error: not exported from the package root. + hap.RTPStreamingControlResponse, + // @ts-expect-error: not exported from the package root. + hap.RTPStreamingCommand, + // @ts-expect-error: not exported from the package root. + hap.RTPStreamingStatus, + // @ts-expect-error: not exported from the package root. + hap.SetupEndpointsAddress, + // @ts-expect-error: not exported from the package root. + hap.SetupEndpointsRequest, + // @ts-expect-error: not exported from the package root. + hap.SetupEndpointsResponse, + // @ts-expect-error: not exported from the package root. + hap.SRTPParameters, + // @ts-expect-error: not exported from the package root. + hap.SetupEndpointsStatus, + // @ts-expect-error: not exported from the package root. + hap.CameraZonesPayload, + // @ts-expect-error: not exported from the package root. + hap.SensorConfiguration, + // @ts-expect-error: not exported from the package root. + hap.CameraVideoStreamCapabilities, + // @ts-expect-error: not exported from the package root. + hap.AudioStreamTier, + // @ts-expect-error: not exported from the package root. + hap.VideoStreamTier, + // @ts-expect-error: not exported from the package root. + hap.SupportedAudioStreamTiersPayload, + // @ts-expect-error: not exported from the package root. + hap.SupportedVideoStreamTiersPayload, + // @ts-expect-error: not exported from the package root. + hap.SensorStreamTiers, + // @ts-expect-error: not exported from the package root. + hap.MotionZonesOptions, + // @ts-expect-error: not exported from the package root. + hap.MotionZonesDelegate, + ] + const removed: Removed | undefined = undefined + const tier: hap.CameraVideoTier = { + bitrate: 768, + frameRate: 30, + height: 720, + id: 2, + quality: hap.CameraVideoQuality.MEDIUM, + width: 1280, + } + const audio: hap.CameraAudioTier = { bitrate: 24 } + const dimensions: hap.SensorDimensions = { height: 720, width: 1280 } + const sensor: hap.CameraVideoSensor = { + audio, + dimensions, + intent: hap.CameraSensorIntent.MAIN, + tiers: [tier], + uuid: 'a1b2c3d4-0000-4000-8000-000000000001', + } + // The zones a sensor's motionZones function is handed keep their types on the root. + const vertex: hap.CameraZoneVertex = [1280, 720] + const polygon: hap.CameraZonePolygon = { + identifier: 'a1b2c3d4-0000-4000-8000-000000000002', + vertices: [ + [0, 0], + vertex, + [0, 720], + ], + } + const zone: hap.CameraZoneData = { + method: hap.CameraZoneApplicationMethod.NORMAL, + polygons: [polygon], + } + // The handles a plugin registers what it makes on are types alone, and the root holds no value of their names. + const scope: hap.ResourceScope | undefined = undefined + const talker: hap.Talker | undefined = undefined + + expect(removed).toBeUndefined() + expect(sensor.tiers).toEqual([tier]) + expect(zone.polygons).toEqual([polygon]) + expect([scope, talker]).toEqual([undefined, undefined]) + expect(['ResourceScope' in hap, 'Talker' in hap]).toEqual([false, false]) + }) + + it('exports neither the sensor registry\'s persisted state, the recording management\'s capabilities, the change reason\'s enum nor the 64-bit TLV helpers ' + + 'from the package root, and keeps the persisted state types the documentation names, the change reason\'s union, the released TLV helpers and every ' + + 'name Homebridge reads', () => { + for (const name of [ + 'OperatingModeChangeReason', + 'readBigUInt64LE', + 'writeBigUInt64LE', + 'readVariableBigUIntLE', + 'writeVariableBigUIntLE', + ]) { + expect(name in hap).toBe(false) + } + + for (const name of [ + 'decode', + 'decodeList', + 'decodeWithLists', + 'encode', + 'readUInt16', + 'readUInt32', + 'readUInt64LE', + 'readVariableUIntLE', + 'writeFloat32LE', + 'writeUInt16', + 'writeUInt32', + 'writeVariableUIntLE', + ]) { + expect(name in hap).toBe(true) + } + + // Each name below left the package's surface: naming it from the root is a type error, which the typecheck reads. A helper is named through its + // typeof, since a function's name is no type and would be refused whether or not the root offered it. + type Removed = [ + // @ts-expect-error: not exported from the package root. + hap.SensorRegistryState, + // @ts-expect-error: not exported from the package root. + hap.RecordingManagementCapabilities, + // @ts-expect-error: not exported from the package root. + hap.OperatingModeChangeReason, + // @ts-expect-error: not exported from the package root. + typeof hap.readBigUInt64LE, + // @ts-expect-error: not exported from the package root. + typeof hap.writeBigUInt64LE, + // @ts-expect-error: not exported from the package root. + typeof hap.readVariableBigUIntLE, + // @ts-expect-error: not exported from the package root. + typeof hap.writeVariableBigUIntLE, + ] + // Homebridge hands plugins the whole module and names the enums read below as values, with their values, and the controllers, their options, the + // delegates and the recording's stored state as types. The named forms of the options, the persisted state types the documented members name, the + // change reason's union and the TLV module's type stay on the root beside them. + type Kept = [ + hap.CameraController, + hap.DoorbellController, + hap.CameraControllerOptions, + hap.CameraControllerLegacyOptions, + hap.CameraControllerCapabilitiesOptions, + hap.CameraCapabilitiesOptions, + hap.CameraSensorOptions, + hap.CameraRecordingDelegate, + hap.CameraStreamingDelegate, + hap.RecordingManagementState, + hap.MotionZonesManagementState, + hap.MultiTierStreamManagementState, + hap.OperatingModeState, + hap.WebRTCStreamManagementState, + hap.CameraChangeReason, + hap.TLVEncodable, + ] + const removed: Removed | undefined = undefined + const kept: Kept | undefined = undefined + + expect([removed, kept]).toEqual([undefined, undefined]) + expect({ ...hap.ResourceRequestReason }).toEqual({ + 0: 'PERIODIC', + 1: 'EVENT', + EVENT: 1, + PERIODIC: 0, + }) + expect(['cameraProblemsChannel' in hap, 'onCameraProblem' in hap]).toEqual([true, true]) + expect({ ...hap.CameraControllerEvents }).toEqual({ + LIVE_VIEW_ENDED: 'live-view-ended', + LIVE_VIEW_STARTED: 'live-view-started', + MICROPHONE_PROPERTIES_CHANGED: 'microphone-change', + OPERATING_MODE_CHANGED: 'operating-mode-change', + RECORDING_ENDED: 'recording-ended', + RECORDING_STARTED: 'recording-started', + SPEAKER_PROPERTIES_CHANGED: 'speaker-change', + STREAMING_ENABLED_CHANGED: 'streaming-enabled-change', + }) + }) + + it('exports each constant set a plugin states from the package root as an object of its names and values alone', () => { + expect({ ...hap.CameraSensorIntent }).toEqual({ + UNKNOWN: 0, + MAIN: 1, + PACKAGE: 2, + GENERIC: 255, + }) + expect({ ...hap.CameraVideoQuality }).toEqual({ + HIGHEST: 1, + HIGH: 2, + MEDIUM: 3, + LOW: 4, + }) + expect({ ...hap.CameraZoneApplicationMethod }).toEqual({ NORMAL: 1, INVERTED: 2 }) + }) + + it('loads werift for a camera with the block at its configure, with or without the webrtc member, one load for the process, and never for a camera ' + + 'without the block', async () => { + const preload = vi.spyOn(WebRTCEngine.prototype, 'preload') + const legacy = new CameraController(createCameraControllerOptions()) + cameras.push(legacy) + + configured(legacy) + + expect(preload).not.toHaveBeenCalled() + + for (const camera of [ + plainCamera(), + wiredCamera(), + ]) { + preload.mockClear() + configured(camera) + + expect(preload).toHaveBeenCalled() + } + + expect(loadWerift()).toBe(loadWerift()) + await expect(loadWerift()).resolves.toHaveProperty('RTCPeerConnection') + }) + + it('adopts a saved webrtc service with its streaming enabled, creates a missing one, and deletes a removed sensor\'s, keeping every key for a block ' + + 'without the webrtc member and none without the block', () => { + const saved = savedMapOf(wiredCamera([FIRST_SENSOR, REMOVED_SENSOR])) + const adopted = saved[FIRST_KEY]! + adopted.updateCharacteristic(Characteristic.StreamingEnabled, false) + + const restored = wiredCamera().initWithServices(saved)! + + expect(restored).toBe(saved) + expect(restored[FIRST_KEY]).toBe(adopted) + expect(adopted.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(false) + expect(restored[SECOND_KEY]!.UUID).toBe(Service.CameraWebRTCStreamManagement.UUID) + expect(restored[REMOVED_KEY]).toBeUndefined() + expect(prefixedKeys(restored)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + FIRST_MULTI_TIER_KEY, + SECOND_MULTI_TIER_KEY, + FIRST_KEY, + SECOND_KEY, + ...RECORDING_KEYS, + ]) + + const kept = savedMapOf(wiredCamera()) + const keys = prefixedKeys(kept) + + expect(plainCamera().initWithServices(kept)).toBeUndefined() + expect(prefixedKeys(kept)).toEqual(keys) + + const legacy = new CameraController(createCameraControllerOptions()) + cameras.push(legacy) + + expect(prefixedKeys(legacy.initWithServices(savedMapOf(wiredCamera()))!)).toEqual([]) + }) + + it('numbers a first publish\'s block in block order below every other service but the accessory information', () => { + const accessory = numberedAccessory(wiredCamera()) + const block = blockOf(accessory) + const numbers = block.map(service => service.iid!) + const others = accessory.services + .filter(service => !block.includes(service) && service.UUID !== Service.AccessoryInformation.UUID) + .map(service => service.iid!) + + expect(numbers).toEqual(numbers.toSorted((left, right) => left - right)) + expect(others).not.toEqual([]) + expect(Math.max(...numbers)).toBeLessThan(Math.min(...others)) + }) + + it('numbers the block in block order and keys each sensor\'s services in the plugin\'s order for a camera given its package sensor first', () => { + const numbers = blockOf(numberedAccessory(wiredCamera([SECOND_SENSOR, FIRST_SENSOR])), [SECOND_SENSOR, FIRST_SENSOR]).map(service => service.iid!) + + expect(numbers).toEqual(numbers.toSorted((left, right) => left - right)) + expect(prefixedKeys(savedMapOf(wiredCamera([SECOND_SENSOR, FIRST_SENSOR])))).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + SECOND_MULTI_TIER_KEY, + FIRST_MULTI_TIER_KEY, + SECOND_KEY, + FIRST_KEY, + ...RECORDING_KEYS, + ]) + }) + + it('numbers the block a restore adds in block order above every number the accessory held, each of which it keeps but its legacy streams\', its ' + + 'Speaker\'s and its recording configuration\'s', () => { + const plain = new CameraController(createCameraControllerOptions()) + cameras.push(plain) + const { block, held, numbers } = renumbered(plain, wiredCamera()) + + expect(block).toEqual(block.toSorted((left, right) => left - right)) + expect(Math.min(...block)).toBeGreaterThan(Math.max(...Object.values(held))) + expect(numbers).toMatchObject(keptBy(held)) + }) + + it('numbers the block a doorbell\'s restore adds in block order above every number the accessory held, each of which it keeps but its legacy ' + + 'streams\', its Speaker\'s and its recording configuration\'s', () => { + const plain = new DoorbellController(createCameraControllerOptions()) + const wired = new DoorbellController(wiredOptions()) + cameras.push(plain, wired) + const { block, held, numbers } = renumbered(plain, wired) + + expect(block).toEqual(block.toSorted((left, right) => left - right)) + expect(Math.min(...block)).toBeGreaterThan(Math.max(...Object.values(held))) + expect(numbers).toMatchObject(keptBy(held)) + }) + + it('gains each sensor\'s webrtc service above every number the accessory held at a restore of a camera saved with the block and no webrtc service', + () => { + // The camera as a run that built no WebRTC stream service saved it: its accessory numbered without those services, which means the cache holds no number + // for them, and its saved map holds no key for them. + const cache = new IdentifierCache(NUMBERED_USERNAME) + const saved = new Accessory('Camera', NUMBERED_ACCESSORY_UUID) + saved.configureController(plainCamera()) + + for (const service of saved.services.filter(candidate => candidate.UUID === Service.CameraWebRTCStreamManagement.UUID)) { + saved.removeService(service) + } + + saved._assignIDs(cache) + + const held = numbersOf(saved) + const accessory = restoredAccessory(saved, plainCamera(), cache) + const gained = [FIRST_SENSOR, SECOND_SENSOR].map(sensor => accessory.getServiceById(Service.CameraWebRTCStreamManagement, sensor.uuid.toLowerCase())) + + expect(gained.map(service => service?.subtype)).toEqual([FIRST_SENSOR, SECOND_SENSOR].map(sensor => sensor.uuid.toLowerCase())) + expect(Math.min(...gained.map(service => service!.iid!))).toBeGreaterThan(Math.max(...Object.values(held))) + expect(numbersOf(accessory)).toMatchObject(held) + expect(publishedLinks(accessory)).toEqual(expectedLinks(accessory, true)) + }) + + it('leaves a saved map whose block keys stand last as it was saved at a restore that changes nothing', () => { + const built = savedMapOf(wiredCamera()) + const block = prefixedKeys(built) + const saved: CameraControllerServiceMap = Object.fromEntries([ + ...Object.entries(built).filter(([key]) => !block.includes(key)), + ...Object.entries(built).filter(([key]) => block.includes(key)), + ]) + const order = Object.keys(saved) + + expect(block).not.toEqual([]) + expect(wiredCamera().initWithServices(saved)).toBeUndefined() + expect(Object.keys(saved)).toEqual(order) + }) + + it('leads a constructed map with the block and keeps the keys of the plugin\'s own motion sensor and of the Speaker a delegate without talkback has ' + + 'none of, the keys whose value is undefined', () => { + const camera = new CameraController({ + ...wiredOptions(), + sensors: { + motion: new Service.MotionSensor('', ''), + occupancy: true, + }, + }) + cameras.push(camera) + const map = camera.constructServices() + + expect(Object.keys(map)).toEqual([ + CAPABILITIES_KEY, + GLOBAL_KEY, + FIRST_MULTI_TIER_KEY, + SECOND_MULTI_TIER_KEY, + FIRST_KEY, + SECOND_KEY, + ...RECORDING_KEYS, + 'microphone', + 'speaker', + 'motionService', + 'occupancyService', + 'cameraEventRecordingManagement', + 'cameraOperatingMode', + 'dataStreamTransportManagement', + ]) + expect(Object.keys(map).filter(key => map[key] === undefined)).toEqual(['speaker', 'motionService']) + }) + + it('links each video sensor\'s multi-tier and webrtc stream services to each other beside the recording service\'s links, and nothing else', () => { + const accessory = numberedAccessory(wiredCamera()) + + expect(publishedLinks(accessory)).toEqual(expectedLinks(accessory, true)) + }) + + it('links each sensor\'s stream services to each other once at a restore, of a camera saved with its pair unlinked as well', () => { + const linked = numberedAccessory(wiredCamera()) + const unlinked = numberedAccessory(wiredCamera()) + + for (const sensor of [FIRST_SENSOR, SECOND_SENSOR]) { + const [multiTier, webRTC] = streamPairOf(unlinked, sensor) + multiTier.removeLinkedService(webRTC) + webRTC.removeLinkedService(multiTier) + } + + expect(publishedLinks(unlinked)).toEqual(expectedLinks(unlinked, false)) + + for (const saved of [linked, unlinked]) { + const accessory = restoredAccessory(saved, wiredCamera()) + + expect(publishedLinks(accessory)).toEqual(expectedLinks(accessory, true)) + } + }) + + it('links each sensor\'s stream services for a block without the webrtc member and none without the block, and a restore without the block that ' + + 'sweeps every webrtc service leaves no link to it', () => { + // A camera without the block, made for each numbering. + const legacy = (): CameraController => { + const camera = new CameraController(createCameraControllerOptions()) + + cameras.push(camera) + return camera + } + const plain = numberedAccessory(plainCamera()) + const unpaired = numberedAccessory(legacy()) + const swept = restoredAccessory(numberedAccessory(wiredCamera()), legacy()) + + expect(publishedLinks(plain)).toEqual(expectedLinks(plain, true)) + expect(swept.getService(Service.CameraWebRTCStreamManagement)).toBeUndefined() + + for (const accessory of [unpaired, swept]) { + const iids = accessory.services.map(service => service.iid) + + expect(publishedLinks(accessory)).toEqual(expectedLinks(accessory, false)) + expect(accessory.services.flatMap(service => service.internalHAPRepresentation().linked ?? []).filter(iid => !iids.includes(iid))).toEqual([]) + expect(accessory.services.flatMap(service => service.linkedServices).filter(linked => !accessory.services.includes(linked))).toEqual([]) + } + }) + + it('serializes and restores each sensor\'s webrtc slice, carries a removed sensor\'s and a record without the member, and drops it at a reset', () => { + const FIRST_SLICE = FIRST_SENSOR.uuid.toLowerCase() + const SECOND_SLICE = SECOND_SENSOR.uuid.toLowerCase() + + expect(wiredCamera().serialize()!.webRTCStreamManagements).toBeUndefined() + + const camera = wiredCamera() + configured(camera) + + expect(camera.serialize()!.webRTCStreamManagements).toEqual({ + [FIRST_SLICE]: { streamingEnabled: true }, + [SECOND_SLICE]: { streamingEnabled: true }, + }) + + const restored = wiredCamera([FIRST_SENSOR]) + const map = configured(restored) + restored.deserialize({ + streamManagements: [], + webRTCStreamManagements: { + [FIRST_SLICE]: { streamingEnabled: false }, + [SECOND_SLICE]: { streamingEnabled: false }, + }, + }) + + expect(webRTCServiceOf(map, FIRST_KEY).getCharacteristic(Characteristic.StreamingEnabled).value).toBe(false) + expect(restored.serialize()!.webRTCStreamManagements).toEqual({ + [FIRST_SLICE]: { streamingEnabled: false }, + [SECOND_SLICE]: { streamingEnabled: false }, + }) + + restored.handleFactoryReset() + + expect(restored.serialize()!.webRTCStreamManagements).toEqual({ + [FIRST_SLICE]: { streamingEnabled: true }, + }) + + const plain = new CameraController(createCameraControllerOptions()) + cameras.push(plain) + const record = { + [SECOND_SLICE]: { streamingEnabled: false }, + } + plain.deserialize({ + streamManagements: [], + webRTCStreamManagements: record, + }) + + expect(plain.serialize()!.webRTCStreamManagements).toEqual(record) + + plain.handleFactoryReset() + + expect(plain.serialize()!.webRTCStreamManagements).toBeUndefined() + + // A record or a slice that is no plain object, and a slice whose value is no boolean, restore nothing and throw nothing. + for (const webRTCStreamManagements of [ + [], + { [FIRST_SLICE]: null }, + { + [FIRST_SLICE]: { streamingEnabled: 'false' }, + }, + ]) { + expect(() => restored.deserialize({ + streamManagements: [], + webRTCStreamManagements: webRTCStreamManagements as unknown as Record, + })).not.toThrow() + } + + expect(webRTCServiceOf(map, FIRST_KEY).getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true) + expect(restored.serialize()!.webRTCStreamManagements).toEqual({ + [FIRST_SLICE]: { streamingEnabled: true }, + }) + }) + + it('ends every webrtc session and releases every answer at camera off, and one service\'s alone at its own streaming enabled, apart from multi-tier', async () => { + const camera = wiredCamera() + const map = configured(camera) + const reporter = reporterOf(camera) + const first = webRTCServiceOf(map, FIRST_KEY) + const second = webRTCServiceOf(map, SECOND_KEY) + const global = map[GLOBAL_KEY]! + const connection = buildEmitterConnection() + const other = buildEmitterConnection() + const streamingControl = first.getCharacteristic(Characteristic.WebRTCStreamingControl) + const firstSessions = [ + await connect(first, connection), + sessionOf(await solicit(first, connection)), + ] + const secondSessions = [await connect(second, connection)] + + // The other connection ends its own session. It holds that End's answer with no session left. + const ended = sessionOf(await solicit(first, other)) + firstSessions.push(ended) + await end(first, other, ended) + + await expect(streamingControl.handleGetRequest(other)).resolves.not.toBe('') + + global.addCharacteristic(Characteristic.ManuallyDisabled) + engine.endSession.mockClear() + global.updateCharacteristic(Characteristic.ManuallyDisabled, 1) + await settle() + + expect(engine.endSession).toHaveBeenCalledTimes(3) + for (const sessionIdentifier of [firstSessions[0], firstSessions[1], secondSessions[0]]) { + expect(engine.endSession).toHaveBeenCalledWith(sessionIdentifier, reporter) + } + expect(activeSessions(first)).toBe(0) + expect(activeSessions(second)).toBe(0) + await expect(streamingControl.handleGetRequest(other)).resolves.toBe('') + expect(await solicit(first, connection)).toEqual({ status: WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE }) + + global.updateCharacteristic(Characteristic.ManuallyDisabled, 0) + const reopened = await connect(first, connection) + firstSessions.push(reopened) + engine.endSession.mockClear() + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + await settle() + + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(reopened, reporter) + expect(activeSessions(first)).toBe(0) + expect(await solicit(second, connection)).toEqual({ status: WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE }) + + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON) + const firstSession = await connect(first, connection) + const secondSession = await connect(second, connection) + firstSessions.push(firstSession) + secondSessions.push(secondSession) + engine.endSession.mockClear() + first.updateCharacteristic(Characteristic.StreamingEnabled, false) + await settle() + + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(firstSession, reporter) + expect(await reoffer(second, connection, secondSession)).toEqual({ + sessionIdentifier: secondSession, + status: WebRTCStreamingStatus.SUCCESS, + sdpAnswer: SDP_ANSWER, + }) + + // Each service's Streaming Enabled gates its own family alone: the WebRTC service's off leaves the multi-tier Status Active true, and the multi-tier + // service's off leaves the WebRTC session live. + expect(map[FIRST_MULTI_TIER_KEY]!.getCharacteristic(Characteristic.StatusActive).value).toBe(true) + + first.updateCharacteristic(Characteristic.StreamingEnabled, true) + const live = await connect(first, connection) + firstSessions.push(live) + map[FIRST_MULTI_TIER_KEY]!.updateCharacteristic(Characteristic.StreamingEnabled, false) + await settle() + + expect(await reoffer(first, connection, live)).toEqual({ sessionIdentifier: live, status: WebRTCStreamingStatus.SUCCESS, sdpAnswer: SDP_ANSWER }) + + // Each service's offer requests name its own sensor, in lowercase. + const sessions = firstSessions.concat(secondSessions) + + for (const [{ sensorUUID, sessionIdentifier }] of engine.createOffer.mock.calls) { + expect(sessions).toContain(sessionIdentifier) + expect(sensorUUID).toBe(firstSessions.includes(sessionIdentifier) + ? FIRST_SENSOR.uuid.toLowerCase() + : SECOND_SENSOR.uuid.toLowerCase()) + } + }) + + it('fails a solicit offer of a camera whose source is away with the communication failure, and answers one switched off, or whose service\'s ' + + 'streaming enabled is off, with privacy mode active, its source away or not', async () => { + const camera = wiredCamera() + const map = configured(camera) + const first = webRTCServiceOf(map, FIRST_KEY) + const global = map[GLOBAL_KEY]! + const connection = buildEmitterConnection() + const answers: WebRTCSolicitOfferStatus[] = [] + const answered = async (): Promise => { + answers.push((await solicit(first, connection)).status) + } + + camera.updateSourceState('away') + await expect(solicit(first, connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.OFF) + await answered() + camera.updateSourceState('available') + await answered() + global.updateCharacteristic(Characteristic.HomeKitCameraActive, Characteristic.HomeKitCameraActive.ON) + first.updateCharacteristic(Characteristic.StreamingEnabled, false) + await answered() + camera.updateSourceState('away') + await answered() + first.updateCharacteristic(Characteristic.StreamingEnabled, true) + camera.updateSourceState('available') + await answered() + + expect(answers).toEqual([ + WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE, + WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE, + WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE, + WebRTCSolicitOfferStatus.PRIVACY_MODE_ACTIVE, + WebRTCSolicitOfferStatus.SUCCESS, + ]) + expect(engine.createOffer).toHaveBeenCalledOnce() + }) + + it('ends every webrtc session and releases every answer before the state-change delegate hears camera off', async () => { + const camera = wiredCamera() + const map = configured(camera) + const first = webRTCServiceOf(map, FIRST_KEY) + const second = webRTCServiceOf(map, SECOND_KEY) + const global = map[GLOBAL_KEY]! + const connection = buildEmitterConnection() + const other = buildEmitterConnection() + const sessions = [await connect(first, connection), await connect(second, connection)] + await end(first, other, sessionOf(await solicit(first, other))) + global.addCharacteristic(Characteristic.ManuallyDisabled) + engine.endSession.mockClear() + + // A held answer is read when the read starts. The promise each call takes records the answer at that call. + const calls: { ended: string[], held: Promise }[] = [] + camera.setupStateChangeDelegate(() => { + calls.push({ + ended: engine.endSession.mock.calls.map(([sessionIdentifier]) => sessionIdentifier), + held: first.getCharacteristic(Characteristic.WebRTCStreamingControl).handleGetRequest(other), + }) + }) + + global.updateCharacteristic(Characteristic.ManuallyDisabled, 1) + + expect(calls.length).toBeGreaterThan(0) + expect([...calls[0].ended].sort()).toEqual([...sessions].sort()) + await expect(calls[0].held).resolves.toBe('') + }) + + it('ends a session on the first sensor\'s webrtc service at the camera\'s factory reset and restores the second\'s streaming enabled', async () => { + const camera = wiredCamera() + const map = configured(camera) + const first = webRTCServiceOf(map, FIRST_KEY) + const second = webRTCServiceOf(map, SECOND_KEY) + const connection = buildEmitterConnection() + const sessionIdentifier = await connect(first, connection) + await second.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, connection) + + // @ts-expect-error: private access + expect(camera.operatingMode.statusActive(SECOND_KEY)).toBe(false) + + camera.handleFactoryReset() + await settle() + + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, reporterOf(camera)) + expect(second.getCharacteristic(Characteristic.StreamingEnabled).value).toBe(true) + expect((await solicit(second, connection)).status).toBe(WebRTCSolicitOfferStatus.SUCCESS) + }) + + it('emits a streaming enabled change naming its sensor and views from away for a write, a restore and a reset, each before the state-change delegate ' + + 'saves it', async () => { + const camera = wiredCamera() + const map = configured(camera) + const changes: StreamingEnabledChange[] = [] + const order: string[] = [] + camera.on(CameraControllerEvents.STREAMING_ENABLED_CHANGED, (change) => { + if (change.where === 'away') { + changes.push(change) + order.push('event') + } + }) + camera.setupStateChangeDelegate(() => order.push('saved')) + + await map[SECOND_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection()) + camera.deserialize({ + streamManagements: [], + webRTCStreamManagements: { + [FIRST_SENSOR.uuid.toLowerCase()]: { streamingEnabled: false }, + }, + }) + camera.handleFactoryReset() + + expect(changes).toEqual([ + { + reason: 'write', + sensorUUID: SECOND_SENSOR.uuid.toLowerCase(), + value: false, + where: 'away', + }, + { + reason: 'restore', + sensorUUID: FIRST_SENSOR.uuid.toLowerCase(), + value: false, + where: 'away', + }, + { + reason: 'reset', + sensorUUID: FIRST_SENSOR.uuid.toLowerCase(), + value: true, + where: 'away', + }, + { + reason: 'reset', + sensorUUID: SECOND_SENSOR.uuid.toLowerCase(), + value: true, + where: 'away', + }, + ]) + + // The delegate saves the camera right after each event, for the same change. + const events = order.flatMap((entry, index) => entry === 'event' + ? [index] + : []) + + expect(events).toHaveLength(4) + for (const index of events) { + expect(order[index + 1]).toBe('saved') + } + }) + + it('ends a webrtc session at a force-stop of its identifier and ignores an identifier no session holds', async () => { + const camera = wiredCamera() + const first = webRTCServiceOf(configured(camera), FIRST_KEY) + const connection = buildEmitterConnection() + const sessionIdentifier = await connect(first, connection) + + expect(() => camera.forceStopStreamingSession(UNKNOWN_SESSION)).not.toThrow() + await settle() + + expect(engine.endSession).not.toHaveBeenCalled() + + camera.forceStopStreamingSession(sessionIdentifier) + await settle() + + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, reporterOf(camera)) + expect(await end(first, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.UNKNOWN_SESSION_IDENTIFIER }) + }) + + it('ends every webrtc session, destroys each management and leaves no policy listener at a reset and a removal, the second run throwing nothing', async () => { + const camera = wiredCamera() + const map = configured(camera) + const first = webRTCServiceOf(map, FIRST_KEY) + const second = webRTCServiceOf(map, SECOND_KEY) + const connection = buildEmitterConnection() + const sessions = [ + await connect(first, connection), + sessionOf(await solicit(second, connection)), + ] + const reporter = reporterOf(camera) + + camera.handleFactoryReset() + camera.handleControllerRemoved() + + expect(() => { + camera.handleFactoryReset() + camera.handleControllerRemoved() + }).not.toThrow() + await settle() + + expect(engine.endSession).toHaveBeenCalledTimes(2) + for (const sessionIdentifier of sessions) { + expect(engine.endSession).toHaveBeenCalledWith(sessionIdentifier, reporter) + } + expect(await solicit(first, connection)).toEqual({ status: WebRTCSolicitOfferStatus.ERROR }) + expect(engine.createOffer).toHaveBeenCalledTimes(2) + + // Each characteristic keeps only its service's own change listener, and Streaming Enabled its class's as well. + for (const service of [first, second]) { + for (const characteristic of service.characteristics) { + expect(characteristic.listenerCount(CharacteristicEventTypes.CHANGE)).toBe(characteristic.UUID === Characteristic.StreamingEnabled.UUID + ? 2 + : 1) + } + } + expect(camera.serialize()!.webRTCStreamManagements).toBeUndefined() + }) + + it('holds a tier table for each video sensor while configured and none once removed: its engine reaches none', () => { + const camera = wiredCamera() + + // Every tier table a camera reaches through its own plain values: its fields and the maps, arrays and plain objects they hold. + const tierTablesOf = (): TierTable[] => { + const tables = new Set() + const seen = new Set() + const pending: unknown[] = [camera] + const owned = [ + Array.prototype, + CameraController.prototype, + Map.prototype, + Object.prototype, + ] + + while (pending.length > 0) { + const value = pending.pop() + + if (value instanceof TierTable) { + tables.add(value) + } else if ((typeof value === 'object') && (value !== null) && !seen.has(value) && owned.includes(Object.getPrototypeOf(value) as object)) { + seen.add(value) + pending.push(...(value instanceof Map + ? value.values() + : Object.values(value))) + } + } + + return [...tables] + } + + configured(camera) + + expect(tierTablesOf().map(({ sensorUUID }) => sensorUUID).toSorted()).toEqual([FIRST_SENSOR, SECOND_SENSOR].map(sensor => sensor.uuid.toLowerCase())) + + camera.handleControllerRemoved() + + expect(tierTablesOf()).toEqual([]) + }) + + it('hands the state-change delegate to every webrtc management, which is how each one\'s streaming enabled saves the camera', async () => { + const camera = wiredCamera() + const map = configured(camera) + const saves = vi.fn() + camera.setupStateChangeDelegate(saves) + + await map[FIRST_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection()) + await map[SECOND_KEY]!.getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, buildEmitterConnection()) + + expect(saves).toHaveBeenCalledTimes(2) + + camera.setupStateChangeDelegate(undefined) + map[SECOND_KEY]!.updateCharacteristic(Characteristic.StreamingEnabled, true) + + expect(saves).toHaveBeenCalledTimes(2) + }) + + it('tells of a view from away once as its answer is accepted and once as its count falls, naming no tier, though its media never connects', async () => { + const camera = wiredCamera() + const first = webRTCServiceOf(configured(camera), FIRST_KEY) + const connection = buildEmitterConnection() + const events: (readonly [string, CameraLiveView, unknown])[] = [] + // Each event is kept with Number of Active Sessions as it stands when the event is told. + const kept = (kind: string): ((view: CameraLiveView) => void) => (view) => { + const count = activeSessions(first) + + events.push([kind, view, count]) + } + camera.on(CameraControllerEvents.LIVE_VIEW_STARTED, kept('started')) + camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, kept('ended')) + + // A session whose offer is never answered is no view. + const offered = sessionOf(await solicit(first, connection)) + + expect(await end(first, connection, offered)).toEqual({ sessionIdentifier: offered, status: WebRTCStreamingStatus.SUCCESS }) + expect(events).toEqual([]) + + // Every engine call is scripted, and no media of the session ever connects. + const sessionIdentifier = await connect(first, connection) + const view: CameraLiveView = { + sensorUUID: FIRST_SENSOR.uuid.toLowerCase(), + sessionIdentifier, + where: 'away', + } + + expect(events).toStrictEqual([ + ['started', view, 1], + ]) + expect(await end(first, connection, sessionIdentifier)).toEqual({ sessionIdentifier, status: WebRTCStreamingStatus.SUCCESS }) + expect(events).toStrictEqual([ + ['started', view, 1], + ['ended', view, 0], + ]) + }) + + it('tells a removed camera\'s listeners of the end of each view from away in the removal\'s own turn, before the controller drops them', async () => { + const camera = wiredCamera() + const first = webRTCServiceOf(configured(camera), FIRST_KEY) + const connection = buildEmitterConnection() + const sessionIdentifier = await connect(first, connection) + const ended = vi.fn<(view: CameraLiveView) => void>() + const reporter = reporterOf(camera) + camera.on(CameraControllerEvents.LIVE_VIEW_ENDED, ended) + + camera.handleControllerRemoved() + + expect(ended.mock.calls).toStrictEqual([ + [ + { + sensorUUID: FIRST_SENSOR.uuid.toLowerCase(), + sessionIdentifier, + where: 'away', + }, + ], + ]) + expect(camera.listenerCount(CameraControllerEvents.LIVE_VIEW_ENDED)).toBe(0) + + await settle() + + expect(ended).toHaveBeenCalledOnce() + expect(engine.endSession).toHaveBeenCalledExactlyOnceWith(sessionIdentifier, reporter) + }) + }) +}) diff --git a/src/lib/camera/buffer/TierKeeper.spec.ts b/src/lib/camera/buffer/TierKeeper.spec.ts new file mode 100644 index 000000000..831b04a98 --- /dev/null +++ b/src/lib/camera/buffer/TierKeeper.spec.ts @@ -0,0 +1,1978 @@ +import type { Mock } from 'vitest' + +import type { ScriptedTierDelegate } from '../../../test-utils/cameraFixtures.js' +import type { CameraProblem } from '../diagnostics/problems.js' +import type { TierFrame, TierStream } from '../StreamingOptions.js' +import type { FrameConsumer, TierHolder } from '../TierTable.js' +import type { BufferedSample, BufferPlace } from './CameraBuffer.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + buildEmitterConnection, + disposedOf, + endedOf, + endsOf, + FIRST_VIDEO_SENSOR, + pendingStart, + scriptedTierDelegate, + signalOf, + streamsOf, + tierSetOf, +} from '../../../test-utils/cameraFixtures.js' +import { captureDebug } from '../../../test-utils/engineDebug.js' +import { + pictureSample, + soundSample, + TIER_STREAM_PARAMETER_SETS, + tierPicture, + tierStreamFragment, + tierStreamInitialization, +} from '../../../test-utils/mp4Fixtures.js' +import { detachedReporter, problemsOf } from '../../../test-utils/reporterFixtures.js' +import { deferred, fakeTimeoutSignals, settle } from '../../../test-utils/settle.js' +import * as uuid from '../../util/uuid.js' +import { TierHold, TierTable } from '../TierTable.js' +import { TierBuffer } from './CameraBuffer.js' +import { TierKeeper } from './TierKeeper.js' + +// The fixture's tiers: video tiers 1 to 3 and the audio tier, of the first video sensor. +const TIERS = tierSetOf(FIRST_VIDEO_SENSOR) + +// The ticks of a second on the picture's 90 kHz track and the sound's 48 kHz track. +const PICTURE_RATE = 90000 +const SOUND_RATE = 48000 + +interface Rig { + readonly delegate: ScriptedTierDelegate + readonly table: TierTable + readonly keeper: TierKeeper + // The synthetic camera whose reporter the keeper holds, the problems the keeper raised on that camera's channel, and its calls telling an open + // recording of a gap. + readonly accessoryUUID: string + readonly alerts: CameraProblem[] + readonly gap: Mock<() => void> + // The held tier's buffer, which the tier holds for the table's life. + readonly buffer: () => TierBuffer +} + +// Every keeper a row made, closed after it. No clock of one row runs into the next. +const keepers: TierKeeper[] = [] + +// A keeper of the fixture's video tier 1 over a table of its own, each of whose video tiers holds a buffer, which the keeper reaches through the lookup a +// controller hands it, reporting for a synthetic camera of its own, which means the keepers of one row hear none of each other's problems. +function rig(prebuffer = 0): Rig { + const delegate = scriptedTierDelegate() + const table = new TierTable(delegate, TIERS, tier => new TierBuffer(tier), detachedReporter()) + const accessoryUUID = uuid.generate(`tier keeper spec camera ${keepers.length}`) + const { problems: alerts, reporter } = problemsOf(accessoryUUID) + const gap = vi.fn<() => void>() + const keeper = new TierKeeper({ + gap, + prebuffer, + reporter, + sensorUUID: table.sensorUUID, + tierId: 1, + tierTable: sensorUUID => sensorUUID === table.sensorUUID + ? table + : undefined, + }) + + keepers.push(keeper) + + return { + accessoryUUID, + alerts, + buffer: () => table.videoTiers.get(1)!.buffer, + delegate, + gap, + keeper, + table, + } +} + +// The kinds of the problems a keeper raised, in order. +function kinds(alerts: readonly CameraProblem[]): string[] { + return alerts.map(({ kind }) => kind) +} + +// The stream the delegate was handed for video tier 1's latest demand. +function streamOf(delegate: ScriptedTierDelegate): TierStream { + return delegate.tierDemandStarted.mock.calls.at(-1)![0] +} + +// A fragment of one picture at a time in seconds, a keyframe or not, with a sound timed beside it. +function fragmentAt(seconds: number, keyframe = false, octets = 100): Buffer { + return tierStreamFragment({ + picture: [ + tierPicture({ keyframe, octets }), + ], + pictureTime: BigInt(seconds * PICTURE_RATE), + sound: [ + soundSample(Buffer.alloc(40, 0x5A)), + ], + soundTime: BigInt(seconds * SOUND_RATE), + }) +} + +// A fragment of one sound alone at a time in seconds. +function soundAt(seconds: number): Buffer { + return tierStreamFragment({ + sound: [ + soundSample(Buffer.alloc(40, 0x5A)), + ], + soundTime: BigInt(seconds * SOUND_RATE), + }) +} + +function scriptedHolder(): TierHolder & { tierFailed: Mock<() => void> } { + return { + tierFailed: vi.fn<() => void>(), + } +} + +// A frame consumer that keeps each frame it is handed. +function keepingConsumer(): FrameConsumer & { frames: TierFrame[] } { + const frames: TierFrame[] = [] + + return { + frames, + take: (frame) => { + frames.push(frame) + }, + } +} + +// A place a row takes in a tier's buffer, which holds no keyframe and keeps each sample it is told by its medium and its time in seconds. +function listeningPlace(): BufferPlace & { told: string[] } { + const told: string[] = [] + + return { + displaced: () => { + told.push('displaced') + }, + taken: (sample: BufferedSample) => { + told.push(`${sample.track.medium} ${sample.time / 1000000}`) + }, + told, + } +} + +// The samples a tier's buffer keeps, each by its medium and its time in seconds, in delivery order. +function kept(buffer: TierBuffer): string[] { + return buffer.samples.map(({ time, track }) => `${track.medium} ${time / 1000000}`) +} + +// The times in seconds of the picture keyframes a tier's buffer keeps. +function keyframeTimes(buffer: TierBuffer): number[] { + return buffer.samples.filter(({ sync, track }) => sync && (track.medium === 'video')).map(({ time }) => time / 1000000) +} + +// Whether a sample's octets are a view of a written chunk's own memory, read by the range they cover, since a small buffer and its copy can share a pool. +function inside(data: Buffer, chunk: Buffer): boolean { + return (data.buffer === chunk.buffer) && (data.byteOffset >= chunk.byteOffset) && (data.byteOffset + data.length <= chunk.byteOffset + chunk.length) +} + +afterEach(() => { + for (const keeper of keepers.splice(0)) { + keeper[Symbol.dispose]() + } + + vi.restoreAllMocks() + vi.useRealTimers() +}) + +describe('tierKeeper', () => { + it('raises its tier\'s demand with no connection, calling tierDemandStarted once, and a session at home joining later cuts at its own server\'s size', + async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + for (const [family, sizes] of [ + [ + 'IPv4', + [12 + 1300], + ], + [ + 'IPv6', + [1228, 12 + 3 + 1298 - 1213], + ], + ] as const) { + const { delegate, keeper, table } = rig() + + keeper.raise('recording') + keeper.raise('recording') + await settle() + + const stream = streamOf(delegate) + + expect(delegate.tierDemandStarted.mock.calls.map(([{ tier }]) => [tier.sensorUUID, tier.id])).toEqual([ + [table.sensorUUID, 1], + ]) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + + // With no session joined the demand cuts nothing. + expect(stream.statistics()).toMatchObject({ packets: 0, consumers: 1 }) + + const offered: number[] = [] + const sent: number[] = [] + + table.join(table.videoTiers.get(1)!, scriptedHolder(), buildEmitterConnection(family), ['video'], (_medium, packetSize) => { + offered.push(packetSize) + + return { + capacity: Number.POSITIVE_INFINITY, + free: Number.POSITIVE_INFINITY, + send: (packet) => { + sent.push(packet.length) + + return true + }, + } + }) + // A picture of one slice of 1300 octets, whole under IPv4's packets and in two fragments under IPv6's. + stream.write(fragmentAt(0.5, false, 4 + 1300)) + await vi.advanceTimersByTimeAsync(200) + + // The session opens behind the keyframe the library's hold let go, which it is handed first, its parameter sets and its slice in one aggregation + // packet. + expect({ family, offered, sent }).toEqual({ + family, + offered: [ + family === 'IPv4' + ? 1378 + : 1228, + ], + sent: [ + 12 + 2 + 3 * (2 + 12) + 2 + 96, + ...sizes, + ], + }) + } + }) + + it('keeps each sample as the stream reader handed it over, a view of the written chunk or the reader\'s own joined copy, and copies none', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const { buffer, delegate, keeper, table } = rig() + const consumer = keepingConsumer() + + keeper.raise('recording') + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), consumer) + await settle() + + const stream = streamOf(delegate) + const chunk = fragmentAt(0, true, 6000) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(chunk) + + expect(buffer()!.samples.map(({ data }) => inside(data, chunk))).toEqual([true, true]) + + // A fragment cut inside its picture's sample, whose octets the reader joins once and hands the frame consumer and the buffer alike. + const spanning = fragmentAt(0.5, false, 6000) + const cut = spanning.length - 3000 + + stream.write(spanning.subarray(0, cut)) + stream.write(spanning.subarray(cut)) + await vi.advanceTimersByTimeAsync(200) + + const [joined] = buffer()!.samples.slice(2) + + expect(joined.data).toBe(consumer.frames.at(-1)!.data) + expect([ + inside(joined.data, spanning), + joined.data.length, + ]).toEqual([false, 6000]) + }) + + it('counts its hold among the stream\'s consumers', async () => { + const { delegate, keeper, table } = rig() + + keeper.raise('recording') + await settle() + + const stream = streamOf(delegate) + + expect(stream.statistics().consumers).toBe(1) + + const viewer = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + + expect(stream.statistics().consumers).toBe(2) + + keeper.release('recording') + + expect(stream.statistics().consumers).toBe(1) + + viewer.release() + }) + + it('joins a demand a viewer raised, whose tier\'s buffer holds the stream\'s tracks and its samples from its latest keyframe, and is ready once that ' + + 'buffer holds the prebuffer', async () => { + const { buffer, delegate, keeper, table } = rig(1000) + + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + await settle() + + const stream = streamOf(delegate) + + // Every fragment arrives on the row's own timeline, the first at 0 ms. The buffer reads each arrival after the one before it however long the + // suite's worker has run: an arrival at the worker's own clock would stand past the later ones, which the buffer reads as a jump. + vi.spyOn(performance, 'now').mockReturnValue(0) + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + keeper.raise('recording') + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(1) + expect([ + buffer().tracks?.video?.parameterSets.length, + buffer().samples.map(({ time, track }) => [track.medium, time]), + ]).toEqual([ + 3 * 16, + [ + ['video', 0], + ['audio', 0], + ], + ]) + + const readings: boolean[] = [] + + for (const [seconds, keyframe] of [ + [0.5, false], + [1, true], + [1.5, false], + [2, false], + ] as const) { + vi.spyOn(performance, 'now').mockReturnValue(seconds * 1000) + stream.write(fragmentAt(seconds, keyframe)) + readings.push(buffer().ready) + } + + expect(readings).toEqual([false, true, true, true]) + }) + + it('ends its hold for a tier whose stream fails, the tier\'s buffer fed nothing more and emptied as the demand ends with its last join', async () => { + const { buffer, delegate, keeper } = rig() + + keeper.raise('recording') + await settle() + + const stream = streamOf(delegate) + + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + stream.fail('the camera went away') + stream.write(fragmentAt(0.5)) + + expect(buffer().samples.map(({ time }) => time)).toEqual([0, 0]) + expect(endsOf(delegate)).toBe(0) + + await settle() + + expect(endedOf(delegate).map(ended => [ended.tier.id, ended === stream])).toEqual([ + [1, true], + ]) + expect(buffer()!.samples).toEqual([]) + }) + + describe('the tier\'s buffer', () => { + it('keeps the samples since its latest keyframe in every running tier\'s buffer, a tier only a viewer holds among them, and empties each as its ' + + 'demand ends', async () => { + const { buffer, delegate, keeper, table } = rig() + const viewed = table.videoTiers.get(2)!.buffer + + keeper.raise('recording') + + const viewer = table.joinFrames(table.videoTiers.get(2)!, 'video', scriptedHolder(), keepingConsumer()) + + await settle() + + for (const [stream] of delegate.tierDemandStarted.mock.calls) { + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + + for (const seconds of [0, 0.5, 1, 1.5]) { + stream.write(fragmentAt(seconds, Number.isInteger(seconds))) + } + } + + expect([ + kept(buffer()), + kept(viewed), + ]).toEqual([ + [ + 'video 1', + 'audio 1', + 'video 1.5', + 'audio 1.5', + ], + [ + 'video 1', + 'audio 1', + 'video 1.5', + 'audio 1.5', + ], + ]) + + keeper.release('recording') + viewer.release() + await settle() + + expect([ + buffer().samples, + viewed.samples, + endsOf(delegate), + ]).toEqual([[], [], 2]) + }) + + it('lets its tier\'s buffer fall at once to the samples since its latest keyframe as its hold is released while a viewer keeps the tier', async () => { + const { buffer, delegate, keeper, table } = rig(2000) + + keeper.raise('recording') + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + await settle() + + const stream = streamOf(delegate) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + + for (let half = 0; half <= 8; half++) { + stream.write(fragmentAt(half / 2, half % 2 === 0)) + } + + expect(keyframeTimes(buffer())).toEqual([2, 3, 4]) + + keeper.release('recording') + + expect([ + keyframeTimes(buffer()), + buffer().span, + ]).toEqual([ + [4], + 0, + ]) + + stream.write(fragmentAt(4.5)) + + expect(kept(buffer())).toEqual([ + 'video 4', + 'audio 4', + 'video 4.5', + 'audio 4.5', + ]) + }) + + it('holds its tier with one join while any of its reasons stands, its tier\'s buffer spanning the prebuffer only while the recording reason stands, ' + + 'and takes no reason once closed, the reasons that stood keeping it until each is released', async () => { + const { buffer, delegate, keeper } = rig(2000) + // The demands started and ended, the joins of the latest one and the span of the tier's buffer. + const reading = (): number[] => [ + delegate.tierDemandStarted.mock.calls.length, + endsOf(delegate), + streamOf(delegate).statistics().consumers, + buffer().span, + ] + const readings: number[][] = [] + + keeper.raise('kept-running') + await settle() + readings.push(reading()) + keeper.raise('recording') + keeper.raise('recording') + readings.push(reading()) + keeper.release('recording') + readings.push(reading()) + keeper.raise('recording') + keeper.release('kept-running') + readings.push(reading()) + keeper.release('recording') + await settle() + readings.push(reading()) + keeper.raise('recording') + await settle() + keeper.close() + keeper.raise('kept-running') + readings.push(reading()) + keeper.release('recording') + await settle() + readings.push(reading()) + keeper.raise('recording') + keeper[Symbol.dispose]() + keeper[Symbol.dispose]() + await settle() + readings.push(reading()) + + expect(readings).toEqual([ + [1, 0, 1, 0], + [1, 0, 1, 2000], + [1, 0, 1, 0], + [1, 0, 1, 2000], + [1, 1, 0, 0], + [2, 1, 1, 2000], + [2, 2, 0, 0], + [2, 2, 0, 0], + ]) + }) + + it('tells each place in its tier\'s buffer of a sample before any packet of it is sent', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const { buffer, delegate, keeper, table } = rig() + const order: string[] = [] + + keeper.raise('recording') + await settle() + + const stream = streamOf(delegate) + + buffer().takePlace({ + displaced: () => undefined, + taken: (sample) => { + order.push(`told ${sample.track.medium}`) + }, + }) + table.join(table.videoTiers.get(1)!, scriptedHolder(), buildEmitterConnection('IPv4'), ['video', 'audio'], medium => ({ + capacity: Number.POSITIVE_INFINITY, + free: Number.POSITIVE_INFINITY, + send: () => { + order.push(`sent ${medium}`) + + return true + }, + })) + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + + // Each place is told of the picture and of the sound inside the write, and the pacer sends the picture and the sound in a turn of its own. + expect(order).toEqual([ + 'told video', + 'told audio', + ]) + + await vi.advanceTimersByTimeAsync(0) + + expect(order).toEqual([ + 'told video', + 'told audio', + 'sent video', + 'sent audio', + ]) + }) + + it('counts a picture whose lengths do not tile it and a sound of no octets once each, and keeps neither in its tier\'s buffer nor tells a place of ' + + 'them', async () => { + const { buffer, delegate, keeper } = rig() + const place = listeningPlace() + + keeper.raise('recording') + await settle() + + const stream = streamOf(delegate) + + buffer().takePlace(place) + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(Buffer.from('0000000a0201', 'hex')), + ], + pictureTime: BigInt(0.5 * PICTURE_RATE), + sound: [ + soundSample(Buffer.alloc(0)), + ], + soundTime: BigInt(0.5 * SOUND_RATE), + })) + stream.write(fragmentAt(1)) + + expect(stream.statistics().drops).toBe(2) + expect([ + place.told, + kept(buffer()), + ]).toEqual([ + [ + 'video 0', + 'audio 0', + 'video 1', + 'audio 1', + ], + [ + 'video 0', + 'audio 0', + 'video 1', + 'audio 1', + ], + ]) + }) + }) + + describe('a release while the tier\'s start is pending', () => { + it('leaves the keeper doing nothing more after a release, a reset and a removal, the start settling afterwards and the reset\'s own withdrawal among ' + + 'them', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const lines = captureDebug('HAP-NodeJS:Camera:Tier') + const reasons = ['release', 'reset', 'removal'] as const + + for (const reason of reasons) { + const { buffer, delegate, keeper, table } = rig() + const start = pendingStart(delegate) + + keeper.raise('recording') + + // A reset and a removal also withdraw each pending demand through the table, which the camera controller does once it has released every keeper; + // here the withdrawal comes first, in the release's own turn, and the keeper does nothing more whatever the order. + if (reason !== 'release') { + table.withdraw('when its service ended every session: the demand is withdrawn and every join waiting on it is refused') + } + + if (reason === 'removal') { + keeper[Symbol.dispose]() + } else { + keeper.release('recording') + } + + start.resolve() + await settle() + + // A release ends the demand as its start settles, releasing what the start registered; a withdrawal aborts the start's signal and then releases what + // the start registered at once, and the start's settling releases nothing more. + expect({ + reason, + starts: delegate.tierDemandStarted.mock.calls.length, + aborted: signalOf(delegate, streamOf(delegate)).aborted, + disposed: disposedOf(delegate, streamOf(delegate)), + samples: buffer().samples.length, + span: buffer().span, + }).toEqual({ + reason, + starts: 1, + aborted: reason !== 'release', + disposed: 1, + samples: 0, + span: 0, + }) + } + + // Each withdrawal is the library's own, written as a debug event, which is why none prints a warning. + expect(lines.filter(line => line.startsWith('The library withdrew'))).toEqual([ + `The library withdrew the pending start of the video tier 1 of the video sensor "${TIERS.sensorUUID.toLowerCase()}" when its service ended every ` + + 'session: the demand is withdrawn and every join waiting on it is refused.', + `The library withdrew the pending start of the video tier 1 of the video sensor "${TIERS.sensorUUID.toLowerCase()}" when its service ended every ` + + 'session: the demand is withdrawn and every join waiting on it is refused.', + ]) + expect(warn).not.toHaveBeenCalled() + }) + + it('lets no wait left from an earlier raise act on a later one, which its own bound withdraws', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, buffer, delegate, keeper, table } = rig() + const start = pendingStart(delegate) + + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(20000) + keeper.release('recording') + keeper.raise('recording') + + const stream = streamOf(delegate) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + await settle() + + expect([delegate.tierDemandStarted.mock.calls.length, buffer()!.samples.length]).toEqual([1, 2]) + + // The stream runs on, a keyframe a second, up to the moment the start's bound falls, 30 seconds from its call and 10 from the later raise's join. + const runFor = async (from: number, to: number): Promise => { + for (let second = from; second <= to; second++) { + await vi.advanceTimersByTimeAsync(1000) + stream.write(fragmentAt(second, true)) + } + } + + await runFor(1, 9) + + expect([ + warn.mock.calls.length, + endsOf(delegate), + buffer()!.samples.length, + alerts, + ]).toEqual([0, 0, 2, []]) + + await runFor(10, 10) + + expect(warn.mock.calls.map(([line]) => line)).toEqual([ + `MultiTierStreamingDelegate did not settle tierDemandStarted for the video tier 1 of the video sensor "${table.sensorUUID}" within 30 seconds: ` + + 'the demand is withdrawn and every join waiting on it is refused.', + ]) + expect([ + endsOf(delegate), + signalOf(delegate, stream).aborted, + buffer()!.samples, + ]).toEqual([1, true, []]) + + // The later raise's hold alone answers the withdrawal, once, and the earlier raise's wait acts on nothing. + expect(alerts.map(({ kind, sentence }) => [kind, sentence])).toEqual([ + [ + 'tier-failed', + `The start of the stream of the video tier 1 of the video sensor "${table.sensorUUID}", which the library holds, did not settle within 30 seconds, ` + + 'and the library asks for it again.', + ], + ]) + + // The withdrawal released what the start registered, and its later settling releases nothing more. + start.resolve() + await settle() + + expect(disposedOf(delegate, stream)).toBe(1) + }) + + it('raises one tier-failed alert at 30 seconds, saying the start did not settle, for a keeper raised at 20 seconds onto a pending demand another hold ' + + 'left at 10 seconds, the demand\'s one warning beside it, and asks again', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, delegate, keeper, table } = rig() + + pendingStart(delegate) + + const other = table.hold(table.videoTiers.get(1)!, scriptedHolder()) + + await vi.advanceTimersByTimeAsync(10000) + other.release() + await vi.advanceTimersByTimeAsync(10000) + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(9999) + + expect([alerts, warn.mock.calls.length, delegate.tierDemandStarted.mock.calls.length]).toEqual([[], 0, 1]) + + await vi.advanceTimersByTimeAsync(1) + + expect(alerts.map(({ kind, sentence }) => [kind, sentence])).toEqual([ + [ + 'tier-failed', + `The start of the stream of the video tier 1 of the video sensor "${table.sensorUUID}", which the library holds, did not settle within 30 seconds, ` + + 'and the library asks for it again.', + ], + ]) + expect(warn.mock.calls).toEqual([ + [ + `MultiTierStreamingDelegate did not settle tierDemandStarted for the video tier 1 of the video sensor "${table.sensorUUID}" within 30 seconds: ` + + 'the demand is withdrawn and every join waiting on it is refused.', + ], + ]) + + // The keeper asks again once its first wait passes, which raises the tier's demand anew. + await vi.advanceTimersByTimeAsync(1000) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + + it('raises one tier-failed alert saying the start was refused for a keeper whose pending start rejects, with no warning, and asks again', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + vi.spyOn(console, 'error').mockImplementation(() => undefined) + + const { alerts, delegate, keeper, table } = rig() + const start = pendingStart(delegate) + + keeper.raise('recording') + start.reject(new Error('The encoder would not start.')) + await settle() + + expect(alerts.map(({ kind, sentence }) => [kind, sentence])).toEqual([ + [ + 'tier-failed', + `The start of the stream of the video tier 1 of the video sensor "${table.sensorUUID}", which the library holds, was refused, and the library asks ` + + 'for it again.', + ], + ]) + expect(warn).not.toHaveBeenCalled() + + // The keeper asks again once its first wait passes, which raises the tier's demand anew. + await vi.advanceTimersByTimeAsync(1000) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + }) + + describe('the clocks of a held tier', () => { + const name = (sensorUUID: string): string => `the video tier 1 of the video sensor "${sensorUUID}"` + + // The fake clock the clocks run on, the bound on a start among them. + function fakeClock(): void { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + } + + // A raised keeper whose tier's stream has started and handed over its initialization segment and a keyframe. + async function running(prebuffer = 0): Promise { + const kept = rig(prebuffer) + + kept.keeper.raise('recording') + await settle() + + const stream = streamOf(kept.delegate) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + + return { ...kept, stream } + } + + it('raises tier-stalled once, two seconds after a running demand\'s last picture, and tier-resumed once at its next, and neither for a start slower ' + + 'than the stall time to its first picture', async () => { + fakeClock() + + const { accessoryUUID, alerts, delegate, keeper, table } = rig() + const start = deferred() + + delegate.tierDemandStarted.mockReturnValueOnce(start.promise) + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(3000) + start.resolve() + await vi.advanceTimersByTimeAsync(3000) + + expect(alerts).toEqual([]) + + const stream = streamOf(delegate) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + await vi.advanceTimersByTimeAsync(1999) + + expect(alerts).toEqual([]) + + await vi.advanceTimersByTimeAsync(4001) + stream.write(fragmentAt(0.5)) + stream.write(fragmentAt(1)) + + expect(alerts).toEqual([ + { + accessoryUUID, + kind: 'tier-stalled', + level: 'warning', + sensorUUID: table.sensorUUID, + sentence: `The stream of ${name(table.sensorUUID)}, which the library holds, handed over no picture for 2 seconds.`, + tierId: 1, + }, + { + accessoryUUID, + kind: 'tier-resumed', + level: 'warning', + sensorUUID: table.sensorUUID, + sentence: `The stream of ${name(table.sensorUUID)}, which the library holds, hands over its pictures again.`, + tierId: 1, + }, + ]) + }) + + it('raises no alert and asks for no tier again while a started stream writes a fragment every second for 40 seconds', async () => { + fakeClock() + + const { alerts, delegate, stream } = await running() + + for (let seconds = 1; seconds <= 40; seconds++) { + await vi.advanceTimersByTimeAsync(1000) + stream.write(fragmentAt(seconds, seconds % 4 === 0)) + } + + expect(alerts).toEqual([]) + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(1) + }) + + it('keeps doubling its waits for a stream whose failures come after sound and pictures that are no keyframe, and starts them over once the stream ' + + 'hands over a keyframe', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { delegate, keeper } = rig() + const moments: number[] = [] + + delegate.tierDemandStarted.mockImplementation(async () => { + moments.push(performance.now()) + }) + keeper.raise('recording') + + // Each start's stream hands over sound and a picture that is no keyframe before it fails, and the fourth a keyframe as well. + for (let start = 1; start <= 4; start++) { + while (delegate.tierDemandStarted.mock.calls.length < start) { + await vi.advanceTimersByTimeAsync(100) + } + + const stream = streamOf(delegate) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + + if (start === 4) { + stream.write(fragmentAt(0, true)) + } + + stream.write(fragmentAt(0.5)) + stream.fail('The camera went away.') + } + + await vi.advanceTimersByTimeAsync(1000) + + expect(moments.slice(1).map((moment, index) => moment - moments[index])).toEqual([ + 1000, + 2000, + 4000, + 1000, + ]) + }) + + it('empties the buffer and ends the demand with every view on it at a long gap, the demand telling its silence once and the keeper raising one ' + + 'tier-failed beside the stall\'s alert, asks again once a second later, and asks again for a demand that then stays silent past its first-sample ' + + 'bound, telling nothing more', async () => { + fakeClock() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, buffer, delegate, gap, table } = await running() + const viewer = scriptedHolder() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', viewer, keepingConsumer()) + + viewer.tierFailed.mockImplementation(() => queueMicrotask(() => view.release())) + await vi.advanceTimersByTimeAsync(9999) + + expect([ + kinds(alerts), + gap.mock.calls.length, + buffer()!.samples.length, + ]).toEqual([ + ['tier-stalled'], + 0, + 2, + ]) + + await vi.advanceTimersByTimeAsync(1) + + // The tier table reports through a reporter of no camera, which prints its one stream-failed problem. + expect({ + alerts: kinds(alerts), + gap: gap.mock.calls.length, + samples: buffer()!.samples.length, + views: viewer.tierFailed.mock.calls.length, + ends: endsOf(delegate), + warnings: warn.mock.calls.map(([line]) => line), + }).toEqual({ + alerts: ['tier-stalled', 'tier-failed'], + gap: 1, + samples: 0, + views: 1, + ends: 1, + warnings: [ + `The library ended the stream of ${name(table.sensorUUID)} (no picture for 10 seconds), and every session on the tier ends.`, + ], + }) + expect(alerts[1].sentence).toBe(`The stream of ${name(table.sensorUUID)}, which the library holds, failed, and the library asks for it again.`) + + await vi.advanceTimersByTimeAsync(999) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(1) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + + // The next demand hands over nothing and ends at its first-sample bound, its silence the tier's told already and the outage's failure raised. + await vi.advanceTimersByTimeAsync(30000) + + expect([ + kinds(alerts), + delegate.tierDemandStarted.mock.calls.length, + warn.mock.calls.length, + ]).toEqual([ + ['tier-stalled', 'tier-failed'], + 2, + 1, + ]) + + await vi.advanceTimersByTimeAsync(2000) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(3) + }) + + it('tells a held tier\'s silence as one tier-stalled at 2 seconds and, at 10 seconds, the gap once before the demand ends with one stream-failed ' + + 'problem and one tier-failed, and asks again after its first wait, raising tier-resumed at the next demand\'s first picture', async () => { + fakeClock() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, delegate, gap, stream, table } = await running() + const viewer = scriptedHolder() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', viewer, keepingConsumer()) + + viewer.tierFailed.mockImplementation(() => queueMicrotask(() => view.release())) + await vi.advanceTimersByTimeAsync(2000) + + const stalled = kinds(alerts) + + await vi.advanceTimersByTimeAsync(8000) + + // The gap is told before the demand's end releases what its start registered, the keeper reading each picture ahead of the demand. + expect({ + stalled, + alerts: kinds(alerts), + gaps: gap.mock.calls.length, + warnings: warn.mock.calls.map(([line]) => line), + gapBeforeEnd: gap.mock.invocationCallOrder[0] < delegate.disposals.get(stream)!.mock.invocationCallOrder[0], + }).toEqual({ + stalled: ['tier-stalled'], + alerts: ['tier-stalled', 'tier-failed'], + gaps: 1, + warnings: [ + `The library ended the stream of ${name(table.sensorUUID)} (no picture for 10 seconds), and every session on the tier ends.`, + ], + gapBeforeEnd: true, + }) + + await vi.advanceTimersByTimeAsync(999) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(1) + + const next = streamOf(delegate) + + next.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + next.write(fragmentAt(0, true)) + + expect([ + delegate.tierDemandStarted.mock.calls.length, + kinds(alerts), + gap.mock.calls.length, + ]).toEqual([ + 2, + ['tier-stalled', 'tier-failed', 'tier-resumed'], + 1, + ]) + }) + + it('ends a demand a viewer raised that is already silent as the keeper joins it, at the demand\'s own first-sample bound, and asks again after its ' + + 'first wait for a fresh one', async () => { + fakeClock() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, delegate, keeper, table } = rig() + const viewer = scriptedHolder() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', viewer, keepingConsumer()) + + // The viewer's demand starts at once and hands over nothing, and the keeper joins it ten seconds on. + viewer.tierFailed.mockImplementation(() => queueMicrotask(() => view.release())) + await vi.advanceTimersByTimeAsync(10000) + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(19999) + + expect([ + kinds(alerts), + delegate.tierDemandStarted.mock.calls.length, + warn.mock.calls.length, + ]).toEqual([[], 1, 0]) + + await vi.advanceTimersByTimeAsync(1) + + expect({ + alerts: kinds(alerts), + views: viewer.tierFailed.mock.calls.length, + ends: endsOf(delegate), + warnings: warn.mock.calls.map(([line]) => line), + }).toEqual({ + alerts: ['tier-failed'], + views: 1, + ends: 1, + warnings: [ + `The library ended the stream of ${name(table.sensorUUID)} (no picture within 30 seconds of its start's settling), and every session on the tier ends.`, + ], + }) + + await vi.advanceTimersByTimeAsync(1000) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + + it('stalls a held tier whose stream hands over sound and no picture, tells its recording of the gap and ends its demand at 10 seconds, the sound ' + + 'moving no clock on', async () => { + fakeClock() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, delegate, gap, stream, table } = await running() + // Writes a fragment of sound alone each half second after the keyframe, from one half second to another. + const sounds = async (from: number, to: number): Promise => { + for (let half = from; half <= to; half++) { + await vi.advanceTimersByTimeAsync(500) + stream.write(soundAt(half / 2)) + } + } + + await sounds(1, 4) + + const stalled = kinds(alerts) + + await sounds(5, 19) + await vi.advanceTimersByTimeAsync(499) + + expect([ + stalled, + kinds(alerts), + gap.mock.calls.length, + endsOf(delegate), + ]).toEqual([ + ['tier-stalled'], + ['tier-stalled'], + 0, + 0, + ]) + + await vi.advanceTimersByTimeAsync(1) + + expect({ + alerts: kinds(alerts), + gaps: gap.mock.calls.length, + ends: endsOf(delegate), + warnings: warn.mock.calls.map(([line]) => line), + }).toEqual({ + alerts: ['tier-stalled', 'tier-failed'], + gaps: 1, + ends: 1, + warnings: [ + `The library ended the stream of ${name(table.sensorUUID)} (no picture for 10 seconds), and every session on the tier ends.`, + ], + }) + }) + + it('raises tier-resumed for a stalled held tier at its next picture and not at a sound', async () => { + fakeClock() + + const { alerts, stream } = await running() + + await vi.advanceTimersByTimeAsync(2500) + stream.write(soundAt(2.5)) + + const sounded = kinds(alerts) + + await vi.advanceTimersByTimeAsync(500) + stream.write(fragmentAt(3)) + + expect([ + sounded, + kinds(alerts), + ]).toEqual([ + ['tier-stalled'], + ['tier-stalled', 'tier-resumed'], + ]) + }) + + it('asks again after waits of 1, 2, 4 and on to 30 seconds, staying at 30, and starts over once the tier hands over a keyframe', async () => { + fakeClock() + vi.spyOn(console, 'error').mockImplementation(() => undefined) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { delegate, keeper } = rig() + const moments: number[] = [] + + delegate.tierDemandStarted.mockImplementation(async () => { + moments.push(performance.now()) + + if (moments.length <= 7) { + throw new Error('The camera is busy.') + } + }) + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(91000) + + const stream = streamOf(delegate) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + stream.fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + expect(moments.slice(1).map((moment, index) => moment - moments[index])).toEqual([ + 1000, + 2000, + 4000, + 8000, + 16000, + 30000, + 30000, + 1000, + ]) + }) + + it('stops asking at a release, and does nothing after a release, a reset or a removal, one made while a start is pending among them', async () => { + fakeClock() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const lines = captureDebug('HAP-NodeJS:Camera:Tier') + const failed = await running() + + failed.stream.fail('The camera went away.') + failed.keeper.release('recording') + + const running2 = await running() + + running2.keeper.release('recording') + + const pending = rig() + const removed = rig() + + for (const { delegate, keeper, table } of [pending, removed]) { + delegate.tierDemandStarted.mockReturnValueOnce(new Promise(() => undefined)) + keeper.raise('recording') + table.withdraw('when its service ended every session: the demand is withdrawn and every join waiting on it is refused') + } + + pending.keeper.release('recording') + removed.keeper[Symbol.dispose]() + await vi.advanceTimersByTimeAsync(60000) + + expect([failed, running2, pending, removed].map(({ alerts, delegate, gap }) => [ + kinds(alerts), + delegate.tierDemandStarted.mock.calls.length, + gap.mock.calls.length, + ])).toEqual([ + [ + ['tier-failed'], + 1, + 0, + ], + [[], 1, 0], + [[], 1, 0], + [[], 1, 0], + ]) + // Each withdrawal is the library's own, written as a debug event, which is why none prints a warning. + expect(lines.filter(line => line.startsWith('The library withdrew the pending start'))).toHaveLength(2) + expect(warn.mock.calls.filter(([line]) => String(line).startsWith('MultiTierStreamingDelegate did not settle'))).toHaveLength(0) + }) + + it('asks again once for each failure, the stream\'s own, the reader\'s refusal, a refused start, a start cut at its bound and a first sample past ' + + 'its bound, and raises tier-failed once and tier-resumed once for an outage of several failed asks', async () => { + fakeClock() + vi.spyOn(console, 'error').mockImplementation(() => undefined) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const failures: [string, (kept: Rig) => Promise][] = [ + [ + 'the stream', + async ({ delegate }) => { + await settle() + streamOf(delegate).fail('The camera went away.') + }, + ], + [ + 'the reader', + async ({ delegate }) => { + await settle() + streamOf(delegate).write(Buffer.from('0000000466726565', 'hex')) + }, + ], + [ + 'a refusal', + async () => undefined, + ], + [ + 'the bound', + async () => { + await vi.advanceTimersByTimeAsync(30000) + }, + ], + [ + 'the first sample', + async () => { + await vi.advanceTimersByTimeAsync(30000) + }, + ], + ] + const readings: unknown[] = [] + + for (const [failure, fail] of failures) { + const kept = rig() + + if (failure === 'a refusal') { + kept.delegate.tierDemandStarted.mockRejectedValueOnce(new Error('The camera is busy.')) + } else if (failure === 'the bound') { + kept.delegate.tierDemandStarted.mockReturnValueOnce(new Promise(() => undefined)) + } + + kept.keeper.raise('recording') + await fail(kept) + await vi.advanceTimersByTimeAsync(999) + + const before = kept.delegate.tierDemandStarted.mock.calls.length + + await vi.advanceTimersByTimeAsync(1) + readings.push([ + failure, + kinds(kept.alerts), + before, + kept.delegate.tierDemandStarted.mock.calls.length, + ]) + kept.keeper.release('recording') + } + + expect(readings).toEqual(failures.map(([failure]) => [ + failure, + ['tier-failed'], + 1, + 2, + ])) + + const { alerts, delegate, keeper } = rig() + + delegate.tierDemandStarted.mockRejectedValueOnce(new Error('The camera is busy.')) + delegate.tierDemandStarted.mockRejectedValueOnce(new Error('The camera is busy.')) + delegate.tierDemandStarted.mockRejectedValueOnce(new Error('The camera is busy.')) + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(7000) + + const stream = streamOf(delegate) + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + stream.write(fragmentAt(0, true)) + stream.write(fragmentAt(0.5)) + + expect([ + kinds(alerts), + delegate.tierDemandStarted.mock.calls.length, + ]).toEqual([ + ['tier-failed', 'tier-resumed'], + 4, + ]) + }) + + it('raises tier-failed once and asks again after its first wait for a held tier whose stream repeats a decode time', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { accessoryUUID, alerts, delegate, stream, table } = await running() + + stream.write(fragmentAt(0.5)) + stream.write(fragmentAt(0.5)) + await vi.advanceTimersByTimeAsync(999) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(1) + + expect(alerts).toEqual([ + { + accessoryUUID, + kind: 'tier-failed', + level: 'warning', + sensorUUID: table.sensorUUID, + sentence: `The stream of ${name(table.sensorUUID)}, which the library holds, failed, and the library asks for it again.`, + tierId: 1, + }, + ]) + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + + it('waits at its first ask for the end of a silent demand a viewer still holds, raising one tier-failed beside the stall\'s alert, and starts the next ' + + 'demand after that demand\'s end', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { alerts, delegate, table } = await running() + const viewer = scriptedHolder() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', viewer, keepingConsumer()) + + // The viewer releases a second and a half after the demand's silence end ends its view, half a second after the keeper's first ask. + viewer.tierFailed.mockImplementation(() => { + setTimeout(() => view.release(), 1500) + }) + await vi.advanceTimersByTimeAsync(11000) + + expect([ + kinds(alerts), + delegate.tierDemandStarted.mock.calls.length, + endsOf(delegate), + ]).toEqual([ + ['tier-stalled', 'tier-failed'], + 1, + 0, + ]) + + await vi.advanceTimersByTimeAsync(500) + + expect([ + kinds(alerts), + delegate.tierDemandStarted.mock.calls.length, + endsOf(delegate), + ]).toEqual([ + ['tier-stalled', 'tier-failed'], + 2, + 1, + ]) + expect(delegate.disposals.get(streamsOf(delegate)[0])!.mock.invocationCallOrder[0]).toBeLessThan(delegate.tierDemandStarted.mock.invocationCallOrder[1]) + }) + + it('doubles no wait for a failed demand a viewer still holds at its ask, its own join on that demand released before it waits', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { alerts, delegate, stream, table } = await running() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + const moments: number[] = [] + + delegate.tierDemandStarted.mockImplementation(async () => { + moments.push(performance.now()) + }) + stream.fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + // The keeper's join on the failed demand is released: the viewer's release ends the demand, and the keeper joins the next at once. + expect(endsOf(delegate)).toBe(0) + + view.release() + await vi.advanceTimersByTimeAsync(0) + + expect([ + endsOf(delegate), + moments.length, + ]).toEqual([1, 1]) + + // The next stream fails at once, and the keeper asks again after the wait the first failure doubled, and once only. + streamOf(delegate).fail('The camera went away.') + await vi.advanceTimersByTimeAsync(5000) + + expect(moments.slice(1).map((moment, index) => moment - moments[index])).toEqual([2000]) + expect(kinds(alerts)).toEqual(['tier-failed']) + }) + + it('arms nothing after a release while it waits for the end of a failed demand a viewer holds', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { alerts, delegate, keeper, stream, table } = await running() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + + stream.fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + keeper.release('recording') + view.release() + await vi.advanceTimersByTimeAsync(60000) + + expect([ + kinds(alerts), + delegate.tierDemandStarted.mock.calls.length, + endsOf(delegate), + error.mock.calls.length, + ]).toEqual([ + ['tier-failed'], + 1, + 1, + 0, + ]) + }) + + it('reports a wait of its own that fails, on its tier\'s pending start and on the end of a failed demand a viewer holds, as the library\'s failure on ' + + 'its tier, printing nothing', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const starting = rig() + const onStart = new Error('The wait on the start failed.') + const onEnd = new Error('The wait on the end failed.') + // Each problem a keeper raised, its sentence's first line alone, a failure's stack left out. + const firstLines = (problems: readonly CameraProblem[]): CameraProblem[] => problems.map(problem => ({ + ...problem, + sentence: problem.sentence.split('\n')[0], + })) + + // The keeper's join finds the start pending, and its wait on the start's answer throws as it begins. + pendingStart(starting.delegate) + vi.spyOn(TierHold.prototype, 'answer').mockImplementationOnce(() => { + throw onStart + }) + starting.keeper.raise('recording') + await settle() + + // The keeper's join after its failed stream finds the failed demand a viewer still holds, and its wait on that demand's end throws as it begins. + const { accessoryUUID, alerts, stream, table } = await running() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + + vi.spyOn(TierHold.prototype, 'ended').mockImplementationOnce(() => { + throw onEnd + }) + stream.fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + view.release() + + const tierName = `the video tier 1 of the video sensor "${table.sensorUUID}"` + + expect(firstLines(starting.alerts)).toEqual([ + { + accessoryUUID: starting.accessoryUUID, + error: onStart, + kind: 'library-failure', + level: 'error', + sensorUUID: table.sensorUUID, + sentence: `The library failed to wait on the start of ${tierName} it holds: Error: The wait on the start failed.`, + tierId: 1, + }, + ]) + expect(firstLines(alerts.filter(({ kind }) => kind === 'library-failure'))).toEqual([ + { + accessoryUUID, + error: onEnd, + kind: 'library-failure', + level: 'error', + sensorUUID: table.sensorUUID, + sentence: `The library failed to wait on the end of the failed stream of ${tierName} it holds: Error: The wait on the end failed.`, + tierId: 1, + }, + ]) + expect(error).not.toHaveBeenCalled() + }) + + it('starts one fresh demand for a release and a raise while it waits for the end of a failed demand a viewer holds, logging no error, and ends that ' + + 'demand at its last release', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, keeper, stream, table } = await running() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + + // The keeper's first ask waits for the failed demand's end, and a release and a raise in one turn leave that wait stale behind a fresh one. + stream.fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + keeper.release('recording') + keeper.raise('recording') + await vi.advanceTimersByTimeAsync(0) + view.release() + await vi.advanceTimersByTimeAsync(0) + + expect([ + delegate.tierDemandStarted.mock.calls.length, + endsOf(delegate), + ]).toEqual([2, 1]) + + // The demand ends at the final release itself, read before any of the keeper's clocks could end a hold a stale wait left behind. + keeper.release('recording') + await vi.advanceTimersByTimeAsync(0) + + expect([ + delegate.tierDemandStarted.mock.calls.length, + endsOf(delegate), + error.mock.calls.length, + ]).toEqual([2, 2, 0]) + }) + + it('raises no alert for a tier a viewer alone holds, one the keeper released among them', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { alerts, delegate, keeper, stream, table } = await running() + + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + table.joinFrames(table.videoTiers.get(2)!, 'video', scriptedHolder(), keepingConsumer()) + await settle() + keeper.release('recording') + stream.write(fragmentAt(0.5)) + await vi.advanceTimersByTimeAsync(15000) + delegate.tierDemandStarted.mock.calls.find(([stream]) => stream.tier.id === 2)![0].fail('The camera went away.') + await vi.advanceTimersByTimeAsync(15000) + + expect(alerts).toEqual([]) + }) + + it('raises buffer-trimmed once an episode for its held tier, naming a prebuffer only where the tier has one, and none for a tier no keeper holds, one ' + + 'the keeper released among them', async () => { + fakeClock() + + // Writes a fragment each second from one time to another, a keyframe at the first alone: the buffer reaches back past its ceiling. + const runFor = async (stream: TierStream, from: number, to: number): Promise => { + for (let seconds = from; seconds <= to; seconds++) { + await vi.advanceTimersByTimeAsync(1000) + stream.write(fragmentAt(seconds, seconds === from)) + } + } + const sentences: string[][] = [] + + for (const prebuffer of [2000, 0]) { + const { alerts, stream } = await running(prebuffer) + + await runFor(stream, 1, 30) + sentences.push(alerts.map(({ kind, sentence }) => `${kind}: ${sentence}`)) + } + + const tier = `the video tier 1 of the video sensor "${TIERS.sensorUUID.toLowerCase()}"` + + expect(sentences).toEqual([ + [ + `buffer-trimmed: The camera buffer of ${tier} reached back more than its prebuffer and the 10-second keyframe allowance between the stream's ` + + 'keyframes: it dropped its oldest samples up to a later keyframe, or every sample without one, and holds less than its prebuffer.', + ], + [ + `buffer-trimmed: The camera buffer of ${tier} reached back more than the 10-second keyframe allowance between the stream's keyframes: it dropped ` + + 'its oldest samples up to a later keyframe, or every sample without one.', + ], + ]) + + // A tier a viewer alone holds, and the keeper's own tier once it is released while a viewer keeps it. + const { alerts, delegate, keeper, stream, table } = await running() + + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + table.joinFrames(table.videoTiers.get(2)!, 'video', scriptedHolder(), keepingConsumer()) + await settle() + keeper.release('recording') + + const viewed = delegate.tierDemandStarted.mock.calls.find(([stream]) => stream.tier.id === 2)![0] + + viewed.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + + for (let seconds = 1; seconds <= 30; seconds++) { + await vi.advanceTimersByTimeAsync(1000) + stream.write(fragmentAt(seconds, seconds === 1)) + viewed.write(fragmentAt(seconds, seconds === 1)) + } + + expect([alerts, table.videoTiers.get(1)!.buffer.samples, table.videoTiers.get(2)!.buffer.samples]).toEqual([[], [], []]) + }) + + it('keeps nothing a plugin writes after its own fail in its tier\'s buffer while a viewer still holds the failed demand, tells no place of it and raises ' + + 'no tier-resumed', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { alerts, buffer, stream, table } = await running() + const place = listeningPlace() + + buffer().takePlace(place) + table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + stream.write(fragmentAt(0.5)) + stream.fail('The camera went away.') + stream.write(fragmentAt(1, true)) + stream.write(fragmentAt(1.5)) + await vi.advanceTimersByTimeAsync(500) + + expect({ + alerts: kinds(alerts), + kept: kept(buffer()), + told: place.told, + }).toEqual({ + alerts: ['tier-failed'], + kept: [ + 'video 0', + 'audio 0', + 'video 0.5', + 'audio 0.5', + ], + told: ['video 0.5', 'audio 0.5'], + }) + }) + + it('empties no buffer a viewer reads at its failure or at a long gap, the buffer emptying as the demand leaves its tier', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const ends: [string, number, number][] = [] + + for (const end of ['failure', 'long gap'] as const) { + const { buffer, stream, table } = await running() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', scriptedHolder(), keepingConsumer()) + + if (end === 'failure') { + stream.fail('The camera went away.') + } + + await vi.advanceTimersByTimeAsync(10000) + + const before = buffer().samples.length + + view.release() + ends.push([end, before, buffer().samples.length]) + } + + expect(ends).toEqual([ + ['failure', 2, 0], + ['long gap', 2, 0], + ]) + }) + + it('treats a throw from its place\'s own call as its tier\'s failure, raising tier-failed once and asking again after its first wait', async () => { + fakeClock() + + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { accessoryUUID, alerts, delegate, stream, table } = await running() + + vi.spyOn(TierKeeper.prototype, 'taken').mockImplementationOnce(() => { + throw new Error('The keeper failed to read its clock.') + }) + stream.write(fragmentAt(0.5)) + await vi.advanceTimersByTimeAsync(999) + + expect([alerts, delegate.tierDemandStarted.mock.calls.length, error.mock.calls.length]).toEqual([ + [ + { + accessoryUUID, + kind: 'tier-failed', + level: 'warning', + sensorUUID: table.sensorUUID, + sentence: `The library's own reading of the camera buffer failed and ended its hold of the stream of ${name(table.sensorUUID)}, and the library ` + + 'asks for it again.', + tierId: 1, + }, + ], + 1, + 1, + ]) + + await vi.advanceTimersByTimeAsync(1) + + expect(delegate.tierDemandStarted).toHaveBeenCalledTimes(2) + }) + + describe('a source recovering', () => { + it('raises no stall and ends nothing at the long gap for a running tier whose source is recovering, and at 30 seconds tells its recording of the ' + + 'gap and ends the view on it, with one stream-failed problem and one tier-failed, and asks for it again', async () => { + fakeClock() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, delegate, gap, keeper, table } = await running() + const viewer = scriptedHolder() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', viewer, keepingConsumer()) + + viewer.tierFailed.mockImplementation(() => queueMicrotask(() => view.release())) + // The keeper is told and then the tier table, as the camera controller tells them. + keeper.sourceRecovering() + table.sourceRecovering() + await vi.advanceTimersByTimeAsync(29999) + + const waiting = [ + gap.mock.calls.length, + viewer.tierFailed.mock.calls.length, + endsOf(delegate), + ] + + await vi.advanceTimersByTimeAsync(1) + + const lapsed = [ + gap.mock.calls.length, + viewer.tierFailed.mock.calls.length, + endsOf(delegate), + ] + + await vi.advanceTimersByTimeAsync(1000) + + expect([ + waiting, + lapsed, + delegate.tierDemandStarted.mock.calls.length, + kinds(alerts), + warn.mock.calls.map(([line]) => line), + ]).toEqual([ + [0, 0, 0], + [1, 1, 1], + 2, + ['tier-failed'], + [ + `The library ended the stream of ${name(table.sensorUUID)} (no picture within 30 seconds of its source being stated reconnecting), and every ` + + 'session on the tier ends.', + ], + ]) + }) + + it('restores the stall two seconds and the long gap ten seconds after the next picture, which lands within the 30 seconds, and stretches nothing ' + + 'at a second recovering before it', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + // One tier hands over a picture five seconds into the wait, and the other is told it is recovering a second time then and hands over nothing. Each + // keeper is told and then its tier table, as the camera controller tells them. + const resumed = await running() + const repeated = await running() + const recovering = ({ keeper, table }: Rig): void => { + keeper.sourceRecovering() + table.sourceRecovering() + } + + recovering(resumed) + recovering(repeated) + await vi.advanceTimersByTimeAsync(5000) + resumed.stream.write(fragmentAt(1)) + recovering(repeated) + + // Each reading: the resumed tier's alerts, its gaps told and the repeated tier's, at 6.999, 7, 14.999, 15, 29.999 and 30 seconds. Each tier's + // demand ends as its gap is told, with the keeper's one tier-failed. + const readings: number[][] = [] + + for (const step of [1999, 1, 7999, 1, 14999, 1]) { + await vi.advanceTimersByTimeAsync(step) + readings.push([ + resumed.alerts.length, + resumed.gap.mock.calls.length, + repeated.gap.mock.calls.length, + ]) + } + + expect(readings).toEqual([ + [0, 0, 0], + [1, 0, 0], + [1, 0, 0], + [2, 1, 0], + [2, 1, 0], + [2, 1, 1], + ]) + expect([ + kinds(resumed.alerts), + kinds(repeated.alerts), + ]).toEqual([ + ['tier-stalled', 'tier-failed'], + ['tier-failed'], + ]) + }) + + it.each([ + { first: 'the keeper' }, + { first: 'the tier table' }, + ])('tells a held tier still silent 30 seconds after a reconnect told to $first first the same: the gap once, one stream-failed problem and one ' + + 'tier-failed, the view ended and the tier asked for again', async ({ first }) => { + fakeClock() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, delegate, gap, keeper, table } = await running() + const viewer = scriptedHolder() + const view = table.joinFrames(table.videoTiers.get(1)!, 'video', viewer, keepingConsumer()) + + viewer.tierFailed.mockImplementation(() => queueMicrotask(() => view.release())) + + // The tier table told first makes its demand's clock the earlier of the two due at 30 seconds, which the camera controller never does. + if (first === 'the keeper') { + keeper.sourceRecovering() + table.sourceRecovering() + } else { + table.sourceRecovering() + keeper.sourceRecovering() + } + + await vi.advanceTimersByTimeAsync(29999) + + const waiting = [ + kinds(alerts), + gap.mock.calls.length, + endsOf(delegate), + ] + + await vi.advanceTimersByTimeAsync(1001) + + expect({ + waiting, + alerts: kinds(alerts), + gaps: gap.mock.calls.length, + views: viewer.tierFailed.mock.calls.length, + ends: endsOf(delegate), + starts: delegate.tierDemandStarted.mock.calls.length, + warnings: warn.mock.calls.map(([line]) => line), + }).toEqual({ + waiting: [[], 0, 0], + alerts: ['tier-failed'], + gaps: 1, + views: 1, + ends: 1, + starts: 2, + warnings: [ + `The library ended the stream of ${name(table.sensorUUID)} (no picture within 30 seconds of its source being stated reconnecting), and every ` + + 'session on the tier ends.', + ], + }) + }) + + it('raises one tier-failed and asks again for a tier lost while its source is recovering, and still tells its recording of the gap at 30 ' + + 'seconds', async () => { + fakeClock() + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { alerts, delegate, gap, keeper, stream } = await running() + + keeper.sourceRecovering() + await vi.advanceTimersByTimeAsync(5000) + stream.fail('The camera went away.') + await vi.advanceTimersByTimeAsync(1000) + + const asked = delegate.tierDemandStarted.mock.calls.length + + await vi.advanceTimersByTimeAsync(23999) + + const waiting = gap.mock.calls.length + + await vi.advanceTimersByTimeAsync(1) + + expect([ + kinds(alerts), + asked, + waiting, + gap.mock.calls.length, + ]).toEqual([ + ['tier-failed'], + 2, + 0, + 1, + ]) + }) + + it('leaves a tier not yet running to its first sample\'s bound and a released keeper doing nothing, a clock moved before the release among it', + async () => { + fakeClock() + + // A raised keeper whose tier's start has settled and whose stream has handed over nothing. + const waiting = rig() + + waiting.keeper.raise('recording') + await settle() + waiting.keeper.sourceRecovering() + + // A released keeper, told it is recovering before its release and after it. + const released = await running() + + released.keeper.sourceRecovering() + released.keeper.release('recording') + released.keeper.sourceRecovering() + await vi.advanceTimersByTimeAsync(60000) + + expect([waiting, released].map(({ alerts, delegate, gap }) => [ + kinds(alerts), + gap.mock.calls.length, + delegate.tierDemandStarted.mock.calls.length, + ])).toEqual([ + [ + ['tier-failed'], + 0, + 2, + ], + [ + [], + 0, + 1, + ], + ]) + }, + ) + }) + }) +}) diff --git a/src/lib/camera/capabilities/setupEndpoints.spec.ts b/src/lib/camera/capabilities/setupEndpoints.spec.ts new file mode 100644 index 000000000..1c0fb89dc --- /dev/null +++ b/src/lib/camera/capabilities/setupEndpoints.spec.ts @@ -0,0 +1,175 @@ +import type { SetupEndpointsRequest, SetupEndpointsResponse } from './setupEndpoints.js' + +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { + buildSetupEndpointsTlv, + SETUP_ENDPOINTS_DISABLED_SUITE, + SETUP_ENDPOINTS_HUB_ANSWER, + SETUP_ENDPOINTS_HUB_REQUEST, + SETUP_ENDPOINTS_NARROW_PORTS, + SETUP_ENDPOINTS_WITHOUT_PORTS, +} from '../../../test-utils/cameraFixtures.js' +import { + decodeSetupEndpointsRequest, + decodeSetupEndpointsResponse, + encodeSetupEndpointsRequest, + encodeSetupEndpointsResponse, + SetupEndpointsStatus, + SRTPCryptoSuites, +} from './setupEndpoints.js' + +// The golden vectors are computed from the R15 tables by an independent TLV8 writer, every integer little-endian at its table width unless a vector says +// otherwise. The hub answer is the one the legacy stream management gives the hub request, which that management's spec asserts byte for byte. +const SESSION = 'a1b2c3d4-0000-4000-8000-0000000000b1' +const FIXTURE_SESSION = '11111111-1111-1111-1111-111111111111' + +// The fixture request, buildSetupEndpointsTlv's bytes: session 1111..., 127.0.0.1, ports 5000 and 5001, and a zero key and salt for each stream. +const FIXTURE_REQUEST = 'ARARERERERERERERERERERERAxYBAQACCTEyNy4wLjAuMQMCiBMEAokTBCUBAQACEAAAAAAAAAAAAAAAAAAAAAADDgAAAAAAAAAAAAAAAAAABSUBAQACEAAAAAAAAAAAAAAAAAAAAAADDgAA' + + 'AAAAAAAAAAAAAAAA' + +// The fixture request with its Video RTP port three bytes long. +const WIDE_PORT_REQUEST = 'ARARERERERERERERERERERERAxcBAQACCTEyNy4wLjAuMQMDiBMABAKJEwQlAQEAAhAAAAAAAAAAAAAAAAAAAAAAAw4AAAAAAAAAAAAAAAAAAAUlAQEAAhAAAAAAAAAAAAAAAAAAAAAAAw' + + '4AAAAAAAAAAAAAAAAAAA==' + +// The fixture request with its Session ID fifteen bytes long. +const SHORT_SESSION_REQUEST = 'AQ8REREREREREREREREREREDFgEBAAIJMTI3LjAuMC4xAwKIEwQCiRMEJQEBAAIQAAAAAAAAAAAAAAAAAAAAAAMOAAAAAAAAAAAAAAAAAAAFJQEBAAIQAAAAAAAAAAAAAAAAAAAAAA' + + 'MOAAAAAAAAAAAAAAAAAAA=' + +// The fixture request with no SRTP Master Key in its video parameters. +const MISSING_KEY_REQUEST = 'ARARERERERERERERERERERERAxYBAQACCTEyNy4wLjAuMQMCiBMEAokTBBMBAQADDgAAAAAAAAAAAAAAAAAABSUBAQACEAAAAAAAAAAAAAAAAAAAAAADDgAAAAAAAAAAAAAAAAAA' + +const ERROR_ANSWER = 'AgEC' +const BUSY_ANSWER = 'ARARERERERERERERERERERERAgEB' +const ERROR_ANSWER_WITH_SESSION = 'ARARERERERERERERERERERERAgEC' + +// The bytes from one value to another, inclusive. +function byteRange(first: number, last: number): Buffer { + return Buffer.from(Array.from({ length: last - first + 1 }, (_, index) => first + index)) +} + +const HUB_REQUEST: SetupEndpointsRequest = { + sessionIdentifier: SESSION, + controllerAddress: { + addressVersion: 'ipv4', + address: '192.0.2.19', + videoRTPPort: 50010, + audioRTPPort: 50012, + }, + videoSRTPParameters: { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: byteRange(0x01, 0x10), + masterSalt: byteRange(0x11, 0x1E), + }, + audioSRTPParameters: { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: byteRange(0x21, 0x30), + masterSalt: byteRange(0x31, 0x3E), + }, +} + +const HUB_ANSWER: SetupEndpointsResponse = { + status: SetupEndpointsStatus.SUCCESS, + sessionIdentifier: SESSION, + accessoryAddress: { + addressVersion: 'ipv4', + address: '192.0.2.130', + videoRTPPort: 51010, + audioRTPPort: 51012, + }, + videoSRTPParameters: { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: byteRange(0xA1, 0xB0), + masterSalt: byteRange(0xB1, 0xBE), + }, + audioSRTPParameters: { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: byteRange(0xC1, 0xD0), + masterSalt: byteRange(0xD1, 0xDE), + }, + videoSSRC: 0x0A0B0C0D, + audioSSRC: 0x0E0F1011, +} + +describe('setup endpoints', () => { + it('decodes a hub request into its model', () => { + expect(decodeSetupEndpointsRequest(SETUP_ENDPOINTS_HUB_REQUEST)).toEqual(HUB_REQUEST) + }) + + it('encodes a hub request back to its bytes', () => { + expect(encodeSetupEndpointsRequest(HUB_REQUEST)).toBe(SETUP_ENDPOINTS_HUB_REQUEST) + }) + + it('decodes and re-encodes the fixture request byte for byte', () => { + expect(buildSetupEndpointsTlv()).toBe(FIXTURE_REQUEST) + expect(encodeSetupEndpointsRequest(decodeSetupEndpointsRequest(FIXTURE_REQUEST))).toBe(FIXTURE_REQUEST) + }) + + it('reads one-byte ports and an ipv6 address', () => { + expect(decodeSetupEndpointsRequest(SETUP_ENDPOINTS_NARROW_PORTS).controllerAddress).toEqual({ + addressVersion: 'ipv6', + address: 'fe80::1', + videoRTPPort: 80, + audioRTPPort: 81, + }) + }) + + it('reads the disabled suite\'s absent and empty keys and salts as zero-length', () => { + const request = decodeSetupEndpointsRequest(SETUP_ENDPOINTS_DISABLED_SUITE) + const disabled = { + cryptoSuite: SRTPCryptoSuites.NONE, + masterKey: Buffer.alloc(0), + masterSalt: Buffer.alloc(0), + } + + expect(request).toEqual({ + sessionIdentifier: '44444444-4444-4444-4444-444444444444', + controllerAddress: { + addressVersion: 'ipv4', + address: '10.0.0.2', + videoRTPPort: 6000, + audioRTPPort: 6002, + }, + videoSRTPParameters: disabled, + audioSRTPParameters: disabled, + }) + }) + + it('refuses a port wider than its format, naming the field', () => { + expect(() => decodeSetupEndpointsRequest(WIDE_PORT_REQUEST)).toThrow(RangeError) + expect(() => decodeSetupEndpointsRequest(WIDE_PORT_REQUEST)).toThrow('The Video RTP port field is 3 bytes long, but its format takes at most 2 bytes.') + }) + + it('refuses a session identifier shorter than sixteen bytes, naming the field', () => { + expect(() => decodeSetupEndpointsRequest(SHORT_SESSION_REQUEST)).toThrow(RangeError) + expect(() => decodeSetupEndpointsRequest(SHORT_SESSION_REQUEST)).toThrow('The Session ID field is 15 bytes long, but its format takes 16 bytes.') + }) + + it('refuses a request without its ports, naming the field', () => { + expect(() => decodeSetupEndpointsRequest(SETUP_ENDPOINTS_WITHOUT_PORTS)).toThrow(TypeError) + expect(() => decodeSetupEndpointsRequest(SETUP_ENDPOINTS_WITHOUT_PORTS)).toThrow('The Video RTP port field is missing.') + }) + + it('refuses a request without a master key under a suite that needs one, naming the field', () => { + expect(() => decodeSetupEndpointsRequest(MISSING_KEY_REQUEST)).toThrow(TypeError) + expect(() => decodeSetupEndpointsRequest(MISSING_KEY_REQUEST)).toThrow('The SRTP Master Key field is missing.') + }) + + it('encodes and decodes a hub answer', () => { + expect(encodeSetupEndpointsResponse(HUB_ANSWER)).toBe(SETUP_ENDPOINTS_HUB_ANSWER) + expect(decodeSetupEndpointsResponse(SETUP_ENDPOINTS_HUB_ANSWER)).toEqual(HUB_ANSWER) + }) + + it('encodes an error without a session, and a busy and an error with one', () => { + expect(encodeSetupEndpointsResponse({ status: SetupEndpointsStatus.ERROR })).toBe(ERROR_ANSWER) + expect(encodeSetupEndpointsResponse({ status: SetupEndpointsStatus.BUSY, sessionIdentifier: FIXTURE_SESSION })).toBe(BUSY_ANSWER) + expect(encodeSetupEndpointsResponse({ status: SetupEndpointsStatus.ERROR, sessionIdentifier: FIXTURE_SESSION })).toBe(ERROR_ANSWER_WITH_SESSION) + }) + + it('refuses a status outside its values, naming the field', () => { + expect(() => decodeSetupEndpointsResponse('AgED')).toThrow(RangeError) + expect(() => decodeSetupEndpointsResponse('AgED')).toThrow('The Status field holds 3, which is not one of its values.') + }) +}) diff --git a/src/lib/camera/index.ts b/src/lib/camera/index.ts index 64e2f4eb6..6396be9ae 100644 --- a/src/lib/camera/index.ts +++ b/src/lib/camera/index.ts @@ -9,6 +9,7 @@ export * from './RTPStreamManagement.js' export type { CameraAudioTier, CameraKeyframe, + CameraSnapshotRequest, CameraVideoSensor, CameraVideoTier, MultiTierStreamingDelegate, diff --git a/src/lib/camera/recording/BufferRecorder.spec.ts b/src/lib/camera/recording/BufferRecorder.spec.ts new file mode 100644 index 000000000..97f30c88c --- /dev/null +++ b/src/lib/camera/recording/BufferRecorder.spec.ts @@ -0,0 +1,2114 @@ +import type { FrameOptions, ScriptedTierDelegate } from '../../../test-utils/cameraFixtures.js' +import type { SampleFixture } from '../../../test-utils/mp4Fixtures.js' +import type { CameraBufferRecordingOptions, CameraControllerServiceMap, CameraRecordingEnd, CameraRecordingStart } from '../../controller/index.js' +import type { AccessoryInformation } from '../../definitions/index.js' +import type { TierBuffer } from '../buffer/CameraBuffer.js' +import type { CameraProblem } from '../diagnostics/problems.js' +import type { Mp4Sample } from '../mp4/mp4Boxes.js' +import type { RecordingPacket } from '../RecordingManagement.js' +import type { CameraAudioTier, TierStream } from '../StreamingOptions.js' +import type { TierTable } from '../TierTable.js' +import type { BufferRecorder } from './BufferRecorder.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + bufferCamera, + endsOf, + FIRST_VIDEO_SENSOR, + FRAME_TICKS, + frames, + handPublishedContext, + SOUND_TICKS, + streamsOf, + UNREAD_SOUND, +} from '../../../test-utils/cameraFixtures.js' +import { DataStreamClient } from '../../../test-utils/dataStreamClient.js' +import { captureDebugEvents } from '../../../test-utils/engineDebug.js' +import { + sampleFragment, + soundSample, + TIER_STREAM_PARAMETER_SETS, + TIER_STREAM_PICTURE, + TIER_STREAM_SOUND, + tierPicture, + tierStreamFragment, + tierStreamInitialization, +} from '../../../test-utils/mp4Fixtures.js' +import { problemsOf } from '../../../test-utils/reporterFixtures.js' +import { settle } from '../../../test-utils/settle.js' +import { Characteristic } from '../../Characteristic.js' +import { CameraController } from '../../controller/index.js' +import { HDSProtocolError, HDSProtocolSpecificErrorReason, HDSStatus, Protocols, Topics } from '../../datastream/index.js' +import { Service } from '../../Service.js' +import * as uuid from '../../util/uuid.js' +import { readTrackBoxEntryBytes, readTrackBoxes, readTrackBoxParameterSets, readTrackSamples, walkBoxes } from '../mp4/mp4Boxes.js' + +// The recorded sensor as the camera names it. +const SENSOR_UUID = FIRST_VIDEO_SENSOR.uuid.toLowerCase() + +interface Rig { + readonly camera: CameraController + readonly delegate: ScriptedTierDelegate + readonly recorder: BufferRecorder + // The camera's services, as its construction answered them. + readonly services: CameraControllerServiceMap + // The camera's accessory, its own among the row's cameras, and the problems heard on its channel. + readonly accessoryUUID: string + readonly alerts: CameraProblem[] + readonly starts: CameraRecordingStart[] + readonly ends: CameraRecordingEnd[] + // Writes Recording Active, which with HomeKit Camera Active on decides whether recording is allowed. + allow: (allowed: boolean) => void + // The stream the latest demand handed out, and the recorded tier's buffer, read through the sensor's tier table while the camera has one. + stream: () => TierStream + buffer: () => TierBuffer | undefined +} + +interface Reading { + readonly packets: RecordingPacket[] + done: boolean +} + +// One segment as the box readers read it back: each track's samples with their decode times. +interface ReadSegment { + readonly video: Mp4Sample[] + readonly audio: Mp4Sample[] +} + +// Every camera a row made, removed after it. No hold, clock or recording outlives its row. +const cameras: CameraController[] = [] + +afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + + vi.restoreAllMocks() + vi.useRealTimers() +}) + +// The fixture's two-sensor camera with the camera capabilities block, recording its first video sensor's best tier from its camera buffer with the +// prebuffer and the shouldRecord given, that sensor's audio stating the source given or none, its streaming delegate a script, configured, handed a +// published context of an accessory of its own, whose problems it reads, and its recording allowed unless the row says otherwise. +function rig({ allowed = true, audio = true, prebuffer = 0, shouldRecord, source }: { + allowed?: boolean + audio?: boolean + prebuffer?: number + shouldRecord?: CameraBufferRecordingOptions['shouldRecord'] + source?: CameraAudioTier['source'] +} = {}): Rig { + const { delegate, options, stream } = bufferCamera({ prebuffer, shouldRecord }) + const [recordedSensor] = options.cameraCapabilities.videoSensors + + recordedSensor.audio = { ...recordedSensor.audio, source } + + const camera = new CameraController(options) + const accessoryUUID = uuid.generate(`buffer recorder spec camera ${cameras.length}`) + const { problems: alerts } = problemsOf(accessoryUUID) + const starts: CameraRecordingStart[] = [] + const ends: CameraRecordingEnd[] = [] + + cameras.push(camera) + + const services = camera.constructServices() + + camera.configureServices() + handPublishedContext(camera, undefined, accessoryUUID) + camera.on('recording-started', start => starts.push(start)) + camera.on('recording-ended', end => ends.push(end)) + + const management = camera.recordingManagement! + // A plugin's update of Active, which the policy reads at once. + const allow = (value: boolean): void => { + management.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(value + ? Characteristic.Active.ACTIVE + : Characteristic.Active.INACTIVE) + } + + management.recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive).updateValue(audio) + + if (allowed) { + allow(true) + } + + return { + accessoryUUID, + alerts, + allow, + // @ts-expect-error: private access + buffer: () => (management.delegate as BufferRecorder).options.tierTable(SENSOR_UUID)?.videoTiers.get(1)?.buffer, + camera, + delegate, + ends, + recorder: management.delegate as BufferRecorder, + services, + starts, + stream, + } +} + +// Starts a stream with its initialization segment. +function initialize(stream: TierStream, options: { parameterSets?: readonly Buffer[], sound?: boolean } = {}): void { + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS, ...options })) +} + +// A rig as the options given make it, whose recorded tier's buffer is ready, its stream started and a second and a half of its frames written. +function ready(options: Parameters[0] = {}): Rig { + const made = rig(options) + + initialize(made.stream()) + frames(made.stream(), 0, 45) + + return made +} + +// A hub's recording open of the stream given, its request ID answered. +function openRecording(client: DataStreamClient, streamId: number): number { + return client.request(Protocols.DATA_SEND, Topics.OPEN, { + reason: 'motion', + streamId, + target: 'controller', + type: 'ipcamera.recording', + }) +} + +// The initialization segment a stream starts with, one track's timescale restated: the field after the two times of its media header, which the fixture +// writes at 32 bits each. +function retimed(handler: 'soun' | 'vide', timescale: number): Buffer { + const data = tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS }) + const moov = walkBoxes(data).boxes.find(({ type }) => type === 'moov')! + const { trak } = readTrackBoxes(data, moov).find(({ track }) => track.handler === handler)! + const mdia = walkBoxes(data, trak.payload, trak.end).boxes.find(({ type }) => type === 'mdia')! + const mdhd = walkBoxes(data, mdia.payload, mdia.end).boxes.find(({ type }) => type === 'mdhd')! + + data.writeUInt32BE(timescale, mdhd.payload + 12) + + return data +} + +// The initialization segment a stream starts with, its picture's size restated and its hvcC kept: the width and height of its visual sample entry, which +// stand 24 octets into the entry's fields, after its header. +function resized(width: number, height: number): Buffer { + const data = tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS }) + const moov = walkBoxes(data).boxes.find(({ type }) => type === 'moov')! + const entry = readTrackBoxEntryBytes(data, readTrackBoxes(data, moov).find(({ track }) => track.handler === 'vide')!)! + + entry.writeUInt16BE(width, 8 + 24) + entry.writeUInt16BE(height, 8 + 26) + + return data +} + +// Reads a recording's packets as they come, in the background, until it ends. +function read(recording: AsyncIterable): Reading { + const reading: Reading = { done: false, packets: [] } + + void (async () => { + for await (const packet of recording) { + reading.packets.push(packet) + } + + reading.done = true + })() + + return reading +} + +// A segment's samples of each track, read back by the library's box readers. +function segmentOf(data: Buffer): ReadSegment { + const moof = walkBoxes(data).boxes.find(({ type }) => type === 'moof')! + + return { + audio: readTrackSamples(data, moof, { limit: 4096, trackId: 2 }).samples, + video: readTrackSamples(data, moof, { limit: 4096, trackId: 1 }).samples, + } +} + +// The media segments of a recording's packets: each packet after the initialization segment that is not the end marker. +function segmentsOf(reading: Reading): ReadSegment[] { + return reading.packets.slice(1).filter(({ data }) => data.length > 1).map(({ data }) => segmentOf(data)) +} + +// The end marker: one zero octet marked last. +const MARKER: RecordingPacket = { + data: Buffer.alloc(1), + isLast: true, +} + +// The recorder's refusal of an open, the one it gives whatever it declined the open for. +const REFUSED = { + admitted: false, + reason: HDSProtocolSpecificErrorReason.BUSY, +} + +// The error a call throws, or undefined for a call that returns. +function thrownBy(call: () => unknown): unknown { + try { + call() + } catch (error) { + return error + } + + return undefined +} + +describe('bufferRecorder', () => { + describe('an open', () => { + it('refuses as busy an open on an empty buffer, a part-filled one and a tier that carries its parameter sets nowhere, each with one alert, the last ' + + 'after its tier\'s stream fault, and serves one on a ready buffer', async () => { + const filling = rig({ prebuffer: 2000 }) + const empty = filling.recorder.admit(1) + + initialize(filling.stream()) + frames(filling.stream(), 0, 45) + + const partFilled = filling.recorder.admit(2) + const bare = rig() + + initialize(bare.stream(), { parameterSets: [] }) + frames(bare.stream(), 0, 45) + + const nowhere = bare.recorder.admit(3) + + await settle() + + expect([empty, partFilled, nowhere]).toEqual([REFUSED, REFUSED, REFUSED]) + + // An acknowledgement or a close naming a refused open's stream tells of nothing. + for (const [{ recorder }, streamId] of [ + [filling, 1], + [filling, 2], + [bare, 3], + ] as const) { + recorder.acknowledgeStream(streamId) + recorder.closeRecordingStream(streamId, HDSProtocolSpecificErrorReason.NORMAL) + recorder.closeRecordingStream(streamId, HDSProtocolSpecificErrorReason.CANCELLED) + } + + const tierName = `the video tier 1 of the video sensor "${FIRST_VIDEO_SENSOR.uuid.toLowerCase()}"` + + expect([ + ...filling.alerts, + ...bare.alerts, + ].map(({ kind, sentence, tierId }: Partial>) => ({ kind, sentence, tierId }))).toEqual([ + { + kind: 'recording-declined', + sentence: `The library declined a hub's recording of ${tierName}, because its camera buffer does not yet hold the prebuffer of 2000 milliseconds.`, + tierId: 1, + }, + { + kind: 'recording-declined', + sentence: `The library declined a hub's recording of ${tierName}, because its camera buffer does not yet hold the prebuffer of 2000 milliseconds.`, + tierId: 1, + }, + { + kind: 'stream-fault', + sentence: `The stream of ${tierName} carries a keyframe without its video, sequence and picture parameter sets, in its sample or its ` + + 'initialization segment, which a viewer needs to decode it, and the keyframe is sent as it stands.', + tierId: 1, + }, + { + kind: 'recording-declined', + sentence: `The library declined a hub's recording of ${tierName}, because its stream carries a keyframe without its video, sequence and picture ` + + 'parameter sets, in its sample or its initialization segment.', + tierId: 1, + }, + ]) + expect([ + filling.starts, + filling.ends, + bare.starts, + bare.ends, + ]).toEqual([[], [], [], []]) + + // The part-filled buffer holds its prebuffer once its newest picture stands two seconds past its first keyframe. + frames(filling.stream(), 45, 61) + + const served = read(filling.recorder.handleRecordingStreamRequest(4)) + + await settle() + + expect(served.packets.length).toBeGreaterThan(0) + expect(served.packets[0].isLast).toBe(false) + expect(filling.starts).toEqual([ + { + sensorUUID: FIRST_VIDEO_SENSOR.uuid.toLowerCase(), + streamId: 4, + tierId: 1, + }, + ]) + }) + + it('names a prebuffer of one millisecond in the singular in the alert of an open it refuses on an empty buffer', async () => { + const filling = rig({ prebuffer: 1 }) + + expect(filling.recorder.admit(1)).toEqual(REFUSED) + + await settle() + + expect(filling.alerts.map(({ kind, sentence }: Partial>) => ({ kind, sentence }))).toEqual([ + { + kind: 'recording-declined', + sentence: `The library declined a hub's recording of the video tier 1 of the video sensor "${FIRST_VIDEO_SENSOR.uuid.toLowerCase()}", because its ` + + 'camera buffer does not yet hold the prebuffer of 1 millisecond.', + }, + ]) + }) + + it('refuses as busy an open on a tier whose description holds the sequence and picture parameter sets alone and whose keyframes carry none, with one ' + + 'alert naming a keyframe without its parameter sets, after its tier\'s stream fault', async () => { + const partial = rig() + const [, ...described] = TIER_STREAM_PARAMETER_SETS + + initialize(partial.stream(), { parameterSets: described }) + frames(partial.stream(), 0, 45) + + const refused = partial.recorder.admit(1) + + await settle() + + expect(refused).toEqual(REFUSED) + expect(partial.alerts.map(({ kind, sentence, tierId }: Partial>) => ({ kind, sentence, tierId }))).toEqual([ + { + kind: 'stream-fault', + sentence: `The stream of the video tier 1 of the video sensor "${SENSOR_UUID}" carries a keyframe without its video, sequence and picture ` + + 'parameter sets, in its sample or its initialization segment, which a viewer needs to decode it, and the keyframe is sent as it stands.', + tierId: 1, + }, + { + kind: 'recording-declined', + sentence: `The library declined a hub's recording of the video tier 1 of the video sensor "${SENSOR_UUID}", because its stream carries a keyframe ` + + 'without its video, sequence and picture parameter sets, in its sample or its initialization segment.', + tierId: 1, + }, + ]) + expect([partial.starts, partial.ends]).toEqual([[], []]) + }) + + it('refuses as busy an open of a camera out of service, raising no alert and telling of no recording, though its buffer filled while it was in ' + + 'service', async () => { + const out = rig() + + initialize(out.stream()) + frames(out.stream(), 0, 45) + + // The camera's accessory is unpublished, and its context reads not published. + out.camera.handleAccessoryContext({ + accessoryInformation: new Service.AccessoryInformation() as AccessoryInformation, + accessoryUUID: out.accessoryUUID, + published: false, + username: undefined, + }) + + const refused = out.recorder.admit(1) + + await settle() + + expect(refused).toEqual(REFUSED) + expect([ + out.alerts, + out.starts, + out.ends, + ]).toEqual([[], [], []]) + }) + + describe('its shouldRecord', () => { + // The recorded tier as the recorder's sentences name it. + const TIER = `the video tier 1 of the video sensor "${SENSOR_UUID}"` + + // A camera whose shouldRecord is the one given, its recorded tier's buffer ready. + function asking(shouldRecord: CameraBufferRecordingOptions['shouldRecord']): Rig { + return ready({ shouldRecord }) + } + + // Opens a recording of each stream given and closes it at once. The next open finds none open. + function openEach(asked: Rig, streamIds: readonly number[]): void { + for (const streamId of streamIds) { + read(asked.recorder.handleRecordingStreamRequest(streamId)) + asked.recorder.closeRecordingStream(streamId, HDSProtocolSpecificErrorReason.NORMAL) + } + } + + // The first line of each error logged, a failure's stack left out. + function errorLines(error: { mock: { calls: unknown[][] } }): string[] { + return error.mock.calls.map(([line]) => String(line).split('\n')[0]) + } + + // Each problem the camera reported, its sentence's first line alone, a failure's stack left out. + function firstLines(problems: readonly CameraProblem[]): CameraProblem[] { + return problems.map(problem => ({ ...problem, sentence: problem.sentence.split('\n')[0] })) + } + + it('refuses as busy an open it answers false, raising no alert and telling of no recording, and serves one it answers true, handed what ' + + 'recording-started then carries', async () => { + const answers = [false, true] + const shouldRecord = vi.fn<(start: CameraRecordingStart) => boolean>(() => answers.shift()!) + const asked = asking(shouldRecord) + const refused = asked.recorder.admit(1) + const served = read(asked.recorder.handleRecordingStreamRequest(2)) + + await settle() + + expect(refused).toEqual(REFUSED) + expect(served.packets[0].isLast).toBe(false) + expect(asked.alerts).toEqual([]) + expect(asked.starts).toEqual([ + { + sensorUUID: SENSOR_UUID, + streamId: 2, + tierId: 1, + }, + ]) + expect(asked.ends).toEqual([]) + expect(shouldRecord.mock.calls).toEqual([ + [ + { + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ], + [asked.starts[0]], + ]) + }) + + it('records an open it answers with neither true nor false, undefined, a string and a promise resolved or rejected alike, reporting that answer ' + + 'once and a rejection once it settles', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const failure = new Error('The plugin\'s answer failed.') + const answers: (() => unknown)[] = [ + () => undefined, + () => 'no', + async () => false, + async () => { + throw failure + }, + ] + const asked = asking(() => answers.shift()!() as boolean) + + openEach(asked, [1, 2, 3, 4]) + await settle() + + expect(asked.starts.map(({ streamId }) => streamId)).toEqual([1, 2, 3, 4]) + expect(errorLines(error)).toEqual([]) + expect(firstLines(asked.alerts)).toEqual([ + { + accessoryUUID: asked.accessoryUUID, + kind: 'plugin-failure', + level: 'error', + sensorUUID: SENSOR_UUID, + sentence: `The shouldRecord function answered a recording of ${TIER} with neither true nor false, and the library records it.`, + tierId: 1, + }, + { + accessoryUUID: asked.accessoryUUID, + error: failure, + kind: 'plugin-failure', + level: 'error', + sensorUUID: SENSOR_UUID, + sentence: `The shouldRecord function failed for a recording of ${TIER}, and the library records it: Error: The plugin's answer failed.`, + tierId: 1, + }, + ]) + }) + + it('records an open whose answer throws, reporting the throw at each open', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const failure = new Error('The plugin\'s shouldRecord failed.') + const asked = asking(() => { + throw failure + }) + const reported = { + accessoryUUID: asked.accessoryUUID, + error: failure, + kind: 'plugin-failure', + level: 'error', + sensorUUID: SENSOR_UUID, + sentence: `The shouldRecord function failed for a recording of ${TIER}, and the library records it: Error: The plugin's shouldRecord failed.`, + tierId: 1, + } + + openEach(asked, [1, 2]) + await settle() + + expect(asked.starts.map(({ streamId }) => streamId)).toEqual([1, 2]) + expect(firstLines(asked.alerts)).toEqual([reported, reported]) + expect(error).not.toHaveBeenCalled() + }) + + // The recordings' places the recorded tier's buffer holds, each carrying its stream ID, read before an open and as its admission returns, since a + // recording takes its place in its serving turn, and the camera leaving service gives up places of its own. A row reads only a place that stands + // after the open and not before it. A camera removed holds no buffer, which means it holds no place. + function placesOf(asked: Rig): () => readonly unknown[] { + // @ts-expect-error: private access + return () => (asked.buffer()?.places as object[] | undefined ?? []).filter(place => 'streamId' in place) + } + + // An open of stream 1 asked of a camera whose shouldRecord runs the call given and answers true, read as its admission, the places it took and how + // many times the plugin was asked. + function askedThrough(call: (asked: Rig) => void): { asked: Rig, admission: unknown, called: number, taken: readonly unknown[] } { + const shouldRecord = vi.fn<(start: CameraRecordingStart) => boolean>() + const asked = asking(shouldRecord) + const places = placesOf(asked) + const before = places() + + shouldRecord.mockImplementation(() => { + call(asked) + + return true + }) + + const admission = asked.recorder.admit(1) + const taken = places().filter(place => !before.includes(place)) + + return { + admission, + asked, + called: shouldRecord.mock.calls.length, + taken, + } + } + + it.each([ + { + leave: (asked: Rig): void => asked.camera.updateSourceState('away'), + leaving: 'states the camera\'s source away', + }, + { + leave: (asked: Rig): void => asked.camera.handleAccessoryContext({ + accessoryInformation: new Service.AccessoryInformation() as AccessoryInformation, + accessoryUUID: asked.accessoryUUID, + published: false, + username: undefined, + }), + leaving: 'unpublishes the camera\'s accessory', + }, + ])('refuses as busy an open whose shouldRecord $leaving and answers true, raising no alert, telling of no recording and taking no place on its tier', + async ({ leave }) => { + const { admission, asked, called, taken } = askedThrough(leave) + + await settle() + + expect(called).toBe(1) + expect(taken).toEqual([]) + expect(admission).toEqual(REFUSED) + expect([ + asked.alerts, + asked.starts, + asked.ends, + ]).toEqual([[], [], []]) + }) + + it('refuses as busy an open whose shouldRecord states the camera\'s source away and then available and answers true, telling of no recording, taking ' + + 'no place on its tier and raising the recorded tier again', async () => { + // How many demands of the recorded tier the call's leave and return raised. + const raisedAgain: number[] = [] + const { admission, asked, taken } = askedThrough(({ camera, delegate }) => { + const raised = streamsOf(delegate, 1).length + + camera.updateSourceState('away') + camera.updateSourceState('available') + raisedAgain.push(streamsOf(delegate, 1).length - raised) + }) + + await settle() + + expect(admission).toEqual(REFUSED) + expect(taken).toEqual([]) + expect([asked.starts, asked.ends]).toEqual([[], []]) + expect(raisedAgain).toEqual([1]) + }) + + it('refuses as busy an open whose shouldRecord turns recording off and answers true, telling of no recording and taking no place on its tier', + async () => { + const { admission, asked, taken } = askedThrough(turned => turned.allow(false)) + + await settle() + + expect(admission).toEqual(REFUSED) + expect(taken).toEqual([]) + expect([asked.starts, asked.ends]).toEqual([[], []]) + }) + + it.each([ + { call: 'handleFactoryReset' as const }, + { call: 'handleControllerRemoved' as const }, + ])('refuses as busy an open whose shouldRecord calls the camera\'s $call and answers true, telling of no recording', async ({ call }) => { + const { admission, asked } = askedThrough(reset => reset.camera[call]()) + + await settle() + + expect(admission).toEqual(REFUSED) + expect([asked.starts, asked.ends]).toEqual([[], []]) + }) + + it('admits and serves an open after the recorder stopped outside any call, its source stated away and then available', async () => { + const asked = asking(() => true) + + asked.camera.updateSourceState('away') + asked.camera.updateSourceState('available') + initialize(asked.stream()) + frames(asked.stream(), 0, 45) + + const admission = asked.recorder.admit(1) + + expect(admission).toEqual({ + admitted: true, + serve: expect.any(Function), + }) + + const served = read((admission as { serve: () => AsyncIterable }).serve()) + + await settle() + + expect(served.packets[0].isLast).toBe(false) + expect(asked.starts).toEqual([ + { + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + }) + + it('publishes one debug event naming its stream and its cause for each open it refuses, out of service, on a buffer not ready, answered false and ' + + 'stopped during its shouldRecord, and none for an open it admits', async () => { + const events = captureDebugEvents('HAP-NodeJS:Camera:BufferRecorder') + const away = rig() + const filling = rig({ prebuffer: 2000 }) + const declining = asking(() => false) + const { asked: stopped } = askedThrough(leaving => leaving.camera.updateSourceState('away')) + const admitting = asking(() => true) + + away.camera.updateSourceState('away') + away.recorder.admit(2) + filling.recorder.admit(3) + declining.recorder.admit(4) + admitting.recorder.admit(5) + + expect(events).toEqual([ + { + accessoryUUID: stopped.accessoryUUID, + cause: 'the recorder stopped during the plugin\'s shouldRecord', + kind: 'recording-refused', + sentence: 'Refusing the recording of stream 1 as busy: the recorder stopped during the plugin\'s shouldRecord.', + streamId: 1, + }, + { + accessoryUUID: away.accessoryUUID, + cause: 'the camera is out of service', + kind: 'recording-refused', + sentence: 'Refusing the recording of stream 2 as busy: the camera is out of service.', + streamId: 2, + }, + { + accessoryUUID: filling.accessoryUUID, + cause: 'the camera buffer is not ready', + kind: 'recording-refused', + sentence: 'Refusing the recording of stream 3 as busy: the camera buffer is not ready.', + streamId: 3, + }, + { + accessoryUUID: declining.accessoryUUID, + cause: 'the plugin\'s shouldRecord declined it', + kind: 'recording-refused', + sentence: 'Refusing the recording of stream 4 as busy: the plugin\'s shouldRecord declined it.', + streamId: 4, + }, + ]) + }) + + it('is asked nothing for an open of a camera out of service or on a buffer not ready, and once for an open of one in service on a ready buffer', + async () => { + const shouldRecord = vi.fn(() => true) + const away = asking(shouldRecord) + const filling = rig({ prebuffer: 2000, shouldRecord }) + const ready = asking(shouldRecord) + + away.camera.updateSourceState('away') + + const refusals = [ + away.recorder.admit(1), + filling.recorder.admit(2), + ] + + await settle() + + expect(refusals).toEqual([REFUSED, REFUSED]) + expect(shouldRecord).not.toHaveBeenCalled() + expect([away.starts, filling.starts]).toEqual([[], []]) + + ready.recorder.handleRecordingStreamRequest(3) + + expect(shouldRecord.mock.calls).toEqual([ + [ready.starts[0]], + ]) + }) + }) + + it.each([ + { + declined: 'its source stated away', + made: (): Rig => { + const away = ready() + + away.camera.updateSourceState('away') + + return away + }, + problems: [], + }, + { + declined: 'its buffer short of the prebuffer', + made: (): Rig => rig({ prebuffer: 2000 }), + problems: ['recording-declined'], + }, + { + declined: 'its shouldRecord answering false', + made: (): Rig => ready({ + shouldRecord: () => false, + }), + problems: [], + }, + ])('refuses a recording it declines, $declined, in the answer to the hub\'s open as busy, sending no data, holding no stream and telling of no ' + + 'recording', async ({ made, problems }) => { + const { alerts, camera, ends, starts } = made() + const client = await DataStreamClient.connect(camera.recordingManagement!.dataStreamManagement) + const id = openRecording(client, 1) + + await settle() + + expect(client.answerTo(id)).toEqual({ + header: { + id, + protocol: Protocols.DATA_SEND, + response: Topics.OPEN, + status: HDSStatus.PROTOCOL_SPECIFIC_ERROR, + }, + message: { status: HDSProtocolSpecificErrorReason.BUSY }, + }) + // @ts-expect-error: private access + expect(camera.recordingManagement!.recordingStream).toBeUndefined() + expect(client.events(Protocols.DATA_SEND, Topics.DATA)).toEqual([]) + expect(alerts.map(({ kind }) => kind)).toEqual(problems) + expect([starts, ends]).toEqual([[], []]) + }) + + it('throws a busy refusal from handleRecordingStreamRequest for an open it refuses, telling of no recording, and answers the packets of an open it ' + + 'admits, its initialization segment first', async () => { + const away = ready() + const admitted = ready() + + away.camera.updateSourceState('away') + + const thrown = thrownBy(() => away.recorder.handleRecordingStreamRequest(1)) + const served = read(admitted.recorder.handleRecordingStreamRequest(2)) + + await settle() + + expect(thrown).toBeInstanceOf(HDSProtocolError) + expect((thrown as HDSProtocolError).reason).toBe(HDSProtocolSpecificErrorReason.BUSY) + expect([away.starts, away.ends]).toEqual([[], []]) + expect(served.packets[0].isLast).toBe(false) + expect(walkBoxes(served.packets[0].data).boxes.map(({ type }) => type)).toContain('moov') + expect(admitted.starts).toEqual([ + { + sensorUUID: SENSOR_UUID, + streamId: 2, + tierId: 1, + }, + ]) + }) + + it('tells of no recording and takes no place for an open it admits whose answer finds its connection closing, and admits and serves the next open', + async () => { + const admitted = ready() + // @ts-expect-error: private access + const places = (): readonly unknown[] => admitted.buffer()!.places + const before = places() + const { dataStreamManagement } = admitted.camera.recordingManagement! + const client = await DataStreamClient.connect(dataStreamManagement) + const other = await DataStreamClient.connect(dataStreamManagement) + + dataStreamManagement.onEventMessage('test', 'shut', connection => connection.close()) + client.send(client.eventFrame('test', 'shut'), client.requestFrame(Protocols.DATA_SEND, Topics.OPEN, { + reason: 'motion', + streamId: 1, + target: 'controller', + type: 'ipcamera.recording', + })) + await settle() + + expect(admitted.starts).toEqual([]) + expect(places().filter(place => !before.includes(place))).toEqual([]) + + const id = openRecording(other, 2) + + await settle() + + expect(other.answerTo(id)?.header.status).toBe(HDSStatus.SUCCESS) + expect(admitted.starts.map(({ streamId }) => streamId)).toEqual([2]) + + other.closeSocket() + await settle() + }) + + it('writes the parameter sets of the recording\'s first keyframe into its initialization segment for a stream whose header holds none', async () => { + const opened = rig() + const { recorder } = opened + const stream = opened.stream() + + initialize(stream, { parameterSets: [] }) + frames(stream, 0, 10, { inBand: true }) + + const reading = read(recorder.handleRecordingStreamRequest(1)) + + await settle() + + const [initialization] = reading.packets + const moov = walkBoxes(initialization.data).boxes.find(({ type }) => type === 'moov')! + const [video] = readTrackBoxes(initialization.data, moov) + + expect(readTrackBoxParameterSets(initialization.data, video, { lengthSize: 4, limit: 16384 })?.units).toEqual(TIER_STREAM_PARAMETER_SETS) + }) + }) + + describe('its segments', () => { + it('cuts at the first keyframe 4 seconds from each opening, the segments held whole leaving at the open and each later one at the end of the fragment ' + + 'holding its closing keyframe, with the sound timed inside it that arrives after that keyframe', async () => { + const opened = rig({ prebuffer: 5000 }) + const { recorder } = opened + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 166, { lag: true }) + + const reading = read(recorder.handleRecordingStreamRequest(1)) + + await settle() + + expect(segmentsOf(reading).length).toBe(1) + + frames(stream, 166, 240, { lag: true }) + await settle() + + expect(segmentsOf(reading).length).toBe(1) + + frames(stream, 240, 241, { lag: true }) + await settle() + + const segments = segmentsOf(reading) + + expect(segments.map(({ audio, video }) => ({ + sounds: audio.length, + soundTime: audio[0].decodeTime, + syncs: video.flatMap(({ sync }, index) => sync + ? [index] + : []), + times: [video[0].decodeTime, video.at(-1)!.decodeTime], + }))).toEqual([ + { + sounds: 200, + soundTime: 0n, + syncs: [0, 30, 60, 90], + times: [0n, 119n * 3000n], + }, + { + sounds: 200, + soundTime: 4n * 48000n, + syncs: [0, 30, 60, 90], + times: [120n * 3000n, 239n * 3000n], + }, + ]) + }) + + it('records the sound a stream delivers ahead of a keyframe and times at or after it in the segment that keyframe opens, as the buffer\'s walk reads it', + async () => { + const opened = rig() + const { recorder } = opened + const stream = opened.stream() + + // Each fragment carries its picture beside the sound timed inside the next picture's span: the sound at a keyframe's own time arrives a fragment + // ahead of that keyframe. + const leading = (from: number, to: number): void => { + for (let index = from; index < to; index++) { + const first = Math.ceil((index + 1) * 5 / 3) + const last = Math.ceil((index + 2) * 5 / 3) + + stream.write(tierStreamFragment({ + picture: [ + tierPicture({ keyframe: index % 30 === 0 }), + ], + pictureTime: BigInt(index * FRAME_TICKS), + sound: Array.from({ length: last - first }, () => soundSample(UNREAD_SOUND)), + soundTime: BigInt(first * SOUND_TICKS), + })) + } + } + + initialize(stream) + leading(0, 1) + + const reading = read(recorder.handleRecordingStreamRequest(1)) + + await settle() + leading(1, 241) + await settle() + + // The second segment opens on its keyframe's own sound, which arrived in the fragment before that keyframe. + expect(segmentsOf(reading).map(({ audio, video }) => ({ + sounds: audio.length, + soundTime: audio[0].decodeTime, + videoTime: video[0].decodeTime, + }))).toEqual([ + { + sounds: 198, + soundTime: 2n * BigInt(SOUND_TICKS), + videoTime: 0n, + }, + { + sounds: 200, + soundTime: 4n * 48000n, + videoTime: 120n * BigInt(FRAME_TICKS), + }, + ]) + }) + + it('closes a segment early at its last keyframe once it would reach the cap, and sends a stretch that alone reaches it as it stands with one alert', async () => { + const early = rig() + + initialize(early.stream()) + frames(early.stream(), 0, 1, { octets: 120000 }) + + const earlyReading = read(early.recorder.handleRecordingStreamRequest(1)) + + frames(early.stream(), 1, 83, { octets: 120000 }) + await settle() + + expect(segmentsOf(earlyReading).length).toBe(0) + + frames(early.stream(), 83, 84, { octets: 120000 }) + await settle() + + expect(segmentsOf(earlyReading).map(({ video }) => video.length)).toEqual([60]) + expect(early.alerts).toEqual([]) + + const stretch = rig() + + initialize(stretch.stream()) + frames(stretch.stream(), 0, 1, { gop: 90, octets: 120000 }) + + const stretchReading = read(stretch.recorder.handleRecordingStreamRequest(1)) + + frames(stretch.stream(), 1, 91, { gop: 90, octets: 120000 }) + await settle() + + expect(segmentsOf(stretchReading).map(({ video }) => video.length)).toEqual([90]) + expect(stretch.alerts.map(({ kind, sentence }) => ({ kind, sentence }))).toEqual([ + { + kind: 'segment-over-cap', + sentence: `The recording of the video tier 1 of the video sensor "${SENSOR_UUID}" sent a segment whose stretch from one keyframe to the next ` + + 'reached the cap of 10000000 octets on an uploaded segment: it left as it stood.', + }, + ]) + }) + + it('leaves out the sound track and every sound run when Recording Audio Active reads off at the open', async () => { + const opened = rig({ audio: false, prebuffer: 8000 }) + const { recorder } = opened + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 241) + + const reading = read(recorder.handleRecordingStreamRequest(1)) + + await settle() + + const [initialization] = reading.packets + const moov = walkBoxes(initialization.data).boxes.find(({ type }) => type === 'moov')! + + expect(readTrackBoxes(initialization.data, moov).map(({ track }) => track.handler)).toEqual(['vide']) + expect(segmentsOf(reading).map(({ audio, video }) => [video.length, audio.length])).toEqual([ + [120, 0], + [120, 0], + ]) + }) + + it('keeps its sound while Recording Audio Active reads on and the camera\'s Microphone is muted, which holds back the live views\' sound alone', async () => { + const [unmuted, muted] = [false, true].map((mute) => { + const opened = rig({ prebuffer: 8000 }) + const stream = opened.stream() + + if (mute) { + opened.camera.setMicrophoneMuted(true) + } + + initialize(stream) + frames(stream, 0, 241) + + return { + reading: read(opened.recorder.handleRecordingStreamRequest(1)), + // @ts-expect-error: private access + table: opened.camera.tierTables.get(SENSOR_UUID) as TierTable, + } + }) + + await settle() + + // The muted camera's table holds its live sound back, and its recording carries every sound the unmuted camera's does. + expect([unmuted, muted].map(({ table }) => table.audioTier.context.microphoneMuted)).toEqual([false, true]) + expect(segmentsOf(muted.reading).map(({ audio }) => audio.length > 0)).toEqual([true, true]) + expect(segmentsOf(muted.reading)).toEqual(segmentsOf(unmuted.reading)) + }) + + it('records the recorded tier\'s own sound while Recording Audio Active reads on where the recorded sensor\'s audio states its source shared', async () => { + const [own, shared] = (['tier', 'shared'] as const).map((source) => { + const opened = rig({ prebuffer: 8000, source }) + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 241) + + return read(opened.recorder.handleRecordingStreamRequest(1)) + }) + + await settle() + + // The shared sensor's sound tier is the recorded tier, and its recording carries every sound the camera whose tiers each carry their own does. + expect(segmentsOf(shared).map(({ audio, video }) => [video.length, audio.length])).toEqual([ + [120, 200], + [120, 200], + ]) + expect(segmentsOf(shared)).toEqual(segmentsOf(own)) + }) + + it('runs the picture\'s decode times on from zero without a break across a discontinuity in mid-segment and a short gap, which reads as the duration ' + + 'of the picture before it, each segment\'s producer reference time box carrying its decode time, and places its sound against its opening keyframe', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const opened = rig({ prebuffer: 2000 }) + const { camera } = opened + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 61) + + const client = await DataStreamClient.connect(camera.recordingManagement!.dataStreamManagement) + + client.request(Protocols.DATA_SEND, Topics.OPEN, { + reason: 'motion', + streamId: 1, + target: 'controller', + type: 'ipcamera.recording', + }) + await settle() + frames(stream, 61, 75) + stream.discontinuity() + frames(stream, 0, 61) + // A short gap of a second and a half, the stream's times and its arrival moving on together, inside the segment from the restart's keyframe. + vi.advanceTimersByTime(1500) + frames(stream, 105, 241) + await settle() + + const sent = client.events(Protocols.DATA_SEND, Topics.DATA).map(({ packets: [{ data }] }) => data as Buffer).slice(1) + + expect(sent.map((data) => { + const prft = walkBoxes(data).boxes.find(({ type }) => type === 'prft')! + const moof = data.subarray(prft.end) + const { audio, video } = segmentOf(moof) + + return { + durations: [ + ...new Set(video.map(({ duration }) => duration)), + ], + pictures: video.length, + prftTime: data.readBigUInt64BE(prft.start + 24), + soundTime: audio[0].decodeTime, + videoTime: video[0].decodeTime, + } + })).toEqual([ + { + durations: [3000], + pictures: 75, + prftTime: 0n, + soundTime: 0n, + videoTime: 0n, + }, + { + // The picture before the gap, the restart's 61st, runs on to the next decode time 45 frames later. + durations: [3000, 45 * 3000], + pictures: 76, + prftTime: 75n * 3000n, + soundTime: 75n * 3000n * 48000n / 90000n, + videoTime: 75n * 3000n, + }, + { + durations: [3000], + pictures: 120, + prftTime: (75n + 120n) * 3000n, + soundTime: (75n + 120n) * 3000n * 48000n / 90000n, + videoTime: (75n + 120n) * 3000n, + }, + ]) + }) + + 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() + const { recorder } = opened + const stream = opened.stream() + // Each picture, and each fragment's last sound, states 0 at an even index and half its step at an odd one. + const options: FrameOptions = { + stated: (step, index) => index % 2 === 0 + ? 0 + : step / 2, + } + + initialize(stream) + frames(stream, 0, 1, options) + + const reading = read(recorder.handleRecordingStreamRequest(1)) + + // Each discontinuity closes the segment in progress as it stands: the first after a picture and a sound that state 0, the second after a picture and + // a sound that state half a step, a sound the voice reader reads no duration of, which runs past the half step of its picture. + frames(stream, 1, 135, options) + stream.discontinuity() + frames(stream, 0, 18, options) + stream.discontinuity() + frames(stream, 0, 1, options) + await settle() + + // A run of samples at a step, its last at a step of its own. + const steps = (count: number, step: number, last = step): number[] => [ + ...Array.from({ length: count - 1 }).fill(step), + last, + ] + + expect(segmentsOf(reading).map(({ audio, video }) => ({ + pictures: video.map(({ duration }) => duration), + sounds: audio.map(({ duration }) => duration), + }))).toEqual([ + { + pictures: steps(120, FRAME_TICKS), + sounds: steps(200, SOUND_TICKS), + }, + { + pictures: steps(15, FRAME_TICKS), + sounds: steps(25, SOUND_TICKS), + }, + { + // The last sound, the 30th, ends where the last picture, the 18th and stating half a step, ends. + pictures: steps(18, FRAME_TICKS, FRAME_TICKS / 2), + sounds: steps(30, SOUND_TICKS, (17 * FRAME_TICKS + FRAME_TICKS / 2) * 48000 / 90000 - 29 * SOUND_TICKS), + }, + ]) + }) + + it('joins each segment\'s sound to the next segment\'s at zero ticks, every sound at its stream\'s own time against its picture, over streams whose sound ' + + 'is in step or a fragment behind, falls on the keyframes or straddles each that closes a segment, and states half or twice its step at each ' + + 'fragment\'s last', async () => { + // Half a sound later than the frames' own times, a sound straddles each keyframe, every one standing on a whole second. + const straddle = (_index: number, time: number): number => time + SOUND_TICKS / 2 + + for (const lag of [false, true]) { + for (const retimeSound of [undefined, straddle]) { + for (const stated of [ + (step: number) => step / 2, + (step: number) => step * 2, + ]) { + const options: FrameOptions = { + lag, + readable: true, + retimeSound, + stated, + } + const opened = rig() + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 1, options) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // Segments each closed at the keyframe 4 seconds after its opening one, the last at 20 seconds. + frames(stream, 1, 601, options) + await settle() + + const segments = segmentsOf(reading) + // The stream's own sounds, each 20 ms on from the one before, those timed before 20 seconds, and its pictures before then. + const first = retimeSound?.(0, 0) ?? 0 + const sounds = Array.from({ length: 1000 }, (_, index) => BigInt(first + index * SOUND_TICKS)) + const pictures = Array.from({ length: 600 }, (_, index) => BigInt(index * FRAME_TICKS)) + + expect(segments).toHaveLength(5) + expect(segments.flatMap(({ audio }) => audio.map(({ decodeTime }) => decodeTime))).toEqual(sounds) + expect(segments.flatMap(({ audio }) => audio.map(({ duration }) => duration))).toEqual(sounds.map(() => SOUND_TICKS)) + expect(segments.flatMap(({ video }) => video.map(({ decodeTime }) => decodeTime))).toEqual(pictures) + } + } + } + }) + + it.each([ + [ + 'a discontinuity', + async ({ stream }: Rig): Promise => stream().discontinuity(), + ], + [ + 'a failure', + async ({ stream }: Rig): Promise => { + stream().fail('The camera went away.') + // The failed demand leaves its tier once the keeper's join is released, the keeper asks for the tier again after its first wait, and the plugin + // starts the new stream with its initialization segment. + await settle() + vi.advanceTimersByTime(1000) + initialize(stream()) + }, + ], + ] as const)('closes the segment in progress at %s in mid-segment with the sound timed before its last picture\'s end alone, its last sound ending no ' + + 'later, each sample at the stream\'s own composition offset and each track\'s decode times rising across the cut', async (_cut, cut) => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + // The sound runs two and a half sounds ahead of the frames' own times: a run's sound reaches past its last picture. + const options: FrameOptions = { + readable: true, + retimeSound: (_index, time) => time + SOUND_TICKS * 5 / 2, + } + const opened = rig() + + initialize(opened.stream()) + frames(opened.stream(), 0, 1, options) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + frames(opened.stream(), 1, 75, options) + await cut(opened) + frames(opened.stream(), 0, 121, options) + await settle() + + const segments = segmentsOf(reading) + const [closed, after] = segments + // The end of the closed segment's last picture, its 75th, on the sound's timescale. + const end = 75n * BigInt(FRAME_TICKS) * 48000n / 90000n + const last = closed.audio.at(-1)! + + expect(segments).toHaveLength(2) + expect(closed.video).toHaveLength(75) + expect(closed.audio.filter(({ decodeTime }) => decodeTime >= end)).toEqual([]) + expect(last.decodeTime + BigInt(last.duration!)).toBeLessThanOrEqual(end) + expect(segments.flatMap(({ audio, video }) => [ + ...video, + ...audio, + ]).filter(({ compositionOffset }) => compositionOffset !== 0)).toEqual([]) + expect(after.video[0].decodeTime).toBeGreaterThan(closed.video.at(-1)!.decodeTime) + expect(after.audio[0].decodeTime).toBeGreaterThanOrEqual(last.decodeTime + BigInt(last.duration!)) + }) + + it('ends a run\'s sound at the least decode time the next run\'s first sound can take on the recording, on a stream of 3003 ticks a frame whose ' + + 'recording opens past its start, and the next run, opening with a sound, repeats no decode time', async () => { + const opened = rig() + const stream = opened.stream() + // A frame's ticks, which do not divide into the sound's, the decode time the recording opens at, and a 20 ms sound whose packet states its length. + const step = 3003 + const opening = 9001 + const voiced = Buffer.concat([ + Buffer.from([0x08]), + Buffer.alloc(39, 0x5A), + ]) + const picture = (keyframe: boolean): SampleFixture => ({ + ...tierPicture({ keyframe }), + duration: step, + }) + const sounds = (count: number): SampleFixture[] => Array.from({ length: count }, () => soundSample(voiced)) + // Pictures from a time, one a fragment, the first a keyframe unless the run carries on, each fragment carrying the count of sounds given, those whose + // 20 ms start inside its picture, timed on from a first sound's time. + const run = (pictureTime: number, soundTime: number, counts: readonly number[], opens = true): void => { + for (const [index, count] of counts.entries()) { + stream.write(tierStreamFragment({ + picture: [ + picture(opens && (index === 0)), + ], + pictureTime: BigInt(pictureTime + index * step), + sound: sounds(count), + soundTime: BigInt(soundTime + counts.slice(0, index).reduce((total, before) => total + before, 0) * SOUND_TICKS), + })) + } + } + + initialize(stream) + run(opening, Math.ceil(opening * 48000 / 90000), [2, 2, 2]) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // The next run opens with a sound at the stream's start, written ahead of its keyframe, and runs on for two more pictures. + stream.discontinuity() + stream.write(sampleFragment( + { + decodeTime: 0n, + samples: sounds(2), + trackId: TIER_STREAM_SOUND, + }, + { + decodeTime: 0n, + samples: [ + picture(true), + ], + trackId: TIER_STREAM_PICTURE, + }, + )) + run(step, 2 * SOUND_TICKS, [2, 1], false) + // The buffer reads a mark at the stream's next sample, which means a third run's keyframe closes the second run's segment. + stream.discontinuity() + run(0, 0, [0]) + await settle() + + const segments = segmentsOf(reading) + const [closed, next] = segments + const last = closed.audio.at(-1)! + // The recording's picture time after the closed segment's three pictures, on the sound's timescale, where the next run's first sound is anchored. + const pictureEnd = 3n * BigInt(step) * 48000n / 90000n + + expect(segments).toHaveLength(2) + expect(closed.audio).toHaveLength(6) + expect(last.decodeTime + BigInt(last.duration!)).toBe(pictureEnd) + expect(next.video[0].decodeTime).toBe(3n * BigInt(step)) + expect(next.audio[0].decodeTime).toBe(pictureEnd) + + for (const medium of ['video', 'audio'] as const) { + const times = segments.flatMap(segment => segment[medium].map(({ decodeTime }) => decodeTime)) + + expect(times.filter((time, index) => (index > 0) && (time <= times[index - 1]))).toEqual([]) + } + }) + + it('closes the segment in progress as it stands at a restart that opens with a fragment of sound alone where the buffer holds no run of sound, that ' + + 'sound in no segment, and runs the recording on from the restart\'s keyframe, each track\'s decode times rising across the end', async () => { + const opened = rig() + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 1, { sound: false }) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // Three seconds of pictures alone. The restart opens with a fragment of sound alone, timed inside the segment in progress and before the restart's + // keyframe at its first second, and runs on to the keyframe of its fifth second, which closes the recording's next segment. + frames(stream, 1, 90, { sound: false }) + stream.discontinuity() + stream.write(tierStreamFragment({ + sound: [ + soundSample(UNREAD_SOUND), + ], + soundTime: 49n * BigInt(SOUND_TICKS), + })) + frames(stream, 30, 151, { readable: true }) + await settle() + + const segments = segmentsOf(reading) + const [closed, next] = segments + + expect(segments).toHaveLength(2) + expect(closed.video.map(({ decodeTime }) => decodeTime)).toEqual(Array.from({ length: 90 }, (_, index) => BigInt(index * FRAME_TICKS))) + expect(closed.audio).toEqual([]) + expect(next.video.map(({ decodeTime }) => decodeTime)).toEqual(Array.from({ length: 120 }, (_, index) => BigInt((90 + index) * FRAME_TICKS))) + // The restart's sounds from its keyframe's second up to its fifth, those its frames wrote, the lone sound before them in none. + expect(next.audio).toHaveLength(200) + + for (const medium of ['video', 'audio'] as const) { + const times = segments.flatMap(segment => segment[medium].map(({ decodeTime }) => decodeTime)) + + expect(times.filter((time, index) => (index > 0) && (time <= times[index - 1]))).toEqual([]) + } + }) + + it('sends no segment for a run whose lone picture states no duration before any picture\'s is known, ended by a mark, the next run\'s first picture ' + + 'opening the recording at its first decode time', async () => { + const opened = rig() + const stream = opened.stream() + + initialize(stream) + // A run of one keyframe that states no duration, with its sound. + frames(stream, 0, 1, { + readable: true, + stated: () => 0, + }) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + stream.discontinuity() + frames(stream, 0, 121, { readable: true }) + await settle() + + const segments = segmentsOf(reading) + + expect(segments).toHaveLength(1) + expect(segments[0].video.map(({ decodeTime }) => decodeTime)).toEqual(Array.from({ length: 120 }, (_, index) => BigInt(index * FRAME_TICKS))) + }) + + it('writes no sound for a run\'s lone sound of no stated length on a packet the voice reader reads no length of, with no sound sent before it', async () => { + const opened = rig() + const stream = opened.stream() + + initialize(stream) + frames(stream, 0, 1, { sound: false }) + // The run's lone sound, stating no duration, on a packet whose length the voice reader cannot read. + stream.write(tierStreamFragment({ + sound: [ + { + ...soundSample(UNREAD_SOUND), + duration: 0, + }, + ], + soundTime: 0n, + })) + frames(stream, 1, 3, { sound: false }) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + // The buffer reads a mark at the stream's next sample, which means the next run's keyframe closes the segment. + stream.discontinuity() + frames(stream, 0, 1, { sound: false }) + await settle() + + const segments = segmentsOf(reading) + + expect(segments).toHaveLength(1) + expect(segments[0].video.map(({ duration }) => duration)).toEqual([FRAME_TICKS, FRAME_TICKS, FRAME_TICKS]) + expect(segments[0].audio).toEqual([]) + }) + + it('cuts the sound of a segment closed at a run\'s end at its last picture\'s end by decode time, on a stream whose composition offsets present that ' + + 'picture past it', async () => { + const opened = rig() + const stream = opened.stream() + // A picture of a frame's ticks in decode order, presented two frames after its decode time, and the 20 ms sounds whose start falls inside its frame, + // each two and a half sounds later than the frame's own times: a run's sound reaches past its last picture's presentation end. + const write = (index: number): void => { + const first = Math.ceil(index * 5 / 3) + + stream.write(tierStreamFragment({ + picture: [ + { + ...tierPicture({ keyframe: index % 30 === 0 }), + compositionOffset: 2 * FRAME_TICKS, + }, + ], + pictureTime: BigInt(index * FRAME_TICKS), + sound: Array.from({ length: Math.ceil((index + 1) * 5 / 3) - first }, () => soundSample(UNREAD_SOUND)), + soundTime: BigInt(first * SOUND_TICKS + SOUND_TICKS * 5 / 2), + })) + } + + initialize(stream) + write(0) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + for (let index = 1; index < 75; index++) { + write(index) + } + + // The buffer reads a mark at the stream's next sample, which means the next run's keyframe closes the segment. + stream.discontinuity() + write(0) + await settle() + + const [closed] = segmentsOf(reading) + const last = closed.audio.at(-1)! + // The decode-time end of the 75th picture on the sound's timescale, two frames before its presentation ends. + const end = 75n * BigInt(FRAME_TICKS) * 48000n / 90000n + + expect(closed.video).toHaveLength(75) + expect(closed.audio.filter(({ decodeTime }) => decodeTime >= end)).toEqual([]) + expect(last.decodeTime + BigInt(last.duration!)).toBe(end) + }) + }) + + describe('its end', () => { + // A ready recording of one whole segment, its segment in progress opening at the keyframe of 4 seconds and holding later keyframes: its place holds + // the buffer past its span. + async function recording(options: FrameOptions = {}): Promise { + const opened = rig() + + initialize(opened.stream()) + frames(opened.stream(), 0, 1, options) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + frames(opened.stream(), 1, 200, options) + await settle() + + return { ...opened, reading } + } + + // The times in seconds of the keyframes the buffer holds. + function keyframeTimes(buffer: TierBuffer | undefined): number[] | undefined { + return buffer?.samples.filter(({ sync, track }) => sync && (track.medium === 'video')).map(({ time }) => time / 1000000) + } + + it.each([ + [ + 'the hub\'s acknowledgement', + 'ended', + ({ recorder }: Rig) => recorder.acknowledgeStream(1), + ], + [ + 'the hub\'s normal close', + 'ended', + ({ recorder }: Rig) => recorder.closeRecordingStream(1, HDSProtocolSpecificErrorReason.NORMAL), + ], + [ + 'the hub\'s close as not allowed', + 'cancelled', + ({ recorder }: Rig) => recorder.closeRecordingStream(1, HDSProtocolSpecificErrorReason.NOT_ALLOWED), + ], + [ + 'the hub\'s close for another reason', + 'failed', + ({ recorder }: Rig) => recorder.closeRecordingStream(1, HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE), + ], + [ + 'its connection\'s close', + 'failed', + ({ recorder }: Rig) => recorder.closeRecordingStream(1, undefined), + ], + ] as const)('ends once at %s, %s, its place given up so the buffer falls back to its span', async (_route, outcome, end) => { + const opened = await recording() + + expect(keyframeTimes(opened.buffer())).toEqual([4, 5, 6]) + + end(opened) + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome, + segments: 1, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(keyframeTimes(opened.buffer())).toEqual([6]) + expect(opened.reading.done).toBe(true) + expect(opened.reading.packets.at(-1)!.isLast).toBe(false) + }) + + it.each([ + [ + 'recording no longer allowed', + 'cancelled', + ({ allow }: Rig) => allow(false), + ], + [ + 'the accessory\'s unpublish', + 'cancelled', + ({ accessoryUUID, camera }: Rig) => camera.handleAccessoryContext({ + accessoryInformation: new Service.AccessoryInformation('Camera') as AccessoryInformation, + accessoryUUID, + published: false, + username: undefined, + }), + ], + [ + 'a factory reset', + 'cancelled', + ({ camera }: Rig) => camera.handleFactoryReset(), + ], + [ + 'the controller\'s removal', + 'cancelled', + ({ camera }: Rig) => camera.handleControllerRemoved(), + ], + ] as const)('ends once at %s, %s, with the end marker after its last whole segment, the hold released and the buffer emptied', async (_route, outcome, end) => { + const opened = await recording() + // The tier's buffer as the recording found it, which the camera's tier tables do not reach once it is removed. + const buffer = opened.buffer()! + + end(opened) + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome, + segments: 1, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(buffer.samples).toEqual([]) + expect(endsOf(opened.delegate)).toBe(1) + expect(segmentsOf(opened.reading).length).toBe(1) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + }) + + it('ends once as the camera\'s source is stated away, cancelled, with the end marker after its segment in progress closed as it stands, the hold ' + + 'released and its tier\'s demand ended', async () => { + const opened = await recording() + const buffer = opened.buffer()! + const events = captureDebugEvents('HAP-NodeJS:Camera:BufferRecorder') + // The pictures the buffer keeps from the segment in progress's keyframe, 4 seconds in, to its newest. + const kept = buffer.samples.filter(({ time, track }) => (track.medium === 'video') && (time >= 4000000)).length + + opened.camera.updateSourceState('away') + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome: 'cancelled', + segments: 2, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + // The recording's length as the hub reads it: the durations of the pictures in its segments, over the picture track's timescale its initialization + // segment states. + const initialization = opened.reading.packets[0].data + const moov = walkBoxes(initialization).boxes.find(({ type }) => type === 'moov')! + const { timescale } = readTrackBoxes(initialization, moov).find(({ track }) => track.handler === 'vide')!.track + const seconds = segmentsOf(opened.reading).flatMap(({ video }) => video).reduce((total, { duration }) => total + duration!, 0) / timescale + + expect(events.filter(({ kind }) => kind === 'recording-ended')).toEqual([ + { + accessoryUUID: opened.accessoryUUID, + dropped: 0, + kind: 'recording-ended', + outcome: 'cancelled', + seconds, + segments: 2, + sensorUUID: SENSOR_UUID, + sentence: `The recording of stream 1 ended cancelled after 2 segments, ${seconds.toFixed(3)} seconds long, 0 of its samples dropped.`, + streamId: 1, + tierId: 1, + }, + ]) + expect(kept).toBe(80) + expect(segmentsOf(opened.reading).map(({ video }) => video.length)).toEqual([120, kept]) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + expect(buffer.samples).toEqual([]) + expect(endsOf(opened.delegate)).toBe(1) + }) + + it('closes no segment as the camera\'s source is stated away while its place waits for a keyframe after a run\'s end, the next run\'s sound kept ' + + 'ahead of its first keyframe, and ends with the end marker, raising no problem', async () => { + const opened = await recording() + const stream = opened.stream() + // A fragment of the next run, a picture that is no keyframe and the sound timed with it. + const next = tierStreamFragment({ + picture: [ + tierPicture(), + ], + pictureTime: 200n * BigInt(FRAME_TICKS), + sound: [ + soundSample(UNREAD_SOUND), + soundSample(UNREAD_SOUND), + ], + soundTime: 334n * BigInt(SOUND_TICKS), + }) + const mdat = walkBoxes(next).boxes.find(({ type }) => type === 'mdat')! + + // A matching initialization segment ends the run, closing the segment in progress, and the next fragment is written up to its first sound's last + // octet, which is why the buffer keeps that sound while the place holds no keyframe. + initialize(stream) + stream.write(next.subarray(0, mdat.payload + tierPicture().data.length + UNREAD_SOUND.length)) + await settle() + + expect(opened.buffer()!.samples.map(({ track }) => track.medium)).toEqual(['audio']) + + opened.camera.updateSourceState('away') + opened.recorder.acknowledgeStream(1) + await settle() + + expect(segmentsOf(opened.reading).map(({ video }) => video.length)).toEqual([120, 80]) + expect(opened.alerts).toEqual([]) + expect(opened.ends).toEqual([ + { + outcome: 'cancelled', + segments: 2, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + }) + + it('raises one library-failure problem for a close of its segment in progress that throws as the camera\'s source is stated away, and still ends ' + + 'once, cancelled, with the end marker after its last whole segment and its tier\'s demand ended', async () => { + const opened = await recording() + + // The close's walk of the buffer throws, and no view walks the buffer in this rig. + vi.spyOn(opened.buffer()!, 'walk').mockImplementation(() => { + throw new Error('The walk failed.') + }) + + expect(() => opened.camera.updateSourceState('away')).not.toThrow() + + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.alerts).toEqual([ + expect.objectContaining({ + kind: 'library-failure', + level: 'error', + sensorUUID: SENSOR_UUID, + sentence: expect.stringContaining(`The recording of the video tier 1 of the video sensor "${SENSOR_UUID}" failed to close its segment in progress ` + + 'and ends without that segment: Error: The walk failed.'), + tierId: 1, + }), + ]) + expect(opened.ends).toEqual([ + { + outcome: 'cancelled', + segments: 1, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(segmentsOf(opened.reading).length).toBe(1) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + expect(endsOf(opened.delegate)).toBe(1) + }) + + it.each([ + { + restore: (opened: Rig) => opened.camera.updateSourceState('available'), + stop: (opened: Rig) => opened.camera.updateSourceState('away'), + told: 'states the camera\'s source available again, the recording having ended as the source was stated away', + }, + { + restore: ({ allow }: Rig) => allow(true), + stop: ({ allow }: Rig) => allow(false), + told: 'turns recording on again, the recording having ended as recording was turned off', + }, + ])('keeps its recorded tier raised and admits the hub\'s next open where a listener of its recording\'s end $told inside its call', async ({ + restore, + stop, + }) => { + const opened = await recording() + + opened.camera.once('recording-ended', () => restore(opened)) + stop(opened) + await settle() + + expect(opened.ends).toHaveLength(1) + expect(endsOf(opened.delegate)).toBe(0) + + frames(opened.stream(), 200, 245) + + expect(opened.recorder.admit(2)).toMatchObject({ admitted: true }) + expect(opened.alerts.filter(({ kind }) => kind === 'recording-declined')).toEqual([]) + }) + + it('ends once as the camera is manually disabled, cancelled, with the end marker after its last whole segment and its tier\'s demand ended, and refuses a ' + + 'hub\'s open as not allowed without asking the recorder until the camera is enabled again, which admits the next', async () => { + const opened = await recording() + // Manually Disabled as the Camera Capabilities service projects it. + const disabled = opened.services['cameraCapabilities:cameraCapabilities']!.getCharacteristic(Characteristic.ManuallyDisabled) + + disabled.updateValue(1) + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome: 'cancelled', + segments: 1, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(endsOf(opened.delegate)).toBe(1) + expect(segmentsOf(opened.reading).length).toBe(1) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + expect(opened.camera.recordingAllowed).toBe(false) + + const admit = vi.spyOn(opened.recorder, 'admit') + const client = await DataStreamClient.connect(opened.camera.recordingManagement!.dataStreamManagement) + const refused = openRecording(client, 2) + + await settle() + + expect(client.answerTo(refused)?.message).toEqual({ status: HDSProtocolSpecificErrorReason.NOT_ALLOWED }) + expect(admit).not.toHaveBeenCalled() + + disabled.updateValue(0) + initialize(opened.stream()) + frames(opened.stream(), 0, 45) + + const admitted = openRecording(client, 3) + + await settle() + + expect(client.answerTo(admitted)?.header.status).toBe(HDSStatus.SUCCESS) + expect(admit.mock.calls).toEqual([ + [3], + ]) + expect(opened.starts.map(({ streamId }) => streamId)).toEqual([1, 3]) + + client.closeSocket() + await settle() + }) + + it('ends once at a long gap, as a gap, with the end marker after its segment in progress closed as it stands', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const opened = await recording() + + vi.advanceTimersByTime(10000) + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome: 'gap', + segments: 2, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + expect(segmentsOf(opened.reading).map(({ video }) => video.length)).toEqual([120, 80]) + }) + + it.each([ + { first: 'each keeper' }, + { first: 'each tier table' }, + ])('ends once as a gap 30 seconds after a reconnect told to $first first, with the end marker after the segment in progress the long gap closes', + async ({ first }) => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const opened = await recording() + + // The camera controller tells each keeper first, and a tier table told first makes the demand's clock the earlier of the two due at 30 seconds. + if (first === 'each keeper') { + opened.camera.updateSourceState('recovering') + } else { + // @ts-expect-error: private access + const { keeper, tierTable } = opened.recorder.options + + tierTable(SENSOR_UUID)!.sourceRecovering() + keeper.sourceRecovering() + } + + await vi.advanceTimersByTimeAsync(30000) + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome: 'gap', + segments: 2, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + expect(segmentsOf(opened.reading).map(({ video }) => video.length)).toEqual([120, 80]) + }, + ) + + it('ends once at a new initialization segment whose picture description differs, as failed, and runs on at one whose descriptions match, closing ' + + 'its segment in progress as it stands', async () => { + const changed = await recording() + + changed.stream().write(tierStreamInitialization({ + parameterSets: TIER_STREAM_PARAMETER_SETS.slice(1), + })) + changed.recorder.acknowledgeStream(1) + await settle() + + expect(changed.ends).toEqual([ + { + outcome: 'failed', + segments: 2, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(changed.reading.packets.at(-1)).toEqual(MARKER) + + const matching = await recording() + + initialize(matching.stream()) + await settle() + + expect(matching.ends).toEqual([]) + expect(segmentsOf(matching.reading).map(({ video }) => video.length)).toEqual([120, 80]) + }) + + it('ends once at a new initialization segment whose picture keeps its hvcC and changes its size, as failed, with the end marker', async () => { + const opened = await recording() + + opened.stream().write(resized(128, 72)) + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome: 'failed', + segments: 2, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + }) + + it('sends a segment whose closing keyframe arrived before an open only once that keyframe\'s fragment ends, with the sound the fragment carries after ' + + 'its keyframe', async () => { + const opened = rig({ prebuffer: 4000 }) + const stream = opened.stream() + // The fragment of the keyframe 4 seconds in, which closes the first segment, carrying the sound of the frame before it, as a fragment behind. + const closing = tierStreamFragment({ + picture: [ + tierPicture({ keyframe: true }), + ], + pictureTime: 120n * BigInt(FRAME_TICKS), + sound: [ + soundSample(UNREAD_SOUND), + ], + soundTime: 199n * BigInt(SOUND_TICKS), + }) + const mdat = walkBoxes(closing).boxes.find(({ type }) => type === 'mdat')! + // The fragment written up to its keyframe's last octet, and the rest, its sound, in a write of its own. + const split = mdat.payload + tierPicture({ keyframe: true }).data.length + + initialize(stream) + frames(stream, 0, 120, { lag: true }) + stream.write(closing.subarray(0, split)) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + await settle() + + expect(segmentsOf(reading)).toEqual([]) + + stream.write(closing.subarray(split)) + await settle() + + expect(segmentsOf(reading).map(({ audio, video }) => ({ + lastSound: audio.at(-1)!.decodeTime, + pictures: video.length, + sounds: audio.length, + }))).toEqual([ + { + lastSound: 199n * BigInt(SOUND_TICKS), + pictures: 120, + sounds: 200, + }, + ]) + }) + + it.each([ + [ + 'picture', + 'vide', + 45000, + ], + [ + 'sound', + 'soun', + 24000, + ], + ] as const)('ends once at a new initialization segment that changes its %s\'s timescale alone, as failed, with the end marker', async ( + _medium, + handler, + timescale, + ) => { + const opened = await recording() + + opened.stream().write(retimed(handler, timescale)) + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome: 'failed', + segments: 2, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(opened.reading.packets.at(-1)).toEqual(MARKER) + }) + + it('ends once at a ceiling\'s trim past its place, as failed, with the end marker', async () => { + const opened = rig() + + initialize(opened.stream()) + frames(opened.stream(), 0, 1, { gop: 1000 }) + + const reading = read(opened.recorder.handleRecordingStreamRequest(1)) + + frames(opened.stream(), 1, 302, { gop: 1000 }) + opened.recorder.acknowledgeStream(1) + await settle() + + expect(opened.ends).toEqual([ + { + outcome: 'failed', + segments: 0, + sensorUUID: SENSOR_UUID, + streamId: 1, + tierId: 1, + }, + ]) + expect(opened.alerts.map(({ kind }) => kind)).toEqual(['buffer-trimmed']) + expect(reading.packets.at(-1)).toEqual(MARKER) + }) + + it('counts no silence on a demand a recording-ended listener ended inside the trim that ended its recording, the tier\'s next silence still told', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const opened = rig() + + // A plugin's listener that states the source away as the recording ends, which here runs inside the buffer's take of the picture that trimmed + // past the recording's place, and ends the tier's demand there. + opened.camera.on('recording-ended', () => opened.camera.updateSourceState('away')) + initialize(opened.stream()) + frames(opened.stream(), 0, 1, { gop: 1000 }) + void read(opened.recorder.handleRecordingStreamRequest(1)) + frames(opened.stream(), 1, 302, { gop: 1000 }) + + // Past the long-gap time of the picture the ended demand took last, then the source back and a fresh demand that hands over nothing. + await vi.advanceTimersByTimeAsync(10000) + opened.camera.updateSourceState('available') + await vi.advanceTimersByTimeAsync(31000) + + expect(opened.alerts.map(({ kind }) => kind)).toEqual([ + 'buffer-trimmed', + 'stream-failed', + 'tier-failed', + ]) + }) + }) +}) diff --git a/src/lib/camera/recording/BufferRecorder.ts b/src/lib/camera/recording/BufferRecorder.ts new file mode 100644 index 000000000..c3272a6c6 --- /dev/null +++ b/src/lib/camera/recording/BufferRecorder.ts @@ -0,0 +1,1004 @@ +import type { + CameraBufferRecordingOptions, + CameraRecordingDelegate, + CameraRecordingEnd, + CameraRecordingOutcome, + CameraRecordingStart, +} from '../../controller/index.js' +import type { BufferedSample, BufferPlace, BufferWalk, TierBuffer } from '../buffer/CameraBuffer.js' +import type { TierKeeper } from '../buffer/TierKeeper.js' +import type { CameraReporter } from '../diagnostics/CameraReporter.js' +import type { Mp4StreamAudioTrack, Mp4StreamTrack, Mp4StreamTracks, Mp4StreamVideoTrack } from '../mp4/Mp4StreamReader.js' +import type { SegmentSample } from '../mp4/mp4Writer.js' +import type { OperatingModePolicy } from '../OperatingModePolicy.js' +import type { RecordingPacket } from '../RecordingManagement.js' +import type { ValidatedVideoSensors } from '../StreamingOptions.js' +import type { TierTable } from '../TierTable.js' + +import { Buffer } from 'node:buffer' + +import { HDSProtocolError, HDSProtocolSpecificErrorReason } from '../../datastream/DataStreamServer.js' +import { counted } from '../../util/counted.js' +import { debugChannel } from '../diagnostics/debugChannels.js' +import { readSampleEntryBoxes } from '../mp4/mp4Boxes.js' +import { segmentLength, writeKeyframeInitializationSegment, writeSegment } from '../mp4/mp4Writer.js' +import { decodable } from '../rtp/FrameCutter.js' +import { OPUS_TICKS_PER_MILLISECOND, readOpusVoice } from '../webrtc/voice/opusVoice.js' + +const BUFFER_RECORDER_DEBUG = debugChannel('HAP-NodeJS:Camera:BufferRecorder') + +// The prebuffer a camera records with unless its plugin gives another, and the longest it may give, in milliseconds. +const DEFAULT_PREBUFFER = 5000 +const LONGEST_PREBUFFER = 30 * 1000 + +/* A segment's target length in microseconds of the stream's times, and the cap on its moof and mdat: the most an uploaded segment is known to be taken at, + * which this testing shows is 10 MB, read as 10,000,000 octets. + */ +const SEGMENT_TARGET = 4 * 1000000 +const SEGMENT_CAP = 10000000 + +// The codec box of each medium's sample entry, which a description is compared by. +const CODEC_BOXES = { audio: 'dOps', video: 'hvcC' } as const + +// Opus's clock of 48 kHz, the units the voice reader states a packet's duration in. +const OPUS_RATE = OPUS_TICKS_PER_MILLISECOND * 1000 + +/** + * Validates a camera's recording from its camera buffer and settles the prebuffer it leaves out at its default, beside the recorded sensor and tier the + * options boundary settled and the plugin's shouldRecord. + * @param options - The block's recording option, absent when the block gives none. + * @param recorded - The recorded sensor in lowercase and its recorded tier, as the options boundary settled them. + * @returns The recorded sensor in lowercase, the recorded tier, the prebuffer and the shouldRecord the option gives, if any. + * @throws TypeError for a prebuffer that is not a whole number from 0 to 30000, and for a shouldRecord that is not a function. + */ +export function validateBufferRecordingOptions(options: CameraBufferRecordingOptions = {}, recorded: ValidatedVideoSensors['recorded']): BufferRecording { + const { prebuffer = DEFAULT_PREBUFFER, shouldRecord } = options + + if (!Number.isInteger(prebuffer) || (prebuffer < 0) || (prebuffer > LONGEST_PREBUFFER)) { + throw new TypeError(`The prebuffer of the camera capabilities block's recording option, ${String(prebuffer)}, is not a whole number of milliseconds from 0 ` + + `to ${LONGEST_PREBUFFER}.`) + } + + if ((shouldRecord !== undefined) && (typeof shouldRecord !== 'function')) { + throw new TypeError('The recording option of the camera capabilities block has a shouldRecord that is not a function.') + } + + return { + prebuffer, + sensorUUID: recorded.sensorUUID, + shouldRecord, + tierId: recorded.tierId, + } +} + +/** + * What a camera's recorder is made with, at the camera controller, its composition root: the callbacks of its recording events, the keeper that holds + * the recorded tier, the policy whose recording state and in-service fact drive the keeper's recording reason, the recorded tier and its prebuffer, the + * camera's reporter, the plugin's shouldRecord, and the lookup the sensor's tier table, which holds the recorded tier's buffer, is reached through, since + * the tables are built after the recorder. + */ +export interface BufferRecorderOptions { + /** + * Tells of a recording's end, as it is decided. + */ + readonly ended: (end: CameraRecordingEnd) => void + /** + * The keeper of the recorded tier, the tier's one keeper whatever other reason holds it. + */ + readonly keeper: TierKeeper + /** + * The camera's operating-mode policy, whose recording state and in-service fact the keeper's recording reason follows, and whose in-service fact and + * Recording Audio Active an open reads. + */ + readonly policy: OperatingModePolicy + /** + * How far back each recording reaches, in milliseconds. + */ + readonly prebuffer: number + /** + * The camera's reporter, through which the recorder raises the problems of the recorded tier on the camera's channel. + */ + readonly reporter: CameraReporter + /** + * The video sensor recorded, in lowercase. + */ + readonly sensorUUID: string + /** + * The plugin's answer to whether a hub's recording opens, asked with the start the recorder would tell of before the open is answered, once the camera + * is in service and the recorded tier's buffer is ready. A recording whose call stopped the recorder, the camera leaving service even for a moment, + * recording turned off, the camera switched off or manually disabled, or the camera reset or removed, is refused whatever the answer. Absent, every + * such recording opens. + */ + readonly shouldRecord?: (start: CameraRecordingStart) => boolean + /** + * Tells of a recording the recorder begins to serve. + */ + readonly started: (start: CameraRecordingStart) => void + /** + * The video tier recorded. + */ + readonly tierId: number + /** + * Finds a sensor's tier table. + */ + readonly tierTable: (sensorUUID: string) => TierTable | undefined +} + +/** + * A camera's recording from its camera buffer as its constructor settles it: the recorded sensor in lowercase, the recorded tier, the prebuffer and the + * plugin's shouldRecord. + */ +export type BufferRecording = Pick + +/** + * The recorder's answer to a hub's recording open, decided once before the recording management answers the open: a refusal, carrying the reason the + * open's answer names, or an admission, carrying the function that serves the recording from what the decision read, called once the open is answered + * with the stream's signal, which a close aborts. + */ +export type RecordingAdmission = { + readonly admitted: false + readonly reason: HDSProtocolSpecificErrorReason +} | { + readonly admitted: true + readonly serve: (signal?: AbortSignal) => AsyncIterable +} + +// The one refusal the recorder gives, as busy, whatever it declined the open for. +const REFUSED: RecordingAdmission = { admitted: false, reason: HDSProtocolSpecificErrorReason.BUSY } + +// What an admission read, which the admitted recording opens on: the recorded tier's buffer, its picture's description, the keyframe at its head and the +// start the recording events carry. +interface AdmittedRecording { + readonly head: BufferedSample + readonly start: CameraRecordingStart + readonly tier: TierBuffer + readonly video: Mp4StreamVideoTrack +} + +// What an open recording reaches in its recorder: the problem of a segment that reached the cap, and its own end. +interface RecordingRoutes { + readonly capped: () => void + 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. +interface Segment { + readonly pictures: readonly BufferedSample[] + readonly sounds: readonly BufferedSample[] + readonly next?: BufferedSample + readonly overCap: boolean + readonly end?: bigint +} + +// The end of a recording the recorder ends itself: one zero octet marked last, which a hub reads as the end of the stream. +function endMarker(): RecordingPacket { + return { + data: Buffer.alloc(1), + isLast: true, + } +} + +// A close's outcome by its reason: a normal close ended the recording, one as not allowed cancelled it, and any other reason, or the connection's close, +// failed it. +function outcomeOf(reason: HDSProtocolSpecificErrorReason | undefined): CameraRecordingOutcome { + switch (reason) { + case HDSProtocolSpecificErrorReason.NORMAL: + return 'ended' + + case HDSProtocolSpecificErrorReason.NOT_ALLOWED: + return 'cancelled' + + default: + return 'failed' + } +} + +// A track's codec box, its hvcC or its dOps, or undefined for an entry that holds none. +function codecBoxOf(track: Mp4StreamTrack): Buffer | undefined { + const found = readSampleEntryBoxes(track.sampleEntry, track.medium).find(({ type }) => type === CODEC_BOXES[track.medium]) + + return found && track.sampleEntry.subarray(found.start, found.end) +} + +// Whether a new description of a track a recording carries matches the one it opened with: the same timescale and codec box, and for a picture the same +// size. The timescale counts because the recording's initialization segment states the one it opened with, and each later sample's times are written in +// the ticks of the track the sample came from. +function matches(carried: Mp4StreamTrack, track: Mp4StreamTrack | undefined): boolean { + if ((track === undefined) || (carried.timescale !== track.timescale)) { + return false + } + + if ((carried.medium === 'video') && (track.medium === 'video') && ((carried.width !== track.width) || (carried.height !== track.height))) { + return false + } + + const [left, right] = [ + codecBoxOf(carried), + codecBoxOf(track), + ] + + return (left === undefined) + ? right === undefined + : (right !== undefined) && left.equals(right) +} + +/* One recording the recorder serves, from a hub's open to its end, and its place in the recorded tier's buffer, held at the keyframe its segment in + * progress opens on. + * + * It cuts each segment at a keyframe, from the place on: at the first keyframe at or past the segment target from the opening one, or earlier at the last + * keyframe once the segment would reach the cap, and a stretch between two keyframes that alone reaches the cap at the keyframe that closes it, with one + * `segment-over-cap` problem. A segment leaves once the fragment holding its closing keyframe has ended, which is why the sound that fragment brings after the + * keyframe goes with it. Each segment's sound is the sound timed from its opening keyframe up to its closing one. Sound timed inside a segment + * already sent is dropped. The picture's decode times start at zero and run on by each sample's duration, across a discontinuity and a short gap alike, + * which reads as the duration of the picture before it, and each segment's sound is placed against its opening keyframe on the stream's own times. An + * unsettled sound lasts as long as its own packet says: the next segment's first sound stands where it ends whatever the stream stated for it, and a + * run's lone sound whose length nothing tells, with no sound sent before it, is not written. Each track's decode times on the recording rise as the + * stream's own do, which the stream reader holds within a run, and across a run's end. + * + * 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. + */ +class OpenRecording implements BufferPlace { + keyframe?: BufferedSample + readonly streamId: number + // The media segments sent, which the recording's end reports. + segments = 0 + private readonly buffer: TierBuffer + private readonly video: Mp4StreamVideoTrack + // The sound the recording carries, absent for a recording without sound. + private readonly audio?: Mp4StreamAudioTrack + private readonly routes: RecordingRoutes + private readonly queue: Buffer[] = [] + // 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. + private wake?: () => void + // The decode time the stream's own times give the next picture the recording sends, in the picture's timescale, from zero at the recording's first. + private pictureTime = 0n + private sequenceNumber = 1 + // The durations a sample with none takes: the last its track sent, a sound's own before a segment's end bounds it. + private pictureDuration = 0 + private soundDuration = 0 + // 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 + + // 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 }: { + readonly audio?: Mp4StreamAudioTrack + readonly routes: RecordingRoutes + readonly streamId: number + }) { + this.buffer = buffer + this.video = video + this.audio = audio + this.routes = routes + this.streamId = streamId + this.keyframe = head + this.queue.push(writeKeyframeInitializationSegment({ audio, keyframe: head.data, video })) + } + + // Sends the segments the buffer already holds whole, once the recording has begun. + begin(): void { + this.cut() + } + + // The samples the recording dropped, which its end reports. + get dropped(): number { + return this.droppedSamples + } + + // The length in seconds of the media segments the recording counts, which its end reports: the durations of their pictures summed over the picture's + // timescale, media time and never the wall time the recording stayed open. + get seconds(): number { + return Number(this.pictureTime) / this.video.timescale + } + + // A recording waiting for a keyframe takes its place at the first the buffer keeps, and sound timed inside a segment already sent is counted as dropped. + taken(sample: BufferedSample): void { + if (sample.track.medium === 'video') { + if ((this.keyframe === undefined) && (sample === this.buffer.head)) { + this.keyframe = sample + } + + return + } + + if ((this.audio !== undefined) && (this.sentUpTo !== undefined) && (sample.time < this.sentUpTo)) { + this.droppedSamples++ + } + } + + fragmentEnd(): void { + this.cut() + } + + /* A new description of a track the recording carries that does not match ends the recording, since it would need a second initialization segment, + * after the segment in progress closed as it stands, written under the description the recording opened on while the buffer still holds its run. + */ + describing(tracks: Mp4StreamTracks): void { + if (!matches(this.video, tracks.video) || ((this.audio !== undefined) && !matches(this.audio, tracks.audio))) { + this.closeAsItStands() + this.routes.end('failed') + } + } + + // The end of a run closes the segment in progress as it stands, and the recording waits for the next keyframe. + ending(): void { + 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. + */ + closeAsItStands(): void { + const open = this.keyframe + + if (open === undefined) { + return + } + + const { pictures, sounds } = this.stretch(open) + const span = this.pictureDurations(pictures).reduce((total, duration) => total + BigInt(duration), 0n) + + if (span === 0n) { + this.droppedSamples += pictures.length + sounds.length + this.keyframe = undefined + this.sentUpTo = undefined + return + } + + const end = this.soundEnd(open, this.pictureTime + span) + const carried = sounds.filter(({ decodeTime }) => decodeTime < end) + + this.droppedSamples += sounds.length - carried.length + this.send({ + end, + overCap: this.length(pictures, pictures.length, carried, carried.length) >= SEGMENT_CAP, + pictures, + sounds: carried, + }) + } + + displaced(): void { + this.routes.end('failed') + } + + // Ends the recording's packets, after the whole segments already queued and, for an end the recorder makes itself, with the end marker, and gives up its + // place in the buffer, which falls back to its span at once. + finish(marked: boolean): void { + this.finished = { marked } + this.keyframe = undefined + this.buffer.givePlaceUp(this) + this.wake?.() + } + + /** + * The recording's packets as the recording management reads them: each queued packet in turn, waiting for the next until the recording finishes or its + * stream's signal aborts. A close never waits on the next segment. + * @param signal - The stream's signal, which a close aborts. + * @yields Each packet. + */ + async* packets(signal?: AbortSignal): AsyncGenerator { + signal?.addEventListener('abort', () => this.wake?.(), { once: true }) + + for (;;) { + if (signal?.aborted === true) { + return + } + + const data = this.queue.shift() + + if (data !== undefined) { + yield { data, isLast: false } + continue + } + + if (this.finished !== undefined) { + if (this.finished.marked) { + yield endMarker() + } + + return + } + + await new Promise((resolve) => { + this.wake = resolve + }) + this.wake = undefined + } + } + + // Sends each segment the buffer holds whole from the place on. + private cut(): void { + for (let segment = this.closing(); segment !== undefined; segment = this.closing()) { + this.send(segment) + } + } + + /* The segment the place opens that can leave now, if one can: closed at the first keyframe at or past the target, or at the last keyframe before the + * segment would reach the cap, or, for a stretch that alone reaches the cap, at the keyframe that closes it. A segment whose closing keyframe arrived in a + * fragment that has not ended waits for that fragment's end. + */ + private closing(): Segment | undefined { + const open = this.keyframe + + if (open === undefined) { + return undefined + } + + const { pictures, sounds } = this.stretch(open) + const { fragments } = this.buffer + let last: number | undefined + let sounded = 0 + + for (let index = 1; index < pictures.length; index++) { + const keyframe = pictures[index] + + if (!keyframe.sync) { + continue + } + + while ((sounded < sounds.length) && (sounds[sounded].time < keyframe.time)) { + sounded++ + } + + if ((last !== undefined) && (this.length(pictures, index, sounds, sounded) >= SEGMENT_CAP)) { + return this.segment(pictures, sounds, last, false) + } + + if (keyframe.fragment >= fragments) { + return undefined + } + + if ((last === undefined) && (this.length(pictures, index, sounds, sounded) >= SEGMENT_CAP)) { + return this.segment(pictures, sounds, index, true) + } + + if (keyframe.time - open.time >= SEGMENT_TARGET) { + return this.segment(pictures, sounds, index, false) + } + + last = index + } + + // A segment that would reach the cap before its next keyframe arrives closes at its last keyframe. + return (last !== undefined) && (this.length(pictures, pictures.length, sounds, sounds.length) >= SEGMENT_CAP) + ? this.segment(pictures, sounds, last, false) + : undefined + } + + // The buffer's walk from a keyframe on, which a view's opening reads too, its sound left out of a recording without sound. + private stretch(open: BufferedSample): BufferWalk { + const walked = this.buffer.walk(open) + + return (this.audio === undefined) + ? { pictures: walked.pictures, sounds: [] } + : walked + } + + // The segment of the pictures before a closing keyframe and the sound timed before it. + private segment(pictures: readonly BufferedSample[], sounds: readonly BufferedSample[], close: number, overCap: boolean): Segment { + const next = pictures[close] + + return { + next, + overCap, + pictures: pictures.slice(0, close), + sounds: sounds.filter(({ time }) => time < next.time), + } + } + + // 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[] { + let last = this.pictureDuration + + return pictures.map(({ duration }) => { + last = duration ?? last + + return last + }) + } + + /* Where a segment closed as it stands ends its sound, on the stream's sound ticks, at a run's end and at an end the stream caused alike: the least + * decode time the next run's first sound can take on the recording, read back through this segment's own anchor. The next run's sound is anchored by + * the same division from the recording's picture time at the end of this segment, and its first sound stands at or after the keyframe its segment opens + * on, which means it takes no decode time on the recording below that picture time on the sound's timescale, rounded down, however each anchor rounds. A close + * that ends the recording has no next run, and the same bound ends its last sound no later than its picture's end. A recording without sound carries + * none to end, and reads it on the picture's own timescale. + */ + private soundEnd(open: BufferedSample, pictureEnd: bigint): bigint { + const { timescale } = this.audio ?? this.video + + return pictureEnd * BigInt(timescale) / BigInt(this.video.timescale) - this.soundOffset(open) + } + + // How far a segment's sound stands on the recording from its stream's own decode times, on the sound's timescale: the recording's picture time at the + // segment's opening keyframe less that keyframe's own decode time, divided toward zero. + private soundOffset(open: BufferedSample): bigint { + const { timescale } = this.audio ?? this.video + + return (this.pictureTime - open.decodeTime) * BigInt(timescale) / BigInt(this.video.timescale) + } + + /* The duration a segment writes for a sound: the one the buffer settled, the distance to its track's next decode time, or for an unsettled sound, its + * run's newest, the duration its own packet states, converted from Opus's clock to its track's timescale. The packet is read only here, for the few + * sounds a segment carries unsettled, and one whose duration the voice reader cannot read keeps the buffer's stand-in, or the last its track sent. + */ + private durationOf({ data, duration = this.soundDuration, settled, track }: BufferedSample): number { + if (!settled) { + const stated = readOpusVoice(data).duration + + if (stated > 0) { + return Math.round(stated * track.timescale / OPUS_RATE) + } + } + + return duration + } + + // The octets of a segment's moof and mdat for the first pictures and sounds given. + private length(pictures: readonly BufferedSample[], pictureCount: number, sounds: readonly BufferedSample[], soundCount: number): number { + const octets = (samples: readonly BufferedSample[], count: number): number => samples.slice(0, count).reduce((total, { data }) => total + data.length, 0) + + return segmentLength([ + { + octets: octets(pictures, pictureCount), + samples: pictureCount, + }, + { + octets: octets(sounds, soundCount), + samples: soundCount, + }, + ]) + } + + /* 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. + */ + private send({ 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, + })).filter(({ own }) => own > 0) + const video: SegmentSample[] = [] + const audio: SegmentSample[] = [] + + for (const [index, { compositionOffset, data, sync }] of pictures.entries()) { + video.push({ + compositionOffset, + data, + duration: durations[index], + sync, + }) + } + + this.pictureDuration = durations.at(-1)! + this.droppedSamples += sounds.length - timed.length + + for (const [index, { own, sound }] of timed.entries()) { + const { compositionOffset, data, decodeTime, sync } = sound + + audio.push({ + compositionOffset, + data, + duration: (end !== undefined) && (index === timed.length - 1) + ? Math.min(own, Number(end - decodeTime)) + : own, + sync, + }) + 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 }, + })) + // 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++ + this.keyframe = next + this.sentUpTo = next?.time + + if (overCap) { + this.routes.capped() + } + + this.wake?.() + } +} + +/** + * The recorder of a camera that records from its camera buffer: the recording delegate its recording management serves a hub's recording through, and the + * driver of the recording reason of the recorded tier's keeper, which holds the tier while the user's switch allows recording and the camera is in + * service, its accessory published and its source not stated away. + * + * The recording reason follows the policy's `recordingInService`, recording allowed and the camera in service: read once as {@link configure} + * subscribes it and raised when it reads true, raised at each move to true and released at each move to false, at a reset and at a removal. Neither the + * recording state nor a configuration reaches the recorder through the delegate's calls, which do nothing. + * + * The recorder decides a hub's open once, through {@link admit}, before the recording management answers it, and each open it declines is refused in that + * answer as busy: no stream opens and no recording event is told. An open on a camera out of service is refused with no problem, and one on a buffer + * that is not ready with one `recording-declined` problem. An open on a ready buffer asks the plugin's shouldRecord, where it gives one, with the start + * `recording-started` would carry, and one it declines is refused with no problem, as is one whose call stopped the recorder whatever it answered: the + * camera left service, even for a moment, recording was turned off, the camera was switched off or manually disabled, or the camera was reset or + * removed. An open it admits begins a recording once it is answered, told of through `recording-started` with that same start, which yields an + * initialization segment of the picture and, unless Recording Audio Active reads off at the open, the sound, and then segments, those the buffer holds + * whole at once and each later one as the fragment holding its closing keyframe ends. A recording ends once, after its last whole segment, its + * `recording-ended` emitted as the end is decided: at the hub's acknowledgement or close, and at an end the recorder makes itself, which yields the end + * marker, at recording no longer allowed or the camera going out of service, a reset or a removal, a long gap, a change of a carried track's + * description, a ceiling's trim past its place, and a throw from its own reading of the buffer, which takes its place off. An end the stream caused, the + * camera's source stated away while recording is still allowed and the accessory published, a long gap or a change of a carried track's description, + * comes after the segment in progress closed as it stands, as a run's end closes it, and every other end the recorder makes drops that segment. + */ +export class BufferRecorder implements CameraRecordingDelegate, Disposable { + private readonly options: BufferRecorderOptions + private recording?: OpenRecording + // Whether the plugin's shouldRecord has answered with neither true nor false, which is reported as a plugin-failure problem once for the recorder. + private answeredOtherwise = false + /* How many times the recorder has stopped: at each move of the policy's `recordingInService` to false, which the camera leaving service, recording + * turned off and the camera switched off or manually disabled each make, at a reset and at a removal. An open compares its reading before the plugin's + * call with its reading after it, within that one call alone: a stop inside the call refuses the open whatever the plugin answered, and the count is + * never reset, since no reading outlives its call. + */ + private stops = 0 + + /** + * Makes a recorder, which holds nothing until it is configured. + * @param options - The recorder's options. + */ + constructor(options: BufferRecorderOptions) { + this.options = options + } + + // The recorded tier as the recorder's sentences name it. + private get tierName(): string { + const { sensorUUID, tierId } = this.options + + return `the video tier ${tierId} of the video sensor "${sensorUUID}"` + } + + /** + * Subscribes the policy's `recordingInService`, which raises the keeper's recording reason at each move to true, and at each move to false stops the + * recorder and then releases the reason, and raises it now when the user's switch allows recording and the camera is in service already. A move to + * false while `recordingPublished` still reads true, recording allowed and the accessory published, is the camera's source stated away: the stop + * serves the segment in progress before the recording's end, and every other move drops it. The reason is released only where the camera still reads + * out of service once the stop returns, since a listener of the recording's end may state the source available again or turn recording on inside its + * call, which raises the reason while the stop runs. + */ + configure(): void { + const { keeper, policy } = this.options + + policy.subscribeDerivation('recordingInService', (allowed) => { + if (allowed) { + keeper.raise('recording') + } else { + this.stop(policy.recordingPublished()) + + if (!policy.recordingInService()) { + keeper.release('recording') + } + } + }) + + if (policy.recordingInService()) { + keeper.raise('recording') + } + } + + // The policy's recording state drives the keeper's recording reason, which is why the call does nothing. + updateRecordingActive(): void { + // Nothing to do. + } + + // A camera that records from its buffer offers no configuration to select, and the call never comes. + updateRecordingConfiguration(): void { + // Nothing to do. + } + + /** + * Decides a hub's recording open, which the recording management asks before it answers the open: refused as busy while the camera is out of service, + * while the buffer is not ready, or where the plugin's shouldRecord answers false or its call stopped the recorder, and otherwise admitted with the + * function that serves the recording from what the decision read. The decision is made once and the recorder holds nothing until it is served. + * @param streamId - The hub's recording stream. + * @returns The refusal, or the admission and its serving function. + */ + admit(streamId: number): RecordingAdmission { + const { policy, reporter, sensorUUID, tierId, tierTable } = this.options + + // A camera out of service holds no tier, which is why its refusal comes first and raises no problem, the plugin having done nothing wrong. + if (!policy.inService()) { + return this.refused(streamId, 'the camera is out of service') + } + + const tier = tierTable(sensorUUID)?.videoTiers.get(tierId)?.buffer + const video = tier?.tracks?.video + const head = tier?.head + + // A ready buffer holds a picture's description and a keyframe at its head. + if ((tier?.ready !== true) || (video === undefined) || (head === undefined)) { + reporter.problem({ + kind: 'recording-declined', + level: 'warning', + sensorUUID, + sentence: this.declinedSentence(tier), + tierId, + }) + + return this.refused(streamId, 'the camera buffer is not ready') + } + + // The plugin is asked only once the library would record, with the start the recording-started event then carries, and its decline raises no problem, + // since the plugin chose it. Plugin code inside the call can stop the recorder, taking the camera out of service even for a moment, turning recording + // off, or resetting or removing the camera. The stop count is read around the call and such an open is refused whatever the answer. + const start: CameraRecordingStart = { sensorUUID, streamId, tierId } + const stops = this.stops + + if (!this.pluginAllows(start) || (this.stops !== stops)) { + return this.refused(streamId, (this.stops !== stops) + ? 'the recorder stopped during the plugin\'s shouldRecord' + : 'the plugin\'s shouldRecord declined it') + } + + return { + admitted: true, + serve: signal => this.serve({ head, start, tier, video }, signal), + } + } + + /** + * Serves a hub's recording from the recorded tier's buffer as {@link admit} decides it, for a caller that asks the delegate alone: the recording's packets + * for an open it admits, and a throw of the refusal for one it refuses. + * @param streamId - The hub's recording stream. + * @param signal - The stream's signal, which a close aborts. + * @returns The recording's packets. + * @throws HDSProtocolError carrying the refusal's reason, busy, for an open the recorder refuses. + */ + handleRecordingStreamRequest(streamId: number, signal?: AbortSignal): AsyncIterable { + const admission = this.admit(streamId) + + if (!admission.admitted) { + throw new HDSProtocolError(admission.reason) + } + + return admission.serve(signal) + } + + // Serves an admitted recording: it opens at the keyframe the admission read at the buffer's head, takes its place on the tier, is told of and begins. + private serve({ head, start, tier, video }: AdmittedRecording, signal?: AbortSignal): AsyncIterable { + const { policy, reporter, sensorUUID, started, tierId } = this.options + const { streamId } = start + const recording: OpenRecording = new OpenRecording(tier, video, head, { + audio: policy.recordingAudioActive + ? tier.tracks?.audio + : undefined, + routes: { + capped: () => { + reporter.problem({ + kind: 'segment-over-cap', + level: 'warning', + sensorUUID, + sentence: `The recording of ${this.tierName} sent a segment whose stretch from one keyframe to the next reached the cap of ${SEGMENT_CAP} ` + + 'octets on an uploaded segment: it left as it stood.', + tierId, + }) + }, + end: (outcome) => { + this.end(recording, outcome, true) + }, + }, + streamId, + }) + + this.recording = recording + tier.takePlace(recording) + started(start) + recording.begin() + + return recording.packets(signal) + } + + /** + * Ends the recording the hub acknowledged, and does nothing for one already ended. + * @param streamId - The hub's recording stream. + */ + acknowledgeStream(streamId: number): void { + this.closed(streamId, 'ended') + } + + /** + * Ends the recording the hub or its connection closed, by the close's reason, and does nothing for one already ended. + * @param streamId - The hub's recording stream. + * @param reason - The close's reason, absent for the connection's close. + */ + closeRecordingStream(streamId: number, reason: HDSProtocolSpecificErrorReason | undefined): void { + this.closed(streamId, outcomeOf(reason)) + } + + /** + * Ends an open recording at the long gap, after its segment in progress closed as it stands, which the keeper tells of once the long-gap time passes + * since the last picture it read from the tier's buffer, while the buffer still holds the run. That order rests on the keeper reading each picture + * first, inside the buffer's take and before the tier's demand moves its own clock on, and on a reconnect telling each keeper before each tier table: + * at the deadline the keeper's clock and the demand's share, the gap is told before the demand's end empties the buffer. + */ + lapsed(): void { + this.closeSegment() + this.end(this.recording, 'gap', true) + } + + /** + * Ends an open recording as cancelled, dropping its segment in progress, and releases the keeper's recording reason, at a factory reset. + */ + reset(): void { + this.stop() + this.options.keeper.release('recording') + } + + // A removal ends the recorder as a factory reset does. + [Symbol.dispose](): void { + this.reset() + } + + /* Recording is no longer allowed or the camera went out of service, or the camera resets or is removed: the stop is counted and an open recording ends + * as cancelled, after its segment in progress closed as it stands where the camera's source alone took the camera out of service, and without it at + * every other stop. The caller releases the keeper's recording reason after the stop: the buffer still holds the run as the segment closes. + */ + private stop(sourceAway = false): void { + this.stops++ + + if (sourceAway) { + this.closeSegment() + } + + this.end(this.recording, 'cancelled', true) + } + + /* Closes the open recording's segment in progress as it stands, and does nothing where no recording is open. An end the stream caused, the camera's + * source stated away, a long gap or a changed description, serves the segment in progress before the end marker, which means the recording keeps the event's + * last seconds. An end the user or HomeKit asked for drops that segment. The source's close and the gap's run here, through the reporter's guard as the + * library's failure, since the keeper calls the gap's end from a timer with no guard of its own and the stop runs inside the recompute a statement of + * the source makes: a throw raises one library-failure problem, and the caller goes on to end the recording with its marker, without that segment. A + * changed description's close runs inside the buffer's own guarded step. + */ + private closeSegment(): void { + const { recording } = this + + if (recording === undefined) { + return + } + + const { reporter, sensorUUID, tierId } = this.options + + reporter.guard('library-failure', () => recording.closeAsItStands(), + `The recording of ${this.tierName} failed to close its segment in progress and ends without that segment`, { sensorUUID, tierId }) + } + + private closed(streamId: number, outcome: CameraRecordingOutcome): void { + const { recording } = this + + if (recording?.streamId === streamId) { + this.end(recording, outcome, false) + } + } + + // Ends a recording once, while it is the open one: its packets finish, its place is given up in the same turn, and its end is told as it is decided. + private end(recording: OpenRecording | undefined, outcome: CameraRecordingOutcome, marked: boolean): void { + if ((recording === undefined) || (recording !== this.recording)) { + return + } + + const { ended, reporter, sensorUUID, tierId } = this.options + const { dropped, seconds, segments, streamId } = recording + + this.recording = undefined + recording.finish(marked) + reporter.debug(BUFFER_RECORDER_DEBUG, 'recording-ended', () => ({ + dropped, + outcome, + seconds, + segments, + sensorUUID, + sentence: `The recording of stream ${streamId} ended ${outcome} after ${counted(segments, 'segment')}, ${seconds.toFixed(3)} seconds long, ` + + `${dropped} of its samples dropped.`, + streamId, + tierId, + })) + ended({ + outcome, + segments, + sensorUUID, + streamId, + tierId, + }) + } + + // Answers an open the recorder refuses, after one debug event naming the cause it read, since a refused open makes no stream and writes none of a + // stream's lines. + private refused(streamId: number, cause: string): RecordingAdmission { + this.options.reporter.debug(BUFFER_RECORDER_DEBUG, 'recording-refused', () => ({ + cause, + sentence: `Refusing the recording of stream ${streamId} as busy: ${cause}.`, + streamId, + })) + + return REFUSED + } + + /* Whether the plugin lets a recording the library would serve open, by its shouldRecord where it gives one, asked on the spot: false declines it, and + * every other answer lets it through. An answer that is neither true nor false is the plugin's failure, reported as a plugin-failure problem once for + * the recorder, and a promise among such answers has its rejection reported as one too, which means none goes unhandled. A throw is reported as one at each call, + * each with its own error. + */ + private pluginAllows(start: CameraRecordingStart): boolean { + const { reporter, sensorUUID, shouldRecord, tierId } = this.options + + if (shouldRecord === undefined) { + return true + } + + const failure = `The shouldRecord function failed for a recording of ${this.tierName}, and the library records it` + let answer: unknown + + try { + answer = shouldRecord(start) + } catch (error) { + reporter.failure('plugin-failure', failure, error, { sensorUUID, tierId }) + + return true + } + + if (typeof answer === 'boolean') { + return answer + } + + if (!this.answeredOtherwise) { + this.answeredOtherwise = true + reporter.problem({ + kind: 'plugin-failure', + level: 'error', + sensorUUID, + sentence: `The shouldRecord function answered a recording of ${this.tierName} with neither true nor false, and the library records it.`, + tierId, + }) + } + + reporter.rejection('plugin-failure', answer, failure, undefined, { sensorUUID, tierId }) + + return true + } + + // Why an open is declined: a stream whose head keyframe a decoder cannot read, named in the words of the demand's own stream-fault problem, or a buffer + // still filling. + private declinedSentence(tier: TierBuffer | undefined): string { + const video = tier?.tracks?.video + const head = tier?.head + const why = (video !== undefined) && (head !== undefined) && !decodable(head.data, video.parameterSets) + ? 'its stream carries a keyframe without its video, sequence and picture parameter sets, in its sample or its initialization segment' + : `its camera buffer does not yet hold the prebuffer of ${counted(this.options.prebuffer, 'millisecond')}` + + return `The library declined a hub's recording of ${this.tierName}, because ${why}.` + } +} diff --git a/src/lib/camera/recording/CMAFRecordingManagement.spec.ts b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts new file mode 100644 index 000000000..0e4b74609 --- /dev/null +++ b/src/lib/camera/recording/CMAFRecordingManagement.spec.ts @@ -0,0 +1,3849 @@ +import type { MockIngestAnswer, MockIngestRequest, MockIngestServerOptions } from '../../../test-utils/MockIngestServer.js' +import type { TrackFixture } from '../../../test-utils/mp4Fixtures.js' +import type { Characteristic as CharacteristicType } from '../../Characteristic.js' +import type { ControllerAccessoryContext } from '../../controller/index.js' +import type { AccessoryInformation, CameraOperatingMode, CameraRecordingManagement } from '../../definitions/index.js' +import type { HAPConnection } from '../../util/eventedhttp.js' +import type { BufferUploadCommandRequest, CameraBufferEvent, CameraRecordingPublishingPointPayload } from '../capabilities/cameraBuffer.js' +import type { CameraClientCertificateRequest, CameraClientCSRResponse, CameraKeyPayload } from '../capabilities/provisioning.js' +import type { CameraReporter } from '../diagnostics/CameraReporter.js' +import type { RecordingPacket } from '../RecordingManagement.js' +import type { TierStream } from '../StreamingOptions.js' +import type { CMAFRecordingManagementOptions } from './CMAFRecordingManagement.js' +import type { ServedRecording, ServedRecordingsOptions } from './ServedRecording.js' + +import { Buffer } from 'node:buffer' +import { createDecipheriv, randomBytes, verify, X509Certificate } from 'node:crypto' +import http2 from 'node:http2' +import process from 'node:process' +import { setTimeout as sleep } from 'node:timers/promises' + +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { + bufferCamera, + createCameraControllerOptions, + frames, + handPublishedContext, + MockDelegate, + mockRecordingOptions, + mockStreamingOptions, + motionZonesFunction, + savedMapOf, + twoSensorCameraOptions, +} from '../../../test-utils/cameraFixtures.js' +import { CertificateAuthority, signingRequestKey } from '../../../test-utils/certificateAuthority.js' +import { buildEmitterConnection } from '../../../test-utils/connectionFixtures.js' +import { DataStreamClient } from '../../../test-utils/dataStreamClient.js' +import { captureDebug, captureDebugEvents } from '../../../test-utils/engineDebug.js' +import { INGEST_CERTIFICATES, MockIngestServer } from '../../../test-utils/MockIngestServer.js' +import { + avc1SampleEntry, + initializationSegment, + mediaFragment, + skeletonPackets, + TIER_STREAM_PARAMETER_SETS, + tierStreamInitialization, +} from '../../../test-utils/mp4Fixtures.js' +import { detachedReporter, namedReporter, problemsOf } from '../../../test-utils/reporterFixtures.js' +import { deferred, settle } from '../../../test-utils/settle.js' +import { Accessory, Categories, MDNSAdvertiser } from '../../Accessory.js' +import { Bridge } from '../../Bridge.js' +import { Access, Characteristic } from '../../Characteristic.js' +import { CameraController } from '../../controller/index.js' +import { HDSProtocolSpecificErrorReason, Protocols, Topics } from '../../datastream/index.js' +import { HAPStatus } from '../../HAPServer.js' +import { PermissionTypes } from '../../model/AccessoryInfo.js' +import { HAPStorage } from '../../model/HAPStorage.js' +import { RecordingProvisioning } from '../../model/RecordingProvisioning.js' +import { Service } from '../../Service.js' +import { EventedHTTPServer } from '../../util/eventedhttp.js' +import { libraryVersion } from '../../util/libraryVersion.js' +import * as uuid from '../../util/uuid.js' +import { + BufferActivity, + BufferEventCommandType, + BufferUploadCommandType, + BufferUploadStopAction, + CameraBufferEventType, + CMAFError, + decodeBufferEventCommandResponse, + decodeBufferUploadCommandResponse, + encodeBufferActivityCommandRequest, + encodeBufferEventCommandRequest, + encodeBufferUploadCommandRequest, + encodeCameraRecordingPublishingPoint, +} from '../capabilities/cameraBuffer.js' +import { + decodeCameraClientCertificateRequest, + decodeCameraClientCertificateStatus, + decodeCameraClientCSRResponse, + decodeCameraKeyID, + encodeCameraClientCertificateRequest, + encodeCameraClientCSRRequest, + encodeCameraKey, + encodeCameraKeyID, +} from '../capabilities/provisioning.js' +import { MotionAttribution } from '../MotionAttribution.js' +import { OperatingModePolicy } from '../OperatingModePolicy.js' +import { EventTriggerOption } from '../RecordingManagement.js' +import { BufferRecorder } from './BufferRecorder.js' +import { SKIP_AHEAD } from './CameraEventQueue.js' +import { closingMediaPlaylist } from './clipPackaging.js' +import { contentKeyOf, keyAttributes } from './clipSealing.js' +import { CMAFRecordingManagement } from './CMAFRecordingManagement.js' +import { IngestSession } from './IngestSession.js' +import { ProducerReferenceTimeWriter } from './ProducerReferenceTimeWriter.js' +import { SERVED_RECORDING_GRACE, ServedRecordings } from './ServedRecording.js' + +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 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(), + sensorUUID: 'b1b2c3d4-0000-4000-8000-00000000000a', +} +const DAY = 24 * 60 * 60 * 1000 +const HOUR = 60 * 60 * 1000 +const NONCE = Buffer.alloc(32, 0x4E) +const POINT = { + serverCACertificates: [ + { + certificate: Buffer.from('3082a1', 'hex'), + }, + ], + url: 'https://ingest.example/v1/token/', +} +const CAMERA_KEY = { + key: Buffer.alloc(32, 0x5A), + keyNumber: 7n, +} + +// A Camera Key a byte short, which no content key derives from, and the reason a camera holding it warns with. +const SHORT_KEY = { + key: Buffer.alloc(31, 0x5A), + keyNumber: 7n, +} +const SHORT_KEY_REASON = 'the camera cannot encrypt its video and audio with the Camera Key it holds: A Camera Key must be thirty-two bytes long.' +const authority = new CertificateAuthority() + +// An accessory's context, which reads published where it carries a username and not published where it carries none, this helper's own choice for these +// rows, since the clip path reads no published state. +function context(username?: string, accessoryUUID = CAMERA): ControllerAccessoryContext { + return { + accessoryInformation: new Service.AccessoryInformation() as AccessoryInformation, + accessoryUUID, + published: username !== undefined, + username, + } +} + +// 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. +function options(): CMAFRecordingManagementOptions { + return { + feed: new ServedRecordings(QUIET_FEED), + policy: new OperatingModePolicy(), + reporter: detachedReporter(), + } +} + +// A management published under a username, as the camera's accessory hands it its context. +function published(username = USERNAME): CMAFRecordingManagement { + const management = new CMAFRecordingManagement(options()) + + management.handleAccessoryContext(context(username)) + + return management +} + +function characteristic(management: CMAFRecordingManagement, type: typeof Characteristic.CameraKey): CharacteristicType { + const { buffer, certificate, key } = management.services + + return [buffer, certificate, key].find(service => service.testCharacteristic(type))!.getCharacteristic(type) +} + +async function write(management: CMAFRecordingManagement, type: typeof Characteristic.CameraKey, value: string, connection: HAPConnection): Promise { + return await characteristic(management, type).handleSetRequest(value, connection) +} + +async function writeCertificate(management: CMAFRecordingManagement, request: CameraClientCertificateRequest, connection: HAPConnection): Promise { + return await write(management, Characteristic.CameraClientCertificate, encodeCameraClientCertificateRequest(request), connection) +} + +async function writeKey(management: CMAFRecordingManagement, cameraKey: CameraKeyPayload, connection: HAPConnection): Promise { + return await write(management, Characteristic.CameraKey, encodeCameraKey(cameraKey), connection) +} + +async function writePoint(management: CMAFRecordingManagement, point: CameraRecordingPublishingPointPayload, connection: HAPConnection): Promise { + return await write(management, Characteristic.CameraRecordingPublishingPoint, encodeCameraRecordingPublishingPoint(point), connection) +} + +async function signingRequest(management: CMAFRecordingManagement, connection: HAPConnection): Promise { + return decodeCameraClientCSRResponse(await write(management, Characteristic.CameraClientCSR, encodeCameraClientCSRRequest({ nonce: NONCE }), connection) as string) +} + +async function read(management: CMAFRecordingManagement, type: typeof Characteristic.CameraKey, connection: HAPConnection): Promise { + return await characteristic(management, type).handleGetRequest(connection) as string +} + +async function needsUpdate(management: CMAFRecordingManagement, connection: HAPConnection): Promise { + return decodeCameraClientCertificateStatus(await read(management, Characteristic.CameraClientCertificateStatus, connection)).needsUpdate +} + +// A signing request through Camera Client CSR, and a certificate the test authority issues for its key, valid for the days given. +async function certify(management: CMAFRecordingManagement, connection: HAPConnection, days = 60): Promise<{ ca: Buffer, clientCertificate: Buffer }> { + const { csr } = await signingRequest(management, connection) + + return { + ca: authority.certificate, + clientCertificate: authority.issue(csr, new Date(Date.now() - DAY), new Date(Date.now() + days * DAY)), + } +} + +// A whole provisioning: the signing request, the certificate, the Camera Key and the publishing point, as a hub writes them. +async function provision(management: CMAFRecordingManagement, connection: HAPConnection, days = 60): Promise<{ ca: Buffer, clientCertificate: Buffer }> { + const credential = await certify(management, connection, days) + + await writeCertificate(management, credential, connection) + await writeKey(management, CAMERA_KEY, connection) + await writePoint(management, POINT, connection) + + return credential +} + +// Every event a Query from the first number answers, read back through Buffer Event Command. +async function queried(management: CMAFRecordingManagement, connection: HAPConnection, sequenceNumber = 0n): Promise { + const request = encodeBufferEventCommandRequest({ command: BufferEventCommandType.QUERY, sequenceNumber }) + + return decodeBufferEventCommandResponse(await write(management, Characteristic.BufferEventCommand, request, connection) as string).events +} + +// The clip rows' video track and its fragments: an H.264 track whose every fragment lasts a whole number of seconds, which is why each segment's duration reads exactly. +const VIDEO: TrackFixture = { + handler: 'vide', + id: 1, + sampleEntry: avc1SampleEntry(1920, 1080, 0x4D, 0x00, 0x28), + timescale: 90000, +} +const SAMPLES = 120 +const SAMPLE_DURATION = 3000 +const FRAGMENT_TICKS = 360000n +const FRAGMENT = 4n << 32n +const WALL_CLOCK = Date.parse('2026-11-12T00:00:00.000Z') + +// A few milliseconds as an NTP time span, for a Start or a Stop just off a boundary. +const A_FEW_MILLISECONDS = (3n << 32n) / 1000n + +const POINT_PATH = '/point/' +const SESSION = 101n + +// The User-Agent a clip's requests carry for the Accessory Information the clip camera names. +const USER_AGENT = `HKSV/3.0 HAP-NodeJS/${libraryVersion()} (Acme Labs Inc.; Cam ra 2; Unknown)` + +// A camera whose management is provisioned against a mock publishing point, its policy allowing recording, with a recording begun on its feed. +interface ClipCamera extends AsyncDisposable { + readonly connection: HAPConnection + readonly feed: ServedRecordings + readonly information: AccessoryInformation + readonly management: CMAFRecordingManagement + readonly mock: MockIngestServer + readonly operatingMode: CameraOperatingMode + readonly policy: OperatingModePolicy + readonly recordingService: CameraRecordingManagement + // The recording the camera's stream is serving, its writer and wall clock, and each of its fragments' bytes as served. + recording: ServedRecording + served: Buffer[] + wallClock: number + writer: ProducerReferenceTimeWriter +} + +// A clip camera, its management reporting through the reporter given, by default one of no camera, which means each problem prints its bare sentence. +async function clipCamera( + { key = true, reporter = detachedReporter(), ...mockOptions }: MockIngestServerOptions & { key?: boolean, reporter?: CameraReporter } = {}, +): Promise { + const connection = buildEmitterConnection() + const feed = new ServedRecordings(QUIET_FEED) + const policy = new OperatingModePolicy() + const recordingService = new Service.CameraRecordingManagement('', '') + const operatingMode = new Service.CameraOperatingMode('', '') + const information = new Service.AccessoryInformation() as AccessoryInformation + + // Each User-Agent field is made printable and free of the comment's syntax, and an empty one reads Unknown. + information.setCharacteristic(Characteristic.Manufacturer, 'Acme (Labs); Inc.') + information.setCharacteristic(Characteristic.Model, 'Caméra\t2') + information.setCharacteristic(Characteristic.FirmwareRevision, '') + policy.bindRecording(recordingService, operatingMode) + recordingService.updateCharacteristic(Characteristic.Active, true) + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, true) + + const mock = await MockIngestServer.start({ clientCAs: authority.pem, ...mockOptions }) + const management = new CMAFRecordingManagement({ feed, policy, reporter }) + + management.handleAccessoryContext({ + accessoryInformation: information, + accessoryUUID: CAMERA, + published: true, + username: USERNAME, + }) + await writeCertificate(management, await certify(management, connection), connection) + + if (key) { + await writeKey(management, CAMERA_KEY, connection) + } + + await writePoint(management, { + serverCACertificates: [ + { + certificate: new X509Certificate(INGEST_CERTIFICATES.serverCA).raw, + }, + ], + url: mock.url, + }, connection) + + const camera: ClipCamera = { + async [Symbol.asyncDispose]() { + await management.destroy() + feed[Symbol.dispose]() + policy[Symbol.dispose]() + await mock[Symbol.asyncDispose]() + }, + connection, + feed, + information, + management, + mock, + operatingMode, + policy, + recording: feed.begin(), + recordingService, + served: [], + wallClock: WALL_CLOCK, + writer: new ProducerReferenceTimeWriter(), + } + + camera.recording.add(camera.writer.writePacket(initializationSegment(VIDEO), camera.wallClock)) + + return camera +} + +// Begins the camera's next recording, a stream whose first fragment the wall clock given places. +function begin(camera: ClipCamera, wallClock: number): void { + camera.recording = camera.feed.begin() + camera.served = [] + camera.wallClock = wallClock + camera.writer = new ProducerReferenceTimeWriter() + camera.recording.add(camera.writer.writePacket(initializationSegment(VIDEO), wallClock)) +} + +// Serves fragments live on the camera's recording, each decode time counting on from the last. +function serve(camera: ClipCamera, count = 1): void { + for (let fragment = 0; fragment < count; fragment++) { + const written = camera.writer.writePacket(mediaFragment({ + decodeTime: BigInt(camera.served.length) * FRAGMENT_TICKS, + defaultDuration: SAMPLE_DURATION, + samples: SAMPLES, + trackId: 1, + }), camera.wallClock) + + camera.recording.add(written) + camera.served.push(written.fragments[0].bytes) + } +} + +function placeOf(camera: Pick, index: number, recording = camera.recording): bigint { + return recording.fragment(index)!.place +} + +function endOf(camera: Pick, index: number, recording = camera.recording): bigint { + return BigInt.asUintN(64, placeOf(camera, index, recording) + FRAGMENT) +} + +// Which of a recording's fragments still hold their bytes. +function held(recording: ServedRecording): boolean[] { + return Array.from({ length: recording.length }, (_, index) => recording.fragment(index)?.bytes !== undefined) +} + +// A hub's verdict on a fragment through Buffer Activity Command. +async function judge(camera: Pick, index: number, record = true, recording = camera.recording): Promise { + const request = encodeBufferActivityCommandRequest({ + activity: record + ? BufferActivity.SHOULD_RECORD + : BufferActivity.SHOULD_NOT_RECORD, + duration: FRAGMENT, + start: placeOf(camera, index, recording), + }) + + await characteristic(camera.management, Characteristic.BufferActivityCommand).handleSetRequest(request, camera.connection) +} + +// A hub's Buffer Upload Command, answered with its Clip ID. +async function command(camera: Pick, request: BufferUploadCommandRequest): Promise { + const upload = characteristic(camera.management, Characteristic.BufferUploadCommand) + + return decodeBufferUploadCommandResponse(await upload.handleSetRequest(encodeBufferUploadCommandRequest(request), camera.connection) as string).clipID +} + +async function startAt(camera: Pick, start: bigint, sessionID = SESSION): Promise { + return await command(camera, { command: BufferUploadCommandType.START, sessionID, start }) +} + +async function stopAt( + camera: Pick, + stop: bigint, + stopAction: BufferUploadStopAction = BufferUploadStopAction.FINALIZE, + sessionID = SESSION, +): Promise { + return await command(camera, { + command: BufferUploadCommandType.STOP, + sessionID, + stop, + stopAction, + }) +} + +// Waits for a condition the upload reaches on its own, checking often and for longer than any repeat's wait. +async function eventually(check: () => T | Promise): Promise { + return await vi.waitFor(check, { interval: 10, timeout: 8000 }) +} + +// The events a clip queued, in order. +async function clipEvents(camera: Pick, clipID: bigint): Promise { + return (await queried(camera.management, camera.connection)).filter(event => 'cmafSessionID' in event && event.cmafSessionID === clipID) +} + +// The event that ended a clip, Session Stop or a CMAF error, once the clip has queued it. +async function ended(camera: Pick, clipID: bigint): Promise { + return await eventually(async () => { + const end = (await clipEvents(camera, clipID)).find(({ type }) => type !== CameraBufferEventType.CMAF_SESSION_START) + + expect(end).toBeDefined() + + return end! + }) +} + +// Each object's path beneath the publishing point, in the order the mock read them. +function paths(camera: Pick): string[] { + return camera.mock.requests.map(({ path }) => path.slice(POINT_PATH.length)) +} + +// The bytes of the last request the mock read at a path, as the camera sent them. +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. +function body(camera: Pick, path: string, cameraKey: CameraKeyPayload = CAMERA_KEY): Buffer { + const bytes = sent(camera, path) + + if (!path.endsWith('.m4s')) { + return bytes + } + + const decipher = createDecipheriv('aes-256-gcm', contentKeyOf(cameraKey).key, bytes.subarray(0, 16), { authTagLength: 16 }) + + decipher.setAuthTag(bytes.subarray(-16)) + + return Buffer.concat([ + decipher.update(bytes.subarray(16, -16)), + decipher.final(), + ]) +} + +// 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() + + return ({ path }) => { + const object = path.slice(POINT_PATH.length) + const send = sends.get(object) ?? 0 + + sends.set(object, send + 1) + + return script[object]?.[send] ?? { status: 201 } + } +} + +// The segment paths of a folder, from the first. +function segmentsOf(clip: bigint, count: number): string[] { + return Array.from({ length: count }, (_, index) => `session_${clip}/high/segment_${1001 + index}.m4s`) +} + +// 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. +function closing(count: number): string { + return closingMediaPlaylist({ + keyAttributes: keyAttributes(contentKeyOf(CAMERA_KEY)), + segments: Array.from({ length: count }, () => ({ initialization: 1, seconds: 4 })), + }) +} + +// Every rejection no handler took while a call ran, as the process reports one once the turn that made it ends unhandled. +async function unhandledRejections(call: () => Promise): Promise { + const rejections: unknown[] = [] + const collect = (reason: unknown): void => { + rejections.push(reason) + } + + process.on('unhandledRejection', collect) + + try { + await call() + await sleep(100) + } finally { + process.off('unhandledRejection', collect) + } + + return rejections +} + +describe('cMAFRecordingManagement', () => { + afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() + RecordingProvisioning.remove(USERNAME) + RecordingProvisioning.remove(OTHER_USERNAME) + }) + + describe('provisioning', () => { + it('answers Camera Client CSR with a request whose key signs the nonce in the fixed-width form', async () => { + const management = published() + const answer = await write(management, Characteristic.CameraClientCSR, encodeCameraClientCSRRequest({ nonce: NONCE }), buildEmitterConnection()) + const { csr, nonceSignature } = decodeCameraClientCSRResponse(answer as string) + + expect(nonceSignature).toHaveLength(64) + expect(verify('sha256', NONCE, { + dsaEncoding: 'ieee-p1363', + key: signingRequestKey(csr), + }, nonceSignature)).toBe(true) + await management.destroy() + }) + + it('saves a certificate issued for the pending key, the status reading Needs Update until the Camera Key and the publishing point are saved too', async () => { + const connection = buildEmitterConnection() + const management = published() + const credential = await certify(management, connection) + + await writeCertificate(management, credential, connection) + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.credential?.certificate).toEqual(credential.clientCertificate) + expect(await needsUpdate(management, connection)).toBe(true) + + await writeKey(management, CAMERA_KEY, connection) + + expect(await needsUpdate(management, connection)).toBe(true) + + await writePoint(management, POINT, connection) + + expect(await needsUpdate(management, connection)).toBe(false) + await management.destroy() + }) + + it('refuses a certificate for another key, one not under its CA and one that does not read, saving nothing', async () => { + const connection = buildEmitterConnection() + const management = published() + const { csr: other } = await signingRequest(management, connection) + const credential = await certify(management, connection) + const refused = [ + { + ca: authority.certificate, + clientCertificate: authority.issue(other, new Date(Date.now() - DAY), new Date(Date.now() + DAY)), + }, + { ca: new CertificateAuthority('Another Authority').certificate, clientCertificate: credential.clientCertificate }, + { + ca: authority.certificate, + clientCertificate: Buffer.from('3082', 'hex'), + }, + ] + + for (const request of refused) { + await expect(writeCertificate(management, request, connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.credential).toBeUndefined() + await management.destroy() + }) + + it('saves the Camera Key and serves its number as Camera Key ID', async () => { + const connection = buildEmitterConnection() + const management = published() + + expect(await read(management, Characteristic.CameraKeyID, connection)).toBe('') + + await writeKey(management, CAMERA_KEY, connection) + + expect(decodeCameraKeyID(await read(management, Characteristic.CameraKeyID, connection)).keyID).toBe(7n) + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.cameraKey).toEqual(CAMERA_KEY) + await management.destroy() + }) + + it('saves a publishing point and serves it to a read, never in its value or the accessory cache, and refuses one it cannot use', async () => { + const connection = buildEmitterConnection() + const management = published() + const point = characteristic(management, Characteristic.CameraRecordingPublishingPoint) + + await writePoint(management, POINT, connection) + + expect(await read(management, Characteristic.CameraRecordingPublishingPoint, connection)).toBe(encodeCameraRecordingPublishingPoint(POINT)) + expect(point.value).not.toContain(encodeCameraRecordingPublishingPoint(POINT)) + expect(JSON.stringify(CharacteristicSerialize(point))).not.toContain(encodeCameraRecordingPublishingPoint(POINT)) + + for (const refused of [ + { ...POINT, url: 'http://ingest.example/v1/token/' }, + { ...POINT, serverCACertificates: [] }, + ]) { + await expect(writePoint(management, refused, connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + } + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.publishingPoint).toEqual(POINT) + await management.destroy() + }) + + it('marks the publishing point, the Camera Key and the client certificate admin-only, the point transient and sensitive', async () => { + const management = published() + const point = characteristic(management, Characteristic.CameraRecordingPublishingPoint).props + const cameraKey = characteristic(management, Characteristic.CameraKey).props + const certificate = characteristic(management, Characteristic.CameraClientCertificate).props + + expect([point.transient, point.sensitive]).toEqual([true, true]) + expect([point.adminOnlyAccess, cameraKey.adminOnlyAccess, certificate.adminOnlyAccess]).toEqual([ + [Access.READ, Access.WRITE], + [Access.WRITE], + [Access.READ, Access.WRITE], + ]) + await management.destroy() + }) + + it('clears the credential and the Camera Key, or the point, at a write of no bytes, keeping the marks, and writes nothing for a no-change clear', async () => { + const connection = buildEmitterConnection() + + RecordingProvisioning.save(USERNAME, CAMERA, { clipMark: 9n, sequenceMark: 5n }) + + // The context saves the restored sequence mark past the skip-ahead and the restored clip mark past its margin, and no provisioning write moves a mark + // from there. + const management = published() + + await provision(management, connection) + await write(management, Characteristic.CameraClientCertificate, '', connection) + + expect(RecordingProvisioning.load(USERNAME, CAMERA)).toStrictEqual({ clipMark: 25n, publishingPoint: POINT, sequenceMark: 5n + SKIP_AHEAD }) + + await write(management, Characteristic.CameraRecordingPublishingPoint, '', connection) + + expect(RecordingProvisioning.load(USERNAME, CAMERA)).toStrictEqual({ clipMark: 25n, sequenceMark: 5n + SKIP_AHEAD }) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + + await write(management, Characteristic.CameraRecordingPublishingPoint, '', connection) + await write(management, Characteristic.CameraClientCertificate, '', connection) + + expect(setItemSync).not.toHaveBeenCalled() + expect(await needsUpdate(management, connection)).toBe(true) + expect(await read(management, Characteristic.CameraKeyID, connection)).toBe('') + await management.destroy() + }) + + it('reads the record again at a factory reset, serving what was edited behind it and dropping the pending key', async () => { + const connection = buildEmitterConnection() + const management = published() + const credential = await certify(management, connection) + + RecordingProvisioning.save(USERNAME, CAMERA, { cameraKey: CAMERA_KEY }) + management.handleFactoryReset() + + expect(decodeCameraKeyID(await read(management, Characteristic.CameraKeyID, connection)).keyID).toBe(7n) + await expect(writeCertificate(management, credential, connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + await management.destroy() + }) + + it('refuses a provisioning write before the camera knows its username, and after its destroy began', async () => { + const connection = buildEmitterConnection() + const unpublished = new CMAFRecordingManagement(options()) + const destroyed = published() + + await destroyed.destroy() + + for (const management of [unpublished, destroyed]) { + await expect(writeKey(management, CAMERA_KEY, connection)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.cameraKey).toBeUndefined() + await unpublished.destroy() + }) + }) + + describe('reads and contexts', () => { + it('answers a read of Camera Client Certificate with the held certificate and its CA in the write\'s form, empty with none, never in its value', async () => { + const connection = buildEmitterConnection() + const reader = buildEmitterConnection() + const management = published() + const certificate = characteristic(management, Characteristic.CameraClientCertificate) + + expect(await read(management, Characteristic.CameraClientCertificate, reader)).toBe('') + + const credential = await provision(management, connection) + const answer = decodeCameraClientCertificateRequest(await read(management, Characteristic.CameraClientCertificate, reader)) + + expect(answer).toEqual(credential) + expect(new X509Certificate(answer.clientCertificate).checkIssued(new X509Certificate(answer.ca))).toBe(true) + expect(await read(management, Characteristic.CameraClientCertificate, connection)).toBe(encodeCameraClientCertificateRequest(credential)) + expect(certificate.value).toBe('') + expect(JSON.stringify(CharacteristicSerialize(certificate))).not.toContain(encodeCameraClientCertificateRequest(credential)) + await management.destroy() + }) + + it('changes nothing at a context naming the identity held, drops the package at one with no username, and loads its own at another', async () => { + const connection = buildEmitterConnection() + + RecordingProvisioning.save(OTHER_USERNAME, CAMERA, { + cameraKey: { + key: Buffer.alloc(32, 1), + keyNumber: 3n, + }, + }) + + const management = published() + + await provision(management, connection) + + const load = vi.spyOn(RecordingProvisioning, 'load') + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + + management.handleAccessoryContext(context(USERNAME)) + + expect(load).not.toHaveBeenCalled() + expect(setItemSync).not.toHaveBeenCalled() + expect(await needsUpdate(management, connection)).toBe(false) + + const credential = await certify(management, connection) + + management.handleAccessoryContext(context()) + + expect(await needsUpdate(management, connection)).toBe(true) + expect(await read(management, Characteristic.CameraRecordingPublishingPoint, connection)).toBe('') + + management.handleAccessoryContext(context(OTHER_USERNAME)) + + expect(decodeCameraKeyID(await read(management, Characteristic.CameraKeyID, connection)).keyID).toBe(3n) + await expect(writeCertificate(management, credential, connection)).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(setItemSync.mock.calls.map(([key]) => key)).toEqual([ + RecordingProvisioning.persistKey(OTHER_USERNAME), + ]) + await management.destroy() + }) + + it('publishes each part its stored record leaves out as a part-unreadable debug event naming its camera, the part named alone', async () => { + const events = captureDebugEvents('HAP-NodeJS:RecordingProvisioning') + + HAPStorage.storage().setItemSync(RecordingProvisioning.persistKey(USERNAME), { + accessories: { + [CAMERA]: { + clipMark: '9', + sequenceMark: '-5', + }, + }, + }) + + const management = new CMAFRecordingManagement({ + ...options(), + reporter: namedReporter('Front Door', CAMERA), + }) + + management.handleAccessoryContext(context(USERNAME)) + + expect(events).toStrictEqual([ + { + accessoryUUID: CAMERA, + kind: 'part-unreadable', + part: 'sequenceMark', + sentence: 'A stored recording provisioning entry holds an unreadable sequenceMark, which is left out.', + }, + ]) + await management.destroy() + }) + + it('answers a Camera Key write the record cannot save with a failure the hub repeats, serving what the record holds', async () => { + const connection = buildEmitterConnection() + const management = published() + + vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementation(() => { + throw new Error('The disk is full.') + }) + + await expect(writeKey(management, CAMERA_KEY, connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(await read(management, Characteristic.CameraKeyID, connection)).toBe('') + await management.destroy() + }) + + it('reports a provisioning write the record cannot save as a storage problem of the camera beside the failure the write answers, printing nothing ' + + 'while the camera\'s channel has a subscriber', async () => { + const connection = buildEmitterConnection() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { problems, reporter } = problemsOf(CAMERA) + const management = new CMAFRecordingManagement({ + ...options(), + reporter, + }) + const full = new Error('The disk is full.') + + management.handleAccessoryContext(context(USERNAME)) + vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementation(() => { + throw full + }) + + await expect(writeKey(management, CAMERA_KEY, connection)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(problems).toEqual([ + { + accessoryUUID: CAMERA, + error: full, + kind: 'storage-failed', + level: 'warning', + sentence: 'The recording provisioning record could not be saved: The disk is full.', + }, + ]) + expect(warn).not.toHaveBeenCalled() + await management.destroy() + }) + + it('changes nothing at a second factory reset in the same removal: no characteristic updated and no record written', async () => { + const connection = buildEmitterConnection() + const management = published() + + await provision(management, connection) + management.handleFactoryReset() + + const updates = Object.values(management.services).map(service => vi.spyOn(service, 'updateCharacteristic')) + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + + management.handleFactoryReset() + + expect(updates.flatMap(update => update.mock.calls)).toEqual([]) + expect(setItemSync).not.toHaveBeenCalled() + await management.destroy() + }) + }) + + describe('the certificate\'s renewal', () => { + it('turns the status to Needs Update seven days before the certificate\'s end at the daily check, notifying once, on an unreferenced timer', async () => { + const timers = process.getActiveResourcesInfo().filter(resource => resource === 'Timeout').length + const connection = buildEmitterConnection() + const management = published() + + expect(process.getActiveResourcesInfo().filter(resource => resource === 'Timeout').length).toBe(timers) + await management.destroy() + + vi.useFakeTimers() + + const renewing = published() + + // The certificate ends seven and a half days out, and the first daily check finds it inside the seventh day. + await provision(renewing, connection, 7.5) + + const status = vi.spyOn(renewing.services.certificate, 'updateCharacteristic') + + expect(await needsUpdate(renewing, connection)).toBe(false) + + vi.advanceTimersByTime(DAY - 1) + + expect(status).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + + expect(status.mock.calls).toEqual([ + [ + Characteristic.CameraClientCertificateStatus, + expect.any(String), + ], + ]) + expect(await needsUpdate(renewing, connection)).toBe(true) + + vi.advanceTimersByTime(3 * DAY) + + expect(status).toHaveBeenCalledTimes(1) + + await renewing.destroy() + + expect(vi.getTimerCount()).toBe(0) + }) + + it('takes a renewal\'s four writes as a whole provisioning, each replacing its value and no mark moving, and reads the status from every part', async () => { + const connection = buildEmitterConnection() + + RecordingProvisioning.save(USERNAME, CAMERA, { clipMark: 9n, sequenceMark: 5n }) + + // The marks the context saved, the sequence mark past the skip-ahead and the clip mark past its margin, are the ones no write moves. + const management = published() + + await provision(management, connection) + + const renewed = await provision(management, connection) + const renewedKey = { + key: Buffer.alloc(32, 0x6B), + keyNumber: 8n, + } + + await writeKey(management, renewedKey, connection) + + const stored = RecordingProvisioning.load(USERNAME, CAMERA) + + expect(stored?.credential?.certificate).toEqual(renewed.clientCertificate) + expect(stored?.cameraKey).toEqual(renewedKey) + expect([stored?.clipMark, stored?.sequenceMark]).toEqual([25n, 5n + SKIP_AHEAD]) + expect(await needsUpdate(management, connection)).toBe(false) + + RecordingProvisioning.save(USERNAME, CAMERA, { ...stored!, cameraKey: undefined }) + management.handleFactoryReset() + + expect(await needsUpdate(management, connection)).toBe(true) + + await writeKey(management, CAMERA_KEY, connection) + await write(management, Characteristic.CameraRecordingPublishingPoint, '', connection) + + expect(await needsUpdate(management, connection)).toBe(true) + + await writePoint(management, POINT, connection) + + expect(await needsUpdate(management, connection)).toBe(false) + await management.destroy() + }) + }) + + describe('the event queue', () => { + function sequenceNumberOf(management: CMAFRecordingManagement): unknown { + return management.services.buffer.getCharacteristic(Characteristic.BufferEventSequenceNumber).value + } + + it('saves the counter as the sequence mark at the context, and again once it passes the saved mark by half a skip-ahead', async () => { + const management = published() + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.sequenceMark).toBe(0n) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + + // The counter also numbers the error event an overflow queues, which is why the loop drives edges until the counter, not a count of edges, reaches its target. + while ((sequenceNumberOf(management) as number) < Number(SKIP_AHEAD / 2n) - 1) { + management.motionChanged((sequenceNumberOf(management) as number) % 2 === 0) + } + + expect(setItemSync).not.toHaveBeenCalled() + + management.motionChanged(true) + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.sequenceMark).toBe(SKIP_AHEAD / 2n) + await management.destroy() + }) + + it('starts a restarted camera\'s counter above every number used before the restart', async () => { + const first = published() + + for (let edge = 0; edge < 5; edge++) { + first.motionChanged(edge % 2 === 0) + } + + const used = sequenceNumberOf(first) as number + + await first.destroy() + + const restarted = published() + + expect(sequenceNumberOf(restarted)).toBe(Number(SKIP_AHEAD)) + expect(sequenceNumberOf(restarted) as number).toBeGreaterThan(used) + await restarted.destroy() + }) + + it('answers Query with the queued events and Acknowledge by removing every event through the number it names', async () => { + const connection = buildEmitterConnection() + const management = published() + + management.motionChanged(true) + management.motionChanged(false) + + expect(await queried(management, connection)).toEqual([ + { active: true, sequenceNumber: 1n, type: CameraBufferEventType.MOTION }, + { active: false, sequenceNumber: 2n, type: CameraBufferEventType.MOTION }, + ]) + + const acknowledgement = encodeBufferEventCommandRequest({ command: BufferEventCommandType.ACKNOWLEDGE, sequenceNumber: 1n }) + + expect(decodeBufferEventCommandResponse(await write(management, Characteristic.BufferEventCommand, acknowledgement, connection) as string).events).toEqual([]) + expect((await queried(management, connection)).map(({ sequenceNumber }) => sequenceNumber)).toEqual([2n]) + await management.destroy() + }) + + it('queues a Motion event at every edge, each setting Buffer Event Sequence Number', async () => { + const connection = buildEmitterConnection() + const management = published() + const updates = vi.spyOn(management.services.buffer, 'updateCharacteristic') + + management.motionChanged(true) + management.motionChanged(false) + management.motionChanged(true) + + expect(updates.mock.calls).toEqual([1, 2, 3].map(value => [Characteristic.BufferEventSequenceNumber, value])) + expect((await queried(management, connection)).map(event => event.type === CameraBufferEventType.MOTION && event.active)).toEqual([true, false, true]) + await management.destroy() + }) + + it('empties the queue at a factory reset, keeping its counter', async () => { + const connection = buildEmitterConnection() + const management = published() + + management.motionChanged(true) + management.motionChanged(false) + management.handleFactoryReset() + + expect(await queried(management, connection)).toEqual([]) + + management.motionChanged(true) + + expect((await queried(management, connection)).map(({ sequenceNumber }) => sequenceNumber)).toEqual([3n]) + await management.destroy() + }) + + it('reads a restored mark within two skip-aheads of 2^64 as absent', async () => { + RecordingProvisioning.save(USERNAME, CAMERA, { sequenceMark: 2n ** 64n - 2n * SKIP_AHEAD }) + + const management = published() + + expect(sequenceNumberOf(management)).toBe(0) + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.sequenceMark).toBe(0n) + await management.destroy() + }) + + it('sets Buffer Event Sequence Number from a restored mark before any event is queued', async () => { + RecordingProvisioning.save(USERNAME, CAMERA, { sequenceMark: 5n }) + + const management = published() + + expect(sequenceNumberOf(management)).toBe(Number(5n + SKIP_AHEAD)) + await management.destroy() + }) + + it('keeps the queue, its events and its counter when the camera is published again under the same username', async () => { + const connection = buildEmitterConnection() + const management = published() + + management.motionChanged(true) + management.handleAccessoryContext(context(USERNAME)) + management.motionChanged(false) + + expect((await queried(management, connection)).map(({ sequenceNumber }) => sequenceNumber)).toEqual([1n, 2n]) + await management.destroy() + }) + + it('logs a record write that fails at a context as one warning naming no stored value, and serves from memory, throwing into no caller', async () => { + const connection = buildEmitterConnection() + + RecordingProvisioning.save(USERNAME, CAMERA, { cameraKey: CAMERA_KEY }) + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementation(() => { + throw new Error('The disk is full.') + }) + + const management = new CMAFRecordingManagement(options()) + + expect(() => management.handleAccessoryContext(context(USERNAME))).not.toThrow() + expect(warn.mock.calls).toEqual([ + [ + expect.stringContaining('The disk is full.'), + ], + ]) + expect(String(warn.mock.calls[0][0])).not.toContain(CAMERA_KEY.key.toString('hex')) + expect(decodeCameraKeyID(await read(management, Characteristic.CameraKeyID, connection)).keyID).toBe(7n) + await management.destroy() + }) + + it('opens a record write\'s warning with the camera\'s Name', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const information = new Service.AccessoryInformation() as AccessoryInformation + + information.setCharacteristic(Characteristic.Name, 'Front Door') + vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementation(() => { + throw new Error('The disk is full.') + }) + + const management = new CMAFRecordingManagement({ + ...options(), + reporter: namedReporter('Front Door'), + }) + + management.handleAccessoryContext({ + accessoryInformation: information, + accessoryUUID: CAMERA, + published: true, + username: USERNAME, + }) + + expect(warn.mock.calls).toEqual([ + ['[Front Door] The camera\'s recording provisioning record could not be written: The disk is full.'], + ]) + await management.destroy() + }) + }) + + describe('clip sessions and uploads', () => { + it('uploads the span a hub commands as its folder, each object in order with its type, the User-Agent and each segment\'s duration', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0) + A_FEW_MILLISECONDS) + + expect(clipID).toBe(1n) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1001.m4s')) + serve(camera, 2) + await judge(camera, 1) + await judge(camera, 2) + + expect(await stopAt(camera, endOf(camera, 2) - A_FEW_MILLISECONDS)).toBe(1n) + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera)).toEqual([ + 'session_1/index.m3u8', + 'session_1/high/index.m3u8', + 'session_1/high/high.init', + ...segmentsOf(1n, 3), + 'session_1/high/index.m3u8', + ]) + expect(camera.mock.requests.map(({ headers }) => headers['content-type'])).toEqual([ + 'application/vnd.apple.mpegurl', + 'application/vnd.apple.mpegurl', + 'video/mp4', + 'video/iso.segment', + 'video/iso.segment', + 'video/iso.segment', + 'application/vnd.apple.mpegurl', + ]) + expect(new Set(camera.mock.requests.map(({ headers }) => headers['user-agent']))).toEqual(new Set([USER_AGENT])) + expect(camera.mock.requests.map(({ headers }) => headers['x-extinf-duration'])).toEqual([ + undefined, + undefined, + undefined, + '4.00000', + '4.00000', + '4.00000', + undefined, + ]) + expect(segmentsOf(1n, 3).map(path => body(camera, path))).toEqual(camera.served) + expect(body(camera, 'session_1/high/high.init')).toEqual(camera.recording.run?.initialization) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(3)) + + // The multivariant playlist went out while the Start's fragment was the only one read, which is why its bandwidths are that fragment's as its segment was sent. + const multivariant = body(camera, 'session_1/index.m3u8').toString() + const bandwidth = Math.ceil((sent(camera, 'session_1/high/segment_1001.m4s').length * 8) / 4) + + expect(multivariant).toContain(`#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},AVERAGE-BANDWIDTH=${bandwidth},RESOLUTION=1920x1080,CODECS="avc1.4d0028"\n`) + expect(await clipEvents(camera, clipID)).toEqual([ + { cmafSessionID: 1n, sequenceNumber: 1n, type: CameraBufferEventType.CMAF_SESSION_START }, + { cmafSessionID: 1n, sequenceNumber: 2n, type: CameraBufferEventType.CMAF_SESSION_STOP }, + ]) + }) + + 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() + + serve(camera) + await judge(camera, 0) + + expect(await startAt(camera, placeOf(camera, 0))).toBe(1n) + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.clipMark).toBe(1n) + expect(await startAt(camera, placeOf(camera, 0), SESSION + 1n)).toBe(2n) + + // A factory reset reads the record again and raises nothing. + camera.management.handleFactoryReset() + + expect(await startAt(camera, placeOf(camera, 0), SESSION + 2n)).toBe(3n) + + await camera.management.destroy() + + const restarted = new CMAFRecordingManagement({ + feed: camera.feed, + policy: camera.policy, + reporter: detachedReporter(), + }) + + restarted.handleAccessoryContext(context(USERNAME)) + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.clipMark).toBe(19n) + expect(await startAt({ connection: camera.connection, management: restarted }, placeOf(camera, 0), SESSION + 3n)).toBe(20n) + await restarted.destroy() + }) + + it('takes the next number from the mark at a 208 on its first object and sends under it, the hub\'s Clip ID unchanged', async () => { + await using camera = await clipCamera({ + answer: answers({ + 'session_1/index.m3u8': [ + { status: 208 }, + ], + }), + }) + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await eventually(() => expect(paths(camera)).toContain('session_2/high/segment_1001.m4s')) + await stopAt(camera, endOf(camera, 0)) + + expect(await ended(camera, clipID)).toEqual({ cmafSessionID: 1n, sequenceNumber: 2n, type: CameraBufferEventType.CMAF_SESSION_STOP }) + expect(paths(camera)).toEqual([ + 'session_1/index.m3u8', + 'session_2/index.m3u8', + 'session_2/high/index.m3u8', + 'session_2/high/high.init', + ...segmentsOf(2n, 1), + 'session_2/high/index.m3u8', + ]) + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.clipMark).toBe(2n) + }) + + it('goes on at a 208 on the repeat of a segment a 503 refused, the repeat being its own earlier send', async () => { + await using camera = await clipCamera({ + answer: answers({ + 'session_1/high/segment_1001.m4s': [ + { status: 503 }, + { status: 208 }, + ], + }), + }) + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await eventually(() => expect(paths(camera).filter(path => path === 'session_1/high/segment_1001.m4s')).toHaveLength(2)) + await stopAt(camera, endOf(camera, 0)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => !path.startsWith('session_1/'))).toEqual([]) + expect(body(camera, 'session_1/high/segment_1001.m4s')).toEqual(camera.served[0]) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(1)) + }) + + it('repeats an object a 503 refused a second later in a new ingest session, and goes on', async () => { + const open = vi.spyOn(IngestSession, 'open') + + await using camera = await clipCamera({ + answer: answers({ + 'session_1/high/index.m3u8': [ + { status: 503 }, + ], + }), + }) + + 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')) + await stopAt(camera, endOf(camera, 0)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path === 'session_1/high/index.m3u8')).toHaveLength(3) + expect(open).toHaveBeenCalledTimes(2) + }) + + it('ends a clip with the 5xx\'s CMAF error once two repeats are spent, and at once at a 400, its CMAF error carrying the Clip ID', async () => { + const open = vi.spyOn(IngestSession, 'open') + + await using unavailable = await clipCamera({ + answer: answers({ + 'session_1/high/high.init': [ + { status: 503 }, + { status: 503 }, + { status: 503 }, + ], + }), + }) + + serve(unavailable) + await judge(unavailable, 0) + + const first = await startAt(unavailable, placeOf(unavailable, 0)) + + expect(await ended(unavailable, first)).toEqual({ + cmafError: CMAFError.HTTP_SERVICE_UNAVAILABLE, + cmafSessionID: 1n, + sequenceNumber: 2n, + type: CameraBufferEventType.CMAF_ERROR, + }) + expect(paths(unavailable).filter(path => path === 'session_1/high/high.init')).toHaveLength(3) + expect(paths(unavailable)).not.toContain('session_1/high/segment_1001.m4s') + expect(open).toHaveBeenCalledTimes(3) + + await unavailable[Symbol.asyncDispose]() + RecordingProvisioning.remove(USERNAME) + open.mockClear() + + await using refused = await clipCamera({ + answer: answers({ + 'session_1/high/index.m3u8': [ + { status: 400 }, + ], + }), + }) + + serve(refused) + await judge(refused, 0) + + const second = await startAt(refused, placeOf(refused, 0)) + + expect(await ended(refused, second)).toMatchObject({ cmafError: CMAFError.HTTP_BAD_REQUEST, cmafSessionID: second }) + expect(paths(refused).filter(path => path === 'session_1/high/index.m3u8')).toHaveLength(1) + expect(open).toHaveBeenCalledTimes(1) + }) + + it('keeps the identity a clip opened with through a clear and a renewal\'s four writes naming another point', async () => { + await using camera = await clipCamera() + await using other = await MockIngestServer.start({ clientCAs: authority.pem }) + const renewedKey = { + key: Buffer.alloc(32, 0x6B), + keyNumber: 8n, + } + + 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')) + await write(camera.management, Characteristic.CameraRecordingPublishingPoint, '', camera.connection) + await write(camera.management, Characteristic.CameraClientCertificate, '', camera.connection) + await writeCertificate(camera.management, await certify(camera.management, camera.connection), camera.connection) + await writeKey(camera.management, renewedKey, camera.connection) + await writePoint(camera.management, { + serverCACertificates: [ + { + certificate: new X509Certificate(INGEST_CERTIFICATES.serverCA).raw, + }, + ], + url: other.url, + }, camera.connection) + + // The session the clip opened ends idle, and its next object goes on a session it opens again, under the identity it opened with. + await sleep(100) + camera.mock.goaway() + await sleep(100) + serve(camera) + await judge(camera, 1) + await stopAt(camera, endOf(camera, 1)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera)).toContain('session_1/high/segment_1002.m4s') + expect(other.requests).toEqual([]) + + // The segment sent after the Camera Key's replacement opens under the content key the clip opened with, and under no other. + expect(body(camera, 'session_1/high/segment_1002.m4s')).toEqual(camera.served[1]) + 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 () => { + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await stopAt(camera, endOf(camera, 1)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + + const attributes = keyAttributes(contentKeyOf(CAMERA_KEY)) + + // Each segment goes out as a 16-byte IV, its ciphertext and a 16-byte tag, the layout the body reader opens. + for (const [index, path] of segmentsOf(1n, 2).entries()) { + expect(sent(camera, path)).toHaveLength(camera.served[index].length + 32) + expect(body(camera, path)).toEqual(camera.served[index]) + } + + 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(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + it.each([ + [ + 'no Camera Key', + undefined, + '', + true, + 'the camera holds no Camera Key to encrypt its video and audio with.', + ], + [ + 'a Camera Key of 31 bytes', + SHORT_KEY, + encodeCameraKeyID({ keyID: SHORT_KEY.keyNumber }), + false, + SHORT_KEY_REASON, + ], + [ + 'a Camera Key whose number does not fit in 48 bits', + { + key: CAMERA_KEY.key, + keyNumber: 2n ** 48n, + }, + encodeCameraKeyID({ keyID: 2n ** 48n }), + false, + 'the camera cannot encrypt its video and audio with the Camera Key it holds: A Camera Key\'s number must fit in 48 bits.', + ], + ] as const)('refuses a Start, uploading nothing, while the camera holds %s, warning why at the first refusal and an hour on with the count', async ( + _name, + cameraKey, + keyID, + status, + reason, + ) => { + vi.useFakeTimers({ + toFake: ['Date'], + }) + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + await using camera = await clipCamera({ + key: false, + reporter: namedReporter('Front Door'), + }) + + if (cameraKey !== undefined) { + await writeKey(camera.management, cameraKey, camera.connection) + } + + camera.information.setCharacteristic(Characteristic.Name, 'Front Door') + serve(camera) + await judge(camera, 0) + + // A hub's repeated Start: the second a millisecond inside the hour after the first warning, the hub having written the same key again before it, + // the third at the hour, the fourth an hour after that, and the last with the clock set back past the last warning. + const lines = captureDebug('HAP-NodeJS:Camera:CMAFRecording', 'HAP-NodeJS:Camera:Ingest', 'HAP-NodeJS:Camera:ServedRecording') + + for (const wait of [0, HOUR - 1, 1, HOUR]) { + vi.advanceTimersByTime(wait) + + if (wait === HOUR - 1 && cameraKey !== undefined) { + await writeKey(camera.management, cameraKey, camera.connection) + } + + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + vi.setSystemTime(Date.now() - 2 * HOUR) + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + + expect(warn.mock.calls).toEqual([ + [`[Front Door] No clip is uploaded, because ${reason}`], + [`[Front Door] No clip is uploaded, because ${reason} The camera has refused 2 requests for a clip since the last warning.`], + [`[Front Door] No clip is uploaded, because ${reason} The camera has refused 1 request for a clip since the last warning.`], + [`[Front Door] No clip is uploaded, because ${reason} The camera has refused 1 request for a clip since the last warning.`], + ]) + expect(lines.filter(line => line.includes('refuses a Start while the camera holds no Camera Key it can encrypt'))).toHaveLength(5) + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.clipMark).toBeUndefined() + expect(await queried(camera.management, camera.connection)).toEqual([]) + expect(camera.mock.requests).toEqual([]) + expect(camera.feed.holding).toBe(false) + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.cameraKey).toEqual(cameraKey) + expect(await read(camera.management, Characteristic.CameraKeyID, camera.connection)).toBe(keyID) + expect(await needsUpdate(camera.management, camera.connection)).toBe(status) + + // A usable Camera Key holds the feed and opens a clip, the refusals having spent no clip number, and a key refused after it warns at its first refusal. + await writeKey(camera.management, CAMERA_KEY, camera.connection) + serve(camera) + await judge(camera, 1) + + expect(await startAt(camera, placeOf(camera, 1))).toBe(1n) + + await writeKey(camera.management, SHORT_KEY, camera.connection) + await expect(startAt(camera, placeOf(camera, 1), SESSION + 1n)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + + expect(warn.mock.calls.slice(4)).toEqual([ + [`[Front Door] No clip is uploaded, because ${SHORT_KEY_REASON}`], + ]) + }) + + it('refuses a Start while a running clip holds its fragment and the Camera Key has turned unusable, spending no clip number and queuing no event', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + await using camera = await clipCamera({ + answer: answers({ + 'session_1/index.m3u8': [ + { hold: true }, + ], + }), + }) + + serve(camera) + await judge(camera, 0) + + expect(await startAt(camera, placeOf(camera, 0))).toBe(1n) + + await writeKey(camera.management, SHORT_KEY, camera.connection) + + // The running clip's reader keeps the fragment: the feed could serve this Start and the refusal alone stands between it and a second clip. + expect(held(camera.recording)).toEqual([true]) + await expect(startAt(camera, placeOf(camera, 0), SESSION + 1n)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.clipMark).toBe(1n) + expect((await queried(camera.management, camera.connection)).filter(event => 'cmafSessionID' in event).map(event => event.cmafSessionID)).toEqual([1n]) + await sleep(100) + expect(paths(camera).filter(path => !path.startsWith('session_1/'))).toEqual([]) + }) + + it('refuses a Start with no warning while recording is disallowed on a camera holding no Camera Key', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + await using camera = await clipCamera({ key: false }) + + serve(camera) + await judge(camera, 0) + camera.recordingService.updateCharacteristic(Characteristic.Active, false) + + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(warn).not.toHaveBeenCalled() + }) + + it('drains a Pause to its stop leaving the playlists open, and a resume clears that stop and uploads on to its own Stop', 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)) + + expect(await stopAt(camera, endOf(camera, 1), BufferUploadStopAction.PAUSE)).toBe(clipID) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + await sleep(100) + + expect(paths(camera).filter(path => path === 'session_1/high/index.m3u8')).toHaveLength(1) + expect((await clipEvents(camera, clipID)).map(({ type }) => type)).toEqual([CameraBufferEventType.CMAF_SESSION_START]) + + serve(camera, 2) + await judge(camera, 2) + await judge(camera, 3) + + // The verdicts have passed the first fragment and the paused clip's reader has ended, which is why a resume naming it is refused and the clip stays paused. + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + await sleep(100) + + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, 2)) + expect(await startAt(camera, placeOf(camera, 2))).toBe(clipID) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1004.m4s')) + await stopAt(camera, endOf(camera, 3)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(segmentsOf(1n, 4).map(path => body(camera, path))).toEqual(camera.served) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(4)) + }) + + it.each([ + [ + 'a Finalize at the Pause\'s stop', + async (camera: ClipCamera): Promise => await stopAt(camera, endOf(camera, 1)), + 2, + ], + [ + 'a StartAndStop that resumes it and applies its Stop', + async (camera: ClipCamera): Promise => await command(camera, { + command: BufferUploadCommandType.START_AND_STOP, + sessionID: SESSION, + start: placeOf(camera, 2), + stop: endOf(camera, 3), + stopAction: BufferUploadStopAction.FINALIZE, + }), + 4, + ], + ] as const)('keeps a paused clip as it is at a second Pause, and finalizes it at %s', async (_name, close, segments) => { + await using camera = await clipCamera() + + serve(camera, 4) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await stopAt(camera, endOf(camera, 1), BufferUploadStopAction.PAUSE) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + await sleep(100) + + const paused = paths(camera) + + expect(await stopAt(camera, endOf(camera, 1), BufferUploadStopAction.PAUSE)).toBe(clipID) + await sleep(100) + + expect(paths(camera)).toEqual(paused) + expect((await clipEvents(camera, clipID)).map(({ type }) => type)).toEqual([CameraBufferEventType.CMAF_SESSION_START]) + expect(await close(camera)).toBe(clipID) + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera)).toEqual([ + 'session_1/index.m3u8', + 'session_1/high/index.m3u8', + 'session_1/high/high.init', + ...segmentsOf(1n, segments), + 'session_1/high/index.m3u8', + ]) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(segments)) + }) + + it('ends every open and paused clip with CMAF Error CANCELED when recording is switched off mid-upload, sending nothing more', async () => { + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + + const paused = await startAt(camera, placeOf(camera, 0), SESSION + 1n) + + await stopAt(camera, endOf(camera, 0), BufferUploadStopAction.PAUSE, SESSION + 1n) + + // The second fragment is judged only once the first clip has its Pause: that clip can ask for nothing past the fragment it pauses at, and every + // request the mock will read has reached it when the requests are counted. + await judge(camera, 1) + + const open = await startAt(camera, placeOf(camera, 1)) + + await eventually(() => expect(paths(camera)).toEqual(expect.arrayContaining(['session_1/high/segment_1001.m4s', 'session_2/high/segment_1001.m4s']))) + camera.recordingService.updateCharacteristic(Characteristic.Active, false) + + for (const clipID of [paused, open]) { + expect(await ended(camera, clipID)).toMatchObject({ cmafError: CMAFError.CANCELED, type: CameraBufferEventType.CMAF_ERROR }) + } + + const sent = camera.mock.requests.length + + serve(camera) + await judge(camera, 2) + await sleep(100) + + expect(camera.mock.requests).toHaveLength(sent) + }) + + it('leaves no ingest session, timer or reader after a destroy mid-clip', async () => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + ], + }) + + const open = vi.spyOn(IngestSession, 'open') + + await using camera = await clipCamera({ + answer: answers({ + 'session_1/high/segment_1001.m4s': [ + { hold: true }, + ], + }), + }) + + serve(camera) + await judge(camera, 0) + await startAt(camera, placeOf(camera, 0)) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1001.m4s')) + await camera.management.destroy() + + const sessions = await Promise.all(open.mock.results.map(async ({ value }) => await (value as Promise))) + + expect(sessions).toHaveLength(1) + // @ts-expect-error: private access + expect(sessions[0].session.destroyed).toBe(true) + // @ts-expect-error: private access + expect(camera.recording.readers.size).toBe(0) + expect(vi.getTimerCount()).toBe(0) + }) + + it('logs and warns of an upload failure by its message and status alone, no line carrying the point\'s URL or the answer\'s body', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + let url = '' + const lines = captureDebug('HAP-NodeJS:Camera:CMAFRecording', 'HAP-NodeJS:Camera:Ingest', 'HAP-NodeJS:Camera:ServedRecording') + + // The camera is disposed as its block ends: every line and warning its end writes is read below. + { + await using camera = await clipCamera({ + answer: answers({ + 'session_1/high/segment_1001.m4s': [ + { body: 'a body the service wrote', status: 400 }, + ], + }), + }) + + url = camera.mock.url + serve(camera) + await judge(camera, 0) + await ended(camera, await startAt(camera, placeOf(camera, 0))) + } + + expect(lines.some(line => line.includes('The publishing point did not accept an object. (CMAF error 15, status 400)'))).toBe(true) + expect(warn.mock.calls).toEqual([ + [ + expect.stringMatching(/^A clip's upload failed\. The publishing point did not accept an object\. Its answer was status 400\.$/), + ], + ]) + + for (const line of [ + ...lines, + ...warn.mock.calls.flat(), + ...error.mock.calls.flat(), + ].map(String)) { + for (const secret of [ + url, + POINT_PATH, + 'a body the service wrote', + CAMERA_KEY.key.toString('hex'), + ]) { + expect(line).not.toContain(secret) + } + } + }) + + it.each([ + { + kind: 'upload-refused', + // A Start while the camera holds no Camera Key, which refuses the Start and uploads nothing. + raise: async (reporter: CameraReporter): Promise => { + await using camera = await clipCamera({ key: false, reporter }) + + serve(camera) + await judge(camera, 0) + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + }, + site: 'a Start refused for no Camera Key', + }, + { + kind: 'upload-failed', + // A clip whose first segment the publishing point refuses, which fails the clip's upload. + raise: async (reporter: CameraReporter): Promise => { + await using camera = await clipCamera({ + answer: answers({ + 'session_1/high/segment_1001.m4s': [ + { body: 'a body the service wrote', status: 400 }, + ], + }), + reporter, + }) + + serve(camera) + await judge(camera, 0) + await ended(camera, await startAt(camera, placeOf(camera, 0))) + }, + site: 'a clip whose upload fails', + }, + ])('raises one problem of its kind at the level warning, carrying no field but its accessory, for $site', async ({ kind, raise }) => { + const { problems, reporter } = problemsOf(CAMERA) + + await raise(reporter) + + // Each problem is read whole, its sentence's wording aside, and a field it gains or loses is read too. + expect(problems).toEqual([ + { + accessoryUUID: CAMERA, + kind, + level: 'warning', + sentence: expect.any(String), + }, + ]) + }) + + it('answers six clips open at once under six Session IDs, two of them reading one recording, each its own Clip ID, each uploading', async () => { + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const shared = camera.recording + const sharedBytes = camera.served + const firsts: Buffer[] = [] + const starts = [ + placeOf(camera, 0), + placeOf(camera, 1), + ] + + for (let recording = 1; recording <= 4; recording++) { + begin(camera, WALL_CLOCK + recording * 60 * 1000) + serve(camera) + await judge(camera, 0) + firsts.push(camera.served[0]) + starts.push(placeOf(camera, 0)) + } + + const clipIDs: bigint[] = [] + + for (const [index, start] of starts.entries()) { + clipIDs.push(await startAt(camera, start, SESSION + BigInt(index))) + } + + expect(clipIDs).toEqual([1n, 2n, 3n, 4n, 5n, 6n]) + await eventually(() => expect(paths(camera)).toEqual(expect.arrayContaining(clipIDs.map(clipID => `session_${clipID}/high/segment_1001.m4s`)))) + expect(clipIDs.map(clipID => body(camera, `session_${clipID}/high/segment_1001.m4s`))).toEqual([sharedBytes[0], sharedBytes[1], ...firsts]) + // @ts-expect-error: private access + expect(shared.readers.size).toBe(2) + }) + + it('finalizes by the grace a clip whose recording ended with no Stop', async () => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout'], + }) + + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + camera.recording.end() + await vi.advanceTimersByTimeAsync(SERVED_RECORDING_GRACE - 1000) + + expect((await clipEvents(camera, clipID)).map(({ type }) => type)).toEqual([CameraBufferEventType.CMAF_SESSION_START]) + + await vi.advanceTimersByTimeAsync(1000) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + it('finalizes no clip a second before the grace has run from the end of a recording that ends well after its last fragment, and finalizes it then', async () => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout', 'Date'], + }) + + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + await vi.advanceTimersByTimeAsync(10 * 1000) + camera.recording.end() + await vi.advanceTimersByTimeAsync(SERVED_RECORDING_GRACE - 1000) + + // A grace timed from the last fragment's arrival would already have finalized the clip, and its closing playlist's answer queued Session Stop. + await sleep(300) + + expect((await clipEvents(camera, clipID)).map(({ type }) => type)).toEqual([CameraBufferEventType.CMAF_SESSION_START]) + + await vi.advanceTimersByTimeAsync(1000) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + // The hubs end a recording in this order: its close, then the last fragment's verdict a few milliseconds later, then the Stop at that fragment's end. + it('sends every fragment of a running clip through a recording\'s end in the hubs\' order, the close, the last fragment\'s verdict and the Stop', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + serve(camera) + await judge(camera, 1) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + serve(camera) + await sleep(50) + camera.recording.end() + await sleep(10) + 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(1n, 3)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(3)) + }) + + it('widens the window of a clip whose recording ended with no Stop at a verdict a second before the grace has run from the end', async () => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout'], + }) + + 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')) + serve(camera) + await sleep(20) + camera.recording.end() + await vi.advanceTimersByTimeAsync(SERVED_RECORDING_GRACE - 1000) + await judge(camera, 1) + await vi.advanceTimersByTimeAsync(1000) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + it('finishes a finalized clip\'s ingest session and prints its debug numbers with no bigint suffix, one segment in the singular', async () => { + const lines = captureDebug('HAP-NodeJS:Camera:CMAFRecording', 'HAP-NodeJS:Camera:Ingest', 'HAP-NodeJS:Camera:ServedRecording') + + // The camera is disposed as its block ends: every line its end writes is read below. + { + await using camera = await clipCamera() + + 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) + await sleep(100) + } + + expect(lines.filter(line => line.includes('The ingest session failed'))).toEqual([]) + expect(lines).toContainEqual(expect.stringContaining('The ingest session ended after it finished')) + expect(lines).toContainEqual(expect.stringContaining('Clip 1 finalized with 1 segment, ')) + expect(lines.filter(line => /\d+n\b/.test(line))).toEqual([]) + }) + + it('publishes a finalized clip\'s length in its finalized debug event, the durations its media playlist states for its segments summed', async () => { + const events = captureDebugEvents('HAP-NodeJS:Camera:CMAFRecording') + let playlist = '' + + // The camera is disposed as its block ends: every event its end publishes is read below. + { + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await stopAt(camera, endOf(camera, 1)) + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + playlist = body(camera, `session_${clipID}/high/index.m3u8`).toString() + } + + // Each duration the closing media playlist states for a segment it lists. + const stated = Array.from(playlist.matchAll(/^#EXTINF:([\d.]+),$/gm), ([, seconds]) => Number(seconds)) + const summed = stated.reduce((sum, duration) => sum + duration, 0) + + expect(stated).toHaveLength(2) + expect(events.filter(({ kind }) => kind === 'clip-finalized')).toEqual([ + { + clipID: '1', + kind: 'clip-finalized', + seconds: summed, + segments: 2, + sentence: `Clip 1 finalized with 2 segments, ${summed.toFixed(3)} seconds long.`, + }, + ]) + }) + + it('finalizes a clip whose ingest session\'s finish rejects after the closing playlist\'s answer', async () => { + await using camera = await clipCamera() + const finish = vi.spyOn(IngestSession.prototype, 'finish').mockRejectedValueOnce(new Error('The session failed late.')) + + 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(finish).toHaveBeenCalledOnce() + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(1)) + }) + + it('takes the mark plus one at each 208 on a clip\'s first object, saved before its resend, never another open clip\'s number', async () => { + // The first clip's first 208 arrives once the second clip has taken the number after its own. + await using camera = await clipCamera({ + answer: answers({ + 'session_1/index.m3u8': [ + { delay: 300, status: 208 }, + ], + 'session_3/index.m3u8': [ + { status: 208 }, + ], + }), + }) + + serve(camera) + await judge(camera, 0) + + const saved: [bigint | undefined, number][] = [] + const save = RecordingProvisioning.save.bind(RecordingProvisioning) + + vi.spyOn(RecordingProvisioning, 'save').mockImplementation((username, accessoryUUID, entry) => { + saved.push([entry.clipMark, paths(camera).length]) + save(username, accessoryUUID, entry) + }) + + expect(await startAt(camera, placeOf(camera, 0), SESSION)).toBe(1n) + expect(await startAt(camera, placeOf(camera, 0), SESSION + 1n)).toBe(2n) + await eventually(() => expect(paths(camera)).toEqual(expect.arrayContaining(['session_2/high/segment_1001.m4s', 'session_4/high/segment_1001.m4s']))) + + for (const folder of [1, 2, 3, 4]) { + expect(paths(camera).filter(path => path === `session_${folder}/index.m3u8`)).toHaveLength(1) + } + + // Each advance saved its number before any request under it. + for (const [clipMark, sent] of saved.filter(([clipMark]) => clipMark === 3n || clipMark === 4n)) { + expect(paths(camera).slice(0, sent)).not.toContain(`session_${clipMark}/index.m3u8`) + } + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.clipMark).toBe(4n) + }) + + it('takes the next number at each of five 208s in a row on a clip\'s first object, going on under the first free one', async () => { + const used = Object.fromEntries([1, 2, 3, 4, 5].map(folder => [ + `session_${folder}/index.m3u8`, + [ + { status: 208 }, + ], + ])) + + await using camera = await clipCamera({ + answer: answers(used), + }) + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await eventually(() => expect(paths(camera)).toContain('session_6/high/segment_1001.m4s')) + await stopAt(camera, endOf(camera, 0)) + + expect(await ended(camera, clipID)).toMatchObject({ cmafSessionID: 1n, type: CameraBufferEventType.CMAF_SESSION_STOP }) + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.clipMark).toBe(6n) + }) + + it('ends a clip with CMAF Error UNKNOWN and a warning when the number a 208 asks for cannot be saved, sending nothing more', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + await using camera = await clipCamera({ + answer: (request) => { + if (request.path === `${POINT_PATH}session_1/index.m3u8`) { + vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementation(() => { + throw new Error('The disk is full.') + }) + + return { status: 208 } + } + + return { status: 201 } + }, + }) + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + expect(await ended(camera, clipID)).toMatchObject({ cmafError: CMAFError.UNKNOWN, type: CameraBufferEventType.CMAF_ERROR }) + expect(paths(camera)).toEqual(['session_1/index.m3u8']) + expect(warn.mock.calls).toEqual([ + [ + expect.stringMatching(/^A clip's upload failed\. The next clip number could not be saved: The disk is full\.$/), + ], + ]) + vi.restoreAllMocks() + }) + + it('advances at a 208 on the repeat of a multivariant playlist a reset cut off, and goes on under the same folder when the reset follows its 201', async () => { + await using cutOff = await clipCamera({ + answer: answers({ + 'session_1/index.m3u8': [ + { reset: http2.constants.NGHTTP2_INTERNAL_ERROR }, + { status: 208 }, + ], + }), + }) + + serve(cutOff) + await judge(cutOff, 0) + await startAt(cutOff, placeOf(cutOff, 0)) + await eventually(() => expect(paths(cutOff)).toContain('session_2/high/segment_1001.m4s')) + + expect(paths(cutOff).slice(0, 3)).toEqual(['session_1/index.m3u8', 'session_1/index.m3u8', 'session_2/index.m3u8']) + + await cutOff[Symbol.asyncDispose]() + RecordingProvisioning.remove(USERNAME) + + await using answered = await clipCamera({ + answer: answers({ + 'session_1/high/index.m3u8': [ + { reset: http2.constants.NGHTTP2_INTERNAL_ERROR }, + ], + }), + }) + + serve(answered) + await judge(answered, 0) + await startAt(answered, placeOf(answered, 0)) + await eventually(() => expect(paths(answered)).toContain('session_1/high/segment_1001.m4s')) + + expect(paths(answered).filter(path => !path.startsWith('session_1/'))).toEqual([]) + }) + + it('opens a Start in an older held recording, refuses one matching no held boundary, and clamps a Stop past an ended recording\'s last fragment', async () => { + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const older = camera.recording + const olderBytes = camera.served + + older.end() + begin(camera, WALL_CLOCK + 60 * 1000) + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 1, older) + FRAGMENT / 2n) + + await expect(startAt(camera, placeOf(camera, 0, older) - 10n * FRAGMENT, SESSION + 1n)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + await stopAt(camera, endOf(camera, 1, older) + 5n * FRAGMENT) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(body(camera, 'session_1/high/segment_1001.m4s')).toEqual(olderBytes[1]) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(1)) + }) + + it('answers a Start whose Clip ID the record cannot save with Service Communication Failure, opening, queuing and sending nothing', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementation(() => { + throw new Error('The disk is full.') + }) + + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + setItemSync.mockRestore() + await sleep(100) + + expect(RecordingProvisioning.load(USERNAME, CAMERA)?.clipMark).toBeUndefined() + expect(await queried(camera.management, camera.connection)).toEqual([]) + expect(camera.mock.requests).toEqual([]) + }) + + it('reports a Start whose Clip ID the record cannot save as a storage problem of the camera beside the Service Communication Failure it answers, ' + + 'printing nothing while the camera\'s channel has a subscriber', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { problems, reporter } = problemsOf(CAMERA) + const full = new Error('The disk is full.') + + await using camera = await clipCamera({ reporter }) + + serve(camera) + await judge(camera, 0) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync').mockImplementation(() => { + throw full + }) + + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + setItemSync.mockRestore() + + expect(problems).toEqual([ + { + accessoryUUID: CAMERA, + error: full, + kind: 'storage-failed', + level: 'warning', + sentence: 'Buffer Upload Command could not save the clip number: The disk is full.', + }, + ]) + expect(warn).not.toHaveBeenCalled() + }) + + it('holds every fragment from a held answer on, repeats the answer after a GOAWAY, and releases each fragment by the rule once it is answered', async () => { + await using camera = await clipCamera({ + answer: answers({ + 'session_1/high/segment_1001.m4s': [ + { hold: true }, + ], + }), + }) + + 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')) + + for (const index of [1, 2, 3]) { + serve(camera) + await judge(camera, index) + } + + expect(held(camera.recording)).toEqual([true, true, true, true]) + + camera.mock.goaway() + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1004.m4s')) + await stopAt(camera, endOf(camera, 3)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path === 'session_1/high/segment_1001.m4s')).toHaveLength(2) + expect(held(camera.recording)).toEqual([false, false, true, true]) + }) + + it('ends a clip CANCELED and never by the grace when HomeKit Camera Active turns off in the turn its recording ends', async () => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout'], + }) + + 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')) + camera.recording.end() + camera.operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + await vi.advanceTimersByTimeAsync(SERVED_RECORDING_GRACE) + + expect((await clipEvents(camera, clipID)).map(({ type }) => type)).toEqual([CameraBufferEventType.CMAF_SESSION_START, CameraBufferEventType.CMAF_ERROR]) + expect(await ended(camera, clipID)).toMatchObject({ cmafError: CMAFError.CANCELED }) + }) + + it.each([ + [ + 'every fragment served judged Should Record, at its last fragment', + 3, + 3, + ], + [ + 'its last two fragments not yet judged, at the latest judged Should Record, those two never requested', + 4, + 2, + ], + ])('finalizes a clip by the grace when its data stream connection closes mid-clip, with %s', async (_name, served, sent) => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout'], + }) + + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + serve(camera, served - 1) + + for (let index = 1; index < sent; index++) { + await judge(camera, index) + } + + await eventually(() => expect(paths(camera)).toContain(segmentsOf(1n, sent).at(-1))) + camera.recording.end() + await vi.advanceTimersByTimeAsync(SERVED_RECORDING_GRACE) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, sent)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(sent)) + }) + + it('finalizes a clip at the hub\'s Stop when it comes before the grace of a closed connection', async () => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout'], + }) + + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + camera.recording.end() + await stopAt(camera, endOf(camera, 0)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + it('writes nothing to the record once a destroy mid-clip has begun, a 208 pending and the event counter one short of the half step', async () => { + await using camera = await clipCamera({ + answer: answers({ + 'session_1/index.m3u8': [ + { delay: 300, status: 208 }, + ], + }), + }) + const sequenceNumber = camera.management.services.buffer.getCharacteristic(Characteristic.BufferEventSequenceNumber) + + serve(camera) + await judge(camera, 0) + + // The counter also numbers the error event an overflow queues, which is why the loop drives edges until the counter reaches its target: the Start's Session Start + // takes it to one short of the half step, and the clip's end would reach it. + while ((sequenceNumber.value as number) < Number(SKIP_AHEAD / 2n) - 2) { + camera.management.motionChanged((sequenceNumber.value as number) % 2 === 0) + } + + await startAt(camera, placeOf(camera, 0)) + await eventually(() => expect(paths(camera)).toContain('session_1/index.m3u8')) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + + await camera.management.destroy() + await sleep(400) + + expect(setItemSync).not.toHaveBeenCalled() + }) + + it('keeps the record cleared at an unpairing\'s reset when a clip\'s cancel takes the counter across the half step', async () => { + await using camera = await clipCamera() + const sequenceNumber = camera.management.services.buffer.getCharacteristic(Characteristic.BufferEventSequenceNumber) + + serve(camera) + await judge(camera, 0) + + // The counter also numbers the error event an overflow queues, which is why the loop drives edges until the counter reaches its target: the Start's Session Start + // takes it to one short of the half step, and the clip's cancel at the reset reaches it. + while ((sequenceNumber.value as number) < Number(SKIP_AHEAD / 2n) - 2) { + camera.management.motionChanged((sequenceNumber.value as number) % 2 === 0) + } + + await startAt(camera, placeOf(camera, 0)) + + const { clipMark } = RecordingProvisioning.load(USERNAME, CAMERA)! + + // The accessory clears the record to its marks before it resets its controllers, which is why the reset meets a record changed behind the management. + RecordingProvisioning.clearProvisioning(USERNAME) + camera.management.handleFactoryReset() + + // The cancel's save moved the sequence mark: the record was written during the reset, and it holds the marks alone. + expect(RecordingProvisioning.load(USERNAME, CAMERA)).toStrictEqual({ clipMark, sequenceMark: SKIP_AHEAD / 2n }) + expect(await needsUpdate(camera.management, camera.connection)).toBe(true) + }) + + it('writes the marks alone into a record cleared behind the management when a motion edge takes the counter across the half step', async () => { + await using camera = await clipCamera() + const sequenceNumber = camera.management.services.buffer.getCharacteristic(Characteristic.BufferEventSequenceNumber) + + // The counter also numbers the error event an overflow queues, which is why the loop drives edges until the counter is one short of the half step. + while ((sequenceNumber.value as number) < Number(SKIP_AHEAD / 2n) - 1) { + camera.management.motionChanged((sequenceNumber.value as number) % 2 === 0) + } + + RecordingProvisioning.clearProvisioning(USERNAME) + camera.management.motionChanged(true) + + expect(RecordingProvisioning.load(USERNAME, CAMERA)).toStrictEqual({ sequenceMark: SKIP_AHEAD / 2n }) + }) + + it('writes the marks alone into a record cleared behind the management before a Start, its Clip ID the held mark plus one', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + RecordingProvisioning.clearProvisioning(USERNAME) + + expect(await startAt(camera, placeOf(camera, 0))).toBe(1n) + expect(RecordingProvisioning.load(USERNAME, CAMERA)).toStrictEqual({ clipMark: 1n, sequenceMark: 0n }) + }) + + it('sends the next fragment on a new session after a GOAWAY between live fragments, its repeats unspent', async () => { + const open = vi.spyOn(IngestSession, 'open') + + await using camera = await clipCamera({ + answer: answers({ + 'session_1/high/segment_1003.m4s': [ + { status: 503 }, + ], + 'session_1/high/segment_1004.m4s': [ + { status: 503 }, + ], + }), + }) + + 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')) + await sleep(100) + camera.mock.goaway() + await sleep(100) + + for (const index of [1, 2, 3]) { + serve(camera) + await judge(camera, index) + } + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1004.m4s')) + await stopAt(camera, endOf(camera, 3)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(open).toHaveBeenCalledTimes(4) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(4)) + }) + + it('hands each verdict to the feed through Buffer Activity Command, refusing an Activity outside the two, and holds while provisioned for uploads', async () => { + const connection = buildEmitterConnection() + const feed = new ServedRecordings(QUIET_FEED) + const management = new CMAFRecordingManagement({ + feed, + policy: new OperatingModePolicy(), + reporter: detachedReporter(), + }) + + management.handleAccessoryContext(context(USERNAME)) + + expect(feed.holding).toBe(false) + + await writeCertificate(management, await certify(management, connection), connection) + + expect(feed.holding).toBe(false) + + // A certificate and a point alone, or with a Camera Key no content key derives from, hold nothing, and a usable key holds. + await writePoint(management, POINT, connection) + + expect(feed.holding).toBe(false) + + await writeKey(management, SHORT_KEY, connection) + + expect(feed.holding).toBe(false) + + await writeKey(management, CAMERA_KEY, connection) + + expect(feed.holding).toBe(true) + + await write(management, Characteristic.CameraClientCertificate, '', connection) + + expect(feed.holding).toBe(false) + await management.destroy() + + await using camera = await clipCamera() + + serve(camera, 3) + await judge(camera, 2, false) + + expect(held(camera.recording)).toEqual([false, true, true]) + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(await startAt(camera, placeOf(camera, 1), SESSION + 1n)).toBe(1n) + + serve(camera) + + const refused = encodeBufferActivityCommandRequest({ + activity: 3 as BufferActivity, + duration: FRAGMENT, + start: placeOf(camera, 3), + }) + + await expect(characteristic(camera.management, Characteristic.BufferActivityCommand).handleSetRequest(refused, camera.connection)) + .rejects + .toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(held(camera.recording)).toEqual([false, true, true, true]) + }) + + it('opens a clip on an ended recording at the Start its last verdict draws after the hub\'s close, and finalizes it at the Stop', async () => { + await using camera = await clipCamera() + + serve(camera, 3) + await judge(camera, 0, false) + await judge(camera, 1, false) + camera.recording.end() + await judge(camera, 2) + + const clipID = await startAt(camera, placeOf(camera, 1)) + + await stopAt(camera, endOf(camera, 2)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(segmentsOf(1n, 2).map(path => body(camera, path))).toEqual(camera.served.slice(1)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + it('runs two clips on one recording as a hub drives them, the second opening at a fragment the first read and never requested', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const first = await startAt(camera, placeOf(camera, 0)) + + for (const index of [1, 2]) { + serve(camera) + await judge(camera, index) + } + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1003.m4s')) + serve(camera) + await judge(camera, 3, false) + await stopAt(camera, placeOf(camera, 3)) + + expect((await ended(camera, first)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + + serve(camera) + await judge(camera, 4) + + const second = await startAt(camera, placeOf(camera, 3), SESSION + 1n) + + camera.recording.end() + await stopAt(camera, endOf(camera, 4), BufferUploadStopAction.FINALIZE, SESSION + 1n) + + expect([first, second]).toEqual([1n, 2n]) + expect((await ended(camera, second)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.startsWith('session_1/high/segment_'))).toEqual(segmentsOf(1n, 3)) + expect(segmentsOf(1n, 3).map(path => body(camera, path))).toEqual(camera.served.slice(0, 3)) + expect(segmentsOf(2n, 2).map(path => body(camera, path))).toEqual(camera.served.slice(3)) + }) + + it('opens at its Start\'s fragment and uploads its window whole while its multivariant playlist\'s answer is held past two verdicts and the close', async () => { + await using camera = await clipCamera({ + answer: answers({ + 'session_1/index.m3u8': [ + { delay: 400, status: 201 }, + ], + }), + }) + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + // The verdicts and the close follow the Start's answer at once, long before the clip's first object is answered. + for (const index of [1, 2]) { + serve(camera) + await judge(camera, index) + } + + camera.recording.end() + + expect(held(camera.recording)).toEqual([true, true, true]) + + await stopAt(camera, endOf(camera, 2)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).indexOf('session_1/index.m3u8')).toBe(0) + expect(segmentsOf(1n, 3).map(path => body(camera, path))).toEqual(camera.served) + }) + + it('requests no fragment until a verdict brings it into the window, nor past a stop a later verdict reads beyond, the playlist listing each one sent', async () => { + // The stop's last segment is answered late, which is why the Stop, and the verdict after it, arrive while the clip still drains to its stop. + await using camera = await clipCamera({ + answer: answers({ + 'session_1/high/segment_1002.m4s': [ + { delay: 300, status: 201 }, + ], + }), + }) + + 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')) + serve(camera) + await sleep(100) + + expect(paths(camera)).not.toContain('session_1/high/segment_1002.m4s') + + await judge(camera, 1) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + serve(camera) + await judge(camera, 2, false) + await stopAt(camera, placeOf(camera, 2)) + serve(camera) + await judge(camera, 3) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, 2)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + it('stops at the latest fragment requested when a Stop ends before it, the playlist listing every segment the folder holds', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + for (const index of [1, 2]) { + serve(camera) + await judge(camera, index) + } + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1003.m4s')) + await stopAt(camera, endOf(camera, 0)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, 3)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(3)) + }) + + it.each([ + ['uploads on through the fragment whose end matches it', true, 4], + ['finalizes at the recording\'s last fragment when the recording ends first', false, 3], + ])('keeps a Stop naming a fragment end not yet served and %s', async (_name, served, sent) => { + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + await stopAt(camera, endOf(camera, 1) + 2n * FRAGMENT) + serve(camera) + + if (served) { + serve(camera) + } else { + camera.recording.end() + } + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, sent)) + expect(segmentsOf(1n, sent).map(path => body(camera, path))).toEqual(camera.served.slice(0, sent)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(sent)) + }) + + it.each([ + ['at the held fragment\'s end, listing the fragments before the rejected one', 1, 2], + ['past the rejected fragment, sending it because the Stop includes it', 3, 4], + ])('holds a clip at the fragment before a Should Not Record verdict until its Stop, whatever a later verdict reads, and stops %s', async (_name, stop, sent) => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + serve(camera, 3) + await judge(camera, 1) + await judge(camera, 2, false) + await judge(camera, 3) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + await sleep(100) + + expect(paths(camera)).not.toContain('session_1/high/segment_1003.m4s') + + await stopAt(camera, endOf(camera, stop)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, sent)) + expect(segmentsOf(1n, sent).map(path => body(camera, path))).toEqual(camera.served.slice(0, sent)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(sent)) + }) + + it('finalizes a held clip whose recording ended with no Stop by the grace, sending nothing past its hold', async () => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout'], + }) + + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + serve(camera, 3) + await judge(camera, 1) + await judge(camera, 2, false) + await judge(camera, 3) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + camera.recording.end() + await vi.advanceTimersByTimeAsync(SERVED_RECORDING_GRACE) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, 2)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + it('keeps a clip at its first hold through a second Should Not Record verdict after a Should Record, sending nothing past it before its Stop', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + serve(camera, 4) + await judge(camera, 1) + await judge(camera, 2, false) + await judge(camera, 3) + await judge(camera, 4, false) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + await sleep(100) + + expect(paths(camera)).not.toContain('session_1/high/segment_1003.m4s') + + await stopAt(camera, endOf(camera, 1)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, 2)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(2)) + }) + + it('holds neither a clip opened after a Should Not Record verdict nor a clip at a verdict on another recording', async () => { + await using camera = await clipCamera() + + serve(camera, 4) + await judge(camera, 0) + await judge(camera, 1, false) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + await judge(camera, 2) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1003.m4s')) + + const older = camera.recording + + begin(camera, WALL_CLOCK + 60 * 1000) + serve(camera) + await judge(camera, 0, false) + await judge(camera, 3, true, older) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1004.m4s')) + await stopAt(camera, endOf(camera, 3, older)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(4)) + }) + + it('ends a hold a paused clip takes at its resume, the resumed clip uploading on past the fragment the hold kept back', 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)) + + await stopAt(camera, endOf(camera, 1), BufferUploadStopAction.PAUSE) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1002.m4s')) + await sleep(100) + serve(camera, 2) + await judge(camera, 2, false) + await judge(camera, 3) + + expect(await startAt(camera, placeOf(camera, 2))).toBe(clipID) + + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1004.m4s')) + await stopAt(camera, endOf(camera, 3)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(segmentsOf(1n, 4).map(path => body(camera, path))).toEqual(camera.served) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(4)) + }) + + it('finalizes a clip at the Stop after its recording\'s close and a last Should Not Record verdict, listing every fragment before it', async () => { + await using camera = await clipCamera() + + serve(camera, 2) + await judge(camera, 0, false) + await judge(camera, 1) + + const clipID = await startAt(camera, placeOf(camera, 0)) + + for (const index of [2, 3]) { + serve(camera) + await judge(camera, index) + } + + serve(camera) + await eventually(() => expect(paths(camera)).toContain('session_1/high/segment_1004.m4s')) + camera.recording.end() + await judge(camera, 4, false) + await stopAt(camera, endOf(camera, 3)) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(segmentsOf(1n, 4).map(path => body(camera, path))).toEqual(camera.served.slice(0, 4)) + expect(body(camera, 'session_1/high/index.m3u8').toString()).toBe(closing(4)) + }) + + it('opens a StartAndStop with both bounds set, and answers an ended clip\'s Session ID with its Clip ID for sixty seconds', async () => { + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout'], + }) + + await using camera = await clipCamera() + + serve(camera, 3) + await judge(camera, 0) + await judge(camera, 1) + + const clipID = await command(camera, { + command: BufferUploadCommandType.START_AND_STOP, + sessionID: SESSION, + start: placeOf(camera, 0), + stop: endOf(camera, 1), + stopAction: BufferUploadStopAction.FINALIZE, + }) + + expect((await ended(camera, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(camera).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(1n, 2)) + expect(await startAt(camera, placeOf(camera, 0))).toBe(clipID) + expect(await stopAt(camera, endOf(camera, 1))).toBe(clipID) + + await vi.advanceTimersByTimeAsync(60 * 1000) + + await expect(stopAt(camera, endOf(camera, 1))).rejects.toBe(HAPStatus.RESOURCE_DOES_NOT_EXIST) + expect(paths(camera).filter(path => path === 'session_1/index.m3u8')).toHaveLength(1) + }) + + it('refuses a Stop naming no session, a malformed command, and a Start with recording disallowed or before provisioning', async () => { + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + await expect(stopAt(camera, endOf(camera, 0))).rejects.toBe(HAPStatus.RESOURCE_DOES_NOT_EXIST) + await expect(command(camera, { command: BufferUploadCommandType.START, sessionID: SESSION })).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + await expect(command(camera, { + command: BufferUploadCommandType.STOP, + sessionID: SESSION, + stop: endOf(camera, 0), + })).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + await expect(command(camera, { + command: BufferUploadCommandType.START_AND_STOP, + sessionID: SESSION, + start: placeOf(camera, 0), + })).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + + camera.recordingService.updateCharacteristic(Characteristic.Active, false) + + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + + camera.recordingService.updateCharacteristic(Characteristic.Active, true) + await write(camera.management, Characteristic.CameraRecordingPublishingPoint, '', camera.connection) + + await expect(startAt(camera, placeOf(camera, 0))).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(camera.mock.requests).toEqual([]) + }) + + it('ends a clip CANCELED once, nothing rejecting, when recording is switched off while its idle session closes before its first object goes', async () => { + await using camera = await clipCamera() + const open = IngestSession.open.bind(IngestSession) + let clipID = 0n + let events: CameraBufferEvent[] = [] + + // The publishing point ends the clip's first session idle before its multivariant playlist goes, and recording is switched off while the clip + // closes that session. + vi.spyOn(IngestSession, 'open').mockImplementationOnce(async (sessionOptions) => { + const session = await open(sessionOptions) + const dispose = session[Symbol.asyncDispose].bind(session) + + session[Symbol.asyncDispose] = async () => { + camera.recordingService.updateCharacteristic(Characteristic.Active, false) + await dispose() + } + await eventually(() => expect(camera.mock.openSessions).toBe(1)) + camera.mock.goaway() + // @ts-expect-error: private access + await eventually(() => expect(session.failure).toBeDefined()) + + return session + }) + + serve(camera) + await judge(camera, 0) + + const lines = captureDebug('HAP-NodeJS:Camera:CMAFRecording', 'HAP-NodeJS:Camera:Ingest', 'HAP-NodeJS:Camera:ServedRecording') + const rejections = await unhandledRejections(async () => { + clipID = await startAt(camera, placeOf(camera, 0)) + await ended(camera, clipID) + events = await clipEvents(camera, clipID) + await camera.management.destroy() + }) + + expect(rejections).toEqual([]) + expect(events.filter(({ type }) => type !== CameraBufferEventType.CMAF_SESSION_START)).toEqual([ + expect.objectContaining({ cmafError: CMAFError.CANCELED, type: CameraBufferEventType.CMAF_ERROR }), + ]) + expect(camera.mock.requests).toEqual([]) + expect(lines.filter(line => line.includes('failure of its own'))).toEqual([]) + }) + + it('ends a clip with CMAF Error UNKNOWN and a warning, nothing rejecting, when its upload throws, and another when a reading throws', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + await using camera = await clipCamera() + + serve(camera) + await judge(camera, 0) + + const rejections = await unhandledRejections(async () => { + const { run } = camera.recording + + // The multivariant playlist's packaging reads the sample entries of the run the clip read, which throw once read, and the upload throws. + vi.spyOn(camera.recording, 'run', 'get').mockImplementationOnce(() => ({ + ...run!, + get sampleEntries(): never { + throw new Error('The sample entries cannot be read.') + }, + })) + + const failedUpload = await startAt(camera, placeOf(camera, 0)) + + expect(await ended(camera, failedUpload)).toMatchObject({ cmafError: CMAFError.UNKNOWN, type: CameraBufferEventType.CMAF_ERROR }) + + // The reading's throw is on a recording of its own, and no reading of the first clip's meets it. + begin(camera, WALL_CLOCK + 60 * 1000) + serve(camera) + await judge(camera, 0) + vi.spyOn(camera.recording, 'run', 'get').mockImplementationOnce(() => { + throw new Error('The run cannot be read.') + }) + + const failedReading = await startAt(camera, placeOf(camera, 0), SESSION + 1n) + + expect(await ended(camera, failedReading)).toMatchObject({ cmafError: CMAFError.UNKNOWN, type: CameraBufferEventType.CMAF_ERROR }) + await camera.management.destroy() + }) + + expect(rejections).toEqual([]) + expect(camera.mock.requests).toEqual([]) + expect(warn.mock.calls).toEqual([ + [ + expect.stringMatching(/^A clip's upload failed\. The library met a failure of its own: The sample entries cannot be read\.$/), + ], + [ + expect.stringMatching(/^A clip's upload failed\. The library met a failure of its own: The run cannot be read\.$/), + ], + ]) + }) + }) + + describe('camera controller wiring', () => { + const KEYS = CMAFRecordingManagement.SERVICE_KEYS + const ACCESSORY_UUID = uuid.generate('cmaf recording management wiring') + + // A selected recording configuration the fixtures' recording options accept, as a hub writes it. + const SELECTED_CONFIGURATION = 'AR0BBKAPAAACCAEAAAAAAAAAAwsBAQACBgEEoA8AAAIkAQEAAhIBAQECAQIDBNAHAAAEBKAPAAADCwECsAQCAkAGAwEYAxQBAQACDwEBAQIBAAMBAwQEQAAAAA==' + + // 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 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[] = [] + + afterEach(async () => { + for (const accessory of accessories.splice(0)) { + await accessory.destroy() + } + + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + }) + + // A recording delegate whose recording yields each packet a row hands it, as it is handed, until the hub's close aborts it. + class LiveDelegate extends MockDelegate { + private readonly queued: RecordingPacket[] = [] + + private arrival = deferred() + + push(...packets: RecordingPacket[]): void { + this.queued.push(...packets) + this.arrival.resolve() + } + + override async* handleRecordingStreamRequest(_streamId?: number, signal?: AbortSignal): AsyncGenerator { + const aborted = new Promise(resolve => signal?.addEventListener('abort', () => resolve(), { once: true })) + + while (signal?.aborted !== true) { + const packet = this.queued.shift() + + if (packet === undefined) { + this.arrival = deferred() + await Promise.race([this.arrival.promise, aborted]) + continue + } + + yield packet + + if (packet.isLast) { + return + } + } + } + } + + // 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 }) + const camera = new CameraController(options) + + cameras.push(camera) + + return { camera, tier: stream } + } + + // A legacy camera without the block, recording through the delegate given with the legacy recording options. + function legacyCamera(delegate: MockDelegate): CameraController { + const camera = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + cameras.push(camera) + + return camera + } + + function managementOf(camera: CameraController): CMAFRecordingManagement { + // @ts-expect-error: private access + return camera.cmafRecordingManagement + } + + function feedOf(camera: CameraController): ServedRecordings { + // @ts-expect-error: private access + return camera.servedRecordings + } + + function prefixedKeys(map: Record): string[] { + return Object.keys(map).filter(key => key.startsWith('cameraCapabilities:')) + } + + // An accessory carrying the camera, published behind the bridge given or else through the advertiser the suite mocks, which means nothing is announced. + async function publishedWith(camera: CameraController, bridge?: Bridge): Promise { + const accessory = new Accessory('Camera', ACCESSORY_UUID) + + accessories.push(accessory) + accessory.configureController(camera) + bridge?.addBridgedAccessory(accessory) + await (bridge ?? accessory).publish({ + advertiser: MDNSAdvertiser.BONJOUR, + category: Categories.CAMERA, + pincode: '031-45-154', + username: USERNAME, + }) + + return accessory + } + + /* Switches the camera's recording on as a hub does, a configuration selected on a camera that offers one and recording Active, and opens a recording + * over a data stream connection. A camera that records from its camera buffer is first handed its recorded tier's initialization segment and first + * keyframe, which its recording's first segment opens on. + */ + async function pull(camera: CameraController, tier?: () => TierStream): Promise { + const { dataStreamManagement, options, recordingManagementService } = camera.recordingManagement! + + if (options) { + recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + } + + recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + await settle() + + if (tier) { + tier().write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS, sound: false })) + frames(tier(), 0, 1, { sound: false }) + } + + const client = await DataStreamClient.connect(dataStreamManagement) + + client.request(Protocols.DATA_SEND, Topics.OPEN, { + reason: 'motion', + streamId: 1, + target: 'controller', + type: 'ipcamera.recording', + }) + await settle() + + return client + } + + // A published camera that records from its camera buffer, whose HKSV3 recording management is provisioned against a mock publishing point, with its + // recording open over a data stream connection and the recording its stream serves, which the row's frames on the recorded tier's stream feed. + interface WiredClip extends AsyncDisposable { + readonly accessory: Accessory + readonly camera: CameraController + readonly client: DataStreamClient + readonly connection: HAPConnection + readonly management: CMAFRecordingManagement + readonly mock: MockIngestServer + readonly recording: ServedRecording + // The recorded tier's stream, and the frames the row has written to it. + readonly tier: () => TierStream + written: number + } + + async function wiredClip(mockOptions: MockIngestServerOptions = {}, { bridge }: { bridge?: Bridge } = {}): Promise { + const { camera, tier } = wiredCamera() + const accessory = await publishedWith(camera, bridge) + const management = managementOf(camera) + const connection = buildEmitterConnection() + const mock = await MockIngestServer.start({ clientCAs: authority.pem, ...mockOptions }) + + await writeCertificate(management, await certify(management, connection), connection) + await writeKey(management, CAMERA_KEY, connection) + await writePoint(management, { + serverCACertificates: [ + { + certificate: new X509Certificate(INGEST_CERTIFICATES.serverCA).raw, + }, + ], + url: mock.url, + }, connection) + + const begin = vi.spyOn(feedOf(camera), 'begin') + const client = await pull(camera, tier) + const recording = begin.mock.results[0].value as ServedRecording + + await eventually(() => expect(recording.run).toBeDefined()) + + return { + accessory, + async [Symbol.asyncDispose]() { + await mock[Symbol.asyncDispose]() + }, + camera, + client, + connection, + management, + mock, + recording, + tier, + written: 1, + } + } + + // Writes the recorded tier's frames on until the recorder has cut the given number of segments more, each from a keyframe to the one 4 seconds on, + // and waits until the camera's stream serves them. + async function stream(clip: WiredClip, count = 1): Promise { + const served = clip.recording.length + const closing = (served + count) * SEGMENT_FRAMES + + frames(clip.tier(), clip.written, closing + 1, { sound: false }) + clip.written = closing + 1 + await eventually(() => expect(clip.recording.length).toBe(served + count)) + } + + it('builds its services under their keys at the end of the block, and adopts them at a restore, building one the saved map lacks', () => { + const map = wiredCamera().camera.constructServices() + + expect(prefixedKeys(map).slice(-3)).toEqual([KEYS.buffer, KEYS.key, KEYS.certificate]) + expect(map[KEYS.buffer]!.UUID).toBe(Service.CameraBufferManagement.UUID) + expect(map[KEYS.key]!.UUID).toBe(Service.CameraKeyManagement.UUID) + expect(map[KEYS.certificate]!.UUID).toBe(Service.CameraClientCertificateManagement.UUID) + + const saved = savedMapOf(wiredCamera().camera) + const adopting = wiredCamera().camera + + expect(adopting.initWithServices(saved)).toBeUndefined() + expect(managementOf(adopting).services).toEqual({ buffer: saved[KEYS.buffer], certificate: saved[KEYS.certificate], key: saved[KEYS.key] }) + + const lacking = savedMapOf(wiredCamera().camera) + + delete lacking[KEYS.key] + + const restored = wiredCamera().camera.initWithServices(lacking)! + + expect(prefixedKeys(restored).slice(-3)).toEqual([KEYS.buffer, KEYS.key, KEYS.certificate]) + expect(restored[KEYS.key]!.UUID).toBe(Service.CameraKeyManagement.UUID) + }) + + 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() + + camera.constructServices() + camera.configureServices() + handPublishedContext(camera) + + const begin = vi.spyOn(feedOf(camera), 'begin') + const client = await pull(camera, tier) + + frames(tier(), 1, SEGMENT_FRAMES + 1, { sound: false }) + await eventually(() => expect(client.events(Protocols.DATA_SEND, Topics.DATA)).toHaveLength(2)) + + const segment = client.events(Protocols.DATA_SEND, Topics.DATA)[1].packets[0].data as Buffer + + expect(segment.subarray(4, 8).toString('latin1')).toBe('prft') + expect((begin.mock.results[0].value as ServedRecording).length).toBe(1) + client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason: HDSProtocolSpecificErrorReason.NORMAL, streamId: 1 }) + + const [initialization, fragment] = skeletonPackets() + const delegate = new LiveDelegate() + const legacy = legacyCamera(delegate) + + legacy.constructServices() + legacy.configureServices() + + const legacyClient = await pull(legacy) + + delegate.push({ data: initialization, isLast: false }, { data: fragment, isLast: false }) + await eventually(() => expect(legacyClient.events(Protocols.DATA_SEND, Topics.DATA)).toHaveLength(2)) + + expect(legacyClient.events(Protocols.DATA_SEND, Topics.DATA)[1].packets[0].data).toEqual(fragment) + expect(feedOf(legacy)).toBeUndefined() + legacyClient.event(Protocols.DATA_SEND, Topics.CLOSE, { reason: HDSProtocolSpecificErrorReason.NORMAL, streamId: 1 }) + }) + + it('loads a published camera\'s record at its context, and reads it again at a factory reset', async () => { + const connection = buildEmitterConnection() + + RecordingProvisioning.save(USERNAME, ACCESSORY_UUID, { cameraKey: CAMERA_KEY }) + + const { camera } = wiredCamera() + + await publishedWith(camera) + + expect(decodeCameraKeyID(await read(managementOf(camera), Characteristic.CameraKeyID, connection)).keyID).toBe(CAMERA_KEY.keyNumber) + + RecordingProvisioning.save(USERNAME, ACCESSORY_UUID, { + cameraKey: { ...CAMERA_KEY, keyNumber: 9n }, + }) + camera.handleFactoryReset() + + expect(decodeCameraKeyID(await read(managementOf(camera), Characteristic.CameraKeyID, connection)).keyID).toBe(9n) + }) + + it('writes the marks alone at an unpairing whose motion zones reset raises a motion edge that takes the counter across the half step', async () => { + vi.spyOn(EventedHTTPServer, 'destroyExistingConnectionsAfterUnpair').mockImplementation(() => undefined) + + const hub = 'AB:CD:EF:00:11:23' + const zones = motionZonesFunction() + const camera = new CameraController(twoSensorCameraOptions({ first: zones })) + + cameras.push(camera) + + const accessory = await publishedWith(camera) + const management = managementOf(camera) + const connection = buildEmitterConnection() + + await provision(management, connection) + + const sequenceNumber = management.services.buffer.getCharacteristic(Characteristic.BufferEventSequenceNumber) + const motionDetected = camera.motionService!.getCharacteristic(Characteristic.MotionDetected) + + // The counter also numbers the error event an overflow queues, which is why the loop drives edges until the counter is one short of the half step. + while ((sequenceNumber.value as number) < Number(SKIP_AHEAD / 2n) - 1) { + management.motionChanged((sequenceNumber.value as number) % 2 === 0) + } + + // The zones function raises Motion Detected inside its reset call, which the controller's reset makes before the HKSV3 recording management's. + zones.mockImplementation(async (_zones, reason) => { + if (reason === 'reset') { + motionDetected.updateValue(motionDetected.value !== true) + } + }) + accessory._accessoryInfo!.addPairedClient(hub, randomBytes(32), PermissionTypes.ADMIN) + // @ts-expect-error: private access + accessory.handleRemovePairing({ username: hub } as HAPConnection, hub, () => undefined) + + expect(zones).toHaveBeenCalledWith(expect.anything(), 'reset', expect.any(AbortSignal)) + expect(RecordingProvisioning.load(USERNAME, ACCESSORY_UUID)).toStrictEqual({ sequenceMark: SKIP_AHEAD / 2n }) + }) + + it('ends its clip and drops it at a removal mid-clip, the record kept, and builds it again at the next configure, which loads the record', async () => { + const open = vi.spyOn(IngestSession, 'open') + + await using clip = await wiredClip({ + answer: answers({ + 'session_1/high/segment_1001.m4s': [ + { hold: true }, + ], + }), + }) + + await stream(clip) + await judge(clip, 0) + await startAt(clip, placeOf(clip, 0)) + await eventually(() => expect(paths(clip)).toContain('session_1/high/segment_1001.m4s')) + + const entry = RecordingProvisioning.load(USERNAME, ACCESSORY_UUID) + const feed = feedOf(clip.camera) + const place = placeOf(clip, 0) + + clip.accessory.removeController(clip.camera) + + const sessions = await Promise.all(open.mock.results.map(async ({ value }) => await (value as Promise))) + + // @ts-expect-error: private access + await eventually(() => expect(sessions.every(session => session.session.destroyed)).toBe(true)) + // @ts-expect-error: private access + expect(clip.recording.readers.size).toBe(0) + expect(feed.fragmentAt(place, 'start')).toBeUndefined() + await expect(queried(clip.management, clip.connection)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(RecordingProvisioning.load(USERNAME, ACCESSORY_UUID)).toEqual(entry) + + clip.accessory.configureController(clip.camera) + + const rebuilt = managementOf(clip.camera) + + expect(rebuilt).not.toBe(clip.management) + expect(rebuilt.services.buffer).not.toBe(clip.management.services.buffer) + expect(await read(rebuilt, Characteristic.CameraRecordingPublishingPoint, clip.connection)).not.toBe('') + }) + + it('ends its clip as canceled once its accessory\'s unpublish takes the camera out of service, and refuses a Start while it is out', async () => { + await using clip = await wiredClip() + + await stream(clip) + await judge(clip, 0) + + const clipID = await startAt(clip, placeOf(clip, 0)) + + await eventually(() => expect(paths(clip)).toContain('session_1/index.m3u8')) + + const lines = captureDebug('HAP-NodeJS:Camera:CMAFRecording') + + await clip.accessory.unpublish() + + expect(await ended(clip, clipID)).toMatchObject({ cmafError: CMAFError.CANCELED, type: CameraBufferEventType.CMAF_ERROR }) + await expect(startAt(clip, placeOf(clip, 0), SESSION + 1n)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(lines.filter(line => line.startsWith('Buffer Upload Command refuses a Start'))).toEqual([ + 'Buffer Upload Command refuses a Start while the camera holds no credential or no publishing point, recording is disallowed or the accessory is ' + + 'unpublished.', + ]) + }) + + it('ends its clip as canceled once the camera is manually disabled, and refuses a Start while it is', async () => { + await using clip = await wiredClip() + + await stream(clip) + await judge(clip, 0) + + const clipID = await startAt(clip, placeOf(clip, 0)) + + await eventually(() => expect(paths(clip)).toContain('session_1/index.m3u8')) + + // Manually Disabled as the Camera Capabilities service projects it. + clip.accessory.services.find(service => service.UUID === Service.CameraCapabilities.UUID)! + .getCharacteristic(Characteristic.ManuallyDisabled) + .updateValue(1) + + expect(await ended(clip, clipID)).toMatchObject({ cmafError: CMAFError.CANCELED, type: CameraBufferEventType.CMAF_ERROR }) + await expect(startAt(clip, placeOf(clip, 0), SESSION + 1n)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + }) + + describe('a source stated away', () => { + // The fragments the rows' recordings serve before the camera's source is stated away. + const SERVED = 2 + + /* A clip uploading the first of the fragments a recording served, each judged Should Record, when the camera's source is stated away, and its Clip + * ID. The recorder ends its recording at the statement with the end marker, which a row acknowledges as the hub does where it reads the clip to its + * end. + */ + async function uploadingAway(clip: WiredClip): Promise { + await stream(clip, SERVED) + + for (let index = 0; index < SERVED; index++) { + await judge(clip, index) + } + + const clipID = await startAt(clip, placeOf(clip, 0)) + + await eventually(() => expect(paths(clip)).toContain(`session_${clipID}/index.m3u8`)) + clip.camera.updateSourceState('away') + + return clipID + } + + // The hub acknowledges the recording's end marker, which closes the recording its stream served. + async function acknowledged(clip: WiredClip): Promise { + await eventually(() => expect(clip.client.events(Protocols.DATA_SEND, Topics.DATA).at(-1)?.endOfStream).toBe(true)) + clip.client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId: 1 }) + await eventually(() => expect(clip.recording.closed).toBe(true)) + } + + it.each([ + { available: false, state: 'away' }, + { available: true, state: 'available again before the hub\'s Stop' }, + ])('finishes a clip uploading as the source is stated away, the source $state, at the hub\'s Stop with Session Stop and its closing playlist', async ({ + available, + }) => { + await using clip = await wiredClip() + + const clipID = await uploadingAway(clip) + + expect((await clipEvents(clip, clipID)).map(({ type }) => type)).not.toContain(CameraBufferEventType.CMAF_ERROR) + + await acknowledged(clip) + + if (available) { + clip.camera.updateSourceState('available') + } + + // The Stop names the end of the last fragment served before the statement, never a moment past the recording's last. + await stopAt(clip, endOf(clip, SERVED - 1)) + + expect((await ended(clip, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect((await clipEvents(clip, clipID)).map(({ type }) => type)).not.toContain(CameraBufferEventType.CMAF_ERROR) + expect(paths(clip).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(clipID, SERVED)) + 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 })), + })) + }) + + it('uploads the segment its recorder closes as the source is stated away as its last, once the hub judges it, and finalizes at the hub\'s Stop with ' + + 'every segment its recording served', async () => { + await using clip = await wiredClip() + + const clipID = await uploadingAway(clip) + + await acknowledged(clip) + + // The recording serves the segment in progress the recorder closed at the statement, after those served before it. + expect(clip.recording.length).toBe(SERVED + 1) + + await judge(clip, SERVED) + await stopAt(clip, endOf(clip, SERVED)) + + expect((await ended(clip, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect((await clipEvents(clip, clipID)).map(({ type }) => type)).not.toContain(CameraBufferEventType.CMAF_ERROR) + expect(paths(clip).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(clipID, SERVED + 1)) + }) + + it('ends a clip uploading as the source is stated away with CMAF Error CANCELED once recording is switched off, sending nothing more', async () => { + await using clip = await wiredClip() + // Each object the clip puts and each event it queues, in the order of the calls: a request the mock reads only after the end still counts as one + // the clip wrote before it. + const put = vi.spyOn(IngestSession.prototype, 'put') + const enqueue = vi.spyOn(clip.management, 'enqueue') + const clipID = await uploadingAway(clip) + + clip.camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.INACTIVE) + + expect(await ended(clip, clipID)).toMatchObject({ cmafError: CMAFError.CANCELED, type: CameraBufferEventType.CMAF_ERROR }) + + await sleep(100) + + const end = enqueue.mock.invocationCallOrder[enqueue.mock.calls.findIndex(([event]) => event.type === CameraBufferEventType.CMAF_ERROR)] + const written = put.mock.calls.filter((_, index) => put.mock.invocationCallOrder[index] < end).map(([path]) => path) + + // Every request the mock read is one the clip put before its end, each put read once at most. + for (const path of paths(clip)) { + expect(written).toContain(path) + written.splice(written.indexOf(path), 1) + } + }) + + it('ends a clip uploading as the source is stated away with CMAF Error CANCELED once its accessory is unpublished, and refuses a Start then', async () => { + await using clip = await wiredClip() + + const clipID = await uploadingAway(clip) + + await clip.accessory.unpublish() + + expect(await ended(clip, clipID)).toMatchObject({ cmafError: CMAFError.CANCELED, type: CameraBufferEventType.CMAF_ERROR }) + await expect(startAt(clip, placeOf(clip, 0), SESSION + 1n)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + }) + + it.each([ + { end: 'its management\'s factory reset' }, + { end: 'the controller\'s removal' }, + ])('ends a clip uploading as the source is stated away with CMAF Error CANCELED at $end', async ({ end }) => { + await using clip = await wiredClip() + // The event each ended clip queues, read as it is queued, since a reset acknowledges the queue it empties and a removal drops the management. + const enqueue = vi.spyOn(clip.management, 'enqueue') + const clipID = await uploadingAway(clip) + + // The management's own reset, which the controller's runs before it turns recording off: the clip ends by the reset's path alone. + if (end === 'its management\'s factory reset') { + clip.management.handleFactoryReset() + } else { + clip.accessory.removeController(clip.camera) + } + + expect(enqueue.mock.calls.map(([event]) => event)).toContainEqual(expect.objectContaining({ + cmafError: CMAFError.CANCELED, + cmafSessionID: clipID, + type: CameraBufferEventType.CMAF_ERROR, + })) + }) + + it('opens a clip at a Start for a fragment served before the statement while the source is away', async () => { + await using clip = await wiredClip() + + await stream(clip) + await judge(clip, 0) + clip.camera.updateSourceState('away') + + const clipID = await startAt(clip, placeOf(clip, 0)) + + expect((await clipEvents(clip, clipID)).map(({ type }) => type)).toEqual([CameraBufferEventType.CMAF_SESSION_START]) + }) + + it('resumes a clip paused before the source is stated away at a Start under its Session ID, answering its own Clip ID and finishing at the hub\'s ' + + 'Stop', async () => { + await using clip = await wiredClip() + + await stream(clip, SERVED) + await judge(clip, 0) + await judge(clip, 1) + + const clipID = await startAt(clip, placeOf(clip, 0)) + + expect(await stopAt(clip, endOf(clip, 0), BufferUploadStopAction.PAUSE)).toBe(clipID) + await eventually(() => expect(paths(clip)).toContain(`session_${clipID}/high/segment_1001.m4s`)) + clip.camera.updateSourceState('away') + + expect(await startAt(clip, placeOf(clip, 1))).toBe(clipID) + expect((await clipEvents(clip, clipID)).map(({ type }) => type)).not.toContain(CameraBufferEventType.CMAF_ERROR) + + await eventually(() => expect(paths(clip)).toContain(`session_${clipID}/high/segment_1002.m4s`)) + await stopAt(clip, endOf(clip, 1)) + + expect((await ended(clip, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + }) + }) + + it('queues a Motion event at each edge the controller\'s one motion listener hands it, beside the attribution\'s list', async () => { + const { camera } = wiredCamera() + + await publishedWith(camera) + + const attribution = vi.spyOn(MotionAttribution.prototype, 'motionChanged') + const management = managementOf(camera) + const motionDetected = camera.motionService!.getCharacteristic(Characteristic.MotionDetected) + const connection = buildEmitterConnection() + + camera.updateMotionDetected(true) + motionDetected.updateValue(true) + motionDetected.updateValue(false) + + expect((await queried(management, connection)).filter(({ type }) => type === CameraBufferEventType.MOTION)).toEqual([ + expect.objectContaining({ active: true }), + expect.objectContaining({ active: false }), + ]) + expect(attribution.mock.calls).toEqual([ + [true], + [false], + ]) + }) + + it('serves a recording its recorder ends with the end marker whole and usable, a clip on it finalizing at its last fragment with Session Stop', async () => { + const segments = 2 + + await using clip = await wiredClip() + + await stream(clip, segments) + + for (let index = 0; index < segments; index++) { + await judge(clip, index) + } + + const clipID = await startAt(clip, placeOf(clip, 0)) + const recorder = clip.camera.recordingManagement!.delegate as BufferRecorder + + // The recorder ends the recording itself with the end marker at a long gap, after the segment in progress it closes as it stands. + recorder.lapsed() + await eventually(() => expect(clip.client.events(Protocols.DATA_SEND, Topics.DATA).at(-1)?.endOfStream).toBe(true)) + clip.client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId: 1 }) + await eventually(() => expect(clip.recording.closed).toBe(true)) + await stopAt(clip, BigInt.asUintN(64, placeOf(clip, segments - 1) + (60n << 32n))) + + expect((await ended(clip, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect((await clipEvents(clip, clipID)).map(({ type }) => type)).not.toContain(CameraBufferEventType.CMAF_ERROR) + expect(clip.recording.length).toBe(segments + 1) + // @ts-expect-error: private access + expect(clip.recording.unusable).toBe(false) + expect(paths(clip).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(clipID, segments + 1)) + }) + + it('uploads a clip from a recording its recorder serves from the recorded tier\'s stream, end to end, with nothing selected', async () => { + const updateRecordingConfiguration = vi.spyOn(BufferRecorder.prototype, 'updateRecordingConfiguration') + + await using clip = await wiredClip() + + await stream(clip, 2) + + const served = [0, 1].map(index => clip.recording.fragment(index)?.bytes) + + await judge(clip, 0) + await judge(clip, 1) + + const clipID = await startAt(clip, placeOf(clip, 0)) + + await stopAt(clip, endOf(clip, 1)) + + expect((await ended(clip, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(clip).filter(path => path.includes('/segment_'))).toEqual(segmentsOf(clipID, 2)) + expect(segmentsOf(clipID, 2).map(path => body(clip, path))).toEqual(served) + expect(body(clip, `session_${clipID}/high/high.init`)).toEqual(clip.recording.run?.initialization) + expect(clip.camera.recordingManagement!.recordingManagementService.testCharacteristic(Characteristic.SelectedCameraRecordingConfiguration)).toBe(false) + expect(updateRecordingConfiguration).not.toHaveBeenCalled() + }) + + it('resumes a paused clip on a later recording its recorder serves, sending that recording\'s initialization segment after a discontinuity', async () => { + const realNow = Date.now + + await using clip = await wiredClip() + + await stream(clip, 2) + await judge(clip, 0) + await judge(clip, 1) + + const clipID = await startAt(clip, placeOf(clip, 0)) + + expect(await stopAt(clip, endOf(clip, 1), BufferUploadStopAction.PAUSE)).toBe(clipID) + await eventually(() => expect(paths(clip)).toContain(`session_${clipID}/high/segment_1002.m4s`)) + + // The hub closes the first recording and opens the next a minute later on its timeline, which the recorder serves from its buffer's latest keyframe. + clip.client.event(Protocols.DATA_SEND, Topics.CLOSE, { reason: HDSProtocolSpecificErrorReason.NORMAL, streamId: 1 }) + await eventually(() => expect(clip.recording.closed).toBe(true)) + vi.spyOn(Date, 'now').mockImplementation(() => realNow() + 60 * 1000) + + const begin = vi.spyOn(feedOf(clip.camera), 'begin') + + clip.client.request(Protocols.DATA_SEND, Topics.OPEN, { + reason: 'motion', + streamId: 2, + target: 'controller', + type: 'ipcamera.recording', + }) + await eventually(() => expect(begin).toHaveBeenCalledTimes(2)) + + const later = begin.mock.results[1].value as ServedRecording + + frames(clip.tier(), clip.written, 2 * SEGMENT_FRAMES + clip.written, { sound: false }) + await eventually(() => expect(later.length).toBe(2)) + await judge(clip, 0, true, later) + await judge(clip, 1, true, later) + + expect(await startAt(clip, placeOf(clip, 0, later))).toBe(clipID) + await eventually(() => expect(paths(clip)).toContain(`session_${clipID}/high/segment_1004.m4s`)) + await stopAt(clip, endOf(clip, 1, later)) + + expect((await ended(clip, clipID)).type).toBe(CameraBufferEventType.CMAF_SESSION_STOP) + expect(paths(clip).filter(path => !path.endsWith('index.m3u8'))).toEqual([ + `session_${clipID}/high/high.init`, + ...segmentsOf(clipID, 2), + `session_${clipID}/high/high_2.init`, + ...segmentsOf(clipID, 4).slice(2), + ]) + expect(body(clip, `session_${clipID}/high/high_2.init`)).toEqual(later.run?.initialization) + + 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).toBe(closingMediaPlaylist({ + keyAttributes: keyAttributes(contentKeyOf(CAMERA_KEY)), + segments: [1, 1, 2, 2].map(initialization => ({ initialization, seconds: 4 })), + })) + }) + + it('walks each packet of a capability camera\'s recording once, the served recording taking what the writer\'s walk read', async () => { + const walks = vi.fn() + + vi.resetModules() + vi.doMock('../mp4/mp4Boxes.js', async (importOriginal) => { + const original = await importOriginal() + + return { + ...original, + walkBoxes: (...parameters: Parameters) => { + walks() + + return original.walkBoxes(...parameters) + }, + } + }) + + try { + await import('../../definitions/index.js') + + const { RecordingManagement } = await import('../RecordingManagement.js') + const { ServedRecordings: FreshServedRecordings } = await import('./ServedRecording.js') + const { DataStreamClient: FreshDataStreamClient } = await import('../../../test-utils/dataStreamClient.js') + const delegate = new LiveDelegate() + const feed = new FreshServedRecordings(QUIET_FEED) + const begin = vi.spyOn(feed, 'begin') + const management = new RecordingManagement(mockRecordingOptions, delegate, new Set([EventTriggerOption.MOTION]), undefined, undefined, { + feed, + reporter: detachedReporter(), + }) + const packets = skeletonPackets() + + management.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + management.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + + const client = await FreshDataStreamClient.connect(management.dataStreamManagement) + + client.request(Protocols.DATA_SEND, Topics.OPEN, { + reason: 'motion', + streamId: 1, + target: 'controller', + type: 'ipcamera.recording', + }) + await settle() + walks.mockClear() + delegate.push(...packets.map((data, index) => ({ data, isLast: index === packets.length - 1 }))) + await eventually(() => expect(client.events(Protocols.DATA_SEND, Topics.DATA)).toHaveLength(packets.length)) + + expect(walks).toHaveBeenCalledTimes(packets.length) + expect((begin.mock.results[0].value as ServedRecording).length).toBe(packets.length - 1) + client.event(Protocols.DATA_SEND, Topics.ACK, { endOfStream: true, streamId: 1 }) + management.destroy() + feed[Symbol.dispose]() + } finally { + vi.doUnmock('../mp4/mp4Boxes.js') + vi.resetModules() + } + }) + + it('ends its clip and its upload at a factory reset, emptying the queue and dropping every served recording, which the recording\'s end adds ' + + 'nothing to', async () => { + const open = vi.spyOn(IngestSession, 'open') + + await using clip = await wiredClip({ + answer: answers({ + 'session_1/high/segment_1001.m4s': [ + { hold: true }, + ], + }), + }) + const sequenceNumber = clip.management.services.buffer.getCharacteristic(Characteristic.BufferEventSequenceNumber) + + await stream(clip) + await judge(clip, 0) + await startAt(clip, placeOf(clip, 0)) + await eventually(() => expect(paths(clip)).toContain('session_1/high/segment_1001.m4s')) + + const counter = sequenceNumber.value as number + const feed = feedOf(clip.camera) + const place = placeOf(clip, 0) + + clip.camera.handleFactoryReset() + + const sessions = await Promise.all(open.mock.results.map(async ({ value }) => await (value as Promise))) + + // @ts-expect-error: private access + await eventually(() => expect(sessions.every(session => session.session.destroyed)).toBe(true)) + expect(await queried(clip.management, clip.connection)).toEqual([]) + expect(sequenceNumber.value as number).toBeGreaterThan(counter) + expect(clip.recording.closed).toBe(true) + expect(feed.fragmentAt(place, 'start')).toBeUndefined() + + const kept = clip.recording.length + const sent = clip.mock.requests.length + + // The recorder ends its recording at the reset, and its end marker reaches the hub after the feed has dropped the recording. + await eventually(() => expect(clip.client.events(Protocols.DATA_SEND, Topics.DATA).at(-1)?.endOfStream).toBe(true)) + + expect(clip.recording.length).toBe(kept) + expect(held(clip.recording)).not.toContain(true) + expect(clip.mock.requests).toHaveLength(sent) + + clip.accessory.removeController(clip.camera) + + expect(feedOf(clip.camera)).toBeUndefined() + }) + + it('drops its identity, its queue and its clip at an accessory\'s destroy mid-clip, its unpublish\'s end of the clip saving the sequence mark before the ' + + 'data is removed and nothing written to the record after it', async () => { + await using clip = await wiredClip() + const sequenceNumber = clip.management.services.buffer.getCharacteristic(Characteristic.BufferEventSequenceNumber) + + await stream(clip) + await judge(clip, 0) + + // The counter also numbers the error event an overflow queues, which is why the loop drives edges until the counter reaches its target: the Start's Session Start + // takes it to one short of the half step, and the clip's end would reach it. + while ((sequenceNumber.value as number) < Number(SKIP_AHEAD / 2n) - 2) { + clip.management.motionChanged((sequenceNumber.value as number) % 2 === 0) + } + + await startAt(clip, placeOf(clip, 0)) + await eventually(() => expect(paths(clip)).toContain('session_1/index.m3u8')) + + // Switching the recording on queued a save of the controller storage, which the row lets land first. The spy reads only what the destroy causes. + // @ts-expect-error: private access + await eventually(() => expect(clip.accessory.controllerStorage.queuedSaveTimeout).toBeUndefined()) + + const held = RecordingProvisioning.load(USERNAME, ACCESSORY_UUID)?.sequenceMark ?? -1n + const key = RecordingProvisioning.persistKey(USERNAME) + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + const removeItemSync = vi.spyOn(HAPStorage.storage(), 'removeItemSync') + + await clip.accessory.destroy() + await sleep(100) + + // The destroy's unpublish takes the camera out of service, and the clip's end that causes saves a sequence mark past the one the record held, before + // the data's removal deletes the record, which nothing writes after it. + const removed = removeItemSync.mock.invocationCallOrder[removeItemSync.mock.calls.findIndex(([removing]) => removing === key)] + const writes = setItemSync.mock.calls.map(([written, value], index) => [ + written, + BigInt((value as { accessories: Record }).accessories[ACCESSORY_UUID].sequenceMark) > held, + setItemSync.mock.invocationCallOrder[index] < removed, + ]) + + // @ts-expect-error: private access + expect(clip.camera.accessoryContext.username).toBeUndefined() + // @ts-expect-error: private access + expect(clip.management.clips.size).toBe(0) + await expect(queried(clip.management, clip.connection)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(writes).toEqual([ + [key, true, true], + ]) + expect(RecordingProvisioning.load(USERNAME, ACCESSORY_UUID)).toBeUndefined() + }) + + it('drops a bridged camera\'s identity and its clip at its bridge\'s destroy mid-clip, writing nothing to the record after the data is removed', async () => { + const bridge = new Bridge('Bridge', uuid.generate('cmaf recording management wiring bridge')) + + accessories.push(bridge) + + await using clip = await wiredClip({}, { bridge }) + + await stream(clip) + await judge(clip, 0) + await startAt(clip, placeOf(clip, 0)) + await eventually(() => expect(paths(clip)).toContain('session_1/index.m3u8')) + + // Switching the recording on queued a save of the controller storage, which the row lets land first. The spy reads only what the destroy causes. + // @ts-expect-error: private access + await eventually(() => expect(bridge.controllerStorage.queuedSaveTimeout).toBeUndefined()) + + const setItemSync = vi.spyOn(HAPStorage.storage(), 'setItemSync') + + await bridge.destroy() + await sleep(100) + + // @ts-expect-error: private access + expect(clip.camera.accessoryContext.username).toBeUndefined() + // @ts-expect-error: private access + expect(clip.management.clips.size).toBe(0) + expect(setItemSync).not.toHaveBeenCalled() + expect(RecordingProvisioning.load(USERNAME, ACCESSORY_UUID)).toBeUndefined() + }) + }) +}) + +// What the accessory cache holds of a characteristic. +function CharacteristicSerialize(characteristic: CharacteristicType): unknown { + return Characteristic.serialize(characteristic) +} diff --git a/src/lib/camera/srtp/SRTPContext.spec.ts b/src/lib/camera/srtp/SRTPContext.spec.ts new file mode 100644 index 000000000..b26c74264 --- /dev/null +++ b/src/lib/camera/srtp/SRTPContext.spec.ts @@ -0,0 +1,632 @@ +import { Buffer } from 'node:buffer' + +import { describe, expect, it, vi } from 'vitest' + +import { SRTP_MASTER_KEY, SRTP_MASTER_SALT } from '../../../test-utils/cameraFixtures.js' +import { ReferenceSRTP } from '../../../test-utils/ReferenceSRTP.js' +import { SRTPContext } from './SRTPContext.js' + +// The packets ffmpeg's SRTP muxer sent on loopback under SRTP_MASTER_KEY and SRTP_MASTER_SALT, each before and after protection, in sending order. The +// sequence wraps after the third, and the fourth is protected at ROC 1. +const RTP_VECTORS = [ + { + rtp: '8000fffdd18afd2012345678ffb8afb8ff382f38ffb8afb8ff382f38ffb8', + srtp: '8000fffdd18afd20123456783650b37177e9f7b1772cbbb145c51db7fbdf65a4fc84fda3d6944bc6', + }, + { + rtp: '8000fffed18afd3212345678afb8ff382f38ffb8afb8ff382f38ffb8afb8', + srtp: '8000fffed18afd32123456780c402d7e3d007aa263daf97f34b2d404a11e8f94896a54df5b7fc96f', + }, + { + rtp: '8000ffffd18afd4412345678ff382f38ffb8afb8ff382f38ffb8afb8ff38', + srtp: '8000ffffd18afd44123456788c6518efe8485a37cbad050956038b34d71f93834ee94184e62477ea', + }, + { + rtp: '80000000d18afd56123456782f38ffb8afb8ff382f38ffb8afb8ff382f38', + srtp: '80000000d18afd5612345678c5e9a16eacf6868e68e13c9f125e2503eb7707c3a42eeba09e1382ba', + }, +] + +// The sender report the muxer sent first, before and after protection: SRTCP index 0, the E flag set. +const RTCP_VECTOR = { + rtcp: '80c8000612345678ee9aa04ed7ced916d18afd200000000000000000', + srtcp: '80c80006123456789ff3933a380cfd4efd8689ecea0ce67e8f66b5d18000000000f3c05003353a8a9b87', +} + +// An RTP packet of the given shape: its CSRC count, a header extension of the given words, its payload length and its padding, each octet distinct. +function rtpPacket({ csrcs = 0, extensionWords, padding = 0, payload, sequence, ssrc = 0x12345678 }: { + csrcs?: number + extensionWords?: number + padding?: number + payload: number + sequence: number + ssrc?: number +}): Buffer { + const extension = extensionWords === undefined + ? 0 + : 4 + 4 * extensionWords + const packet = Buffer.alloc(12 + 4 * csrcs + extension + payload + padding) + + packet[0] = 0x80 | (padding > 0 + ? 0x20 + : 0) | (extensionWords === undefined + ? 0 + : 0x10) | csrcs + packet[1] = 96 + packet.writeUInt16BE(sequence, 2) + packet.writeUInt32BE((sequence * 3000) >>> 0, 4) + packet.writeUInt32BE(ssrc, 8) + + for (let octet = 12; octet < packet.length; octet++) { + packet[octet] = (octet * 7 + sequence) & 0xFF + } + + if (extensionWords !== undefined) { + const offset = 12 + 4 * csrcs + packet.writeUInt16BE(0xBEDE, offset) + packet.writeUInt16BE(extensionWords, offset + 2) + } + + if (padding > 0) { + packet[packet.length - 1] = padding + } + + return packet +} + +function protect(context: SRTPContext, packet: Buffer): Buffer { + const output = Buffer.alloc(packet.length + 10) + + return output.subarray(0, context.protect(packet, output)) +} + +function protectRTCP(context: SRTPContext, packet: Buffer): Buffer { + const output = Buffer.alloc(packet.length + 14) + + return output.subarray(0, context.protectRTCP(packet, output)) +} + +// The RTCP packet a context unprotects, in hex, or undefined for one it refuses. +function unprotectRTCP(context: SRTPContext, packet: Buffer): string | undefined { + const output = Buffer.alloc(packet.length) + const length = context.unprotectRTCP(packet, output) + + return length === undefined + ? undefined + : output.subarray(0, length).toString('hex') +} + +// The RTP packet a context unprotects, in hex, or undefined for one it refuses. +function unprotect(context: SRTPContext, packet: Buffer): string | undefined { + const output = Buffer.alloc(packet.length) + const length = context.unprotect(packet, output) + + return length === undefined + ? undefined + : output.subarray(0, length).toString('hex') +} + +interface WindowState { + highest?: number + words: number[] +} + +interface ReceiveState { + highestSequence?: number + rolloverCounter: number + rtpWindow: WindowState + rtcpWindow: WindowState +} + +// What a context holds of the packets it received, read through private access: its RTP index and the replay window over each stream's index. +function receiveState(context: SRTPContext): ReceiveState { + const held = context as unknown as { + highestSequence?: number + rolloverCounter: number + rtpWindow: { highest?: number, words: Uint32Array } + rtcpWindow: { highest?: number, words: Uint32Array } + } + const windowOf = ({ highest, words }: { highest?: number, words: Uint32Array }): WindowState => ({ + highest, + words: [...words], + }) + + return { + highestSequence: held.highestSequence, + rolloverCounter: held.rolloverCounter, + rtpWindow: windowOf(held.rtpWindow), + rtcpWindow: windowOf(held.rtcpWindow), + } +} + +// One RTP packet of each shape and payload length class: no CSRC, fifteen CSRCs, a header extension and padding. The sequence steps 0x2000 from 0xF000, +// and the walk crosses the sequence wrap at least twice. +function shapedPackets(): Buffer[] { + const shapes = [ + { csrcs: 0 }, + { csrcs: 15 }, + { extensionWords: 3 }, + { padding: 4 }, + ] + const payloads = [0, 1, 15, 16, 17, 1366] + + return shapes + .flatMap(shape => payloads.map(payload => ({ ...shape, payload }))) + .map((shape, index) => rtpPacket({ ...shape, sequence: (0xF000 + index * 0x2000) % 0x10000 })) +} + +/* A walk of short and long jumps, reorderings and replays across both words of a replay window whose receiver has accepted indexes 0, 1 and 64, each answer + * checked against the set model of RFC 3711 3.3.2: the read answers the packet at an index, and an index the model admits answers its expected packet. + */ +function expectReplayWalk(read: (index: number) => string | undefined, expected: (index: number) => string): void { + const order = '70 66 65 70 101 100 69 38 37 135 134 72 71 103 102 103 199 136 137 140 199 198 150 135 136'.split(' ').map(Number) + const accepted = new Set([0, 1, 64]) + let highest = 64 + + for (const index of order) { + const admitted = index > highest || (highest - index < 64 && !accepted.has(index)) + + const answer = read(index) + + expect({ index, answer }).toEqual({ + index, + answer: admitted + ? expected(index) + : undefined, + }) + + if (admitted) { + accepted.add(index) + highest = Math.max(highest, index) + } + } +} + +// A receiver report with one report block, then a source description, the compound a controller sends. +const RECEIVER_REPORT = '81c90007aabbccdd112233440000000000000064000000000000000000000000' +const SOURCE_DESCRIPTION = '81ca0003aabbccdd0104697061640000' + +describe('sRTPContext', () => { + it('protects the muxer\'s packets in order through one context, the fourth at ROC 1', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + + // The reference reproduces the vectors first: every later comparison against it rests on a reference the muxer agrees with. + expect(RTP_VECTORS.map(({ rtp }) => reference.protect(Buffer.from(rtp, 'hex')).toString('hex'))).toEqual(RTP_VECTORS.map(({ srtp }) => srtp)) + + for (const { rtp, srtp } of RTP_VECTORS) { + expect(protect(context, Buffer.from(rtp, 'hex')).toString('hex')).toBe(srtp) + } + }) + + it('protects the muxer\'s sender report at SRTCP index 0, and a second report at index 1 as the reference does', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + const report = Buffer.from(RTCP_VECTOR.rtcp, 'hex') + + expect(reference.protectRTCP(report).toString('hex')).toBe(RTCP_VECTOR.srtcp) + expect(protectRTCP(context, report).toString('hex')).toBe(RTCP_VECTOR.srtcp) + + const second = protectRTCP(context, report) + + expect(second.readUInt32BE(report.length)).toBe(0x80000001) + expect(second.toString('hex')).toBe(reference.protectRTCP(report).toString('hex')) + }) + + it('matches the reference across two sequence wraps for CSRCs, a header extension, padding and payloads of every length class', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + const packets = shapedPackets() + + for (const packet of packets) { + expect(protect(context, packet).toString('hex')).toBe(reference.protect(packet).toString('hex')) + } + + // The packets step 0x2000 from 0xF000, and the walk crosses the sequence wrap at least twice. + expect(packets.length * 0x2000 + 0xF000).toBeGreaterThan(3 * 0x10000) + }) + + it('matches the reference at ROC 0 for a packet more than 32768 ahead of the highest, the ROC before 0 wrapping to its top, and the reference unprotects both', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + const receiver = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + + // The first sequence number sits below 32768 and the second more than 32768 above it. By RFC 3711 3.3.1 the second packet belongs to the ROC before zero. + for (const sequence of [0x0010, 0x9000]) { + const packet = rtpPacket({ payload: 16, sequence }) + const protectedPacket = protect(context, packet) + + expect(protectedPacket.toString('hex')).toBe(reference.protect(packet).toString('hex')) + expect(receiver.unprotect(protectedPacket)?.toString('hex')).toBe(packet.toString('hex')) + } + }) + + it('matches the reference for SRTCP packets of several lengths, the index counting up from 0', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + + for (const [index, length] of [8, 9, 28, 100, 1000].entries()) { + const packet = Buffer.alloc(length, length & 0xFF) + packet.writeUInt32BE(0x80C80006, 0) + packet.writeUInt32BE(0x12345678, 4) + + const protectedPacket = protectRTCP(context, packet) + + expect(protectedPacket.readUInt32BE(length)).toBe((0x80000000 | index) >>> 0) + expect(protectedPacket.toString('hex')).toBe(reference.protectRTCP(packet).toString('hex')) + } + }) + + it('refuses a master key that is not 16 octets and a master salt that is not 14 with a type error', () => { + expect(() => new SRTPContext(Buffer.alloc(15), SRTP_MASTER_SALT)).toThrow(TypeError) + expect(() => new SRTPContext(SRTP_MASTER_KEY, Buffer.alloc(13))).toThrow(TypeError) + }) + + it('refuses a short output and a header longer than its packet with a range error', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const packet = rtpPacket({ payload: 16, sequence: 1 }) + const longHeader = rtpPacket({ csrcs: 15, payload: 0, sequence: 2 }).subarray(0, 40) + const report = Buffer.from(RTCP_VECTOR.rtcp, 'hex') + + expect(() => context.protect(packet, Buffer.alloc(packet.length + 9))).toThrow(RangeError) + expect(() => context.protect(longHeader, Buffer.alloc(longHeader.length + 10))).toThrow(RangeError) + expect(() => context.protectRTCP(report, Buffer.alloc(report.length + 13))).toThrow(RangeError) + expect(() => context.protectRTCP(report.subarray(0, 7), Buffer.alloc(32))).toThrow(RangeError) + }) + + it('refuses a packet longer than 1500 octets, protects one of 1500 as the reference does, and a feed packet after them', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + + // An RTCP packet of the given length: a sender report's first octets and an SSRC, then distinct octets, since the context reads nothing past the header. + const rtcpPacket = (length: number): Buffer => { + const packet = Buffer.alloc(length) + + for (let octet = 0; octet < length; octet++) { + packet[octet] = (octet * 11) & 0xFF + } + + packet[0] = 0x80 + packet[1] = 200 + packet.writeUInt32BE(0x12345678, 4) + + return packet + } + + expect(() => protect(context, rtpPacket({ payload: 1505 - 12, sequence: 1 }))).toThrow(RangeError) + expect(() => protectRTCP(context, rtcpPacket(1505))).toThrow(RangeError) + expect(unprotectRTCP(receiver, new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }).protectRTCP(rtcpPacket(1505)))).toBeUndefined() + + // At the bound each message, the packet and its ROC or SRTCP index after it, fills the 1504 octets the tag work buffer holds. + const rtp = rtpPacket({ payload: 1500 - 12, sequence: 2 }) + const rtcp = rtcpPacket(1500) + const srtcp = protectRTCP(context, rtcp) + + expect(protect(context, rtp)).toEqual(reference.protect(rtp)) + expect(srtcp).toEqual(reference.protectRTCP(rtcp)) + expect(unprotectRTCP(receiver, srtcp)).toBe(rtcp.toString('hex')) + + const feed = rtpPacket({ payload: 1378 - 12, sequence: 3 }) + + expect(protect(context, feed)).toEqual(reference.protect(feed)) + }) + + it('zeroes its keys, salts and work buffers at disposal, after which protect and protectRTCP throw', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + protect(context, rtpPacket({ payload: 32, sequence: 1 })) + // A second report leaves SRTCP index 1 in the ROC word: every work buffer holds a nonzero octet before the disposal. + protectRTCP(context, Buffer.from(RTCP_VECTOR.rtcp, 'hex')) + protectRTCP(context, Buffer.from(RTCP_VECTOR.rtcp, 'hex')) + + const held = context as unknown as Record<'counters' | 'iv' | 'roc' | 'rtcpInner' | 'rtcpOuter' | 'rtcpSalt' | 'rtpInner' | 'rtpOuter' | 'rtpSalt', Buffer> + const buffers = [ + held.rtpInner, + held.rtpOuter, + held.rtpSalt, + held.rtcpInner, + held.rtcpOuter, + held.rtcpSalt, + held.iv, + held.counters, + held.roc, + ] + + expect(buffers.every(buffer => buffer.some(octet => octet !== 0))).toBe(true) + + context[Symbol.dispose]() + context[Symbol.dispose]() + + expect(buffers.every(buffer => buffer.every(octet => octet === 0))).toBe(true) + expect(() => protect(context, rtpPacket({ payload: 1, sequence: 2 }))).toThrow(ReferenceError) + expect(() => protectRTCP(context, Buffer.from(RTCP_VECTOR.rtcp, 'hex'))).toThrow(ReferenceError) + }) + + it('unprotects the muxer\'s sender report, a compound and an unencrypted packet back to the packets protected', () => { + const sender = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + const muxerReceiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const compound = RECEIVER_REPORT + SOURCE_DESCRIPTION + + expect(unprotectRTCP(muxerReceiver, Buffer.from(RTCP_VECTOR.srtcp, 'hex'))).toBe(RTCP_VECTOR.rtcp) + expect(unprotectRTCP(receiver, protectRTCP(sender, Buffer.from(compound, 'hex')))).toBe(compound) + + // The reference's third packet carries its E flag clear, which means its payload travels unencrypted and the receiver copies it under the tag. + reference.protectRTCP(Buffer.from(compound, 'hex')) + reference.protectRTCP(Buffer.from(compound, 'hex')) + const clear = reference.protectRTCP(Buffer.from(compound, 'hex'), false) + + expect(clear.readUInt32BE(compound.length / 2)).toBe(2) + expect(clear.subarray(8, compound.length / 2).toString('hex')).toBe(compound.slice(16)) + expect(unprotectRTCP(receiver, clear)).toBe(compound) + }) + + it('refuses an SRTCP packet whose tag or payload was altered, or one too short for its trailer, and advances nothing', () => { + const sender = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const packet = protectRTCP(sender, Buffer.from(RECEIVER_REPORT + SOURCE_DESCRIPTION, 'hex')) + + for (const octet of [packet.length - 1, 10]) { + const altered = Buffer.from(packet) + altered[octet] ^= 0x01 + + expect(unprotectRTCP(receiver, altered)).toBeUndefined() + } + + expect(unprotectRTCP(receiver, packet.subarray(0, 21))).toBeUndefined() + expect(unprotectRTCP(receiver, packet)).toBe(RECEIVER_REPORT + SOURCE_DESCRIPTION) + }) + + it('refuses a replayed index and one 64 behind the highest accepted, and admits every other index as a set of the indexes seen would', () => { + const sender = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const packets = Array.from({ length: 200 }, () => protectRTCP(sender, Buffer.from(RECEIVER_REPORT, 'hex'))) + + expect(unprotectRTCP(receiver, packets[0])).toBe(RECEIVER_REPORT) + expect(unprotectRTCP(receiver, packets[0])).toBeUndefined() + expect(unprotectRTCP(receiver, packets[64])).toBe(RECEIVER_REPORT) + expect(unprotectRTCP(receiver, packets[0])).toBeUndefined() + expect(unprotectRTCP(receiver, packets[1])).toBe(RECEIVER_REPORT) + expect(unprotectRTCP(receiver, packets[1])).toBeUndefined() + + expectReplayWalk(index => unprotectRTCP(receiver, packets[index]), () => RECEIVER_REPORT) + }) + + it('calls no Buffer factory to unprotect a packet or to refuse one once constructed, and throws after disposal', () => { + const sender = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const packet = protectRTCP(sender, Buffer.from(RECEIVER_REPORT + SOURCE_DESCRIPTION, 'hex')) + const output = Buffer.alloc(packet.length) + const factories = ([ + 'alloc', + 'allocUnsafe', + 'allocUnsafeSlow', + 'from', + 'concat', + 'copyBytesFrom', + 'of', + ] as const).map(name => vi.spyOn(Buffer, name)) + + try { + expect(receiver.unprotectRTCP(packet, output)).toBe(packet.length - 14) + expect(receiver.unprotectRTCP(packet, output)).toBeUndefined() + + for (const factory of factories) { + expect(factory).not.toHaveBeenCalled() + } + } finally { + for (const factory of factories) { + factory.mockRestore() + } + } + + receiver[Symbol.dispose]() + + expect(() => receiver.unprotectRTCP(packet, output)).toThrow(ReferenceError) + }) + + it('calls no Buffer factory to protect a packet once constructed', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const packet = rtpPacket({ payload: 1366, sequence: 0xFFFF }) + const report = Buffer.from(RTCP_VECTOR.rtcp, 'hex') + const output = Buffer.alloc(packet.length + 14) + const factories = ([ + 'alloc', + 'allocUnsafe', + 'allocUnsafeSlow', + 'from', + 'concat', + 'copyBytesFrom', + 'of', + ] as const).map(name => vi.spyOn(Buffer, name)) + + try { + context.protect(packet, output) + context.protect(packet, output) + context.protectRTCP(report, output) + + for (const factory of factories) { + expect(factory).not.toHaveBeenCalled() + } + } finally { + for (const factory of factories) { + factory.mockRestore() + } + } + }) + + it('unprotects the muxer\'s packets in order through one context back to the packets protected, the fourth at ROC 1', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + + expect(RTP_VECTORS.map(({ srtp }) => unprotect(context, Buffer.from(srtp, 'hex')))).toEqual(RTP_VECTORS.map(({ rtp }) => rtp)) + expect(receiveState(context)).toMatchObject({ highestSequence: 0, rolloverCounter: 1 }) + }) + + it('unprotects the reference\'s packets across two sequence wraps for CSRCs, a header extension, padding and payloads of every length class', () => { + const context = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + + for (const packet of shapedPackets()) { + expect(unprotect(context, reference.protect(packet))).toBe(packet.toString('hex')) + } + + expect(receiveState(context).rolloverCounter).toBeGreaterThanOrEqual(2) + }) + + it('refuses a replayed RTP index and one 64 behind the highest accepted, moving nothing, and admits every other index as a set of the indexes seen would', () => { + const sender = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const plain = Array.from({ length: 200 }, (_packet, sequence) => rtpPacket({ payload: 16, sequence })) + const packets = plain.map(packet => protect(sender, packet)) + const expected = (index: number): string => plain[index].toString('hex') + + expect(unprotect(receiver, packets[0])).toBe(expected(0)) + + const first = receiveState(receiver) + + expect(unprotect(receiver, packets[0])).toBeUndefined() + expect(receiveState(receiver)).toEqual(first) + expect(unprotect(receiver, packets[64])).toBe(expected(64)) + + const ahead = receiveState(receiver) + + expect(unprotect(receiver, packets[0])).toBeUndefined() + expect(receiveState(receiver)).toEqual(ahead) + expect(unprotect(receiver, packets[1])).toBe(expected(1)) + expect(unprotect(receiver, packets[1])).toBeUndefined() + + expectReplayWalk(index => unprotect(receiver, packets[index]), expected) + }) + + it('refuses an RTP packet whose payload or tag was altered, or one too short for its header and tag, past a sequence wrap, and moves nothing', () => { + const sender = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const last = rtpPacket({ payload: 16, sequence: 0xFFFF }) + const wrapped = rtpPacket({ payload: 16, sequence: 0 }) + const lastPacket = protect(sender, last) + const wrappedPacket = protect(sender, wrapped) + + expect(unprotect(receiver, lastPacket)).toBe(last.toString('hex')) + + const state = receiveState(receiver) + const refused = [ + ...[wrappedPacket.length - 1, 20].map((octet) => { + const altered = Buffer.from(wrappedPacket) + altered[octet] ^= 0x01 + + return altered + }), + wrappedPacket.subarray(0, 21), + // The first octet announces fifteen CSRCs, a header longer than the packet less its tag. + Buffer.concat([ + Buffer.from([wrappedPacket[0] | 0x0F]), + wrappedPacket.subarray(1), + ]), + ] + + for (const packet of refused) { + expect(unprotect(receiver, packet)).toBeUndefined() + expect(receiveState(receiver)).toEqual(state) + } + + expect(unprotect(receiver, wrappedPacket)).toBe(wrapped.toString('hex')) + expect(receiveState(receiver)).toMatchObject({ highestSequence: 0, rolloverCounter: 1 }) + }) + + it('refuses an RTP packet longer than 1500 octets whatever its output, unprotects one of 1500, and refuses a short output with a range error', () => { + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const long = reference.protect(rtpPacket({ payload: 1501 - 12, sequence: 0 })) + const bound = rtpPacket({ payload: 1500 - 12, sequence: 1 }) + const boundPacket = reference.protect(bound) + const next = reference.protect(rtpPacket({ payload: 16, sequence: 2 })) + const output = Buffer.alloc(1500) + + expect(receiver.unprotect(long, output)).toBeUndefined() + expect(receiver.unprotect(boundPacket, output)).toBe(1500) + expect(output).toEqual(bound) + expect(() => receiver.unprotect(next, Buffer.alloc(next.length - 11))).toThrow(RangeError) + }) + + it('keeps the RTP and SRTCP replay windows apart, admitting index 0 of each once', () => { + const sender = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const rtp = rtpPacket({ payload: 16, sequence: 0 }) + const srtp = protect(sender, rtp) + const srtcp = protectRTCP(sender, Buffer.from(RECEIVER_REPORT, 'hex')) + + expect(srtcp.readUInt32BE(RECEIVER_REPORT.length / 2)).toBe(0x80000000) + expect(unprotect(receiver, srtp)).toBe(rtp.toString('hex')) + expect(unprotectRTCP(receiver, srtcp)).toBe(RECEIVER_REPORT) + expect(unprotect(receiver, srtp)).toBeUndefined() + expect(unprotectRTCP(receiver, srtcp)).toBeUndefined() + }) + + it('calls no Buffer factory to unprotect an RTP packet or to refuse one once constructed, zeroes both replay windows at disposal, and throws after it', () => { + const sender = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const packet = protect(sender, rtpPacket({ extensionWords: 1, payload: 160, sequence: 7 })) + const report = protectRTCP(sender, Buffer.from(RECEIVER_REPORT, 'hex')) + const output = Buffer.alloc(packet.length) + const factories = ([ + 'alloc', + 'allocUnsafe', + 'allocUnsafeSlow', + 'from', + 'concat', + 'copyBytesFrom', + 'of', + ] as const).map(name => vi.spyOn(Buffer, name)) + + try { + expect(receiver.unprotect(packet, output)).toBe(packet.length - 10) + expect(receiver.unprotect(packet, output)).toBeUndefined() + + for (const factory of factories) { + expect(factory).not.toHaveBeenCalled() + } + } finally { + for (const factory of factories) { + factory.mockRestore() + } + } + + expect(unprotectRTCP(receiver, report)).toBe(RECEIVER_REPORT) + + const { rtpWindow, rtcpWindow } = receiveState(receiver) + + expect([rtpWindow, rtcpWindow].every(window => window.highest !== undefined && window.words.some(word => word !== 0))).toBe(true) + + receiver[Symbol.dispose]() + + // Both windows read as a context that never received a packet. + const zeroed = { + highest: undefined, + words: [0, 0], + } + + expect(receiveState(receiver)).toMatchObject({ + rtpWindow: zeroed, + rtcpWindow: zeroed, + }) + expect(() => receiver.unprotect(packet, output)).toThrow(ReferenceError) + }) + + it('unprotects a packet in its own buffer to the reference\'s plain packet with its tag behind it, and refuses a tampered one with its octets as they arrived', () => { + const reference = new ReferenceSRTP({ masterKey: SRTP_MASTER_KEY, masterSalt: SRTP_MASTER_SALT }) + const receiver = new SRTPContext(SRTP_MASTER_KEY, SRTP_MASTER_SALT) + const plain = rtpPacket({ csrcs: 2, payload: 160, sequence: 9 }) + const packet = reference.protect(plain) + const tag = Buffer.from(packet.subarray(plain.length)) + const tampered = reference.protect(rtpPacket({ payload: 160, sequence: 10 })) + tampered[40] ^= 0x01 + const arrived = Buffer.from(tampered) + + expect(receiver.unprotect(packet, packet)).toBe(plain.length) + expect(packet.subarray(0, plain.length)).toEqual(plain) + expect(packet.subarray(plain.length)).toEqual(tag) + expect(receiver.unprotect(tampered, tampered)).toBeUndefined() + expect(tampered).toEqual(arrived) + }) +}) diff --git a/src/lib/camera/srtp/keystream.spec.ts b/src/lib/camera/srtp/keystream.spec.ts new file mode 100644 index 000000000..16576d36e --- /dev/null +++ b/src/lib/camera/srtp/keystream.spec.ts @@ -0,0 +1,51 @@ +import { Buffer } from 'node:buffer' + +import { describe, expect, it } from 'vitest' + +import { SRTP_MASTER_KEY, SRTP_MASTER_SALT } from '../../../test-utils/cameraFixtures.js' +import { applyKeystream, createKeystreamCipher, deriveSessionKey } from './keystream.js' + +// RFC 3711 appendix B.2: the AES-CM keystream of a session key over the counter blocks that count up from an offset, the salt already shifted into it. +const B2_SESSION_KEY = Buffer.from('2b7e151628aed2a6abf7158809cf4f3c', 'hex') +const B2_OFFSET = Buffer.from('f0f1f2f3f4f5f6f7f8f9fafbfcfd0000', 'hex') +const B2_SEGMENT_BLOCKS = 0xFF02 +const B2_BLOCKS: [block: number, keystream: string][] = [ + [0x0000, 'e03ead0935c95e80e166b16dd92b4eb4'], + [0x0001, 'd23513162b02d0f72a43a2fe4a5f97ab'], + [0x0002, '41e95b3bb0a2e8dd477901e4fca894c0'], + [0xFEFF, 'ec8cdf7398607cb0f2d21675ea9ea1e4'], + [0xFF00, '362b7c3c6773516318a077d7fc5073ae'], + [0xFF01, '6a2cc3787889374fbeb4c81b17ba6c44'], +] + +// RFC 3711 appendix B.3: the session values SRTP_MASTER_KEY and SRTP_MASTER_SALT derive at index 0, the authentication label run out to the octets the +// RFC prints rather than to its HMAC key's length. +const B3_CIPHER_KEY = 'c61e7a93744f39ee10734afe3ff7a087' +const B3_CIPHER_SALT = '30cbbc08863d8c85d49db34a9ae1' +const B3_AUTH_KEY = 'cebe321f6ff7716b6fd4ab49af256a156d38baa48f0a0acf3c34e2359e6cdbcee049646c43d9327ad175578ef72270986371c10c9a369ac2f94a8c5fbcdddc25' + + '6d6e919a48b610ef17c2041e474035766b68642c59bbfc2f34db60dbdfb2' + +describe('srtp keystream', () => { + it('reproduces appendix B.2\'s keystream at each block it prints, through a counter buffer smaller than the segment', () => { + const segment = Buffer.alloc(B2_SEGMENT_BLOCKS * 16) + const counters = Buffer.alloc(96 * 16) + + applyKeystream(createKeystreamCipher(B2_SESSION_KEY), B2_OFFSET, segment, counters) + + for (const [block, keystream] of B2_BLOCKS) { + expect(segment.subarray(block * 16, block * 16 + 16).toString('hex')).toBe(keystream) + } + }) + + it('derives appendix B.3\'s cipher key under label 0', () => { + expect(deriveSessionKey(SRTP_MASTER_KEY, SRTP_MASTER_SALT, 0, 16).toString('hex')).toBe(B3_CIPHER_KEY) + }) + + it('derives appendix B.3\'s cipher salt under label 2', () => { + expect(deriveSessionKey(SRTP_MASTER_KEY, SRTP_MASTER_SALT, 2, 14).toString('hex')).toBe(B3_CIPHER_SALT) + }) + + it('derives appendix B.3\'s authentication octets under label 1', () => { + expect(deriveSessionKey(SRTP_MASTER_KEY, SRTP_MASTER_SALT, 1, B3_AUTH_KEY.length / 2).toString('hex')).toBe(B3_AUTH_KEY) + }) +}) diff --git a/src/lib/camera/webrtc/WebRTCEngine.loopback.spec.ts b/src/lib/camera/webrtc/WebRTCEngine.loopback.spec.ts new file mode 100644 index 000000000..5ab68de20 --- /dev/null +++ b/src/lib/camera/webrtc/WebRTCEngine.loopback.spec.ts @@ -0,0 +1,744 @@ +import type { Mock } from 'vitest' +import type * as werift from 'werift' +import type { RTCPeerConnection } from 'werift' + +import type { KeepingSink } from '../../../test-utils/talkbackSink.js' +import type { LoopbackConnections } from '../../../test-utils/webRTCEngineFixtures.js' +import type { AccessoryInformation, CameraWebRTCStreamManagement } from '../../definitions/index.js' +import type * as packetRules from '../rtp/packetRules.js' +import type { TierStream } from '../StreamingOptions.js' +import type { WebRTCOffer, WebRTCOfferRequest } from '../WebRTCStreamManagement.js' + +import { Buffer } from 'node:buffer' +import { randomUUID } from 'node:crypto' + +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' + +import { buildEmitterConnection } from '../../../test-utils/connectionFixtures.js' +import { withParameterSets, writeTierFrame } from '../../../test-utils/mp4Fixtures.js' +import { detachedReporter } from '../../../test-utils/reporterFixtures.js' +import { until } from '../../../test-utils/settle.js' +import { openSFrameReference } from '../../../test-utils/sframeVectors.js' +import { keepingSink } from '../../../test-utils/talkbackSink.js' +import { picture, realTimePause, SENSOR_UUID, ssrcsOf, STREAM_TIERS } from '../../../test-utils/webRTCEngineFixtures.js' +import { TierBuffer } from '../buffer/CameraBuffer.js' +import { + decodeWebRTCSessionStatusResponse, + decodeWebRTCSolicitOfferResponse, + encodeWebRTCProvideAnswerRequest, + encodeWebRTCSolicitOfferRequest, + WebRTCSolicitOfferStatus, + WebRTCStreamingStatus, +} from '../capabilities/webrtc.js' +import { firstSequence, SEQUENCE_RANGE } from '../rtp/packetRules.js' +import { TierTable } from '../TierTable.js' +import { deriveStreamKeys, FIRST_PAYLOAD, LAST_PAYLOAD, sealSFrame, SFRAME_AUDIO_SUITE } from './sframe.js' +import { BETTER_VOICE, DEPENDABLE_VOICE } from './voice/ViewerVoice.js' +import { WebRTCEngine } from './WebRTCEngine.js' +import { loadWerift } from './werift.js' + +/* The suite's setup file imports the definitions, whose graph imports the engine's module through the camera controller, though nothing builds an engine + * there. The engine and its loader stand evaluated before this file's mocks are in place. The module registry is reset first, which is why this file's imports + * evaluate the engine over the mocked loader and the recorded draw. + */ +vi.hoisted(() => vi.resetModules()) + +// Every connection the mocked loader's class makes, the engine's and the far end's, in the order made. +const connections = vi.hoisted((): LoopbackConnections => ({ configs: [], peers: [] })) +const { peers } = connections + +// The engine reaches werift through its one loader, mocked here to bind the loopback interface alone, and every socket of both ends stands on 127.0.0.1. +vi.mock('./werift.js', async () => { + const { loopbackLoader } = await import('../../../test-utils/webRTCEngineFixtures.js') + + return loopbackLoader(connections) +}) + +vi.mock('../rtp/packetRules.js', async (importOriginal) => { + const { recordedDraw } = await import('../../../test-utils/webRTCEngineFixtures.js') + + return recordedDraw(await importOriginal()) +}) + +// The identifier the offer gives the RID header extension in every section, after the MID's. +const RID_EXTENSION = 4 + +// A session the engine offered, the far end answered and both connected over the loopback interface, with what the far end received by SSRC. +interface Loopback { + readonly delegate: { readonly tierDemandStarted: Mock } + readonly engine: WebRTCEngine + readonly far: RTCPeerConnection + readonly near: RTCPeerConnection + readonly offer: WebRTCOffer + readonly offerRequest: WebRTCOfferRequest + readonly received: Map + // The sink the delegate's talkbackStarted answers. + readonly talkback: KeepingSink + // Ends the session as the signaling class does at any of its exits: the request's signal aborted, then the engine's endSession. + end: () => Promise + // The stream a video tier's demand handed the plugin at its start. + streamOf: (tierId: number) => TierStream +} + +// A far end made from the mocked loader's exports, ICE-lite as Apple's relay is: the engine nominates toward it as toward a hub's view, and it takes the +// DTLS client's part. +async function farEnd(): Promise { + const { RTCPeerConnection: PeerConnection, RTCRtpCodecParameters, useSdesMid, useSdesRTPStreamId } = await loadWerift() + const extensions = [ + useSdesMid(), + useSdesRTPStreamId(), + ] + + return new PeerConnection({ + bundlePolicy: 'max-bundle', + codecs: { + audio: [ + new RTCRtpCodecParameters({ + channels: 1, + clockRate: 48000, + mimeType: 'audio/opus', + payloadType: 110, + }), + ], + video: [ + new RTCRtpCodecParameters({ + clockRate: 90000, + mimeType: 'video/H265', + payloadType: 99, + rtcpFeedback: [ + { type: 'nack' }, + { parameter: 'pli', type: 'nack' }, + { parameter: 'fir', type: 'ccm' }, + ], + }), + ], + }, + headerExtensions: { + audio: extensions, + video: extensions, + }, + iceLite: true, + }) +} + +// The far end's answer to an offer, as an ICE-lite DTLS client writes it. +function answerOf(far: RTCPeerConnection): string { + const answer = far.localDescription?.sdp ?? '' + + expect(answer).toContain('a=ice-lite') + expect(answer).toContain('a=setup:active') + + return answer +} + +async function loopback(): Promise { + const controller = new AbortController() + const talkback = keepingSink() + const delegate = { + talkbackStarted: vi.fn(() => talkback.sink), + tierDemandStarted: vi.fn(), + } + const reporter = detachedReporter() + const table = new TierTable(delegate, STREAM_TIERS, tier => new TierBuffer(tier), reporter) + const offerRequest: WebRTCOfferRequest = { + connection: buildEmitterConnection(), + options: { sframeEnabled: false }, + reporter, + sensorUUID: SENSOR_UUID, + sessionIdentifier: randomUUID(), + signal: controller.signal, + } + let engine: WebRTCEngine | undefined + const ended = vi.fn(async () => { + controller.abort() + await engine?.endSession(offerRequest.sessionIdentifier, reporter) + }) + + engine = new WebRTCEngine({ + endSession: ended, + speakerMuted: () => false, + tierTable: sensorUUID => sensorUUID === SENSOR_UUID + ? table + : undefined, + }) + const offer = await engine.createOffer(offerRequest) + const near = peers[0] + const far = await farEnd() + const received = new Map() + + await far.setRemoteDescription({ sdp: offer.sdpOffer, type: 'offer' }) + await far.setLocalDescription(await far.createAnswer()) + far.dtlsTransports[0].onRtp.subscribe((packet) => { + received.set(packet.header.ssrc, [ + ...(received.get(packet.header.ssrc) ?? []), + packet, + ]) + }) + + await engine.acceptAnswer(offerRequest.sessionIdentifier, { + sdpAnswer: answerOf(far), + additionalCandidates: [], + }) + // Both ends report connected before a row sends: the far end, the DTLS client, may finish its handshake a moment after the engine's side does. + await until( + () => (near.connectionState === 'connected') && (far.connectionState === 'connected') && (delegate.tierDemandStarted.mock.calls.length === 3), + realTimePause, + ) + + return { + delegate, + end: async () => ended(), + engine, + far, + near, + offer, + offerRequest, + received, + streamOf: tierId => delegate.tierDemandStarted.mock.calls.find(([started]) => (started as TierStream).tier.id === tierId)![0] as TierStream, + talkback, + } +} + +/* The ciphertexts a stream's packets carry, each put back from the payloads that run from one marked first to the next. The packets are read in sequence + * order, each by its distance from the stream's first packet within the sequence range, which means a stream whose numbers wrap reads in the order it was sent. + */ +function ciphertextsOf(packets: readonly werift.RtpPacket[]): Buffer[] { + const first = packets[0]?.header.sequenceNumber ?? 0 + const distance = ({ header }: werift.RtpPacket): number => (header.sequenceNumber - first + SEQUENCE_RANGE) % SEQUENCE_RANGE + const ordered = packets.toSorted((left, right) => distance(left) - distance(right)) + const ciphertexts: Buffer[][] = [] + + for (const { payload } of ordered) { + if (payload[0] & FIRST_PAYLOAD) { + ciphertexts.push([]) + } + + ciphertexts.at(-1)?.push(payload.subarray(1)) + } + + return ciphertexts.map(pieces => Buffer.concat(pieces)) +} + +// Waits for a sink to be written and then for its writes to stop, reading its count a tenth of a second apart. +async function writesSettled(packets: readonly Buffer[]): Promise { + let seen = -1 + + await until(() => { + const settled = (packets.length > 0) && (packets.length === seen) + + seen = packets.length + + return settled + }, async () => new Promise(resolve => setTimeout(resolve, 100))) +} + +// The sockets the process holds open, which a connection opens as it gathers and closes a turn or more after its close. +function sockets(): number { + return process.getActiveResourcesInfo().filter(resource => resource === 'UDPWrap').length +} + +// What a session's far end made of the frames written to every tier and to the sound: what was written and what the far end opened by SSRC, and every +// packet it received carrying a stream ID. +interface EveryTierReceived { + readonly opened: Map + readonly streamIdentified: werift.RtpPacket[] + readonly written: Map +} + +// Connects a session, writes frames to every tier, each tier's first a keyframe, and to the sound, and ends the session once the far end has received them +// all. +async function everyTierReceived(): Promise { + const { end, offer, received, streamOf } = await loopback() + const ssrcs = ssrcsOf(offer.sdpOffer) + const key = Buffer.from(offer.sframeConfiguration?.key ?? Buffer.alloc(0)) + const written = new Map([ + [ + ssrcs[0], + [ + withParameterSets(picture(3000, 1)), + picture(900, 2), + ], + ], + [ + ssrcs[1], + [ + withParameterSets(picture(1500, 3)), + picture(400, 4), + ], + ], + [ + ssrcs[2], + [ + withParameterSets(picture(500, 5)), + picture(200, 6), + ], + ], + [ + ssrcs[3], + [ + Buffer.alloc(60, 7), + Buffer.alloc(80, 8), + ], + ], + ]) + + for (const [index, ssrc] of ssrcs.entries()) { + const video = index < 3 + const stream = streamOf(video + ? index + 1 + : 1) + + for (const [frame, data] of written.get(ssrc)!.entries()) { + writeTierFrame(stream, video + ? 'video' + : 'audio', { data, keyframe: video && (frame === 0), time: frame * 20000 }) + } + } + + await until( + () => ssrcs.every(ssrc => ciphertextsOf(received.get(ssrc) ?? []).length === 2 && (received.get(ssrc)!.at(-1)!.payload[0] & LAST_PAYLOAD) !== 0), + realTimePause, + ) + await end() + + const opened = new Map() + + for (const [index, ssrc] of ssrcs.entries()) { + const video = index < 3 + + opened.set(ssrc, ciphertextsOf(received.get(ssrc)!).map(ciphertext => openSFrameReference({ + ciphertext, + sessionKey: key, + ssrc, + suite: video + ? 6 + : 8, + tagLength: video + ? 10 + : 4, + }))) + } + + return { + opened, + streamIdentified: [ + ...received.values(), + ].flat().filter(({ header }) => header.extensions.some(({ id }) => id === RID_EXTENSION)), + written, + } +} + +afterEach(async () => { + vi.restoreAllMocks() + connections.configs.length = 0 + + for (const peer of peers.splice(0)) { + await peer.close() + } + + await until(() => sockets() === 0, realTimePause) +}) + +describe('webRTCEngine over the loopback interface', () => { + it('connects to an ICE-lite far end, which receives every tier\'s frames and the sound, each opening to what the plugin wrote, and no stream ID', async () => { + const { opened, streamIdentified, written } = await everyTierReceived() + + expect(opened).toEqual(written) + expect(streamIdentified).toEqual([]) + }, 20000) + + it('delivers every tier\'s frames and the sound in the order written when every stream starts at the sequence range\'s last number and wraps', async () => { + const draw = vi.mocked(firstSequence).mockReturnValue(SEQUENCE_RANGE - 1) + + onTestFinished(() => { + draw.mockReset() + }) + + const { opened, written } = await everyTierReceived() + + expect(draw).toHaveBeenCalled() + expect(opened).toEqual(written) + }, 20000) + + it('hands the far end the best tier\'s picture and the sound each with its timestamps stepping as their one run places them', async () => { + const { end, offer, received, streamOf } = await loopback() + const ssrcs = ssrcsOf(offer.sdpOffer) + const stream = streamOf(1) + // Each timestamp a stream's packets carry, in sequence order, less its first. + const steps = (ssrc: number): number[] => { + const packets = received.get(ssrc)! + const first = packets[0].header.sequenceNumber + const timestamps = packets.toSorted((left, right) => ((left.header.sequenceNumber - first + SEQUENCE_RANGE) % SEQUENCE_RANGE) + - ((right.header.sequenceNumber - first + SEQUENCE_RANGE) % SEQUENCE_RANGE)).map(({ header }) => header.timestamp) + + return timestamps.slice(1).map(timestamp => (timestamp - timestamps[0]) >>> 0) + } + + writeTierFrame(stream, 'video', { + data: withParameterSets(picture(300, 1)), + keyframe: true, + time: 0, + }) + writeTierFrame(stream, 'audio', { + data: Buffer.alloc(60, 2), + time: 0, + }) + writeTierFrame(stream, 'video', { + data: picture(300, 3), + time: 33333, + }) + writeTierFrame(stream, 'audio', { + data: Buffer.alloc(60, 4), + time: 20000, + }) + writeTierFrame(stream, 'audio', { + data: Buffer.alloc(60, 5), + time: 40000, + }) + writeTierFrame(stream, 'video', { + data: picture(300, 6), + time: 66667, + }) + + await until(() => (received.get(ssrcs[0])?.length === 3) && (received.get(ssrcs[3])?.length === 3), realTimePause) + await end() + + expect([ + steps(ssrcs[0]), + steps(ssrcs[3]), + ]).toEqual([ + [3000, 6000], + [960, 1920], + ]) + }, 20000) + + it('brings the far end tier 2\'s picture again from its latest keyframe released at a PLI it sends for tier 2\'s SSRC, on timestamps above the last it ' + + 'received', async () => { + const { end, far, offer, received, streamOf } = await loopback() + const ssrcs = ssrcsOf(offer.sdpOffer) + const key = Buffer.from(offer.sframeConfiguration?.key ?? Buffer.alloc(0)) + const stream = streamOf(2) + const frames = [ + picture(300, 1), + picture(300, 2), + picture(300, 3), + ] + + // A keyframe and a picture after it, each one packet, which the far end receives live. + writeTierFrame(stream, 'video', { + data: frames[0], + keyframe: true, + time: 0, + }) + writeTierFrame(stream, 'video', { + data: frames[1], + time: 33333, + }) + await until(() => received.get(ssrcs[1])?.length === 2, realTimePause) + + const last = received.get(ssrcs[1])!.at(-1)!.header.timestamp + + // The far end reports a lost picture, and a picture written once the request has reached the engine moves the live edge past the stretch. + await far.getTransceivers()[0].receiver.sendRtcpPLI(ssrcs[1]) + await new Promise(resolve => setTimeout(resolve, 100)) + writeTierFrame(stream, 'video', { + data: frames[2], + time: 66667, + }) + + // The live picture's release is the turn that hands the opening: once it arrives a short pause lets every packet of that turn arrive. + await until(() => (received.get(ssrcs[1])?.length ?? 0) >= 3, realTimePause) + await new Promise(resolve => setTimeout(resolve, 200)) + await end() + + const packets = received.get(ssrcs[1])! + + expect(ciphertextsOf(packets).map(ciphertext => openSFrameReference({ + ciphertext, + sessionKey: key, + ssrc: ssrcs[1], + suite: 6, + tagLength: 10, + }))).toEqual([frames[0], frames[1], ...frames]) + expect(packets.slice(2).map(({ header }) => ((header.timestamp - last) >>> 0) > 0 && ((header.timestamp - last) >>> 0) < 90000)).toEqual([true, true, true]) + }, 20000) + + it('closes both transports at the session\'s end, leaving no socket open', async () => { + expect(sockets()).toBe(0) + + const { end, far, near } = await loopback() + + expect(sockets()).toBeGreaterThan(0) + + await end() + await until(() => far.dtlsTransports[0].state === 'closed', realTimePause) + + expect(near.connectionState).toBe('closed') + + await far.close() + await until(() => sockets() === 0, realTimePause) + }, 20000) + + it('serves a session on a two-sensor camera\'s second sensor from that sensor\'s tiers through the camera\'s engine, and ends it through that sensor\'s ' + + 'service when the far end closes', async () => { + // The camera's graph comes through the package root, which imports the definitions first as the library's entry does, since the registry reset leaves + // this file's graph without them. Nothing the row runs reads storage, and that graph's own storage is never opened. + const { CameraController, Characteristic } = await import('../../../index.js') + const { + disposedOf, + endsOf, + handPublishedContext, + SECOND_VIDEO_SENSOR, + scriptedTierDelegate, + streamsOf, + twoSensorCameraOptions, + } = await import('../../../test-utils/cameraFixtures.js') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const delegate = scriptedTierDelegate() + const options = twoSensorCameraOptions() + const camera = new CameraController({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities!, + streaming: { + ...options.cameraCapabilities!.streaming, + delegate, + }, + webrtc: {}, + }, + }) + + onTestFinished(() => { + camera.handleControllerRemoved() + }) + + const sensorUUID = SECOND_VIDEO_SENSOR.uuid.toLowerCase() + const service = camera.constructServices()[`cameraCapabilities:webRTCStream:${sensorUUID}`] as CameraWebRTCStreamManagement + const connection = buildEmitterConnection() + const solicitOffer = service.getCharacteristic(Characteristic.WebRTCSolicitOffer) + const provideAnswer = service.getCharacteristic(Characteristic.WebRTCProvideAnswer) + const activeSessions = (): unknown => service.getCharacteristic(Characteristic.WebRTCNumberOfActiveSessions).value + const sensorsOf = (): string[] => streamsOf(delegate).map(({ tier }) => tier.sensorUUID) + + camera.configureServices() + handPublishedContext(camera) + + const solicit = encodeWebRTCSolicitOfferRequest({ + options: { sframeEnabled: false }, + }) + const solicited = decodeWebRTCSolicitOfferResponse(await solicitOffer.handleSetRequest(solicit, connection) as string) + + expect(solicited.status).toBe(WebRTCSolicitOfferStatus.SUCCESS) + + const { sdpOffer, sessionIdentifier } = solicited as Extract + const far = await farEnd() + + await far.setRemoteDescription({ sdp: sdpOffer, type: 'offer' }) + await far.setLocalDescription(await far.createAnswer()) + + const answer = encodeWebRTCProvideAnswerRequest({ + additionalCandidates: [], + sdpAnswer: answerOf(far), + sessionIdentifier, + }) + + expect(decodeWebRTCSessionStatusResponse(await provideAnswer.handleSetRequest(answer, connection) as string)).toEqual({ + sessionIdentifier, + status: WebRTCStreamingStatus.SUCCESS, + }) + + await until(() => delegate.tierDemandStarted.mock.calls.length === 3, realTimePause) + + expect(sensorsOf()).toEqual(Array.from({ length: 3 }).fill(sensorUUID)) + expect(activeSessions()).toBe(1) + + await far.close() + await until(() => (endsOf(delegate) === 3) && (activeSessions() === 0), realTimePause) + + // Each demand of the sensor ended once, through the disposable its start registered on its own stream. + expect(streamsOf(delegate).map(stream => disposedOf(delegate, stream))).toEqual([1, 1, 1]) + expect(warn).toHaveBeenCalledExactlyOnceWith(`[Camera] WebRTC session ${sessionIdentifier} had its DTLS transport closed. The session ends.`) + }, 20000) + + it('ends a view from away whose joins wait on a pending start of its tier as the camera\'s accessory is unpublished, aborting the start\'s signal and ' + + 'warning neither that the tier refused the session nor that the start did not settle', async () => { + const { CameraController, Characteristic, Service } = await import('../../../index.js') + const { + FIRST_VIDEO_SENSOR, + handPublishedContext, + NUMBERED_ACCESSORY_UUID, + pendingStart, + scriptedTierDelegate, + signalOf, + streamsOf, + twoSensorCameraOptions, + } = await import('../../../test-utils/cameraFixtures.js') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const delegate = scriptedTierDelegate() + // The session's first join raises video tier 1, whose start stays pending, and every join on that tier waits on it. + const pending = pendingStart(delegate) + const options = twoSensorCameraOptions() + const camera = new CameraController({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities!, + streaming: { + ...options.cameraCapabilities!.streaming, + delegate, + }, + webrtc: {}, + }, + }) + + onTestFinished(() => { + pending.resolve() + camera.handleControllerRemoved() + }) + + const service = camera.constructServices()[`cameraCapabilities:webRTCStream:${FIRST_VIDEO_SENSOR.uuid.toLowerCase()}`] as CameraWebRTCStreamManagement + const connection = buildEmitterConnection() + const activeSessions = (): unknown => service.getCharacteristic(Characteristic.WebRTCNumberOfActiveSessions).value + + camera.configureServices() + handPublishedContext(camera) + + const solicit = encodeWebRTCSolicitOfferRequest({ + options: { sframeEnabled: false }, + }) + const solicited = decodeWebRTCSolicitOfferResponse(await service.getCharacteristic(Characteristic.WebRTCSolicitOffer).handleSetRequest(solicit, + connection) as string) + const { sdpOffer, sessionIdentifier } = solicited as Extract + const far = await farEnd() + + await far.setRemoteDescription({ sdp: sdpOffer, type: 'offer' }) + await far.setLocalDescription(await far.createAnswer()) + await service.getCharacteristic(Characteristic.WebRTCProvideAnswer).handleSetRequest(encodeWebRTCProvideAnswerRequest({ + additionalCandidates: [], + sdpAnswer: answerOf(far), + sessionIdentifier, + }), connection) + await until(() => delegate.tierDemandStarted.mock.calls.length === 3, realTimePause) + + const [waitedOn] = streamsOf(delegate) + + // The accessory's unpublish hands the camera the context it holds, reading not published. + camera.handleAccessoryContext({ + accessoryInformation: new Service.AccessoryInformation() as AccessoryInformation, + accessoryUUID: NUMBERED_ACCESSORY_UUID, + published: false, + username: undefined, + }) + await until(() => activeSessions() === 0, realTimePause) + await new Promise(resolve => setTimeout(resolve, 100)) + + expect([ + waitedOn.tier.id, + activeSessions(), + signalOf(delegate, waitedOn).aborted, + warn.mock.calls.filter(([line]) => ['refused WebRTC session', 'did not settle tierDemandStarted'].some(words => String(line).includes(words))), + ]).toEqual([1, 0, true, []]) + }, 20000) + + it('hands the plugin\'s sink the sealed voice the far end sends on both payload types and SSRCs no section names, as one stream in order', async () => { + const { end, engine, far, offer, offerRequest, talkback } = await loopback() + const { RtpHeader } = await loadWerift() + const key = Buffer.alloc(16, 0x4E) + const keyId = 0x5A6978698001n + // The viewer's dependable stream and its better one, each on an SSRC of its own made up here and with the milliseconds from one of its packets to the + // next, and the table-of-contents octet of its Opus packets, which say voice in speech-layer frames of 20 milliseconds and last the stream's step: + // one frame on the dependable stream, and two of one length on the better. + const streams = [ + { + kind: DEPENDABLE_VOICE, + ssrc: 0x51525354, + step: 20, + tag: 0x19, + toc: 0x48, + }, + { + kind: BETTER_VOICE, + ssrc: 0x61626364, + step: 40, + tag: 0x97, + toc: 0x49, + }, + ] + const sent = new Set() + const [transport] = far.dtlsTransports + + expect([ + ...ssrcsOf(offer.sdpOffer), + ...ssrcsOf(answerOf(far)), + ].filter(ssrc => streams.some(stream => stream.ssrc === ssrc))).toEqual([]) + + await engine.updateReceiveKeys(offerRequest.sessionIdentifier, { + receiveKeysToAdd: [ + { + key: Buffer.from(key), + kid: keyId, + }, + ], + receiveKIDsToRemove: [], + }, detachedReporter()) + + // A fifth of a second of talk in real time, a packet of the dependable stream every 20 milliseconds and one of the better stream every 40. + for (let at = 0; at < 200; at += 20) { + for (const { kind, ssrc, step, tag, toc } of streams.filter(({ step }) => at % step === 0)) { + const index = at / step + const opus = Buffer.from([ + toc, + 0x80, + tag, + index >> 8, + index & 0xFF, + ]) + const keys = deriveStreamKeys({ + keyId, + sessionKey: key, + ssrc, + suite: SFRAME_AUDIO_SUITE, + }) + const payload = Buffer.concat([ + Buffer.from([FIRST_PAYLOAD | LAST_PAYLOAD]), + sealSFrame(keys, BigInt(index), opus), + ]) + + sent.add(opus.toString('hex')) + await transport.sendRtp(payload, new RtpHeader({ + payloadType: kind.payloadType, + sequenceNumber: 3000 + index, + ssrc, + timestamp: 48000 + index * step * 48, + })) + } + + await new Promise(resolve => setTimeout(resolve, 20)) + } + + await writesSettled(talkback.packets) + await end() + + // Each packet handed, its duration in 48 kHz units read from its frame count code. + const handed = talkback.packets.map(packet => ({ + duration: (packet[12] & 0x03) === 0 + ? 960 + : 1920, + opus: packet.subarray(12).toString('hex'), + payloadType: packet[1] & 0x7F, + sequenceNumber: packet.readUInt16BE(2), + ssrc: packet.readUInt32BE(8), + timestamp: packet.readUInt32BE(4), + })) + + expect(new Set(handed.map(({ payloadType }) => payloadType))).toEqual(new Set([STREAM_TIERS.audioStreamTiers.payloadType])) + expect(new Set(handed.map(({ ssrc }) => ssrc)).size).toBe(1) + expect(streams.map(({ ssrc }) => ssrc)).toContain(handed[0].ssrc) + expect(handed.slice(1).every(({ sequenceNumber }, index) => (sequenceNumber - handed[index].sequenceNumber + SEQUENCE_RANGE) % SEQUENCE_RANGE === 1)) + .toBe(true) + expect(handed.every(({ opus }) => sent.has(opus))).toBe(true) + expect(new Set(handed.map(({ opus }) => opus)).size).toBe(handed.length) + + // Every packet lasts its stream's step: each one handed starts where the one before it ends, a change of stream among them. + expect(handed.slice(1).map(({ timestamp }, index) => timestamp - handed[index].timestamp - handed[index].duration)).toEqual(handed.slice(1).map(() => 0)) + }, 20000) +}) diff --git a/src/lib/camera/webrtc/WebRTCEngine.spec.ts b/src/lib/camera/webrtc/WebRTCEngine.spec.ts new file mode 100644 index 000000000..981a0aa2c --- /dev/null +++ b/src/lib/camera/webrtc/WebRTCEngine.spec.ts @@ -0,0 +1,3521 @@ +import type { Mock, MockInstance } from 'vitest' +import type * as werift from 'werift' +import type { RTCDtlsTransport, RTCPeerConnection } from 'werift' + +import type { KeepingSink } from '../../../test-utils/talkbackSink.js' +import type { LoopbackConnections } from '../../../test-utils/webRTCEngineFixtures.js' +import type { ControllerAccessoryContext } from '../../controller/Controller.js' +import type { CameraProblem } from '../diagnostics/problems.js' +import type * as packetRules from '../rtp/packetRules.js' +import type { CameraVideoSensor, MultiTierStreamingDelegate, SensorStreamTiers, Talker, TierStream } from '../StreamingOptions.js' +import type { TierHolder } from '../TierTable.js' +import type { WebRTCOffer, WebRTCOfferRequest } from '../WebRTCStreamManagement.js' +import type * as sframe from './sframe.js' +import type { SFrameStreamKeys } from './sframe.js' +import type { WebRTCEngineOptions } from './WebRTCEngine.js' + +import { Buffer } from 'node:buffer' +import { randomUUID } from 'node:crypto' +import { subscribe, unsubscribe } from 'node:diagnostics_channel' +import { getEventListeners } from 'node:events' +import { format } from 'node:util' + +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { RtcpPacketConverter, RtpHeader, RtpPacket } from 'werift' + +import { advanceAsync, keepStreaming, streamsOf } from '../../../test-utils/cameraFixtures.js' +import { buildEmitterConnection } from '../../../test-utils/connectionFixtures.js' +import { captureDebug, captureDebugEvents } from '../../../test-utils/engineDebug.js' +import { pictureSample, soundSample, tierStreamFragment, tierStreamInitialization, withParameterSets, writeTierFrame } from '../../../test-utils/mp4Fixtures.js' +import { openingStamp } from '../../../test-utils/openingStamp.js' +import { detachedReporter } from '../../../test-utils/reporterFixtures.js' +import { deferred, fakeTimeoutSignals, settle, until } from '../../../test-utils/settle.js' +import { openSFrameReference } from '../../../test-utils/sframeVectors.js' +import { keepingSink } from '../../../test-utils/talkbackSink.js' +import { LATER_BEST_TIERS, picture, SENSOR_UUID, ssrcsOf, STREAM_TIERS } from '../../../test-utils/webRTCEngineFixtures.js' +import { TierBuffer } from '../buffer/CameraBuffer.js' +import { CameraSensorIntent } from '../capabilities/cameraSensors.js' +import { CameraReporter } from '../diagnostics/CameraReporter.js' +import { cameraProblemsChannel } from '../diagnostics/problems.js' +import { firstSequence, SEQUENCE_RANGE } from '../rtp/packetRules.js' +import { SessionTalkback } from '../session/SessionTalkback.js' +import { DELEGATE_CALL_TIMEOUT } from '../session/settleWithin.js' +import { validateVideoSensors } from '../StreamingOptions.js' +import { TierHold, TierTable } from '../TierTable.js' +import { CALL_TIMEOUT, CONNECT_TIMEOUT, EngineSession, EngineStream } from './EngineSession.js' +import { deriveStreamKeys, SFrameSealer } from './sframe.js' +import { ReceiveKeys } from './voice/ReceiveKeys.js' +import { BETTER_VOICE, DEPENDABLE_VOICE, Viewer, ViewerVoice, VoiceStream } from './voice/ViewerVoice.js' +import { WebRTCEngine } from './WebRTCEngine.js' +import { loadWerift } from './werift.js' + +/* The suite's setup file imports the definitions, whose graph imports the engine's module through the camera controller, though nothing builds an engine + * there. The engine and its loader stand evaluated before this file's mocks are in place. The module registry is reset first, which is why this file's imports + * evaluate the engine over the mocked loader, the recorded sealing and the recorded draw. + */ +vi.hoisted(() => vi.resetModules()) + +// Every connection the mocked loader's class makes, in the order made, and the configuration each was handed. +const connections = vi.hoisted((): LoopbackConnections => ({ configs: [], peers: [] })) +const { configs, peers } = connections + +// The engine reaches werift through its one loader, mocked here to bind the loopback interface alone. +vi.mock('./werift.js', async () => { + const { loopbackLoader } = await import('../../../test-utils/webRTCEngineFixtures.js') + + return loopbackLoader(connections) +}) + +// The sealing module as it is, its derivation recorded, which lets a row read the SSRC each stream was keyed by and zeroing on the bytes of every derived key. +vi.mock('./sframe.js', async (importOriginal) => { + const actual = await importOriginal() + + return { + ...actual, + deriveStreamKeys: vi.fn(actual.deriveStreamKeys), + } +}) + +vi.mock('../rtp/packetRules.js', async (importOriginal) => { + const { recordedDraw } = await import('../../../test-utils/webRTCEngineFixtures.js') + + return recordedDraw(await importOriginal()) +}) + +// The sealing module unrecorded, which seals what the rows' viewer sends. +const sealing = await vi.importActual('./sframe.js') + +const OFFER_TIMEOUT = 5 * 1000 + +// The accessory of the camera whose reporter a row's caller hands the engine. +const CALLER_ACCESSORY_UUID = 'a1b2c3d4-0000-4000-8000-0000000000ca' + +/* A reporter of the caller's camera and every problem published on that camera's channel while the row runs, in the order published. The suite's module + * reset leaves the definitions unloaded in this file. The reporter's context carries its accessory's UUID alone, as the caller's reporter of the rows + * below does, which is all a published problem reads of it, and a subscription on the bare channel keeps each problem as it is published. + */ +function heardProblems(): { problems: CameraProblem[], reporter: CameraReporter } { + const problems: CameraProblem[] = [] + const name = cameraProblemsChannel(CALLER_ACCESSORY_UUID) + const hear = (message: unknown): void => { + problems.push(message as CameraProblem) + } + + subscribe(name, hear) + onTestFinished(() => { + unsubscribe(name, hear) + }) + + return { + problems, + reporter: new CameraReporter(() => ({ accessoryUUID: CALLER_ACCESSORY_UUID }) as ControllerAccessoryContext), + } +} + +// What the signaling class does for a session it holds, as the engine's way to end one: it aborts the session's request signal and calls the engine's +// endSession in the caller's turn, once. +// The camera's delegate the sensor's tier table reports to, each of its calls a mock, every demand's start registering at once a disposable of its own on +// its stream, whose disposal is a mock kept in the order of the starts, and answering nothing, unless a row scripts it. +interface ScriptedDelegate { + readonly disposals: Mock<() => void>[] + readonly talkbackStarted?: Mock> + readonly tierDemandStarted: Mock +} + +// How many times the library released the disposable each start the delegate did not script registered, in the order of the starts. +function disposalsOf(delegate: ScriptedDelegate): number[] { + return delegate.disposals.map(dispose => dispose.mock.calls.length) +} + +interface Signaling { + readonly delegate: ScriptedDelegate + readonly engine: WebRTCEngine + readonly ends: Mock<(sensorUUID: string, sessionIdentifier: string) => Promise> + readonly table: TierTable + // The sink the delegate's first talkbackStarted call answers, with the release it registers on its talker. + readonly talkback: KeepingSink + // The sink each talkbackStarted call answers, a sink of its own with a release of its own registered on its talker, in the order called. + readonly talkbacks: KeepingSink[] + // Makes a session's offer request, its signal one the double aborts as it ends the session. + request: (sframeEnabled?: boolean) => WebRTCOfferRequest + // Ends a session as the signaling class does at any of its exits. + end: (request: WebRTCOfferRequest) => Promise +} + +// What a row asks of its double: the reporter its sessions and its table report through, one of no camera by default, the reader of the Speaker's mute +// the engine is handed, unmuted by default, a delegate without talkbackStarted, the sensor's tiers when they are not the fixture's, and the voice setting +// the engine is handed. +interface SignalingOptions { + readonly reporter?: CameraReporter + readonly speakerMuted?: () => boolean + readonly talkback?: boolean + readonly tiers?: SensorStreamTiers + readonly voice?: WebRTCEngineOptions['voice'] +} + +function signaling(options: SignalingOptions = {}): Signaling { + const controllers = new Map() + const talkbacks = [ + keepingSink(), + ] + let started = 0 + const disposals: Mock<() => void>[] = [] + const delegate: ScriptedDelegate = { + disposals, + tierDemandStarted: vi.fn((stream) => { + const dispose = vi.fn<() => void>() + + disposals.push(dispose) + stream.use({ [Symbol.dispose]: dispose }) + }), + ...(options.talkback === false + ? {} + : { + talkbackStarted: vi.fn((talker: Talker) => (talkbacks[started++] ??= keepingSink()).start(talker)), + }), + } + const reporter = options.reporter ?? detachedReporter() + const table = new TierTable(delegate, options.tiers ?? STREAM_TIERS, tier => new TierBuffer(tier), reporter) + let engine: WebRTCEngine | undefined + const ends = vi.fn(async (_sensorUUID: string, sessionIdentifier: string) => { + const controller = controllers.get(sessionIdentifier) + + if (!controller) { + return + } + + controllers.delete(sessionIdentifier) + controller.abort() + await engine?.endSession(sessionIdentifier, reporter) + }) + + engine = new WebRTCEngine({ + endSession: ends, + speakerMuted: options.speakerMuted ?? (() => false), + tierTable: sensorUUID => sensorUUID === SENSOR_UUID + ? table + : undefined, + voice: options.voice, + }) + + return { + delegate, + engine, + ends, + table, + talkback: talkbacks[0], + talkbacks, + request: (sframeEnabled = false) => { + const controller = new AbortController() + const sessionIdentifier = randomUUID() + + controllers.set(sessionIdentifier, controller) + + return { + connection: buildEmitterConnection(), + options: { sframeEnabled }, + reporter, + sensorUUID: SENSOR_UUID, + sessionIdentifier, + signal: controller.signal, + } + }, + end: async request => ends(SENSOR_UUID, request.sessionIdentifier), + } +} + +// The sections of a description, each its lines from its m= line on. +function sectionsOf(sdp: string): string[][] { + return sdp.split('\r\nm=').slice(1).map(section => `m=${section}`.split('\r\n').filter(line => line !== '')) +} + +// The keys each stream of the rows' sessions was derived, in order. +function derivedKeys(): SFrameStreamKeys[] { + return vi.mocked(deriveStreamKeys).mock.results.map(result => result.value as SFrameStreamKeys) +} + +function zeroed(buffer: Buffer): boolean { + return buffer.every(octet => octet === 0) +} + +async function weriftPrototype(): Promise { + return (await loadWerift()).RTCPeerConnection.prototype +} + +// An answer the rows hand the engine, each with werift's apply held on a spy, which means werift never parses it: a routable host candidate on a documentation +// address and one on an mDNS host. +const ANSWER_MDNS_LINE = 'a=candidate:2 1 udp 2122317823 0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0.local 50002 typ host' +const ANSWER_SDP = [ + 'v=0', + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + 'a=candidate:1 1 udp 2122317823 192.0.2.20 50000 typ host', + ANSWER_MDNS_LINE, + '', +].join('\r\n') +const ROUTABLE_CANDIDATE = { candidate: 'candidate:3 1 udp 1686052607 198.51.100.20 50004 typ srflx', sdpMid: '0', sdpMLineIndex: 0 } +const MDNS_CANDIDATE = { candidate: 'candidate:4 1 udp 2122317823 9a8b7c6d-5e4f-4321-8765-0fedcba98765.local 50006 typ host', sdpMid: '0', sdpMLineIndex: 0 } + +// A session offered by an engine of its own, with the connection its offer built. +async function offered(options?: SignalingOptions): Promise { + const double = signaling(options) + const offerRequest = double.request() + const offer = await double.engine.createOffer(offerRequest) + + return { + ...double, + offer, + offerRequest, + peer: peers[peers.length - 1], + } +} + +// Accepts an answer with werift's apply and its candidate adds held on spies that resolve. +async function answered(engine: WebRTCEngine, offerRequest: WebRTCOfferRequest, additionalCandidates: typeof ROUTABLE_CANDIDATE[] = []): Promise { + const prototype = await weriftPrototype() + + vi.spyOn(prototype, 'setRemoteDescription').mockResolvedValue(undefined) + vi.spyOn(prototype, 'addIceCandidate').mockResolvedValue(undefined) + await engine.acceptAnswer(offerRequest.sessionIdentifier, { sdpAnswer: ANSWER_SDP, additionalCandidates }) +} + +// A Reoffer the rows hand the engine, a viewer's audio section added to what the hub answered, with a routable candidate and one on an mDNS host, and the +// answer werift's description operations are scripted to make for it. +const REOFFER_MDNS_LINE = 'a=candidate:6 1 udp 2122317823 4c3b2a19-0807-4f6e-9d5c-b4a392817065.local 50010 typ host' +const REOFFER_SDP = [ + 'v=0', + 'm=audio 9 UDP/TLS/RTP/SAVPF 111', + 'a=candidate:5 1 udp 2122317823 192.0.2.30 50008 typ host', + REOFFER_MDNS_LINE, + '', +].join('\r\n') +const REOFFER_ANSWER_SDP = ['v=0', 'm=audio 9 UDP/TLS/RTP/SAVPF 111', ''].join('\r\n') + +// werift's description operations for a Reoffer, held on spies that run them one at a time as werift does and move the connection's signaling state as +// werift's own do: a remote offer's apply to have-remote-offer, the answer's apply and a rollback back to stable, and a rollback refused in stable. A row +// scripts a step of its own through each step's hook, which runs in the step's place in the queue. +interface ReofferSteps { + readonly answer: Mock<() => Promise> + readonly apply: Mock<() => Promise> + readonly local: Mock<() => Promise> + // Every description the connection was asked to apply as a remote one, in order. + readonly remote: Mock<(description: werift.RTCSessionDescriptionInit) => Promise> + // How many rollbacks werift took. + rollbacks: number +} + +async function reofferSteps(peer: RTCPeerConnection): Promise { + const prototype = await weriftPrototype() + let tail = Promise.resolve() + + // The rows' answer is applied on a spy, which moves no state. The connection is set as werift leaves an answered one. + peer.signalingState = 'stable' + const queued = async (operation: () => Promise): Promise => { + const run = tail.then(operation) + + tail = run.then(() => undefined, () => undefined) + + return run + } + const steps: ReofferSteps = { + answer: vi.fn(async () => undefined), + apply: vi.fn(async () => undefined), + local: vi.fn(async () => undefined), + remote: vi.fn(async (description: werift.RTCSessionDescriptionInit) => queued(async () => { + if (description.type === 'rollback') { + if (peer.signalingState !== 'have-remote-offer') { + throw new Error('werift refuses a rollback in stable.') + } + + steps.rollbacks++ + peer.signalingState = 'stable' + + return + } + + await steps.apply() + peer.signalingState = 'have-remote-offer' + })), + rollbacks: 0, + } + + vi.spyOn(prototype, 'setRemoteDescription').mockImplementation(steps.remote) + vi.spyOn(prototype, 'createAnswer').mockImplementation(async () => queued(async () => { + await steps.answer() + + return { sdp: REOFFER_ANSWER_SDP, type: 'answer' } as werift.RTCSessionDescription + })) + vi.spyOn(prototype, 'setLocalDescription').mockImplementation(async () => queued(async () => { + await steps.local() + peer.signalingState = 'stable' + + return {} as werift.SessionDescription + })) + vi.spyOn(prototype, 'localDescription', 'get').mockReturnValue({ sdp: REOFFER_ANSWER_SDP, type: 'answer' } as werift.RTCSessionDescription) + + return steps +} + +// Moves a DTLS transport to a state as werift's handshake would, its state read and its subscribers told, since that handshake waits on timers. +function scriptTransport(transport: RTCDtlsTransport, state: RTCDtlsTransport['state']): void { + transport.state = state + transport.onStateChange.execute(state) +} + +// A packet the engine handed a sender, as it was handed, with a copy of its payload's octets taken at the send. +interface SentPacket { + readonly packet: werift.RtpPacket + readonly sentPayload: Buffer + readonly ssrc: number +} + +// A session offered and answered whose senders record every packet the engine hands them, its connection not yet connected, with the SSRC of each section. +async function sending(options?: SignalingOptions): Promise> & { sent: SentPacket[], ssrcs: number[] }> { + const session = await offered(options) + const sent: SentPacket[] = [] + + for (const sender of session.peer.getSenders()) { + vi.spyOn(sender, 'sendRtp').mockImplementation(async (rtp) => { + const packet = rtp as werift.RtpPacket + + sent.push({ + packet, + sentPayload: Buffer.from(packet.payload), + ssrc: sender.ssrc, + }) + }) + } + + await answered(session.engine, session.offerRequest) + + return { + ...session, + sent, + ssrcs: ssrcsOf(session.offer.sdpOffer), + } +} + +// The stream a video tier's demand handed the plugin at its start. +function streamOf(delegate: ScriptedDelegate, tierId: number): TierStream { + const call = delegate.tierDemandStarted.mock.calls.find(([stream]) => stream.tier.id === tierId) + + if (!call) { + throw new Error(`The video tier ${tierId} was never started.`) + } + + return call[0] +} + +// The fixture's sensor with its audio shared and the tier of the identifier given marked recorded, its tier set built by the options boundary, which +// chooses its sound tier. +function sharedTiers(recordedTierId: number): SensorStreamTiers { + const sensor: CameraVideoSensor = { + audio: { bitrate: 32, source: 'shared' }, + dimensions: { height: 1080, width: 1920 }, + intent: CameraSensorIntent.MAIN, + tiers: STREAM_TIERS.videoStreamTiers.tiers.map(({ frameRate, height, identifier, quality, targetAverageBitrate, width }) => ({ + bitrate: targetAverageBitrate, + frameRate, + height, + id: identifier, + quality, + recorded: identifier === recordedTierId, + width, + })), + uuid: SENSOR_UUID, + } + + const streaming = { + delegate: { + tierDemandStarted: (): void => undefined, + }, + } + + return validateVideoSensors([sensor], streaming, false).tierSets[0] +} + +// Each frame the picture stream of a video tier was handed, in the order handed: its time in milliseconds and the timestamp it was handed at, whole, read +// from a spy on the streams' hand-over. +function handed(take: MockInstance, tierId: number): { readonly time: number, readonly timestamp: number }[] { + return take.mock.calls.flatMap(([frame, timestamp], index) => { + const stream = take.mock.contexts[index] as EngineStream + + return ((stream.medium === 'video') && (stream.tier.tierId === tierId)) + ? [ + { + time: Math.round(frame.time / 1000), + timestamp, + }, + ] + : [] + }) +} + +// A frame's ciphertext put back from its packets, each payload's octet in front taken off. +function ciphertextOf(packets: readonly SentPacket[]): Buffer { + return Buffer.concat(packets.map(({ sentPayload }) => sentPayload.subarray(1))) +} + +// A ciphertext's counter, read from its SFrame header as RFC 9605 writes it. +function counterOf(ciphertext: Buffer): bigint { + const config = ciphertext[0] + const keyLength = (config & 0x80) + ? ((config >> 4) & 0x07) + 1 + : 0 + + if (!(config & 0x08)) { + return BigInt(config & 0x07) + } + + return ciphertext.subarray(1 + keyLength, 2 + keyLength + (config & 0x07)).reduce((value, octet) => (value << 8n) | BigInt(octet), 0n) +} + +// A holder of the rows' own for a frame consumer they join beside the engine's streams. +function rowHolder(): TierHolder { + return { + tierFailed: vi.fn(), + } +} + +// An event of a connection the engine subscribes to, read loosely, since each carries arguments of its own. +interface Subscribable { + subscribe: (...args: never[]) => { unSubscribe: () => void } +} + +// Spies on every event of a connection the engine subscribes to, answering the unSubscribe of each subscription made on one from then on. +function subscriptions(peer: RTCPeerConnection): Mock<() => void>[] { + return subscriptionsOf([ + peer.connectionStateChange, + ...peer.dtlsTransports.flatMap(transport => [ + transport.onStateChange, + transport.iceTransport.connection.onData, + transport.onRtp, + transport.onRtcp, + ]), + ...peer.getSenders().map(sender => sender.onKeyFrameRequest), + ]) +} + +// Spies on each event handed, answering the unSubscribe of each subscription made on one from then on. +function subscriptionsOf(events: readonly Subscribable[]): Mock<() => void>[] { + const made: Mock<() => void>[] = [] + + for (const event of events) { + const subscribe = event.subscribe + + vi.spyOn(event, 'subscribe').mockImplementation((...args) => { + const subscription = subscribe(...args) + const unSubscribe = vi.fn(subscription.unSubscribe) + + made.push(unSubscribe) + + return { ...subscription, unSubscribe } + }) + } + + return made +} + +// Whether any of the targets is reachable from the engine through the engine's own objects, its sessions, their streams, their key stores, their voice +// readers with their viewers, each viewer's talkback and voice streams, and the plain values they hold, werift's objects and the tier table being the +// library's or werift's own. +function reaches(engine: WebRTCEngine, targets: readonly unknown[]): boolean { + const seen = new Set() + const pending: unknown[] = [engine] + const owned = (value: object): boolean => [ + Array.prototype, + EngineSession.prototype, + EngineStream.prototype, + Map.prototype, + Object.prototype, + ReceiveKeys.prototype, + SessionTalkback.prototype, + Viewer.prototype, + ViewerVoice.prototype, + VoiceStream.prototype, + WebRTCEngine.prototype, + ].includes(Object.getPrototypeOf(value) as object) + + while (pending.length > 0) { + const value = pending.pop() + + if (targets.includes(value)) { + return true + } + + if ((typeof value !== 'object') || (value === null) || seen.has(value) || !owned(value)) { + continue + } + + seen.add(value) + pending.push(...(value instanceof Map + ? value.values() + : Object.values(value))) + } + + return false +} + +// The key ID and key a hub wrote for the rows' viewer, the SSRC its voice comes on and the Opus packet it says, each made up, and a second viewer's key ID, +// key and SSRC. +const VOICE_KEY_ID = 0x6B5A49388001n +const VOICE_SSRC = 0x3C4D5E6F +const VIEWER_SSRC = 0x4D5E6F70 +const VOICE_OPUS = [0x48, 0x80, 0x01, 0x02] +const SECOND_VOICE_KEY_ID = 0x6B5A49388002n +const SECOND_VOICE_SSRC = 0x5E6F7081 + +// A viewer of the rows' sessions: the key ID its packets are sealed under, its key's seed and the SSRC its voice comes on. +interface VoiceViewer { + readonly keyId: bigint + readonly seed: number + readonly ssrc: number +} + +const FIRST_VIEWER: VoiceViewer = { keyId: VOICE_KEY_ID, seed: 0x6A, ssrc: VOICE_SSRC } +const SECOND_VIEWER: VoiceViewer = { keyId: SECOND_VOICE_KEY_ID, seed: 0x7B, ssrc: SECOND_VOICE_SSRC } + +function voiceKey(viewer: VoiceViewer = FIRST_VIEWER): Buffer { + return Buffer.alloc(16, viewer.seed) +} + +// A viewer's voice packet on a payload type, sealed under the viewer's key and its own SSRC at a counter behind the octet that marks a whole ciphertext. +function voicePacket(payloadType: number, counter: bigint, viewer: VoiceViewer = FIRST_VIEWER): RtpPacket { + const keys = sealing.deriveStreamKeys({ + keyId: viewer.keyId, + sessionKey: voiceKey(viewer), + ssrc: viewer.ssrc, + suite: sealing.SFRAME_AUDIO_SUITE, + }) + const ciphertext = sealing.sealSFrame(keys, counter, Buffer.from(VOICE_OPUS)) + + return new RtpPacket(new RtpHeader({ + payloadType, + sequenceNumber: 500 + Number(counter), + ssrc: viewer.ssrc, + timestamp: 96000 + Number(counter) * 960, + }), Buffer.concat([ + Buffer.from([0xC0]), + ciphertext, + ])) +} + +// Hands a session's engine a viewer's key. +async function writeVoiceKey(engine: WebRTCEngine, sessionIdentifier: string, viewer: VoiceViewer = FIRST_VIEWER): Promise { + await engine.updateReceiveKeys(sessionIdentifier, { + receiveKeysToAdd: [ + { + key: voiceKey(viewer), + kid: viewer.keyId, + }, + ], + receiveKIDsToRemove: [], + }, detachedReporter()) +} + +beforeEach(() => { + vi.mocked(deriveStreamKeys).mockClear() +}) + +// The mocks are restored before the real timers return, which means a row that spies on a mock timer leaves the real one in place for the rows after it. +afterEach(async () => { + vi.restoreAllMocks() + vi.useRealTimers() + configs.length = 0 + + for (const peer of peers.splice(0)) { + await peer.close() + } +}) + +describe('webRTCEngine', () => { + describe('offer', () => { + it('offers one bundle of a video section for each tier in the advertised order and then the audio section, every candidate in its text', async () => { + const { end, engine, request } = signaling() + const offerRequest = request() + const offer = await engine.createOffer(offerRequest) + const sections = sectionsOf(offer.sdpOffer) + const videoSections = sections.slice(0, 3) + const extensions = sections.map(section => section.filter(line => line.startsWith('a=extmap:'))) + + expect(offer.sdpOffer).toContain('\r\na=group:BUNDLE 0 1 2 3\r\n') + expect(sections.map(section => section[0])).toEqual([ + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + 'm=video 9 UDP/TLS/RTP/SAVPF 99', + 'm=audio 9 UDP/TLS/RTP/SAVPF 110', + ]) + + for (const section of sections) { + expect(section).toContain('a=sendonly') + expect(section.filter(line => line.startsWith('a=ssrc:'))).toHaveLength(1) + expect(section.filter(line => line.startsWith('a=candidate:')).length).toBeGreaterThan(0) + } + + for (const [index, section] of videoSections.entries()) { + const { frameRate, height, targetAverageBitrate, width } = STREAM_TIERS.videoStreamTiers.tiers[index] + + expect(section.filter(line => /^a=(?:rtpmap|rtcp-fb|fmtp|rid|simulcast):/.test(line))).toEqual([ + 'a=rtpmap:99 H265/90000', + 'a=rtcp-fb:99 nack', + 'a=rtcp-fb:99 nack pli', + 'a=rtcp-fb:99 ccm fir', + `a=rid:${index + 1} send max-width=${width};max-height=${height};max-fps=${frameRate};max-br=${targetAverageBitrate * 1000}`, + `a=simulcast:send ${index + 1}`, + ]) + } + + expect(sections[3].filter(line => /^a=(?:rtpmap|fmtp|rid|simulcast):/.test(line))).toEqual([ + 'a=rtpmap:110 opus/48000', + 'a=fmtp:110 minptime=20;useinbandfec=0', + ]) + expect(extensions[0]).toEqual([ + expect.stringMatching(/^a=extmap:\d+ urn:ietf:params:rtp-hdrext:sdes:mid$/), + expect.stringMatching(/^a=extmap:\d+ urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id$/), + ]) + expect(extensions).toEqual([ + extensions[0], + extensions[0], + extensions[0], + extensions[0], + ]) + expect(offer.additionalCandidates).toEqual([]) + + await end(offerRequest) + }) + + it('builds the transceivers again on a fresh connection while two SSRCs share their low sixteen bits, keying each stream by the final SSRCs', async () => { + const prototype = await weriftPrototype() + const addTransceiver = prototype.addTransceiver + const { end, engine, request } = signaling() + const offerRequest = request() + + // The first build's SSRCs share their low sixteen bits and the second's differ, every SSRC written as werift writes a sender's, before the offer. + vi.spyOn(prototype, 'addTransceiver').mockImplementation(function (this: RTCPeerConnection, ...args: Parameters) { + const transceiver = addTransceiver.apply(this, args) + const index = this.getTransceivers().length - 1 + const low = peers.indexOf(this) === 0 + ? 0x4242 + : index; + + (transceiver.sender as { ssrc: number }).ssrc = ((index + 1) * 0x10000) + low + + return transceiver + }) + + const offer = await engine.createOffer(offerRequest) + const finalSSRCs = [0x10000, 0x20001, 0x30002, 0x40003] + + expect(peers).toHaveLength(2) + expect(peers[0].connectionState).toBe('closed') + expect(ssrcsOf(offer.sdpOffer)).toEqual(finalSSRCs) + expect(vi.mocked(deriveStreamKeys).mock.calls.map(([stream]) => stream.ssrc)).toEqual(finalSSRCs) + + await end(offerRequest) + }) + + it('fails the offer once every build draws SSRCs sharing their low sixteen bits, closing every connection it built', async () => { + const prototype = await weriftPrototype() + const addTransceiver = prototype.addTransceiver + const { end, engine, request } = signaling() + const offerRequest = request() + + vi.spyOn(prototype, 'addTransceiver').mockImplementation(function (this: RTCPeerConnection, ...args: Parameters) { + const transceiver = addTransceiver.apply(this, args); + + (transceiver.sender as { ssrc: number }).ssrc = (this.getTransceivers().length * 0x10000) + 0x4242 + + return transceiver + }) + + await expect(engine.createOffer(offerRequest)).rejects.toThrow( + `WebRTC session ${offerRequest.sessionIdentifier} drew SSRCs sharing their low sixteen bits on 8 connections in a row, and its offer fails.`, + ) + expect(peers).toHaveLength(8) + expect(peers.map(peer => peer.connectionState)).toEqual(Array.from({ length: 8 }).fill('closed')) + expect(deriveStreamKeys).not.toHaveBeenCalled() + + await end(offerRequest) + }) + + it('fails an offer whose gather never ends at 5 seconds, the teardown the signaling class then calls closing its connection', async () => { + const prototype = await weriftPrototype() + const gather = vi.spyOn(prototype, 'setLocalDescription').mockImplementation(async () => new Promise(() => undefined)) + const { end, engine, request } = signaling() + const offerRequest = request() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + let settled = false + const offer = engine.createOffer(offerRequest).finally(() => { + settled = true + }) + + void offer.catch(() => undefined) + + await until(() => gather.mock.calls.length > 0) + await vi.advanceTimersByTimeAsync(OFFER_TIMEOUT - 1) + + expect(settled).toBe(false) + + await vi.advanceTimersByTimeAsync(1) + await expect(offer).rejects.toThrow(`The offer of WebRTC session ${offerRequest.sessionIdentifier} was cut at the gather by its budget of 5 seconds.`) + + expect(peers).toHaveLength(1) + expect(peers[0].connectionState).not.toBe('closed') + + await end(offerRequest) + + expect(peers[0].connectionState).toBe('closed') + }) + + it('fails an offer at once when its signal aborts during the gather', async () => { + const prototype = await weriftPrototype() + const gather = vi.spyOn(prototype, 'setLocalDescription').mockImplementation(async () => new Promise(() => undefined)) + const { end, engine, request } = signaling() + const offerRequest = request() + const offer = engine.createOffer(offerRequest) + + void offer.catch(() => undefined) + + await until(() => gather.mock.calls.length > 0) + await end(offerRequest) + await expect(offer).rejects.toThrow(`WebRTC session ${offerRequest.sessionIdentifier} ended during the gather, and its offer fails.`) + + expect(peers[0].connectionState).toBe('closed') + }) + + it('returns a fresh 32-octet key under a key ID whose low sixteen bits read 0x8000 with every offer, whether or not the solicit asks for SFrame', async () => { + const { end, engine, request } = signaling() + const requests = [ + request(false), + request(true), + ] + const offers: WebRTCOffer[] = [] + + for (const offerRequest of requests) { + offers.push(await engine.createOffer(offerRequest)) + } + + const configurations = offers.map(({ sframeConfiguration }) => sframeConfiguration) + + for (const configuration of configurations) { + expect(configuration?.key).toHaveLength(32) + expect((configuration?.kid ?? 0n) & 0xFFFFn).toBe(0x8000n) + } + + expect(configurations[0]?.key.equals(configurations[1]?.key ?? Buffer.alloc(0))).toBe(false) + expect(configurations[0]?.kid).not.toBe(configurations[1]?.kid) + + for (const offerRequest of requests) { + await end(offerRequest) + } + }) + + it('logs a solicit that asks for SFrame once at debug, and one that does not ask nothing', async () => { + const lines = captureDebug() + const { end, engine, request } = signaling() + const asking = request(true) + const silent = request(false) + + await engine.createOffer(asking) + await engine.createOffer(silent) + await end(asking) + await end(silent) + + expect(lines.filter(line => line.includes('asking for SFrame'))).toEqual([ + expect.stringContaining(`WebRTC session ${asking.sessionIdentifier} was solicited asking for SFrame.`), + ]) + }) + + it('writes no SDP text, address, candidate or key to any console or debug line of an offer and its teardown', async () => { + const events = captureDebugEvents() + const consoleLines: unknown[][] = [] + + for (const method of [ + 'debug', + 'error', + 'info', + 'log', + 'warn', + ] as const) { + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + consoleLines.push(args) + }) + } + + const { end, engine, request } = signaling() + const offerRequest = request(true) + const offer = await engine.createOffer(offerRequest) + const key = offer.sframeConfiguration?.key.toString('hex') ?? '' + const credentials = sectionsOf(offer.sdpOffer)[0].filter(line => /^a=(?:ice-ufrag|ice-pwd|fingerprint):/.test(line)).map(line => line.slice(line.indexOf(':') + 1)) + + await answered(engine, offerRequest, [ROUTABLE_CANDIDATE, MDNS_CANDIDATE]) + await reofferSteps(peers[0]) + await engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: true }, + }) + peers[0].connectionStateChange.execute('failed') + await settle() + await end(offerRequest) + + // Each debug event is read whole, its sentence and every detail it carries. + const written = [ + ...events.map(event => JSON.stringify(event)), + ...consoleLines.map(args => format(...args)), + ] + + expect(events.length).toBeGreaterThan(0) + expect(credentials).toHaveLength(3) + + for (const line of written) { + for (const needle of [ + '127.0.0.1', + 'candidate:', + 'a=', + 'v=0', + 'IN IP4', + '192.0.2.20', + '192.0.2.30', + '198.51.100.20', + '.local', + key, + ...credentials, + ]) { + expect(line).not.toContain(needle) + } + } + }) + + it.each([ + { step: 'the werift load' }, + { step: 'werift\'s offer' }, + { step: 'the gather' }, + ])('fails an offer whose session ends during $step, leaving no connection open and registering nothing on the ended session', async ({ step }) => { + const exports = await loadWerift() + const prototype = exports.RTCPeerConnection.prototype + const held = deferred() + const reached = vi.fn() + const { end, engine, request } = signaling() + const offerRequest = request() + + switch (step) { + case 'the werift load': + vi.mocked(loadWerift).mockImplementationOnce(async () => { + reached() + + return held.promise + }) + break + + case 'werift\'s offer': + vi.spyOn(prototype, 'createOffer').mockImplementationOnce(async () => { + reached() + + return new Promise(() => undefined) + }) + break + + default: + vi.spyOn(prototype, 'setLocalDescription').mockImplementationOnce(async () => { + reached() + + return new Promise(() => undefined) + }) + } + + const offer = engine.createOffer(offerRequest) + + void offer.catch(() => undefined) + + await until(() => reached.mock.calls.length > 0) + + const derived = vi.mocked(deriveStreamKeys).mock.calls.length + + await end(offerRequest) + held.resolve(exports) + await expect(offer).rejects.toThrow(`WebRTC session ${offerRequest.sessionIdentifier} ended during ${step}, and its offer fails.`) + await settle() + + expect(peers.map(peer => peer.connectionState).filter(state => state !== 'closed')).toEqual([]) + expect(vi.mocked(deriveStreamKeys).mock.calls).toHaveLength(derived) + expect(derivedKeys().every(({ secret }) => zeroed(secret))).toBe(true) + }) + + it('fails an offer that awaits a failed werift load, as a failed offer', async () => { + const failure = new Error('The werift install is broken.') + const { end, engine, request } = signaling() + const offerRequest = request() + + vi.mocked(loadWerift).mockRejectedValueOnce(failure) + + const rejection = await engine.createOffer(offerRequest).then(() => undefined, (error: unknown) => error as Error) + + expect(rejection?.message).toBe(`WebRTC session ${offerRequest.sessionIdentifier} failed at the werift load, and its offer fails.`) + expect(rejection?.cause).toBe(failure) + expect(peers).toHaveLength(0) + + await end(offerRequest) + }) + }) + + describe('answer and transport', () => { + it('hands werift the answer and its additional candidates without a candidate on an mDNS host', async () => { + const prototype = await weriftPrototype() + const apply = vi.spyOn(prototype, 'setRemoteDescription').mockResolvedValue(undefined) + const add = vi.spyOn(prototype, 'addIceCandidate').mockResolvedValue(undefined) + const { end, engine, offerRequest, peer } = await offered() + // A host with a label after .local, which werift looks up by multicast DNS too, in the answer's text and in its additional candidates. + const labelled = 'a=candidate:7 1 udp 2122317823 printer.local.example 50012 typ host' + const labelledCandidate = { candidate: 'candidate:8 1 udp 2122317823 printer.local.example 50014 typ host', sdpMid: '0', sdpMLineIndex: 0 } + + await engine.acceptAnswer(offerRequest.sessionIdentifier, { + sdpAnswer: ANSWER_SDP.replace(`${ANSWER_MDNS_LINE}\r\n`, `${ANSWER_MDNS_LINE}\r\n${labelled}\r\n`), + additionalCandidates: [ROUTABLE_CANDIDATE, MDNS_CANDIDATE, labelledCandidate], + }) + + expect(apply).toHaveBeenCalledExactlyOnceWith({ + sdp: ANSWER_SDP.replace(`${ANSWER_MDNS_LINE}\r\n`, ''), + type: 'answer', + }) + expect(add).toHaveBeenCalledExactlyOnceWith(ROUTABLE_CANDIDATE) + + const { remote } = await reofferSteps(peer) + + await engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }) + + expect(remote).toHaveBeenCalledExactlyOnceWith({ + sdp: REOFFER_SDP.replace(`${REOFFER_MDNS_LINE}\r\n`, ''), + type: 'offer', + }) + + await end(offerRequest) + }) + + it('replays a DTLS record that arrives while its transport is new once, on the turn after the transport reports connecting', async () => { + const { end, engine, offerRequest, peer } = await offered() + const transport = peer.dtlsTransports[0] + const { connection } = transport.iceTransport + const record = Buffer.from([22, 0xFE, 0xFD, 0, 1, 2, 3]) + const heard = vi.fn() + + await answered(engine, offerRequest) + connection.onData.execute(record) + connection.onData.subscribe(heard) + scriptTransport(transport, 'connecting') + + expect(heard).not.toHaveBeenCalled() + + await settle() + await settle() + + expect(heard).toHaveBeenCalledExactlyOnceWith(record) + + await end(offerRequest) + }) + + it('keeps at most 8 early DTLS records and 16,384 octets, dropping and counting the rest, and holds nothing after its replay', async () => { + const lines = captureDebug() + const { end, engine, offerRequest, peer } = await offered() + const transport = peer.dtlsTransports[0] + const { connection } = transport.iceTransport + const subscribers = connection.onData.length + const records = Array.from({ length: 9 }, (_, index) => Buffer.alloc(100, 20 + index)) + const large = Buffer.alloc(16 * 1024, 23) + const heard = vi.fn() + + await answered(engine, offerRequest) + + for (const record of [ + ...records, + Buffer.from([0, 1, 0, 0]), + large, + ]) { + connection.onData.execute(record) + } + + connection.onData.subscribe(heard) + scriptTransport(transport, 'connecting') + await settle() + await settle() + + expect(heard.mock.calls.map(([record]) => record as Buffer)).toEqual(records.slice(0, 8)) + expect(lines).toContainEqual(expect.stringContaining(`WebRTC session ${offerRequest.sessionIdentifier} replays 8 early DTLS records, 2 dropped.`)) + expect(connection.onData.length).toBe(subscribers + 1) + + await end(offerRequest) + }) + + it.each([ + { + failure: 'its connection fails', + script: (peer: RTCPeerConnection) => peer.connectionStateChange.execute('failed'), + warning: 'lost its connection. The session ends.', + }, + { + failure: 'a connected DTLS transport closes', + script: (peer: RTCPeerConnection) => { + peer.connectionStateChange.execute('connected') + scriptTransport(peer.dtlsTransports[0], 'closed') + }, + warning: 'had its DTLS transport closed. The session ends.', + }, + { + failure: 'its DTLS transport and connection fail', + script: (peer: RTCPeerConnection) => { + scriptTransport(peer.dtlsTransports[0], 'failed') + peer.connectionStateChange.execute('failed') + }, + // werift turns the connection failed inside the transport's own pass: the connection's route is the one that ends the session. + warning: 'lost its connection. The session ends.', + }, + ])('ends a session once through the signaling class with one warning when $failure, closing its connection and zeroing its key', async ({ script, warning }) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { ends, engine, offer, offerRequest, peer } = await offered() + const { sessionIdentifier } = offerRequest + + await answered(engine, offerRequest) + script(peer) + await settle() + + expect(ends).toHaveBeenCalledExactlyOnceWith(SENSOR_UUID, sessionIdentifier) + expect(warn).toHaveBeenCalledExactlyOnceWith(`WebRTC session ${sessionIdentifier} ${warning}`) + expect(peer.connectionState).toBe('closed') + expect(zeroed(offer.sframeConfiguration?.key ?? Buffer.alloc(1, 1))).toBe(true) + }) + + it('ends nothing again at the engine\'s own teardown, whose close sets the DTLS transport closed', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { end, ends, engine, offerRequest, peer } = await offered() + const transport = peer.dtlsTransports[0] + + await answered(engine, offerRequest) + peer.connectionStateChange.execute('connected') + await end(offerRequest) + await settle() + + expect(transport.state).toBe('closed') + expect(ends).toHaveBeenCalledOnce() + expect(warn).not.toHaveBeenCalled() + }) + + it('rejects an answer whose apply fails, and cuts one whose apply never settles at 2 seconds', async () => { + const prototype = await weriftPrototype() + const failure = new Error('The apply failed.') + const apply = vi.spyOn(prototype, 'setRemoteDescription').mockRejectedValueOnce(failure) + const failing = await offered() + const rejection = await failing.engine.acceptAnswer(failing.offerRequest.sessionIdentifier, { sdpAnswer: ANSWER_SDP, additionalCandidates: [] }) + .then(() => undefined, (error: unknown) => error as Error) + + expect(rejection?.message).toBe(`WebRTC session ${failing.offerRequest.sessionIdentifier} failed at the answer's apply, and its answer fails.`) + expect(rejection?.cause).toBe(failure) + + const stuck = await offered() + + apply.mockImplementation(async () => new Promise(() => undefined)) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + const accepting = stuck.engine.acceptAnswer(stuck.offerRequest.sessionIdentifier, { sdpAnswer: ANSWER_SDP, additionalCandidates: [] }) + + void accepting.catch(() => undefined) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT) + await expect(accepting).rejects.toThrow( + `The answer of WebRTC session ${stuck.offerRequest.sessionIdentifier} was cut at the answer's apply by its budget of 2 seconds.`, + ) + vi.useRealTimers() + await failing.end(failing.offerRequest) + await stuck.end(stuck.offerRequest) + }) + + it('ends a session whose connection has not connected 30 seconds after its accepted answer once, with one warning, and leaves one that connects', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const late = await offered() + const prompt = await offered() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + await answered(late.engine, late.offerRequest) + await answered(prompt.engine, prompt.offerRequest) + await vi.advanceTimersByTimeAsync(CONNECT_TIMEOUT - 1000) + prompt.peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(999) + + expect(late.ends).not.toHaveBeenCalled() + + // Every tier the connected session joined hands over pictures through the wait, which keeps each demand inside its silence bounds and leaves the + // connect bound alone to end a session. + await vi.advanceTimersByTimeAsync(1) + await keepStreaming(streamsOf(prompt.delegate), CONNECT_TIMEOUT, { advance: advanceAsync }) + + expect(late.ends).toHaveBeenCalledExactlyOnceWith(SENSOR_UUID, late.offerRequest.sessionIdentifier) + expect(prompt.ends).not.toHaveBeenCalled() + expect(warn).toHaveBeenCalledExactlyOnceWith( + `WebRTC session ${late.offerRequest.sessionIdentifier} did not connect within 30 seconds of its accepted answer. The session ends.`, + ) + + vi.useRealTimers() + await prompt.end(prompt.offerRequest) + }) + + it('arms no bound for a session whose connection reported connected before its answer\'s apply settled and then dropped', async () => { + const prototype = await weriftPrototype() + const held = deferred() + const { delegate, end, ends, engine, offerRequest, peer } = await offered() + + vi.spyOn(prototype, 'setRemoteDescription').mockReturnValueOnce(held.promise) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + const accepted = engine.acceptAnswer(offerRequest.sessionIdentifier, { sdpAnswer: ANSWER_SDP, additionalCandidates: [] }) + + await settle() + peer.connectionStateChange.execute('connected') + peer.connectionStateChange.execute('disconnected') + held.resolve() + await accepted + // Every tier the session joined as it connected hands over pictures through the wait, which keeps each demand inside its silence bounds. + await keepStreaming(streamsOf(delegate), CONNECT_TIMEOUT * 2, { advance: advanceAsync }) + + expect(ends).not.toHaveBeenCalled() + + vi.useRealTimers() + await end(offerRequest) + }) + + it('warns nothing of the bound for a session the signaling class ends before it, ending it once and leaving no listener on the bound', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { end, ends, engine, offerRequest } = await offered() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + await answered(engine, offerRequest) + + const bound = vi.mocked(AbortSignal.timeout).mock.calls.findIndex(([delay]) => delay === CONNECT_TIMEOUT) + const signal = vi.mocked(AbortSignal.timeout).mock.results[bound].value as AbortSignal + + expect(getEventListeners(signal, 'abort')).toHaveLength(1) + + await vi.advanceTimersByTimeAsync(CONNECT_TIMEOUT / 3) + + const ending = end(offerRequest) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT) + await ending + + expect(getEventListeners(signal, 'abort')).toHaveLength(0) + + await vi.advanceTimersByTimeAsync(CONNECT_TIMEOUT) + + expect(ends).toHaveBeenCalledOnce() + expect(warn).not.toHaveBeenCalled() + }) + + it('logs the throw of a subscriber\'s work and throws nothing into werift', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { end, ends, engine, offerRequest, peer } = await offered() + + await answered(engine, offerRequest) + ends.mockImplementationOnce(() => { + throw new Error('The signaling class failed.') + }) + + expect(() => peer.connectionStateChange.execute('failed')).not.toThrow() + expect(error).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('The WebRTC engine failed to handle a connection state for WebRTC session ' + + `${offerRequest.sessionIdentifier}: Error: The signaling class failed.`)) + + await end(offerRequest) + }) + + it('logs once a route\'s call of the signaling class that rejects, leaving no rejection unhandled', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const failure = new Error('The signaling class failed to end the session.') + const unhandled = vi.fn() + const { end, ends, engine, offerRequest, peer } = await offered() + + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + await answered(engine, offerRequest) + ends.mockRejectedValueOnce(failure) + process.on('unhandledRejection', unhandled) + + try { + peer.connectionStateChange.execute('failed') + await settle() + await settle() + + expect(ends).toHaveBeenCalledOnce() + expect(error).toHaveBeenCalledExactlyOnceWith(expect.stringContaining(`The WebRTC engine failed to end WebRTC session ${offerRequest.sessionIdentifier}: ` + + 'Error: The signaling class failed to end the session.')) + expect(unhandled).not.toHaveBeenCalled() + } finally { + process.off('unhandledRejection', unhandled) + } + + await end(offerRequest) + }) + + it.each([ + { + // The route that ends a session whose connection fails, with the view's own problem. + failing: false, + site: 'a route that ends its session', + }, + { + // The same route, the signaling class throwing inside it. The subscriber's work fails and its guard reports the engine's own failure after the + // view's problem. + failing: true, + site: 'a subscriber\'s work that throws', + }, + ])('raises each problem of its kind and level naming the sensor and the session for $site', async ({ failing }) => { + const { problems, reporter } = heardProblems() + const thrown = new Error('The signaling class failed.') + const { end, ends, engine, offerRequest, peer } = await offered({ reporter }) + const { sessionIdentifier } = offerRequest + + await answered(engine, offerRequest) + + if (failing) { + ends.mockImplementationOnce(() => { + throw thrown + }) + } + + peer.connectionStateChange.execute('failed') + await settle() + + // Each problem is read whole, its sentence's wording aside, and a field it gains or loses is read too. + const viewFailed = { + accessoryUUID: CALLER_ACCESSORY_UUID, + kind: 'view-failed', + level: 'warning', + sensorUUID: SENSOR_UUID, + sentence: expect.any(String), + sessionIdentifier, + } + const engineFailed = { + accessoryUUID: CALLER_ACCESSORY_UUID, + error: thrown, + kind: 'library-failure', + level: 'error', + sensorUUID: SENSOR_UUID, + sentence: expect.any(String), + sessionIdentifier, + } + + expect(problems).toEqual([ + viewFailed, + ...(failing + ? [engineFailed] + : []), + ]) + + await end(offerRequest) + }) + + it('hands each connection it builds the fixed options, host candidates of both families among them, before the loopback class binds it', async () => { + const { end, offerRequest } = await offered() + + expect(peers).not.toHaveLength(0) + expect(configs).toEqual(peers.map(() => expect.objectContaining({ + bundlePolicy: 'max-bundle', + certificateScope: 'standard', + iceServers: [], + iceUseDefaultStunServer: false, + iceUseIpv6: true, + keyFrameRequestRouting: 'standard', + }))) + + await end(offerRequest) + }) + + it('replays nothing for a session torn down while the replay of its early DTLS records is pending', async () => { + const { end, engine, offerRequest, peer } = await offered() + const transport = peer.dtlsTransports[0] + const { connection } = transport.iceTransport + const heard = vi.fn() + + await answered(engine, offerRequest) + connection.onData.execute(Buffer.from([22, 0xFE, 0xFD, 0, 1, 2, 3])) + connection.onData.subscribe(heard) + scriptTransport(transport, 'connecting') + await end(offerRequest) + await settle() + await settle() + + expect(heard).not.toHaveBeenCalled() + }) + + it('keeps no early record whose first octet passes 63, the last octet RFC 7983 gives a DTLS record', async () => { + const { end, engine, offerRequest, peer } = await offered() + const transport = peer.dtlsTransports[0] + const { connection } = transport.iceTransport + const records = [63, 64, 127, 128].map(first => Buffer.from([first, 0xFE, 0xFD, 0])) + const heard = vi.fn() + + await answered(engine, offerRequest) + + for (const record of records) { + connection.onData.execute(record) + } + + connection.onData.subscribe(heard) + scriptTransport(transport, 'connecting') + await settle() + await settle() + + expect(heard.mock.calls.map(([record]) => record as Buffer)).toEqual(records.slice(0, 1)) + + await end(offerRequest) + }) + + it('holds no subscriber on a DTLS transport\'s state once its session\'s teardown has run, before werift closes the transport', async () => { + const prototype = await weriftPrototype() + const { end, engine, offerRequest, peer } = await offered() + const transport = peer.dtlsTransports[0] + const subscribers = transport.onStateChange.length + + await answered(engine, offerRequest) + + expect(transport.onStateChange.length).toBeGreaterThan(subscribers) + + // The connection's close is held: werift's own close, which drops every subscriber of the transport, leaves the count to the engine's teardown. + vi.spyOn(prototype, 'close').mockResolvedValue(undefined) + await end(offerRequest) + + expect(transport.onStateChange.length).toBe(subscribers) + }) + + it('starts no tier at a report of connected for a session whose end has begun', async () => { + const { delegate, end, engine, offerRequest, peer } = await offered() + + await answered(engine, offerRequest) + + const ending = end(offerRequest) + + peer.connectionStateChange.execute('connected') + await ending + await settle() + + expect(delegate.tierDemandStarted).not.toHaveBeenCalled() + }) + }) + + describe('media', () => { + it('joins every tier at connected and sends each frame after it sealed whole through its tier\'s sender, none released before', async () => { + const { delegate, end, offer, offerRequest, peer, sent, ssrcs, table } = await sending() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const key = Buffer.from(offer.sframeConfiguration?.key ?? Buffer.alloc(0)) + const placed: number[] = [] + const watching = table.joinFrames(table.videoTiers.get(1)!, 'video', rowHolder(), { + take: (_frame, timestamp) => placed.push(timestamp), + }) + + await settle() + + const stream = streamOf(delegate, 1) + + // A picture and a sound released before the view connects, and after the connect a keyframe and a picture after it. The picture reaches no + // consumer, since none has been sent a keyframe, and the sound, which a consumer joined then would be sent at once, reaches none, since the view + // joins its tiers only at connected. + writeTierFrame(stream, 'video', { + data: picture(500, 1), + time: 0, + }) + writeTierFrame(stream, 'audio', { + data: Buffer.alloc(60, 9), + time: 0, + }) + await vi.advanceTimersByTimeAsync(0) + peer.connectionStateChange.execute('connected') + await settle() + + expect(sent).toEqual([]) + expect(delegate.tierDemandStarted.mock.calls.map(([stream]) => stream.tier.id)).toEqual([1, 2, 3]) + + const frames = [ + withParameterSets(picture(3000, 2)), + picture(40, 3), + ] + + writeTierFrame(stream, 'video', { data: frames[0], keyframe: true, time: 33333 }) + writeTierFrame(stream, 'video', { data: frames[1], time: 66667 }) + await vi.advanceTimersByTimeAsync(67) + + const packets = sent.filter(({ ssrc }) => ssrc === ssrcs[0]) + const first = packets[0].packet.header.sequenceNumber + + expect(sent).toHaveLength(packets.length) + expect(packets.map(({ packet }) => packet.header.marker)).toEqual([false, false, true, true]) + expect(packets.map(({ packet }) => packet.header.sequenceNumber)).toEqual([0, 1, 2, 3].map(step => (first + step) % 0x10000)) + expect(packets.map(({ packet }) => packet.header.timestamp)).toEqual([ + placed[0], + placed[0], + placed[0], + placed[1], + ].map(timestamp => timestamp >>> 0)) + expect(packets.every(({ packet }) => packet.header.payloadType === 99 && packet.payload.length <= 1088)).toBe(true) + expect([ + packets.slice(0, 3), + packets.slice(3), + ].map(ciphertextOf).map(ciphertext => openSFrameReference({ + ciphertext, + sessionKey: key, + ssrc: ssrcs[0], + suite: 6, + tagLength: 10, + }))).toEqual(frames) + + watching.release() + vi.useRealTimers() + await end(offerRequest) + }) + + it('takes a view\'s sound from the sensor\'s best tier, a tie of pixels going to the higher bitrate, sent under the audio tier\'s payload type and sealed ' + + 'as sound', async () => { + const { delegate, end, offer, offerRequest, peer, sent, ssrcs, table } = await sending({ tiers: LATER_BEST_TIERS }) + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const key = Buffer.from(offer.sframeConfiguration?.key ?? Buffer.alloc(0)) + + peer.connectionStateChange.execute('connected') + await settle() + + // Each tier's stream carries a sound of its own, which only the best tier's reaches the view. + for (const tierId of [1, 2, 3]) { + writeTierFrame(streamOf(delegate, tierId), 'audio', { + data: Buffer.alloc(60, tierId), + time: 0, + }) + } + + await vi.advanceTimersByTimeAsync(0) + + expect(table.soundTier.tierId).toBe(3) + expect(sent.map(({ ssrc }) => ssrc)).toEqual([ssrcs[3]]) + expect(sent.map(({ packet }) => packet.header.payloadType)).toEqual([110]) + expect(sent.map(({ sentPayload }) => sentPayload[0])).toEqual([0xC0]) + expect(sent.map(packet => openSFrameReference({ + ciphertext: ciphertextOf([packet]), + sessionKey: key, + ssrc: ssrcs[3], + suite: 8, + tagLength: 4, + }))).toEqual([ + Buffer.alloc(60, 3), + ]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('takes a view\'s sound from the sound tier of a shared sensor marked recorded on a tier that is not its best, and none from the best tier\'s Opus, ' + + 'which the best tier\'s stream reads as none', async () => { + const tiers = sharedTiers(2) + const { delegate, end, offer, offerRequest, peer, sent, ssrcs, table } = await sending({ tiers }) + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const key = Buffer.from(offer.sframeConfiguration?.key ?? Buffer.alloc(0)) + + peer.connectionStateChange.execute('connected') + await settle() + + // Each tier's stream carries a sound of its own, which only the sound tier's reaches the view. + for (const tierId of [1, 2, 3]) { + writeTierFrame(streamOf(delegate, tierId), 'audio', { + data: Buffer.alloc(60, tierId), + time: 0, + }) + } + + await vi.advanceTimersByTimeAsync(0) + + expect(table.soundTier.tierId).toBe(2) + expect([1, 2, 3].map(tierId => table.videoTiers.get(tierId)!.buffer.tracks?.audio !== undefined)).toEqual([false, true, false]) + expect(sent.map(({ ssrc }) => ssrc)).toEqual([ssrcs[3]]) + expect(sent.map(packet => openSFrameReference({ + ciphertext: ciphertextOf([packet]), + sessionKey: key, + ssrc: ssrcs[3], + suite: 8, + tagLength: 4, + }))).toEqual([ + Buffer.alloc(60, 2), + ]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('places the best tier\'s picture and a sound written a fragment after it on one run, at their presentation times\' distance, each at its own ' + + 'rate', async () => { + const { delegate, end, offerRequest, peer, sent, ssrcs, table } = await sending() + + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + peer.connectionStateChange.execute('connected') + await settle() + + const { clock } = table.videoTiers.get(1)!.context + const stream = delegate.tierDemandStarted.mock.calls.find(([started]) => started.tier.id === 1)![0] + const timestamps = (ssrc: number): number[] => sent.filter(packet => packet.ssrc === ssrc).map(({ packet }) => packet.header.timestamp) + const moment = performance.now() + + // A fragment of a keyframe alone decoded at 1 s, and half a second later a fragment of the next picture and a sound presented at 1.02 s. + const now = vi.spyOn(performance, 'now').mockReturnValue(moment) + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(withParameterSets(picture(300, 1)), true), + ], + pictureTime: 90000n, + })) + await vi.advanceTimersByTimeAsync(0) + now.mockReturnValue(moment + 500) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(picture(300, 2)), + ], + pictureTime: 93000n, + sound: [ + soundSample(Buffer.alloc(60, 3)), + ], + soundTime: 48960n, + })) + await vi.advanceTimersByTimeAsync(0) + now.mockRestore() + + // The run opened at the first picture's arrival: the sound stands 20 ms of its own ticks after that moment, not at its own arrival. + expect([ + timestamps(ssrcs[0]), + timestamps(ssrcs[3]), + ]).toEqual([ + [ + clock.timestamp('video', moment), + clock.timestamp('video', moment) + 3000, + ].map(timestamp => timestamp >>> 0), + [ + (clock.timestamp('audio', moment) + 960) >>> 0, + ], + ]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('sends a view from away no sound while the camera\'s Microphone is muted and its picture all the while, and unmuted the next sound at the timestamp ' + + 'the clock gives it, unmarked, as if none were withheld', async () => { + const { delegate, end, offerRequest, peer, sent, ssrcs, table } = await sending() + + // The row reads the steady clock through its own spies: the mock clock runs the pacer's timer alone. + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + peer.connectionStateChange.execute('connected') + await settle() + + const { clock } = table.videoTiers.get(1)!.context + const stream = streamOf(delegate, 1) + const headers = (ssrc: number): { marker: boolean, timestamp: number }[] => sent.filter(packet => packet.ssrc === ssrc) + .map(({ packet: { header: { marker, timestamp } } }) => ({ marker, timestamp })) + const moment = performance.now() + + table.muteMicrophone(true) + + // A fragment of a keyframe decoded at 1 s with sounds presented with it and 20 ms after it opens the run, the run's first sound among those the mute + // holds back, and once the mute is off a fragment of the next picture and a sound presented at 1.04 s. + const now = vi.spyOn(performance, 'now').mockReturnValue(moment) + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(withParameterSets(picture(300, 1)), true), + ], + pictureTime: 90000n, + sound: [ + soundSample(Buffer.alloc(60, 1)), + soundSample(Buffer.alloc(60, 2)), + ], + soundTime: 48000n, + })) + await vi.advanceTimersByTimeAsync(0) + now.mockReturnValue(moment + 500) + await vi.advanceTimersByTimeAsync(20) + + expect([ + headers(ssrcs[0]).length, + headers(ssrcs[3]), + ]).toEqual([1, []]) + + table.muteMicrophone(false) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(picture(300, 2)), + ], + pictureTime: 93000n, + sound: [ + soundSample(Buffer.alloc(60, 3)), + ], + soundTime: 49920n, + })) + // The sound falls due by its own decode time, 7 ms after the fragment's picture. + now.mockReturnValue(moment + 510) + await vi.advanceTimersByTimeAsync(10) + now.mockRestore() + + // The sound sent is the one written once the mute was off, 40 ms of its own ticks after the moment the run opened at, and it carries no marker, since + // the run's first sound was placed as the mute held it back. + expect([ + headers(ssrcs[0]).length, + headers(ssrcs[3]), + ]).toEqual([ + 2, + [ + { + marker: false, + timestamp: (clock.timestamp('audio', moment) + 1920) >>> 0, + }, + ], + ]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('hands a view the picture and the sound the plugin writes inside the best tier\'s start, in a turn after every join of the view', async () => { + const { delegate, end, offer, offerRequest, peer, sent, ssrcs } = await sending() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + + const key = Buffer.from(offer.sframeConfiguration?.key ?? Buffer.alloc(0)) + + // The view's picture join raises the best tier's demand before its sound join, and the plugin writes inside that start. + delegate.tierDemandStarted.mockImplementation(async (stream) => { + if (stream.tier.id === 1) { + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + pictureSample(withParameterSets(picture(300, 1)), true), + ], + sound: [ + soundSample(Buffer.alloc(60, 2)), + ], + })) + } + }) + peer.connectionStateChange.execute('connected') + + expect(sent).toEqual([]) + + await settle() + await vi.advanceTimersByTimeAsync(0) + + expect(sent.filter(({ ssrc }) => ssrc === ssrcs[0]).length).toBeGreaterThan(0) + expect(sent.filter(({ ssrc }) => ssrc === ssrcs[3]).map(packet => openSFrameReference({ + ciphertext: ciphertextOf([packet]), + sessionKey: key, + ssrc: ssrcs[3], + suite: 8, + tagLength: 4, + }))).toEqual([ + Buffer.alloc(60, 2), + ]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('sends an audio frame as one payload behind 0xC0, marked when it opens a run', async () => { + const { delegate, end, offer, offerRequest, peer, sent, ssrcs } = await sending() + const key = Buffer.from(offer.sframeConfiguration?.key ?? Buffer.alloc(0)) + const frames = [ + Buffer.alloc(60, 7), + Buffer.alloc(80, 8), + ] + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + peer.connectionStateChange.execute('connected') + await settle() + + const stream = streamOf(delegate, 1) + + writeTierFrame(stream, 'audio', { data: frames[0], time: 0 }) + writeTierFrame(stream, 'audio', { data: frames[1], time: 20000 }) + await vi.advanceTimersByTimeAsync(0) + + const packets = sent.filter(({ ssrc }) => ssrc === ssrcs[3]) + + expect(packets.map(({ packet }) => packet.header.marker)).toEqual([true, false]) + expect(packets.map(({ sentPayload }) => sentPayload[0])).toEqual([0xC0, 0xC0]) + expect(packets.map(({ packet }) => packet.header.payloadType)).toEqual([110, 110]) + expect(packets.map(packet => openSFrameReference({ + ciphertext: ciphertextOf([packet]), + sessionKey: key, + ssrc: ssrcs[3], + suite: 8, + tagLength: 4, + }))).toEqual(frames) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('sends a stream\'s first packet at the sequence number its draw answered and each packet after it one more, wrapping to 0', async () => { + // Every stream of the session draws the range's last sequence number, and the second packet of each stream wraps. + const draw = vi.mocked(firstSequence).mockReturnValue(SEQUENCE_RANGE - 1) + + onTestFinished(() => { + draw.mockReset() + }) + + const { delegate, end, offerRequest, peer, sent, ssrcs } = await sending() + const sequences = (ssrc: number): number[] => sent.filter(packet => packet.ssrc === ssrc).map(({ packet }) => packet.header.sequenceNumber) + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + peer.connectionStateChange.execute('connected') + await settle() + + const stream = streamOf(delegate, 1) + + writeTierFrame(stream, 'video', { + data: withParameterSets(picture(2000, 1)), + keyframe: true, + time: 0, + }) + writeTierFrame(stream, 'audio', { + data: Buffer.alloc(60, 2), + time: 0, + }) + writeTierFrame(stream, 'audio', { + data: Buffer.alloc(60, 3), + time: 20000, + }) + await vi.advanceTimersByTimeAsync(20) + + expect(sequences(ssrcs[0])).toEqual([SEQUENCE_RANGE - 1, 0]) + expect(sequences(ssrcs[3])).toEqual([SEQUENCE_RANGE - 1, 0]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('runs each stream\'s count from zero across a keyframe request and a discontinuity', async () => { + const { delegate, end, offerRequest, peer, sent, ssrcs } = await sending() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + peer.connectionStateChange.execute('connected') + await settle() + + const stream = streamOf(delegate, 2) + + writeTierFrame(stream, 'video', { + data: withParameterSets(picture(100, 1)), + keyframe: true, + time: 0, + }) + await vi.advanceTimersByTimeAsync(0) + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + writeTierFrame(stream, 'video', { + data: picture(100, 2), + time: 33333, + }) + await vi.advanceTimersByTimeAsync(34) + writeTierFrame(stream, 'video', { + data: withParameterSets(picture(100, 3)), + keyframe: true, + time: 5000000, + discontinuity: true, + }) + await vi.advanceTimersByTimeAsync(0) + writeTierFrame(stream, 'video', { + data: picture(100, 4), + time: 5033333, + }) + await vi.advanceTimersByTimeAsync(34) + + // The request finds the stream's keyframe released and opens the stream again from it. The stream seals that keyframe a second time, its count + // running on across the answer and the discontinuity. + expect(sent.filter(({ ssrc }) => ssrc === ssrcs[1]).map(packet => counterOf(ciphertextOf([packet])))).toEqual([0n, 1n, 2n, 3n, 4n]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('opens the picture stream of the one tier whose sender reports a lost picture again from its latest keyframe released, each frame sealed at the ' + + 'stream\'s next count, while another tier\'s stream takes the live releases alone, and nothing after the session\'s end', + async () => { + const { delegate, end, offerRequest, peer, sent, ssrcs } = await sending() + const take = vi.spyOn(EngineStream.prototype, 'take') + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(0) + + // Tiers 1 and 2 each release a keyframe and a picture after it, every frame one packet, and after tier 2's sender reports a lost picture, a picture + // written to each moves the live edge. + const write = (time: number, keyframe = false): void => { + for (const tierId of [1, 2]) { + writeTierFrame(streamOf(delegate, tierId), 'video', { + data: picture(100, tierId), + keyframe, + time, + }) + } + } + + write(0, true) + write(33333) + await vi.advanceTimersByTimeAsync(50) + + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + write(66667) + await vi.advanceTimersByTimeAsync(50) + + const live = handed(take, 1) + const answered = handed(take, 2) + + expect(live.map(({ time }) => time)).toEqual([0, 33, 67]) + expect(answered).toEqual([ + ...answered.slice(0, 2), + ...[0, 100 / 3, 200 / 3].map(distance => ({ + time: Math.round(distance), + timestamp: openingStamp(answered[1].timestamp, distance), + })), + ]) + expect(sent.filter(({ ssrc }) => ssrc === ssrcs[1]).map(packet => counterOf(ciphertextOf([packet])))).toEqual([0n, 1n, 2n, 3n, 4n]) + + vi.useRealTimers() + await end(offerRequest) + + // After the session's end a report on the sender reaches nothing. + const taken = take.mock.calls.length + + expect(() => peer.getSenders()[1].onKeyFrameRequest.execute('pli')).not.toThrow() + expect(take.mock.calls.length).toBe(taken) + }) + + it('writes one debug line for each of a picture stream\'s keyframe requests, naming the session, its video tier and what the request came to', + async () => { + const { delegate, end, offerRequest, peer } = await sending() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(0) + + const lines = captureDebug() + + // Tier 2's sender reports a lost picture before its stream writes a keyframe, and twice once the keyframe is released. + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + writeTierFrame(streamOf(delegate, 2), 'video', { + data: picture(100, 2), + keyframe: true, + time: 0, + }) + await vi.advanceTimersByTimeAsync(50) + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + + expect(lines.filter(line => line.includes('takes a keyframe request'))).toEqual([ + 'no keyframe kept', + 'answered', + 'answered from this keyframe already', + ].map(outcome => `WebRTC session ${offerRequest.sessionIdentifier} takes a keyframe request on video tier 2: ${outcome}.`)) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('answers a picture stream level after its join\'s opening at its first request, passes by a second that finds the keyframe it was answered from, ' + + 'and answers a request after the next keyframe\'s release and one after a restart\'s keyframe from each', async () => { + const { delegate, end, offerRequest, peer, table } = await sending() + const take = vi.spyOn(EngineStream.prototype, 'take') + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + // The library holds tier 2, whose stream releases a keyframe and a picture before the session connects. The session's picture stream of tier 2 + // joins with an opening from that keyframe. Each frame written falls due as it arrives. + table.hold(table.videoTiers.get(2)!, rowHolder()) + await vi.advanceTimersByTimeAsync(0) + + const stream = streamOf(delegate, 2) + let seed = 0 + let read = 0 + const write = async (time: number, { discontinuity = false, keyframe = false } = {}): Promise => { + writeTierFrame(stream, 'video', { + data: picture(100, ++seed), + discontinuity, + keyframe, + time, + }) + await vi.advanceTimersByTimeAsync(40) + } + // The frames the stream was handed since the last reading. + const since = (): number => { + const count = handed(take, 2).length - read + + read += count + + return count + } + // A viewer's request, and the turn a millisecond after it that takes its opening's start. + const request = async (): Promise => { + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + await vi.advanceTimersByTimeAsync(1) + } + + await write(0, { keyframe: true }) + await write(33333) + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(1) + await write(66667) + + const steps = [ + since(), + ] + + await request() + await write(100000) + steps.push(since()) + await request() + await write(133333) + steps.push(since()) + await write(166667, { keyframe: true }) + steps.push(since()) + await request() + await write(200000) + steps.push(since()) + await write(5000000, { discontinuity: true, keyframe: true }) + steps.push(since()) + await request() + await write(5033333) + steps.push(since()) + + // The join's opening, the first answer's stretch, a request passed by, the next keyframe live, its answer, the restart's keyframe live and its answer. + expect(steps).toEqual([3, 4, 1, 1, 2, 1, 2]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('answers a request where the buffer keeps a keyframe released and a newer one not yet released from the released one', async () => { + const { delegate, end, offerRequest, peer, table } = await sending() + const take = vi.spyOn(EngineStream.prototype, 'take') + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + table.videoTiers.get(2)!.buffer.span = 5000 + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(0) + + const stream = streamOf(delegate, 2) + + // A keyframe and a picture released, and a keyframe timed a second ahead of its arrival, which the buffer keeps beside them while the pacer holds it. + writeTierFrame(stream, 'video', { + data: picture(100, 1), + keyframe: true, + time: 0, + }) + writeTierFrame(stream, 'video', { + data: picture(100, 2), + time: 33333, + }) + await vi.advanceTimersByTimeAsync(50) + writeTierFrame(stream, 'video', { + data: picture(100, 3), + keyframe: true, + time: 1000000, + }) + await vi.advanceTimersByTimeAsync(10) + + const before = handed(take, 2).length + + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + await vi.advanceTimersByTimeAsync(1100) + + expect(handed(take, 2).slice(before).map(({ time }) => time)).toEqual([0, 33, 1000]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('counts the keyframe an answer\'s opening carries on to as the one its stream was answered from, passing by a request once level that finds it', + async () => { + const { delegate, end, offerRequest, peer, table } = await sending() + const take = vi.spyOn(EngineStream.prototype, 'take') + // The timestamp each picture of tier 2 was placed at, by its time in milliseconds, which a frame consumer of the live releases is handed. + const placed = new Map() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(0) + table.joinFrames(table.videoTiers.get(2)!, 'video', rowHolder(), { + take: (frame, timestamp) => placed.set(Math.round(frame.time / 1000), timestamp), + }) + + const stream = streamOf(delegate, 2) + let seed = 0 + const write = async (time: number, keyframe = false): Promise => { + writeTierFrame(stream, 'video', { + data: picture(100, ++seed), + keyframe, + time, + }) + await vi.advanceTimersByTimeAsync(40) + } + // A viewer's request, and the turn a millisecond after it that takes its opening's start. + const request = async (): Promise => { + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + await vi.advanceTimersByTimeAsync(1) + } + + await write(0, true) + await write(33333) + + // An answer's opening from the first keyframe, which a keyframe falling due as it arrives lets go of: the opening carries on from it, and a picture + // written after it moves the live edge past the keyframe and itself. + const answered = handed(take, 2).length + + await request() + await write(66667, true) + await write(100000) + + const passed = handed(take, 2).length + + await request() + await write(133333) + + // The answer's opening hands the keyframe it carried on to and the picture after it on the opening's own timestamps, and the request that finds that + // keyframe leaves the stream the live release alone, at its placement. + expect([ + handed(take, 2).slice(answered, passed), + handed(take, 2).slice(passed), + ]).toEqual([ + [0, 100 / 3].map(distance => ({ + time: Math.round(200 / 3 + distance), + timestamp: openingStamp(placed.get(67)!, distance), + })), + [ + { + time: 133, + timestamp: placed.get(133), + }, + ], + ]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('counts nothing for a join\'s opening that carries on to a newer keyframe, and a request once level that finds that keyframe is answered', async () => { + const { delegate, end, offerRequest, peer, table } = await sending() + const take = vi.spyOn(EngineStream.prototype, 'take') + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + table.hold(table.videoTiers.get(2)!, rowHolder()) + await vi.advanceTimersByTimeAsync(0) + + const stream = streamOf(delegate, 2) + let seed = 0 + const write = async (time: number, keyframe = false): Promise => { + writeTierFrame(stream, 'video', { + data: picture(100, ++seed), + keyframe, + time, + }) + await vi.advanceTimersByTimeAsync(40) + } + + // The session's picture stream of tier 2 joins with an opening from the keyframe the library's hold released, which a keyframe falling due as it + // arrives lets go of: the join's opening carries on from it, and a picture written after it moves the live edge past the keyframe and itself. + await write(0, true) + await write(33333) + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(1) + await write(66667, true) + await write(100000) + + const level = handed(take, 2).length + + // A request once level, and the turn a millisecond after it that takes its opening's start. + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + await vi.advanceTimersByTimeAsync(1) + await write(133333) + + expect([ + handed(take, 2).slice(0, level).map(({ time }) => time), + handed(take, 2).slice(level).map(({ time }) => time), + ]).toEqual([ + [67, 100], + [67, 100, 133], + ]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('answers a request made between a keyframe\'s due moment and the turn that releases it, on a demand that has placed no picture, on finite timestamps ' + + 'from one millisecond past that keyframe\'s own', async () => { + const { delegate, end, offerRequest, peer, table } = await sending() + const take = vi.spyOn(EngineStream.prototype, 'take') + const placed: number[] = [] + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(0) + table.joinFrames(table.videoTiers.get(2)!, 'video', rowHolder(), { + take: (_frame, timestamp) => placed.push(timestamp), + }) + + const stream = streamOf(delegate, 2) + + // The keyframe falls due as it is written, and the request comes before the pacer's turn releases it. + writeTierFrame(stream, 'video', { + data: picture(100, 1), + keyframe: true, + time: 0, + }) + peer.getSenders()[1].onKeyFrameRequest.execute('pli') + await vi.advanceTimersByTimeAsync(10) + writeTierFrame(stream, 'video', { + data: picture(100, 2), + time: 33333, + }) + await vi.advanceTimersByTimeAsync(50) + + const answered = handed(take, 2) + + expect(answered.every(({ timestamp }) => Number.isFinite(timestamp))).toBe(true) + expect(answered).toEqual([0, 100 / 3].map(distance => ({ + time: Math.round(distance), + timestamp: openingStamp(placed[0], distance), + }))) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('ends a session once with one warning, the engine\'s, naming the first tier found refused', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { delegate, ends, offerRequest, peer } = await sending() + + delegate.tierDemandStarted.mockImplementation(async ({ tier }) => { + if (tier.id > 1) { + throw new Error('The plugin refused the tier.') + } + }) + peer.connectionStateChange.execute('connected') + await settle() + await settle() + + expect(ends).toHaveBeenCalledExactlyOnceWith(SENSOR_UUID, offerRequest.sessionIdentifier) + expect(warn).toHaveBeenCalledExactlyOnceWith( + `The video tier 2 of the video sensor "${SENSOR_UUID}" refused WebRTC session ${offerRequest.sessionIdentifier}. The session ends.`, + ) + }) + + it('ends a session whose join waits past its bound once with one warning, the table\'s withdrawal', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, ends, offerRequest, peer, table } = await sending() + + delegate.tierDemandStarted.mockImplementation(async ({ tier }) => tier.id === 3 + ? new Promise(() => undefined) + : undefined) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(DELEGATE_CALL_TIMEOUT - 1) + + expect(ends).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + + expect(ends).toHaveBeenCalledExactlyOnceWith(SENSOR_UUID, offerRequest.sessionIdentifier) + expect(warn).toHaveBeenCalledExactlyOnceWith('MultiTierStreamingDelegate did not settle tierDemandStarted for the video tier 3 of the video sensor ' + + `"${SENSOR_UUID}" within 30 seconds: the demand is withdrawn and every join waiting on it is refused.`) + expect(table.videoTiers.get(3)?.demand).toBeUndefined() + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT) + vi.useRealTimers() + }) + + it('ends a view from away at 30 seconds from the start\'s call whose join at 20 seconds takes back a pending demand a library hold left at 10 seconds, ' + + 'with the demand\'s one warning, none of the engine\'s own and its debug line', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const lines = captureDebug() + const { delegate, ends, offerRequest, peer, table } = await sending() + + delegate.tierDemandStarted.mockImplementation(async ({ tier }) => tier.id === 3 + ? new Promise(() => undefined) + : undefined) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + // The library holds tier 3, whose start never settles, and leaves it at 10 seconds. The session's join at 20 seconds takes the demand back. + const held = table.hold(table.videoTiers.get(3)!, rowHolder()) + + await vi.advanceTimersByTimeAsync(10000) + held.release() + await vi.advanceTimersByTimeAsync(10000) + peer.connectionStateChange.execute('connected') + await vi.advanceTimersByTimeAsync(9999) + + expect([ends.mock.calls.length, warn.mock.calls.length]).toEqual([0, 0]) + + await vi.advanceTimersByTimeAsync(1) + + expect(ends).toHaveBeenCalledExactlyOnceWith(SENSOR_UUID, offerRequest.sessionIdentifier) + expect(warn).toHaveBeenCalledExactlyOnceWith('MultiTierStreamingDelegate did not settle tierDemandStarted for the video tier 3 of the video sensor ' + + `"${SENSOR_UUID}" within 30 seconds: the demand is withdrawn and every join waiting on it is refused.`) + expect(lines.filter(line => line.includes('not started within its bound'))).toEqual([ + expect.stringContaining(`WebRTC session ${offerRequest.sessionIdentifier} ends, a demand it joined not started within its bound.`), + ]) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT) + vi.useRealTimers() + }) + + it('ends a session once under the table\'s one warning when a tier it joined fails', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, ends, offerRequest, peer } = await sending() + + peer.connectionStateChange.execute('connected') + await settle() + streamOf(delegate, 2).fail('a synthetic failure') + await settle() + + expect(ends).toHaveBeenCalledExactlyOnceWith(SENSOR_UUID, offerRequest.sessionIdentifier) + expect(warn).toHaveBeenCalledExactlyOnceWith(`The plugin failed the stream of the video tier 2 of the video sensor "${SENSOR_UUID}" (a synthetic failure), ` + + 'and every session on the tier ends.') + }) + + it('joins no further tier and leaves none held for a session that plugin code ends inside a join', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { delegate, ends, peer, table } = await sending() + + delegate.tierDemandStarted.mockImplementation((stream) => { + if (stream.tier.id === 2) { + stream.fail('a failure inside the start') + } + }) + peer.connectionStateChange.execute('connected') + await settle() + await settle() + + expect(ends).toHaveBeenCalledOnce() + expect(delegate.tierDemandStarted.mock.calls.map(([stream]) => stream.tier.id)).toEqual([1, 2]) + expect([ + ...table.videoTiers.values(), + ].map(({ demand }) => demand?.statistics().consumers ?? 0)).toEqual([0, 0, 0]) + }) + + it('counts a send whose promise rejects, throwing nothing and stopping nothing', async () => { + const lines = captureDebug() + const { delegate, end, offerRequest, peer, sent, ssrcs } = await sending() + const sender = peer.getSenders()[0] + + vi.mocked(sender.sendRtp).mockRejectedValueOnce(new Error('The send failed.')) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + peer.connectionStateChange.execute('connected') + await settle() + expect(() => writeTierFrame(streamOf(delegate, 1), 'video', { + data: withParameterSets(picture(3000, 5)), + keyframe: true, + time: 0, + })).not.toThrow() + await vi.advanceTimersByTimeAsync(0) + await settle() + + expect(sender.sendRtp).toHaveBeenCalledTimes(3) + expect(sent.filter(({ ssrc }) => ssrc === ssrcs[0])).toHaveLength(2) + + vi.useRealTimers() + await end(offerRequest) + + expect(lines).toContainEqual(expect.stringContaining(`WebRTC session ${offerRequest.sessionIdentifier} sealed 1 frame and handed werift 3 packets, 1 of ` + + 'whose sends werift rejected.')) + }) + + it('logs the throw of a keyframe request\'s work and throws nothing into werift', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { end, offerRequest, peer } = await sending() + + peer.connectionStateChange.execute('connected') + await settle() + vi.spyOn(TierHold.prototype, 'answerKeyframeRequest').mockImplementation(() => { + throw new Error('The hold failed.') + }) + + expect(() => peer.getSenders()[0].onKeyFrameRequest.execute('pli')).not.toThrow() + expect(error).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('The WebRTC engine failed to handle a keyframe request for WebRTC session ' + + `${offerRequest.sessionIdentifier}: Error: The hold failed.`)) + + await end(offerRequest) + }) + + it('logs once a wait on the tiers a session joined that fails, with the thrown value, and throws nothing into werift', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { end, offerRequest, peer } = await sending() + + // The wait reads which joins wait on their start as it begins, and that read throws. + vi.spyOn(TierHold.prototype, 'waiting', 'get').mockImplementationOnce(() => { + throw new Error('The tiers could not be read.') + }) + + expect(() => peer.connectionStateChange.execute('connected')).not.toThrow() + await settle() + + expect(error).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('The WebRTC engine failed to wait on the tiers of WebRTC session ' + + `${offerRequest.sessionIdentifier}: Error: The tiers could not be read.`)) + + await end(offerRequest) + }) + + it('hands each packet a payload buffer of its own, shared with no other packet and unchanged after its send', async () => { + const { delegate, end, offerRequest, peer, sent } = await sending() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + peer.connectionStateChange.execute('connected') + await settle() + + for (const [tierId, length] of [ + [1, 3000], + [2, 2500], + [3, 900], + ]) { + writeTierFrame(streamOf(delegate, tierId), 'video', { + data: withParameterSets(picture(length, tierId)), + keyframe: true, + time: 0, + }) + } + + writeTierFrame(streamOf(delegate, 1), 'audio', { + data: Buffer.alloc(60, 9), + time: 0, + }) + await vi.advanceTimersByTimeAsync(0) + + const payloads = sent.map(({ packet }) => packet.payload) + const overlapping = payloads.some((payload, index) => payloads.slice(index + 1).some(other => (other.buffer === payload.buffer) + && (other.byteOffset < payload.byteOffset + payload.length) && (payload.byteOffset < other.byteOffset + other.length))) + + expect(payloads.length).toBeGreaterThan(4) + expect(overlapping).toBe(false) + expect(sent.every(({ packet, sentPayload }) => packet.payload.equals(sentPayload))).toBe(true) + + vi.useRealTimers() + await end(offerRequest) + }) + }) + + describe('reoffer and keys', () => { + it('leaves the key and every count running across a Reoffer, answering its text and no key', async () => { + const { delegate, end, engine, offer, offerRequest, peer, sent, ssrcs } = await sending() + const key = offer.sframeConfiguration?.key ?? Buffer.alloc(0) + const keyCopy = Buffer.from(key) + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + peer.connectionStateChange.execute('connected') + await settle() + + const stream = streamOf(delegate, 1) + + writeTierFrame(stream, 'video', { + data: withParameterSets(picture(100, 1)), + keyframe: true, + time: 0, + }) + await vi.advanceTimersByTimeAsync(0) + await reofferSteps(peer) + await expect(engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: true }, + })).resolves.toStrictEqual({ + sdpAnswer: REOFFER_ANSWER_SDP, + }) + writeTierFrame(stream, 'video', { + data: picture(100, 2), + time: 33333, + }) + await vi.advanceTimersByTimeAsync(34) + + expect(sent.filter(({ ssrc }) => ssrc === ssrcs[0]).map(packet => counterOf(ciphertextOf([packet])))).toEqual([0n, 1n]) + expect(key.equals(keyCopy)).toBe(true) + expect(deriveStreamKeys).toHaveBeenCalledTimes(4) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('rejects a Reoffer whose remote offer werift refuses, the connection stable and no rollback sent', async () => { + const { end, engine, offerRequest, peer } = await sending() + const steps = await reofferSteps(peer) + const failure = new Error('werift refused the offer.') + + steps.apply.mockRejectedValueOnce(failure) + + const rejection = await engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }) + .then(() => undefined, (error: unknown) => error as Error) + + await settle() + + expect(rejection?.message).toBe(`WebRTC session ${offerRequest.sessionIdentifier} failed at the reoffer's apply, and its reoffer fails.`) + expect(rejection?.cause).toBe(failure) + expect(steps.remote.mock.calls.map(([description]) => description.type)).toEqual(['offer']) + expect(peer.signalingState).toBe('stable') + + await end(offerRequest) + }) + + it('rolls back a Reoffer that fails at werift\'s answer and answers a later one, streaming throughout', async () => { + const { delegate, end, engine, offerRequest, peer, sent, ssrcs } = await sending() + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + peer.connectionStateChange.execute('connected') + await settle() + + const stream = streamOf(delegate, 1) + const steps = await reofferSteps(peer) + + steps.answer.mockRejectedValueOnce(new Error('werift failed to answer.')) + writeTierFrame(stream, 'video', { + data: withParameterSets(picture(100, 1)), + keyframe: true, + time: 0, + }) + await vi.advanceTimersByTimeAsync(0) + await expect(engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + })).rejects.toThrow( + `WebRTC session ${offerRequest.sessionIdentifier} failed at werift's answer, and its reoffer fails.`, + ) + await settle() + + expect(steps.rollbacks).toBe(1) + expect(peer.signalingState).toBe('stable') + + writeTierFrame(stream, 'video', { + data: picture(100, 2), + time: 33333, + }) + await vi.advanceTimersByTimeAsync(34) + await expect(engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + })).resolves.toStrictEqual({ + sdpAnswer: REOFFER_ANSWER_SDP, + }) + writeTierFrame(stream, 'video', { + data: picture(100, 3), + time: 66667, + }) + await vi.advanceTimersByTimeAsync(34) + + expect(sent.filter(({ ssrc }) => ssrc === ssrcs[0]).map(packet => counterOf(ciphertextOf([packet])))).toEqual([0n, 1n, 2n]) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('rejects a Reoffer whose answer\'s apply fails with that failure as its cause, rolling its offer back', async () => { + const { end, engine, offerRequest, peer } = await sending() + const failure = new Error('werift failed to apply the answer.') + const steps = await reofferSteps(peer) + + steps.local.mockRejectedValueOnce(failure) + + const rejection = await engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }).then(() => undefined, (error: unknown) => error as Error) + + await settle() + + expect(rejection?.message).toBe(`WebRTC session ${offerRequest.sessionIdentifier} failed at the reoffer answer's apply, and its reoffer fails.`) + expect(rejection?.cause).toBe(failure) + expect(steps.rollbacks).toBe(1) + expect(peer.signalingState).toBe('stable') + + await end(offerRequest) + }) + + it('cuts a Reoffer at 2 seconds before its answer\'s apply begins, rolling its offer back once werift\'s answer settles', async () => { + const { end, engine, offerRequest, peer } = await sending() + const steps = await reofferSteps(peer) + const held = deferred() + + steps.answer.mockImplementationOnce(async () => held.promise) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + const reoffering = engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }) + + void reoffering.catch(() => undefined) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT) + await expect(reoffering).rejects.toThrow(`The reoffer of WebRTC session ${offerRequest.sessionIdentifier} was cut at werift's answer by its budget of 2 seconds.`) + held.resolve() + await vi.advanceTimersByTimeAsync(0) + + expect(steps.rollbacks).toBe(1) + expect(steps.local).not.toHaveBeenCalled() + expect(peer.signalingState).toBe('stable') + + vi.useRealTimers() + await end(offerRequest) + }) + + it('rolls back a Reoffer cut while its remote offer\'s apply is pending once that apply settles, and takes the refusal of one it never applied', async () => { + const unhandled = vi.fn() + const { end, engine, offerRequest, peer } = await sending() + const steps = await reofferSteps(peer) + const applying = deferred() + const refusing = deferred() + + process.on('unhandledRejection', unhandled) + onTestFinished(() => { + process.off('unhandledRejection', unhandled) + }) + steps.apply.mockImplementationOnce(async () => applying.promise).mockImplementationOnce(async () => refusing.promise) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + // The first held apply then applies, and its rollback, queued behind it, takes it back; the second is then refused, and its rollback is refused too. + for (const [settleHeld, taken] of [ + [ + () => applying.resolve(), + 1, + ], + [ + () => refusing.reject(new Error('werift refused the offer.')), + 0, + ], + ] as const) { + const reoffering = engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }) + + void reoffering.catch(() => undefined) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT) + await expect(reoffering).rejects.toThrow( + `The reoffer of WebRTC session ${offerRequest.sessionIdentifier} was cut at the reoffer's apply by its budget of 2 seconds.`, + ) + + expect(steps.rollbacks).toBe(0) + + settleHeld() + await vi.advanceTimersByTimeAsync(0) + + expect(steps.rollbacks).toBe(taken) + expect(peer.signalingState).toBe('stable') + steps.rollbacks = 0 + } + + expect(steps.remote.mock.calls.map(([description]) => description.type)).toEqual([ + 'offer', + 'rollback', + 'offer', + 'rollback', + ]) + + vi.useRealTimers() + await settle() + + expect(unhandled).not.toHaveBeenCalled() + + await end(offerRequest) + }) + + it('awaits a Reoffer whose answer\'s apply has begun whole, past its budget', async () => { + const { end, engine, offerRequest, peer } = await sending() + const steps = await reofferSteps(peer) + const held = deferred() + let answered: unknown + + steps.local.mockImplementationOnce(async () => held.promise) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + const answering = engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }).then((answer) => { + answered = answer + }) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT * 2) + + expect(steps.local).toHaveBeenCalledOnce() + expect(answered).toBeUndefined() + + held.resolve() + await answering + + expect(answered).toStrictEqual({ sdpAnswer: REOFFER_ANSWER_SDP }) + expect(steps.rollbacks).toBe(0) + + vi.useRealTimers() + await end(offerRequest) + }) + + it('fails a Reoffer at once when its session ends during werift\'s answer, rolling nothing back', async () => { + const { end, engine, offerRequest, peer } = await sending() + const steps = await reofferSteps(peer) + const held = deferred() + + steps.answer.mockImplementationOnce(async () => held.promise) + + const reoffering = engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }) + + void reoffering.catch(() => undefined) + + await until(() => steps.answer.mock.calls.length > 0) + await end(offerRequest) + await expect(reoffering).rejects.toThrow(`WebRTC session ${offerRequest.sessionIdentifier} ended during werift's answer, and its reoffer fails.`) + held.resolve() + await settle() + + expect(steps.remote.mock.calls.map(([description]) => description.type)).toEqual(['offer']) + }) + + it('watches a DTLS transport an applied Reoffer adds, its close ending the session once', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { ends, engine, offerRequest, peer } = await sending() + // Another engine's offered session, whose transport stands for the one a Reoffer adds. + const other = await offered() + const added = other.peer.dtlsTransports[0] + const steps = await reofferSteps(peer) + + steps.local.mockImplementationOnce(async () => { + const listed = [...peer.dtlsTransports, added] + + Object.defineProperty(peer, 'dtlsTransports', { + configurable: true, + get: () => listed, + }) + }) + await engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }) + scriptTransport(added, 'closed') + await settle() + + expect(ends).toHaveBeenCalledExactlyOnceWith(SENSOR_UUID, offerRequest.sessionIdentifier) + expect(warn).toHaveBeenCalledExactlyOnceWith(`WebRTC session ${offerRequest.sessionIdentifier} had its DTLS transport closed. The session ends.`) + + await other.end(other.offerRequest) + }) + + it('holds each receive key by its key ID as the very buffer handed, zeroing one removed and one replaced, and keeps the key an update removes and adds ' + + 'under one ID, every key zeroed at the session\'s end', async () => { + const lines = captureDebug() + const { end, engine, offerRequest } = await sending() + const { sessionIdentifier } = offerRequest + const removed = Buffer.alloc(32, 0x5A) + const replaced = Buffer.alloc(32, 0x5B) + const replacing = Buffer.alloc(32, 0x5C) + const readded = Buffer.alloc(32, 0x5D) + + await expect(engine.updateReceiveKeys(sessionIdentifier, { + receiveKeysToAdd: [ + { key: removed, kid: 0x8001n }, + { key: replaced, kid: 0x8002n }, + ], + receiveKIDsToRemove: [], + }, detachedReporter())).resolves.toBeUndefined() + + expect(reaches(engine, [removed])).toBe(true) + expect(reaches(engine, [replaced])).toBe(true) + + await engine.updateReceiveKeys(sessionIdentifier, { + receiveKeysToAdd: [], + receiveKIDsToRemove: [ + { kid: 0x8001n }, + ], + }, detachedReporter()) + + expect(zeroed(removed)).toBe(true) + expect(reaches(engine, [removed])).toBe(false) + + await engine.updateReceiveKeys(sessionIdentifier, { + receiveKeysToAdd: [ + { key: replacing, kid: 0x8002n }, + ], + receiveKIDsToRemove: [], + }, detachedReporter()) + + expect(zeroed(replaced)).toBe(true) + expect(reaches(engine, [replaced])).toBe(false) + expect(reaches(engine, [replacing])).toBe(true) + + await engine.updateReceiveKeys(sessionIdentifier, { + receiveKeysToAdd: [ + { key: readded, kid: 0x8002n }, + ], + receiveKIDsToRemove: [ + { kid: 0x8002n }, + ], + }, detachedReporter()) + + expect(zeroed(replacing)).toBe(true) + expect(readded.every(octet => octet === 0x5D)).toBe(true) + expect(reaches(engine, [readded])).toBe(true) + + await end(offerRequest) + + expect(zeroed(readded)).toBe(true) + expect(lines.filter(line => line.includes('receive key'))).toEqual([ + expect.stringContaining(`WebRTC session ${sessionIdentifier} adds 2 receive keys and zeroes 0, holding 2.`), + expect.stringContaining(`WebRTC session ${sessionIdentifier} adds 0 receive keys and zeroes 1, holding 1.`), + expect.stringContaining(`WebRTC session ${sessionIdentifier} adds 1 receive key and zeroes 1, holding 1.`), + expect.stringContaining(`WebRTC session ${sessionIdentifier} adds 1 receive key and zeroes 1, holding 1.`), + ]) + + for (const octet of [0x5A, 0x5B, 0x5C, 0x5D]) { + expect(lines.some(line => line.includes(Buffer.alloc(32, octet).toString('hex')))).toBe(false) + } + }) + + it('resolves an update with no key and no key ID, and zeroes at once and holds nothing of a key handed for a session it does not hold or one whose ' + + 'end has begun', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { ends, engine, offerRequest, peer } = await sending() + const { sessionIdentifier } = offerRequest + const unheld = Buffer.alloc(32, 0x11) + const ending = Buffer.alloc(32, 0x22) + + await expect(engine.updateReceiveKeys(sessionIdentifier, { receiveKeysToAdd: [], receiveKIDsToRemove: [] }, detachedReporter())).resolves.toBeUndefined() + await expect(engine.updateReceiveKeys(randomUUID(), { + receiveKeysToAdd: [ + { key: unheld, kid: 0x8001n }, + ], + receiveKIDsToRemove: [], + }, detachedReporter())).resolves.toBeUndefined() + + expect(zeroed(unheld)).toBe(true) + + // A route marks the session ending and calls the signaling class, held here. The engine still holds a session whose end has begun. + ends.mockImplementationOnce(async () => undefined) + peer.connectionStateChange.execute('failed') + + await expect(engine.updateReceiveKeys(sessionIdentifier, { + receiveKeysToAdd: [ + { key: ending, kid: 0x8002n }, + ], + receiveKIDsToRemove: [], + }, detachedReporter())).resolves.toBeUndefined() + + expect(ends).toHaveBeenCalledOnce() + expect(zeroed(ending)).toBe(true) + expect(reaches(engine, [unheld, ending])).toBe(false) + + await engine.endSession(sessionIdentifier, detachedReporter()) + }) + + it('zeroes every receive key held at a teardown in which another release throws', async () => { + const failure = new Error('A release failed.') + // The stack takes a sealer's disposal as the sealer is registered, which is why the spy stands before the offer that registers them. + const dispose = vi.spyOn(SFrameSealer.prototype, Symbol.dispose).mockImplementationOnce(() => { + throw failure + }) + const { engine, offerRequest } = await sending() + const { sessionIdentifier } = offerRequest + const keys = [ + Buffer.alloc(32, 0x31), + Buffer.alloc(32, 0x32), + ] + + await engine.updateReceiveKeys(sessionIdentifier, { + receiveKeysToAdd: keys.map((key, index) => ({ + key, + kid: BigInt(0x8001 + index), + })), + receiveKIDsToRemove: [], + }, detachedReporter()) + + await expect(engine.endSession(sessionIdentifier, detachedReporter())).rejects.toBe(failure) + + expect(dispose).toHaveBeenCalledTimes(4) + + expect(keys.map(zeroed)).toEqual([true, true]) + }) + }) + + describe('teardown', () => { + it.each([ + { state: 'an offer pending' }, + { state: 'offered' }, + { state: 'answered' }, + { state: 'connected' }, + { state: 'streaming' }, + ])('settles its teardown $state within its bound, leaving no connection, signal listener, join or subscriber', async ({ state }) => { + const prototype = await weriftPrototype() + const { delegate, end, engine, request, table } = signaling() + const offerRequest = request() + let made: Mock<() => void>[] = [] + let offering: Promise = Promise.resolve() + + if (state === 'an offer pending') { + const gather = vi.spyOn(prototype, 'setLocalDescription').mockImplementationOnce(async () => new Promise(() => undefined)) + + offering = engine.createOffer(offerRequest).catch(() => undefined) + await until(() => gather.mock.calls.length > 0) + } else { + await engine.createOffer(offerRequest) + made = subscriptions(peers[0]) + } + + if (['answered', 'connected', 'streaming'].includes(state)) { + await answered(engine, offerRequest) + } + + if (state === 'connected') { + delegate.tierDemandStarted.mockImplementation(async () => new Promise(() => undefined)) + } + + if (['connected', 'streaming'].includes(state)) { + peers[0].connectionStateChange.execute('connected') + await settle() + } + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + if (state === 'streaming') { + writeTierFrame(streamOf(delegate, 1), 'video', { + data: picture(100, 1), + time: 0, + }) + await vi.advanceTimersByTimeAsync(0) + } + + let settled = false + const teardown = end(offerRequest).then(() => { + settled = true + }) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT) + await teardown + await offering + + expect(settled).toBe(true) + expect(peers.map(peer => peer.connectionState)).toEqual(['closed']) + expect(getEventListeners(offerRequest.signal, 'abort')).toHaveLength(0) + expect([ + ...table.videoTiers.values(), + ].map(({ demand }) => demand?.statistics().consumers ?? 0)).toEqual([0, 0, 0]) + expect(made.length > 0).toBe(!['an offer pending', 'offered'].includes(state)) + expect(made.filter(unSubscribe => unSubscribe.mock.calls.length === 0)).toHaveLength(0) + + vi.useRealTimers() + }) + + it('releases every join before its connection closes, as a failed tier ends the session', async () => { + const prototype = await weriftPrototype() + const { delegate, peer, table } = await sending() + + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + peer.connectionStateChange.execute('connected') + await settle() + + const close = vi.spyOn(prototype, 'close').mockImplementation(async () => new Promise(() => undefined)) + + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + streamOf(delegate, 2).fail('a synthetic failure') + await settle() + + expect(close).toHaveBeenCalled() + expect([ + ...table.videoTiers.values(), + ].map(({ demand }) => demand?.statistics().consumers ?? 0)).toEqual([0, 0, 0]) + expect(disposalsOf(delegate)).toEqual([1, 1, 1]) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT) + vi.useRealTimers() + }) + + it('publishes the debug event of an end and of a key update that find no session through the reporter their caller hands, naming its camera', async () => { + const events = captureDebugEvents() + const { engine } = signaling() + // The caller's camera holds a context of its accessory's UUID alone, which is all a debug event reads of it. + const caller = new CameraReporter(() => ({ accessoryUUID: CALLER_ACCESSORY_UUID }) as ControllerAccessoryContext) + const sessionIdentifier = randomUUID() + + await engine.endSession(sessionIdentifier, caller) + await engine.updateReceiveKeys(sessionIdentifier, { + receiveKeysToAdd: [ + { + key: Buffer.alloc(16, 0x11), + kid: 1n, + }, + ], + receiveKIDsToRemove: [], + }, caller) + + expect(events).toStrictEqual([ + { + accessoryUUID: CALLER_ACCESSORY_UUID, + kind: 'end-unheld', + sentence: `WebRTC session ${sessionIdentifier} has ended already or was never held.`, + sessionIdentifier, + }, + { + accessoryUUID: CALLER_ACCESSORY_UUID, + keys: 1, + kind: 'keys-zeroed', + sentence: `WebRTC session ${sessionIdentifier} is handed 1 receive key while the engine holds no live store for it, and zeroes each.`, + sessionIdentifier, + }, + ]) + }) + + it('ends a session once for two calls and a later one, and resolves for an identifier it never held', async () => { + const dispose = vi.spyOn(SFrameSealer.prototype, Symbol.dispose) + const { engine, request } = signaling() + const offerRequest = request() + + await engine.createOffer(offerRequest) + await Promise.all([ + engine.endSession(offerRequest.sessionIdentifier, detachedReporter()), + engine.endSession(offerRequest.sessionIdentifier, detachedReporter()), + ]) + await engine.endSession(offerRequest.sessionIdentifier, detachedReporter()) + + expect(dispose).toHaveBeenCalledTimes(4) + expect(peers[0].connectionState).toBe('closed') + await expect(engine.endSession(randomUUID(), detachedReporter())).resolves.toBeUndefined() + }) + + it('zeroes the session key and every stream\'s secret, keys and salt at the teardown, read on the bytes', async () => { + const { end, engine, request } = signaling() + const offerRequest = request() + const offer = await engine.createOffer(offerRequest) + const key = offer.sframeConfiguration?.key ?? Buffer.alloc(0) + + expect(derivedKeys()).toHaveLength(4) + expect(zeroed(key)).toBe(false) + expect(derivedKeys().some(({ secret }) => zeroed(secret))).toBe(false) + + await end(offerRequest) + + expect(key).toHaveLength(32) + expect(zeroed(key)).toBe(true) + + for (const { authenticationKey, encryptionKey, salt, secret } of derivedKeys()) { + expect([ + secret, + encryptionKey, + authenticationKey, + salt, + ].map(zeroed)).toEqual([true, true, true, true]) + } + }) + + it('fails the offer of a session ended during it and zeroes its key through the one teardown', async () => { + const prototype = await weriftPrototype() + const gather = vi.spyOn(prototype, 'setLocalDescription').mockImplementation(async () => new Promise(() => undefined)) + const dispose = vi.spyOn(SFrameSealer.prototype, Symbol.dispose) + const { end, engine, request } = signaling() + const offerRequest = request() + const offer = engine.createOffer(offerRequest) + + void offer.catch(() => undefined) + + await until(() => gather.mock.calls.length > 0) + + const [{ sessionKey }] = vi.mocked(deriveStreamKeys).mock.calls[0] + + expect(zeroed(sessionKey)).toBe(false) + + await end(offerRequest) + await expect(offer).rejects.toThrow(`WebRTC session ${offerRequest.sessionIdentifier} ended during the gather`) + + expect(zeroed(sessionKey)).toBe(true) + expect(dispose).toHaveBeenCalledTimes(4) + expect(peers.map(peer => peer.connectionState)).toEqual(['closed']) + }) + + it('settles its teardown at the call budget when the connection\'s close never settles', async () => { + const prototype = await weriftPrototype() + const { end, engine, request } = signaling() + const offerRequest = request() + + await engine.createOffer(offerRequest) + + vi.spyOn(prototype, 'close').mockImplementation(async () => new Promise(() => undefined)) + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + fakeTimeoutSignals() + + let settled = false + const teardown = end(offerRequest).then(() => { + settled = true + }) + + await vi.advanceTimersByTimeAsync(CALL_TIMEOUT - 1) + + expect(settled).toBe(false) + + await vi.advanceTimersByTimeAsync(1) + await teardown + + expect(settled).toBe(true) + }) + }) + + describe('a viewer\'s voice', () => { + it('gives a session of a sensor whose delegate has no talkbackStarted no reader and no RTP subscriber', async () => { + const lines = captureDebug() + const { end, engine, offerRequest, peer } = await offered({ talkback: false }) + const made = peer.dtlsTransports.map(transport => subscriptionsOf([transport.onRtp])) + + await answered(engine, offerRequest) + await end(offerRequest) + + expect(made.flat()).toEqual([]) + expect(lines.some(line => /voice packets? and wrote/.test(line))).toBe(false) + }) + + it('subscribes the reader to each transport listed at the answer and each a Reoffer newly lists, and takes every subscription off at the teardown', async () => { + const { end, engine, offerRequest, peer } = await offered() + // Another engine's offered session, whose transport stands for the one a Reoffer adds. + const other = await offered() + const added = other.peer.dtlsTransports[0] + const listed = peer.dtlsTransports.map(transport => subscriptionsOf([transport.onRtp])) + const addedMade = subscriptionsOf([added.onRtp]) + + await answered(engine, offerRequest) + + expect(listed.map(made => made.length)).toEqual(peer.dtlsTransports.map(() => 1)) + + const steps = await reofferSteps(peer) + + steps.local.mockImplementationOnce(async () => { + const transports = [...peer.dtlsTransports, added] + + Object.defineProperty(peer, 'dtlsTransports', { + configurable: true, + get: () => transports, + }) + }) + await engine.reoffer(offerRequest.sessionIdentifier, { + sdpOffer: REOFFER_SDP, + options: { sframeEnabled: false }, + }) + + expect(addedMade).toHaveLength(1) + + await end(offerRequest) + + expect([ + ...listed.flat(), + ...addedMade, + ].map(unSubscribe => unSubscribe.mock.calls.length)).toEqual([ + ...listed.flat(), + ...addedMade, + ].map(() => 1)) + + await other.end(other.offerRequest) + }) + + it('hands a sealed voice packet a transport receives to a sink of its viewer\'s own, starting talkback once for each of two viewers, and ends each sink ' + + 'at the teardown', async () => { + const { delegate, end, engine, offerRequest, peer, table, talkbacks } = await sending() + const [transport] = peer.dtlsTransports + + await writeVoiceKey(engine, offerRequest.sessionIdentifier) + await writeVoiceKey(engine, offerRequest.sessionIdentifier, SECOND_VIEWER) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n)) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n, SECOND_VIEWER)) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n, SECOND_VIEWER)) + + expect(delegate.talkbackStarted?.mock.calls.map(([talker]) => talker.sensorUUID)).toEqual([ + table.sensorUUID, + table.sensorUUID, + ]) + expect(talkbacks.map(({ packets }) => packets.length)).toEqual([1, 2]) + expect(talkbacks.map(({ packets }) => packets[0].readUInt32BE(8))).toEqual([VOICE_SSRC, SECOND_VOICE_SSRC]) + + for (const packet of talkbacks.flatMap(({ packets }) => packets)) { + expect(packet[1] & 0x7F).toBe(STREAM_TIERS.audioStreamTiers.payloadType) + expect([ + ...packet.subarray(12), + ]).toEqual(VOICE_OPUS) + } + + await end(offerRequest) + + expect(talkbacks.map(({ release }) => release.mock.calls.length)).toEqual([1, 1]) + }) + + it('opens no viewer\'s voice packet while the camera\'s Speaker is muted, starting no sink and keeping a started one, and writes each once the Speaker is ' + + 'unmuted, those that arrived muted among them', async () => { + let muted = true + const lines = captureDebug() + const { delegate, end, engine, offerRequest, peer, talkback } = await sending({ + speakerMuted: () => muted, + }) + const [transport] = peer.dtlsTransports + + await writeVoiceKey(engine, offerRequest.sessionIdentifier) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n)) + + expect(delegate.talkbackStarted).not.toHaveBeenCalled() + + muted = false + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n)) + muted = true + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n)) + + expect(talkback.packets).toHaveLength(1) + expect(talkback.release).not.toHaveBeenCalled() + + muted = false + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n)) + + expect(delegate.talkbackStarted).toHaveBeenCalledOnce() + expect(talkback.packets.map(packet => [ + ...packet.subarray(12), + ])).toEqual([ + VOICE_OPUS, + VOICE_OPUS, + ]) + + await end(offerRequest) + + // The reader opened only the packets it read unmuted, and no muted packet moved its stream's counter. + expect(lines.filter(line => /voice packets? and wrote/.test(line)).map(line => line.split(' of them')[0])).toEqual([ + `WebRTC session ${offerRequest.sessionIdentifier} opened 2 voice packets and wrote 2`, + ]) + expect(talkback.release).toHaveBeenCalledOnce() + }) + + it('names a viewer\'s talkback in its lines by the viewer\'s key ID and its session, the second viewer\'s failed writes stated at the teardown', async () => { + const lines: string[] = [] + + vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { + lines.push(args.map(String).join(' ')) + }) + + const { end, engine, offerRequest, peer, talkbacks } = await sending() + const [transport] = peer.dtlsTransports + const firstFailure = expect.stringContaining('TalkbackSink failed to write a packet: Error: The sink failed to write.') + + await writeVoiceKey(engine, offerRequest.sessionIdentifier) + await writeVoiceKey(engine, offerRequest.sessionIdentifier, SECOND_VIEWER) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n)) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n, SECOND_VIEWER)) + talkbacks[1].sink.write.mockImplementation(() => { + throw new Error('The sink failed to write.') + }) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n, SECOND_VIEWER)) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 2n, SECOND_VIEWER)) + + expect(lines).toEqual([firstFailure]) + + await end(offerRequest) + + expect(lines).toEqual([ + firstFailure, + `TalkbackSink failed 1 more write before viewer ${SECOND_VOICE_KEY_ID} of WebRTC session ${offerRequest.sessionIdentifier} ended.`, + ]) + }) + + it('reads no longer as voice the second SSRC of a FID group an applied Reoffer names, a Reoffer that rejects changing nothing', async () => { + const { end, engine, offerRequest, peer, talkback } = await sending() + const steps = await reofferSteps(peer) + const reoffer = { + sdpOffer: [ + 'v=0', + 'm=audio 9 UDP/TLS/RTP/SAVPF 111 97', + `a=ssrc-group:FID ${VIEWER_SSRC} ${VOICE_SSRC}`, + '', + ].join('\r\n'), + options: { sframeEnabled: false }, + } + + await writeVoiceKey(engine, offerRequest.sessionIdentifier) + steps.apply.mockRejectedValueOnce(new Error('werift refuses the offer.')) + await expect(engine.reoffer(offerRequest.sessionIdentifier, reoffer)).rejects.toThrow() + peer.dtlsTransports[0].onRtp.execute(voicePacket(BETTER_VOICE.payloadType, 0n)) + + expect(talkback.packets).toHaveLength(1) + + await engine.reoffer(offerRequest.sessionIdentifier, reoffer) + peer.dtlsTransports[0].onRtp.execute(voicePacket(BETTER_VOICE.payloadType, 1n)) + + expect(talkback.packets).toHaveLength(1) + + await end(offerRequest) + }) + + it('ends a viewer\'s sink inside the update that removes its key, zeroing what the reader derived from it, and leaves the other viewer\'s sink', async () => { + const { delegate, end, engine, offerRequest, peer, talkbacks } = await sending() + const [transport] = peer.dtlsTransports + + await writeVoiceKey(engine, offerRequest.sessionIdentifier) + await writeVoiceKey(engine, offerRequest.sessionIdentifier, SECOND_VIEWER) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n)) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n, SECOND_VIEWER)) + + const derived = derivedKeys().filter((_, index) => vi.mocked(deriveStreamKeys).mock.calls[index][0].ssrc === VOICE_SSRC) + + await engine.updateReceiveKeys(offerRequest.sessionIdentifier, { + receiveKeysToAdd: [], + receiveKIDsToRemove: [ + { kid: VOICE_KEY_ID }, + ], + }, detachedReporter()) + + expect(talkbacks.map(({ release }) => release.mock.calls.length)).toEqual([1, 0]) + + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n)) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n, SECOND_VIEWER)) + + expect(derived).toHaveLength(1) + expect(derived.map(({ secret }) => zeroed(secret))).toEqual([true]) + expect(talkbacks.map(({ packets }) => packets.length)).toEqual([1, 2]) + + // The removed key written again in a later update is a new talker, asked for again with a talker of its own, the first one's release left at one. + await writeVoiceKey(engine, offerRequest.sessionIdentifier) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 2n)) + + const talkers = delegate.talkbackStarted?.mock.calls.map(([talker]) => talker) ?? [] + + expect(talkers).toHaveLength(3) + expect(talkers[2]).not.toBe(talkers[0]) + expect(talkbacks.map(({ packets }) => packets.length)).toEqual([1, 2, 1]) + expect(talkbacks.map(({ release }) => release.mock.calls.length)).toEqual([1, 0, 0]) + + await end(offerRequest) + + expect(talkbacks.map(({ release }) => release.mock.calls.length)).toEqual([1, 1, 1]) + }) + + it.each([ + { route: 'the signaling class' }, + { route: 'a failed connection' }, + { route: 'the second viewer\'s talkbackStarted' }, + ])('ends each viewer\'s sink once when $route ends the session', async ({ route }) => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + + const { delegate, end, engine, offerRequest, peer, talkback } = await sending() + // The transport is read before the session ends, since the connection's close leaves its list empty. + const [transport] = peer.dtlsTransports + const inside = route === 'the second viewer\'s talkbackStarted' + // The second viewer's sink, answered by its talkbackStarted call. + const second = keepingSink() + + await writeVoiceKey(engine, offerRequest.sessionIdentifier) + await writeVoiceKey(engine, offerRequest.sessionIdentifier, SECOND_VIEWER) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n)) + delegate.talkbackStarted?.mockImplementationOnce((talker) => { + if (inside) { + void end(offerRequest) + } + + return second.start(talker) + }) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 0n, SECOND_VIEWER)) + + if (route === 'a failed connection') { + peer.connectionStateChange.execute('failed') + } else { + await end(offerRequest) + } + + await settle() + await end(offerRequest) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n)) + transport.onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n, SECOND_VIEWER)) + + expect(delegate.talkbackStarted).toHaveBeenCalledTimes(2) + expect([talkback, second].map(({ release }) => release.mock.calls.length)).toEqual([1, 1]) + expect(talkback.packets).toHaveLength(1) + expect(second.packets).toHaveLength(inside + ? 0 + : 1) + }) + + it('hands its reader the dependable setting, which reads no packet of the better payload type', async () => { + const { end, engine, offerRequest, peer, talkback } = await sending({ voice: 'dependable' }) + + await writeVoiceKey(engine, offerRequest.sessionIdentifier) + peer.dtlsTransports[0].onRtp.execute(voicePacket(BETTER_VOICE.payloadType, 0n)) + + expect(engine.voice).toBe('dependable') + expect(talkback.packets).toEqual([]) + + peer.dtlsTransports[0].onRtp.execute(voicePacket(DEPENDABLE_VOICE.payloadType, 1n)) + + expect(talkback.packets).toHaveLength(1) + + await end(offerRequest) + }) + }) + + describe('transport feedback', () => { + // An RTCP transport layer feedback packet of a format, from the viewer's SSRC about its voice stream's: of format 9, one PAUSED entry of RFC 7728, + // PauseID 1, and of format 1, one generic NACK. + function feedback(format: number): ReturnType[number] { + const packet = Buffer.alloc(20) + + packet[0] = 0x80 | format + packet[1] = 205 + packet.writeUInt16BE(4, 2) + packet.writeUInt32BE(VIEWER_SSRC, 4) + packet.writeUInt32BE(format === 9 + ? 0 + : VOICE_SSRC, 8) + packet.writeUInt32BE(format === 9 + ? VOICE_SSRC + : 0x00010000, 12) + packet.writeUInt32BE(format === 9 + ? 0x20000001 + : 0, 16) + + return RtcpPacketConverter.deSerialize(packet)[0] + } + + // A receiver report from the viewer's SSRC, with no report block. + function receiverReport(): ReturnType[number] { + const packet = Buffer.alloc(8) + + packet[0] = 0x80 + packet[1] = 201 + packet.writeUInt16BE(1, 2) + packet.writeUInt32BE(VIEWER_SSRC, 4) + + return RtcpPacketConverter.deSerialize(packet)[0] + } + + it('logs a viewer\'s pause and resume feedback once a session, a second and every other RTCP packet logging nothing, and sends nothing for it', async () => { + const lines = captureDebug() + const { end, offerRequest, peer, sent } = await sending() + const [transport] = peer.dtlsTransports + + for (const packet of [ + feedback(9), + feedback(9), + feedback(1), + receiverReport(), + ]) { + transport.onRtcp.execute(packet) + } + + expect(lines.filter(line => line.includes('pause and resume'))).toEqual([ + expect.stringContaining(`WebRTC session ${offerRequest.sessionIdentifier} was sent pause and resume feedback by its viewer, which changes nothing it ` + + 'sends.'), + ]) + expect(sent).toEqual([]) + + await end(offerRequest) + }) + + it('takes every RTCP subscription off at the teardown', async () => { + const { end, engine, offerRequest, peer } = await offered({ talkback: false }) + const made = peer.dtlsTransports.map(transport => subscriptionsOf([transport.onRtcp])) + + await answered(engine, offerRequest) + + expect(made.map(subscribed => subscribed.length)).toEqual(peer.dtlsTransports.map(() => 1)) + + await end(offerRequest) + + expect(made.flat().map(unSubscribe => unSubscribe.mock.calls.length)).toEqual(made.flat().map(() => 1)) + }) + }) +}) diff --git a/src/lib/controller/CameraController.characterization.spec.ts b/src/lib/controller/CameraController.characterization.spec.ts new file mode 100644 index 000000000..0987683b1 --- /dev/null +++ b/src/lib/controller/CameraController.characterization.spec.ts @@ -0,0 +1,1861 @@ +import type { DataStreamConnection } from '../datastream/index.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { CameraControllerLegacyOptions, CameraControllerOptions, CameraControllerServiceMap, CameraControllerState, PrepareStreamCallback } from './index.js' + +import { Buffer } from 'node:buffer' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { + buildMockConnection, + buildSetupEndpointsTlv, + capabilitiesCameraOptions, + createCameraControllerOptions, + FIRST_VIDEO_SENSOR, + idleStreaming, + MOCK_IMAGE, + MockDelegate, + mockRecordingOptions, + mockStreamingOptions, + savedMapOf, +} from '../../test-utils/cameraFixtures.js' +import { settle } from '../../test-utils/settle.js' +import { Accessory } from '../Accessory.js' +import { decodeSetupEndpointsResponse, SetupEndpointsStatus } from '../camera/capabilities/setupEndpoints.js' +import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' +import { HDSProtocolSpecificErrorReason, HDSStatus, Protocols, Topics } from '../datastream/index.js' +import { HAPStatus } from '../HAPServer.js' +import { ControllerStorage } from '../model/ControllerStorage.js' +import { Service } from '../Service.js' +import { HapStatusError } from '../util/hapStatusError.js' +import * as uuid from '../util/uuid.js' +import { CameraController, DoorbellController } from './index.js' + +import '../definitions/index.js' + +const SUSPEND_SESSION = 'AQMCAQI=' +const SETUP_ENDPOINTS_ERROR = 'AgEC' +const SELECTED_CONFIGURATION = 'AR0BBKAPAAACCAEAAAAAAAAAAwsBAQACBgEEoA8AAAIkAQEAAhIBAQECAQIDBNAHAAAEBKAPAAADCwECsAQCAkAGAwEYAxQBAQACDwEBAQIBAAMBAwQEQAAAAA==' + +// END_SESSION is a SelectedRTPStreamConfiguration write that ends the session SESSION_ID names. +const SESSION_ID = '22222222-2222-2222-2222-222222222222' +const END_SESSION = 'ARUBECIiIiIiIiIiIiIiIiIiIiICAQA=' + +function legacyOptions(overrides: Partial = {}): CameraControllerLegacyOptions { + return { + ...createCameraControllerOptions(), + ...overrides, + } +} + +function configured(options: CameraControllerOptions = legacyOptions()): CameraController { + const controller = new CameraController(options) + controller.constructServices() + controller.configureServices() + return controller +} + +function fakeConnection(): DataStreamConnection & { sendResponse: ReturnType } { + return { + remoteAddress: 'test', + sendResponse: vi.fn(), + } as unknown as DataStreamConnection & { sendResponse: ReturnType } +} + +const OPEN_MESSAGE = { + streamId: 1, + type: 'ipcamera.recording', + target: 'controller', + reason: 'test', +} + +function openRecording(controller: CameraController): ReturnType { + const connection = fakeConnection() + // @ts-expect-error: private access + controller.recordingManagement!.handleDataSendOpen(connection, 7, OPEN_MESSAGE) + return connection.sendResponse +} + +function refusal(status: HDSProtocolSpecificErrorReason): unknown[] { + return [ + Protocols.DATA_SEND, + Topics.OPEN, + 7, + HDSStatus.PROTOCOL_SPECIFIC_ERROR, + { status }, + ] +} + +// What a restart restores for recording active: the state serialize writes, read back into a camera that restores it. +function restartedRecordingActive(controller: CameraController): unknown { + const restarted = configured() + restarted.deserialize(controller.serialize()!) + return restarted.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value +} + +// A camera whose cached recording service reads Active on, adopted by the reconcile with no stored record restored over it. +function adoptedActiveCamera(delegate: MockDelegate): CameraController { + const saved = savedMapOf(new CameraController(legacyOptions())) + saved.cameraEventRecordingManagement!.getCharacteristic(Characteristic.Active).value = Characteristic.Active.ACTIVE + const camera = new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + camera.initWithServices(saved) + camera.configureServices() + return camera +} + +// The layout an older library saves once it has restored the operating-mode slice: the legacy fields, recording active dropped because it holds it undefined. +function legacyLayoutWithoutRecordingActive(camera: CameraController): CameraControllerState { + return { + streamManagements: [], + recordingManagement: { + configurationHash: camera.serialize()!.recordingManagement!.configurationHash, + selectedConfiguration: SELECTED_CONFIGURATION, + recordingAudioActive: false, + eventSnapshotsActive: true, + homeKitCameraActive: true, + periodicSnapshotsActive: true, + }, + } +} + +// Opens a recording the camera lets through, then acknowledges its end as the hub does. The stream closes and frees the camera for the next open. +async function recordAndAcknowledge(controller: CameraController): Promise { + const connection = { + remoteAddress: 'test', + on: vi.fn(), + removeListener: vi.fn(), + addProtocolHandler: vi.fn(), + removeProtocolHandler: vi.fn(), + sendResponse: vi.fn(), + sendEvent: vi.fn(), + } + // @ts-expect-error: private access + controller.recordingManagement!.handleDataSendOpen(connection, 7, OPEN_MESSAGE) + await settle() + connection.addProtocolHandler.mock.calls[0][1].eventHandler[Topics.ACK]({ streamId: OPEN_MESSAGE.streamId, endOfStream: true }) +} + +// The delegate answers each stream preparation at once with its ports, SSRCs, keys and salts. A Setup Endpoints write on a camera's stream holds an answer. +function answerPreparations(): void { + vi.spyOn(MockDelegate.prototype, 'prepareStream').mockImplementation(((_request: unknown, callback: PrepareStreamCallback) => { + callback(undefined, { + video: { + port: 51010, + ssrc: 0x0A0B0C0D, + srtp_key: Buffer.alloc(16, 0xA1), + srtp_salt: Buffer.alloc(14, 0xB1), + }, + audio: { + port: 51012, + ssrc: 0x0E0F1011, + srtp_key: Buffer.alloc(16, 0xC1), + srtp_salt: Buffer.alloc(14, 0xD1), + }, + }) + }) as () => void) +} + +// A delegate handler that is async and rejects, as a plugin's async implementation of a handler the contract types as returning nothing does. It stays a plain +// function, because a Vitest mock observes the promise its implementation returns, which means it takes the rejection a plugin would leave unhandled. +function rejectsWith(message: string): () => Promise { + return async () => { + throw new Error(message) + } +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('camera controller characterization', () => { + describe('restore path', () => { + it('adopts every saved key and reports no change', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + const copy = { ...saved } + const camera = new CameraController(legacyOptions()) + + expect(camera.initWithServices(saved)).toBeUndefined() + + camera.configureServices() + camera.setMicrophoneMuted(true) + camera.setSpeakerMuted(true) + + expect(saved).toEqual(copy) + expect(camera.streamManagements[0].getService()).toBe(copy.streamManagement0) + expect(camera.streamManagements[1].getService()).toBe(copy.streamManagement1) + expect(camera.recordingManagement!.recordingManagementService).toBe(copy.cameraEventRecordingManagement) + expect(camera.motionService).toBe(copy.motionService) + expect(camera.occupancyService).toBe(copy.occupancyService) + expect(copy.microphone!.getCharacteristic(Characteristic.Mute).value).toBe(true) + expect(copy.speaker!.getCharacteristic(Characteristic.Mute).value).toBe(true) + }) + + it('creates and inserts a stream service the saved map lacks', () => { + const saved = savedMapOf(new CameraController(legacyOptions({ cameraStreamCount: 1 }))) + + expect(new CameraController(legacyOptions({ cameraStreamCount: 2 })).initWithServices(saved)).toBe(saved) + expect(saved.streamManagement1!.subtype).toBe('1') + }) + + it('deletes a saved stream service past the stream count', () => { + const saved = savedMapOf(new CameraController(legacyOptions({ cameraStreamCount: 3 }))) + + expect(new CameraController(legacyOptions({ cameraStreamCount: 2 })).initWithServices(saved)).toBe(saved) + expect(saved).not.toHaveProperty('streamManagement2') + }) + + it('deletes every saved stream at or past the stream count whatever gap the saved indexes leave, with a count of one and with none', () => { + // A legacy camera's saved map holding the streams 0 and 2, the stream 1 between them missing. + const gapped = (): CameraControllerServiceMap => { + const saved = savedMapOf(new CameraController(legacyOptions({ cameraStreamCount: 3 }))) + delete saved.streamManagement1 + + return saved + } + const streamKeys = (map: CameraControllerServiceMap): string[] => Object.keys(map).filter(key => key.startsWith('streamManagement')) + const one = gapped() + const first = one.streamManagement0 + + expect(new CameraController(legacyOptions({ cameraStreamCount: 1 })).initWithServices(one)).toBe(one) + expect(streamKeys(one)).toEqual(['streamManagement0']) + expect(one.streamManagement0).toBe(first) + + // A camera with the camera capabilities block runs no legacy stream. + const none = gapped() + const block = new CameraController(capabilitiesCameraOptions({ + videoSensors: [FIRST_VIDEO_SENSOR], + streaming: idleStreaming(), + })) + + expect(block.initWithServices(none)).toBe(none) + expect(streamKeys(none)).toEqual([]) + + block.handleControllerRemoved() + }) + + it('creates the microphone and speaker when audio arrives and deletes them when it goes', () => { + const silent = { + ...mockStreamingOptions, + audio: undefined, + } + const saved = savedMapOf(new CameraController(legacyOptions({ streamingOptions: silent }))) + + expect(new CameraController(legacyOptions()).initWithServices(saved)).toBe(saved) + expect(saved.microphone!.getCharacteristic(Characteristic.Volume).value).toBe(100) + expect(saved.speaker).toBeInstanceOf(Service.Speaker) + + expect(new CameraController(legacyOptions({ streamingOptions: silent })).initWithServices(saved)).toBe(saved) + expect(saved).not.toHaveProperty('microphone') + expect(saved).not.toHaveProperty('speaker') + }) + + it('inserts each service a saved map lacks in the order of the reconcile', () => { + const saved: CameraControllerServiceMap = {} + + expect(new CameraController(legacyOptions()).initWithServices(saved)).toBe(saved) + expect(Object.keys(saved)).toEqual([ + 'streamManagement0', + 'streamManagement1', + 'microphone', + 'speaker', + 'cameraEventRecordingManagement', + 'cameraOperatingMode', + 'dataStreamTransportManagement', + 'motionService', + 'occupancyService', + ]) + }) + + it('deletes the microphone and speaker when it restores in legacy mode', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + + expect(new CameraController(legacyOptions(), true).initWithServices(saved)).toBe(saved) + expect(saved).not.toHaveProperty('microphone') + expect(saved).not.toHaveProperty('speaker') + }) + + it('rebuilds every recording service when one is missing', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + const recordingService = saved.cameraEventRecordingManagement + delete saved.dataStreamTransportManagement + + expect(new CameraController(legacyOptions()).initWithServices(saved)).toBe(saved) + expect(saved.cameraEventRecordingManagement).not.toBe(recordingService) + expect(saved.dataStreamTransportManagement).toBeDefined() + }) + + it('deletes the recording services when recording goes', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + + expect(new CameraController(legacyOptions({ recording: undefined })).initWithServices(saved)).toBe(saved) + expect(saved).not.toHaveProperty('cameraEventRecordingManagement') + expect(saved).not.toHaveProperty('cameraOperatingMode') + expect(saved).not.toHaveProperty('dataStreamTransportManagement') + }) + + it('creates a boolean sensor the saved map lacks and inserts it under its key, which the restored accessory then holds', () => { + const saved = savedMapOf(new CameraController(legacyOptions({ sensors: undefined }))) + const camera = new CameraController(legacyOptions()) + + expect(camera.initWithServices(saved)).toBe(saved) + expect(saved.motionService).toBe(camera.motionService) + expect(saved.occupancyService).toBe(camera.occupancyService) + expect(camera.motionService!.getCharacteristic(Characteristic.StatusActive).value).toBe(true) + expect(camera.recordingManagement!.recordingManagementService.linkedServices).toContain(camera.motionService) + expect(camera.recordingManagement!.recordingManagementService.linkedServices).toContain(camera.occupancyService) + + // A cached accessory whose camera ran with no sensors gains the sensors its camera creates at the restore. + const first = new Accessory('Camera', uuid.generate('camera-characterization-created-sensor')) + first.configureController(new CameraController(legacyOptions({ sensors: undefined }))) + const restored = Accessory.deserialize(Accessory.serialize(first)) + const sensing = new CameraController(legacyOptions()) + restored.configureController(sensing) + + expect(restored.services).toContain(sensing.motionService) + expect(restored.services).toContain(sensing.occupancyService) + }) + + it('unlinks and deletes a saved sensor an external service replaces', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + const savedMotion = saved.motionService + const external = new Service.MotionSensor('External', 'external') + const camera = new CameraController(legacyOptions({ + sensors: { motion: external, occupancy: true }, + })) + + expect(camera.initWithServices(saved)).toBe(saved) + expect(saved).not.toHaveProperty('motionService') + expect(camera.motionService).toBe(external) + expect(camera.recordingManagement!.recordingManagementService.linkedServices).toContain(external) + expect(camera.recordingManagement!.recordingManagementService.linkedServices).not.toContain(savedMotion) + }) + + it('deletes a saved sensor its option leaves out', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + const savedMotion = saved.motionService + const savedOccupancy = saved.occupancyService + const camera = new CameraController(legacyOptions({ + sensors: { motion: true }, + })) + + expect(camera.initWithServices(saved)).toBe(saved) + expect(saved).not.toHaveProperty('occupancyService') + expect(saved.motionService).toBe(savedMotion) + expect(camera.motionService).toBe(savedMotion) + expect(camera.recordingManagement!.recordingManagementService.linkedServices).not.toContain(savedOccupancy) + }) + + it('deletes a doorbell key on a camera and keeps a key it does not know', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + const other = new Service.Switch('Other', 'other') + saved.doorbell = new Service.Doorbell('Doorbell', '') + saved.someOtherKey = other + + expect(new CameraController(legacyOptions()).initWithServices(saved)).toBe(saved) + expect(saved).not.toHaveProperty('doorbell') + expect(saved.someOtherKey).toBe(other) + }) + }) + + describe('doorbell restore', () => { + it('adopts a saved doorbell and marks it primary', () => { + const saved = savedMapOf(new DoorbellController(legacyOptions())) + const savedDoorbell = saved.doorbell + const doorbell = new DoorbellController(legacyOptions()) + + expect(doorbell.initWithServices(saved)).toBeUndefined() + expect(saved.doorbell).toBe(savedDoorbell) + expect(savedDoorbell!.isPrimaryService).toBe(true) + // @ts-expect-error: private access + expect(doorbell.recordingManagement!.eventTriggerOptions).toBe(3) + }) + + it('creates and inserts a doorbell a camera map lacks', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + + expect(new DoorbellController(legacyOptions()).initWithServices(saved)).toBe(saved) + expect(saved.doorbell).toBeInstanceOf(Service.Doorbell) + }) + + it('deletes a saved doorbell an external service replaces', () => { + const saved = savedMapOf(new DoorbellController(legacyOptions())) + const external = new Service.Doorbell('External', 'external') + const doorbell = new DoorbellController({ + ...legacyOptions(), + externalDoorbellService: external, + }) + + expect(doorbell.initWithServices(saved)).toBe(saved) + expect(saved).not.toHaveProperty('doorbell') + expect(external.isPrimaryService).toBe(true) + }) + }) + + describe('operating-mode gates', () => { + it('suspends and refuses a stream while its active flag is off', async () => { + const camera = configured() + const stream = camera.streamManagements[0] + const connection = buildMockConnection() + answerPreparations() + stream.selectedConfiguration = 'selected' + await stream.service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest(buildSetupEndpointsTlv(), connection) + stream.service.updateCharacteristic(Characteristic.Active, false) + + await expect(stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleGetRequest()).resolves.toBe(SUSPEND_SESSION) + await expect(stream.service.getCharacteristic(Characteristic.SetupEndpoints).handleGetRequest(connection)).resolves.toBe(SETUP_ENDPOINTS_ERROR) + await expect(stream.service.getCharacteristic(Characteristic.SetupEndpoints).handleGetRequest()).resolves.toBe(SETUP_ENDPOINTS_ERROR) + await expect(stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleSetRequest('AAAA')) + .rejects + .toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + await expect(stream.service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest('AAAA', {} as HAPConnection)) + .rejects + .toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + }) + + it('suspends every stream while the camera is off', async () => { + const camera = configured() + camera.recordingManagement!.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + + for (const stream of camera.streamManagements) { + stream.selectedConfiguration = 'selected' + + await expect(stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleGetRequest()).resolves.toBe(SUSPEND_SESSION) + await expect(stream.service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest('AAAA', {} as HAPConnection)) + .rejects + .toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + }) + + it('releases a stream\'s held answer when the camera turns off: its writer reads an error then and once the camera is back on', async () => { + const camera = configured() + const setupEndpoints = camera.streamManagements[0].service.getCharacteristic(Characteristic.SetupEndpoints) + const operatingMode = camera.recordingManagement!.operatingModeService + const connection = buildMockConnection() + answerPreparations() + await setupEndpoints.handleSetRequest(buildSetupEndpointsTlv(), connection) + + expect(decodeSetupEndpointsResponse(await setupEndpoints.handleGetRequest(connection) as string).status).toBe(SetupEndpointsStatus.SUCCESS) + + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + + await expect(setupEndpoints.handleGetRequest(connection)).resolves.toBe(SETUP_ENDPOINTS_ERROR) + + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, true) + + await expect(setupEndpoints.handleGetRequest(connection)).resolves.toBe(SETUP_ENDPOINTS_ERROR) + }) + + it('serves a stream and parses its write on a camera without recording', async () => { + const camera = configured(legacyOptions({ recording: undefined })) + const stream = camera.streamManagements[0] + stream.selectedConfiguration = 'selected' + + await expect(stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleGetRequest()).resolves.toBe('selected') + await expect(stream.service.getCharacteristic(Characteristic.SetupEndpoints).handleSetRequest('AAAA', {} as HAPConnection)) + .rejects + .toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + }) + + it('serves a snapshot while one stream of two is on', async () => { + const camera = configured() + camera.streamManagements[0].service.updateCharacteristic(Characteristic.Active, false) + + await expect(camera.handleSnapshotRequest(100, 100, 'test')).resolves.toBeDefined() + }) + + it('refuses a recording open in the order of its checks', async () => { + const camera = configured() + const recording = camera.recordingManagement! + const connection = fakeConnection() + + // @ts-expect-error: private access + recording.handleDataSendOpen(connection, 7, { ...OPEN_MESSAGE, target: 'accessory' }) + expect(connection.sendResponse).toHaveBeenLastCalledWith(...refusal(HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE)) + + expect(openRecording(camera)).toHaveBeenLastCalledWith(...refusal(HDSProtocolSpecificErrorReason.NOT_ALLOWED)) + + recording.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(true) + await settle() + recording.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + expect(openRecording(camera)).toHaveBeenLastCalledWith(...refusal(HDSProtocolSpecificErrorReason.NOT_ALLOWED)) + + recording.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, true) + const busy = { + connection: { remoteAddress: 'other' }, + streamId: 2, + } + // @ts-expect-error: private access + recording.recordingStream = busy + expect(openRecording(camera)).toHaveBeenLastCalledWith(...refusal(HDSProtocolSpecificErrorReason.BUSY)) + + // @ts-expect-error: private access + recording.recordingStream = undefined + expect(openRecording(camera)).toHaveBeenLastCalledWith(...refusal(HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION)) + }) + }) + + describe('legacy snapshots', () => { + const SLOW = '[test] The image snapshot handler for the given accessory is slow to respond! See https://homebridge.io/w/JtMGR for more info.' + const SILENT = '[test] The image snapshot handler for the given accessory didn\'t respond at all! See https://homebridge.io/w/JtMGR for more info.' + + afterEach(() => { + vi.useRealTimers() + }) + + // A legacy camera whose streaming delegate answers each snapshot request as the row's handler does. + function answering(handler: MockDelegate['handleSnapshotRequest']): CameraController { + const delegate = new MockDelegate() + + vi.spyOn(delegate, 'handleSnapshotRequest').mockImplementation(handler) + + return configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + } + + it('warns of a handler that never answers at 8 seconds and not before, and fails its snapshot as timed out at 25 seconds and not before, warning ' + + 'again', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const snapshot = answering(() => undefined).handleSnapshotRequest(100, 100, 'test') + const outcomes: unknown[] = [] + + snapshot.then(undefined, (status: unknown) => { + outcomes.push(status) + }) + + await vi.advanceTimersByTimeAsync(7999) + + expect(warn).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + + expect(warn.mock.calls).toEqual([ + [SLOW], + ]) + + await vi.advanceTimersByTimeAsync(16999) + + expect(outcomes).toEqual([]) + + await vi.advanceTimersByTimeAsync(1) + + expect(outcomes).toEqual([HAPStatus.OPERATION_TIMED_OUT]) + expect(warn.mock.calls).toEqual([ + [SLOW], + [SILENT], + ]) + }) + + it('fails a snapshot whose handler answers an empty picture with a communication failure, warning once', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const camera = answering((_request, callback) => callback(undefined, Buffer.alloc(0))) + + await expect(camera.handleSnapshotRequest(100, 100, 'test')).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + + expect(warn.mock.calls).toEqual([ + ['[test] Snapshot request handler provided empty image buffer!'], + ]) + }) + + it('answers a snapshot whose handler calls back a status with that status, and one whose handler calls back an error with a communication failure', + async () => { + await expect(answering((_request, callback) => callback(HAPStatus.RESOURCE_BUSY)).handleSnapshotRequest(100, 100, 'test')) + .rejects + .toBe(HAPStatus.RESOURCE_BUSY) + await expect(answering((_request, callback) => callback(new Error('The camera has no picture.'))).handleSnapshotRequest(100, 100, 'test')) + .rejects + .toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + }) + + it('fails a snapshot at once whose async handler rejects before it answers, with the status its HapStatusError names or a communication failure and ' + + 'the warning of a handler that throws, clearing its bound\'s timers', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const busy = answering(async () => { + throw new HapStatusError(HAPStatus.RESOURCE_BUSY) + }) + const failing = answering(rejectsWith('The camera has no picture.')) + const timers = vi.getTimerCount() + const outcomes: unknown[] = [] + + for (const camera of [busy, failing]) { + camera.handleSnapshotRequest(100, 100, 'test').then(undefined, (status: unknown) => { + outcomes.push(status) + }) + } + + await settle() + + expect(outcomes).toEqual([HAPStatus.RESOURCE_BUSY, HAPStatus.SERVICE_COMMUNICATION_FAILURE]) + expect(vi.getTimerCount()).toBe(timers) + expect(warn.mock.calls).toEqual([ + [ + expect.stringMatching(/^\[test\] Unhandled error thrown inside snapshot request handler: HapStatusError: HAP Status Error: -70403\n/), + ], + [ + expect.stringMatching(/^\[test\] Unhandled error thrown inside snapshot request handler: Error: The camera has no picture\./), + ], + ]) + expect(error).not.toHaveBeenCalled() + }) + }) + + describe('operating-mode side effects', () => { + it('reports recording active to the delegate once per change', async () => { + const delegate = new MockDelegate() + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const characteristic = camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + + characteristic.setValue(true) + await settle() + characteristic.setValue(true) + await settle() + + expect(active.mock.calls).toEqual([ + [true], + ]) + }) + + it('mirrors the camera state onto the sensors and closes a recording on every write', () => { + const camera = configured() + const recording = camera.recordingManagement! + const close = vi.fn() + const stream = { close } + // @ts-expect-error: private access + recording.recordingStream = stream + const statusActive = vi.fn() + camera.motionService!.getCharacteristic(Characteristic.StatusActive).on(CharacteristicEventTypes.CHANGE, statusActive) + + recording.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + recording.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + + expect(camera.motionService!.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + expect(camera.occupancyService!.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + expect(close.mock.calls).toEqual([ + [HDSProtocolSpecificErrorReason.NOT_ALLOWED], + [HDSProtocolSpecificErrorReason.NOT_ALLOWED], + ]) + expect(statusActive).toHaveBeenCalledTimes(2) + }) + + it('reports a state change for each write of an operating-mode characteristic', () => { + const camera = configured() + const recording = camera.recordingManagement! + const stateChange = vi.fn() + camera.setupStateChangeDelegate(stateChange) + + recording.recordingManagementService.updateCharacteristic(Characteristic.Active, true) + recording.recordingManagementService.updateCharacteristic(Characteristic.RecordingAudioActive, true) + recording.operatingModeService.updateCharacteristic(Characteristic.EventSnapshotsActive, false) + recording.operatingModeService.updateCharacteristic(Characteristic.PeriodicSnapshotsActive, false) + recording.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + camera.streamManagements[0].service.updateCharacteristic(Characteristic.Active, false) + + expect(stateChange).toHaveBeenCalledTimes(6) + }) + + it('adds an active flag a saved stream service lacks', () => { + const saved = savedMapOf(new CameraController(legacyOptions())) + const stream = saved.streamManagement0! + stream.removeCharacteristic(stream.getCharacteristic(Characteristic.Active)) + + new CameraController(legacyOptions()).initWithServices(saved) + + expect(stream.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + }) + }) + + describe('persistence', () => { + it('serializes every stream and the operating mode beside the recording state', () => { + const state = configured().serialize()! + + expect(state.streamManagements).toEqual([ + { id: 0, active: true }, + { id: 1, active: true }, + ]) + expect(state.recordingManagement).toEqual({ + configurationHash: { + algorithm: 'sha256', + hash: expect.any(String), + }, + selectedConfiguration: undefined, + }) + expect(state.operatingMode).toEqual({ + recordingActive: false, + recordingAudioActive: false, + eventSnapshotsActive: true, + homeKitCameraActive: true, + periodicSnapshotsActive: true, + }) + }) + + it('writes no operating mode for a camera without recording', () => { + expect(configured(legacyOptions({ recording: undefined })).serialize()!.operatingMode).toBeUndefined() + }) + + it('restores the operating-mode slice over the legacy fields', () => { + const camera = configured() + const operatingModeService = camera.recordingManagement!.operatingModeService + const state = camera.serialize()! + state.recordingManagement = { + ...state.recordingManagement!, + homeKitCameraActive: true, + eventSnapshotsActive: true, + } + state.operatingMode = { + ...state.operatingMode!, + homeKitCameraActive: false, + eventSnapshotsActive: false, + } + + camera.deserialize(state) + + expect(operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF) + expect(operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive).value).toBe(0) + }) + + it('tells the delegate the configuration before recording active when it restores the legacy layout', () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + camera.deserialize({ + streamManagements: [], + recordingManagement: { + configurationHash: camera.serialize()!.recordingManagement!.configurationHash, + selectedConfiguration: SELECTED_CONFIGURATION, + recordingActive: true, + recordingAudioActive: false, + eventSnapshotsActive: true, + homeKitCameraActive: true, + periodicSnapshotsActive: true, + }, + }) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(configuration).toHaveBeenCalledWith(expect.objectContaining({ prebufferLength: 4000 })) + expect(active.mock.calls).toEqual([ + [true], + ]) + expect(configuration.mock.invocationCallOrder[0]).toBeLessThan(active.mock.invocationCallOrder[0]) + }) + + it('tells the delegate the configuration before recording active when it restores the operating-mode slice', () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + camera.deserialize({ + streamManagements: [], + recordingManagement: { + configurationHash: camera.serialize()!.recordingManagement!.configurationHash, + selectedConfiguration: SELECTED_CONFIGURATION, + }, + operatingMode: { + recordingActive: true, + recordingAudioActive: false, + eventSnapshotsActive: true, + homeKitCameraActive: true, + periodicSnapshotsActive: true, + }, + }) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(configuration).toHaveBeenCalledWith(expect.objectContaining({ prebufferLength: 4000 })) + expect(active.mock.calls).toEqual([ + [true], + ]) + expect(configuration.mock.invocationCallOrder[0]).toBeLessThan(active.mock.invocationCallOrder[0]) + }) + + it('turns recording off over an adopted active camera and tells the delegate the configuration alone when it restores the legacy layout', () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = adoptedActiveCamera(delegate) + const state = legacyLayoutWithoutRecordingActive(camera) + state.recordingManagement = { + ...state.recordingManagement!, + recordingActive: false, + } + + camera.deserialize(state) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(active).not.toHaveBeenCalled() + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + }) + + it('turns recording off over an adopted active camera and tells the delegate the configuration alone when it restores the operating-mode slice', () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = adoptedActiveCamera(delegate) + const state = camera.serialize()! + state.recordingManagement = { + ...state.recordingManagement!, + selectedConfiguration: SELECTED_CONFIGURATION, + } + state.operatingMode = { + ...state.operatingMode!, + recordingActive: false, + } + + camera.deserialize(state) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(active).not.toHaveBeenCalled() + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + }) + + it('tells the delegate recording off after the configuration when it restores the legacy layout over a plugin update turning recording on', () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + camera.recordingManagement!.recordingManagementService.updateCharacteristic(Characteristic.Active, true) + const state = legacyLayoutWithoutRecordingActive(camera) + state.recordingManagement = { + ...state.recordingManagement!, + recordingActive: false, + } + + camera.deserialize(state) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(active.mock.calls).toEqual([ + [true], + [false], + ]) + expect(configuration.mock.invocationCallOrder[0]).toBeLessThan(active.mock.invocationCallOrder[1]) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + }) + + it('tells the delegate recording off after the configuration when it restores the operating-mode slice over a plugin update turning recording on', () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + camera.recordingManagement!.recordingManagementService.updateCharacteristic(Characteristic.Active, true) + const state = camera.serialize()! + state.recordingManagement = { + ...state.recordingManagement!, + selectedConfiguration: SELECTED_CONFIGURATION, + } + state.operatingMode = { + ...state.operatingMode!, + recordingActive: false, + } + + camera.deserialize(state) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(active.mock.calls).toEqual([ + [true], + [false], + ]) + expect(configuration.mock.invocationCallOrder[0]).toBeLessThan(active.mock.invocationCallOrder[1]) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + }) + + it('tells the delegate recording active once when it restores the operating-mode slice over a plugin update turning recording on', () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + camera.recordingManagement!.recordingManagementService.updateCharacteristic(Characteristic.Active, true) + const state = camera.serialize()! + state.recordingManagement = { + ...state.recordingManagement!, + selectedConfiguration: SELECTED_CONFIGURATION, + } + + camera.deserialize(state) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(active.mock.calls).toEqual([ + [true], + ]) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + }) + + it('tells the delegate recording active past a configuration replay that throws, and logs the throw, when it restores the operating-mode slice', () => { + const delegate = new MockDelegate() + vi.spyOn(delegate, 'updateRecordingConfiguration').mockImplementation(() => { + throw new Error('The delegate failed to configure.') + }) + const active = vi.spyOn(delegate, 'updateRecordingActive') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const state = camera.serialize()! + state.recordingManagement = { + ...state.recordingManagement!, + selectedConfiguration: SELECTED_CONFIGURATION, + } + state.operatingMode = { + ...state.operatingMode!, + recordingActive: true, + } + + camera.deserialize(state) + + expect(active.mock.calls).toEqual([ + [true], + ]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('Failed to properly initialize CameraRecordingDelegate from persistent storage: Error: The delegate failed to configure.'), + ], + ]) + }) + + it('logs a delegate that throws at the report and keeps the restore when it restores the operating-mode slice', () => { + const delegate = new MockDelegate() + const active = vi.spyOn(delegate, 'updateRecordingActive').mockImplementation(() => { + throw new Error('The delegate failed to update recording active.') + }) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const state = camera.serialize()! + state.recordingManagement = { + ...state.recordingManagement!, + selectedConfiguration: SELECTED_CONFIGURATION, + } + state.operatingMode = { + ...state.operatingMode!, + recordingActive: true, + } + + camera.deserialize(state) + + expect(active).toHaveBeenCalledTimes(1) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraRecordingDelegate failed to update state after a restore: Error: The delegate failed to update recording active.'), + ], + ]) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + }) + + it('tells the delegate the configuration alone for a legacy layout without recording active, and recording active at the first recording', async () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const request = vi.spyOn(delegate, 'handleRecordingStreamRequest') + const camera = adoptedActiveCamera(delegate) + + camera.deserialize(legacyLayoutWithoutRecordingActive(camera)) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(active).not.toHaveBeenCalled() + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + + await recordAndAcknowledge(camera) + + expect(active.mock.calls).toEqual([ + [true], + ]) + expect(configuration.mock.invocationCallOrder[0]).toBeLessThan(active.mock.invocationCallOrder[0]) + expect(active.mock.invocationCallOrder[0]).toBeLessThan(request.mock.invocationCallOrder[0]) + }) + + it('reports no recording state for a legacy layout without recording active over a camera with recording off', () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + camera.deserialize(legacyLayoutWithoutRecordingActive(camera)) + + expect(configuration).toHaveBeenCalledTimes(1) + expect(active).not.toHaveBeenCalled() + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + }) + + it('restores every other operating-mode field and mirrors the camera state onto the sensors from a legacy layout without recording active', () => { + const camera = configured() + const recording = camera.recordingManagement! + const state = legacyLayoutWithoutRecordingActive(camera) + state.recordingManagement = { + ...state.recordingManagement!, + recordingAudioActive: true, + eventSnapshotsActive: false, + homeKitCameraActive: false, + periodicSnapshotsActive: false, + } + + camera.deserialize(state) + + expect(recording.recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive).value).toBe(Characteristic.RecordingAudioActive.ENABLE) + expect(recording.operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive).value).toBe(Characteristic.EventSnapshotsActive.DISABLE) + expect(recording.operatingModeService.getCharacteristic(Characteristic.PeriodicSnapshotsActive).value).toBe(Characteristic.PeriodicSnapshotsActive.DISABLE) + expect(recording.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF) + expect(camera.motionService!.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + expect(camera.occupancyService!.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + }) + + it('restores the camera off beside every other field at its default and mirrors it onto the sensors from a legacy layout without recording active', () => { + const camera = configured() + const recording = camera.recordingManagement! + const state = legacyLayoutWithoutRecordingActive(camera) + state.recordingManagement = { + ...state.recordingManagement!, + homeKitCameraActive: false, + } + + camera.deserialize(state) + + expect(recording.recordingManagementService.getCharacteristic(Characteristic.RecordingAudioActive).value).toBe(Characteristic.RecordingAudioActive.DISABLE) + expect(recording.operatingModeService.getCharacteristic(Characteristic.EventSnapshotsActive).value).toBe(Characteristic.EventSnapshotsActive.ENABLE) + expect(recording.operatingModeService.getCharacteristic(Characteristic.PeriodicSnapshotsActive).value).toBe(Characteristic.PeriodicSnapshotsActive.ENABLE) + expect(recording.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.OFF) + expect(camera.motionService!.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + expect(camera.occupancyService!.getCharacteristic(Characteristic.StatusActive).value).toBe(false) + }) + + it('fires a change for every value a restore writes, unchanged values included', () => { + const camera = configured() + const homeKitCameraActive = vi.fn() + const statusActive = vi.fn() + camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).on(CharacteristicEventTypes.CHANGE, homeKitCameraActive) + camera.motionService!.getCharacteristic(Characteristic.StatusActive).on(CharacteristicEventTypes.CHANGE, statusActive) + + camera.deserialize(camera.serialize()!) + + expect(homeKitCameraActive).toHaveBeenCalledTimes(1) + expect(statusActive).toHaveBeenCalledTimes(2) + }) + + it('forces every stream on when saved recording state meets a camera without recording', () => { + const recordingCamera = configured() + for (const stream of recordingCamera.streamManagements) { + stream.service.updateCharacteristic(Characteristic.Active, false) + } + const camera = configured(legacyOptions({ recording: undefined })) + const stateChange = vi.fn() + camera.setupStateChangeDelegate(stateChange) + + camera.deserialize(recordingCamera.serialize()!) + + for (const stream of camera.streamManagements) { + expect(stream.service.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + } + expect(stateChange).toHaveBeenCalled() + }) + + it('drops the saves a camera restore requests and saves its layout at the next change', () => { + const accessory = new Accessory('Camera', uuid.generate('camera-characterization-restore-guard')) + const storage = new ControllerStorage(accessory) + const controller = configured() + storage.trackController(controller) + const record = { + streamManagements: [ + { id: 0, active: false }, + { id: 1, active: true }, + ], + recordingManagement: { + configurationHash: { algorithm: 'sha256', hash: 'stale' }, + recordingActive: false, + recordingAudioActive: true, + eventSnapshotsActive: false, + homeKitCameraActive: false, + periodicSnapshotsActive: true, + }, + } + + // @ts-expect-error: private access + storage.init([ + { + type: 'camera', + controllerData: { data: record }, + }, + ]) + + // @ts-expect-error: private access + expect(storage.controllerData.camera.data).toEqual(record) + + controller.recordingManagement!.operatingModeService.updateCharacteristic(Characteristic.EventSnapshotsActive, true) + + // @ts-expect-error: private access + expect(storage.controllerData.camera.data).toEqual(controller.serialize()) + // @ts-expect-error: private access + expect(storage.controllerData.camera.data.operatingMode).toEqual({ + recordingActive: false, + recordingAudioActive: true, + eventSnapshotsActive: true, + homeKitCameraActive: false, + periodicSnapshotsActive: true, + }) + // @ts-expect-error: private access + expect(storage.controllerData.camera.data.recordingManagement).toEqual({ + configurationHash: { + algorithm: 'sha256', + hash: expect.any(String), + }, + }) + // @ts-expect-error: private access + clearTimeout(storage.queuedSaveTimeout) + }) + }) + + describe('reset and unpair', () => { + it('turns recording off for a restart and the recording gate after a factory reset', async () => { + const delegate = new MockDelegate() + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const characteristic = camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + + characteristic.setValue(true) + await settle() + camera.handleFactoryReset() + + expect(characteristic.value).toBe(Characteristic.Active.INACTIVE) + expect(restartedRecordingActive(camera)).toBe(Characteristic.Active.INACTIVE) + expect(openRecording(camera)).toHaveBeenLastCalledWith(...refusal(HDSProtocolSpecificErrorReason.NOT_ALLOWED)) + + characteristic.setValue(true) + await settle() + + expect(active.mock.calls).toEqual([ + [true], + [false], + [true], + ]) + }) + + it('fires a change for every value a factory reset writes, unchanged values included', () => { + const camera = configured() + const homeKitCameraActive = vi.fn() + const motionStatus = vi.fn() + const occupancyStatus = vi.fn() + camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).on(CharacteristicEventTypes.CHANGE, homeKitCameraActive) + camera.motionService!.getCharacteristic(Characteristic.StatusActive).on(CharacteristicEventTypes.CHANGE, motionStatus) + camera.occupancyService!.getCharacteristic(Characteristic.StatusActive).on(CharacteristicEventTypes.CHANGE, occupancyStatus) + + camera.handleFactoryReset() + + expect(homeKitCameraActive).toHaveBeenCalledTimes(1) + expect(motionStatus).toHaveBeenCalledTimes(2) + expect(occupancyStatus).toHaveBeenCalledTimes(2) + }) + + it('turns recording on for a restart, the recording gate and the delegate after a plugin update', () => { + const delegate = new MockDelegate() + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + camera.recordingManagement!.recordingManagementService.updateCharacteristic(Characteristic.Active, true) + + expect(restartedRecordingActive(camera)).toBe(Characteristic.Active.ACTIVE) + expect(openRecording(camera)).toHaveBeenLastCalledWith(...refusal(HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION)) + expect(active.mock.calls).toEqual([ + [true], + ]) + }) + + it('reads recording on for a restart and the recording gate when it adopts an active recording service', () => { + const delegate = new MockDelegate() + const active = vi.spyOn(delegate, 'updateRecordingActive') + const camera = adoptedActiveCamera(delegate) + + expect(restartedRecordingActive(camera)).toBe(Characteristic.Active.ACTIVE) + expect(openRecording(camera)).toHaveBeenLastCalledWith(...refusal(HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION)) + expect(active).not.toHaveBeenCalled() + }) + + it('tells the delegate recording active once at the first recording when it adopts an active recording service', async () => { + const delegate = new MockDelegate() + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const request = vi.spyOn(delegate, 'handleRecordingStreamRequest') + const camera = adoptedActiveCamera(delegate) + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + await settle() + + await recordAndAcknowledge(camera) + await recordAndAcknowledge(camera) + + expect(active.mock.calls).toEqual([ + [true], + ]) + expect(request).toHaveBeenCalledTimes(2) + expect(configuration.mock.invocationCallOrder[0]).toBeLessThan(active.mock.invocationCallOrder[0]) + expect(active.mock.invocationCallOrder[0]).toBeLessThan(request.mock.invocationCallOrder[0]) + }) + + it('tells a throwing delegate recording active once, logs its throw and lets each recording through', async () => { + const delegate = new MockDelegate() + const active = vi.spyOn(delegate, 'updateRecordingActive').mockImplementation(() => { + throw new Error('The delegate failed to update recording active.') + }) + const request = vi.spyOn(delegate, 'handleRecordingStreamRequest') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = adoptedActiveCamera(delegate) + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + await settle() + + await recordAndAcknowledge(camera) + await recordAndAcknowledge(camera) + + expect(active).toHaveBeenCalledTimes(1) + expect(request).toHaveBeenCalledTimes(2) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraRecordingDelegate failed to update state before a recording request: Error: The delegate failed to update recording active.'), + ], + ]) + }) + + it('resets the operating mode and purges the record when the last pairing goes', () => { + const accessory = new Accessory('Camera', uuid.generate('camera-characterization-unpair')) + const camera = new CameraController(legacyOptions()) + accessory.configureController(camera) + const operatingMode = camera.recordingManagement!.operatingModeService + + operatingMode.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + operatingMode.updateCharacteristic(Characteristic.EventSnapshotsActive, false) + // @ts-expect-error: private access + accessory.handleAccessoryUnpairedForControllers() + + expect(operatingMode.getCharacteristic(Characteristic.HomeKitCameraActive).value).toBe(Characteristic.HomeKitCameraActive.ON) + expect(operatingMode.getCharacteristic(Characteristic.EventSnapshotsActive).value).toBe(1) + expect(camera.motionService!.getCharacteristic(Characteristic.StatusActive).value).toBe(true) + // @ts-expect-error: private access + expect(accessory.controllerStorage.controllerData.camera).toBeUndefined() + }) + + it('serves the selected configuration of a stream the camera removed', async () => { + const accessory = new Accessory('Camera', uuid.generate('camera-characterization-removed-stream')) + const camera = new CameraController(legacyOptions()) + accessory.configureController(camera) + const stream = camera.streamManagements[0] + + accessory.removeController(camera) + stream.selectedConfiguration = 'selected' + + await expect(stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleGetRequest()).resolves.toBe('selected') + }) + + it('keeps the record purged while a removed camera resets', () => { + const accessory = new Accessory('Camera', uuid.generate('camera-characterization-removed-record')) + const camera = new CameraController(legacyOptions()) + accessory.configureController(camera) + + camera.recordingManagement!.operatingModeService.updateCharacteristic(Characteristic.EventSnapshotsActive, false) + // @ts-expect-error: private access + expect(accessory.controllerStorage.controllerData.camera).toBeDefined() + + accessory.removeController(camera) + + // @ts-expect-error: private access + expect(accessory.controllerStorage.controllerData.camera).toBeUndefined() + }) + + it('resets and saves a camera whose stored state fails to restore', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const accessory = new Accessory('Camera', uuid.generate('camera-characterization-unreadable')) + const storage = new ControllerStorage(accessory) + const controller = configured() + controller.recordingManagement!.operatingModeService.updateCharacteristic(Characteristic.HomeKitCameraActive, false) + storage.trackController(controller) + + // @ts-expect-error: private access + storage.init([ + { + type: 'camera', + controllerData: { + data: { recordingManagement: {} }, + }, + }, + ]) + + expect(warn).toHaveBeenCalledTimes(1) + expect(controller.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value) + .toBe(Characteristic.HomeKitCameraActive.ON) + // @ts-expect-error: private access + expect(storage.controllerData.camera.data).toEqual(controller.serialize()) + // @ts-expect-error: private access + clearTimeout(storage.queuedSaveTimeout) + }) + + it('comes back with recording when the same instance is configured again', () => { + const camera = new CameraController(legacyOptions()) + const first = new Accessory('First', uuid.generate('camera-characterization-first')) + first.configureController(camera) + first.removeController(camera) + const second = new Accessory('Second', uuid.generate('camera-characterization-second')) + + second.configureController(camera) + + expect(camera.recordingManagement).toBeDefined() + expect(camera.streamManagements).toHaveLength(2) + expect(camera.serialize()!.operatingMode).toBeDefined() + }) + + it('builds a new motion sensor when the same instance is configured again, holding none between its removal and the second configure', () => { + const camera = new CameraController(legacyOptions()) + const first = new Accessory('First', uuid.generate('camera-characterization-first')) + first.configureController(camera) + const sensor = camera.motionService + + first.removeController(camera) + + expect(camera.motionService).toBeUndefined() + + const second = new Accessory('Second', uuid.generate('camera-characterization-second')) + second.configureController(camera) + + expect(sensor).toBeDefined() + expect(camera.motionService).toBeDefined() + expect(camera.motionService).not.toBe(sensor) + }) + + it('fires a change on Mute at each call of the plugin\'s setter and no mute event, and leaves Mute muted at a factory reset that unmutes the field, on a ' + + 'camera without the block', () => { + const camera = new CameraController(legacyOptions()) + const map = camera.constructServices() + const heard: string[] = [] + + camera.configureServices() + + const mute = map.microphone!.getCharacteristic(Characteristic.Mute) + + mute.on(CharacteristicEventTypes.CHANGE, ({ newValue }: { newValue: unknown }) => heard.push(`change ${String(newValue)}`)) + camera.on('microphone-change', muted => heard.push(`microphone-change ${muted}`)) + + camera.setMicrophoneMuted(true) + camera.setMicrophoneMuted(true) + camera.handleFactoryReset() + + expect(heard).toEqual([ + 'change true', + 'change true', + ]) + expect(mute.value).toBe(true) + // @ts-expect-error: private access + expect(camera.microphoneMuted).toBe(false) + }) + }) + + describe('delegate failures', () => { + // The listener collects each rejection no handler takes during a row, any of which would end a Homebridge process, and Vitest reports none of them while it stands. + const unhandled: unknown[] = [] + const collect = (reason: unknown): void => { + unhandled.push(reason) + } + + beforeEach(() => { + unhandled.length = 0 + process.on('unhandledRejection', collect) + }) + + afterEach(() => { + process.off('unhandledRejection', collect) + }) + + it('logs a delegate that rejects at a write of Active and keeps the write', async () => { + const delegate = new MockDelegate() + delegate.updateRecordingActive = rejectsWith('The delegate failed to update recording active.') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const characteristic = camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + + characteristic.setValue(true) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraRecordingDelegate failed to update state at a write of Active: Error: The delegate failed to update recording active.'), + ], + ]) + expect(characteristic.value).toBe(Characteristic.Active.ACTIVE) + }) + + it('logs a delegate that rejects without a reason at a write of Active and keeps the write', async () => { + const delegate = new MockDelegate() + // eslint-disable-next-line prefer-promise-reject-errors -- a plugin rejecting with no reason + delegate.updateRecordingActive = () => Promise.reject() + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const characteristic = camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + + characteristic.setValue(true) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + ['CameraRecordingDelegate failed to update state at a write of Active: undefined'], + ]) + expect(characteristic.value).toBe(Characteristic.Active.ACTIVE) + }) + + it('answers a write of Active whose delegate throws with a communication failure and stores a retry that reaches the delegate', async () => { + const delegate = new MockDelegate() + const active = vi.spyOn(delegate, 'updateRecordingActive').mockImplementationOnce(() => { + throw new Error('The delegate failed to update recording active.') + }) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const characteristic = camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + + await expect(characteristic.handleSetRequest(Characteristic.Active.ACTIVE)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(characteristic.value).toBe(Characteristic.Active.INACTIVE) + + await expect(characteristic.handleSetRequest(Characteristic.Active.ACTIVE)).resolves.toBeUndefined() + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([]) + expect(active.mock.calls).toEqual([ + [true], + [true], + ]) + expect(characteristic.value).toBe(Characteristic.Active.ACTIVE) + }) + + it('answers a write turning Active off whose delegate throws with a communication failure and stores a retry that reaches the delegate', async () => { + const delegate = new MockDelegate() + const active = vi.spyOn(delegate, 'updateRecordingActive') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const characteristic = camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + await characteristic.handleSetRequest(Characteristic.Active.ACTIVE) + active.mockImplementationOnce(() => { + throw new Error('The delegate failed to update recording active.') + }) + + await expect(characteristic.handleSetRequest(Characteristic.Active.INACTIVE)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(characteristic.value).toBe(Characteristic.Active.ACTIVE) + + await expect(characteristic.handleSetRequest(Characteristic.Active.INACTIVE)).resolves.toBeUndefined() + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([]) + expect(active.mock.calls).toEqual([ + [true], + [false], + [false], + ]) + expect(characteristic.value).toBe(Characteristic.Active.INACTIVE) + }) + + it('tells a delegate that writes Active from inside its call at a write of Active once', async () => { + const delegate = new MockDelegate() + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const service = camera.recordingManagement!.recordingManagementService + const active = vi.spyOn(delegate, 'updateRecordingActive').mockImplementation(() => { + service.updateCharacteristic(Characteristic.Active, true) + }) + + await expect(service.getCharacteristic(Characteristic.Active).handleSetRequest(Characteristic.Active.ACTIVE)).resolves.toBeUndefined() + await settle() + + expect(unhandled).toEqual([]) + expect(active.mock.calls).toEqual([ + [true], + ]) + }) + + it('logs a delegate that rejects at a plugin update of Active and keeps the update', async () => { + const delegate = new MockDelegate() + delegate.updateRecordingActive = rejectsWith('The delegate failed to update recording active.') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const characteristic = camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + + camera.recordingManagement!.recordingManagementService.updateCharacteristic(Characteristic.Active, true) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraRecordingDelegate failed to update state after an update of Active: Error: The delegate failed to update recording active.'), + ], + ]) + expect(characteristic.value).toBe(Characteristic.Active.ACTIVE) + }) + + it('logs a delegate that rejects before the first recording request and lets the recording through', async () => { + const delegate = new MockDelegate() + delegate.updateRecordingActive = rejectsWith('The delegate failed to update recording active.') + const request = vi.spyOn(delegate, 'handleRecordingStreamRequest') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = adoptedActiveCamera(delegate) + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + await settle() + + await recordAndAcknowledge(camera) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraRecordingDelegate failed to update state before a recording request: Error: The delegate failed to update recording active.'), + ], + ]) + expect(request).toHaveBeenCalledTimes(1) + }) + + it('logs a delegate that rejects at the report of a restore and keeps the restore', async () => { + const delegate = new MockDelegate() + delegate.updateRecordingActive = rejectsWith('The delegate failed to update recording active.') + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const state = camera.serialize()! + state.recordingManagement = { + ...state.recordingManagement!, + selectedConfiguration: SELECTED_CONFIGURATION, + } + state.operatingMode = { + ...state.operatingMode!, + recordingActive: true, + } + + camera.deserialize(state) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraRecordingDelegate failed to update state after a restore: Error: The delegate failed to update recording active.'), + ], + ]) + expect(configuration).toHaveBeenCalledTimes(1) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + }) + + it('logs a delegate that rejects at a write of the selected configuration and saves the configuration', async () => { + const delegate = new MockDelegate() + delegate.updateRecordingConfiguration = rejectsWith('The delegate failed to configure.') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const stateChange = vi.fn() + camera.setupStateChangeDelegate(stateChange) + + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining( + 'CameraRecordingDelegate failed to update state at a write of the selected recording configuration: Error: The delegate failed to configure.', + ), + ], + ]) + expect(stateChange).toHaveBeenCalledTimes(1) + expect(camera.serialize()!.recordingManagement!.selectedConfiguration).toBe(SELECTED_CONFIGURATION) + }) + + it('answers a write of the selected configuration whose delegate throws with a communication failure and saves a retry that reaches the delegate', async () => { + const delegate = new MockDelegate() + const configure = vi.spyOn(delegate, 'updateRecordingConfiguration').mockImplementationOnce(() => { + throw new Error('The delegate failed to configure.') + }) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const characteristic = camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration) + const stateChange = vi.fn() + camera.setupStateChangeDelegate(stateChange) + + await expect(characteristic.handleSetRequest(SELECTED_CONFIGURATION)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(stateChange).not.toHaveBeenCalled() + expect(camera.serialize()!.recordingManagement!.selectedConfiguration).toBeUndefined() + + await expect(characteristic.handleSetRequest(SELECTED_CONFIGURATION)).resolves.toBeUndefined() + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([]) + expect(configure).toHaveBeenCalledTimes(2) + expect(stateChange).toHaveBeenCalledTimes(1) + expect(camera.serialize()!.recordingManagement!.selectedConfiguration).toBe(SELECTED_CONFIGURATION) + }) + + it('tells a delegate that writes the selected configuration from inside its call at a write of it once', async () => { + const delegate = new MockDelegate() + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const service = camera.recordingManagement!.recordingManagementService + const configure = vi.spyOn(delegate, 'updateRecordingConfiguration').mockImplementation(() => { + service.setCharacteristic(Characteristic.SelectedCameraRecordingConfiguration, SELECTED_CONFIGURATION) + }) + + await expect(service.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).handleSetRequest(SELECTED_CONFIGURATION)).resolves.toBeUndefined() + await settle() + + expect(unhandled).toEqual([]) + expect(configure).toHaveBeenCalledTimes(1) + }) + + it('logs a delegate that rejects at the configuration replay of a restore and reports recording active', async () => { + const delegate = new MockDelegate() + delegate.updateRecordingConfiguration = rejectsWith('The delegate failed to configure.') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const state = camera.serialize()! + state.recordingManagement = { + ...state.recordingManagement!, + selectedConfiguration: SELECTED_CONFIGURATION, + } + state.operatingMode = { + ...state.operatingMode!, + recordingActive: true, + } + + camera.deserialize(state) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('Failed to properly initialize CameraRecordingDelegate from persistent storage: Error: The delegate failed to configure.'), + ], + ]) + expect(active.mock.calls).toEqual([ + [true], + ]) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + }) + + it('logs a delegate that rejects at the recording report of a factory reset and completes the reset', async () => { + const delegate = new MockDelegate() + delegate.updateRecordingActive = rejectsWith('The delegate failed to update recording active.') + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + camera.handleFactoryReset() + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraRecordingDelegate failed to update state after handleFactoryReset: Error: The delegate failed to update recording active.'), + ], + ]) + expect(configuration.mock.calls).toEqual([ + [undefined], + ]) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + }) + + it('logs a delegate that rejects at the configuration report of a factory reset and completes the reset', async () => { + const delegate = new MockDelegate() + delegate.updateRecordingConfiguration = rejectsWith('The delegate failed to configure.') + const active = vi.spyOn(delegate, 'updateRecordingActive') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + camera.handleFactoryReset() + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraRecordingDelegate failed to update state after handleFactoryReset: Error: The delegate failed to configure.'), + ], + ]) + expect(active.mock.calls).toEqual([ + [false], + ]) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + }) + + it('logs a delegate that throws a symbol at the recording report of a factory reset and completes the reset', () => { + const delegate = new MockDelegate() + vi.spyOn(delegate, 'updateRecordingActive').mockImplementation(() => { + throw Symbol('The delegate failed to update recording active.') + }) + const configuration = vi.spyOn(delegate, 'updateRecordingConfiguration') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + camera.handleFactoryReset() + + expect(error.mock.calls).toEqual([ + ['CameraRecordingDelegate failed to update state after handleFactoryReset: Symbol(The delegate failed to update recording active.)'], + ]) + expect(configuration.mock.calls).toEqual([ + [undefined], + ]) + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + }) + + it('logs a recording request that throws without an error and frees the camera for the next', async () => { + const delegate = new MockDelegate() + delegate.handleRecordingStreamRequest = () => { + // eslint-disable-next-line no-throw-literal -- a plugin throwing something that is not an Error + throw undefined + } + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = adoptedActiveCamera(delegate) + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + await settle() + const connection = { + remoteAddress: 'test', + on: vi.fn(), + removeListener: vi.fn(), + addProtocolHandler: vi.fn(), + removeProtocolHandler: vi.fn(), + sendResponse: vi.fn(), + sendEvent: vi.fn(), + isConsideredClosed: () => false, + } + + // @ts-expect-error: private access + camera.recordingManagement!.handleDataSendOpen(connection, 7, OPEN_MESSAGE) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + ['[HDS test] Encountered unexpected error for recording stream 1: undefined'], + ]) + // @ts-expect-error: private access + expect(camera.recordingManagement!.recordingStream).toBeUndefined() + }) + + it('logs a delegate that rejects when the hub acknowledges a recording and frees the camera for the next', async () => { + const delegate = Object.assign(new MockDelegate(), { + acknowledgeStream: rejectsWith('The delegate failed to acknowledge the recording.'), + }) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = adoptedActiveCamera(delegate) + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + await settle() + + await recordAndAcknowledge(camera) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('[HDS test] CameraRecordingDelegate failed to handle closing the stream 1: Error: The delegate failed to acknowledge the recording.'), + ], + ]) + // @ts-expect-error: private access + expect(camera.recordingManagement!.recordingStream).toBeUndefined() + }) + + it('logs a delegate that rejects after it answers a snapshot request and keeps the answer', async () => { + const delegate = new MockDelegate() + delegate.handleSnapshotRequest = async (_request, callback) => { + callback(undefined, MOCK_IMAGE) + throw new Error('The delegate failed to publish the snapshot.') + } + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + await expect(camera.handleSnapshotRequest(100, 100, 'test')).resolves.toBe(MOCK_IMAGE) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('[test] Unhandled error thrown inside snapshot request handler: Error: The delegate failed to publish the snapshot.'), + ], + ]) + }) + + it('answers a snapshot request whose delegate throws with a communication failure', async () => { + const delegate = new MockDelegate() + vi.spyOn(delegate, 'handleSnapshotRequest').mockImplementation(() => { + throw new Error('The delegate failed to take a snapshot.') + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + + await expect(camera.handleSnapshotRequest(100, 100, 'test')).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await settle() + + expect(unhandled).toEqual([]) + expect(warn.mock.calls).toEqual([ + [ + expect.stringContaining('[test] Unhandled error thrown inside snapshot request handler: Error: The delegate failed to take a snapshot.'), + ], + ]) + expect(error.mock.calls).toEqual([]) + }) + + it('logs a delegate that rejects at a stream preparation', async () => { + const delegate = new MockDelegate() + delegate.prepareStream = rejectsWith('The delegate failed to prepare the stream.') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const stream = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)).streamManagements[0] + const callback = vi.fn() + + // @ts-expect-error: private access + stream.handleSetupEndpoints(buildSetupEndpointsTlv(), callback, buildMockConnection()) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to prepare a stream: Error: The delegate failed to prepare the stream.'), + ], + ]) + expect(callback).not.toHaveBeenCalled() + }) + + it('logs a delegate that rejects at a stream request that ends a session', async () => { + const delegate = new MockDelegate() + delegate.handleStreamRequest = rejectsWith('The delegate failed to stop the stream.') + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const stream = configured(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)).streamManagements[0] + stream.sessionIdentifier = SESSION_ID + + void stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleSetRequest(END_SESSION) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to handle a stop stream request: Error: The delegate failed to stop the stream.'), + ], + ]) + expect(stream.sessionIdentifier).toBeUndefined() + }) + + it('answers a write whose stream request throws with a communication failure', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const stream = configured().streamManagements[0] + stream.sessionIdentifier = SESSION_ID + + await expect(stream.service.getCharacteristic(Characteristic.SelectedRTPStreamConfiguration).handleSetRequest(END_SESSION)) + .rejects + .toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await settle() + + expect(unhandled).toEqual([]) + expect(error.mock.calls).toEqual([]) + expect(stream.sessionIdentifier).toBeUndefined() + }) + + it('logs a delegate that throws at the stream request a closed connection sends', () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const stream = configured().streamManagements[0] + + // @ts-expect-error: private access + expect(() => stream.activeConnectionClosedListener()).not.toThrow() + + expect(error.mock.calls).toEqual([ + [ + expect.stringContaining('CameraStreamingDelegate failed to handle a stop stream request: Error: Unsupported!'), + ], + ]) + }) + }) +}) diff --git a/src/lib/controller/CameraController.spec.ts b/src/lib/controller/CameraController.spec.ts index 9f89a4f7b..c648f1e7d 100644 --- a/src/lib/controller/CameraController.spec.ts +++ b/src/lib/controller/CameraController.spec.ts @@ -1,158 +1,75 @@ -import type { - CameraRecordingOptions, - CameraStreamingOptions, - RecordingPacket, - SnapshotRequest, -} from '../camera/index.js' -import type { - CameraControllerOptions, - CameraRecordingDelegate, - CameraStreamingDelegate, - SnapshotRequestCallback, -} from './index.js' +import type { ScriptedTierDelegate } from '../../test-utils/cameraFixtures.js' +import type { CharacteristicValue, Nullable, WithUUID } from '../../types.js' +import type { SerializedAccessory } from '../Accessory.js' +import type { CameraReporter } from '../camera/diagnostics/CameraReporter.js' +import type { CameraProblem } from '../camera/diagnostics/problems.js' +import type { OperatingModeChange, OperatingModePolicy, StreamingEnabledChange } from '../camera/OperatingModePolicy.js' +import type { ServedRecording, ServedRecordings } from '../camera/recording/ServedRecording.js' +import type { MultiTierStreamingDelegate, TalkbackSink, TierStream } from '../camera/StreamingOptions.js' +import type { CharacteristicChange, CharacteristicProps } from '../Characteristic.js' +import type { RecordingProvisioningEntry } from '../model/RecordingProvisioning.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { CameraControllerOptions, CameraControllerServiceMap, CameraControllerState } from './index.js' import { Buffer } from 'node:buffer' -import crypto from 'node:crypto' +import { generateKeyPairSync } from 'node:crypto' -import { beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { - AudioBitrate, - AudioRecordingCodecType, - AudioRecordingSamplerate, - AudioStreamingCodecType, - AudioStreamingSamplerate, - EventTriggerOption, - H264Level, - H264Profile, - MediaContainerType, - SRTPCryptoSuites, - VideoCodecType, -} from '../camera/index.js' -import { Characteristic } from '../Characteristic.js' + bufferCamera, + capabilitiesCameraOptions, + createCameraControllerOptions, + endedOf, + endsOf, + FIRST_VIDEO_SENSOR, + handPublishedContext, + idleStreaming, + MOCK_IMAGE, + MockDelegate, + mockRecordingOptions, + mockStreamingOptions, + motionZonesFunction, + NUMBERED_ACCESSORY_UUID, + numberedAccessory, + numbersOf, + restartHarness, + savedMapOf, + scriptedTierDelegate, + SECOND_VIDEO_SENSOR, + snapshotFunction, + streamsOf, + twoSensorCameraOptions, + videoSensor, +} from '../../test-utils/cameraFixtures.js' +import { CertificateAuthority } from '../../test-utils/certificateAuthority.js' +import { DataStreamClient } from '../../test-utils/dataStreamClient.js' +import { captureDebug, captureDebugEvents } from '../../test-utils/engineDebug.js' +import { TIER_STREAM_PARAMETER_SETS, tierPicture, tierStreamFragment, tierStreamInitialization } from '../../test-utils/mp4Fixtures.js' +import { problemsOf } from '../../test-utils/reporterFixtures.js' +import { deferred, settle } from '../../test-utils/settle.js' +import { Accessory, Categories, MDNSAdvertiser } from '../Accessory.js' +import { Bridge } from '../Bridge.js' +import { TierKeeper } from '../camera/buffer/TierKeeper.js' +import { decodeCameraClientCertificateStatus } from '../camera/capabilities/provisioning.js' +import { onCameraProblem } from '../camera/diagnostics/problems.js' +import { CameraSensorIntent, EventTriggerOption } from '../camera/index.js' +import { TierTable } from '../camera/TierTable.js' +import { Access, Characteristic, CharacteristicEventTypes } from '../Characteristic.js' +import { HDSProtocolSpecificErrorReason, HDSStatus, Protocols, Topics } from '../datastream/index.js' import { HAPStatus } from '../HAPServer.js' -import { Service } from '../Service.js' -import { - CameraController, - DoorbellController, - ResourceRequestReason, -} from './index.js' +import { AccessoryInfo } from '../model/AccessoryInfo.js' +import { ControllerStorage } from '../model/ControllerStorage.js' +import { HAPStorage } from '../model/HAPStorage.js' +import { RecordingProvisioning } from '../model/RecordingProvisioning.js' +import { Service, ServiceEventTypes } from '../Service.js' +import { HapStatusError } from '../util/hapStatusError.js' +import * as uuid from '../util/uuid.js' +import { CameraController, CameraControllerEvents, DoorbellController, ResourceRequestReason } from './index.js' import '../definitions/index.js' -export const MOCK_IMAGE = crypto.randomBytes(64) - -export const mockStreamingOptions: CameraStreamingOptions = { - supportedCryptoSuites: [SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80], - video: { - codec: { - profiles: [H264Profile.BASELINE, H264Profile.MAIN, H264Profile.HIGH], - levels: [H264Level.LEVEL3_1, H264Level.LEVEL3_2, H264Level.LEVEL4_0], - }, - resolutions: [ - [1920, 1080, 30], // width, height, framerate - [1280, 960, 30], - [1280, 720, 30], - [1024, 768, 30], - [640, 480, 30], - [640, 360, 30], - [480, 360, 30], - [480, 270, 30], - [320, 240, 30], - [320, 240, 15], - [320, 180, 30], - ], - }, - audio: { - twoWayAudio: true, - codecs: [ - { - type: AudioStreamingCodecType.AAC_ELD, - samplerate: AudioStreamingSamplerate.KHZ_24, - }, - ], - }, -} - -export const mockRecordingOptions: CameraRecordingOptions = { - prebufferLength: 4000, - mediaContainerConfiguration: [ - { - type: MediaContainerType.FRAGMENTED_MP4, - fragmentLength: 8000, - }, - ], - - video: { - type: VideoCodecType.H264, - parameters: mockStreamingOptions.video.codec, - resolutions: mockStreamingOptions.video.resolutions, - }, - audio: { - codecs: [ - { - type: AudioRecordingCodecType.AAC_ELD, - audioChannels: 1, - bitrateMode: AudioBitrate.VARIABLE, - samplerate: AudioRecordingSamplerate.KHZ_48, - }, - ], - }, -} - -export class MockDelegate implements CameraStreamingDelegate, CameraRecordingDelegate { - handleSnapshotRequest(_request: SnapshotRequest, callback: SnapshotRequestCallback): void { - callback(undefined, MOCK_IMAGE) - } - - handleStreamRequest(): void { - throw new Error('Unsupported!') - } - - prepareStream(): void { - throw new Error('Unsupported!') - } - - async* handleRecordingStreamRequest(): AsyncGenerator { - yield { - data: Buffer.alloc(64, 0), - isLast: true, - } - } - - closeRecordingStream(): void { - // do nothing - } - - updateRecordingActive(): void { - // do nothing - } - - updateRecordingConfiguration(): void { - // do nothing - } -} - -export function createCameraControllerOptions( - recordingOptions: CameraRecordingOptions = mockRecordingOptions, - streamingOptions: CameraStreamingOptions = mockStreamingOptions, - cameraStreamCount = 2, - delegate: CameraStreamingDelegate & CameraRecordingDelegate = new MockDelegate(), -): CameraControllerOptions { - return { - cameraStreamCount, - delegate, - streamingOptions, - recording: { - options: recordingOptions, - delegate, - }, - sensors: { - motion: true, - occupancy: true, - }, - } -} +const SELECTED_CONFIGURATION = 'AR0BBKAPAAACCAEAAAAAAAAAAwsBAQACBgEEoA8AAAIkAQEAAhIBAQECAQIDBNAHAAAEBKAPAAADCwECsAQCAkAGAwEYAxQBAQACDwEBAQIBAAMBAwQEQAAAAA==' describe('CameraController', () => { let controller: CameraController @@ -233,8 +150,10 @@ describe('CameraController', () => { }) it('with motion service and doorbell and override', () => { - const options = mockRecordingOptions - options.overrideEventTriggerOptions = [EventTriggerOption.MOTION] + const options = { + ...mockRecordingOptions, + overrideEventTriggerOptions: [EventTriggerOption.MOTION], + } const doorbell = new DoorbellController(createCameraControllerOptions(options)) doorbell.constructServices() doorbell.configureServices() @@ -244,8 +163,10 @@ describe('CameraController', () => { }) it('with motion service and doorbell specified as override', () => { - const options = mockRecordingOptions - options.overrideEventTriggerOptions = [EventTriggerOption.DOORBELL] + const options = { + ...mockRecordingOptions, + overrideEventTriggerOptions: [EventTriggerOption.DOORBELL], + } const camera = new CameraController(createCameraControllerOptions(options)) camera.constructServices() camera.configureServices() @@ -255,6 +176,607 @@ describe('CameraController', () => { }) }) + describe('the forms of the options', () => { + const delegate = new MockDelegate() + const { recording } = createCameraControllerOptions() + + // The cameras a row builds, removed after it. No policy or keeper outlives its row. + const cameras: CameraController[] = [] + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + }) + + // A camera with the block whose delegate is the one given, over the first sensor alone. + function blockCamera(streamingDelegate: MultiTierStreamingDelegate): CameraController { + const camera = new CameraController(capabilitiesCameraOptions({ + streaming: { delegate: streamingDelegate }, + videoSensors: [FIRST_VIDEO_SENSOR], + })) + + cameras.push(camera) + + return camera + } + + it('throws a TypeError naming each member of the other form, the legacyMode, a missing motion sensor and a block without its snapshot function, ' + + 'the block\'s own members first, and builds a doorbell with the block and no motion sensor', () => { + const block = twoSensorCameraOptions() + const beside = (member: string): TypeError => new TypeError(`A camera with the camera capabilities block streams through the block and takes no ${member} ` + + 'option.') + const needs = (member: string): TypeError => new TypeError(`A camera without the camera capabilities block needs its ${member} option, since it streams ` + + 'through its legacy stream management.') + const motion = new TypeError('A camera with the camera capabilities block needs a motion sensor in its sensors option, since a hub starts its ' + + 'recordings at motion.') + const legacyMode = new TypeError('A camera with the camera capabilities block takes no legacyMode, since it always publishes its Microphone.') + + // @ts-expect-error The types refuse the legacy streaming delegate beside the block. + expect(() => new CameraController({ ...block, delegate })).toThrow(beside('delegate')) + // @ts-expect-error The types refuse the legacy streaming options beside the block. + expect(() => new CameraController({ ...block, streamingOptions: mockStreamingOptions })).toThrow(beside('streamingOptions')) + // @ts-expect-error The types refuse a legacy stream count beside the block. + expect(() => new CameraController({ ...block, cameraStreamCount: 2 })).toThrow(beside('cameraStreamCount')) + // @ts-expect-error The types refuse the top-level recording option beside the block. + expect(() => new CameraController({ ...block, recording })).toThrow(new TypeError( + 'A camera with the camera capabilities block records from its camera buffer and takes no top-level recording option.', + )) + expect(() => new CameraController(block, true)).toThrow(legacyMode) + + for (const sensors of [ + undefined, + { occupancy: true }, + { motion: false }, + ]) { + expect(() => new CameraController({ ...block, sensors })).toThrow(motion) + } + + // @ts-expect-error The types refuse options of neither form. + expect(() => new CameraController({})).toThrow(needs('delegate')) + // @ts-expect-error The types refuse a legacy streaming delegate without its options. + expect(() => new CameraController({ delegate })).toThrow(needs('streamingOptions')) + // @ts-expect-error The types refuse legacy streaming options without their delegate. + expect(() => new CameraController({ streamingOptions: mockStreamingOptions })).toThrow(needs('delegate')) + expect(() => new CameraController({ + ...block, + // @ts-expect-error The types refuse a block whose snapshot is no function. + cameraCapabilities: { ...block.cameraCapabilities, snapshot: 'picture' }, + })).toThrow(new TypeError('The camera capabilities block has no snapshot function, which answers every snapshot a hub asks for.')) + + // The block's own members are read before the members beside it, those before the legacyMode, and the legacyMode before the motion sensor. + expect(() => new CameraController({ + ...block, + // @ts-expect-error The types refuse a block whose snapshot is no function. + cameraCapabilities: { ...block.cameraCapabilities, snapshot: undefined }, + delegate, + })).toThrow(new TypeError('The camera capabilities block has no snapshot function, which answers every snapshot a hub asks for.')) + // @ts-expect-error The types refuse the legacy streaming delegate beside the block. + expect(() => new CameraController({ ...block, delegate, sensors: {} }, true)).toThrow(beside('delegate')) + expect(() => new CameraController({ ...block, sensors: {} }, true)).toThrow(legacyMode) + + // A doorbell needs no motion sensor, and a plugin's own subclass of the camera controller is refused as the base is. + class PluginCamera extends CameraController {} + + const doorbell = new DoorbellController({ ...block, sensors: undefined }) + + cameras.push(doorbell) + + expect(doorbell.motionService).toBeUndefined() + expect(() => new PluginCamera({ ...block, sensors: {} })).toThrow(motion) + }) + + it('builds a camera with the block with no legacy stream, its Microphone always and its Speaker exactly where its delegate has talkbackStarted, ' + + 'fresh and restored over a legacy camera\'s saved map, and saves no legacy stream', () => { + // A delegate written as a class, whose prototype carries talkbackStarted, and one written as an object without it. + class TalkingDelegate implements MultiTierStreamingDelegate { + tierDemandStarted(): void {} + + talkbackStarted(): TalkbackSink | undefined { + return undefined + } + } + + for (const [streamingDelegate, speaker] of [ + [ + new TalkingDelegate(), + true, + ], + [ + { + tierDemandStarted: () => undefined, + }, + false, + ], + ] as const) { + const fresh = blockCamera(streamingDelegate) + const built = fresh.constructServices() + + fresh.configureServices() + + const legacy = new CameraController(createCameraControllerOptions()) + + cameras.push(legacy) + + const saved = savedMapOf(legacy) + + expect(Object.keys(saved)).toEqual(expect.arrayContaining(['speaker', 'streamManagement0', 'streamManagement1'])) + + const restoredCamera = blockCamera(streamingDelegate) + const restored = restoredCamera.initWithServices(saved)! + + restoredCamera.configureServices() + + for (const [camera, map] of [ + [fresh, built], + [restoredCamera, restored], + ] as const) { + expect(Object.keys(map).filter(key => key.startsWith('streamManagement'))).toEqual([]) + expect(camera.streamManagements).toEqual([]) + expect(map.microphone?.UUID).toBe(Service.Microphone.UUID) + expect(map.speaker?.UUID).toBe(speaker ? Service.Speaker.UUID : undefined) + expect(camera.serialize()!.streamManagements).toEqual([]) + } + } + }) + + it('keeps a legacy camera\'s service map keys and order at a construct and at a restore from an empty map, and its saved state, as the base has ' + + 'them, the restore inserting the sensors it creates after the recording keys', () => { + const constructed = new CameraController(createCameraControllerOptions()) + const restored = new CameraController(createCameraControllerOptions()) + const restoredMap: CameraControllerServiceMap = {} + + cameras.push(constructed, restored) + + expect(Object.keys(constructed.constructServices())).toEqual([ + 'microphone', + 'speaker', + 'motionService', + 'occupancyService', + 'cameraEventRecordingManagement', + 'cameraOperatingMode', + 'dataStreamTransportManagement', + 'streamManagement0', + 'streamManagement1', + ]) + + restored.initWithServices(restoredMap) + + expect(Object.keys(restoredMap)).toEqual([ + 'streamManagement0', + 'streamManagement1', + 'microphone', + 'speaker', + 'cameraEventRecordingManagement', + 'cameraOperatingMode', + 'dataStreamTransportManagement', + 'motionService', + 'occupancyService', + ]) + + for (const camera of [constructed, restored]) { + expect(JSON.stringify(camera.serialize())).toBe('{"streamManagements":[{"id":0,"active":true},{"id":1,"active":true}],"recordingManagement":' + + '{"configurationHash":{"algorithm":"sha256","hash":"d1ccc6e88cfbb142ff81d235b3c9af110bca0a65c6b318d090d067c3d602f5eb"}},"operatingMode":' + + '{"recordingActive":false,"recordingAudioActive":false,"eventSnapshotsActive":true,"homeKitCameraActive":true,"periodicSnapshotsActive":true}}') + } + }) + }) + + describe('the switch at a restart', () => { + /* The legacy camera, with its legacy streams, its Microphone and Speaker and its legacy recording, and the camera with the block over the first and + * second video sensors, whose delegate takes talkback, which is why it keeps the Speaker. Each gives the motion sensor and the occupancy sensor where the row + * says, and a switch into a camera that gives the occupancy sensor creates it at the restore. + */ + const legacyCamera = (occupancy = true): CameraController => new CameraController({ + ...createCameraControllerOptions(), + sensors: { motion: true, occupancy }, + }) + const blockCamera = (occupancy = true): CameraController => new CameraController({ + ...capabilitiesCameraOptions({ + videoSensors: [FIRST_VIDEO_SENSOR, SECOND_VIDEO_SENSOR], + streaming: { + delegate: scriptedTierDelegate(), + }, + }), + sensors: { motion: true, occupancy }, + }) + + // The numbers of the recording configuration's characteristics, which only a legacy camera's recording service carries. + const CONFIGURATION_TYPES = [ + Characteristic.SupportedCameraRecordingConfiguration, + Characteristic.SupportedVideoRecordingConfiguration, + Characteristic.SupportedAudioRecordingConfiguration, + Characteristic.SelectedCameraRecordingConfiguration, + ] + const CONFIGURATION_IDS = CONFIGURATION_TYPES.map(({ UUID }) => `${Service.CameraRecordingManagement.UUID}|${UUID}`) + + // The keys of the camera's service map an accessory saved, the camera being its one controller. + function savedKeysOf(accessory: Accessory): string[] { + return Object.keys(Accessory.serialize(accessory).controllers![0].services) + } + + // Every number one accessory holds that the other did not, each above every number the other held. + function addedAbove(held: Record, numbers: Record): boolean { + const highest = Math.max(...Object.values(held)) + + return Object.entries(numbers).every(([id, number]) => (id in held) || (number > highest)) + } + + function motionCharacteristicsOf(accessory: Accessory): boolean[] { + const sensor = accessory.getService(Service.MotionSensor)! + + return [Characteristic.ContributingSensors, Characteristic.MotionEnabled].map(type => sensor.testCharacteristic(type)) + } + + // The authority the provisioning rows' credentials are issued under. + const authority = new CertificateAuthority() + + // A whole provisioning entry, as the hubs leave a camera that ran with the block: a credential valid for sixty days, a Camera Key, a publishing point + // and the marks. A camera with the block that loads it reads no update needed. + function wholeEntry(): RecordingProvisioningEntry { + const day = 24 * 60 * 60 * 1000 + const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' }) + + return { + cameraKey: { + key: Buffer.alloc(32, 0x5A), + keyNumber: 7n, + }, + clipMark: 9n, + credential: { + ca: authority.certificate, + certificate: authority.issue(publicKey, new Date(Date.now() - day), new Date(Date.now() + 60 * day)), + privateKey, + }, + publishingPoint: { + serverCACertificates: [ + { + certificate: Buffer.from('3082a1', 'hex'), + }, + ], + url: 'https://ingest.example/v1/token/', + }, + sequenceMark: 5n, + } + } + + // Every camera's entry the record stores under a username, as stored. + function storedEntries(username: string): Record { + const stored = HAPStorage.storage().getItem(RecordingProvisioning.persistKey(username)) as { accessories?: Record } | undefined + + return stored?.accessories ?? {} + } + + // Each switch row runs with the camera configured before its publish and after it, the order Homebridge restores a cached accessory in: it publishes + // the accessory and then configures the camera, which means the number rises at the configure's pass rather than at the publish. + const ORDERS = [ + ['before its publish', 'before'], + ['after its publish, as Homebridge restores a cached accessory, publishes it and then configures it', 'after'], + ] as const + + it.each(ORDERS)('drops the legacy streams of a legacy camera restored with the block and adds the block and the sensor it creates above every number ' + + 'held, keeping every other number but the recording configuration\'s, the motion sensor gaining the block\'s characteristics, the saved streams ' + + 'and selection leaving, the operating mode carried and the configuration number raised once, the camera configured %s', async (_, configure) => { + const harness = restartHarness() + const legacy = legacyCamera(false) + const first = await harness.run(legacy, configure, () => { + legacy.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration) + .setValue(SELECTED_CONFIGURATION) + legacy.recordingManagement!.operatingModeService.setCharacteristic(Characteristic.EventSnapshotsActive, false) + }) + const held = numbersOf(first.accessory) + + expect(legacy.serialize()).toMatchObject({ + streamManagements: [ + { id: 0, active: true }, + { id: 1, active: true }, + ], + recordingManagement: { selectedConfiguration: SELECTED_CONFIGURATION }, + }) + + const block = blockCamera() + const restore = vi.spyOn(block, 'deserialize') + const warn = vi.spyOn(console, 'warn') + const second = await harness.run(block, configure) + const numbers = numbersOf(second.accessory) + const kept = Object.fromEntries(Object.entries(held).filter(([id]) => !id.startsWith(Service.CameraRTPStreamManagement.UUID) + && !CONFIGURATION_IDS.includes(id))) + + expect(savedKeysOf(second.accessory).filter(key => key.startsWith('streamManagement'))).toEqual([]) + expect(Object.keys(numbers).filter(id => id.startsWith(Service.CameraRTPStreamManagement.UUID) || CONFIGURATION_IDS.includes(id))).toEqual([]) + expect(savedKeysOf(second.accessory).filter(key => key.startsWith('cameraCapabilities:')).length).toBeGreaterThan(0) + expect(numbers).toMatchObject(kept) + expect(addedAbove(held, numbers)).toBe(true) + expect(Object.keys(kept)).toContain(second.accessory.getService(Service.Speaker)!.getServiceId()) + expect(second.accessory.services).toContain(block.occupancyService) + expect(block.occupancyService!.iid).toBeGreaterThan(Math.max(...Object.values(held))) + expect(motionCharacteristicsOf(first.accessory)).toEqual([false, false]) + expect(motionCharacteristicsOf(second.accessory)).toEqual([true, true]) + expect(restore.mock.calls.map(([state]) => state)).toMatchObject([ + { + streamManagements: [ + { id: 0, active: true }, + { id: 1, active: true }, + ], + recordingManagement: { selectedConfiguration: SELECTED_CONFIGURATION }, + }, + ]) + expect(warn.mock.calls.filter(([line]) => String(line).startsWith('Could not initialize controller'))).toEqual([]) + // @ts-expect-error: private access + expect(block.recordingManagement!.selectedConfiguration).toBeUndefined() + expect(block.serialize()!.operatingMode).toMatchObject({ eventSnapshotsActive: false }) + expect([second.atPublish, second.afterPass]).toEqual(configure === 'before' + ? [first.afterPass + 1, first.afterPass + 1] + : [first.afterPass, first.afterPass + 1]) + }) + + it.each(ORDERS)('drops the block of a camera restored without it and builds legacy streams and the sensor it creates above every number held, ' + + 'keeping every number held under an id it still carries, the recording service regaining the configuration\'s characteristics, the motion sensor ' + + 'losing the block\'s characteristics, the block\'s saved slices and its provisioning record\'s marks carried and the configuration number raised ' + + 'once, the camera configured %s', async (_, configure) => { + const harness = restartHarness() + const block = blockCamera(false) + const first = await harness.run(block, configure, (accessory) => { + accessory.getServiceById(Service.CameraMultiTierRTPStreamManagement, FIRST_VIDEO_SENSOR.uuid.toLowerCase())! + .setCharacteristic(Characteristic.StreamingEnabled, false) + }) + const held = numbersOf(first.accessory) + const slices = { + multiTierStreamManagements: block.serialize()!.multiTierStreamManagements, + webRTCStreamManagements: block.serialize()!.webRTCStreamManagements, + } + const savedServices = Accessory.serialize(first.accessory).controllers![0].services + const blockIds = Object.keys(savedServices).filter(key => key.startsWith('cameraCapabilities:')).map(key => savedServices[key]) + + RecordingProvisioning.save(harness.username, first.accessory.UUID, wholeEntry()) + + const legacy = legacyCamera() + const second = await harness.run(legacy, configure) + const numbers = numbersOf(second.accessory) + const kept = Object.fromEntries(Object.entries(held).filter(([id]) => id in numbers)) + const recording = second.accessory.getService(Service.CameraRecordingManagement)! + + expect(slices.multiTierStreamManagements).toMatchObject({ + [FIRST_VIDEO_SENSOR.uuid.toLowerCase()]: { streamingEnabled: false }, + }) + expect(blockIds.length).toBeGreaterThan(0) + expect(savedKeysOf(second.accessory).filter(key => key.startsWith('cameraCapabilities:'))).toEqual([]) + expect(blockIds.filter(id => second.accessory.services.some(service => service.getServiceId() === id))).toEqual([]) + expect(legacy.streamManagements.map(stream => stream.getService().iid! > Math.max(...Object.values(held)))).toEqual([true, true]) + expect(second.accessory.services).toContain(legacy.occupancyService) + expect(legacy.occupancyService!.iid).toBeGreaterThan(Math.max(...Object.values(held))) + expect(numbers).toMatchObject(kept) + expect(addedAbove(held, numbers)).toBe(true) + expect(CONFIGURATION_TYPES.map(type => recording.testCharacteristic(type))).toEqual([true, true, true, true]) + expect(motionCharacteristicsOf(first.accessory)).toEqual([true, true]) + expect(motionCharacteristicsOf(second.accessory)).toEqual([false, false]) + expect(legacy.serialize()).toMatchObject(slices) + expect(RecordingProvisioning.load(harness.username, first.accessory.UUID)).toEqual({ clipMark: 9n, sequenceMark: 5n }) + expect([second.atPublish, second.afterPass]).toEqual(configure === 'before' + ? [first.afterPass + 1, first.afterPass + 1] + : [first.afterPass, first.afterPass + 1]) + }) + + it.each(ORDERS)('writes nothing to the provisioning record of a camera never run with the block, the camera configured %s', async (_, configure) => { + const harness = restartHarness() + const storage = HAPStorage.storage() + const key = RecordingProvisioning.persistKey(harness.username) + const setItem = vi.spyOn(storage, 'setItemSync') + const removeItem = vi.spyOn(storage, 'removeItemSync') + + // The storage is the suite's one store, which is why its spies go with the row. + onTestFinished(() => { + setItem.mockRestore() + removeItem.mockRestore() + }) + + await harness.run(legacyCamera(false), configure) + await harness.run(legacyCamera(false), configure) + + expect([ + ...setItem.mock.calls, + ...removeItem.mock.calls, + ].filter(([written]) => written === key)).toEqual([]) + }) + + it.each(ORDERS)('reads Camera Client Certificate Status as needing an update on a camera with the block run again after a run without it, the camera ' + + 'configured %s', async (_, configure) => { + const harness = restartHarness() + + await harness.run(blockCamera(false), configure) + RecordingProvisioning.save(harness.username, NUMBERED_ACCESSORY_UUID, wholeEntry()) + await harness.run(legacyCamera(false), configure) + + const back = await harness.run(blockCamera(false), configure) + const status = back.accessory.getService(Service.CameraClientCertificateManagement)!.getCharacteristic(Characteristic.CameraClientCertificateStatus) + + expect(decodeCameraClientCertificateStatus(status.value as string)).toEqual({ needsUpdate: true }) + }) + + it.each(ORDERS)('clears its own entry to its marks at a start without the block and leaves whole another camera\'s entry under the same username, the ' + + 'camera configured %s', async (_, configure) => { + const harness = restartHarness() + const other = uuid.generate('another camera under the same username') + + RecordingProvisioning.save(harness.username, NUMBERED_ACCESSORY_UUID, wholeEntry()) + RecordingProvisioning.save(harness.username, other, wholeEntry()) + + const before = storedEntries(harness.username) + + await harness.run(legacyCamera(false), configure) + + expect(storedEntries(harness.username)).toEqual({ + [NUMBERED_ACCESSORY_UUID]: { clipMark: '9', sequenceMark: '5' }, + [other]: before[other], + }) + }) + + it.each(ORDERS)('warns once where the store throws at the clear of a start without the block, and completes the restore, its recording delegate told ' + + 'as where the store does not throw, the camera configured %s', async (_, configure) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const storage = HAPStorage.storage() + const setItemSync = storage.setItemSync.bind(storage) + const failing = restartHarness() + const steady = restartHarness() + const failingKey = RecordingProvisioning.persistKey(failing.username) + + // A first run of each camera turns recording on, which means the next run's restore has a recording state to report to the delegate once it completes. The + // cameras run side by side, each under a username of its own. + await Promise.all([failing, steady].map(async (harness) => { + await harness.run(legacyCamera(false), configure, (accessory) => { + accessory.getService(Service.CameraRecordingManagement)!.setCharacteristic(Characteristic.Active, Characteristic.Active.ACTIVE) + }) + RecordingProvisioning.save(harness.username, NUMBERED_ACCESSORY_UUID, wholeEntry()) + })) + + // The store throws at every write of the failing camera's record, the clear's among them, and writes every other key as it stands. The storage is + // the suite's one store and the console every row's, which is why their spies go with the row. + const setItem = vi.spyOn(storage, 'setItemSync').mockImplementation((key, value) => { + if (key === failingKey) { + throw new Error('The disk is full.') + } + + setItemSync(key, value) + }) + + onTestFinished(() => { + setItem.mockRestore() + warn.mockRestore() + }) + + const runs = await Promise.all([failing, steady].map(async (harness) => { + const heard: string[] = [] + const delegate = Object.assign(new MockDelegate(), { + updateRecordingActive: (active: boolean) => heard.push(`active ${active}`), + }) + const { accessory } = await harness.run(new CameraController({ + ...createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate), + sensors: { motion: true }, + }), configure) + + return { accessory, heard } + })) + + // The name the warning carries is the failing accessory's Accessory Information Name, which its publish wrote. + const name = runs[0].accessory.getService(Service.AccessoryInformation)!.getCharacteristic(Characteristic.Name).value + + expect(warn.mock.calls.filter(([line]) => String(line).includes('recording provisioning record'))).toEqual([ + [`[${String(name)}] The camera's recording provisioning record could not be written: The disk is full.`], + ]) + expect(runs[0].heard).toContain('active true') + expect(runs[0].heard).toEqual(runs[1].heard) + expect(Object.keys(storedEntries(failing.username)[NUMBERED_ACCESSORY_UUID] as object)).toContain('certificate') + }) + + it.each(ORDERS)('clears nothing of a camera with the block at its first context, the camera configured %s', async (_, configure) => { + const harness = restartHarness() + + RecordingProvisioning.save(harness.username, NUMBERED_ACCESSORY_UUID, wholeEntry()) + + // The entry's provisioned parts as stored, its marks left out, since the camera's clips may move them. + const provisioned = Object.fromEntries(Object.entries(storedEntries(harness.username)[NUMBERED_ACCESSORY_UUID] as object) + .filter(([field]) => !['clipMark', 'sequenceMark'].includes(field))) + + await harness.run(blockCamera(false), configure) + + expect(storedEntries(harness.username)[NUMBERED_ACCESSORY_UUID]).toMatchObject(provisioned) + }) + + it.each([ + ['a legacy camera restored with the block', legacyCamera, blockCamera], + ['a camera with the block restored without it', blockCamera, legacyCamera], + ])('moves nothing at a second restart in the same mode after %s, its sensors adopted and its numbers, its saved state and its configuration ' + + 'number kept', async (_, from, to) => { + const harness = restartHarness() + + await harness.run(from(false), 'before') + + const switched = to() + const second = await harness.run(switched, 'before') + const again = to() + const third = await harness.run(again, 'before') + + expect(third.accessory.services).toEqual(expect.arrayContaining([again.motionService, again.occupancyService])) + expect(numbersOf(third.accessory)).toEqual(numbersOf(second.accessory)) + expect(savedKeysOf(third.accessory)).toEqual(savedKeysOf(second.accessory)) + expect(again.serialize()).toEqual(switched.serialize()) + expect([third.atPublish, third.afterPass]).toEqual([second.afterPass, second.afterPass]) + }) + }) + + describe('the configuration number', () => { + // The types whose value the hashed representation writes, each a value that states a camera's configuration. + const VALUE_TYPES = [ + Characteristic.CameraCapabilitiesData, + Characteristic.SupportedVideoStreamTiers, + Characteristic.SupportedAudioStreamTiers, + Characteristic.WebRTCSupportedVideoStreamTiers, + Characteristic.WebRTCSupportedAudioStreamTiers, + ].map(({ UUID }) => UUID) + + // A camera removed at its row's end. No policy outlives the row. + function removedAfter(camera: CameraController): CameraController { + onTestFinished(() => camera.handleControllerRemoved()) + + return camera + } + + // Each characteristic of a numbered accessory: its type, the value it holds and the value its hashed representation writes. + function hashedValuesOf(camera: CameraController): { hashed: unknown, held: unknown, UUID: string }[] { + return numberedAccessory(removedAfter(camera)).services.flatMap(service => service.characteristics.map(characteristic => ({ + hashed: characteristic.internalHAPRepresentation().value, + held: characteristic.value, + UUID: characteristic.UUID, + }))) + } + + // The two-sensor camera with the block, the first sensor's second tier at the given bitrate. + function cameraAt(bitrate: number): CameraController { + return new CameraController(capabilitiesCameraOptions({ + videoSensors: [ + videoSensor(FIRST_VIDEO_SENSOR.uuid, { + tiers: FIRST_VIDEO_SENSOR.tiers.map((tier, index) => (index === 1) + ? { ...tier, bitrate } + : { ...tier }), + }), + SECOND_VIDEO_SENSOR, + ], + streaming: idleStreaming(), + })) + } + + it('hashes the values of Camera Capabilities Data and each tier list of a camera with the block and null for every other value, and null for ' + + 'every value of a legacy camera', () => { + const block = hashedValuesOf(new CameraController(twoSensorCameraOptions())) + const listed = block.filter(({ UUID }) => VALUE_TYPES.includes(UUID)) + + expect(new Set(listed.map(({ UUID }) => UUID))).toEqual(new Set(VALUE_TYPES)) + expect(listed.every(({ hashed, held }) => (typeof held === 'string') && (hashed === held))).toBe(true) + expect(block.filter(({ UUID }) => !VALUE_TYPES.includes(UUID)).map(({ hashed }) => hashed)).toEqual(block.filter(({ UUID }) => !VALUE_TYPES.includes(UUID)) + .map(() => null)) + expect(hashedValuesOf(new CameraController(createCameraControllerOptions())).every(({ hashed }) => hashed === null)).toBe(true) + }) + + it.each([ + ['before its publish', 'before'], + ['after its publish, as Homebridge restores a cached accessory, publishes it and then configures it', 'after'], + ] as const)('keeps its number at a restart with the same tier lists and raises it once at a changed tier\'s bitrate, the camera configured %s', + async (_, configure) => { + const harness = restartHarness() + const first = await harness.run(cameraAt(768), configure) + const same = await harness.run(cameraAt(768), configure) + const changed = await harness.run(cameraAt(900), configure) + const again = await harness.run(cameraAt(900), configure) + const raised = first.afterPass + 1 + + expect([same.atPublish, same.afterPass]).toEqual([first.afterPass, first.afterPass]) + expect([changed.atPublish, changed.afterPass]).toEqual(configure === 'before' + ? [raised, raised] + : [first.afterPass, raised]) + expect([again.atPublish, again.afterPass]).toEqual([raised, raised]) + }, 20000) + }) + describe('handleSnapshotRequest', () => { beforeEach(() => { controller.recordingManagement?.operatingModeService @@ -400,4 +922,3056 @@ describe('CameraController', () => { expect(serialized0).toEqual(serialized1) }) }) + + describe('whether recording and streaming are allowed', () => { + // The cameras a row builds, removed after it. No policy or hold outlives its row. + const cameras: CameraController[] = [] + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + }) + + function configured(options: CameraControllerOptions): CameraController { + const made = new CameraController(options) + + cameras.push(made) + made.constructServices() + made.configureServices() + + return made + } + + // The two-sensor camera with the block, its delegate a script that settles each start. A tier the camera raises in service ends quietly. + function blockOptions(): CameraControllerOptions { + return bufferCamera().options + } + + // The camera's policy, which every gate and each property reads, the one a removal makes among them. + function policyOf(made: CameraController): OperatingModePolicy { + // @ts-expect-error: private access + return made.operatingMode + } + + // What the properties read, streaming's first. + function allowed(made: CameraController): boolean[] { + return [made.streamingAllowed, made.recordingAllowed] + } + + function cameraActive(made: CameraController): Characteristic { + return made.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive) + } + + function recordingActive(made: CameraController): Characteristic { + return made.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + } + + it.each([ + ['with the camera capabilities block', blockOptions], + ['without the block', createCameraControllerOptions], + ])('reads the user\'s switches on a camera %s, the whole state a factory reset leaves inside an operating-mode-change listener, and the new policy ' + + 'after a removal', (_, options) => { + const made = configured(options()) + const read: unknown[] = [] + // Reads the properties at each change of a switch they read. + const heard = ({ field }: OperatingModeChange): void => { + if (['homeKitCameraActive', 'recordingActive'].includes(field)) { + read.push([ + field, + ...allowed(made), + ]) + } + } + + handPublishedContext(made) + read.push(allowed(made)) + recordingActive(made).updateValue(Characteristic.Active.ACTIVE) + read.push(allowed(made)) + cameraActive(made).updateValue(Characteristic.HomeKitCameraActive.OFF) + read.push(allowed(made)) + + // The reset stores every switch before it raises the event for any: the listener reads the whole state it leaves at each change, the camera on and + // recording off. + made.on(CameraControllerEvents.OPERATING_MODE_CHANGED, heard) + made.handleFactoryReset() + made.off(CameraControllerEvents.OPERATING_MODE_CHANGED, heard) + recordingActive(made).updateValue(Characteristic.Active.ACTIVE) + read.push(allowed(made)) + + // A removal resets the camera and makes a new policy, which a configure binds to the new services: recording turned on there reads on while the + // dropped policy, bound to the dropped services the removal's reset turned off, reads off. + const dropped = policyOf(made) + + made.handleControllerRemoved() + made.constructServices() + made.configureServices() + recordingActive(made).updateValue(Characteristic.Active.ACTIVE) + read.push([ + ...allowed(made), + dropped.recordingAllowed(), + ]) + + expect(policyOf(made)).not.toBe(dropped) + expect(read).toEqual([ + [true, false], + [true, true], + [false, false], + ['recordingActive', true, false], + ['homeKitCameraActive', true, false], + [true, true], + [true, true, false], + ]) + }) + + it('reads each property true on a camera with the block whose switches allow recording and streaming and which is out of service, handed no context ' + + 'and then stated away, while its own gates read it out of service', () => { + const made = configured(blockOptions()) + const read: boolean[][] = [] + // What the properties read, then the policy's own in-service reads beside them. + const reading = (): boolean[] => [ + ...allowed(made), + policyOf(made).streamingInService(), + policyOf(made).recordingInService(), + ] + + recordingActive(made).updateValue(Characteristic.Active.ACTIVE) + read.push(reading()) + made.updateSourceState('away') + read.push(reading()) + + expect(read).toEqual([ + [true, true, false, false], + [true, true, false, false], + ]) + }) + + it.each([ + { + disabled: [false, false], + options: blockOptions, + reading: 'not allowed', + which: 'with the camera capabilities block', + }, + { + disabled: [true, true], + options: createCameraControllerOptions, + reading: 'as its other switches read', + which: 'without the block', + }, + ])('reads recording and streaming $reading on a camera $which whose Camera Operating Mode service carries a Manually Disabled turned on', ({ + disabled, + options, + }) => { + const made = configured(options()) + const read: boolean[][] = [] + + recordingActive(made).updateValue(Characteristic.Active.ACTIVE) + read.push(allowed(made)) + made.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.ManuallyDisabled).updateValue(1) + read.push(allowed(made)) + + expect(read).toEqual([ + [true, true], + disabled, + ]) + }) + }) + + describe('the recording state reported once the restore completes', () => { + const USERNAME = 'AB:CD:EF:00:44:01' + const BRIDGE_USERNAME = 'AB:CD:EF:00:44:02' + const ACCESSORY_UUID = uuid.generate('camera restore report') + const published: Accessory[] = [] + + afterEach(async () => { + for (const target of published.splice(0)) { + await target.unpublish() + await target.destroy() + } + + for (const username of [USERNAME, BRIDGE_USERNAME]) { + Accessory.cleanupAccessoryData(username) + } + }) + + // Publishes an accessory through the advertiser the suite mocks, and nothing is announced. + async function publish(target: Accessory, username: string): Promise { + published.push(target) + await target.publish({ + advertiser: MDNSAdvertiser.BONJOUR, + category: Categories.CAMERA, + pincode: '031-45-154', + username, + }) + } + + // A camera whose delegate records each recording state and configuration it hears, in order. + function recordedCamera(): { camera: CameraController, heard: string[] } { + const heard: string[] = [] + const delegate = Object.assign(new MockDelegate(), { + updateRecordingActive: (active: boolean) => heard.push(`active ${active}`), + updateRecordingConfiguration: (configuration: unknown) => heard.push(configuration === undefined + ? 'no configuration' + : 'configuration'), + }) + + return { + camera: new CameraController(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)), + heard, + } + } + + // The accessory a cache restores at startup, its camera's recording Active saved on. + function cachedAccessory(): Accessory { + const saved = new Accessory('Camera', ACCESSORY_UUID) + const camera = new CameraController(createCameraControllerOptions()) + saved.configureController(camera) + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value = Characteristic.Active.ACTIVE + + return Accessory.deserialize(Accessory.serialize(saved)) + } + + // A stored camera record in the layout that keeps the operating mode beside the selected configuration, with or without recording active. + function storeRecord(recordingActive?: boolean): void { + const reference = new CameraController(createCameraControllerOptions()) + reference.constructServices() + const state: CameraControllerState = { + streamManagements: [], + recordingManagement: { + configurationHash: reference.serialize()!.recordingManagement!.configurationHash, + selectedConfiguration: SELECTED_CONFIGURATION, + recordingActive, + recordingAudioActive: false, + eventSnapshotsActive: true, + homeKitCameraActive: true, + periodicSnapshotsActive: true, + }, + } + + reference.handleControllerRemoved() + HAPStorage.storage().setItemSync(ControllerStorage.persistKey(USERNAME), { + accessories: { + [ACCESSORY_UUID]: [ + { + type: 'camera', + controllerData: { + data: state, + }, + }, + ], + }, + }) + } + + // Opens a recording the camera lets through and acknowledges its end as the hub does. The stream frees the camera. + async function recordAndAcknowledge(camera: CameraController): Promise { + const connection = { + addProtocolHandler: vi.fn(), + on: vi.fn(), + remoteAddress: 'test', + removeListener: vi.fn(), + removeProtocolHandler: vi.fn(), + sendEvent: vi.fn(), + sendResponse: vi.fn(), + } + + // @ts-expect-error: private access + camera.recordingManagement!.handleDataSendOpen(connection, 7, { + reason: 'motion', + streamId: 1, + target: 'controller', + type: 'ipcamera.recording', + }) + await settle() + connection.addProtocolHandler.mock.calls[0][1].eventHandler[Topics.ACK]({ endOfStream: true, streamId: 1 }) + } + + it('tells the delegate a cached recording Active once its published accessory\'s restore completes, after a configuration the restore replays', async () => { + const bare = recordedCamera() + const withoutRecord = cachedAccessory() + withoutRecord.configureController(bare.camera) + + expect(bare.heard).toEqual([]) + + await publish(withoutRecord, USERNAME) + + expect(bare.heard).toEqual(['active true']) + + await withoutRecord.unpublish() + await withoutRecord.destroy() + storeRecord() + const replayed = recordedCamera() + const withRecord = cachedAccessory() + withRecord.configureController(replayed.camera) + + await publish(withRecord, USERNAME) + + expect(replayed.heard).toEqual(['configuration', 'active true']) + }) + + it('reports nothing more at the first recording once the restore reported the recording state', async () => { + storeRecord() + const { camera, heard } = recordedCamera() + const target = cachedAccessory() + target.configureController(camera) + await publish(target, USERNAME) + + await recordAndAcknowledge(camera) + + expect(heard).toEqual(['configuration', 'active true']) + }) + + it('reports nothing at the context once a stored record restored and reported the recording state', async () => { + storeRecord(true) + const { camera, heard } = recordedCamera() + const target = cachedAccessory() + target.configureController(camera) + + await publish(target, USERNAME) + + expect(heard).toEqual(['configuration', 'active true']) + }) + + it('reports a cached recording Active again at the first context of a controller removed and configured again on its accessory', async () => { + const bridge = new Bridge('Bridge', uuid.generate('camera restore report bridge')) + await publish(bridge, BRIDGE_USERNAME) + const { camera, heard } = recordedCamera() + const target = new Accessory('Camera', ACCESSORY_UUID) + const adopt = (): void => { + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value = Characteristic.Active.ACTIVE + } + target.configureController(camera) + adopt() + + bridge.addBridgedAccessory(target) + + expect(heard).toEqual(['active true']) + + target.removeController(camera) + bridge.removeBridgedAccessory(target) + target.configureController(camera) + adopt() + heard.length = 0 + + bridge.addBridgedAccessory(target) + + expect(heard).toEqual(['active true']) + }) + }) + + describe('the recording services of a camera with the capabilities block, which gives no legacy recording options', () => { + const CONFIGURATION_CHARACTERISTICS = [ + Characteristic.SupportedCameraRecordingConfiguration, + Characteristic.SupportedVideoRecordingConfiguration, + Characteristic.SupportedAudioRecordingConfiguration, + Characteristic.SelectedCameraRecordingConfiguration, + ] + + // The cameras a row builds, removed after it. No policy or stream outlives its row. + const cameras: CameraController[] = [] + + afterEach(() => { + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + + vi.restoreAllMocks() + }) + + // A camera built from the options given, its services constructed or adopted from a saved map and configured. + function configured(options: CameraControllerOptions, saved?: CameraControllerServiceMap): CameraController { + const camera = new CameraController(options) + + cameras.push(camera) + + if (saved) { + camera.initWithServices(saved) + } else { + camera.constructServices() + } + + camera.configureServices() + + return camera + } + + function heldConfigurationCharacteristics(camera: CameraController): boolean[] { + return CONFIGURATION_CHARACTERISTICS.map(type => camera.recordingManagement!.recordingManagementService.testCharacteristic(type)) + } + + it('keeps the legacy recording services under their keys, its recording service carrying Active and Recording Audio Active alone', () => { + const camera = new CameraController(twoSensorCameraOptions()) + + cameras.push(camera) + + const map = camera.constructServices() + + camera.configureServices() + + expect(map.cameraEventRecordingManagement).toBe(camera.recordingManagement!.recordingManagementService) + expect(map.cameraOperatingMode).toBe(camera.recordingManagement!.operatingModeService) + expect(map.dataStreamTransportManagement).toBe(camera.recordingManagement!.dataStreamManagement.getService()) + expect(camera.recordingManagement!.options).toBeUndefined() + expect(camera.recordingManagement!.recordingManagementService.characteristics.map(({ UUID }) => UUID)).toEqual([ + Characteristic.Active.UUID, + Characteristic.RecordingAudioActive.UUID, + ]) + }) + + it('reports recording Active to its recorder and never a configuration, and saves no recording state, the factory reset\'s report included', async () => { + const camera = configured(twoSensorCameraOptions()) + const recorder = camera.recordingManagement!.delegate + const updateRecordingActive = vi.spyOn(recorder, 'updateRecordingActive') + const updateRecordingConfiguration = vi.spyOn(recorder, 'updateRecordingConfiguration') + + camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + await settle() + + const state = camera.serialize()! + + camera.handleFactoryReset() + + expect(state.recordingManagement).toBeUndefined() + expect(state.operatingMode?.recordingActive).toBe(true) + expect(updateRecordingActive.mock.calls).toEqual([ + [true], + [false], + ]) + expect(updateRecordingConfiguration).not.toHaveBeenCalled() + }) + + it('adopts the services a camera with the options saved, removing the configuration characteristics, ignoring the selection and forcing no stream on', async () => { + const dual = new CameraController(createCameraControllerOptions()) + const saved = dual.constructServices() + + dual.configureServices() + dual.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.SelectedCameraRecordingConfiguration).setValue(SELECTED_CONFIGURATION) + dual.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + await settle() + + for (const stream of dual.streamManagements) { + stream.service.updateCharacteristic(Characteristic.Active, false) + } + + // The camera that saved the services leaves them, as a restart does, before the camera with the block adopts them. + const state = dual.serialize()! + const configurationChanges = vi.fn() + + dual.handleControllerRemoved() + + expect(state.recordingManagement?.selectedConfiguration).toBe(SELECTED_CONFIGURATION) + saved.cameraEventRecordingManagement!.on(ServiceEventTypes.SERVICE_CONFIGURATION_CHANGE, configurationChanges) + + const camera = configured(twoSensorCameraOptions(), saved) + const updateRecordingConfiguration = vi.spyOn(camera.recordingManagement!.delegate, 'updateRecordingConfiguration') + + camera.deserialize(state) + + expect(camera.recordingManagement!.recordingManagementService).toBe(saved.cameraEventRecordingManagement) + expect(heldConfigurationCharacteristics(camera)).toEqual([false, false, false, false]) + expect(configurationChanges).toHaveBeenCalled() + expect(updateRecordingConfiguration).not.toHaveBeenCalled() + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + + for (const stream of camera.streamManagements) { + expect(stream.service.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + } + }) + + it('restores its state on a camera that gives the options with no throw and no reset, its recording Active restored and nothing selected', async () => { + const buffered = configured(twoSensorCameraOptions()) + + buffered.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).setValue(Characteristic.Active.ACTIVE) + await settle() + + const camera = configured(createCameraControllerOptions()) + const handleFactoryReset = vi.spyOn(camera, 'handleFactoryReset') + + expect(() => camera.deserialize(buffered.serialize()!)).not.toThrow() + expect(handleFactoryReset).not.toHaveBeenCalled() + expect(camera.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + expect(heldConfigurationCharacteristics(camera)).toEqual([true, true, true, true]) + // @ts-expect-error: private access + expect(camera.recordingManagement!.selectedConfiguration).toBeUndefined() + }) + + it('forces every stream on when its stored state meets a camera without recording', () => { + const buffered = configured(twoSensorCameraOptions()) + const camera = configured({ + ...createCameraControllerOptions(), + recording: undefined, + }) + const stateChange = vi.fn() + + for (const stream of buffered.streamManagements) { + stream.service.updateCharacteristic(Characteristic.Active, false) + } + + camera.setupStateChangeDelegate(stateChange) + camera.deserialize(buffered.serialize()!) + + for (const stream of camera.streamManagements) { + expect(stream.service.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.ACTIVE) + } + + expect(stateChange).toHaveBeenCalled() + }) + + it('leaves its streams as they stand on a camera that gives the legacy recording options restoring a state saved with the capabilities block, which ' + + 'holds no stream, forcing none on while it records', () => { + const state = configured(twoSensorCameraOptions()).serialize()! + const camera = configured(createCameraControllerOptions()) + + for (const stream of camera.streamManagements) { + stream.service.updateCharacteristic(Characteristic.Active, false) + } + + camera.deserialize(state) + + expect(state.recordingManagement).toBeUndefined() + expect(state.streamManagements).toEqual([]) + expect(camera.streamManagements).toHaveLength(2) + + for (const stream of camera.streamManagements) { + expect(stream.service.getCharacteristic(Characteristic.Active).value).toBe(Characteristic.Active.INACTIVE) + } + }) + + it('throws a TypeError naming the rule for a camera without the capabilities block whose recording option gives no recording options', () => { + const delegate = new MockDelegate() + + expect(() => new CameraController({ + ...createCameraControllerOptions(), + // @ts-expect-error The types refuse a recording option without its options, which an untyped caller can still give. + recording: { delegate }, + })).toThrow(new TypeError( + 'A camera without the camera capabilities block needs the recording option\'s options, because it records through them alone.', + )) + }) + }) + + describe('a camera that records from its camera buffer', () => { + const USERNAME = 'AB:CD:EF:00:44:03' + const ACCESSORY_UUID = uuid.generate('camera buffer recording') + const SENSOR_UUID = FIRST_VIDEO_SENSOR.uuid.toLowerCase() + + // The accessories and cameras a row builds, destroyed and removed after it. No hold, recording or policy outlives its row. + const accessories: Accessory[] = [] + const cameras: CameraController[] = [] + + afterEach(async () => { + for (const accessory of accessories.splice(0)) { + await accessory.unpublish() + await accessory.destroy() + } + + for (const camera of cameras.splice(0)) { + camera.handleControllerRemoved() + } + + Accessory.cleanupAccessoryData(USERNAME) + vi.restoreAllMocks() + }) + + function camera(options: CameraControllerOptions): CameraController { + const made = new CameraController(options) + + cameras.push(made) + + return made + } + + // Publishes an accessory through the advertiser the suite mocks, and nothing is announced. + async function publish(target: Accessory): Promise { + accessories.push(target) + await target.publish({ + advertiser: MDNSAdvertiser.BONJOUR, + category: Categories.CAMERA, + pincode: '031-45-154', + username: USERNAME, + }) + } + + // An accessory's multi-tier stream services, in its order. + function multiTierOf(target: Accessory): Service[] { + return target.services.filter(service => service.UUID === Service.CameraMultiTierRTPStreamManagement.UUID) + } + + function statusActiveOf(services: readonly Service[]): unknown[] { + return services.map(service => service.getCharacteristic(Characteristic.StatusActive).value) + } + + // Each service of an accessory in order with its type and subtype, and each of its characteristics' types in order. + function shapeOf(target: Accessory): unknown[] { + return target.services.map(({ characteristics, subtype, UUID }) => [ + UUID, + subtype, + characteristics.map(({ UUID }) => UUID), + ]) + } + + /* What the two-sensor camera saved at its first publish when it recorded through its plugin's recording delegate with no legacy recording options, a + * setup the camera controller refuses beside the block, written out because no camera the library builds saves it: each service the camera built, + * under its key and in its order, with each characteristic's value and the properties the library set on it beyond its type's own; the camera's + * state; and the accessory record's configuration hash and number. The accessory's own services stand first and last, as its publish places them. + */ + type SavedCharacteristic = readonly [WithUUID Characteristic>, Nullable, Partial?] + + type SavedService = readonly [ + string | undefined, + WithUUID Service>, + string | undefined, + readonly SavedCharacteristic[], + ] + + const ADMIN_WRITE = { + adminOnlyAccess: [Access.WRITE], + } + + function savedTierStream(sensorUUID: string, identifier: string): SavedService { + return [ + `cameraCapabilities:multiTierStream:${sensorUUID}`, + Service.CameraMultiTierRTPStreamManagement, + sensorUUID, + [ + [Characteristic.StreamingEnabled, true], + [Characteristic.StatusActive, true], + [ + Characteristic.SupportedVideoStreamTiers, + 'AQECAgFjAxoBBAEAAAACAQIDBKQGAAAEAoAHBQI4BAYBHgAAAxoBBAIAAAACAQMDBAADAAAEAgAFBQLQAgYBHgAAAxoBBAMAAAACAQQDBLQAAAAEAoACBQJoAQYBDw==', + ], + [Characteristic.SupportedAudioStreamTiers, 'AQEDAgFuAxgBBAEAAAACBMBdAAADAQQEAQIFARQGAQE='], + [Characteristic.SupportedRTPConfiguration, 'AgEA'], + [Characteristic.SetupEndpoints, null], + [Characteristic.RTPStreamingControl, null], + [Characteristic.SensorUUID, identifier], + ], + ] + } + + const SAVED_SERVICES: readonly SavedService[] = [ + [ + 'cameraCapabilities:cameraCapabilities', + Service.CameraCapabilities, + '', + [ + [Characteristic.Version, '17.99'], + [Characteristic.CameraCapabilitiesData, 'AQEBAk4BJAEIAQKABwICOAQCENEAAAEAAEAAgAAAAAAAAAEDAQEEAQEFAAAAASQBCAECAAUCAtACAhDSAAACAABAAIAAAAAAAAACAwH/BAECBQA='], + ], + ], + [ + 'cameraCapabilities:globalOperatingMode', + Service.CameraGlobalOperatingMode, + '', + [ + [Characteristic.HomeKitCameraActive, 1, ADMIN_WRITE], + [Characteristic.StreamingEnabled, true], + [Characteristic.CameraOperatingModeIndicator, 1, ADMIN_WRITE], + ], + ], + savedTierStream(FIRST_VIDEO_SENSOR.uuid.toLowerCase(), '0QAAAQAAQACAAAAAAAAAAQ=='), + savedTierStream(SECOND_VIDEO_SENSOR.uuid.toLowerCase(), '0gAAAgAAQACAAAAAAAAAAg=='), + [ + 'cameraCapabilities:cameraBufferManagement', + Service.CameraBufferManagement, + '', + [ + [Characteristic.BufferUploadCommand, null], + [ + Characteristic.BufferActivityCommand, + null, + { transient: true }, + ], + [Characteristic.BufferEventCommand, null], + [Characteristic.BufferEventSequenceNumber, 0], + [ + Characteristic.CameraRecordingPublishingPoint, + null, + { + adminOnlyAccess: [Access.READ, Access.WRITE], + sensitive: true, + transient: true, + }, + ], + ], + ], + [ + 'cameraCapabilities:cameraKeyManagement', + Service.CameraKeyManagement, + '', + [ + [Characteristic.CameraKey, null, ADMIN_WRITE], + [Characteristic.CameraKeyID, ''], + ], + ], + [ + 'cameraCapabilities:cameraClientCertificateManagement', + Service.CameraClientCertificateManagement, + '', + [ + [Characteristic.CameraClientCSR, null], + [ + Characteristic.CameraClientCertificate, + null, + { + adminOnlyAccess: [Access.READ, Access.WRITE], + }, + ], + [Characteristic.CameraClientCertificateStatus, 'AQEB'], + ], + ], + [ + 'microphone', + Service.Microphone, + '', + [ + [Characteristic.Mute, false], + [Characteristic.Volume, 100], + ], + ], + [ + 'speaker', + Service.Speaker, + '', + [ + [Characteristic.Mute, false], + [Characteristic.Volume, 100], + ], + ], + [ + 'motionService', + Service.MotionSensor, + '', + [ + [Characteristic.MotionDetected, false], + [Characteristic.StatusActive, true], + [Characteristic.MotionEnabled, true], + [Characteristic.ContributingSensors, 'AQA='], + ], + ], + [ + 'occupancyService', + Service.OccupancySensor, + '', + [ + [Characteristic.OccupancyDetected, 0], + [Characteristic.StatusActive, true], + ], + ], + [ + 'cameraEventRecordingManagement', + Service.CameraRecordingManagement, + '', + [ + [Characteristic.Active, 0, ADMIN_WRITE], + [Characteristic.RecordingAudioActive, 0], + ], + ], + [ + 'cameraOperatingMode', + Service.CameraOperatingMode, + '', + [ + [Characteristic.EventSnapshotsActive, 1, ADMIN_WRITE], + [Characteristic.HomeKitCameraActive, 1, ADMIN_WRITE], + [Characteristic.PeriodicSnapshotsActive, 1, ADMIN_WRITE], + ], + ], + [ + 'dataStreamTransportManagement', + Service.DataStreamTransportManagement, + '', + [ + [Characteristic.SetupDataStreamTransport, ''], + [Characteristic.SupportedDataStreamTransportConfiguration, 'AQMBAQA='], + [Characteristic.Version, '1.0'], + ], + ], + [ + undefined, + Service.ProtocolInformation, + undefined, + [ + [Characteristic.Version, '1.1.0'], + ], + ], + ] + + const SAVED_STATE: CameraControllerState = { + streamManagements: [], + operatingMode: { + eventSnapshotsActive: true, + globalStreamingEnabled: true, + homeKitCameraActive: true, + manuallyDisabled: false, + motionEnabled: true, + nightVision: false, + operatingModeIndicator: true, + periodicSnapshotsActive: true, + recordingActive: false, + recordingAudioActive: false, + thirdPartyCameraActive: false, + }, + multiTierStreamManagements: { + [FIRST_VIDEO_SENSOR.uuid.toLowerCase()]: { streamingEnabled: true }, + [SECOND_VIDEO_SENSOR.uuid.toLowerCase()]: { streamingEnabled: true }, + }, + } + + const SAVED_RECORD = { configHash: 'd565436eb68211c1e8dbaf7556c74052d7babbab', configVersion: 2 } + + // The accessory as the accessory cache holds it, the camera's service map among its controllers, built from the saved services. + function savedAccessory(): SerializedAccessory { + const saved = new Accessory('Camera D598', ACCESSORY_UUID) + const map: Record = {} + + for (const [key, type, subtype, characteristics] of SAVED_SERVICES) { + const service = new type('', subtype) + + for (const characteristic of [...service.characteristics]) { + if (!characteristics.some(([held]) => held.UUID === characteristic.UUID)) { + service.removeCharacteristic(characteristic) + } + } + + for (const [held, value, props] of characteristics) { + const characteristic = service.getCharacteristic(held) + + if (props) { + characteristic.setProps(props) + } + + characteristic.value = value + } + + saved.addService(service) + + if (key !== undefined) { + map[key] = service + } + } + + for (const key of ['dataStreamTransportManagement', 'motionService', 'occupancyService']) { + map.cameraEventRecordingManagement.addLinkedService(map[key]) + } + + return { + ...Accessory.serialize(saved), + controllers: [ + { + services: Object.fromEntries(Object.entries(map).map(([key, service]) => [ + key, + service.getServiceId(), + ])), + type: 'camera', + }, + ], + lastKnownUsername: USERNAME, + } + } + + it('throws a TypeError naming the rule for a top-level recording option beside the block, with the block\'s own and without it, and a prebuffer ' + + 'that is not a whole number from 0 to 30000', () => { + const block = bufferCamera().options.cameraCapabilities + const { recording } = createCameraControllerOptions() + + for (const own of [{}, undefined]) { + // @ts-expect-error The types refuse the top-level recording option beside the block. + expect(() => new CameraController({ + ...twoSensorCameraOptions(), + cameraCapabilities: { ...block, recording: own }, + recording, + })).toThrow(new TypeError('A camera with the camera capabilities block records from its camera buffer and takes no top-level recording option.')) + } + + for (const prebuffer of [-1, 1.5, 30001]) { + expect(() => new CameraController(bufferCamera({ prebuffer }).options)).toThrow(new TypeError( + `The prebuffer of the camera capabilities block's recording option, ${prebuffer}, is not a whole number of milliseconds from 0 to 30000.`, + )) + } + }) + + it('throws a TypeError naming a shouldRecord that is not a function, and throws it before refusing a member of the other form beside the block', () => { + const { options } = bufferCamera({ + // @ts-expect-error The types refuse a shouldRecord that is not a function, which an untyped caller can still give. + shouldRecord: 1, + }) + const refusal = new TypeError('The recording option of the camera capabilities block has a shouldRecord that is not a function.') + + expect(() => new CameraController(options)).toThrow(refusal) + // @ts-expect-error The types refuse a member of the other form beside the block. + expect(() => new CameraController({ + ...options, + delegate: new MockDelegate(), + recording: createCameraControllerOptions().recording, + })).toThrow(refusal) + }) + + it('throws the same TypeError for a top-level recording option beside the block that carries a delegate and no recording options', () => { + const delegate = new MockDelegate() + + expect(() => new CameraController({ + ...bufferCamera().options, + // @ts-expect-error The types refuse a top-level recording option without its options, which an untyped caller can still give beside the block. + recording: { delegate }, + })).toThrow(new TypeError('A camera with the camera capabilities block records from its camera buffer and takes no top-level recording option.')) + }) + + it('records by default the block\'s first sensor and its best tier with a prebuffer of 5000, and throws nothing for a block with no recording option', + () => { + const options = bufferCamera().options + const { cameraCapabilities: block } = options + // The first sensor's tiers stated smallest first. + const reordered = camera({ + ...options, + cameraCapabilities: { + ...block, + videoSensors: block.videoSensors.map((sensor, index) => index === 0 + ? { + ...sensor, + tiers: [...sensor.tiers].reverse(), + } + : sensor), + }, + }) + + expect(() => camera(bufferCamera().options)).not.toThrow() + // @ts-expect-error: private access + expect(reordered.bufferRecording).toEqual({ prebuffer: 5000, sensorUUID: SENSOR_UUID, tierId: 1 }) + }) + + it('records the tier its entry marks recorded, the second sensor\'s tier 2, holding that tier while recording is allowed', async () => { + const options = bufferCamera({ prebuffer: 0 }).options + const { delegate } = options.cameraCapabilities.streaming + const marked = camera({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities, + videoSensors: options.cameraCapabilities.videoSensors.map((sensor, index) => index === 1 + ? { + ...sensor, + tiers: sensor.tiers.map(tier => ({ ...tier, recorded: tier.id === 2 })), + } + : sensor), + }, + }) + + marked.constructServices() + marked.configureServices() + handPublishedContext(marked) + marked.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + await settle() + + // @ts-expect-error: private access + expect(marked.bufferRecording).toEqual({ + prebuffer: 0, + sensorUUID: SECOND_VIDEO_SENSOR.uuid.toLowerCase(), + tierId: 2, + }) + expect(streamsOf(delegate).map(({ tier }) => [tier.sensorUUID, tier.id])).toEqual([ + [ + SECOND_VIDEO_SENSOR.uuid.toLowerCase(), + 2, + ], + ]) + }) + + it('reaches nothing a configure advertises, holds or calls from a change to the plugin\'s entries after construction', async () => { + const zones = motionZonesFunction() + const later = motionZonesFunction() + const options = bufferCamera().options + const { delegate } = options.cameraCapabilities.streaming + const sensors = [ + videoSensor(FIRST_VIDEO_SENSOR.uuid, { motionZones: zones }), + videoSensor(SECOND_VIDEO_SENSOR.uuid, { + dimensions: { width: 1280, height: 720 }, + intent: CameraSensorIntent.PACKAGE, + }), + ] + const built = camera({ + ...options, + cameraCapabilities: { ...options.cameraCapabilities, videoSensors: sensors }, + }) + const advertised = (map: CameraControllerServiceMap): unknown[] => Object.keys(map).filter(key => key.startsWith('cameraCapabilities:')).flatMap(key => [ + map[key]!.getCharacteristic(Characteristic.CameraCapabilitiesData).value, + map[key]!.getCharacteristic(Characteristic.SupportedVideoStreamTiers).value, + map[key]!.getCharacteristic(Characteristic.SupportedAudioStreamTiers).value, + ]) + const first = advertised(built.constructServices()) + + built.configureServices() + sensors[0].tiers[0].bitrate = 900 + sensors[0].tiers[1].keepRunning = true + sensors[0].audio.bitrate = 64 + sensors[0].motionZones = later + built.handleControllerRemoved() + + const second = advertised(built.constructServices()) + + built.configureServices() + built.handleFactoryReset() + await settle() + + expect(second).toEqual(first) + expect(delegate.tierDemandStarted).not.toHaveBeenCalled() + expect(zones).toHaveBeenCalled() + expect(later).not.toHaveBeenCalled() + }) + + it('raises its hold once published on a restored camera recording is allowed on, and raises and releases it with each move of recording allowed, a ' + + 'reset and a removal releasing it', async () => { + const saved = camera(bufferCamera().options).constructServices() + + saved.cameraEventRecordingManagement!.getCharacteristic(Characteristic.Active).value = Characteristic.Active.ACTIVE + + const options = bufferCamera().options + const { delegate } = options.cameraCapabilities.streaming + const restored = camera(options) + const active = (): Characteristic => restored.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + const calls = (): number[] => [ + delegate.tierDemandStarted.mock.calls.length, + endsOf(delegate), + ] + + restored.initWithServices(saved) + restored.configureServices() + handPublishedContext(restored) + await settle() + + expect(calls()).toEqual([1, 0]) + expect([streamsOf(delegate)[0].tier.sensorUUID, streamsOf(delegate)[0].tier.id]).toEqual([SENSOR_UUID, 1]) + + active().updateValue(Characteristic.Active.INACTIVE) + await settle() + + expect(calls()).toEqual([1, 1]) + + active().updateValue(Characteristic.Active.ACTIVE) + await settle() + restored.handleFactoryReset() + await settle() + + expect(calls()).toEqual([2, 2]) + + active().updateValue(Characteristic.Active.ACTIVE) + await settle() + restored.handleControllerRemoved() + await settle() + + expect(calls()).toEqual([3, 3]) + }) + + it('keeps its services and its state and gains each sensor\'s webrtc service, raising its configuration number once, when it moves from its ' + + 'plugin\'s recording delegate to its camera buffer', async () => { + // A restart finds the accessory record, the cached accessory and the camera's state the camera saved, before the camera with the block adopts them. + HAPStorage.storage().setItemSync(AccessoryInfo.persistKey(USERNAME), SAVED_RECORD) + + const restored = Accessory.deserialize(savedAccessory()) + const shape = shapeOf(restored) + const buffered = camera(bufferCamera().options) + const sensorUUIDs = [FIRST_VIDEO_SENSOR, SECOND_VIDEO_SENSOR].map(sensor => sensor.uuid.toLowerCase()) + + restored.configureController(buffered) + buffered.deserialize(SAVED_STATE) + await publish(restored) + + // A camera with the block answers views from away, which is why the restore adds each sensor's WebRTC stream service after every service the accessory + // held, with that service's streaming enabled in the camera's state, and the configuration number rises once for them. + expect(restored._accessoryInfo!.getConfigVersion()).toBe(SAVED_RECORD.configVersion + 1) + expect(shapeOf(restored).slice(0, shape.length)).toEqual(shape) + expect(restored.services.slice(shape.length).map(({ subtype, UUID }) => [UUID, subtype])) + .toEqual(sensorUUIDs.map(sensorUUID => [Service.CameraWebRTCStreamManagement.UUID, sensorUUID])) + expect(buffered.serialize()).toEqual({ + ...SAVED_STATE, + webRTCStreamManagements: Object.fromEntries(sensorUUIDs.map(sensorUUID => [ + sensorUUID, + { streamingEnabled: true }, + ])), + microphoneMuted: false, + speakerMuted: false, + }) + }) + + it('adds each segment its recorder sends to the served record, where the HKSV3 recording management\'s open finds it by its place', async () => { + const options = bufferCamera().options + const { delegate } = options.cameraCapabilities.streaming + const buffered = camera(options) + + buffered.constructServices() + buffered.configureServices() + handPublishedContext(buffered) + + const { dataStreamManagement, recordingManagementService } = buffered.recordingManagement! + + recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + + const stream = delegate.tierDemandStarted.mock.calls[0][0] + + stream.write(tierStreamInitialization({ parameterSets: TIER_STREAM_PARAMETER_SETS })) + + for (let index = 0; index < 241; index++) { + stream.write(tierStreamFragment({ + picture: [ + tierPicture({ keyframe: index % 30 === 0 }), + ], + pictureTime: BigInt(index * 3000), + })) + } + + // @ts-expect-error: private access + const feed: ServedRecordings = buffered.servedRecordings + const begin = vi.spyOn(feed, 'begin') + const client = await DataStreamClient.connect(dataStreamManagement) + + client.request(Protocols.DATA_SEND, Topics.OPEN, { + reason: 'motion', + streamId: 1, + target: 'controller', + type: 'ipcamera.recording', + }) + await settle() + + const recording = begin.mock.results[0].value as ServedRecording + const sent = client.events(Protocols.DATA_SEND, Topics.DATA).map(({ packets: [{ data }] }) => data as Buffer) + const fragment = recording.fragment(0)! + + // The camera's default prebuffer of 5 seconds opens the recording at the keyframe of 3 seconds: one segment of 4 seconds stands whole at the open. + expect(recording.run?.initialization).toEqual(sent[0]) + expect([sent.length, recording.length, fragment.timescaleDuration]).toEqual([2, 1, 120n * 3000n]) + expect(feed.fragmentAt(fragment.place, 'start')).toEqual({ fragment, recording }) + }) + + describe('its service, while its accessory is published', () => { + // Each value the services' Status Active moves to from here on, in order, a write that leaves it as it stands recording nothing. + function movesOf(services: readonly Service[]): unknown[] { + const moves: unknown[] = [] + + for (const service of services) { + service.getCharacteristic(Characteristic.StatusActive).on(CharacteristicEventTypes.CHANGE, ({ newValue, oldValue }: CharacteristicChange) => { + if (newValue !== oldValue) { + moves.push(newValue) + } + }) + } + + return moves + } + + it('raises no kept tier and no recorded tier while its accessory is not published, recording and streaming on, leaving each multi-tier status active ' + + 'on, and raises each once its accessory is published', async () => { + const { delegate, options } = bufferCamera({ prebuffer: 0 }) + const made = camera({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities, + videoSensors: options.cameraCapabilities.videoSensors.map((sensor, index) => ({ + ...sensor, + tiers: sensor.tiers.map(tier => ({ ...tier, keepRunning: (index === 0) && (tier.id === 2) })), + })), + }, + }) + const accessory = new Accessory('Camera', ACCESSORY_UUID) + + accessory.configureController(made) + made.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + await settle() + + const unpublished = [ + streamsOf(delegate).length, + statusActiveOf(multiTierOf(accessory)), + ] + + await publish(accessory) + await settle() + + expect(unpublished).toEqual([ + 0, + [true, true], + ]) + expect([ + streamsOf(delegate).map(({ tier }) => [tier.sensorUUID, tier.id]), + statusActiveOf(multiTierOf(accessory)), + ]).toEqual([ + [ + [SENSOR_UUID, 2], + [SENSOR_UUID, 1], + ], + [true, true], + ]) + }) + + it.each([ + [ + 'before its unpublish, the cache holding each true, moving none', + 'before', + [true, true], + [], + ], + [ + 'after its unpublish, as Homebridge\'s shutdown saves it, the cache holding each true, moving none', + 'after', + [true, true], + [], + ], + ] as const)('moves no multi-tier status active to false at a configure after its accessory\'s publish, the accessory saved %s', async (_saved, order, + cached, moved) => { + const first = new Accessory('Camera', ACCESSORY_UUID) + const earlier = camera(bufferCamera().options) + let saved: SerializedAccessory + + first.configureController(earlier) + await publish(first) + first.controllerStorage.save() + + if (order === 'before') { + saved = Accessory.serialize(first) + await first.unpublish() + } else { + await first.unpublish() + saved = Accessory.serialize(first) + } + + first.removeController(earlier) + + // Homebridge restores the cached accessory, publishes it and then configures its camera, which means the listeners stand before the configure. + const restored = Accessory.deserialize(saved) + + await publish(restored) + + const services = multiTierOf(restored) + const held = statusActiveOf(services) + const moves = movesOf(services) + + restored.configureController(camera(bufferCamera().options)) + await settle() + + expect([ + held, + moves, + statusActiveOf(services), + ]).toEqual([ + cached, + moved, + [true, true], + ]) + }) + + it('writes each multi-tier status active false at its first context for a camera its stored state reads off and its cache holds true, configured ' + + 'before its publish, and moves each to true once as the camera is switched on', async () => { + const first = new Accessory('Camera', ACCESSORY_UUID) + const earlier = camera(bufferCamera().options) + const cameraActive = (target: Accessory): Characteristic => target.getService(Service.CameraGlobalOperatingMode)! + .getCharacteristic(Characteristic.HomeKitCameraActive) + + // The accessory is saved with the camera on, and the camera's stored state with it switched off after. + first.configureController(earlier) + await publish(first) + + const saved = Accessory.serialize(first) + + cameraActive(first).setValue(false) + await settle() + first.controllerStorage.save() + await first.unpublish() + first.removeController(earlier) + + const restored = Accessory.deserialize(saved) + const services = multiTierOf(restored) + const cached = statusActiveOf(services) + + restored.configureController(camera(bufferCamera().options)) + await publish(restored) + await settle() + + const stored = statusActiveOf(services) + const moves = movesOf(services) + + cameraActive(restored).setValue(true) + await settle() + + expect([ + cached, + stored, + moves, + ]).toEqual([ + [true, true], + [false, false], + [true, true], + ]) + }) + }) + + describe('its source\'s state', () => { + // The two-sensor camera with its first sensor's tier 2 marked keepRunning, recording its first sensor's tier 1 with no prebuffer, and an accessory + // for it, which the row configures it on, its delegate's starts read by their tiers. + function keptCamera(): { accessory: Accessory, made: CameraController, starts: () => number[] } { + const { delegate, options } = bufferCamera({ prebuffer: 0 }) + const made = camera({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities, + videoSensors: options.cameraCapabilities.videoSensors.map((sensor, index) => ({ + ...sensor, + tiers: sensor.tiers.map(tier => ({ ...tier, keepRunning: (index === 0) && (tier.id === 2) })), + })), + }, + }) + + return { + accessory: new Accessory('Camera', ACCESSORY_UUID), + made, + starts: () => streamsOf(delegate).map(({ tier }) => tier.id), + } + } + + function recordingOn(made: CameraController): void { + made.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(Characteristic.Active.ACTIVE) + } + + it('raises no tier once published for a camera whose source was stated away before its configure, leaving each multi-tier status active on, and ' + + 'raises each tier it holds once its source is stated available', async () => { + const { accessory, made, starts } = keptCamera() + + made.updateSourceState('away') + accessory.configureController(made) + recordingOn(made) + await publish(accessory) + await settle() + + const away = [ + starts(), + statusActiveOf(multiTierOf(accessory)), + ] + + made.updateSourceState('available') + await settle() + + expect([ + away, + [ + starts(), + statusActiveOf(multiTierOf(accessory)), + ], + ]).toEqual([ + [ + [], + [true, true], + ], + [ + [2, 1], + [true, true], + ], + ]) + }) + + it('holds its source stated away through a factory reset, an unpublish and a publish, and a removal and a configure again, raising no tier until ' + + 'its source is stated available', async () => { + const { accessory, made, starts } = keptCamera() + + accessory.configureController(made) + await publish(accessory) + await settle() + made.updateSourceState('away') + made.handleFactoryReset() + await accessory.unpublish() + await publish(accessory) + accessory.removeController(made) + accessory.configureController(made) + await settle() + + const held = starts() + + made.updateSourceState('available') + await settle() + + expect([ + held, + starts().slice(held.length), + ]).toEqual([ + [2], + [2], + ]) + }) + + it('reads recovering stated while its source is away as available, raising each tier it holds and reading each multi-tier status active true', async () => { + const { accessory, made, starts } = keptCamera() + + accessory.configureController(made) + recordingOn(made) + await publish(accessory) + made.updateSourceState('away') + await settle() + + const away = starts().length + + made.updateSourceState('recovering') + await settle() + + expect([ + starts().slice(away), + statusActiveOf(multiTierOf(accessory)), + ]).toEqual([ + [2, 1], + [true, true], + ]) + }) + + it('tells every keeper and then every tier table its source is recovering at a statement of recovering while its source is not away', async () => { + const { accessory, made } = keptCamera() + + accessory.configureController(made) + recordingOn(made) + await publish(accessory) + + const recovering = vi.spyOn(TierKeeper.prototype, 'sourceRecovering') + const tablesRecovering = vi.spyOn(TierTable.prototype, 'sourceRecovering') + // @ts-expect-error: private access + const { every }: { every: readonly TierKeeper[] } = made.keepers + // @ts-expect-error: private access + const tables: TierTable[] = Array.from(made.tierTables.values()) + + made.updateSourceState('recovering') + + // Every keeper is told before any table, which keeps each keeper's gap ahead of its demand's end. + expect([ + recovering.mock.contexts.length, + every.map(keeper => recovering.mock.contexts.includes(keeper)), + tablesRecovering.mock.contexts.length, + tables.map(table => tablesRecovering.mock.contexts.includes(table)), + Math.max(...recovering.mock.invocationCallOrder) < Math.min(...tablesRecovering.mock.invocationCallOrder), + ]).toEqual([ + 2, + [true, true], + 2, + [true, true], + true, + ]) + }) + + it('leaves a camera without the block as it stands at each statement of its source, and throws a TypeError naming the states for a value that is ' + + 'none of them, on a camera without the block and with it', async () => { + const legacy = camera(createCameraControllerOptions()) + const map = legacy.constructServices() + + legacy.configureServices() + + // Every value the camera's services hold, its stored state and a snapshot it serves. + const reading = async (): Promise => [ + Object.values(map).map(service => service?.characteristics.map(({ UUID, value }) => [UUID, value])), + legacy.serialize(), + await legacy.handleSnapshotRequest(100, 100, 'SomeAccessory', ResourceRequestReason.EVENT), + ] + const before = await reading() + + legacy.updateSourceState('away') + + const away = await reading() + + legacy.updateSourceState('available') + + expect([ + away, + await reading(), + ]).toEqual([ + before, + before, + ]) + + for (const made of [ + legacy, + camera(bufferCamera().options), + ]) { + // @ts-expect-error The types refuse a value that is none of the source's states. + const statement = (): void => made.updateSourceState('gone') + + expect(statement).toThrow(TypeError) + expect(statement).toThrow('The source state gone is none of \'available\', \'recovering\' and \'away\'.') + } + }) + + it('moves no motion or occupancy sensor\'s status active and writes none as its source is stated away and then available, its stream services\' ' + + 'status active staying on', async () => { + const made = camera(bufferCamera().options) + const accessory = new Accessory('Camera', ACCESSORY_UUID) + + accessory.configureController(made) + await publish(accessory) + + const sensors = [made.motionService!, made.occupancyService!] + const written: unknown[] = [] + + for (const sensor of sensors) { + sensor.getCharacteristic(Characteristic.StatusActive).on(CharacteristicEventTypes.CHANGE, ({ newValue }: CharacteristicChange) => { + written.push(newValue) + }) + } + + const held = [ + made.recordingManagement!.sensorServices, + sensors.map(sensor => sensor.getCharacteristic(Characteristic.StatusActive).value), + ] + + made.updateSourceState('away') + + const away = statusActiveOf(multiTierOf(accessory)) + + made.updateSourceState('available') + + expect([ + held, + away, + statusActiveOf(multiTierOf(accessory)), + written, + sensors.map(sensor => sensor.getCharacteristic(Characteristic.StatusActive).value), + ]).toEqual([ + [ + sensors, + [true, true], + ], + [true, true], + [true, true], + [], + [true, true], + ]) + }) + + it('raises no kept tier after a start that states its source away, that tier\'s stream ending with no alert and no warning, and raises each kept ' + + 'tier once its source is stated available', async () => { + const { delegate, options } = bufferCamera({ prebuffer: 0 }) + const made = camera({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities, + videoSensors: options.cameraCapabilities.videoSensors.map((sensor, index) => ({ + ...sensor, + tiers: sensor.tiers.map(tier => ({ ...tier, keepRunning: (index === 0) && (tier.id !== 1) })), + })), + }, + }) + const accessory = new Accessory('Camera', ACCESSORY_UUID) + const start = delegate.tierDemandStarted.getMockImplementation()! + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { problems: alerts } = problemsOf(ACCESSORY_UUID) + const starts = (): number[] => streamsOf(delegate).map(({ tier }) => tier.id) + + // The plugin's first start finds its source unreachable and states it away before it answers. + delegate.tierDemandStarted.mockImplementationOnce(async (stream, signal) => { + made.updateSourceState('away') + await start(stream, signal) + }) + accessory.configureController(made) + await publish(accessory) + await settle() + + const away = [ + starts(), + endsOf(delegate, 2), + alerts, + warn.mock.calls, + statusActiveOf(multiTierOf(accessory)), + ] + + made.updateSourceState('available') + await settle() + + expect([ + away, + starts().slice(1), + ]).toEqual([ + [ + [2], + 1, + [], + [], + [true, true], + ], + [2, 3], + ]) + }) + }) + + describe('the tiers its sensors keep running', () => { + interface Keeping { + readonly camera: CameraController + readonly delegate: ScriptedTierDelegate + // The problems heard on the channel of the published context's accessory. + readonly alerts: CameraProblem[] + // Writes Recording Active, which with HomeKit Camera Active on decides whether recording is allowed, and the global Streaming Enabled, which + // with it decides whether streaming is allowed. + recording: (active: boolean) => void + streaming: (enabled: boolean) => void + // Each demand's start and end the delegate heard, as its sensor, the first or the second, and its tier, and the span of the first sensor's tier. + starts: () => [string, number][] + ends: () => [string, number][] + span: (tierId: number) => number + } + + // The two-sensor camera recording the first sensor's best tier, tier 1, each sensor's tiers in the list at its index marked keepRunning, constructed, + // configured and handed a published context, whose accessory's problems it reads, its global Streaming Enabled turned off before the configure where a + // row asks. + function keeping(lists: readonly (number[] | undefined)[], { streamingEnabled = true }: { streamingEnabled?: boolean } = {}): Keeping { + const { delegate, options } = bufferCamera() + const kept = camera({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities, + videoSensors: options.cameraCapabilities.videoSensors.map((sensor, index) => ({ + ...sensor, + tiers: sensor.tiers.map(tier => ({ ...tier, keepRunning: lists[index]?.includes(tier.id) ?? false })), + })), + }, + }) + const { problems: alerts } = problemsOf(NUMBERED_ACCESSORY_UUID) + const map = kept.constructServices() + const named = (streams: readonly TierStream[]): [string, number][] => streams.map(({ tier }) => [ + tier.sensorUUID === SENSOR_UUID + ? 'first' + : 'second', + tier.id, + ]) + + if (!streamingEnabled) { + map['cameraCapabilities:globalOperatingMode']!.updateCharacteristic(Characteristic.StreamingEnabled, false) + } + + kept.configureServices() + handPublishedContext(kept) + + return { + alerts, + camera: kept, + delegate, + ends: () => named(endedOf(delegate)), + recording: (active) => { + kept.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active).updateValue(active + ? Characteristic.Active.ACTIVE + : Characteristic.Active.INACTIVE) + }, + // @ts-expect-error: private access + span: tierId => kept.tierTables.get(SENSOR_UUID)!.videoTiers.get(tierId)!.buffer.span, + starts: () => named(streamsOf(delegate)), + streaming: (enabled) => { + map['cameraCapabilities:globalOperatingMode']!.updateCharacteristic(Characteristic.StreamingEnabled, enabled) + }, + } + } + + it('holds each tier marked keepRunning once published while streaming is allowed, with one tierDemandStarted, releases it when streaming stops ' + + 'being allowed and raises it again when it returns', async () => { + const { ends, starts, streaming } = keeping([ + [2], + [3], + ]) + + await settle() + + expect([ + starts(), + ends(), + ]).toEqual([ + [ + ['first', 2], + ['second', 3], + ], + [], + ]) + + streaming(false) + await settle() + + expect([ + starts().length, + ends(), + ]).toEqual([ + 2, + [ + ['first', 2], + ['second', 3], + ], + ]) + + streaming(true) + await settle() + + expect([ + starts().slice(2), + ends().length, + ]).toEqual([ + [ + ['first', 2], + ['second', 3], + ], + 2, + ]) + }) + + it('answers the first sensor\'s newest keyframe with no sensor named and the named sensor\'s in any case, and nothing for a sensor the camera does ' + + 'not have, a camera not configured and a camera without the block', async () => { + const { camera: kept, delegate } = keeping([ + [2], + [3], + ]) + + await settle() + + // Each sensor's kept tier is written a keyframe of octets of its own, which the movie's one sample, its last octets, carries. + const keyframes = new Map(streamsOf(delegate).map((stream) => { + const keyframe = tierPicture({ + inBand: true, + keyframe: true, + octets: stream.tier.sensorUUID === SENSOR_UUID + ? 120 + : 140, + }) + + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [keyframe], + })) + + return [stream.tier.sensorUUID, keyframe.data] + })) + const tail = (movie: Buffer, keyframe: Buffer): Buffer => movie.subarray(movie.length - keyframe.length) + const first = keyframes.get(SENSOR_UUID)! + const second = keyframes.get(SECOND_VIDEO_SENSOR.uuid.toLowerCase())! + const legacy = camera(createCameraControllerOptions()) + + legacy.constructServices() + legacy.configureServices() + + expect(tail(kept.latestKeyframe()!.movie, first)).toEqual(first) + expect(tail(kept.latestKeyframe(SECOND_VIDEO_SENSOR.uuid.toUpperCase())!.movie, second)).toEqual(second) + expect(kept.latestKeyframe('C0000003-0000-4000-8000-000000000003')).toBeUndefined() + expect(camera(bufferCamera().options).latestKeyframe()).toBeUndefined() + expect(legacy.latestKeyframe()).toBeUndefined() + }) + + it('raises none of the tiers marked keepRunning at a configure while streaming is not allowed, and each once streaming is allowed', async () => { + const { ends, starts, streaming } = keeping([ + [2], + [3], + ], { streamingEnabled: false }) + + await settle() + + expect([ + starts(), + ends(), + ]).toEqual([ + [], + [], + ]) + + streaming(true) + await settle() + + expect([ + starts(), + ends(), + ]).toEqual([ + [ + ['first', 2], + ['second', 3], + ], + [], + ]) + }) + + it('takes one keeper for the recorded tier marked keepRunning too: one demand, one join and one set of alerts, its buffer spanning the prebuffer ' + + 'while recording is allowed and nothing while streaming alone holds it', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { alerts, delegate, ends, recording, span, starts } = keeping([ + [1], + ]) + const readings: number[][] = [] + const read = (): void => { + readings.push([ + starts().length, + ends().length, + delegate.tierDemandStarted.mock.calls[0][0].statistics().consumers, + span(1), + ]) + } + + await settle() + read() + recording(true) + await settle() + read() + recording(false) + await settle() + read() + recording(true) + await settle() + read() + delegate.tierDemandStarted.mock.calls[0][0].fail('The camera went away.') + + expect(readings).toEqual([ + [1, 0, 1, 0], + [1, 0, 1, 5000], + [1, 0, 1, 0], + [1, 0, 1, 5000], + ]) + // The stream's failure is the tier table's problem and the keeper's one tier-failed follows it, each on the camera's channel: the console hears + // neither. + expect([ + alerts.map(({ kind, tierId }: Partial>) => [kind, tierId]), + warn.mock.calls.length, + ]).toEqual([ + [ + ['stream-failed', 1], + ['tier-failed', 1], + ], + 0, + ]) + }) + + it('holds each listed tier again after a factory reset while streaming is allowed, where the reset moved streaming allowed and where it did not, ' + + 'leaves the recorded tier released, and raises no start and no tier-failed at a removal', async () => { + const { alerts, camera: kept, ends, recording, starts, streaming } = keeping([ + [2], + [3], + ]) + + recording(true) + await settle() + + expect(starts()).toEqual([ + ['first', 2], + ['second', 3], + ['first', 1], + ]) + + // Streaming is allowed before the reset and after it: of what the policy tells its listeners the reset moves recording allowed alone, which falls + // to its default of off. + kept.handleFactoryReset() + await settle() + + expect([ + starts().slice(3), + ends(), + ]).toEqual([ + [ + ['first', 2], + ['second', 3], + ], + [ + ['first', 1], + ['first', 2], + ['second', 3], + ], + ]) + + // Streaming is not allowed before the reset, which moves it back to allowed. + streaming(false) + await settle() + kept.handleFactoryReset() + await settle() + + expect([ + starts().slice(5), + ends().length, + ]).toEqual([ + [ + ['first', 2], + ['second', 3], + ], + 5, + ]) + + kept.handleControllerRemoved() + await settle() + + expect([ + starts().length, + ends().length, + alerts.filter(({ kind }) => kind === 'tier-failed'), + ]).toEqual([7, 7, []]) + }) + + it('calls both cleanups registered on a tier only its keeper holds before that tier\'s next tierDemandStarted, at a factory reset that ends the tier ' + + 'and raises it again in one call', async () => { + const { camera: kept, delegate, starts } = keeping([ + [2], + ]) + + await settle() + + // The start registered its disposable, and a second cleanup is registered on its stream once it has started, as at a reconnect. The release + // calls the newer cleanup and then the older. + const [stream] = streamsOf(delegate) + const newer = vi.fn<() => void>() + + stream.defer(newer) + kept.handleFactoryReset() + + const [, nextStart] = delegate.tierDemandStarted.mock.invocationCallOrder + + expect([ + starts(), + newer.mock.invocationCallOrder[0] < nextStart, + delegate.disposals.get(stream)!.mock.invocationCallOrder[0] < nextStart, + ]).toEqual([ + [ + ['first', 2], + ['first', 2], + ], + true, + true, + ]) + }) + + it('releases each keeper at a factory reset ahead of its table\'s withdrawal', async () => { + const { camera: kept, ends, starts } = keeping([ + [2], + [3], + ]) + + await settle() + + const held = starts().length + const release = vi.spyOn(TierKeeper.prototype, 'release') + const withdraw = vi.spyOn(TierTable.prototype, 'withdraw') + + kept.handleFactoryReset() + + const firstWithdrawal = Math.min(...withdraw.mock.invocationCallOrder) + + expect([held, ends().length, withdraw.mock.calls.length]).toEqual([2, 2, 2]) + expect(release.mock.calls.map(([reason], index) => [reason, release.mock.invocationCallOrder[index] < firstWithdrawal])).toEqual([ + ['recording', true], + ['kept-running', true], + ['kept-running', true], + ['kept-running', true], + ]) + }) + }) + + it('warns once of a stream past twice its tier\'s peak for a camera given strict, writing no debug line', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout', 'performance'], + }) + onTestFinished(() => { + vi.useRealTimers() + }) + + const lines = captureDebug('HAP-NodeJS:Camera:Tier') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { options, stream } = bufferCamera() + const strict = camera({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities, + strict: true, + }, + }) + + strict.constructServices() + strict.configureServices() + + // The first sensor's tier 1, whose peak is its class's maximum of 1800 kbps, is held by a viewer of the live releases and written a keyframe alone of + // 625000 octets, read as a second long at 5000 kbps, which a viewer joining once it is released opens on. + // @ts-expect-error: private access + const table: TierTable = strict.tierTables.get(SENSOR_UUID) + const tier = table.videoTiers.get(1)! + const holder = { + tierFailed: (): void => undefined, + } + const consumer = { + take: (): void => undefined, + } + const live = table.joinFrames(tier, 'video', holder, consumer) + + stream().write(tierStreamInitialization()) + stream().write(tierStreamFragment({ + picture: [ + tierPicture({ inBand: true, keyframe: true, octets: 625000 }), + ], + })) + await vi.advanceTimersByTimeAsync(50) + + const opening = table.joinFrames(tier, 'video', holder, consumer) + + await vi.advanceTimersByTimeAsync(10) + opening.release() + live.release() + + expect([ + warn.mock.calls, + lines, + ]).toEqual([ + [ + [`The stream of the video tier 1 of the video sensor "${SENSOR_UUID}" runs at 5000 kbps over the stretch a view opens on, read over a second at least, ` + + 'past twice the peak of 1800 kbps its tier advertises.'], + ], + [], + ]) + }) + + describe('its problems', () => { + // A problem the camera's reporter raises at the step named, its sentence naming the step. + function raise(reporter: CameraReporter, step: string): void { + reporter.problem({ kind: 'value-refused', level: 'warning', sentence: `The synthetic value was refused at the ${step}.` }) + } + + // The reporter the camera holds as the row reads it. + function reporterOf(made: CameraController): CameraReporter { + // @ts-expect-error: private access + return made.reporter + } + + it('reports each problem on the channel of the accessory it is configured on through its publish, its unpublish and its destroy, prints its bare ' + + 'sentence before its configure and once removed, and reports on the channel of the accessory it is configured on next', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const first = new Accessory('Camera', ACCESSORY_UUID) + const second = new Accessory('Camera', uuid.generate('camera buffer recording, configured again')) + const heard: string[] = [] + const subscriptions = [first, second].map(({ UUID }, index) => onCameraProblem(UUID, ({ accessoryUUID, sentence }) => { + heard.push(`${['first', 'second'][index]} ${accessoryUUID === UUID} ${sentence}`) + })) + const made = camera(bufferCamera().options) + + onTestFinished(() => { + for (const subscription of subscriptions) { + subscription[Symbol.dispose]() + } + }) + raise(reporterOf(made), 'construction') + first.configureController(made) + raise(reporterOf(made), 'configure') + await publish(first) + raise(reporterOf(made), 'publish') + await first.unpublish() + raise(reporterOf(made), 'unpublish') + await first.destroy() + raise(reporterOf(made), 'destroy') + first.removeController(made) + raise(reporterOf(made), 'removal') + second.configureController(made) + raise(reporterOf(made), 'second configure') + await settle() + + expect(heard).toEqual([ + 'first true The synthetic value was refused at the configure.', + 'first true The synthetic value was refused at the publish.', + 'first true The synthetic value was refused at the unpublish.', + 'first true The synthetic value was refused at the destroy.', + 'second true The synthetic value was refused at the second configure.', + ]) + expect(warn.mock.calls.filter(([line]) => String(line).startsWith('The synthetic'))).toEqual([ + ['The synthetic value was refused at the construction.'], + ['The synthetic value was refused at the removal.'], + ]) + }) + + it('keeps the accessory a part of a removed configuration reports for, after the removal and once the camera is configured on another accessory', () => { + const first = new Accessory('Camera', ACCESSORY_UUID) + const second = new Accessory('Camera', uuid.generate('camera buffer recording, configured again')) + const { problems } = problemsOf(first.UUID) + const made = camera(bufferCamera().options) + + first.configureController(made) + + // @ts-expect-error: private access + const held: CameraReporter = made.bufferRecorder.options.reporter + + first.removeController(made) + raise(held, 'removal') + second.configureController(made) + raise(held, 'second configure') + + expect(problems.map(({ accessoryUUID, sentence }) => [accessoryUUID, sentence])).toEqual([ + [first.UUID, 'The synthetic value was refused at the removal.'], + [first.UUID, 'The synthetic value was refused at the second configure.'], + ]) + }) + + describe('a restore before its first context', () => { + // The opening of the sentence of the problem the first sensor's saved zones raise at the restore. + const REFUSED_ZONES = `The saved motion zones of video sensor ${SENSOR_UUID} cannot be restored because` + + /* Stores a camera record whose saved zones the first sensor refuses, since they are no canonical base64, under the accessory, which its controller + * storage loads at its publish. The camera's configure on the published accessory restores them before the accessory hands it its first + * context, as Homebridge configures a cached accessory's camera. + */ + function storeRefusedZones(): void { + const state: CameraControllerState = { + motionZonesManagements: { + [SENSOR_UUID]: { active: true, zones: 'not canonical base64' }, + }, + streamManagements: [], + } + + HAPStorage.storage().setItemSync(ControllerStorage.persistKey(USERNAME), { + accessories: { + [ACCESSORY_UUID]: [ + { + controllerData: { + data: state, + }, + type: 'camera', + }, + ], + }, + }) + } + + // Every problem a subscriber by the accessory's UUID hears while the row runs. + function subscribed(): CameraProblem[] { + const heard: CameraProblem[] = [] + const subscription = onCameraProblem(ACCESSORY_UUID, problem => heard.push(problem)) + + onTestFinished(() => { + subscription[Symbol.dispose]() + }) + + return heard + } + + it.each([ + ['a subscriber by the accessory\'s UUID', true], + ['no subscriber', false], + ] as const)('reports the problem of saved zones its restore refuses as its accessory hands it its first context, with %s', async (_, subscribing) => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const heard = subscribing + ? subscribed() + : [] + const accessory = new Accessory('Camera', ACCESSORY_UUID) + + storeRefusedZones() + await publish(accessory) + accessory.configureController(camera(twoSensorCameraOptions({ + first: motionZonesFunction(), + }))) + await settle() + + // The camera's name, as its accessory's Accessory Information carries it once published. + const name = accessory.getService(Service.AccessoryInformation)!.getCharacteristic(Characteristic.Name).value + const printed = warn.mock.calls.map(([line]) => String(line)).filter(line => line.includes(REFUSED_ZONES)) + + expect(heard.map(({ accessoryUUID, kind, level, sentence, ...fields }) => ({ + accessoryUUID, + fields, + kind, + level, + refused: sentence.startsWith(REFUSED_ZONES), + }))).toEqual(subscribing + ? [ + { + accessoryUUID: ACCESSORY_UUID, + fields: { sensorUUID: SENSOR_UUID }, + kind: 'value-refused', + level: 'warning', + refused: true, + }, + ] + : []) + expect(printed.map(line => line.startsWith(`[${String(name)}] ${REFUSED_ZONES}`))).toEqual(subscribing + ? [] + : [true]) + }) + + it('reports the refusal of its saved zones and then the failure of its zones function at that restore, in that order', async () => { + const heard = subscribed() + const accessory = new Accessory('Camera', ACCESSORY_UUID) + const motionZones = motionZonesFunction().mockRejectedValue(new Error('The synthetic zones function failed.')) + + storeRefusedZones() + await publish(accessory) + accessory.configureController(camera(twoSensorCameraOptions({ + first: motionZones, + }))) + await settle() + + expect(motionZones.mock.calls.map(([, reason]) => reason)).toEqual(['restore']) + expect(heard.map(({ kind, sentence }) => ({ + kind, + refused: sentence.startsWith(REFUSED_ZONES), + }))).toEqual([ + { kind: 'value-refused', refused: true }, + { kind: 'plugin-failure', refused: false }, + ]) + }) + }) + }) + + describe('the debug events of its settings', () => { + // A hub's write, which carries a connection: each change reads its reason as a write. + const HUB = {} as HAPConnection + + it.each([ + { + before: Characteristic.Active.INACTIVE, + field: 'recordingActive', + setting: 'recording\'s Active on', + value: Characteristic.Active.ACTIVE, + }, + { + before: Characteristic.Active.ACTIVE, + field: 'recordingActive', + setting: 'recording\'s Active off', + value: Characteristic.Active.INACTIVE, + }, + { + before: Characteristic.HomeKitCameraActive.ON, + field: 'homeKitCameraActive', + setting: 'HomeKit Camera Active off', + value: Characteristic.HomeKitCameraActive.OFF, + }, + ] as const)('publishes one debug event and calls its listener once for a hub\'s write of $setting', async ({ before, field, value }) => { + const made = camera(bufferCamera().options) + const accessory = new Accessory('Camera', ACCESSORY_UUID) + const heard: OperatingModeChange[] = [] + + accessory.configureController(made) + + const setting = (field === 'recordingActive') + ? made.recordingManagement!.recordingManagementService.getCharacteristic(Characteristic.Active) + : accessory.getService(Service.CameraGlobalOperatingMode)!.getCharacteristic(Characteristic.HomeKitCameraActive) + + setting.updateValue(before) + + const events = captureDebugEvents('HAP-NodeJS:Camera:Controller') + + made.on(CameraControllerEvents.OPERATING_MODE_CHANGED, change => heard.push(change)) + await setting.handleSetRequest(value, HUB) + + const change = { field, reason: 'write', value: value === 1 } + + expect(events.filter(({ kind }) => kind === 'operating-mode-change')).toEqual([ + { + ...change, + accessoryUUID: ACCESSORY_UUID, + kind: 'operating-mode-change', + sentence: `The camera's ${field} reads ${String(change.value)}, its reason write.`, + }, + ]) + expect(heard).toEqual([change]) + }) + + it('publishes one debug event and calls its listener once for a hub\'s write of a multi-tier stream service\'s streaming enabled', async () => { + const made = camera(bufferCamera().options) + const accessory = new Accessory('Camera', ACCESSORY_UUID) + const heard: StreamingEnabledChange[] = [] + + accessory.configureController(made) + + const events = captureDebugEvents('HAP-NodeJS:Camera:Controller') + + made.on(CameraControllerEvents.STREAMING_ENABLED_CHANGED, change => heard.push(change)) + await multiTierOf(accessory)[0].getCharacteristic(Characteristic.StreamingEnabled).handleSetRequest(false, HUB) + + const change = { + reason: 'write', + sensorUUID: SENSOR_UUID, + value: false, + where: 'home', + } + + expect(events.filter(({ kind }) => kind === 'streaming-enabled-change')).toEqual([ + { + ...change, + accessoryUUID: ACCESSORY_UUID, + kind: 'streaming-enabled-change', + sentence: `Streaming Enabled for views at home of the video sensor ${SENSOR_UUID} reads false, its reason write.`, + }, + ]) + expect(heard).toEqual([change]) + }) + }) + + describe('a plugin\'s set handler on a setting', () => { + // A hub's write, which carries a connection. + const HUB = {} as HAPConnection + + it.each([ + { + field: 'operatingModeIndicator', + held: 1, + setting: 'the operating mode indicator', + type: Characteristic.CameraOperatingModeIndicator, + written: 0, + }, + { + field: 'nightVision', + held: false, + setting: 'night vision', + type: Characteristic.NightVision, + written: true, + }, + ] as const)('refuses a hub\'s write of $setting before the camera stores it, at each service that carries it', async ({ field, held, type, written }) => { + const made = camera(bufferCamera().options) + const accessory = new Accessory('Camera', ACCESSORY_UUID) + const heard: OperatingModeChange[] = [] + + accessory.configureController(made) + + // The setting on the camera-wide service and on the recording camera's operating mode, where a plugin that adds it to both puts its handler on each. + const places = [ + accessory.getService(Service.CameraGlobalOperatingMode)!, + made.recordingManagement!.operatingModeService, + ].map(service => service.getCharacteristic(type)) + const refuse = vi.fn((): void => { + throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + }) + + for (const place of places) { + place.onSet(refuse) + } + + const events = captureDebugEvents('HAP-NodeJS:Camera:Controller') + const saved = made.serialize() + + made.on(CameraControllerEvents.OPERATING_MODE_CHANGED, change => heard.push(change)) + + for (const place of places) { + await expect(place.handleSetRequest(written, HUB)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + expect(refuse).toHaveBeenCalledTimes(places.length) + expect(places.map(place => place.value)).toEqual(places.map(() => held)) + expect(heard).toEqual([]) + expect(events.filter(({ kind }) => kind === 'operating-mode-change')).toEqual([]) + expect(made.serialize()).toEqual(saved) + + // A write the handler lets through is stored and told once, and the camera's copy to the other service calls no handler. + refuse.mockImplementation(() => {}) + await places[0].handleSetRequest(written, HUB) + + expect(refuse).toHaveBeenCalledTimes(places.length + 1) + expect(places.map(place => place.value)).toEqual(places.map(() => written)) + expect(heard).toEqual([ + { + field, + reason: 'write', + value: Boolean(written), + }, + ]) + }) + }) + + describe('the snapshot function', () => { + // The sentences of the function's warnings, and the function's lines as the camera prints them where nothing subscribes, opened by the Name of the + // accessory the camera holds. + const SLOW_SENTENCE = 'The image snapshot function for the given accessory is slow to respond! See https://homebridge.io/w/JtMGR for more info.' + const SILENT_SENTENCE = 'The image snapshot function for the given accessory didn\'t respond at all! See https://homebridge.io/w/JtMGR for more info.' + const SLOW = `[Camera] ${SLOW_SENTENCE}` + const SILENT = `[Camera] ${SILENT_SENTENCE}` + const NO_PICTURE = '[Camera] The snapshot function answered no picture, and the snapshot failed.' + + afterEach(() => { + vi.useRealTimers() + }) + + interface Snapshotting { + readonly camera: CameraController + readonly map: CameraControllerServiceMap + readonly snapshot: ReturnType + readonly streamDelegate: ScriptedTierDelegate + } + + // The two-sensor camera with the block, constructed, configured and handed a published context, its snapshot function a mock answering the mock + // picture, and the first sensor's tiers in the list given marked keepRunning. + function snapshotting(kept: readonly number[] = []): Snapshotting { + const { delegate: streamDelegate, options } = bufferCamera() + const snapshot = snapshotFunction() + const made = camera({ + ...options, + cameraCapabilities: { + ...options.cameraCapabilities, + snapshot, + videoSensors: options.cameraCapabilities.videoSensors.map((sensor, index) => ({ + ...sensor, + tiers: sensor.tiers.map(tier => ({ ...tier, keepRunning: (index === 0) && kept.includes(tier.id) })), + })), + }, + }) + const map = made.constructServices() + + made.configureServices() + handPublishedContext(made) + + return { + camera: made, + map, + snapshot, + streamDelegate, + } + } + + // A snapshot's outcome as the row reads it, its picture or the status it was refused or failed with, each pushed as it settles. + function outcomes(pending: Promise, settled: unknown[]): void { + pending.then(picture => settled.push(picture), status => settled.push(status)) + } + + it('answers a resource request through its function for the first sensor, handed the size, the reason, the newest keyframe and a signal, refused ' + + 'while streaming is not allowed or the request\'s kind is switched off, where a legacy camera meets its legacy gate alone', async () => { + const { camera: made, map, snapshot, streamDelegate } = snapshotting([2]) + + await settle() + + const [stream] = streamsOf(streamDelegate, 2) + + stream.write(tierStreamInitialization()) + stream.write(tierStreamFragment({ + picture: [ + tierPicture({ inBand: true, keyframe: true, octets: 120 }), + ], + })) + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).resolves.toBe(MOCK_IMAGE) + + expect(snapshot).toHaveBeenCalledExactlyOnceWith({ + height: 360, + keyframe: { + age: expect.any(Number), + height: 36, + movie: made.latestKeyframe()!.movie, + width: 64, + }, + reason: ResourceRequestReason.EVENT, + sensorUUID: SENSOR_UUID, + width: 640, + }, expect.any(AbortSignal)) + + map['cameraCapabilities:globalOperatingMode']!.updateCharacteristic(Characteristic.StreamingEnabled, false) + + for (const reason of [undefined, ResourceRequestReason.PERIODIC, ResourceRequestReason.EVENT]) { + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', reason)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + map['cameraCapabilities:globalOperatingMode']!.updateCharacteristic(Characteristic.StreamingEnabled, true) + made.recordingManagement!.operatingModeService.setCharacteristic(Characteristic.EventSnapshotsActive, false) + made.recordingManagement!.operatingModeService.setCharacteristic(Characteristic.PeriodicSnapshotsActive, false) + + for (const reason of [undefined, ResourceRequestReason.PERIODIC, ResourceRequestReason.EVENT]) { + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', reason)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + expect(snapshot).toHaveBeenCalledTimes(1) + + // A legacy camera never reads whether its policy allows streaming, and one whose policy reads false is served as its legacy gate lets it. + const legacy = camera(createCameraControllerOptions()) + + legacy.constructServices() + legacy.configureServices() + // @ts-expect-error: private access + vi.spyOn(legacy.operatingMode, 'streamingAllowed').mockReturnValue(false) + + await expect(legacy.handleSnapshotRequest(360, 640, 'Front Door')).resolves.toBe(MOCK_IMAGE) + }) + + it('refuses a snapshot with HAP status -70412 and over the data stream as not allowed while the global streaming enabled is off, with -70402 and ' + + 'as busy while its source is stated away, and with -70412 and as not allowed while both hold, the user\'s switch read first, calling no snapshot ' + + 'function and publishing one debug event of each open\'s refusal', async () => { + const { camera: made, map, snapshot } = snapshotting() + const events = captureDebugEvents('HAP-NodeJS:Camera:RecordingManagement') + const client = await DataStreamClient.connect(made.recordingManagement!.dataStreamManagement) + const globalOperatingMode = map['cameraCapabilities:globalOperatingMode']! + + // A data stream open of a snapshot under the given stream ID, answered before the row moves the camera on, and the reason its answer carries. + async function opened(streamId: number): Promise<{ reason?: number, status?: number }> { + const id = client.request(Protocols.DATA_SEND, Topics.OPEN, { + metadata: { imageHeight: 360, imageWidth: 640, reason: ResourceRequestReason.EVENT }, + reason: 'snapshot', + streamId, + target: 'controller', + type: 'ipcamera.snapshot', + }) + + await settle() + + const written = client.answerTo(id) + + return { reason: written?.message.status, status: written?.header.status } + } + + globalOperatingMode.updateCharacteristic(Characteristic.StreamingEnabled, false) + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(await opened(2)).toEqual({ reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + + globalOperatingMode.updateCharacteristic(Characteristic.StreamingEnabled, true) + made.updateSourceState('away') + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + expect(await opened(3)).toEqual({ reason: HDSProtocolSpecificErrorReason.BUSY, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + + globalOperatingMode.updateCharacteristic(Characteristic.StreamingEnabled, false) + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', ResourceRequestReason.EVENT)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + expect(await opened(4)).toEqual({ reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }) + expect(client.events(Protocols.DATA_SEND, Topics.DATA)).toEqual([]) + expect(snapshot).not.toHaveBeenCalled() + expect(events).toStrictEqual([ + [2, 'snapshot-open-not-allowed', 'as snapshots are not allowed.'], + [3, 'snapshot-open-out-of-service', 'as the camera is out of service.'], + [4, 'snapshot-open-not-allowed', 'as snapshots are not allowed.'], + ].map(([streamId, kind, ending]) => ({ + accessoryUUID: NUMBERED_ACCESSORY_UUID, + kind, + remoteAddress: events[0]?.remoteAddress, + sentence: `[HDS ${String(events[0]?.remoteAddress)}] Rejecting DATA_SEND OPEN of snapshot stream ${streamId} ${ending}`, + streamId, + }))) + }) + + it.each([ + { + off: 'event', + refused: ResourceRequestReason.EVENT, + served: ResourceRequestReason.PERIODIC, + setting: 'event snapshots active', + switched: Characteristic.EventSnapshotsActive, + }, + { + off: 'periodic', + refused: ResourceRequestReason.PERIODIC, + served: ResourceRequestReason.EVENT, + setting: 'periodic snapshots active', + switched: Characteristic.PeriodicSnapshotsActive, + }, + ])('refuses with HAP status -70412 a resource request of $off snapshots while $setting is off, one naming no reason and one naming neither kind, ' + + 'and as not allowed a data stream open of that kind and one naming no reason, serving the other kind on each path and publishing one debug event ' + + 'naming the switched off kind for each refusal', async ({ off, refused, served, switched }) => { + const { camera: made, snapshot } = snapshotting() + + made.recordingManagement!.operatingModeService.setCharacteristic(switched, false) + + // The capture begins after the switch-off: it reads every event the channel publishes from there on. + const events = captureDebugEvents('HAP-NodeJS:Camera:Controller') + + // A resource request's reason reaches the controller as the request carries it, and one naming neither kind is read as naming none. + for (const reason of [refused, undefined, 2 as ResourceRequestReason]) { + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', reason)).rejects.toBe(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + } + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', served)).resolves.toBe(MOCK_IMAGE) + + const client = await DataStreamClient.connect(made.recordingManagement!.dataStreamManagement) + const size = { imageHeight: 360, imageWidth: 640 } + + // The data stream's opens name the switched off kind, no reason and the other kind in their metadata. + const opens = [ + { ...size, reason: refused }, + size, + { ...size, reason: served }, + ].map((metadata, index) => client.request(Protocols.DATA_SEND, Topics.OPEN, { + metadata, + reason: 'snapshot', + streamId: index + 2, + target: 'controller', + type: 'ipcamera.snapshot', + })) + + await settle() + + expect(opens.map(id => client.answerTo(id)).map(written => ({ reason: written?.message.status, status: written?.header.status }))).toEqual([ + { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + { reason: HDSProtocolSpecificErrorReason.NOT_ALLOWED, status: HDSStatus.PROTOCOL_SPECIFIC_ERROR }, + { reason: HDSStatus.SUCCESS, status: HDSStatus.SUCCESS }, + ]) + expect(snapshot.mock.calls.map(([{ reason }]) => reason)).toEqual([served, served]) + // The resource requests name their accessory as the request hands it, and the data stream's opens by the Name the camera's context holds. + expect(events).toStrictEqual([ + 'Front Door', + 'Front Door', + 'Front Door', + 'Camera', + 'Camera', + ].map(accessoryName => ({ + accessoryName, + accessoryUUID: NUMBERED_ACCESSORY_UUID, + kind: 'snapshot-switched-off', + sentence: `[${accessoryName}] Rejecting snapshot as ${off} snapshots are switched off.`, + switchedOff: off, + }))) + }) + + it('refuses a resource request of a width or height of 0, -1, 1.5 or NaN as an invalid value without calling its function, where a legacy camera ' + + 'hands the same request to its handler', async () => { + const { camera: made, snapshot } = snapshotting() + const delegate = new MockDelegate() + const legacyHandler = vi.spyOn(delegate, 'handleSnapshotRequest') + const legacy = camera(createCameraControllerOptions(mockRecordingOptions, mockStreamingOptions, 2, delegate)) + const sizes = [0, -1, 1.5, Number.NaN].flatMap(size => [ + [size, 360], + [640, size], + ]) + + legacy.constructServices() + legacy.configureServices() + + for (const [width, height] of sizes) { + await expect(made.handleSnapshotRequest(height, width, 'Front Door')).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + await expect(legacy.handleSnapshotRequest(height, width, 'Front Door')).resolves.toBe(MOCK_IMAGE) + } + + expect(snapshot).not.toHaveBeenCalled() + expect(legacyHandler.mock.calls.map(([{ height, width }]) => [width, height])).toEqual(sizes) + }) + + it('publishes its refusal of a size no picture has as a debug event carrying its accessory\'s UUID', async () => { + const { camera: made } = snapshotting() + const events = captureDebugEvents('HAP-NodeJS:Camera:Controller') + + await expect(made.handleSnapshotRequest(360, 0, 'Front Door')).rejects.toBe(HAPStatus.INVALID_VALUE_IN_REQUEST) + expect(events).toStrictEqual([ + { + accessoryName: 'Front Door', + accessoryUUID: NUMBERED_ACCESSORY_UUID, + kind: 'snapshot-size-refused', + sentence: '[Front Door] Rejecting snapshot as it names no valid picture size.', + }, + ]) + }) + + it('fails a snapshot whose function throws or rejects with its HapStatusError\'s status or a communication failure, logging each once, and one whose ' + + 'function answers no picture with a communication failure, writing its sentence once and the answer nowhere', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { camera: made, snapshot } = snapshotting() + + snapshot.mockRejectedValueOnce(new HapStatusError(HAPStatus.RESOURCE_BUSY)) + snapshot.mockRejectedValueOnce(new Error('The camera has no picture.')) + snapshot.mockImplementationOnce(() => { + throw new Error('The camera is unreachable.') + }) + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door')).rejects.toBe(HAPStatus.RESOURCE_BUSY) + await expect(made.handleSnapshotRequest(360, 640, 'Front Door')).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await expect(made.handleSnapshotRequest(360, 640, 'Front Door')).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await settle() + + expect(error.mock.calls).toEqual([ + [ + expect.stringMatching(/^\[Camera\] The snapshot function failed: HapStatusError: HAP Status Error: -70403/), + ], + [ + expect.stringMatching(/^\[Camera\] The snapshot function failed: Error: The camera has no picture\./), + ], + [ + expect.stringMatching(/^\[Camera\] The snapshot function failed: Error: The camera is unreachable\./), + ], + ]) + + error.mockClear() + + const answers = [ + 'a picture', + Buffer.alloc(0), + undefined, + ] + + for (const answer of answers) { + snapshot.mockResolvedValueOnce(answer as Buffer) + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door')).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + await settle() + + expect(error.mock.calls).toEqual([ + [NO_PICTURE], + [NO_PICTURE], + [NO_PICTURE], + ]) + }) + + it('warns of a function that never settles at 8 seconds and fails its snapshot as timed out at 25, aborting its signal then, dropping its later ' + + 'answer and logging no later rejection', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { camera: made, snapshot } = snapshotting() + const answers = [ + deferred(), + deferred(), + ] + const settled: unknown[] = [] + + for (const answer of answers) { + snapshot.mockImplementationOnce(async () => await answer.promise) + outcomes(made.handleSnapshotRequest(360, 640, 'Front Door'), settled) + } + + const signals = snapshot.mock.calls.map(([, signal]) => signal) + + await vi.advanceTimersByTimeAsync(7999) + + expect(warn).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(1) + + expect(warn.mock.calls).toEqual([ + [SLOW], + [SLOW], + ]) + + await vi.advanceTimersByTimeAsync(16999) + + expect(settled).toEqual([]) + expect(signals.map(signal => signal.aborted)).toEqual([false, false]) + + await vi.advanceTimersByTimeAsync(1) + + expect(settled).toEqual([HAPStatus.OPERATION_TIMED_OUT, HAPStatus.OPERATION_TIMED_OUT]) + expect(signals.map(signal => signal.aborted)).toEqual([true, true]) + expect(warn.mock.calls.slice(2)).toEqual([ + [SILENT], + [SILENT], + ]) + + answers[0].reject(new Error('The camera answered too late.')) + answers[1].resolve(MOCK_IMAGE) + await settle() + + expect(settled).toHaveLength(2) + expect(error).not.toHaveBeenCalled() + }) + + it('reports a function that never settles as the plugin\'s failure on the channel of the camera\'s accessory at 8 seconds and at 25, printing ' + + 'nothing while the channel has a subscriber', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { camera: made, snapshot } = snapshotting() + const answer = deferred() + const problems: CameraProblem[] = [] + const settled: unknown[] = [] + const subscription = onCameraProblem(NUMBERED_ACCESSORY_UUID, problem => problems.push(problem)) + + onTestFinished(() => { + subscription[Symbol.dispose]() + }) + snapshot.mockImplementationOnce(async () => await answer.promise) + outcomes(made.handleSnapshotRequest(360, 640, 'Front Door'), settled) + + await vi.advanceTimersByTimeAsync(8000) + + expect(problems.map(({ sentence }) => sentence)).toEqual([SLOW_SENTENCE]) + + await vi.advanceTimersByTimeAsync(17000) + + expect(settled).toEqual([HAPStatus.OPERATION_TIMED_OUT]) + expect(problems).toEqual([ + { + accessoryUUID: NUMBERED_ACCESSORY_UUID, + kind: 'plugin-failure', + level: 'warning', + sensorUUID: SENSOR_UUID, + sentence: SLOW_SENTENCE, + }, + { + accessoryUUID: NUMBERED_ACCESSORY_UUID, + kind: 'plugin-failure', + level: 'warning', + sensorUUID: SENSOR_UUID, + sentence: SILENT_SENTENCE, + }, + ]) + expect(warn).not.toHaveBeenCalled() + + answer.resolve(MOCK_IMAGE) + await settle() + }) + + it('aborts a pending call\'s signal at the camera\'s removal, failing its snapshot and logging none of the rejection that follows', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { camera: made, snapshot } = snapshotting() + + snapshot.mockImplementationOnce(async (_request, signal) => await new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(new Error('The fetch was cut.')), { once: true }) + })) + + const pending = made.handleSnapshotRequest(360, 640, 'Front Door') + const [[, signal]] = snapshot.mock.calls + + await settle() + + expect(signal.aborted).toBe(false) + + made.handleControllerRemoved() + + expect(signal.aborted).toBe(true) + await expect(pending).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + await settle() + + expect(error).not.toHaveBeenCalled() + }) + + it('leaves a pending call\'s signal unaborted at a factory reset, and aborts it at the removal after', async () => { + const { camera: made, snapshot } = snapshotting() + const answer = deferred() + + snapshot.mockImplementationOnce(async () => await answer.promise) + + const pending = made.handleSnapshotRequest(360, 640, 'Front Door') + const [[, signal]] = snapshot.mock.calls + + made.handleFactoryReset() + await settle() + + expect(signal.aborted).toBe(false) + + made.handleControllerRemoved() + + expect(signal.aborted).toBe(true) + await expect(pending).rejects.toBe(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + }) + + it('settles a pending call at once when its asker goes at 1 second and when the camera is removed, each leaving the timers as they stood before it ' + + 'and drawing no warning through 30 seconds', async () => { + vi.useFakeTimers({ + toFake: ['setTimeout', 'clearTimeout'], + }) + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const { camera: made, snapshot } = snapshotting() + const asker = new AbortController() + const settled: unknown[] = [] + + snapshot.mockImplementation(async () => await deferred().promise) + + const timers = vi.getTimerCount() + + outcomes(made.handleSnapshotRequest(360, 640, 'Front Door', undefined, asker.signal), settled) + await vi.advanceTimersByTimeAsync(1000) + + expect(settled).toEqual([]) + + asker.abort() + await vi.advanceTimersByTimeAsync(0) + + expect(settled).toEqual([HAPStatus.SERVICE_COMMUNICATION_FAILURE]) + expect(vi.getTimerCount()).toBe(timers) + + outcomes(made.handleSnapshotRequest(360, 640, 'Front Door'), settled) + await vi.advanceTimersByTimeAsync(1000) + made.handleControllerRemoved() + await vi.advanceTimersByTimeAsync(0) + + expect(settled).toEqual([HAPStatus.SERVICE_COMMUNICATION_FAILURE, HAPStatus.SERVICE_COMMUNICATION_FAILURE]) + expect(vi.getTimerCount()).toBe(timers) + + await vi.advanceTimersByTimeAsync(30000) + + expect(warn).not.toHaveBeenCalled() + expect(snapshot.mock.calls.map(([, signal]) => signal.aborted)).toEqual([true, true]) + }) + + it('keeps the signal of a call that answered unaborted when its asker goes and when the camera is removed after the answer', async () => { + const { camera: made, snapshot } = snapshotting() + const asker = new AbortController() + + await expect(made.handleSnapshotRequest(360, 640, 'Front Door', undefined, asker.signal)).resolves.toBe(MOCK_IMAGE) + + const [[, signal]] = snapshot.mock.calls + + asker.abort() + made.handleControllerRemoved() + + expect(signal.aborted).toBe(false) + }) + }) + + describe('its mutes', () => { + const HUB = {} as HAPConnection + + // The two-sensor camera with the block, constructed, configured and handed a published context, its delegate taking talkback: it publishes its + // Speaker beside its Microphone. + function muting(): { readonly made: CameraController, readonly map: CameraControllerServiceMap } { + const made = camera(bufferCamera().options) + const map = made.constructServices() + + made.configureServices() + handPublishedContext(made) + + return { made, map } + } + + // The tier tables a camera holds, one for each video sensor. + function tablesOf(made: CameraController): TierTable[] { + // @ts-expect-error: private access + return Array.from(made.tierTables.values()) + } + + // The flag the sound half of each table's demands reads, as each table holds it. + function microphoneFlags(tables: readonly TierTable[]): boolean[] { + return tables.map(table => table.audioTier.context.microphoneMuted) + } + + it('raises one event and one change for a HomeKit write of each mute and one change and no event for the plugin\'s setter, sets the field, Mute and ' + + 'every tier table at a restore, and unmutes them at a reset', async () => { + const { made, map } = muting() + const mutes = [map.microphone!, map.speaker!].map(service => service.getCharacteristic(Characteristic.Mute)) + const heard: string[] = [] + // Each mute's field, which its GET handler answers. + const fields = async (): Promise => Promise.all(mutes.map(async mute => mute.handleGetRequest(HUB))) + + made.on(CameraControllerEvents.MICROPHONE_PROPERTIES_CHANGED, muted => heard.push(`microphone-change ${muted}`)) + made.on(CameraControllerEvents.SPEAKER_PROPERTIES_CHANGED, muted => heard.push(`speaker-change ${muted}`)) + + for (const [index, mute] of mutes.entries()) { + const name = ['microphone', 'speaker'][index] + + mute.on(CharacteristicEventTypes.CHANGE, ({ newValue, reason }: CharacteristicChange) => heard.push(`${name} ${String(newValue)} ${reason}`)) + } + + for (const mute of mutes) { + await expect(mute.handleSetRequest(true, HUB)).resolves.toBeUndefined() + } + + expect(heard.splice(0)).toEqual([ + 'microphone true write', + 'microphone-change true', + 'speaker true write', + 'speaker-change true', + ]) + expect(microphoneFlags(tablesOf(made))).toEqual([true, true]) + + made.setMicrophoneMuted(false) + made.setSpeakerMuted(false) + + expect(heard.splice(0)).toEqual([ + 'microphone false update', + 'speaker false update', + ]) + expect(microphoneFlags(tablesOf(made))).toEqual([false, false]) + + made.deserialize({ + ...made.serialize()!, + microphoneMuted: true, + speakerMuted: true, + }) + + expect(heard.splice(0)).toEqual([ + 'microphone true update', + 'speaker true update', + ]) + expect(await fields()).toEqual([true, true]) + expect(microphoneFlags(tablesOf(made))).toEqual([true, true]) + + made.handleFactoryReset() + + expect(heard.splice(0)).toEqual([ + 'microphone false update', + 'speaker false update', + ]) + expect(await fields()).toEqual([false, false]) + expect(microphoneFlags(tablesOf(made))).toEqual([false, false]) + }) + + it('tells the state-change delegate once for a HomeKit write and for the plugin\'s setter of each mute that moves its value, and nothing for one ' + + 'that leaves it as it stands', async () => { + const { made, map } = muting() + const stateChange = vi.fn<() => void>() + const mutes = [map.microphone!, map.speaker!].map(service => service.getCharacteristic(Characteristic.Mute)) + const setters = [ + (muted: boolean): void => made.setMicrophoneMuted(muted), + (muted: boolean): void => made.setSpeakerMuted(muted), + ] + const calls: number[] = [] + // The delegate's calls one step makes, read once the step has returned. + const step = async (act: () => unknown): Promise => { + stateChange.mockClear() + await act() + calls.push(stateChange.mock.calls.length) + } + + made.setupStateChangeDelegate(stateChange) + + for (const [index, mute] of mutes.entries()) { + await step(async () => mute.handleSetRequest(true, HUB)) + await step(async () => mute.handleSetRequest(true, HUB)) + await step(() => setters[index](false)) + await step(() => setters[index](false)) + } + + expect(calls).toEqual([1, 0, 1, 0, 1, 0, 1, 0]) + }) + + it('tells the state-change delegate nothing at its removal, whose reset unmutes a muted camera and moves every part back to its first state', () => { + const { made } = muting() + const stateChange = vi.fn<() => void>() + + made.setMicrophoneMuted(true) + made.setSpeakerMuted(true) + made.setupStateChangeDelegate(stateChange) + made.handleControllerRemoved() + + expect(stateChange).not.toHaveBeenCalled() + }) + + it('stores its mutes on a camera with the block and drops them through a run without the block, whose stored state carries no mute and reads as ' + + 'one never muted: the block\'s next run restores each unmuted', () => { + const { made } = muting() + + made.setMicrophoneMuted(true) + made.setSpeakerMuted(true) + + const stored = made.serialize()! + + expect([stored.microphoneMuted, stored.speakerMuted]).toEqual([true, true]) + + // Runs without the block restore the record, as at a restart that switches the camera, one of them muted through its own setters. + const [legacy, neverMuted] = [true, false].map((muted) => { + const run = camera(createCameraControllerOptions()) + + run.constructServices() + run.configureServices() + run.deserialize(stored) + + if (muted) { + run.setMicrophoneMuted(true) + run.setSpeakerMuted(true) + } + + return run.serialize()! + }) + + expect(legacy).not.toHaveProperty('microphoneMuted') + expect(legacy).not.toHaveProperty('speakerMuted') + expect(JSON.stringify(legacy)).toBe(JSON.stringify(neverMuted)) + + const { made: back } = muting() + + back.deserialize(legacy) + + expect([back.serialize()!.microphoneMuted, back.serialize()!.speakerMuted]).toEqual([false, false]) + expect(microphoneFlags(tablesOf(back))).toEqual([false, false]) + }) + + it('hands each tier table a configure makes again after a removal the Microphone\'s mute as it stands, and the next mute reaches that table and not ' + + 'the one the removal dropped', () => { + const { made } = muting() + + made.setMicrophoneMuted(true) + + const dropped = tablesOf(made) + + made.handleControllerRemoved() + made.constructServices() + made.configureServices() + handPublishedContext(made) + + const remade = tablesOf(made) + + // The removal's reset unmuted the camera, and each table made again reads unmuted, as the field does. + expect(remade.some(table => dropped.includes(table))).toBe(false) + expect(made.serialize()!.microphoneMuted).toBe(false) + expect(microphoneFlags(remade)).toEqual([false, false]) + + made.setMicrophoneMuted(true) + + expect(microphoneFlags(remade)).toEqual([true, true]) + expect(microphoneFlags(dropped)).toEqual([false, false]) + }) + }) + }) }) diff --git a/src/lib/controller/CameraController.ts b/src/lib/controller/CameraController.ts index 538a37b3e..30919e2ec 100644 --- a/src/lib/controller/CameraController.ts +++ b/src/lib/controller/CameraController.ts @@ -1,6 +1,4 @@ /* global NodeJS */ -import type { Buffer } from 'node:buffer' - import type { CharacteristicValue, SessionIdentifier } from '../../types.js' import type { CameraRecordingConfiguration, @@ -8,17 +6,40 @@ import type { CameraStreamingOptions, PrepareStreamRequest, PrepareStreamResponse, + RecordingManagementServices, RecordingManagementState, RecordingPacket, RTPStreamManagementState, SnapshotRequest, StreamingRequest, } from '../camera/index.js' -import type { CharacteristicGetCallback, CharacteristicSetCallback } from '../Characteristic.js' +import type { MotionZonesManagementOptions, MotionZonesManagementState } from '../camera/MotionZonesManagement.js' +import type { MultiTierStreamManagementOptions, MultiTierStreamManagementState } from '../camera/MultiTierStreamManagement.js' +import type { OperatingModeChange, OperatingModeState, StreamingEnabledChange } from '../camera/OperatingModePolicy.js' +import type { BufferRecording, RecordingAdmission } from '../camera/recording/BufferRecorder.js' +import type { CMAFRecordingServices } from '../camera/recording/CMAFRecordingManagement.js' +import type { + CameraKeyframe, + CameraSnapshotRequest, + CameraVideoSensor, + MultiTierStreamingOptions, + SensorStreamTiers, + SnapshotFetchRequest, + SnapshotRefusal, + ValidatedVideoSensors, +} from '../camera/StreamingOptions.js' +import type { WebRTCStreamingOptions, WebRTCStreamManagementOptions, WebRTCStreamManagementState } from '../camera/WebRTCStreamManagement.js' +import type { CharacteristicChange, CharacteristicGetCallback, CharacteristicSetCallback } from '../Characteristic.js' import type { HDSProtocolSpecificErrorReason } from '../datastream/index.js' import type { + CameraCapabilities, + CameraGlobalOperatingMode, + CameraMotionZones, + CameraMultiTierRTPStreamManagement, CameraOperatingMode, CameraRecordingManagement, + CameraRTPStreamManagement, + CameraWebRTCStreamManagement, DataStreamTransportManagement, Doorbell, Microphone, @@ -26,32 +47,299 @@ import type { OccupancySensor, Speaker, } from '../definitions/index.js' -import type { ControllerIdentifier, ControllerServiceMap, SerializableController, StateChangeDelegate } from './Controller.js' +import type { ControllerAccessoryContext, ControllerIdentifier, ControllerServiceMap, SerializableController, StateChangeDelegate } from './Controller.js' +import { Buffer } from 'node:buffer' import crypto from 'node:crypto' import { EventEmitter } from 'node:events' import createDebug from 'debug' +import { 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' +import { debugChannel } from '../camera/diagnostics/debugChannels.js' +import { GlobalOperatingMode } from '../camera/GlobalOperatingMode.js' import { EventTriggerOption, RecordingManagement, RTPStreamManagement, } from '../camera/index.js' +import { MotionAttribution } from '../camera/MotionAttribution.js' +import { MotionZonesManagement } from '../camera/MotionZonesManagement.js' +import { MultiTierStreamManagement } from '../camera/MultiTierStreamManagement.js' +import { OperatingModePolicy } from '../camera/OperatingModePolicy.js' +import { BufferRecorder, validateBufferRecordingOptions } from '../camera/recording/BufferRecorder.js' +import { CMAFRecordingManagement } from '../camera/recording/CMAFRecordingManagement.js' +import { ServedRecordings } from '../camera/recording/ServedRecording.js' +import { SensorRegistry } from '../camera/SensorRegistry.js' +import { settleWithin } from '../camera/session/settleWithin.js' +import { isPictureSize, ResourceRequestReason, validateVideoSensors } from '../camera/StreamingOptions.js' +import { TierTable } from '../camera/TierTable.js' +import { WebRTCEngine } from '../camera/webrtc/WebRTCEngine.js' +import { WEBRTC_MINIMUM_SESSIONS, webRTCMaxSessions, WebRTCStreamManagement } from '../camera/WebRTCStreamManagement.js' import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' -import { DataStreamManagement } from '../datastream/index.js' import { HAPStatus } from '../HAPServer.js' +import { RecordingProvisioning } from '../model/RecordingProvisioning.js' import { Service } from '../Service.js' -import { errorMessage, errorStack } from '../util/errors.js' +import { counted } from '../util/counted.js' +import { DisposableStack } from '../util/disposableStack.js' +import { errorMessage } from '../util/errors.js' import { HapStatusError } from '../util/hapStatusError.js' +import { isThenable, logDelegateFailure } from '../util/promise-utils.js' +import { guardValues } from '../util/valueGuard.js' import { DefaultControllerType } from './Controller.js' +import { dispatchEvent } from './eventDispatch.js' const debug = createDebug('HAP-NodeJS:Camera:Controller') +// The channel of a camera's debug events under the controller's debug name, which a camera with the capabilities block publishes on and a legacy camera, +// whose lines the debug package writes under the same name, never does. +const CONTROLLER_DEBUG = debugChannel('HAP-NodeJS:Camera:Controller') + +// What the debug event of a start withdrawn as the camera goes out of service says became of it. +const OUT_OF_SERVICE = 'as the camera went out of service: every join waiting on it is refused' + +// Every state a plugin may state of its camera's source. +const SOURCE_STATES: readonly CameraSourceState[] = ['available', 'recovering', 'away'] + +// The status a resource request's snapshot is refused with for each cause the snapshot gate of a camera with the capabilities block answers. +const SNAPSHOT_STATUSES: Readonly> = { + 'not allowed': HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE, + 'out of service': HAPStatus.SERVICE_COMMUNICATION_FAILURE, +} + +/** + * One capability's part in restoring a camera's service map: it adopts the services the map holds under its keys, creates the ones it lacks and + * removes the ones its configuration leaves out, mutating the map in place, and answers whether it changed the map. + */ +type ServiceMapReconciler = (serviceMap: CameraControllerServiceMap) => boolean + +// One snapshot's fetch, as a resource request or the data stream hands it to the controller: the picture's size and the request's reason, which every fetch +// carries, the camera's name for its lines, and the signal of whoever asked, which a legacy handler is never handed. +interface SnapshotFetch extends SnapshotFetchRequest { + readonly accessoryName?: string + readonly signal?: AbortSignal +} + +// The rule the microphone and the speaker share: a wanted service is adopted from the map or created and inserted, and a saved one the camera does not +// want is deleted. +function reconcileAudioService( + serviceMap: CameraControllerServiceMap, + key: K, + wanted: boolean, + create: () => NonNullable, +): { service?: CameraControllerServiceMap[K], modified: boolean } { + const saved = serviceMap[key] + + if (wanted) { + if (saved) { + return { service: saved, modified: false } + } + + const service = create() + serviceMap[key] = service + return { service, modified: true } + } + + if (saved) { + delete serviceMap[key] + return { modified: true } + } + + return { modified: false } +} + +// Writes an audio service's Mute only where the characteristic holds another value. A HomeKit write, whose characteristic has taken the written value +// by the time the setter runs, fires its one change and no second. +function writeMute(service: Microphone | Speaker | undefined, muted: boolean): void { + const mute = service?.getCharacteristic(Characteristic.Mute) + + if (mute && (mute.value !== muted)) { + mute.updateValue(muted) + } +} + +// A service map reordered in place: the leading keys it holds first, in the order given, and every other key after them in its present order, a key whose +// value is undefined among them. The map is reordered rather than copied, because a restore answers the accessory with the map it was handed. +function orderServiceMap(serviceMap: ControllerServiceMap, leading: readonly string[]): void { + const rank = (key: string): number => { + const index = leading.indexOf(key) + return index === -1 + ? leading.length + : index + } + + // The sort is stable: every other key keeps its order, and an object's own keys take a new order only by being deleted and inserted again. + const entries = Object.entries(serviceMap).sort(([left], [right]) => rank(left) - rank(right)) + + for (const [key] of entries) { + delete serviceMap[key] + } + + for (const [key, service] of entries) { + serviceMap[key] = service + } +} + +// A restore reads a persisted record only when it is a plain object. A hand-edited or partial state restores what it holds rather than throwing into the +// storage's factory reset. +function isPlainObject(value: unknown): value is object { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +// One stream family's record: none for a camera with no management and no restored record, which writes no field, and otherwise each management's slice written over the +// record the last restore read, which keeps the state of a video sensor missing from the plugin's inventory. +function serializeSlices(managements: ReadonlyMap State }>, restored?: Record): Record | undefined { + if (managements.size === 0 && !restored) { + return undefined + } + + const record = { ...restored } + + for (const [sensorUUID, management] of managements) { + record[sensorUUID] = management.serialize() + } + + return record +} + +// One stream family's restore: the record is kept only when it is a plain object, and each management applies its own slice under the same guard. +function deserializeSlices(managements: ReadonlyMap void }>, record: unknown): Record | undefined { + const restored = isPlainObject(record) + ? record as Record + : undefined + + for (const [sensorUUID, management] of managements) { + const slice = restored?.[sensorUUID] + + if (isPlainObject(slice)) { + management.deserialize(slice) + } + } + + return restored +} + +/** + * How a camera with the camera capabilities block records from its camera buffer, the block's `recording` option. The camera records the tier marked + * {@link CameraVideoTier.recorded}, or with none marked the first sensor's best tier, and a block that leaves the option out, or gives it empty, records + * it with the default prebuffer. + * + * Such a camera uploads each clip a hub commands from its recorded tier's stream, and that stream carries the formats Apple's HomeKit Secure Video guide + * requires: HEVC video, at up to 3840x2160 and 24 or 30 frames per second, and Opus audio captured at 16 or 24 kHz. The guide also gives target bitrates, + * and says the maximums should not be exceeded: 4K at 4500 kbps average and 5000 maximum, 2K at 2800 and 3000, 1080p at 1700 and 1800. Apple's service + * refuses a segment that is too large, and the rest of that clip is not uploaded. This testing shows 10 MB is the cap on a segment that service takes, + * which is why the camera holds each segment under it: it cuts a segment at a keyframe before it reaches that cap, and a stretch from one keyframe to the next that + * alone reaches the cap leaves as it stands, with a `segment-over-cap` problem on the camera's channel. + * + * @group Camera + */ +export interface CameraBufferRecordingOptions { + /** + * How far back each recording reaches before a hub asks for it, in milliseconds, 5000 by default. A hub's recording is declined until the camera buffer + * holds this much of the tier. The camera controller's constructor throws a `TypeError` for a value that is not a whole number from 0 to 30000. + */ + prebuffer?: number + /** + * Whether the camera records a hub's recording, asked once a hub asks for one, the camera in service and its camera buffer ready, before the library + * answers the hub's open, with what the `recording-started` event would carry, and answered on the spot. `false` declines the recording, which the + * library refuses in its answer to the open as busy, raising no problem and no recording event, and `true` records it. Any other answer, a promise among + * them, records it with a `plugin-failure` problem on the camera's channel once for each configuration of the camera, and a throw records it with one at + * each call, each printed where nothing subscribes to that channel. Whatever the answer, a recording whose call stopped the recorder is refused the same + * way as one answered `false`: the camera left service, even for a moment, the function stating its source away or unpublishing its accessory, recording + * was turned off, the camera was switched off or manually disabled, or the camera was reset or removed. The camera controller's constructor throws a + * `TypeError` for a value that is not a function. + */ + shouldRecord?: (start: CameraRecordingStart) => boolean +} + +/** + * The options of a camera controller, in the form the camera capabilities block decides: a camera with the block takes + * {@link CameraControllerCapabilitiesOptions}, streams through the block's multi-tier and WebRTC services and records from its camera buffer, and a + * camera without it takes {@link CameraControllerLegacyOptions}, streams through its legacy stream management and records through a plugin's recording + * delegate when it gives the top-level `recording` option. The types refuse a member of the other form, and so does the camera controller's constructor. + * + * @group Camera + */ +export type CameraControllerOptions = CameraControllerLegacyOptions | CameraControllerCapabilitiesOptions + /** + * What a plugin states of its camera's source through {@link CameraController.updateSourceState}, for the camera as a whole: `available`, the source + * reachable; `away`, the source unreachable, which takes the camera out of service until the plugin states it available; and `recovering`, the source + * reconnecting, which holds every running tier through the reconnect for up to 30 seconds, and which stated while the camera is away means available. + * + * @group Camera + */ +export type CameraSourceState = 'available' | 'recovering' | 'away' + +/** + * The sensors a camera controller creates and maintains, or adopts from the plugin, beside the camera's streams. + * + * You may either specify and provide the desired {@link Service}s or specify their creation and maintenance using a `boolean` flag. + * In this case the controller will create and maintain the service for you. + * Otherwise, when you supply an already created instance of the {@link Service}, you are responsible yourself to manage the service + * (e.g. creating, restoring, adding to the accessory, ...). + * + * The services can be accessed through the documented property after the call to {@link Accessory.configureController} has returned. + * + * @group Camera + */ +export interface CameraSensorOptions { + /** + * Define if a {@link Service.MotionSensor} should be created/associated with the controller. + * + * You may access the created service via the {@link CameraController.motionService} property to configure listeners. + * + * ## HomeKit Secure Video: + * + * If supplied, this sensor will be used as a {@link EventTriggerOption.MOTION} trigger, which the legacy recording options' supported configuration + * advertises. A camera that gives no such options advertises no trigger. + * The characteristic {@link Characteristic.StatusActive} will be added, which is used to enable or disable the sensor. + * + * On a camera with the camera capabilities block the controller also adds {@link Characteristic.ContributingSensors} and + * {@link Characteristic.MotionEnabled} to the sensor. The plugin reports motion by writing the sensor's {@link Characteristic.MotionDetected}, the one + * supported way as on a camera without the block, through `updateValue`, `setValue`, `sendEventNotification`, the service's `updateCharacteristic` or + * `setCharacteristic`, or a read handler's answer, or through {@link CameraController.updateMotionDetected} where it names the video sensors that saw + * the motion. The library reports Motion Enabled, clears standing motion as Motion Enabled turns off and holds back the motion any of them writes while Motion Enabled + * is off, which means that motion is never stored and never sent to a hub. A plugin keeps the Motion Enabled the controller adds, because one + * it replaces with a fresh characteristic becomes the switch's source at that characteristic's value, with no `operating-mode-change` event. The + * controller added Contributing Sensors and Motion Enabled when the camera ran with the block, and it removes them from any motion sensor, a plugin's + * own among them, when the camera returns without the block at a restart. + * + * The controller takes this sensor once, as it is configured, and follows no sensor removed from its accessory or added in its place. A plugin + * keeps the sensor it gave for the controller's life. On a camera with the block the same holds for the sensor's + * {@link Characteristic.MotionDetected}: one a plugin puts in its place carries neither the library's motion listener nor the Motion Enabled guard, + * and one stripped of its listeners keeps the guard alone. + * + * A camera with the camera capabilities block needs this sensor, since a hub starts its recordings at motion, which is why the camera controller's constructor + * throws a `TypeError` for a camera with the block whose `motion` is missing or `false`, unless the camera is a doorbell, whose press starts them. + */ + motion?: Service | boolean + /** + * Define if a {@link Service.OccupancySensor} should be created/associated with the controller. + * + * You may access the created service via the {@link CameraController.occupancyService} property to configure listeners. + * + * ## HomeKit Secure Video: + * + * The characteristic {@link Characteristic.StatusActive} will be added, which is used to enable or disable the sensor. + * + * The controller takes this sensor once, as it is configured, as it takes the motion sensor, and follows no sensor removed from its accessory or + * added in its place. + */ + occupancy?: Service | boolean +} + +/** + * The options of a camera without the camera capabilities block, which streams through its legacy stream management and records through a plugin's + * recording delegate when it gives the top-level `recording` option. The camera controller's constructor throws a `TypeError` for a missing `delegate` + * or `streamingOptions`. + * * @group Camera */ -export interface CameraControllerOptions { +export interface CameraControllerLegacyOptions { /** * Amount of parallel camera streams the accessory is capable of running. * According to the official HAP specification, non SecureVideo cameras have a minimum required amount of 2 (but 1 is also fine). @@ -78,10 +366,15 @@ export interface CameraControllerOptions { * * NOTE: The controller only initializes the required characteristics for the {@link Service.CameraOperatingMode}. * You may add optional characteristics, if required, by accessing the service directly `CameraController.recordingManagement.operatingModeService`. + * + * A camera with the camera capabilities block takes no such option: it is advertised with these services and records from its camera buffer, as the + * block's own `recording` option sets out. The camera controller's constructor throws a `TypeError` for this option given beside the block, and for + * this option without its legacy recording options. */ recording?: { /** - * Options regarding Recordings (Secure Video) + * Options regarding Recordings (Secure Video): the legacy recording configurations the camera offers for a HomeKit controller to select. The camera + * records through them alone, and its controller's constructor throws a `TypeError` when they are missing. */ options: CameraRecordingOptions @@ -94,37 +387,191 @@ export interface CameraControllerOptions { /** * This config section configures optional sensors for the camera. * It e.g. may be used to set up a {@link EventTriggerOption.MOTION} trigger when configuring Secure Video. + */ + sensors?: CameraSensorOptions + + /** + * A camera without the camera capabilities block takes none, and the types refuse it here. + */ + cameraCapabilities?: never +} + +/** + * The options of a camera with the camera capabilities block, which streams through the block's multi-tier and WebRTC services and records from its camera + * buffer. The camera controller's constructor throws a `TypeError` for a top-level `recording`, `delegate`, `streamingOptions` or `cameraStreamCount` + * given beside the block, and for a camera with the block whose `sensors.motion` is missing or `false`, unless the camera is a doorbell. + * + * Such a camera reports through Node's diagnostics channels. Each of its problems, a failure of the plugin's code or of the library's own among them, is a + * {@link CameraProblem} published on the camera's channel, which a plugin hears through {@link onCameraProblem} and a tool through the channel + * {@link cameraProblemsChannel} names, each by the UUID of the camera's accessory. Where that channel has no subscriber, the library prints the problem's + * sentence at its level, opened by the camera's name in brackets, or bare while the camera holds no accessory yet. A problem raised while the camera + * restores its saved state before its accessory hands it a context is held and reported once that context arrives, or bare at the end of that step where + * none arrives. Every other line of its own is a debug event on the channel named exactly as its debug name, `HAP-NodeJS:Camera:Tier` among them, which + * every camera shares: each event carries `accessoryUUID`, absent while the camera holds no accessory, `kind` and `sentence` by promise, and every field of + * these events is promised too: `recording-ended` on `HAP-NodeJS:Camera:BufferRecorder` carries `dropped`, `outcome`, `seconds`, `segments`, `sensorUUID`, + * `streamId` and `tierId`, its `seconds` the length of the video in the segments it counts, the prebuffer among them, and `clip-finalized` on + * `HAP-NodeJS:Camera:CMAFRecording` carries `clipID`, `seconds` and `segments`, its `seconds` the durations its media playlist states for the segments it + * uploaded, summed. A sentence's wording is never a promise, and every other event's kind and details are free to change in any release. The library prints + * each event's sentence under the debug name it is published on, where the DEBUG setting named that name as the library loaded. A subscriber on such a + * channel is called inside the library's own work as each event is published, as {@link cameraProblemsChannel} states of a camera's problems channel: it + * must not call back into the camera, and a throw from it is an uncaught exception, which ends a Homebridge bridge. The recording management's lines that + * every camera writes, a recording stream's and those under `HAP-NodeJS:HKSV` among them, reach the console and the debug package as a camera without the + * block writes them. + * + * @group Camera + */ +export interface CameraControllerCapabilitiesOptions { + /** + * The camera's Camera Capabilities feature set, which a hub discovers through the {@link Service.CameraCapabilities} service. A camera with it is always + * advertised with its recording services, among them the {@link Service.CameraBufferManagement}, {@link Service.CameraKeyManagement} and + * {@link Service.CameraClientCertificateManagement} services, through which a hub provisions the camera and commands the uploads of the recordings it + * serves, and it records from its camera buffer, as the block's own `recording` option sets out. + */ + cameraCapabilities: CameraCapabilitiesOptions + + /** + * The camera's sensors, its motion sensor among them, which a camera with the block needs unless it is a doorbell. + */ + sensors?: CameraSensorOptions + + // A camera with the camera capabilities block streams through the block and takes none of the legacy form's members. The types refuse each here. + cameraStreamCount?: never + delegate?: never + streamingOptions?: never + recording?: never +} + +/** + * The camera capabilities block: the camera's video sensors, its multi-tier streaming, its snapshot function and its WebRTC, minimums and recording + * settings, from which the library builds every service and value of the camera's Camera Capabilities feature set. + * + * @group Camera + */ +export interface CameraCapabilitiesOptions { + /** + * The camera's video sensors, each stated once as an entry the library derives the sensor's Camera Capabilities, its stream services and its zones + * service from, every value only the library chooses filled in. The camera lists them in this order, the first labelled Primary and the rest Generic, + * in Camera Capabilities and in its stream services alike, because a controller shows the sensor that comes first. + * + * The camera controller's constructor throws a `TypeError`, naming the member and the sensor or the tier, for a `videoSensors` that is not an array or + * is empty, an entry that is not an object, naming its index in this list, a sensor UUID that is not a UUID or that two sensors share, either naming + * the sensor's index in this list, a sensor whose `tiers` is missing or empty, a sensor without `audio` or without `audio.bitrate`, a sensor without + * `dimensions`, a `motionZones` that is not a function, a tier that is not an object, naming its index in `tiers`, two tiers of one sensor sharing an + * `id`, a `keepRunning` or a `recorded` that is not a boolean, a `peakBitrate` below its `bitrate`, more than one tier of the camera marked `recorded`, + * tiers the stream tier codec cannot encode and a configuration Camera Capabilities cannot encode. * - * You may either specify and provide the desired {@link Service}s or specify their creation and maintenance using a `boolean` flag. - * In this case the controller will create and maintain the service for you. - * Otherwise, when you supply an already created instance of the {@link Service}, you are responsible for managing the service yourself - * (e.g. creating, restoring, adding to the accessory, ...). + * @example + * A camera of one sensor, whose best tier runs while the user's switch allows streaming and the camera is in service, its accessory published and its + * source not stated away, and is the one it records, whose zones go to the plugin's detector, and whose motion sensor the controller creates: * - * The services can be accessed through the documented property after the call to {@link Accessory.configureController} has returned. + * ```ts + * const camera = new hap.CameraController({ + * cameraCapabilities: { + * snapshot: async (request, signal): Promise => await device.snapshot(request, { signal }), + * streaming: { delegate }, + * videoSensors: [{ + * audio: { bitrate: 24 }, + * dimensions: { height: 2160, width: 3840 }, + * intent: hap.CameraSensorIntent.MAIN, + * motionZones: async (zones, reason, signal): Promise => detector.setZones(zones, { signal }), + * tiers: [ + * { bitrate: 4500, frameRate: 30, height: 2160, id: 1, keepRunning: true, quality: hap.CameraVideoQuality.HIGH, recorded: true, width: 3840 }, + * { bitrate: 768, frameRate: 30, height: 720, id: 2, quality: hap.CameraVideoQuality.MEDIUM, width: 1280 }, + * { bitrate: 180, frameRate: 15, height: 360, id: 3, quality: hap.CameraVideoQuality.LOW, width: 640 }, + * ], + * uuid: hap.uuid.generate(device.mac), + * }], + * }, + * sensors: { motion: true }, + * }) + * ``` */ - sensors?: { - /** - * Define if a {@link Service.MotionSensor} should be created/associated with the controller. - * - * You may access the created service via the {@link CameraController.motionService} property to configure listeners. - * - * ## HomeKit Secure Video: - * - * If supplied, this sensor will be used as a {@link EventTriggerOption.MOTION} trigger. - * The characteristic {@link Characteristic.StatusActive} will be added, which is used to enable or disable the sensor. - */ - motion?: Service | boolean - /** - * Define if a {@link Service.OccupancySensor} should be created/associated with the controller. - * - * You may access the created service via the {@link CameraController.occupancyService} property to configure listeners. - * - * ## HomeKit Secure Video: - * - * The characteristic {@link Characteristic.StatusActive} will be added, which is used to enable or disable the sensor. - */ - occupancy?: Service | boolean - } + videoSensors: CameraVideoSensor[] + /** + * The camera's multi-tier streaming: the one delegate every sensor's tiers report their demand to, and the bound on each sensor's sessions. The camera + * controller's constructor throws a `TypeError` for a `streaming` that is not an object, a delegate without a `tierDemandStarted` function and a + * `maxSessions` that is not a positive integer. + */ + streaming: MultiTierStreamingOptions + /** + * The camera's snapshots: called for each snapshot a hub asks that the library lets through, over the data stream or a resource request, for the + * camera's first video sensor, and handed the request's size and reason, that sensor's UUID and what {@link CameraController.latestKeyframe} answers + * for it. The library refuses a snapshot without calling the function while streaming is not allowed, with HomeKit Camera Active off, the global + * Streaming Enabled off or the camera manually disabled, answering a resource request with HAP status -70412 and the data stream with the reason Not + * Allowed. It refuses an event snapshot while Event Snapshots Active is off, a periodic one while Periodic Snapshots Active is off and one naming no + * reason while either is off, each as it refuses one while streaming is not allowed. While the camera is out of service, its accessory not published or + * its source stated away, it refuses a snapshot without calling the function as well, answering a resource request with HAP status -70402, the + * communication failure, and the data stream with the reason Busy. A request of any size but a positive whole number of pixels each way is refused + * without the call too. The function answers a promise of the JPEG picture at the asked size. A throw, a rejection and an answer that is no `Buffer` of + * at least one octet each fail the snapshot with one `plugin-failure` problem on the camera's channel, printed where nothing subscribes, and a rejection + * that follows the library's own abort of the signal raises none. + * + * The signal is aborted at the snapshot's bound of 25 seconds, when whoever asked is gone and at the camera's removal, and at no other moment, which means a + * factory reset aborts none and neither does anything after the snapshot is answered. A function that has not answered at 8 seconds raises a + * `plugin-failure` problem and one that has not answered at the bound raises a second, where the library warns at each for a legacy handler. A listener + * on the signal runs outside the library's guard: a throw from it is an uncaught exception that ends the process. A child process started with + * the signal raises an error when the signal aborts, which ends the process where the plugin listens for no `error` on that child process, and a write + * still going to that child's input then fails with an error on the input, which ends the process where the plugin listens for none there. The camera + * controller's constructor throws a `TypeError` for a `snapshot` that is not a function. + * + * @example + * A snapshot decoded from the newest keyframe where the library hands one, and fetched from the camera where it does not: + * + * ```ts + * snapshot: async ({ height, keyframe, width }, signal): Promise => { + * if (!keyframe) { + * return await device.fetchSnapshot({ height, signal, width }) + * } + * + * // The child is started with the signal, and an abort ends it with an error, which the wait on its close takes as its rejection. + * const ffmpeg = spawn('ffmpeg', ['-i', 'pipe:0', '-frames:v', '1', '-s', `${width}x${height}`, '-f', 'mjpeg', 'pipe:1'], { signal }) + * const chunks: Buffer[] = [] + * + * ffmpeg.stdout.on('data', (chunk: Buffer) => chunks.push(chunk)) + * // An abort can fail a write still going to the child's input, and an error there ends the process unless a listener hears it. + * ffmpeg.stdin.on('error', () => undefined) + * ffmpeg.stdin.end(keyframe.movie) + * await once(ffmpeg, 'close') + * + * return Buffer.concat(chunks) + * }, + * ``` + */ + snapshot: (request: CameraSnapshotRequest, signal: AbortSignal) => Promise + /** + * The WebRTC settings of the camera, which always answers views from away: the library's own engine answers each video sensor's Camera WebRTC Stream + * Management service from that sensor's tiers in `videoSensors`, and this member holds that streaming's settings alone, `maxSessions` and `voice`. + * `maxSessions` bounds the sessions each service holds. `voice` chooses which of a viewer's two voice streams a view from away writes to that viewer's + * talkback sink. Under `'automatic'`, the default, a viewer's better stream plays while it keeps pace with its dependable one and, once it has fallen + * behind, again after it has kept pace for a second, each change falling between packets so nothing is played twice. Under `'dependable'` the + * dependable stream alone plays. The debug name `HAP-NodeJS:Camera:WebRTC:werift`, listed by itself in the debug setting, turns on the output of + * werift, the WebRTC stack the engine is built on, which carries network addresses, the ICE passwords of both ends of a connection and the DTLS record + * layer's write keys and nonces, and a wider pattern that covers that name, `HAP-NodeJS:*` and `*` among them, leaves it off. The camera controller's + * constructor throws a `TypeError` for a `maxSessions` that is not an integer from 1 to 255 and for a `voice` that is neither value, and reads a + * `maxSessions` below six as a minimum of the specification, as `strict` says. + */ + webrtc?: WebRTCStreamingOptions + /** + * Whether a configuration below the specification's minimums throws a `TypeError` from the constructor rather than writing a debug event, each read + * once every refusal of the options has passed: a `maxSessions` below five, a WebRTC `maxSessions` below six, fewer than three video tiers, audio other + * than a 20 ms packet time and one channel, a Highest tier without both a 4K and a 2K tier, and a bitrate above its resolution's maximum. Under it the + * first minimum's sentence is thrown, and otherwise each is a debug event under the debug name `HAP-NodeJS:Camera:Controller`. While the camera runs, a + * tier's stream that runs past twice its tier's peak over the stretch a view opens on, read over a second at least, raises one `stream-fault` problem on + * the camera's channel for its demand under it, printed where nothing subscribes and naming the stretch's rate and the peak, and one debug event under + * the name `HAP-NodeJS:Camera:Tier` otherwise. Defaults to `false`. + */ + strict?: boolean + /** + * The camera's recording from its camera buffer, in which the library builds every recording and the plugin builds no clip. While the user's switch + * allows recording and the camera is in service, its accessory published and its source not stated away, the library holds the recorded tier itself, + * through the multi-tier streaming delegate's `tierDemandStarted`, keeps its recent samples, and builds and serves each recording a hub asks for from + * them, its picture and, while Recording Audio Active is on, its sound. A recording asked for while the camera is out of service, or before the camera + * buffer holds the prebuffer, is declined, and so is one its `shouldRecord` answers false or whose call stopped the recorder, each decided once before + * the hub's open is answered and refused in that answer as busy. The controller tells of each recording through the `recording-started` and + * `recording-ended` events, and raises the problems of the held tier and its buffer on the camera's channel. The camera controller's constructor throws + * a `TypeError` for a member its own documentation names. + */ + recording?: CameraBufferRecordingOptions } /** @@ -140,21 +587,7 @@ export type PrepareStreamCallback = (error?: Error, response?: PrepareStreamResp */ export type StreamRequestCallback = (error?: Error) => void -/** - * @group Camera - */ -export enum ResourceRequestReason { - /** - * The reason describes periodic resource requests. - * In the example of camera image snapshots those are the typical preview images every 10 seconds. - */ - PERIODIC = 0, - /** - * The resource request is the result of some event. - * In the example of camera image snapshots, requests are made due to e.g. a motion event or similar. - */ - EVENT = 1, -} +export { ResourceRequestReason } from '../camera/StreamingOptions.js' /** * @group Camera @@ -166,7 +599,8 @@ export interface CameraStreamingDelegate { * The handler must respect the desired image height and width given in the {@link SnapshotRequest}. * The returned Buffer (via the callback) must be encoded in jpeg. * - * HAP-NodeJS will complain about slow running handlers after 5 seconds and terminate the request after 15 seconds. + * HAP-NodeJS warns of a handler that has not answered after 8 seconds and fails its snapshot after 25 seconds. A handler that throws, or an async + * handler whose returned promise rejects before it calls back, fails its snapshot at once. * * @param request - Request containing image size. * @param callback - Callback supplied with the resulting Buffer @@ -188,6 +622,28 @@ export interface CameraStreamingDelegate { * - Recording must be enabled by the user. Signaled through {@link updateRecordingActive}. * - Recording configurations must be selected by a HomeKit controller through {@link updateRecordingConfiguration}. * + * A camera records one way, decided by whether it gives the camera capabilities block, and each way needs something different from your plugin. + * + * 1. A camera without the camera capabilities block, which gives the top-level `recording` option: its legacy recording options and this delegate. + * The home hub picks a recording format from your options. The library tells your plugin which format, through + * {@link updateRecordingConfiguration}. The hub stores the recording. + * + * 2. A camera with the camera capabilities block, which takes no top-level `recording` option and has no recording delegate. + * The library records from its camera buffer, and your plugin builds no clip. Your plugin hands each video tier one fragmented MP4 stream of HEVC, + * with Opus in every tier's stream, or in the sound's tier's alone where the sensor's audio states its `source` `'shared'`, through the `TierStream` + * its multi-tier streaming delegate's `tierDemandStarted` is given. + * While the user's switch allows recording and the camera is in service, its accessory published and its source not stated away, the library holds + * the recorded tier itself and keeps its recent samples. It builds every recording a hub asks for from them: the picture, and the sound while + * Recording Audio Active is on. + * The recorded tier is the one its sensor's entry marks `recorded`, or with none marked the first sensor's tier with the most pixels, and the + * block's own `recording` option sets the `prebuffer`, 5000 milliseconds by default and 30000 at most. {@link CameraBufferRecordingOptions} states + * the formats Apple's guide requires of the recorded tier's stream, its bitrates and the cap on a segment. + * A recording a hub asks for while the camera is out of service, or before the camera buffer holds the prebuffer, is declined, and so is one the + * option's `shouldRecord` answers false or whose call stopped the recorder, each refused in the answer to the hub's open as busy. + * A clip a hub uploads from a recording finishes with what that recording served when the camera's source is stated away. + * The controller tells your plugin of each recording through its `recording-started` and `recording-ended` events, and raises the problems of the + * held tier, its buffer and the recordings it serves on the camera's channel, which `onCameraProblem` subscribes to. + * * A typical recording event scenario happens as follows: * - The camera is in idle mode, maintaining the prebuffer (the duration of the prebuffer depends on the selected {@link CameraRecordingConfiguration}). * - A recording event is triggered (e.g. motion or doorbell button press) and the camera signals it through @@ -257,16 +713,16 @@ export interface CameraRecordingDelegate { * It is guaranteed that there is only ever one ongoing recording stream request at a time. * * When this method is called return the currently ongoing (or next in case of a potentially queued) - * recording via an `AsyncGenerator`. Every `yield` of the generator represents a complete recording `packet`. + * recording as an async iterable, an async generator being the usual form. Every value it yields represents a complete recording `packet`. * The first packet MUST always be the {@link PacketDataType.MEDIA_INITIALIZATION} packet. * Any following packet will transport the actual mp4 fragments in {@link PacketDataType.MEDIA_FRAGMENT} packets, * starting with the content of the prebuffer. Every {@link PacketDataType.MEDIA_FRAGMENT} starts with a key frame * and must not be longer than the specified duration set via the `CameraRecordingConfiguration.mediaContainerConfiguration.fragmentLength` * **selected** by the HomeKit Controller in {@link updateRecordingConfiguration}. * - * NOTE: You MUST respect the value of {@link Characteristic.RecordingAudioActive} characteristic of the {@link Service.CameraOperatingMode} + * NOTE: You MUST respect the value of {@link Characteristic.RecordingAudioActive} characteristic of the {@link Service.CameraRecordingManagement} * service. When the characteristic is set to false you MUST NOT include audio in the mp4 fragments. You can access the characteristic via - * the `CameraController.recordingManagement.operatingModeService` property. + * the `CameraController.recordingManagement.recordingManagementService` property. * * You might throw an error in this method if encountering a non-recoverable state. * You may throw a {@link HDSProtocolError} to manually define the {@link HDSProtocolSpecificErrorReason} for the `DATA_SEND` `CLOSE` event. @@ -281,25 +737,30 @@ export interface CameraRecordingDelegate { * - Closed by the HomeKit Controller (unexpectedly): A HomeKit Controller might at any point decide to close a recording stream * if it encounters erroneous state. This is signaled by a call to {@link closeRecordingStream} with the respective reason. * - * Once a close of stream is signaled, the `AsyncGenerator` function must return gracefully. + * HAP-NodeJS takes one iterator from the async iterable and consumes it as `for await` does, and when a stream closes before the iterable ends it + * closes that iterator through its optional `return` method, which an async generator answers by running its `finally` blocks. + * Once a close of stream is signaled, the async iterable must end gracefully. * - * For more information about `AsyncGenerator`s you might have a look at: + * For more information about async iterables you might have a look at: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of * - * NOTE: HAP-NodeJS guarantees that this method is only called with a valid selected {@link CameraRecordingConfiguration}. + * NOTE: HAP-NodeJS guarantees that this method is only called with a valid selected {@link CameraRecordingConfiguration} on a camera that gives the + * legacy recording options. * * NOTE: Don't rely on the streamId for unique identification. Two {@link DataStreamConnection}s might share the same identifier space. * * @param streamId - The streamId of the currently ongoing stream. * @param signal - An optional {@link AbortSignal} that is aborted when the recording stream is closed. Delegates can use this to interrupt pending async - * operations (e.g. pacing delays) for immediate cleanup, rather than waiting for {@link closeRecordingStream} to be called. + * operations (e.g. pacing delays) for immediate cleanup, rather than waiting for {@link closeRecordingStream} to be called. A listener on the signal runs + * outside the library's guard: a throw from it is an uncaught exception that ends the process. A child process started with the signal raises an + * error when the signal aborts, which ends the process where the plugin listens for no `error` on that child process. */ - handleRecordingStreamRequest(streamId: number, signal?: AbortSignal): AsyncGenerator + handleRecordingStreamRequest(streamId: number, signal?: AbortSignal): AsyncIterable /** * This method is called once the HomeKit Controller acknowledges the `endOfStream`. * An `endOfStream` is sent by the accessory by setting {@link RecordingPacket.isLast} to `true` in the last packet yielded - * by the {@link handleRecordingStreamRequest} `AsyncGenerator`. + * by the async iterable {@link handleRecordingStreamRequest} answers. * * @param streamId - The streamId of the acknowledged stream. */ @@ -310,7 +771,7 @@ export interface CameraRecordingDelegate { * * The method is also called if an ongoing recording stream is closed gracefully (using {@link HDSProtocolSpecificErrorReason.NORMAL}). * In either case, the delegate should stop supplying further fragments to the recording stream. - * The `AsyncGenerator` function must return without yielding any further {@link RecordingPacket}s. + * The async iterable must end without yielding any further {@link RecordingPacket}s. * HAP-NodeJS won't send out any fragments from this point onwards. * * @param streamId - The streamId for which the close event was sent. @@ -347,9 +808,46 @@ export interface CameraControllerServiceMap extends ControllerServiceMap { export interface CameraControllerState { streamManagements: RTPStreamManagementState[] recordingManagement?: RecordingManagementState + /** + * The operating mode, present while a characteristic projects a field of it or while the camera carries a restored slice that holds a field none of its + * services projects. A state without it keeps the operating mode in {@link CameraControllerState.recordingManagement}, which `deserialize` reads instead. + */ + operatingMode?: OperatingModeState + /** + * Each video sensor's multi-tier stream state, keyed by its sensor UUID in lowercase: the state of every sensor the plugin supplies, written over the + * record the last restore read. The state of a sensor missing from the plugin's inventory is kept untouched. Present while the camera supplies a sensor + * or carries a restored record. + */ + multiTierStreamManagements?: Record + /** + * Each video sensor's WebRTC stream state, keyed by its sensor UUID in lowercase: the state of every sensor the plugin supplies a WebRTC stream service + * for, written over the record the last restore read. The state of a sensor missing from the plugin's inventory is kept untouched. Present while the + * camera supplies a WebRTC stream service or carries a restored record. + */ + webRTCStreamManagements?: Record + /** + * Each video sensor's motion zones state, keyed by its sensor UUID in lowercase: the state of every sensor the plugin lists for zones, written over the + * record the last restore read. The state of a sensor missing from the plugin's list is kept untouched. Present while the camera supplies a zones + * service or carries a restored record. + */ + motionZonesManagements?: Record + /** + * Whether the camera's Microphone is muted, which a camera with the camera capabilities block alone stores and restores. A run without the block + * drops it. + */ + microphoneMuted?: boolean + /** + * Whether the camera's Speaker is muted, which a camera with the camera capabilities block alone stores where it has a Speaker and restores. A run + * without the block drops it. + */ + speakerMuted?: boolean } /** + * The events a camera controller emits, which a plugin reads through `api.hap`, as in `hap.CameraControllerEvents.RECORDING_STARTED`. A listener's + * failure that an event names as a `plugin-failure` problem is published on the camera's channel and printed where nothing subscribes, as + * {@link CameraControllerCapabilitiesOptions} states. + * * @group Camera */ export enum CameraControllerEvents { @@ -357,13 +855,119 @@ export enum CameraControllerEvents { * Emitted when the mute state or the volume changed. The Apple Home App typically does not set those values * except the mute state. When you adjust the volume in the Camera view it will reset the muted state if it was set previously. * The value of volume has nothing to do with the volume slider in the Camera view of the Home app. + * On a camera with the camera capabilities block the library mutes the camera's live sound itself: a muted Microphone sends a view at home or from + * away no sound while a recording keeps its sound as Recording Audio Active says, and a listener has nothing to do for the mute. + * Each listener is called in turn and the library waits on none: a throw or a rejection is a `plugin-failure` problem on the channel of a camera with + * the camera capabilities block and is logged on any other camera, and the next listener is still called. */ MICROPHONE_PROPERTIES_CHANGED = 'microphone-change', /** * Emitted when the mute state or the volume changed. The Apple Home App typically does not set those values * except the mute state. When you unmute the device microphone it will reset the mute state if it was set previously. + * On a camera with the camera capabilities block the library mutes talkback itself: a muted Speaker has the library write no talkback to a sink, and + * a listener has nothing to do for the mute. + * Each listener is called in turn and the library waits on none: a throw or a rejection is a `plugin-failure` problem on the channel of a camera with + * the camera capabilities block and is logged on any other camera, and the next listener is still called. */ SPEAKER_PROPERTIES_CHANGED = 'speaker-change', + /** + * Emitted once for each change of an operating-mode field, whichever characteristic carried it, with the field, its value and the reason, after the + * field's side effects. A write that leaves the value unchanged emits it again. A restore and a factory reset store every field first and then emit once + * for each, in the order they write the fields, while a characteristic's own change event arrives as each field is stored, which is why a plugin reads the camera's + * whole state at this event. A field a listener writes to another value while a restore or a reset emits stands, emitted by that write alone. A field + * written from a characteristic's own change listener while a restore or a reset still stores is emitted at once, the camera's state part restored, and a + * field later in their order then takes their value and is emitted again. Plugins keep writing a field through its characteristic. Each listener is called + * in turn and the library waits on none: a throw or a rejection is a `plugin-failure` problem on the channel of a camera with the camera capabilities + * block and is logged on any other camera, the next listener is still called, and the write is answered as it stands. + */ + OPERATING_MODE_CHANGED = 'operating-mode-change', + /** + * Emitted once for each change of a video sensor's Camera Multi-Tier RTP Stream Management or Camera WebRTC Stream Management `StreamingEnabled`, with + * a {@link StreamingEnabledChange} naming the sensor and whether the change is for views at home or from away, with its value and the reason, before the + * state-change delegate. A write that leaves the value unchanged emits it again. Each listener is called in turn and the library waits on none: a throw or + * a rejection is a `plugin-failure` problem on the camera's channel and the next listener is still called. + */ + STREAMING_ENABLED_CHANGED = 'streaming-enabled-change', + /** + * Emitted with a {@link CameraRecordingStart} as a camera that records from its camera buffer begins to serve a hub's recording, and never for a + * recording it declines. Each listener is called in turn and the library waits on none: a throw or a rejection is a `plugin-failure` problem on the + * camera's channel and the next listener is still called. + */ + RECORDING_STARTED = 'recording-started', + /** + * Emitted once with a {@link CameraRecordingEnd} for each recording a `recording-started` event told of, as its end is decided: the end of a removal + * reaches its listeners before the controller drops them. Each listener is called in turn and the library waits on none: a throw or a rejection is a + * `plugin-failure` problem on the camera's channel and the next listener is still called. + */ + RECORDING_ENDED = 'recording-ended', + /** + * Emitted with a {@link CameraLiveView} as a live view of a camera with the camera capabilities block starts: a view at home as its session's Start is + * answered with success, and a view from away as the hub's answer to its session's offer is accepted, whether or not its media connects after. Each + * listener is called in turn and the library waits on none: a throw or a rejection is a `plugin-failure` problem on the camera's channel and the next + * listener is still called. + */ + LIVE_VIEW_STARTED = 'live-view-started', + /** + * Emitted once with a {@link CameraLiveView} for each view a `live-view-started` event told of, naming the same view, as its session ends: the end of + * a removal reaches its listeners before the controller drops them. Each listener is called in turn and the library waits on none: a throw or a rejection + * is a `plugin-failure` problem on the camera's channel and the next listener is still called. + */ + LIVE_VIEW_ENDED = 'live-view-ended', +} + +/** + * A recording a camera serves from its camera buffer, as the `recording-started` event tells of it. + * + * @group Camera + */ +export interface CameraRecordingStart { + /** + * The video sensor recorded, in lowercase. + */ + readonly sensorUUID: string + /** + * The video tier recorded. + */ + readonly tierId: number + /** + * The identifier of the hub's recording stream. + */ + readonly streamId: number +} + +/** + * How a recording from the camera buffer ended, each end coming after its last whole segment, and at the camera's source stated away, a long gap or a + * changed description after its segment in progress closed as it stands. + * + * - `ended`: the hub acknowledged the recording's end or closed it normally. + * - `cancelled`: the hub closed it as not allowed, or the camera ended it as recording stopped being allowed or the camera went out of service, at a + * factory reset or at the controller's removal. A close of the segment in progress that fails as the source is stated away still ends the recording + * `cancelled`, without that segment, its failure raised as a `library-failure` problem. + * - `gap`: the recorded tier handed over no picture for the long-gap time of 10 seconds, or of 30 seconds from its source being stated reconnecting, + * the recording ending after its segment in progress. + * - `failed`: a track the recording carries changed its codec description, the recording ending after its segment in progress, a ceiling of the camera + * buffer trimmed past the segment in progress, the recording ending after its last whole segment, the recorder failed as it read the camera buffer, or + * the hub closed the recording for any other reason or its connection closed. A close of the segment in progress that fails at a changed description + * still ends the recording `failed`, without that segment, its failure raised as a `library-failure` problem. + * + * @group Camera + */ +export type CameraRecordingOutcome = 'ended' | 'cancelled' | 'gap' | 'failed' + +/** + * The end of a recording from the camera buffer, as the `recording-ended` event tells of it. + * + * @group Camera + */ +export interface CameraRecordingEnd extends CameraRecordingStart { + /** + * How the recording ended. + */ + readonly outcome: CameraRecordingOutcome + /** + * The media segments the recording sent, its initialization segment not counted. + */ + readonly segments: number } /** @@ -401,9 +1005,21 @@ export type CameraLiveView = { export declare interface CameraController { on(event: 'microphone-change', listener: (muted: boolean, volume: number) => void): this on(event: 'speaker-change', listener: (muted: boolean, volume: number) => void): this + on(event: 'operating-mode-change', listener: (change: OperatingModeChange) => void): this + on(event: 'streaming-enabled-change', listener: (change: StreamingEnabledChange) => void): this + on(event: 'recording-started', listener: (start: CameraRecordingStart) => void): this + on(event: 'recording-ended', listener: (end: CameraRecordingEnd) => void): this + on(event: 'live-view-started', listener: (view: CameraLiveView) => void): this + on(event: 'live-view-ended', listener: (view: CameraLiveView) => void): this emit(event: 'microphone-change', muted: boolean, volume: number): boolean emit(event: 'speaker-change', muted: boolean, volume: number): boolean + emit(event: 'operating-mode-change', change: OperatingModeChange): boolean + emit(event: 'streaming-enabled-change', change: StreamingEnabledChange): boolean + emit(event: 'recording-started', start: CameraRecordingStart): boolean + emit(event: 'recording-ended', end: CameraRecordingEnd): boolean + emit(event: 'live-view-started', view: CameraLiveView): boolean + emit(event: 'live-view-ended', view: CameraLiveView): boolean } /** @@ -412,88 +1028,414 @@ export declare interface CameraController { * @group Camera */ export class CameraController extends EventEmitter implements SerializableController { - private static readonly STREAM_MANAGEMENT = 'streamManagement' // key to index all RTPStreamManagement services - private stateChangeDelegate?: StateChangeDelegate - private readonly streamCount: number - private readonly delegate: CameraStreamingDelegate - private readonly streamingOptions: CameraStreamingOptions /** - * **Temporary** storage for {@link CameraRecordingOptions} and {@link CameraRecordingDelegate}. - * This property is reset to `undefined` after the CameraController was fully initialized. - * You can still access those values via the {@link CameraController.recordingManagement}. + * The legacy streaming of a camera without the camera capabilities block, kept for the controller's life: the plugin's streaming delegate and options, + * and the count of its legacy streams. A camera with the block holds none, which is why every legacy read narrows on this one field. + */ + private readonly legacy?: { + readonly delegate: CameraStreamingDelegate + readonly streamingOptions: CameraStreamingOptions + readonly streamCount: number + } + + /** + * The camera's {@link CameraRecordingOptions} and {@link CameraRecordingDelegate}, kept for the controller's life as the multi-tier options are. A + * controller removed and configured again rebuilds the same recording services. They stay the plugin's own objects, because nothing validates them, and + * the management built from them is {@link CameraController.recordingManagement}. */ - private recording?: { + private readonly recording?: { options: CameraRecordingOptions delegate: CameraRecordingDelegate } /** - * Temporary storage for the sensor option. + * The recording of a camera with the camera capabilities block, from its camera buffer, kept for the controller's life as the recording options are: + * the recorded sensor in lowercase, the recorded tier, the prebuffer and the plugin's shouldRecord, each validated and settled when the controller is + * constructed. */ - private sensorOptions?: { - motion?: Service | boolean - occupancy?: Service | boolean - } + private readonly bufferRecording?: BufferRecording - private readonly legacyMode: boolean = false + /** + * The recorder of a camera that records from its camera buffer, made with each configuration's recording management. + */ + private bufferRecorder?: BufferRecorder /** - * @private + * The keepers of a camera that records from its camera buffer, made with each configuration's recording management, one for each video tier the + * library holds itself: every keeper, and those of the tiers marked `keepRunning`, which the controller raises while the user's switch allows streaming + * and the camera is in service, its accessory published and its source not stated away. */ - streamManagements: RTPStreamManagement[] = [] + private keepers: { readonly every: readonly TierKeeper[], readonly listed: readonly TierKeeper[] } = { every: [], listed: [] } + /** - * The {@link RecordingManagement} which is responsible for handling HomeKit Secure Video. - * This property is only present if recording was configured. + * The sensor option, kept for the controller's life as the recording options are. A controller removed and configured again rebuilds the same + * sensors. */ - recordingManagement?: RecordingManagement + private readonly sensorOptions?: CameraSensorOptions - private microphoneService?: Microphone - private speakerService?: Speaker + /** + * The video sensor inventory the plugin supplies, validated when the controller is constructed. + */ + private readonly sensorRegistry?: SensorRegistry - private microphoneMuted = false - private microphoneVolume = 100 - private speakerMuted = false - private speakerVolume = 100 + /** + * The camera's multi-tier streaming: the plugin's delegate and session bound beside each sensor's tier set as the options boundary built it, `strict` + * among what it carries, in the registry's order, which the constructor keeps for the controller's life. Every configuration builds its managements + * from them, one after a removal included, and a later change to the plugin's entries never reaches one. + */ + private readonly streaming?: Required & { readonly tiers: readonly SensorStreamTiers[] } - motionService?: MotionSensor - private motionServiceExternallySupplied = false - occupancyService?: OccupancySensor - private occupancyServiceExternallySupplied = false + /** + * The snapshot function of a camera with the camera capabilities block, kept for the controller's life as the multi-tier options are, which every + * snapshot of the camera calls. + */ + private readonly snapshot?: (request: CameraSnapshotRequest, signal: AbortSignal) => Promise - constructor(options: CameraControllerOptions, legacyMode = false) { - super() - this.streamCount = Math.max(1, options.cameraStreamCount || 1) - this.delegate = options.delegate - this.streamingOptions = options.streamingOptions - this.recording = options.recording - this.sensorOptions = options.sensors + /** + * The controller of each call of the snapshot function whose fetch has not settled, which the controller's removal aborts. A fetch adds its call before + * the function is called and takes it out as it settles, whichever way: nothing aborts a call's signal once its snapshot is answered or refused. + */ + private readonly snapshotCalls = new Set() - this.legacyMode = legacyMode // legacy mode will prevent Microphone and Speaker services from being created to avoid collisions - } + /** + * The multi-tier stream record the last restore read, which `serialize` writes each management's state over. A sensor missing from the plugin's + * inventory keeps its state. + */ + private restoredMultiTierStreamManagements?: Record /** - * @private + * The camera's WebRTC streaming, which every camera with the camera capabilities block holds, kept for the controller's life as the multi-tier options + * are: the camera's one engine, which answers every sensor's WebRTC service from the stream tiers that service advertises and holds the voice setting, + * and the bound the constructor validated, never the plugin's own object. */ - controllerId(): ControllerIdentifier { - return DefaultControllerType.CAMERA - } + private readonly webrtc?: { readonly engine: WebRTCEngine, readonly options: Required> } - // ----------------------------------- STREAM API ------------------------------------ + /** + * The WebRTC stream record the last restore read, which `serialize` writes each management's state over. A sensor missing from the plugin's inventory + * keeps its state. + */ + private restoredWebRTCStreamManagements?: Record /** - * Call this method if you want to forcefully suspend an ongoing streaming session. - * This would be adequate if the rtp server or media encoding encountered an unexpected error. - * - * @param sessionId - id of the current ongoing streaming session + * The camera's motion zones, kept for the controller's life as the multi-tier options are: each zoned sensor's `motionZones` function by its UUID in + * lowercase, taken apart from its entry as the camera was constructed. A later change to the plugin's entries reaches no configuration. */ - public forceStopStreamingSession(sessionId: SessionIdentifier): void { - this.streamManagements.forEach((management) => { - if (management.sessionIdentifier === sessionId) { - management.forceStop() + private readonly motionZones?: ValidatedVideoSensors['motionZones'] + + /** + * The motion zones record the last restore read, which `serialize` writes each management's state over. A sensor missing from the plugin's list keeps + * its state. + */ + private restoredMotionZonesManagements?: Record + + private readonly legacyMode: boolean = false + + /** + * @private + */ + streamManagements: RTPStreamManagement[] = [] + /** + * The {@link RecordingManagement} which is responsible for handling HomeKit Secure Video. + * This property is present on a camera that gives the `recording` option or the camera capabilities block, and its `options` read undefined on a + * camera with the block, which records from its camera buffer. + */ + recordingManagement?: RecordingManagement + + /** + * Each video sensor's multi-tier stream management, keyed by its sensor UUID in lowercase, in the registry's order. + */ + private readonly multiTierStreamManagements = new Map() + + /** + * Each video sensor's tier table, keyed by its sensor UUID in lowercase, as its multi-tier management takes it. The WebRTC engine joins a sensor's tiers + * through it for a view from away, each keeper holds its tier through it, and the recorder reads the recorded tier's camera buffer through it. + */ + private readonly tierTables = new Map() + + /** + * Each video sensor's WebRTC stream management, keyed by its sensor UUID in lowercase, in the registry's order. + */ + private readonly webRTCStreamManagements = new Map() + + /** + * Each listed video sensor's motion zones management, keyed by its sensor UUID in lowercase, in the registry's order. + */ + private readonly motionZonesManagements = new Map() + + /** + * The recordings a camera with the camera capabilities block serves, one feed per configuration, which its recording stream adds to and its clips upload + * from. + */ + private servedRecordings?: ServedRecordings + + /** + * The HKSV3 recording management of a camera with the camera capabilities block. It is built and dropped with the policy it subscribes, and it is reset + * before the feed at every reset and dropped before it at every removal, the order the camera's lifecycle keeps. + */ + private cmafRecordingManagement?: CMAFRecordingManagement + + /** + * Every part the controller creates or adopts and releases at its removal, released in reverse order. The policy is registered first: it is + * released last, after every part that queries it. + */ + private ownership = new DisposableStack() + + /** + * The owner of the operating mode, which every gate queries. A removed controller disposes it and starts over with a new one. + */ + private operatingMode = this.createOperatingModePolicy() + + private microphoneService?: Microphone + private speakerService?: Speaker + + private microphoneMuted = false + private microphoneVolume = 100 + private speakerMuted = false + private speakerVolume = 100 + + motionService?: MotionSensor + private motionServiceExternallySupplied = false + /** + * The owner of the motion sensor's Contributing Sensors on a camera with the camera capabilities block. + */ + private motionAttribution?: MotionAttribution + occupancyService?: OccupancySensor + private occupancyServiceExternallySupplied = false + + /** + * The context of the accessory the controller is configured on, as the accessory last handed it, and none once the controller is removed. + */ + private accessoryContext?: ControllerAccessoryContext + + /** + * How this configuration of a camera with the camera capabilities block reports, reading the camera's accessory from the context the controller holds, + * and none on a camera without the block. A removal retires it, which means the parts its configuration built keep their camera for their last lines. The + * removal also makes the next configuration's. + */ + private reporter?: CameraReporter + + /** + * Whether the plugin last stated the camera's source away, held for the controller's life, through every factory reset, unpublish and removal, since + * the plugin's source does not change with them. + */ + private sourceAway = false + + /** + * Whether this configuration's restore has completed, which the first context carrying a username marks: the recording management reports an adopted + * recording state once per configuration. + */ + private restoreCompleted = false + + /** + * Builds a camera's controller in the form its options take, which the camera capabilities block decides, and throws a `TypeError` naming the member + * for options that do not hold that form. A camera with the block is refused first for each of the block's own members its documentation names, then + * for a top-level `recording`, `delegate`, `streamingOptions` or `cameraStreamCount` beside the block, then for a `legacyMode` of `true`, and last for + * a `sensors.motion` that is missing or `false`, unless the camera is a doorbell, and once every refusal has passed it reads the specification's + * minimums, as the block's `strict` says. A camera without the block is refused for a missing `delegate`, then a missing `streamingOptions`, then a + * top-level `recording` without its legacy recording options. + * + * @param options - The camera's options, in the form the camera capabilities block decides. + * @param legacyMode - Whether the accessory carries its own audio services, which keeps a camera without the block from publishing its Microphone and + * its Speaker. A camera with the block always publishes its Microphone and takes none. + */ + constructor(options: CameraControllerOptions, legacyMode = false) { + super() + this.sensorOptions = options.sensors + + // The options boundary validates the sensors first and answers the specification's minimums they fall below, which the constructor reads last, and + // builds every value the camera keeps from copies of the entries, never the plugin's objects: a later change inside them reaches no configuration, + // while the delegate stays the plugin's own object. The registry encodes the configurations it answers, and the WebRTC services advertise the tier sets + // it built. + const capabilities = options.cameraCapabilities + if (capabilities) { + const strict = capabilities.strict ?? false + const sensors = validateVideoSensors(capabilities.videoSensors, capabilities.streaming, strict) + + if (typeof capabilities.snapshot !== 'function') { + throw new TypeError('The camera capabilities block has no snapshot function, which answers every snapshot a hub asks for.') } - }) + + this.snapshot = capabilities.snapshot + this.sensorRegistry = new SensorRegistry(sensors.configurations) + this.streaming = { + delegate: capabilities.streaming.delegate, + maxSessions: sensors.maxSessions, + tiers: sensors.tierSets, + } + this.motionZones = sensors.motionZones + this.reporter = this.createReporter() + + // A camera with the block always answers views from away, which is why its engine is built whether or not the block gives its WebRTC settings. The engine + // reaches each sensor's current tier table, ends a session through the sensor's own management, which calls the engine back, reads the Speaker's mute + // as it stands, and checks the voice setting as it is made. + const webrtc = capabilities.webrtc ?? {} + this.webrtc = { + engine: new WebRTCEngine({ + endSession: async (sensorUUID, sessionIdentifier) => { + await this.webRTCStreamManagements.get(sensorUUID)?.endSession(sessionIdentifier) + }, + speakerMuted: () => this.speakerMuted, + tierTable: sensorUUID => this.tierTables.get(sensorUUID), + voice: webrtc.voice, + }), + options: { + maxSessions: webRTCMaxSessions(webrtc.maxSessions), + }, + } + + this.bufferRecording = validateBufferRecordingOptions(capabilities.recording, sensors.recorded) + + // The block's own members are validated first, which is why each member's error names that member whatever else the options lack. Every member of + // the other form an untyped caller can still give beside the block is validated after them. + if (options.recording) { + throw new TypeError('A camera with the camera capabilities block records from its camera buffer and takes no top-level recording option.') + } + + for (const member of ['delegate', 'streamingOptions', 'cameraStreamCount'] as const) { + if (options[member] !== undefined) { + throw new TypeError(`A camera with the camera capabilities block streams through the block and takes no ${member} option.`) + } + } + + if (legacyMode) { + throw new TypeError('A camera with the camera capabilities block takes no legacyMode, since it always publishes its Microphone.') + } + + const motion = options.sensors?.motion + + if (this.motionSensorRequired() && ((motion === undefined) || (motion === false))) { + throw new TypeError('A camera with the camera capabilities block needs a motion sensor in its sensors option, since a hub starts its recordings at ' + + 'motion.') + } + + /* The specification's minimums are read once every refusal has passed: a refusal always names its own member, whatever minimum the camera also + * falls below. A configuration below a minimum still runs: a hub takes such a configuration and a plugin states what its camera has, + * which is why each minimum is a debug event, and strict throws the first instead. + */ + const { maxSessions } = this.webrtc.options + const minimums = (maxSessions < WEBRTC_MINIMUM_SESSIONS) + ? [...sensors.minimums, `The WebRTC streaming holds at most ${counted(maxSessions, 'session')} per video sensor, but the specification requires at least six.`] + : sensors.minimums + + if (strict && (minimums.length > 0)) { + throw new TypeError(minimums[0]) + } + + for (const sentence of minimums) { + this.reporter.debug(CONTROLLER_DEBUG, 'below-minimum', () => ({ sentence })) + } + } else { + for (const member of ['delegate', 'streamingOptions'] as const) { + if (options[member] === undefined) { + throw new TypeError(`A camera without the camera capabilities block needs its ${member} option, since it streams through its legacy stream ` + + 'management.') + } + } + + if (options.recording && !options.recording.options) { + throw new TypeError('A camera without the camera capabilities block needs the recording option\'s options, because it records through them alone.') + } + + this.legacy = { + delegate: options.delegate, + streamingOptions: options.streamingOptions, + streamCount: Math.max(1, options.cameraStreamCount || 1), + } + this.recording = options.recording + } + + // Legacy mode keeps a legacy camera's Microphone and Speaker out, since the accessory carries its own audio services there. + this.legacyMode = legacyMode + } + + /** + * Whether the user's switches allow the camera to record: recording is active, the camera is on and it is not manually disabled, through the recording + * management's Active, HomeKit Camera Active and Manually Disabled. HomeKit Camera Active and Manually Disabled read as allowing it where the camera + * does not carry them, and the recording management's Active reads off where the camera carries none. A camera that does not record reads `false`. + * It reads those switches alone, on a camera with the camera capabilities block and on one without it, and never whether the camera is in service, its + * accessory published and its source not stated away, which means a camera with the block that is out of service reads `true` where its switches allow recording + * while the library records nothing for it. Inside an `operating-mode-change` listener it reads the camera's whole state at each change, a restore's and + * a factory reset's among them, since those store every switch before they raise the event for any. + */ + get recordingAllowed(): boolean { + return this.operatingMode.recordingAllowed() + } + + /** + * Whether the user's switches allow the camera to stream: the camera is on, streaming as a whole is on and the camera is not manually disabled, through + * HomeKit Camera Active, the global Streaming Enabled and Manually Disabled, a switch the camera does not carry reading as allowing it. It reads those + * switches alone, on a camera with the camera capabilities block and on one without it, and never whether the camera is in service, its accessory + * published and its source not stated away, which means a camera with the block that is out of service reads `true` where its switches allow streaming while the + * library runs none of its own streams. Inside an `operating-mode-change` listener it reads the camera's whole state at each change, a restore's and a + * factory reset's among them, since those store every switch before they raise the event for any. + */ + get streamingAllowed(): boolean { + return this.operatingMode.streamingAllowed() + } + + /** + * Whether a camera with the camera capabilities block needs a motion sensor, which the constructor reads before any subclass field is set: a hub starts + * a camera's recordings at motion, and a doorbell, whose press starts them, overrides this to answer `false`. + * + * @returns Whether the constructor refuses a camera with the block that gives no motion sensor. + */ + protected motionSensorRequired(): boolean { + return true + } + + /** + * @private + */ + controllerId(): ControllerIdentifier { + return DefaultControllerType.CAMERA + } + + // ----------------------------------- STREAM API ------------------------------------ + + /** + * Call this method if you want to forcefully suspend an ongoing streaming session. + * On a camera without the camera capabilities block, call it where the RTP server or the media encoding meets an unexpected error. On a camera with the + * block, a failing tier is told through `TierStream.fail`, and this method ends the one view a `live-view-started` event named. + * The legacy stream holding the identifier tells its delegate STOP for it, a multi-tier or WebRTC session under it ends, and an identifier no session + * holds is ignored. + * + * @param sessionId - id of the current ongoing streaming session + */ + public forceStopStreamingSession(sessionId: SessionIdentifier): void { + for (const management of this.streamManagements) { + if (management.sessionIdentifier === sessionId) { + management.forceStop() + } + } + + for (const management of this.multiTierStreamManagements.values()) { + void management.endSession(sessionId) + } + + for (const management of this.webRTCStreamManagements.values()) { + void management.endSession(sessionId) + } + } + + /** + * The newest keyframe of a video sensor's best running tier on a camera with the camera capabilities block, as a movie of that one picture with its + * width, height and age, for a snapshot a plugin takes on its own. Nothing is started for it: a tier that is not running keeps no keyframe, and a plugin + * that wants a keyframe at every call marks a tier `keepRunning`. The movie's bytes are the library's, handed again while that keyframe is the newest. + * A plugin reads them and never changes them. A tier whose newest keyframe lacks any of HEVC's video, sequence and picture parameter sets, in the + * keyframe and in its stream's description alike, answers none, and the next tier that runs answers in its place. + * + * @param sensorUUID - The video sensor's UUID, in any case, or none for the camera's first sensor. + * @returns The keyframe, or `undefined` for a camera without the block, a sensor the camera does not have, a camera not configured and a sensor none of + * whose tiers runs with a newest keyframe a decoder can read. + */ + public latestKeyframe(sensorUUID?: string): CameraKeyframe | undefined { + const sensor = sensorUUID?.toLowerCase() ?? this.sensorRegistry?.sensorUUIDs[0] + + return (sensor === undefined) + ? undefined + : this.tierTables.get(sensor)?.latestKeyframe() } public static generateSynchronisationSource(): number { @@ -502,13 +1444,126 @@ export class CameraController extends EventEmitter implements SerializableContro return ssrc.readInt32BE(0) } + /** + * Raises or clears motion on the camera's motion sensor. On a camera with the camera capabilities block it is the way to name the video sensors that saw + * the motion on a camera of several: it writes the motion sensor's {@link Characteristic.ContributingSensors} before + * {@link Characteristic.MotionDetected}, the same Motion Detected a plugin may write itself, and motion that names none, a direct write's among it, + * belongs to every video sensor. On a camera without the block it writes Motion Detected alone, because such a camera has no video sensors to name. A + * camera with no motion sensor changes nothing and tells of each call once: a camera with the block raises a `value-refused` problem on its channel, + * printed where nothing subscribes, and any other camera warns. + * + * On a camera with the block the motion it reports passes the same guard as any write of Motion Detected, which holds motion back while the motion + * sensor's {@link Characteristic.MotionEnabled} is off. Raising motion then writes nothing while clearing it always passes, and the library clears + * standing motion itself as Motion Enabled turns off. + * + * @param detected - Whether motion is detected. + * @param sensorUUIDs - The UUIDs of the video sensors that saw the motion, read only on a camera with the capabilities block. + */ + public updateMotionDetected(detected: boolean, sensorUUIDs?: readonly string[]): void { + if (this.motionAttribution) { + this.motionAttribution.report(detected, sensorUUIDs) + return + } + + if (this.motionService) { + this.motionService.updateCharacteristic(Characteristic.MotionDetected, detected) + return + } + + const sentence = 'The camera has no motion sensor, which means the motion update reaches nothing.' + + // A camera with the capabilities block reports the refusal through its reporter, and a legacy camera, which holds none, warns. + if (this.reporter) { + this.reporter.problem({ kind: 'value-refused', level: 'warning', sentence }) + } else { + console.warn(sentence) + } + } + + /** + * States, for the camera as a whole, that its source is away, back or reconnecting, as {@link CameraSourceState} words it. The statement may come before + * the controller is configured, holds through every factory reset, unpublish and removal, and does nothing on a camera without the camera capabilities + * block, whose streams are its plugin's own. + * + * While the source is away the camera is out of service: the library asks the plugin for no stream and raises no `tier-failed` problem, ends every view and + * recording and withdraws every start still pending, refuses every snapshot without calling the snapshot function, a resource request's with the + * communication failure and one over the data stream as busy, refuses every recording a hub asks for in the answer to its open, as busy, and fails a + * view's Setup Endpoints at home and its Solicit Offer from away with the communication failure, while each multi-tier stream service's Status Active + * follows the user's switches alone. The recording serves its segment in progress before it ends. A clip a hub is uploading finishes with the segments + * its recording served, and a hub's Start for a recording already served opens a clip while the source is away; the recording's own end is told as + * `cancelled`, an event of the recording stream and not of the clip, while the user's switches, an unpublish, a reset and a removal end every clip. The + * source's state moves no motion or occupancy sensor's Status Active, which follows HomeKit Camera Active alone. A plugin shows a camera it cannot + * reach in its own way. Stated available, the camera is in service again while its accessory is published, and each tier the library holds is raised at + * once. Stated recovering while away, the source is back. + * + * Stated recovering while not away, the source is reconnecting and its streams fall silent meanwhile: every tier whose stream is running is held through + * the reconnect for up to 30 seconds, whoever holds it, a tier the library holds raising no `tier-stalled` problem, its views and an open recording + * waiting on it, and the tier's next picture ends the wait. A tier that hands over no picture by then fails with one `stream-failed` problem, an open + * recording told of the gap and the views on it ended, and a tier the library holds raises `tier-failed` and is asked for again. A tier that has handed + * over no picture yet is left to the bound on its first picture, and a second statement during the wait stretches nothing. A value that is none of the source's + * states throws a `TypeError`, on every camera. + * + * @param state - The source's state. + */ + public updateSourceState(state: CameraSourceState): void { + if (!SOURCE_STATES.includes(state)) { + throw new TypeError(`The source state ${String(state)} is none of 'available', 'recovering' and 'away'.`) + } + + if (this.legacy) { + return + } + + // A source reconnecting while it is not away holds each running tier through the reconnect, and one stated reconnecting while away is back. Every + // keeper is told before any table, which keeps a keeper's gap clock ahead of its demand's at the deadline they share: an open recording is told of + // the gap before the demand's end empties the tier's buffer. + if ((state === 'recovering') && !this.sourceAway) { + for (const keeper of this.keepers.every) { + keeper.sourceRecovering() + } + + for (const table of this.tierTables.values()) { + table.sourceRecovering() + } + + return + } + + const away = state === 'away' + + if (away === this.sourceAway) { + return + } + + const inService = this.operatingMode.inService() + + this.sourceAway = away + this.serviceChanged(inService) + } + // ----------------------------- MICROPHONE/SPEAKER API ------------------------------ + /** + * Mutes or unmutes the camera's Microphone, writing its Mute, and raises no `microphone-change` event, since the plugin made the change. A camera that + * publishes no Microphone ignores the call. + * + * On a camera with the camera capabilities block the library mutes the camera's live sound itself, whether the plugin or a HomeKit controller muted it: + * a muted Microphone sends a view at home or from away no sound, while a recording keeps its sound as Recording Audio Active says, and the camera keeps + * the mute across a restart. Mute is written there only where it holds another value. A camera without the block writes Mute at each call, and its + * plugin mutes its own streams. + * + * @param muted - Whether the Microphone is muted. + */ public setMicrophoneMuted(muted = true): void { if (!this.microphoneService) { return } + if (!this.legacy) { + this.muteMicrophone(muted) + return + } + this.microphoneMuted = muted this.microphoneService.updateCharacteristic(Characteristic.Mute, muted) } @@ -522,11 +1577,27 @@ export class CameraController extends EventEmitter implements SerializableContro this.microphoneService.updateCharacteristic(Characteristic.Volume, volume) } + /** + * Mutes or unmutes the camera's Speaker, writing its Mute, and raises no `speaker-change` event, since the plugin made the change. A camera that publishes + * no Speaker ignores the call. + * + * On a camera with the camera capabilities block the library mutes talkback itself, whether the plugin or a HomeKit controller muted it: a muted Speaker + * has the library write no talkback packet to a sink and start none, at home and from away, a sink already started stays started, and the camera keeps + * the mute across a restart. Mute is written there only where it holds another value. A camera without the block writes Mute at each call, and its + * plugin mutes its own talkback. + * + * @param muted - Whether the Speaker is muted. + */ public setSpeakerMuted(muted = true): void { if (!this.speakerService) { return } + if (!this.legacy) { + this.muteSpeaker(muted) + return + } + this.speakerMuted = muted this.speakerService.updateCharacteristic(Characteristic.Mute, muted) } @@ -540,12 +1611,46 @@ export class CameraController extends EventEmitter implements SerializableContro this.speakerService.updateCharacteristic(Characteristic.Volume, volume) } - private emitMicrophoneChange() { - this.emit(CameraControllerEvents.MICROPHONE_PROPERTIES_CHANGED, this.microphoneMuted, this.microphoneVolume) + /* The one setter of a camera with the block's Microphone mute, which a HomeKit write, the plugin's setter, a restore and a factory reset each call, and a + * legacy camera never does: it assigns the field, writes Mute where it holds another value and sets every tier table's flag, and each running demand's sound + * follows from its next release. The setter also tells the state-change delegate where the field moved, which is how the mute is stored. + */ + private muteMicrophone(muted: boolean): void { + const moved = this.microphoneMuted !== muted + + this.microphoneMuted = muted + writeMute(this.microphoneService, muted) + + for (const table of this.tierTables.values()) { + table.muteMicrophone(muted) + } + + if (moved) { + this.stateChangeDelegate?.() + } } - private emitSpeakerChange() { - this.emit(CameraControllerEvents.SPEAKER_PROPERTIES_CHANGED, this.speakerMuted, this.speakerVolume) + /* The one setter of a camera with the block's Speaker mute, which a HomeKit write, the plugin's setter, a restore and a factory reset each call, and a + * legacy camera never does: it assigns the field, which every talkback reads at each packet, writes Mute where it holds another value, and tells the + * state-change delegate where the field moved, which is how the mute is stored. + */ + private muteSpeaker(muted: boolean): void { + const moved = this.speakerMuted !== muted + + this.speakerMuted = muted + writeMute(this.speakerService, muted) + + if (moved) { + this.stateChangeDelegate?.() + } + } + + private emitMicrophoneChange(): void { + dispatchEvent(this, CameraControllerEvents.MICROPHONE_PROPERTIES_CHANGED, this.reporter, this.microphoneMuted, this.microphoneVolume) + } + + private emitSpeakerChange(): void { + dispatchEvent(this, CameraControllerEvents.SPEAKER_PROPERTIES_CHANGED, this.reporter, this.speakerMuted, this.speakerVolume) } // ----------------------------------------------------------------------------------- @@ -553,25 +1658,16 @@ export class CameraController extends EventEmitter implements SerializableContro * @private */ constructServices(): CameraControllerServiceMap { - for (let i = 0; i < this.streamCount; i++) { - const rtp = new RTPStreamManagement(i, this.streamingOptions, this.delegate, undefined, this.rtpStreamManagementDisabledThroughOperatingMode.bind(this)) - this.streamManagements.push(rtp) + for (let i = 0; i < (this.legacy?.streamCount ?? 0); i++) { + this.createStreamManagement(i) } - if (!this.legacyMode && this.streamingOptions.audio) { - // In theory the Microphone Service is a necessity. In practice, it's not. lol. - // So we just add it if the user wants to support audio - this.microphoneService = new Service.Microphone('', '') - this.microphoneService.setCharacteristic(Characteristic.Volume, this.microphoneVolume) - - if (this.streamingOptions.audio.twoWayAudio) { - this.speakerService = new Service.Speaker('', '') - this.speakerService.setCharacteristic(Characteristic.Volume, this.speakerVolume) - } + if (this.microphoneWanted()) { + this.microphoneService = this.createMicrophoneService() } - if (this.recording) { - this.recordingManagement = new RecordingManagement(this.recording.options, this.recording.delegate, this.retrieveEventTriggerOptions()) + if (this.speakerWanted()) { + this.speakerService = this.createSpeakerService() } if (this.sensorOptions?.motion) { @@ -583,7 +1679,6 @@ export class CameraController extends EventEmitter implements SerializableContro } this.motionService.setCharacteristic(Characteristic.StatusActive, true) - this.recordingManagement?.recordingManagementService.addLinkedService(this.motionService) } if (this.sensorOptions?.occupancy) { @@ -595,7 +1690,6 @@ export class CameraController extends EventEmitter implements SerializableContro } this.occupancyService.setCharacteristic(Characteristic.StatusActive, true) - this.recordingManagement?.recordingManagementService.addLinkedService(this.occupancyService) } const serviceMap: CameraControllerServiceMap = { @@ -609,18 +1703,28 @@ export class CameraController extends EventEmitter implements SerializableContro : undefined, } - if (this.recordingManagement) { - serviceMap.cameraEventRecordingManagement = this.recordingManagement.recordingManagementService - serviceMap.cameraOperatingMode = this.recordingManagement.operatingModeService - serviceMap.dataStreamTransportManagement = this.recordingManagement.dataStreamManagement.getService() + // The recording reconciler builds the recording services after the sensors, over a map that holds none of them, and each sensor then links to the + // recording service, after the data stream service the recording management links itself. + this.reconcileRecordingServices(serviceMap) + + for (const sensor of [this.motionService, this.occupancyService]) { + if (sensor) { + this.recordingManagement?.recordingManagementService.addLinkedService(sensor) + } } - this.streamManagements.forEach((management, index) => { - serviceMap[CameraController.STREAM_MANAGEMENT + index] = management.getService() - }) + for (const [index, management] of this.streamManagements.entries()) { + serviceMap[RTPStreamManagement.serviceKey(index)] = management.getService() + } + + // The block's reconcilers build its services the same way, the surface after the recording services, which is why the camera state it shares with them takes the + // recording service's value. Each video sensor's multi-tier stream service is built after the advertisement, in the registry's order, then each sensor's + // WebRTC stream service and each listed sensor's motion zones service, family by family in the same order, and the map leads with the block's keys. + for (const reconcile of this.capabilityReconcilers()) { + reconcile(serviceMap) + } - this.recording = undefined - this.sensorOptions = undefined + orderServiceMap(serviceMap, this.capabilityServiceKeys()) return serviceMap } @@ -637,318 +1741,978 @@ export class CameraController extends EventEmitter implements SerializableContro } protected _initWithServices(serviceMap: CameraControllerServiceMap): { serviceMap: CameraControllerServiceMap, updated: boolean } { - let modifiedServiceMap = false + // Each capability reconciles its own keys, in this order: the sensor reconcilers link their services to the recording service the recording reconciler + // adopts or creates, and the capability key sweep follows every reconciler that claims a prefixed key, the multi-tier and WebRTC stream services' among + // them. The class that owns a capability's keys walks them, and the controller hands it the factory that wires what it builds. Every reconciler runs, + // whatever an earlier one answered. + const reconcilers: ServiceMapReconciler[] = [ + map => RTPStreamManagement.reconcile(map, this.legacy?.streamCount ?? 0, (index, service) => this.createStreamManagement(index, service)), + map => this.reconcileMicrophone(map), + map => this.reconcileSpeaker(map), + map => this.reconcileRecordingServices(map), + map => this.reconcileMotionSensor(map), + map => this.reconcileOccupancySensor(map), + ...this.capabilityReconcilers(), + map => this.reconcileCapabilityKeys(map), + map => this.migrateFromDoorbell(map), + ] + + let updated = false + for (const reconcile of reconcilers) { + if (reconcile(serviceMap)) { + updated = true + } + } - for (let i = 0; true; i++) { - const streamManagementService = serviceMap[CameraController.STREAM_MANAGEMENT + i] + // A map the reconcilers changed leaves with the block's keys first, and an unchanged one as it was saved. The order is applied here rather than in + // initWithServices, because the doorbell's restore reaches the base through this method alone. + if (updated) { + orderServiceMap(serviceMap, this.capabilityServiceKeys()) + } - if (i < this.streamCount) { - const operatingModeClosure = this.rtpStreamManagementDisabledThroughOperatingMode.bind(this) + return { serviceMap, updated } + } - if (streamManagementService) { // normal init - this.streamManagements.push(new RTPStreamManagement(i, this.streamingOptions, this.delegate, streamManagementService, operatingModeClosure)) - } else { // stream count got bigger, we need to create a new service - const management = new RTPStreamManagement(i, this.streamingOptions, this.delegate, undefined, operatingModeClosure) + // The recording services are one set, which the recording management's reconciler adopts or builds while the camera records, through its delegate or + // from its camera buffer, and deletes from a camera that does not record. + private reconcileRecordingServices(serviceMap: CameraControllerServiceMap): boolean { + const { bufferRecording, recording } = this + const create = recording + ? (services?: RecordingManagementServices) => this.createRecordingManagement(recording.delegate, recording.options, services) + : bufferRecording && ((services?: RecordingManagementServices) => this.createBufferRecordingManagement(bufferRecording, services)) - this.streamManagements.push(management) - serviceMap[CameraController.STREAM_MANAGEMENT + i] = management.getService() + return RecordingManagement.reconcile(serviceMap, create) + } - modifiedServiceMap = true - } - } else { - if (streamManagementService) { // stream count got reduced, we need to remove old service - delete serviceMap[CameraController.STREAM_MANAGEMENT + i] - modifiedServiceMap = true - } else { - break // we finished counting, and we got no saved service; we are finished + // The camera capabilities block's reconcilers in the order they run, none for a camera without the block: the surface, the advertisement, then every + // video sensor's multi-tier stream service, WebRTC stream service and motion zones service, family by family, each family in the registry's order, and + // last the HKSV3 recording management's services, after the recording reconciler has made the feed it uploads from. + private capabilityReconcilers(): ServiceMapReconciler[] { + const { sensorRegistry } = this + + if (!sensorRegistry) { + return [] + } + + return [ + map => GlobalOperatingMode.reconcile(map, service => this.createGlobalOperatingMode(service)), + map => sensorRegistry.reconcile(map, service => this.bindCameraCapabilities(service)), + map => MultiTierStreamManagement.reconcile( + map, + this.multiTierStreamManagementOptions(), + (options, service) => this.createMultiTierStreamManagement(options, service), + ), + map => WebRTCStreamManagement.reconcile( + map, + this.webRTCStreamManagementOptions(), + (options, service) => this.createWebRTCStreamManagement(options, service), + ), + map => MotionZonesManagement.reconcile( + map, + this.motionZonesManagementOptions(), + (options, service) => this.createMotionZonesManagement(options, service), + ), + map => CMAFRecordingManagement.reconcile(map, services => this.createCMAFRecordingManagement(services)), + ] + } + + /* The camera capabilities block's keys, in the order every map this controller builds, and every restored map its reconcilers change, leads with them: Camera + * Capabilities, Camera Global Operating Mode, then each video sensor's multi-tier stream service, WebRTC stream service and motion zones service, family by + * family, each family in the registry's order, then the HKSV3 recording management's services, and none for a camera without the block. The accessory + * adds the services a configure adds in map order and numbers each new service above every number it holds. The block's new services take lower + * numbers than any other service the same configure adds. + * Reordering alone is no update: a restored service keeps its number wherever its key stands, and a restore that changes nothing leaves the map as saved. + */ + private capabilityServiceKeys(): string[] { + if (!this.sensorRegistry) { + return [] + } + + return [ + SensorRegistry.SERVICE_KEY, + GlobalOperatingMode.SERVICE_KEY, + ...Array.from(this.multiTierStreamManagements.values(), management => management.serviceKey), + ...Array.from(this.webRTCStreamManagements.values(), management => management.serviceKey), + ...Array.from(this.motionZonesManagements.values(), management => management.serviceKey), + ...CMAFRecordingManagement.SERVICE_KEY_ORDER, + ] + } + + /* Whether the camera publishes its Microphone, the one rule a construct and a restore share: a camera with the block always, since it always states one + * audio tier, and a legacy camera while it streams audio, which legacy mode keeps out, because the accessory carries its own audio services there. + */ + private microphoneWanted(): boolean { + return this.legacy + ? !this.legacyMode && !!this.legacy.streamingOptions.audio + : true + } + + /* Whether the camera publishes its Speaker, the one rule a construct and a restore share: a camera with the block publishes it exactly where its multi-tier delegate + * has talkbackStarted, which means a controller offers talkback to a camera that takes it. A legacy camera publishes it while it streams two-way audio, which legacy + * mode keeps out for the same reason it keeps out the Microphone. + */ + private speakerWanted(): boolean { + return this.legacy + ? !this.legacyMode && !!this.legacy.streamingOptions.audio?.twoWayAudio + : typeof this.streaming?.delegate.talkbackStarted === 'function' + } + + private reconcileMicrophone(serviceMap: CameraControllerServiceMap): boolean { + const { service, modified } = reconcileAudioService(serviceMap, 'microphone', this.microphoneWanted(), () => this.createMicrophoneService()) + this.microphoneService = service + return modified + } + + private reconcileSpeaker(serviceMap: CameraControllerServiceMap): boolean { + const { service, modified } = reconcileAudioService(serviceMap, 'speaker', this.speakerWanted(), () => this.createSpeakerService()) + this.speakerService = service + return modified + } + + private reconcileMotionSensor(serviceMap: CameraControllerServiceMap): boolean { + const option = this.sensorOptions?.motion + const savedWithBlock = Object.keys(serviceMap).some(key => key.startsWith(CAPABILITY_KEY_PREFIX)) + const { service, modified } = this.reconcileSensor(serviceMap, 'motionService', option, () => new Service.MotionSensor('', '')) + + if (service) { + this.motionService = service + + if (typeof option !== 'boolean') { + this.motionServiceExternallySupplied = true + } + } + + /* A camera restored without the capabilities block whose saved map carries a key under the capability prefix ran with the block before, when the + * controller added Contributing Sensors and Motion Enabled to its motion sensor, which is why they leave the motion sensor in use, whoever built it, a plugin's + * own among them, as the capability key sweep drops the block's services. A camera that never had the block keeps whatever the plugin gave its sensor. + */ + if (!this.sensorRegistry && savedWithBlock && service) { + for (const type of [Characteristic.ContributingSensors, Characteristic.MotionEnabled]) { + const characteristic = service.characteristics.find(candidate => candidate.UUID === type.UUID) + + if (characteristic) { + service.removeCharacteristic(characteristic) } } } - // MICROPHONE - if (!this.legacyMode && this.streamingOptions.audio) { // microphone should be present - if (serviceMap.microphone) { - this.microphoneService = serviceMap.microphone - } else { - // microphone wasn't created yet => create a new one - this.microphoneService = new Service.Microphone('', '') - this.microphoneService.setCharacteristic(Characteristic.Volume, this.microphoneVolume) + return modified + } + + private reconcileOccupancySensor(serviceMap: CameraControllerServiceMap): boolean { + const option = this.sensorOptions?.occupancy + const { service, modified } = this.reconcileSensor(serviceMap, 'occupancyService', option, () => new Service.OccupancySensor('', '')) + + if (service) { + this.occupancyService = service - serviceMap.microphone = this.microphoneService - modifiedServiceMap = true + if (typeof option !== 'boolean') { + this.occupancyServiceExternallySupplied = true } - } else if (serviceMap.microphone) { // microphone service supplied, though settings seemed to have changed - // we need to remove it - delete serviceMap.microphone - modifiedServiceMap = true } - // SPEAKER - if (!this.legacyMode && this.streamingOptions.audio?.twoWayAudio) { // speaker should be present - if (serviceMap.speaker) { - this.speakerService = serviceMap.speaker - } else { - // speaker wasn't created yet => create a new one - this.speakerService = new Service.Speaker('', '') - this.speakerService.setCharacteristic(Characteristic.Volume, this.speakerVolume) + return modified + } - serviceMap.speaker = this.speakerService - modifiedServiceMap = true + /* The rule the motion and the occupancy sensor share. A sensor its option leaves out is deleted from the map. A boolean option adopts the saved sensor or + * creates one and inserts it under its key, which is why the accessory adds it through the map as it adds any service a restore inserts. A service option is the + * plugin's own sensor, which the plugin restores itself, and a saved sensor it replaces is deleted from the map. A deleted sensor is unlinked from the + * recording service first, and the wanted sensor is marked active and linked to it. A created sensor can sit beside an external sensor an earlier run + * linked, which stays linked, because the map never held it. + */ + private reconcileSensor( + serviceMap: CameraControllerServiceMap, + key: 'motionService' | 'occupancyService', + option: Service | boolean | undefined, + create: () => Service, + ): { service?: Service, modified: boolean } { + const saved = serviceMap[key] + const recordingService = this.recordingManagement?.recordingManagementService + + if (!option) { + if (!saved) { + return { modified: false } } - } else if (serviceMap.speaker) { // speaker service supplied, though settings seemed to have changed - // we need to remove it - delete serviceMap.speaker - modifiedServiceMap = true - } - - // RECORDING - if (this.recording) { - const eventTriggers = this.retrieveEventTriggerOptions() - - // RECORDING MANAGEMENT - if (serviceMap.cameraEventRecordingManagement && serviceMap.cameraOperatingMode && serviceMap.dataStreamTransportManagement) { - this.recordingManagement = new RecordingManagement( - this.recording.options, - this.recording.delegate, - eventTriggers, - { - recordingManagement: serviceMap.cameraEventRecordingManagement, - operatingMode: serviceMap.cameraOperatingMode, - dataStreamManagement: new DataStreamManagement(serviceMap.dataStreamTransportManagement), - }, - ) + + recordingService?.removeLinkedService(saved) + delete serviceMap[key] + return { modified: true } + } + + let service: Service + let modified = false + if (typeof option === 'boolean') { + if (saved) { + service = saved } else { - this.recordingManagement = new RecordingManagement( - this.recording.options, - this.recording.delegate, - eventTriggers, - ) - - serviceMap.cameraEventRecordingManagement = this.recordingManagement.recordingManagementService - serviceMap.cameraOperatingMode = this.recordingManagement.operatingModeService - serviceMap.dataStreamTransportManagement = this.recordingManagement.dataStreamManagement.getService() - modifiedServiceMap = true + service = create() + serviceMap[key] = service + modified = true } } else { - if (serviceMap.cameraEventRecordingManagement) { - delete serviceMap.cameraEventRecordingManagement - modifiedServiceMap = true + service = option + + if (saved) { + recordingService?.removeLinkedService(saved) + delete serviceMap[key] + modified = true } - if (serviceMap.cameraOperatingMode) { - delete serviceMap.cameraOperatingMode - modifiedServiceMap = true + } + + service.setCharacteristic(Characteristic.StatusActive, true) + recordingService?.addLinkedService(service) + return { service, modified } + } + + // Every key under the capability prefix that the configured block does not claim is deleted, and a camera restored without the block keeps no orphaned + // service, whichever run of the camera saved the key. The block claims the surface's key, the advertisement's and the key of each per-sensor management + // the reconcile built, the WebRTC and motion zones managements among them. The services of a video sensor missing from the plugin's inventory are + // deleted, as is every zones key of a sensor whose entry gives no motionZones function, and a camera without the block claims none, its WebRTC keys + // among them. + private reconcileCapabilityKeys(serviceMap: CameraControllerServiceMap): boolean { + const claimed = this.capabilityServiceKeys() + let modified = false + + for (const key of Object.keys(serviceMap)) { + if (key.startsWith(CAPABILITY_KEY_PREFIX) && !claimed.includes(key)) { + delete serviceMap[key] + modified = true } - if (serviceMap.dataStreamTransportManagement) { - delete serviceMap.dataStreamTransportManagement - modifiedServiceMap = true + } + + return modified + } + + // overwritten in DoorbellController (to avoid cyclic dependencies, I hate typescript for that) + protected migrateFromDoorbell(serviceMap: ControllerServiceMap): boolean { + if (serviceMap.doorbell) { // See NOTICE in DoorbellController + delete serviceMap.doorbell + return true + } + + return false + } + + protected retrieveEventTriggerOptions(): Set { + if (!this.recording) { + return new Set() + } + + const triggerOptions = new Set() + + if (this.recording.options.overrideEventTriggerOptions) { + for (const option of this.recording.options.overrideEventTriggerOptions) { + triggerOptions.add(option) } } - // MOTION SENSOR if (this.sensorOptions?.motion) { - if (typeof this.sensorOptions.motion === 'boolean') { - if (serviceMap.motionService) { - this.motionService = serviceMap.motionService - } else { - // it could be the case that we previously had a manually supplied motion service - // at this point we can't remove the iid from the list of linked services from the recording management! - this.motionService = new Service.MotionSensor('', '') - - serviceMap.motionService = this.motionService // or the new service is never added to the accessory - modifiedServiceMap = true - } - } else { - this.motionService = this.sensorOptions.motion - this.motionServiceExternallySupplied = true + triggerOptions.add(EventTriggerOption.MOTION) + } - if (serviceMap.motionService) { // motion service previously supplied as bool option - this.recordingManagement?.recordingManagementService.removeLinkedService(serviceMap.motionService) - delete serviceMap.motionService - modifiedServiceMap = true + // this method is overwritten by the `DoorbellController` to automatically configure EventTriggerOption.DOORBELL + + return triggerOptions + } + + /** + * @private + */ + configureServices(): void { + /* A HomeKit write of Mute on a camera with the block answers first, since the characteristic takes the written value inside the callback, and then + * calls the mute's one setter, which finds the characteristic holding the value and writes nothing: the write fires its one change before its one + * event. A legacy camera's write assigns the field and answers. + */ + if (this.microphoneService) { + this.microphoneService.getCharacteristic(Characteristic.Mute) + .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => { + callback(undefined, this.microphoneMuted) + }) + .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => { + if (this.legacy) { + this.microphoneMuted = value as boolean + callback() + } else { + callback() + this.muteMicrophone(value as boolean) + } + + this.emitMicrophoneChange() + }) + this.microphoneService.getCharacteristic(Characteristic.Volume) + .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => { + callback(undefined, this.microphoneVolume) + }) + .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => { + this.microphoneVolume = value as number + callback() + this.emitMicrophoneChange() + }) + } + + if (this.speakerService) { + this.speakerService.getCharacteristic(Characteristic.Mute) + .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => { + callback(undefined, this.speakerMuted) + }) + .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => { + if (this.legacy) { + this.speakerMuted = value as boolean + callback() + } else { + callback() + this.muteSpeaker(value as boolean) + } + + this.emitSpeakerChange() + }) + this.speakerService.getCharacteristic(Characteristic.Volume) + .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => { + callback(undefined, this.speakerVolume) + }) + .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => { + this.speakerVolume = value as number + callback() + this.emitSpeakerChange() + }) + } + + // make the sensor services available to the RecordingManagement. + if (this.motionService) { + this.recordingManagement?.sensorServices.push(this.motionService) + } + if (this.occupancyService) { + this.recordingManagement?.sensorServices.push(this.occupancyService) + } + + // On a camera with the capabilities block the motion sensor, whoever built it, projects the policy's Motion Enabled, and the attribution keeps its + // Contributing Sensors in step with Motion Detected. + const { motionService, sensorRegistry } = this + if (sensorRegistry && motionService) { + this.operatingMode.bindMotionSensor(motionService) + + const attribution = new MotionAttribution(motionService, sensorRegistry.sensorUUIDs, this.reporter!) + this.motionAttribution = attribution + + /* One listener takes each edge of Motion Detected, a report's and a direct write's alike, and hands it to every consumer of motion, the attribution + * and the HKSV3 recording management's event queue. No consumer listens on its own. The listener skips a write that leaves the value as it stands and is registered + * ahead of the service's own listener: the attribution writes its list before the service forwards the motion change. The ownership + * stack releases it at a removal. + */ + const motionDetected = motionService.getCharacteristic(Characteristic.MotionDetected) + const recordingManagement = this.cmafRecordingManagement + const motionChanged = ({ newValue, oldValue }: CharacteristicChange): void => { + if (!!newValue !== !!oldValue) { + attribution.motionChanged(!!newValue) + recordingManagement?.motionChanged(!!newValue) } } - this.motionService.setCharacteristic(Characteristic.StatusActive, true) - this.recordingManagement?.recordingManagementService.addLinkedService(this.motionService) - } else { - if (serviceMap.motionService) { - this.recordingManagement?.recordingManagementService.removeLinkedService(serviceMap.motionService) - delete serviceMap.motionService - modifiedServiceMap = true + motionDetected.prependListener(CharacteristicEventTypes.CHANGE, motionChanged) + this.ownership.defer(() => motionDetected.removeListener(CharacteristicEventTypes.CHANGE, motionChanged)) + + /* Motion Detected stores no motion while Motion Enabled reads off, whoever writes it and by whichever call, and a clear is stored as written. The + * guard sits in the characteristic's own value path rather than a listener, since a hub has been told a value before any listener can answer it. It + * reads this configuration's policy at each value, and the ownership stack removes it at a removal, as it releases the listener above. + */ + const policy = this.operatingMode + + this.ownership.use(guardValues(motionDetected, value => (value && !policy.motionEnabled) + ? false + : value)) + + /* Motion Enabled turned off clears standing motion through the report's own path. The attribution empties its list and every consumer hears the + * clear: at each write of off, a restore's among them, through the subscription on this configuration's policy, and once here where it reads off + * already, since the sensor's first projection is no write and tells no subscriber. + */ + this.operatingMode.subscribe('motionEnabled', (enabled) => { + if (!enabled) { + this.updateMotionDetected(false) + } + }) + + if (!this.operatingMode.motionEnabled) { + this.updateMotionDetected(false) } } - // OCCUPANCY SENSOR - if (this.sensorOptions?.occupancy) { - if (typeof this.sensorOptions.occupancy === 'boolean') { - if (serviceMap.occupancyService) { - this.occupancyService = serviceMap.occupancyService - } else { - // it could be the case that we previously had a manually supplied occupancy service - // at this point we can't remove the iid from the list of linked services from the recording management! - this.occupancyService = new Service.OccupancySensor('', '') - - serviceMap.occupancyService = this.occupancyService // or the new service is never added to the accessory - modifiedServiceMap = true + for (const management of this.multiTierStreamManagements.values()) { + management.configureServices() + } + + /* The controller binds each WebRTC service's Streaming Enabled into the policy under its key, and the key's stream gate, which its Solicit Offer + * queries, reads it. The controller also subscribes the key's streamOpen derivation, the gate read open, which means a camera that stops allowing the service's + * sessions, or goes out of service, releases its answers and ends them. The controller makes the bind and the subscription because the class takes its gate as a + * function and holds no policy. The session end runs ahead of every hook and state-change delegate, because the policy tells its derivations before the + * field-change hook and the state-change delegate. + */ + for (const management of this.webRTCStreamManagements.values()) { + this.operatingMode.bindStreamingEnabled(management.serviceKey, management.getService().getCharacteristic(Characteristic.StreamingEnabled)) + this.operatingMode.subscribeDerivation('streamOpen', (open) => { + if (!open) { + void management.endAllSessions() } + }, management.serviceKey) + } + + /* A camera that records from its camera buffer holds the recorded tier while the user's switch allows recording and the camera is in service, its + * accessory published and its source not stated away, and each tier marked keepRunning while the user's switch allows streaming and the camera is in + * service, from this configure on, the tier tables standing. The plugin's tierDemandStarted runs here for each tier a reason holds already, and + * otherwise once the camera is in service. + */ + this.bufferRecorder?.configure() + this.operatingMode.subscribeDerivation('streamingInService', () => this.keepRunning()) + this.keepRunning() + } + + /* Raises or releases the kept-running reason of each listed tier's keeper, as streaming is allowed and the camera is in service or not: at a configure, + * at each move of the policy's streamingInService through the subscription on this configuration's policy, which handleControllerRemoved disposes, and + * once a reset has run. A keeper's raise calls the plugin's tierDemandStarted in the same turn, and a release calls what a start registered, which means the + * plugin can change whether the camera is in service inside such a call: a start that states its source away has the policy tell every subscriber, + * this one among them, before this loop reaches its next keeper. The loop reads the policy at each keeper rather than once before it: it raises + * nothing once the camera is out of service and releases nothing once it is back. + */ + private keepRunning(): void { + for (const keeper of this.keepers.listed) { + if (this.operatingMode.streamingInService()) { + keeper.raise('kept-running') } else { - this.occupancyService = this.sensorOptions.occupancy - this.occupancyServiceExternallySupplied = true + keeper.release('kept-running') + } + } + } - if (serviceMap.occupancyService) { // occupancy service previously supplied as bool option - this.recordingManagement?.recordingManagementService.removeLinkedService(serviceMap.occupancyService) - delete serviceMap.occupancyService - modifiedServiceMap = true - } + /* Each factory below wires what it builds into this controller and registers it on the ownership stack, the one place a removal releases it from. A + * legacy stream is a legacy camera's alone, since a camera with the block counts none: this factory reads the legacy streaming every such camera holds. + */ + private createStreamManagement(index: number, service?: CameraRTPStreamManagement): RTPStreamManagement { + const operatingMode = this.operatingMode + const { delegate, streamingOptions } = this.legacy! + const management = new RTPStreamManagement(index, streamingOptions, delegate, service, () => operatingMode.legacyStreamingDisabled(index)) + operatingMode.bindStream(index, management.getService()) + + /* The camera's half of the disable transition: the stream hears its own Active, and the camera's state, which this controller owns, moves through the + * policy. A camera that stops allowing streams releases every answer the stream's Setup Endpoints holds. The subscription lives on this policy, + * which handleControllerRemoved disposes, and it ends with this controller's managements. + */ + operatingMode.subscribeDerivation('streamingAllowed', (allowed) => { + if (!allowed) { + management.service.getCharacteristic(Characteristic.SetupEndpoints).releaseTransientAnswers() } + }) + + this.streamManagements.push(this.ownership.adopt(management, stream => stream.destroy())) + return management + } + + private createMicrophoneService(): Microphone { + const microphone = new Service.Microphone('', '') + microphone.setCharacteristic(Characteristic.Volume, this.microphoneVolume) + return microphone + } + + private createSpeakerService(): Speaker { + const speaker = new Service.Speaker('', '') + speaker.setCharacteristic(Characteristic.Volume, this.speakerVolume) + return speaker + } + + /* The recording management reads the event triggers from the recording and sensor options the controller keeps. On a camera with the capabilities block + * it takes the configuration's feed, which turns on the producer reference time box its recordings carry and serves those recordings to the HKSV3 + * recording management's clips, and the recorder's decision it asks before it answers a recording open, and it answers the snapshots a hub asks over + * the data stream through this controller's snapshot gate, whose cause of a refusal it maps to its own reason, and its fetch. The feed goes on the + * ownership stack before that management: a removal drops the management first. The feed's `store-full` problem names the sensor the camera buffer + * records and goes through this configuration's reporter, as each failed call of that management's delegate does. + */ + private createRecordingManagement( + delegate: CameraRecordingDelegate, + options: CameraRecordingOptions | undefined, + services?: RecordingManagementServices, + admit?: (streamId: number) => RecordingAdmission, + ): RecordingManagement { + const { bufferRecording } = this + const feed = bufferRecording && this.ownership.use(new ServedRecordings({ + reporter: this.reporter!, + sensorUUID: bufferRecording.sensorUUID, + })) + const capabilities = feed && { + admit, + feed, + reporter: this.reporter!, + snapshot: { + refusal: (reason: ResourceRequestReason | undefined): SnapshotRefusal | undefined => this.snapshotGate(this.reporter!.name, reason), + fetch: async (request: SnapshotFetch): Promise => await this.fetchSnapshot(request), + }, + } + const management = new RecordingManagement(options, delegate, this.retrieveEventTriggerOptions(), services, this.operatingMode, capabilities) + this.servedRecordings = feed + this.recordingManagement = this.ownership.adopt(management, recordingManagement => recordingManagement.destroy()) + return management + } + + /* A camera with the camera capabilities block records from its camera buffer: its recording management takes the recorder as its delegate, whose + * decision on each open it asks before it answers the open, and no legacy options. The keepers and the recorder are this configuration's, the keepers + * and the recorder going on the ownership stack after the management: a removal drops them first. A video tier the library holds has one keeper, + * whatever reasons stand: the recorded tier, whose recording reason the recorder drives, and each tier marked keepRunning, whose kept-running reason the + * controller drives, a marked recorded tier taking the recorded tier's keeper, which means it raises one demand and one set of problems and spans the prebuffer + * while its recording reason stands. Each keeper and the recorder reach a tier's buffer through the sensor's tier table, by a lookup, since the tables + * are built after the recording reconciler, and the recorded tier's keeper alone tells this configuration's recorder of a long gap. Every problem goes + * through this configuration's reporter and every recording event through the guarded dispatch. + */ + private createBufferRecordingManagement(recording: BufferRecording, services?: RecordingManagementServices): RecordingManagement { + const reporter = this.reporter! + const tierTable = (sensorUUID: string): TierTable | undefined => this.tierTables.get(sensorUUID) + const keeper = new TierKeeper({ + gap: () => this.bufferRecorder?.lapsed(), + prebuffer: recording.prebuffer, + reporter, + sensorUUID: recording.sensorUUID, + tierId: recording.tierId, + tierTable, + }) + const keepers = new Map([ + [`${recording.sensorUUID} ${recording.tierId}`, keeper], + ]) + const marked = this.sensorStreamTiers().flatMap(({ tiers }) => Array.from(tiers.values()).filter(tier => tier.keepRunning)) + const listed = marked.map(({ id: tierId, sensorUUID }) => { + const key = `${sensorUUID} ${tierId}` + const made = keepers.get(key) ?? new TierKeeper({ + prebuffer: recording.prebuffer, + reporter, + sensorUUID, + tierId, + tierTable, + }) + + keepers.set(key, made) + + return made + }) + const recorder = new BufferRecorder({ + ...recording, + ended: end => dispatchEvent(this, CameraControllerEvents.RECORDING_ENDED, this.reporter, end), + keeper, + policy: this.operatingMode, + reporter, + started: start => dispatchEvent(this, CameraControllerEvents.RECORDING_STARTED, this.reporter, start), + tierTable, + }) + const management = this.createRecordingManagement(recorder, undefined, services, streamId => recorder.admit(streamId)) + const every = Array.from(keepers.values()) + + for (const made of every) { + this.ownership.use(made) + } + + this.keepers = { every, listed } + this.bufferRecorder = this.ownership.use(recorder) + + 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. + private createCMAFRecordingManagement(services: Partial): CMAFRecordingManagement { + const management = new CMAFRecordingManagement({ feed: this.servedRecordings!, policy: this.operatingMode, reporter: this.reporter! }, services) + this.cmafRecordingManagement = this.ownership.adopt(management, cmafRecordingManagement => void cmafRecordingManagement.destroy()) + + if (this.accessoryContext) { + management.handleAccessoryContext(this.accessoryContext) + } + + return management + } + + private createGlobalOperatingMode(service?: CameraGlobalOperatingMode): GlobalOperatingMode { + return new GlobalOperatingMode(this.operatingMode, service) + } + + private bindCameraCapabilities(service: CameraCapabilities): void { + this.operatingMode.bindCameraCapabilities(service) + } + + private createMultiTierStreamManagement(options: MultiTierStreamManagementOptions, service?: CameraMultiTierRTPStreamManagement): MultiTierStreamManagement { + const management = new MultiTierStreamManagement(options, this.operatingMode, service) + this.multiTierStreamManagements.set(options.table.sensorUUID, this.ownership.adopt(management, multiTier => void multiTier.destroy())) + this.tierTables.set(options.table.sensorUUID, options.table) + return management + } + + // The WebRTC management's gate queries the policy it was built with, as the legacy stream's does. A removed controller's management never reads its + // successor's. The engine's werift load starts here: a camera without the block never loads werift, and a first offer finds it loaded. + private createWebRTCStreamManagement(options: WebRTCStreamManagementOptions, service?: CameraWebRTCStreamManagement): WebRTCStreamManagement { + const operatingMode = this.operatingMode + const sensorUUID = options.sensorUUID.toLowerCase() + const key = WebRTCStreamManagement.serviceKey(options.sensorUUID) + const management = new WebRTCStreamManagement(options, () => operatingMode.streamGate(key), service) + this.webRTCStreamManagements.set(sensorUUID, this.ownership.adopt(management, webRTC => void webRTC.destroy())) + this.webrtc?.engine.preload() + + /* A hub asks for a remote view over WebRTC once a video sensor's Camera Multi-Tier RTP Stream Management and Camera WebRTC Stream Management services + * link each other, which is why each links the other here. A restore that adopts a standing link leaves it as it is. The WebRTC reconciler runs after the + * multi-tier one at a construct and at a restore alike: the sensor's multi-tier management stands here, and a reconciler order that reached this + * factory first throws at the lookup rather than dropping the link. + */ + const multiTier = this.multiTierStreamManagements.get(sensorUUID)!.getService() + const webRTC = management.getService() + multiTier.addLinkedService(webRTC) + webRTC.addLinkedService(multiTier) + + return management + } + + /* A video sensor's Camera Motion Zones service links the sensor's Camera Multi-Tier RTP Stream Management service one way, which ties the zones to the + * sensor whose coordinates they use, and the multi-tier service's own links are left as they are. The zones reconciler runs after the multi-tier one at a + * construct and at a restore alike: the sensor's multi-tier management stands here, and a reconciler order that reached this factory first throws at + * the lookup rather than dropping the link. + */ + private createMotionZonesManagement(options: MotionZonesManagementOptions, service?: CameraMotionZones): MotionZonesManagement { + const management = new MotionZonesManagement(options, service) + this.motionZonesManagements.set(options.sensorUUID, this.ownership.adopt(management, zones => zones.destroy())) + management.getService().addLinkedService(this.multiTierStreamManagements.get(options.sensorUUID)!.getService()) + + return management + } + + // Each video sensor's tier set, as the options boundary built it in the registry's order, and none without the camera capabilities block. + private sensorStreamTiers(): readonly SensorStreamTiers[] { + return this.streaming?.tiers ?? [] + } + + /* One set of multi-tier options per video sensor, each management reporting its Streaming Enabled changes and its live views' starts and ends as this + * controller's events and reading the Speaker's mute as it stands. Each sensor's tier table is built here, the composition root, from the camera's + * delegate and the very tier set the sensor's WebRTC service is handed. Every tier the table holds carries the stream tier object the sensor's services + * advertise, and with it each video tier's buffer, which the tier holds for the table's life. Each table takes the Microphone's mute as it stands as it is + * made, and the mute's one setter sets every table from then on. Each table, its buffers and each management report through this configuration's + * reporter. + */ + private multiTierStreamManagementOptions(): MultiTierStreamManagementOptions[] { + const { streaming } = this - this.occupancyService.setCharacteristic(Characteristic.StatusActive, true) - this.recordingManagement?.recordingManagementService.addLinkedService(this.occupancyService) - } else { - if (serviceMap.occupancyService) { - this.recordingManagement?.recordingManagementService.removeLinkedService(serviceMap.occupancyService) - delete serviceMap.occupancyService - modifiedServiceMap = true - } + if (!streaming) { + return [] } - if (this.migrateFromDoorbell(serviceMap)) { - modifiedServiceMap = true - } + const reporter = this.reporter! - this.recording = undefined - this.sensorOptions = undefined + return this.sensorStreamTiers().map((tiers) => { + const table = new TierTable(streaming.delegate, tiers, tier => new TierBuffer(tier), reporter) - return { - serviceMap, - updated: modifiedServiceMap, - } + table.muteMicrophone(this.microphoneMuted) + + return { + delegate: streaming.delegate, + table, + maxSessions: streaming.maxSessions, + onLiveViewEnded: this.liveViewEnded, + onLiveViewStarted: this.liveViewStarted, + onStreamingEnabledChange: this.streamingEnabledChanged, + reporter, + speakerMuted: () => this.speakerMuted, + } + }) } - // overwritten in DoorbellController (to avoid cyclic dependencies, I hate typescript for that) - protected migrateFromDoorbell(serviceMap: ControllerServiceMap): boolean { - if (serviceMap.doorbell) { // See NOTICE in DoorbellController - delete serviceMap.doorbell - return true + // One set of WebRTC options per video sensor, none without the camera capabilities block: the camera's engine, this configuration's reporter, the bound, + // the sensor's lowercase UUID and the video and audio tiers of its tier set, each management reporting its Streaming Enabled changes and its live views' + // starts and ends as this controller's events. + private webRTCStreamManagementOptions(): WebRTCStreamManagementOptions[] { + const { webrtc } = this + + if (!webrtc) { + return [] } - return false + const reporter = this.reporter! + + return this.sensorStreamTiers().map(({ audioStreamTiers, sensorUUID, videoStreamTiers }) => ({ + engine: webrtc.engine, + reporter, + maxSessions: webrtc.options.maxSessions, + videoStreamTiers, + audioStreamTiers, + sensorUUID: sensorUUID.toLowerCase(), + onLiveViewEnded: this.liveViewEnded, + onLiveViewStarted: this.liveViewStarted, + onStreamingEnabledChange: this.streamingEnabledChanged, + })) } - protected retrieveEventTriggerOptions(): Set { - if (!this.recording) { - return new Set() - } - - const triggerOptions = new Set() + // One set of zones options per video sensor whose entry gives a motionZones function, in the registry's order, each with that function, the sensor's + // dimensions as the registry kept them and this configuration's reporter, and none without the block. + private motionZonesManagementOptions(): MotionZonesManagementOptions[] { + const { motionZones, reporter, sensorRegistry } = this - if (this.recording.options.overrideEventTriggerOptions) { - for (const option of this.recording.options.overrideEventTriggerOptions) { - triggerOptions.add(option) - } + if (!motionZones || !sensorRegistry) { + return [] } - if (this.sensorOptions?.motion) { - triggerOptions.add(EventTriggerOption.MOTION) - } + return sensorRegistry.sensorUUIDs + .filter(sensorUUID => motionZones.has(sensorUUID)) + .map(sensorUUID => ({ + motionZones: motionZones.get(sensorUUID)!, + reporter: reporter!, + sensorUUID, + sensorDimensions: sensorRegistry.sensorDimensions(sensorUUID)!, + })) + } - // this method is overwritten by the `DoorbellController` to automatically configure EventTriggerOption.DOORBELL + /* The hook every stream management reports a change of its Streaming Enabled through, which makes each change this controller's event for a plugin and a + * debug event for a tool. The debug event is written first: the channel tells each change before anything a listener does in answer to it. The event + * goes through the guarded dispatch, and a listener's throw never reaches the write that carried the change. + */ + private readonly streamingEnabledChanged = (change: StreamingEnabledChange): void => { + const { reason, sensorUUID, value, where } = change + + this.reporter?.debug(CONTROLLER_DEBUG, 'streaming-enabled-change', () => ({ + reason, + sensorUUID, + sentence: `Streaming Enabled for views ${(where === 'home') + ? 'at home' + : 'from away'} of the video sensor ${sensorUUID} reads ${String(value)}, its reason ${reason}.`, + value, + where, + })) + dispatchEvent(this, CameraControllerEvents.STREAMING_ENABLED_CHANGED, this.reporter, change) + } - return triggerOptions + // The hooks every stream management tells of a live view's start and its end through, which makes each this controller's event. Each goes through the guarded + // dispatch, and a listener's throw never reaches the session's Start, its answer or its exit. + private readonly liveViewStarted = (view: CameraLiveView): void => { + dispatchEvent(this, CameraControllerEvents.LIVE_VIEW_STARTED, this.reporter, view) } - /** - * @private - */ - configureServices(): void { - if (this.microphoneService) { - this.microphoneService.getCharacteristic(Characteristic.Mute) - .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => { - callback(undefined, this.microphoneMuted) - }) - .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => { - this.microphoneMuted = value as boolean - callback() - this.emitMicrophoneChange() - }) - this.microphoneService.getCharacteristic(Characteristic.Volume) - .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => { - callback(undefined, this.microphoneVolume) - }) - .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => { - this.microphoneVolume = value as number - callback() - this.emitMicrophoneChange() - }) - } + private readonly liveViewEnded = (view: CameraLiveView): void => { + dispatchEvent(this, CameraControllerEvents.LIVE_VIEW_ENDED, this.reporter, view) + } - if (this.speakerService) { - this.speakerService.getCharacteristic(Characteristic.Mute) - .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => { - callback(undefined, this.speakerMuted) - }) - .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => { - this.speakerMuted = value as boolean - callback() - this.emitSpeakerChange() - }) - this.speakerService.getCharacteristic(Characteristic.Volume) - .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => { - callback(undefined, this.speakerVolume) - }) - .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => { - this.speakerVolume = value as number - callback() - this.emitSpeakerChange() - }) - } + /* The one construction of the policy, at the controller's creation and at its removal: each policy announces its field changes, recording turned on + * or off among them, as this controller's event for a plugin, through the guarded dispatch, and as a debug event for a tool, the debug event written + * first so the channel tells each change before anything a listener does in answer to it. Each policy reads whether the camera's accessory is + * published, from the context the controller holds, and whether its source is away, from the fact the controller holds, each as it stands at each + * query, the policy a removal makes among them. It goes on the ownership stack first, which is why a removal disposes it after every part that queries it. + */ + private createOperatingModePolicy(): OperatingModePolicy { + return this.ownership.use(new OperatingModePolicy({ + fieldChanged: (change) => { + const { field, reason, value } = change - // make the sensor services available to the RecordingManagement. - if (this.motionService) { - this.recordingManagement?.sensorServices.push(this.motionService) - } - if (this.occupancyService) { - this.recordingManagement?.sensorServices.push(this.occupancyService) - } + this.reporter?.debug(CONTROLLER_DEBUG, 'operating-mode-change', () => ({ + field, + reason, + sentence: `The camera's ${field} reads ${String(value)}, its reason ${reason}.`, + value, + })) + dispatchEvent(this, CameraControllerEvents.OPERATING_MODE_CHANGED, this.reporter, change) + }, + published: () => this.accessoryContext?.published === true, + sourceAway: () => this.sourceAway, + })) } - private rtpStreamManagementDisabledThroughOperatingMode(): boolean { - return this.recordingManagement - ? !this.recordingManagement.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value - : false + // The one construction of a configuration's reporter, at the controller's creation and at its removal, as the policy's, reading the camera's accessory + // from the context the controller holds as it stands at each report. + private createReporter(): CameraReporter { + return new CameraReporter(() => this.accessoryContext) } /** * @private */ handleControllerRemoved(): void { + // Every pending call of the snapshot function is aborted before anything else: its plugin hears that no hub waits on the picture before any part of + // the camera it might read ends, and each fetch settles as failed. + for (const call of this.snapshotCalls) { + call.abort() + } + + // Every keeper is closed next: the reset below, which releases each keeper's reasons in its own order, raises no tier whatever the policy reads. The + // accessory hands a controller it removes a context reading not published first, which is why neither its reset before this call nor the one below raises a tier + // there. The close holds the same for a removal that hands none. + for (const keeper of this.keepers.every) { + keeper.close() + } + + // The state-change delegate is taken off before the reset, since a removal reports no change: the reset moves every part back to its first state, and + // a part that told the delegate of it would queue a save of a controller that is leaving. An accessory that removes a controller has untracked it by + // now, and a caller of this method alone meets the same silence. A controller configured again is handed its delegate afresh. + this.setupStateChangeDelegate(undefined) this.handleFactoryReset() - for (const management of this.streamManagements) { - management.destroy() + // The stack releases every part in reverse order, the policy last, and a new stack and policy follow. A controller configured again starts over. + this.ownership.dispose() + this.ownership = new DisposableStack() + this.operatingMode = this.createOperatingModePolicy() + + // The removed configuration's reporter keeps the context it reads at this point, before the clear below: the teardown its parts run after this call + // names this accessory, and the next configuration reports through a reporter of its own. + if (this.reporter) { + this.reporter.retire() + this.reporter = this.createReporter() } + this.streamManagements.splice(0, this.streamManagements.length) + this.multiTierStreamManagements.clear() + this.tierTables.clear() + this.webRTCStreamManagements.clear() + this.motionZonesManagements.clear() + this.cmafRecordingManagement = undefined + this.servedRecordings = undefined + this.bufferRecorder = undefined + this.keepers = { every: [], listed: [] } + this.motionAttribution = undefined this.microphoneService = undefined this.speakerService = undefined - - this.recordingManagement?.destroy() this.recordingManagement = undefined + this.motionService = undefined + this.motionServiceExternallySupplied = false + this.occupancyService = undefined + this.occupancyServiceExternallySupplied = false + this.accessoryContext = undefined + this.restoreCompleted = false this.removeAllListeners() } + /** + * @private + */ + handleAccessoryContext(context: ControllerAccessoryContext): void { + const held = this.accessoryContext + + // The accessory hands its context again at every later publish and its end, unpublish, link, unlink, configure and destroy, which is why one naming the + // accessory, the username and the published state already held is no change. + if (held !== undefined && held.accessoryUUID === context.accessoryUUID && held.username === context.username && held.published === context.published) { + return + } + + const inService = this.operatingMode.inService() + + // The problems a restore held before this context are reported as it arrives, before anything it sets off reports: they keep the order raised. + this.accessoryContext = context + this.reporter?.releaseProblems() + this.cmafRecordingManagement?.handleAccessoryContext(context) + this.serviceChanged(inService) + + /* A configure writes no Status Active, since the accessory hands its first context after the configure and the restore. The first context of each + * configuration writes each multi-tier service's from the policy as it stands, and the derivations carry each later move. A camera configured after + * its accessory is published then moves no Status Active to false on the way to true. + */ + if (held === undefined) { + for (const management of this.multiTierStreamManagements.values()) { + management.writeStatusActive() + } + } + + // The accessory hands a context carrying a username only once its controller storage has restored this controller, which means the first one is where the + // restore completed, whether it read a stored record or found none. + if (context.username !== undefined && !this.restoreCompleted) { + this.restoreCompleted = true + this.recordingManagement?.handleRestoreComplete() + + /* A camera that starts without the capabilities block clears its own entry of the recording provisioning record to its marks. The credentials + * and the Camera Key a run with the block left go, and a later run with the block reads Needs Update, while the marks stay so no number is used + * twice. It names its own accessory, since a bridged camera's username is its bridge's, which every camera of the bridge shares. The clear follows + * the restore's mark and report inside a guard of its own, which is why a store that throws warns and skips neither. + */ + if (this.legacy) { + try { + RecordingProvisioning.clearProvisioning(context.username, context.accessoryUUID) + } catch (error) { + console.warn(`[${this.accessoryName()}] The camera's recording provisioning record could not be written: ${errorMessage(error)}`) + } + } + } + } + + // The camera's name in a line a legacy camera writes, its Accessory Information's Name characteristic, since the accessory builds that service unnamed, + // and none while the controller holds no context. A camera with the capabilities block names itself through its reporter. + private accessoryName(): string | undefined { + return this.accessoryContext && accessoryNameOf(this.accessoryContext) + } + + /* A cause of whether the camera is in service has changed, the camera in service before it as given. The policy recomputes every derivation, which as + * the camera leaves service releases the keepers, ends the recording, ends the clips where recording stops being allowed or the accessory is + * unpublished, and ends every session, in that order, a source stated away leaving each clip to finish, and as it returns raises each tier the library + * holds. Where the camera left service, every start still pending on any of its tables is then withdrawn with a debug event and no + * problem, since the plugin did nothing wrong: its signal aborts and what it registered is released at once. The sessions' ends began in the + * recompute's turn, which is why a view from away whose join waits on such a start finds its session ending and writes no refusal. A user's switch-off ends the + * sessions through the same derivations and withdraws nothing. + */ + private serviceChanged(inService: boolean): void { + this.operatingMode.serviceChanged() + + if (!inService || this.operatingMode.inService()) { + return + } + + for (const table of this.tierTables.values()) { + table.withdraw(OUT_OF_SERVICE) + } + } + /** * @private */ handleFactoryReset(): void { - this.streamManagements.forEach(management => management.handleFactoryReset()) - this.recordingManagement?.handleFactoryReset() + // The recorder ends an open recording as cancelled and releases its keeper's recording reason, and every keeper's kept-running reason is released, all + // first: the sessions' reset below withdraws no demand a keeper still waits on. + this.bufferRecorder?.reset() + + for (const keeper of this.keepers.every) { + keeper.release('kept-running') + } + + for (const management of this.streamManagements) { + management.handleFactoryReset() + } + + for (const management of this.multiTierStreamManagements.values()) { + management.handleFactoryReset() + } + + for (const management of this.webRTCStreamManagements.values()) { + management.handleFactoryReset() + } + + for (const management of this.motionZonesManagements.values()) { + management.handleFactoryReset() + } + + // The HKSV3 recording management ends every clip by the reset's path, their events emptied with its queue, before the feed ends and drops every served + // recording, the order the camera's lifecycle keeps. + this.cmafRecordingManagement?.handleFactoryReset() + this.servedRecordings?.clear() + + // The recording management resets the operating mode beside the recording state it owns, and a camera without it resets the policy directly. + if (this.recordingManagement) { + this.recordingManagement.handleFactoryReset() + } else { + this.operatingMode.reset() + } + + /* The reset tells the policy's listeners only of a value it moved. The kept-running reason is read again here, and a listed tier is held again while + * the user's switch allows streaming and the camera is in service, its accessory published and its source not stated away, as at a configure. The + * recorded tier stays released, recording's default being off, and a keeper a removal closed raises nothing. + */ + this.keepRunning() + + // A camera with the block unmutes through each mute's one setter, and its services and its tier tables follow. A legacy camera assigns its fields + // alone, writing no characteristic. + if (this.legacy) { + this.microphoneMuted = false + this.speakerMuted = false + } else { + this.muteMicrophone(false) + this.muteSpeaker(false) + } - this.microphoneMuted = false this.microphoneVolume = 100 - this.speakerMuted = false this.speakerVolume = 100 + this.restoredMultiTierStreamManagements = undefined + this.restoredWebRTCStreamManagements = undefined + this.restoredMotionZonesManagements = undefined } /** @@ -964,16 +2728,50 @@ export class CameraController extends EventEmitter implements SerializableContro } } - return { + const state: CameraControllerState = { streamManagements: streamManagementStates, recordingManagement: this.recordingManagement?.serialize(), + operatingMode: this.operatingMode.serialize(), + } + + const multiTierStreamManagements = serializeSlices(this.multiTierStreamManagements, this.restoredMultiTierStreamManagements) + const webRTCStreamManagements = serializeSlices(this.webRTCStreamManagements, this.restoredWebRTCStreamManagements) + const motionZonesManagements = serializeSlices(this.motionZonesManagements, this.restoredMotionZonesManagements) + + if (multiTierStreamManagements) { + state.multiTierStreamManagements = multiTierStreamManagements + } + + if (webRTCStreamManagements) { + state.webRTCStreamManagements = webRTCStreamManagements + } + + if (motionZonesManagements) { + state.motionZonesManagements = motionZonesManagements + } + + // A camera with the block stores its mutes, the Speaker's where it has one, and a legacy camera's state carries neither. + if (!this.legacy) { + state.microphoneMuted = this.microphoneMuted + + if (this.speakerService) { + state.speakerMuted = this.speakerMuted + } } + + return state } /** * @private */ deserialize(serialized: CameraControllerState): void { + // A restore before the camera's first context runs inside the accessory's configure, which hands that context later in the same call: each problem + // the restore raises is held until it arrives and is reported named by it, or bare at the end of the step where it never does. + if (this.accessoryContext === undefined) { + this.reporter?.holdProblems() + } + for (const streamManagementState of serialized.streamManagements) { const streamManagement = this.streamManagements[streamManagementState.id] if (streamManagement) { @@ -981,10 +2779,18 @@ export class CameraController extends EventEmitter implements SerializableContro } } - if (serialized.recordingManagement) { - if (this.recordingManagement) { - this.recordingManagement.deserialize(serialized.recordingManagement) - } else { + this.restoredMultiTierStreamManagements = deserializeSlices(this.multiTierStreamManagements, serialized.multiTierStreamManagements) + this.restoredWebRTCStreamManagements = deserializeSlices(this.webRTCStreamManagements, serialized.webRTCStreamManagements) + this.restoredMotionZonesManagements = deserializeSlices(this.motionZonesManagements, serialized.motionZonesManagements) + + if (serialized.recordingManagement && this.recordingManagement) { + this.recordingManagement.deserialize(serialized.recordingManagement, serialized.operatingMode) + } else { + /* A camera that recorded saved either its recording state or, when it gave no legacy recording options, only the operating mode slice, whose + * recording Active every camera with the recording services writes. A camera without those services keeps carrying a slice that holds the + * capabilities block's fields, and each later restore forces the streams on again, which leaves them as they already are. + */ + if (!this.recordingManagement && (serialized.recordingManagement || serialized.operatingMode?.recordingActive !== undefined)) { // Active characteristic cannot be controlled if removing HSV, ensure they are all active! for (const streamManagement of this.streamManagements) { streamManagement.service.updateCharacteristic(Characteristic.Active, true) @@ -992,6 +2798,24 @@ export class CameraController extends EventEmitter implements SerializableContro this.stateChangeDelegate?.() } + + // The policy writes only a field a characteristic projects: on a camera with neither the recording services nor the global service every gate + // keeps its default, and the policy carries a slice that holds a field none of the camera's services projects. + if (serialized.operatingMode) { + this.operatingMode.restore(serialized.operatingMode) + } + } + + // A camera with the block restores each mute it stored through that mute's one setter: the stored value wins over the Mute the accessory cache + // restored, and a value that is no boolean restores nothing. + if (!this.legacy) { + if (typeof serialized.microphoneMuted === 'boolean') { + this.muteMicrophone(serialized.microphoneMuted) + } + + if (typeof serialized.speakerMuted === 'boolean') { + this.muteSpeaker(serialized.speakerMuted) + } } } @@ -1005,89 +2829,303 @@ export class CameraController extends EventEmitter implements SerializableContro streamManagement.setupStateChangeDelegate(delegate) } + for (const management of this.multiTierStreamManagements.values()) { + management.setupStateChangeDelegate(delegate) + } + + for (const management of this.webRTCStreamManagements.values()) { + management.setupStateChangeDelegate(delegate) + } + + for (const management of this.motionZonesManagements.values()) { + management.setupStateChangeDelegate(delegate) + } + this.recordingManagement?.setupStateChangeDelegate(delegate) + this.operatingMode.setupStateChangeDelegate(delegate) } /** * @private */ - handleSnapshotRequest(height: number, width: number, accessoryName?: string, reason?: ResourceRequestReason): Promise { + handleSnapshotRequest(height: number, width: number, accessoryName?: string, reason?: ResourceRequestReason, signal?: AbortSignal): Promise { + // A camera with the capabilities block passes its snapshot gate, handed the request's reason, its refusal answered with the status of its cause, and + // then refuses a size no picture has, before its snapshot function is called, and every other camera meets the legacy gate alone. + const cause = this.snapshot && this.snapshotGate(accessoryName, reason) + + if (cause !== undefined) { + return Promise.reject(SNAPSHOT_STATUSES[cause]) + } + + const refusal = this.snapshot + ? this.pictureSizeGate(height, width, accessoryName) + : this.legacySnapshotGate(accessoryName, reason) + + if (refusal !== undefined) { + return Promise.reject(refusal) + } + + return this.fetchSnapshot({ + accessoryName, + height, + reason, + signal, + width, + }) + } + + /* The one gate a snapshot over the data stream passes on a camera with the capabilities block, and the first gate a resource request's snapshot passes + * there. It answers the cause of its refusal, which each path maps to a status of its own: not allowed while streaming is not allowed and then while the + * user switched off the kind the request's reason names, the user's switches read first, and then out of service while the camera is out of service. + * The snapshot function is never called for a camera out of service. + */ + private snapshotGate(accessoryName?: string, reason?: ResourceRequestReason): SnapshotRefusal | undefined { + if (!this.operatingMode.streamingAllowed()) { + this.reporter!.debug(CONTROLLER_DEBUG, 'snapshot-not-allowed', () => ({ + accessoryName, + sentence: `[${accessoryName}] Rejecting snapshot as streaming is not allowed.`, + })) + return 'not allowed' + } + + const switchedOff = this.snapshotKindOff(reason) + + if (switchedOff !== undefined) { + this.reporter!.debug(CONTROLLER_DEBUG, 'snapshot-switched-off', () => ({ + accessoryName, + sentence: `[${accessoryName}] Rejecting snapshot as ${switchedOff} snapshots are switched off.`, + switchedOff, + })) + return 'not allowed' + } + + if (!this.operatingMode.inService()) { + this.reporter!.debug(CONTROLLER_DEBUG, 'snapshot-out-of-service', () => ({ + accessoryName, + sentence: `[${accessoryName}] Rejecting snapshot as the camera is out of service.`, + })) + return 'out of service' + } + + return undefined + } + + /* The kind of snapshot the user switched off that a request's reason asks for, read as the legacy gate reads the switches: an event snapshot while Event + * Snapshots Active is off, a periodic one while Periodic Snapshots Active is off, and one naming no reason while either is off. A reason that names + * neither kind reads as none, as the data stream reads its request's reason. A request answers alike over a resource request and the data stream. + */ + private snapshotKindOff(reason?: ResourceRequestReason): 'event' | 'periodic' | undefined { + if (!this.operatingMode.eventSnapshotsActive && (reason !== ResourceRequestReason.PERIODIC)) { + return 'event' + } + + if (!this.operatingMode.periodicSnapshotsActive && (reason !== ResourceRequestReason.EVENT)) { + return 'periodic' + } + + return undefined + } + + // The size a resource request's snapshot names on a camera with the capabilities block, checked as the data stream's open checks it. The snapshot + // function is handed only a size a picture can have. + private pictureSizeGate(height: number, width: number, accessoryName?: string): HAPStatus | undefined { + if (!isPictureSize(width, height)) { + this.reporter!.debug(CONTROLLER_DEBUG, 'snapshot-size-refused', () => ({ + accessoryName, + sentence: `[${accessoryName}] Rejecting snapshot as it names no valid picture size.`, + })) + return HAPStatus.INVALID_VALUE_IN_REQUEST + } + + return undefined + } + + // The legacy gate: at least one legacy stream Active, then on a recording camera HomeKit Camera Active and the snapshot switches by the request's reason. + private legacySnapshotGate(accessoryName?: string, reason?: ResourceRequestReason): HAPStatus | undefined { // first step is to verify that the reason is applicable to our current policy // disabled if every stream is switched off. Without any stream (e.g. after the controller was removed) nothing is // switched off, and a reduce() without a start value would throw. const streamingDisabled = this.streamManagements.length > 0 - && this.streamManagements.every(management => !management.getService().getCharacteristic(Characteristic.Active).value) + && this.streamManagements.every((_management, index) => !this.operatingMode.streamActive(index)) if (streamingDisabled) { debug('[%s] Rejecting snapshot as streaming is disabled.', accessoryName) - return Promise.reject(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + return HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE } if (this.recordingManagement) { - const operatingModeService = this.recordingManagement.operatingModeService - if (!operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value) { + if (!this.operatingMode.homeKitCameraActive) { debug('[%s] Rejecting snapshot as HomeKit camera is disabled.', accessoryName) - return Promise.reject(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + return HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE } - const eventSnapshotsActive = operatingModeService - .getCharacteristic(Characteristic.EventSnapshotsActive) - .value - if (!eventSnapshotsActive) { + if (!this.operatingMode.eventSnapshotsActive) { if (reason == null) { debug('[%s] Rejecting snapshot as reason is required due to disabled event snapshots.', accessoryName) - return Promise.reject(HAPStatus.INSUFFICIENT_PRIVILEGES) + return HAPStatus.INSUFFICIENT_PRIVILEGES } else if (reason === ResourceRequestReason.EVENT) { debug('[%s] Rejecting snapshot as event snapshots are disabled.', accessoryName) - return Promise.reject(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + return HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE } } - const periodicSnapshotsActive = operatingModeService - .getCharacteristic(Characteristic.PeriodicSnapshotsActive) - .value - if (!periodicSnapshotsActive) { + if (!this.operatingMode.periodicSnapshotsActive) { if (reason == null) { debug('[%s] Rejecting snapshot as reason is required due to disabled periodic snapshots.', accessoryName) - return Promise.reject(HAPStatus.INSUFFICIENT_PRIVILEGES) + return HAPStatus.INSUFFICIENT_PRIVILEGES } else if (reason === ResourceRequestReason.PERIODIC) { debug('[%s] Rejecting snapshot as periodic snapshots are disabled.', accessoryName) - return Promise.reject(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE) + return HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE } } } - // now do the actual snapshot request. - return new Promise((resolve, reject) => { - // TODO test and make timeouts configurable! - let timeout: NodeJS.Timeout | undefined = setTimeout(() => { - console.warn( - `[${accessoryName}] The image snapshot handler for the given accessory is slow to respond! See https://homebridge.io/w/JtMGR for more info.`, - ) - - timeout = setTimeout(() => { - timeout = undefined - - console.warn( - `[${accessoryName}] The image snapshot handler for the given accessory didn't respond at all! See https://homebridge.io/w/JtMGR for more info.`, - ) - - reject(HAPStatus.OPERATION_TIMED_OUT) - }, 17000) - timeout.unref() - }, 8000) + return undefined + } + + // The fetch of one picture, which every gate has let through: from the block's snapshot function on a camera with the camera capabilities block, and + // from the streaming delegate's handler on any other camera. + private fetchSnapshot(fetch: SnapshotFetch): Promise { + return this.snapshot + ? this.fetchFromFunction(this.snapshot, fetch) + : this.fetchFromHandler(this.legacy!.delegate, fetch) + } + + /* Arms the bound of one snapshot's fetch and answers its release, which reports whether the bound still ran: the first of the fetch's answer, its + * failure and the bound's expiry settles it. One bound, its warnings and its expiry, serves the block's snapshot function and a legacy handler alike, + * because a hub waits on the picture the same way whichever form the plugin answers it through, and its warnings name the form it waits on. A + * plugin's author reads the function or the handler it wrote. Each warning goes through the writer its caller hands, a `plugin-failure` problem of the + * camera's for the function and a console warning opened by the camera's name for a handler, and it names the camera as that form's other lines do. + */ + private snapshotBound(warn: (sentence: string) => void, form: 'function' | 'handler', expire: () => void): () => boolean { + let timeout: NodeJS.Timeout | undefined = setTimeout(() => { + warn(`The image snapshot ${form} for the given accessory is slow to respond! See https://homebridge.io/w/JtMGR for more info.`) + + timeout = setTimeout(() => { + timeout = undefined + + warn(`The image snapshot ${form} for the given accessory didn't respond at all! See https://homebridge.io/w/JtMGR for more info.`) + + expire() + }, 17000) timeout.unref() + }, 8000) + timeout.unref() + + return () => { + if (timeout === undefined) { + return false + } + + clearTimeout(timeout) + timeout = undefined + + return true + } + } + + /* The fetch of one picture from the block's snapshot function, for the camera's first video sensor, handed the newest keyframe the library holds of it + * and a signal of the call's own, which the bound's expiry, the asker's signal, through one listener, and the controller's removal abort, and nothing + * else does. The call's settlement, its answer or its error, is awaited through settleWithin over that signal: the fetch settles at the first of the + * answer, the error and the abort, and an outcome of `undefined` is the abort alone. A rejection is a `plugin-failure` problem of the camera's unless the + * call's signal was aborted first. + * Every settle releases the bound, the listener on the asker's signal and the call's place among the pending calls, which means nothing aborts the function's + * signal once the fetch has settled. + */ + private async fetchFromFunction( + snapshot: (request: CameraSnapshotRequest, signal: AbortSignal) => Promise, + { height, reason, signal, width }: SnapshotFetch, + ): Promise { + const reporter = this.reporter! + const sensorUUID = this.sensorRegistry!.sensorUUIDs[0] + const request: CameraSnapshotRequest = { + height, + keyframe: this.latestKeyframe(sensorUUID), + reason, + sensorUUID, + width, + } + const call = new AbortController() + let expired = false + const warn = (sentence: string): void => reporter.problem({ + kind: 'plugin-failure', + level: 'warning', + sensorUUID, + sentence, + }) + const release = this.snapshotBound(warn, 'function', () => { + expired = true + call.abort() + }) + const abandon = (): void => call.abort() + + signal?.addEventListener('abort', abandon, { once: true }) + this.snapshotCalls.add(call) + try { + const pending = (async () => snapshot(request, call.signal))() + + reporter.rejection('plugin-failure', pending, 'The snapshot function failed', call.signal, { sensorUUID }) + + const outcome = await settleWithin(pending.then(answer => ({ answer }), (error: unknown) => ({ error })), call.signal) + + if (outcome === undefined) { + return await Promise.reject(expired + ? HAPStatus.OPERATION_TIMED_OUT + : HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + if ('error' in outcome.value) { + return await Promise.reject(outcome.value.error instanceof HapStatusError + ? outcome.value.error.hapStatus + : HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + const { answer } = outcome.value + + if (!Buffer.isBuffer(answer) || (answer.length === 0)) { + reporter.problem({ + kind: 'plugin-failure', + level: 'error', + sensorUUID, + sentence: 'The snapshot function answered no picture, and the snapshot failed.', + }) + + return await Promise.reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + return answer + } finally { + release() + signal?.removeEventListener('abort', abandon) + this.snapshotCalls.delete(call) + } + } + + // The fetch of one picture from a legacy camera's streaming delegate under the snapshot's bound, its handler handed the request's size and reason alone. + private fetchFromHandler(delegate: CameraStreamingDelegate, { accessoryName, height, reason, width }: SnapshotFetch): Promise { + return new Promise((resolve, reject) => { + const release = this.snapshotBound(sentence => console.warn(`[${accessoryName}] ${sentence}`), 'handler', () => reject(HAPStatus.OPERATION_TIMED_OUT)) + const failure = `[${accessoryName}] Unhandled error thrown inside snapshot request handler` + // A failure while the request still waits fails the snapshot at once, warned of under the failure sentence with the status a HapStatusError names. + const fail = (error: unknown): void => { + console.warn(`${failure}: ${(error as { stack?: string } | undefined)?.stack ?? String(error)}`) + reject(error instanceof HapStatusError + ? error.hapStatus + : HAPStatus.SERVICE_COMMUNICATION_FAILURE) + } + + /* A throw from the handler and the rejection of the promise an async handler returns are each answered while the request still waits, the snapshot + * failing at once rather than at its bound. A rejection that comes once the callback has answered, or once the bound has failed the snapshot, is + * logged under the same sentence, and the answer stands. + */ try { - this.delegate.handleSnapshotRequest({ + const answer = delegate.handleSnapshotRequest({ height, width, reason, }, (error, buffer) => { - if (!timeout) { + if (!release()) { return - } else { - clearTimeout(timeout) - timeout = undefined } if (error) { @@ -1107,18 +3145,20 @@ export class CameraController extends EventEmitter implements SerializableContro resolve(buffer) } }) + + if (isThenable(answer)) { + answer.then(undefined, (error: unknown) => { + if (release()) { + fail(error) + } else { + logDelegateFailure(failure, error) + } + }) + } } catch (error) { - if (!timeout) { - return - } else { - clearTimeout(timeout) - timeout = undefined + if (release()) { + fail(error) } - - console.warn(`[${accessoryName}] Unhandled error thrown inside snapshot request handler: ${errorStack(error) ?? errorMessage(error)}`) - reject(error instanceof HapStatusError - ? error.hapStatus - : HAPStatus.SERVICE_COMMUNICATION_FAILURE) } }) } diff --git a/src/lib/controller/DoorbellController.spec.ts b/src/lib/controller/DoorbellController.spec.ts index 3534f6fea..74e421a66 100644 --- a/src/lib/controller/DoorbellController.spec.ts +++ b/src/lib/controller/DoorbellController.spec.ts @@ -1,17 +1,28 @@ +import type { CharacteristicValue, Nullable } from '../../types.js' + import { Buffer } from 'node:buffer' import { describe, expect, it, vi } from 'vitest' +import { createCameraControllerOptions, MockDelegate } from '../../test-utils/cameraFixtures.js' import { Accessory } from '../Accessory.js' import { EventTriggerOption } from '../camera/index.js' -import { Characteristic } from '../Characteristic.js' +import { Characteristic, CharacteristicEventTypes } from '../Characteristic.js' import { Service } from '../Service.js' import * as uuid from '../util/uuid.js' -import { createCameraControllerOptions } from './CameraController.spec.js' import { DoorbellController, DoorbellOperatingState, DoorbellOperatingStateAbnormalReason, encodeOperatingStateResponse } from './DoorbellController.js' import '../definitions/index.js' +// A doorbell configured on its accessory, removed from it and configured on it again, and the Doorbell services the accessory then holds. +function reconfigured(accessory: Accessory, doorbell: DoorbellController): Service[] { + accessory.configureController(doorbell) + accessory.removeController(doorbell) + accessory.configureController(doorbell) + + return accessory.services.filter(service => service.UUID === Service.Doorbell.UUID) +} + describe('DoorbellController', () => { it('event trigger options', () => { const controller = new DoorbellController(createCameraControllerOptions()) @@ -28,6 +39,46 @@ describe('DoorbellController', () => { expect(controller.recordingManagement.eventTriggerOptions).toEqual(3) }) + it('throws a TypeError naming the rule for a doorbell without the camera capabilities block whose recording option gives no recording options', () => { + const delegate = new MockDelegate() + + expect(() => new DoorbellController({ + ...createCameraControllerOptions(), + // @ts-expect-error The types refuse a recording option without its options, which an untyped caller can still give. + recording: { delegate }, + })).toThrow(new TypeError('A camera without the camera capabilities block needs the recording option\'s options, because it records through them alone.')) + }) + + it('keeps its name through a removal, and a doorbell configured again holds one Doorbell service under that name', () => { + const doorbell = new DoorbellController({ + ...createCameraControllerOptions(), + name: 'Front Door', + }) + + expect(reconfigured(new Accessory('Doorbell', uuid.generate('doorbell-reconfigured-named')), doorbell).map(service => service.displayName)).toEqual([ + 'Front Door', + ]) + }) + + it('keeps its external Doorbell service through a removal, and a doorbell configured again holds that service alone, which a ring after the second ' + + 'configure reaches once', () => { + const external = new Service.Doorbell('Porch', '') + const accessory = new Accessory('Doorbell', uuid.generate('doorbell-reconfigured-external')) + const doorbell = new DoorbellController({ + ...createCameraControllerOptions(), + externalDoorbellService: external, + }) + const rings: Nullable[] = [] + accessory.addService(external) + + expect(reconfigured(accessory, doorbell)).toEqual([external]) + + external.getCharacteristic(Characteristic.ProgrammableSwitchEvent).on(CharacteristicEventTypes.CHANGE, change => rings.push(change.newValue)) + doorbell.ringDoorbell() + + expect(rings).toEqual([Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS]) + }) + describe('ringDoorbell while the controller is not added to an accessory', () => { it('should warn instead of throwing before configureController', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) diff --git a/src/lib/controller/DoorbellController.ts b/src/lib/controller/DoorbellController.ts index ae5896876..691f0263d 100644 --- a/src/lib/controller/DoorbellController.ts +++ b/src/lib/controller/DoorbellController.ts @@ -104,9 +104,10 @@ export class DoorbellController extends CameraController { private doorbellService?: Doorbell private doorbellServiceExternallySupplied = false /** - * Temporary storage. Erased after init. + * The doorbell's options, kept for the controller's life, which serve every configure: each builds the Doorbell service under its given name or takes + * the external service again, a configure after the controller's removal among them. */ - private doorbellOptions?: DoorbellOptions + private readonly doorbellOptions: DoorbellOptions /** * Initializes a new `DoorbellController`. @@ -164,11 +165,12 @@ export class DoorbellController extends CameraController { } override constructServices(): CameraControllerServiceMap { - if (this.doorbellOptions?.externalDoorbellService) { + if (this.doorbellOptions.externalDoorbellService) { this.doorbellService = this.doorbellOptions.externalDoorbellService this.doorbellServiceExternallySupplied = true } else { - this.doorbellService = new Service.Doorbell(this.doorbellOptions?.name ?? '', '') + this.doorbellService = new Service.Doorbell(this.doorbellOptions.name ?? '', '') + this.doorbellServiceExternallySupplied = false } this.doorbellService.setPrimaryService() @@ -182,7 +184,7 @@ export class DoorbellController extends CameraController { override initWithServices(serviceMap: CameraControllerServiceMap): void | CameraControllerServiceMap { const result = super._initWithServices(serviceMap) - if (this.doorbellOptions?.externalDoorbellService) { + if (this.doorbellOptions.externalDoorbellService) { this.doorbellService = this.doorbellOptions.externalDoorbellService this.doorbellServiceExternallySupplied = true @@ -192,9 +194,10 @@ export class DoorbellController extends CameraController { } } else { this.doorbellService = result.serviceMap.doorbell + this.doorbellServiceExternallySupplied = false if (!this.doorbellService) { // see NOTICE above - this.doorbellService = new Service.Doorbell(this.doorbellOptions?.name ?? '', '') + this.doorbellService = new Service.Doorbell(this.doorbellOptions.name ?? '', '') result.serviceMap.doorbell = this.doorbellService result.updated = true @@ -213,6 +216,12 @@ export class DoorbellController extends CameraController { return false } + // A doorbell with the camera capabilities block needs no motion sensor, since the hubs open and keep a recording at a press alone. The base's constructor + // reads this before any field of the doorbell is set, and it reads none. + protected override motionSensorRequired(): boolean { + return false + } + protected override retrieveEventTriggerOptions(): Set { const result = super.retrieveEventTriggerOptions() result.add(EventTriggerOption.DOORBELL) @@ -230,7 +239,5 @@ export class DoorbellController extends CameraController { this.doorbellService!.getCharacteristic(Characteristic.ProgrammableSwitchEvent) .onGet(() => null) // a value of null represents nothing is pressed - - this.doorbellOptions = undefined } } diff --git a/src/lib/controller/eventDispatch.spec.ts b/src/lib/controller/eventDispatch.spec.ts new file mode 100644 index 000000000..3d9ab300a --- /dev/null +++ b/src/lib/controller/eventDispatch.spec.ts @@ -0,0 +1,210 @@ +import type { CameraProblem } from '../camera/diagnostics/problems.js' +import type { HAPConnection } from '../util/eventedhttp.js' +import type { CameraRecordingStart } from './CameraController.js' + +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' + +import { + bufferCamera, + createCameraControllerOptions, + handPublishedContext, + NUMBERED_ACCESSORY_UUID, + twoSensorCameraOptions, +} from '../../test-utils/cameraFixtures.js' +import { settle } from '../../test-utils/settle.js' +import { onCameraProblem } from '../camera/diagnostics/problems.js' +import { Characteristic } from '../Characteristic.js' +import { HAPStatus } from '../HAPServer.js' +import { CameraController, CameraControllerEvents } from './CameraController.js' +import { dispatchEvent } from './eventDispatch.js' + +const HUB = {} as HAPConnection + +const START: CameraRecordingStart = { + sensorUUID: 'a1b2c3d4-0000-4000-8000-000000000001', + streamId: 1, + tierId: 1, +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('eventDispatch', () => { + it('calls every listener in turn, a throwing one among them, hears a once listener once and awaits nothing', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = new CameraController(createCameraControllerOptions()) + const heard: string[] = [] + + camera.on(CameraControllerEvents.RECORDING_STARTED, () => { + heard.push('throwing') + throw new Error('The listener failed.') + }) + camera.on(CameraControllerEvents.RECORDING_STARTED, async () => { + heard.push('rejecting') + throw new Error('The listener rejected.') + }) + camera.on(CameraControllerEvents.RECORDING_STARTED, async () => { + heard.push('pending') + await new Promise(() => undefined) + }) + camera.once(CameraControllerEvents.RECORDING_STARTED, (start) => { + heard.push(`once ${start.streamId}`) + }) + camera.on(CameraControllerEvents.RECORDING_STARTED, (start) => { + heard.push(`last ${start.tierId}`) + }) + dispatchEvent(camera, CameraControllerEvents.RECORDING_STARTED, undefined, START) + dispatchEvent(camera, CameraControllerEvents.RECORDING_STARTED, undefined, START) + + expect(heard).toEqual([ + 'throwing', + 'rejecting', + 'pending', + 'once 1', + 'last 1', + 'throwing', + 'rejecting', + 'pending', + 'last 1', + ]) + + await settle() + + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A listener of the camera controller\'s recording-started event failed: Error: The listener failed.', + 'A listener of the camera controller\'s recording-started event failed: Error: The listener failed.', + 'A listener of the camera controller\'s recording-started event failed: Error: The listener rejected.', + 'A listener of the camera controller\'s recording-started event failed: Error: The listener rejected.', + ]) + }) + + it('answers the write that carried an operating-mode change and a streaming enabled change whose listener throws, logging the throw', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = new CameraController(twoSensorCameraOptions()) + const map = camera.constructServices() + + camera.configureServices() + + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, () => { + throw new Error('The operating-mode-change listener failed.') + }) + camera.on(CameraControllerEvents.STREAMING_ENABLED_CHANGED, () => { + throw new Error('The streaming-enabled-change listener failed.') + }) + + const active = camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive) + const [, streaming] = Object.entries(map).find(([key]) => key.startsWith('cameraCapabilities:multiTierStream:'))! + const enabled = streaming!.getCharacteristic(Characteristic.StreamingEnabled) + + await expect(active.handleSetRequest(0, HUB)).resolves.toBeUndefined() + await expect(enabled.handleSetRequest(false, HUB)).resolves.toBeUndefined() + + expect([active.value, enabled.value]).toEqual([0, false]) + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A listener of the camera controller\'s operating-mode-change event failed: Error: The operating-mode-change listener failed.', + 'A listener of the camera controller\'s streaming-enabled-change event failed: Error: The streaming-enabled-change listener failed.', + ]) + }) + + it('reports a listener\'s throw and its rejection as the plugin\'s failures on the channel of a camera with the block and an accessory, printing nothing ' + + 'and calling the next listener', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const camera = new CameraController(twoSensorCameraOptions()) + const thrown = new Error('The listener failed.') + const rejected = new Error('The listener rejected.') + const heard: string[] = [] + const problems: CameraProblem[] = [] + const subscription = onCameraProblem(NUMBERED_ACCESSORY_UUID, problem => problems.push(problem)) + + onTestFinished(() => { + subscription[Symbol.dispose]() + camera.handleControllerRemoved() + }) + camera.constructServices() + camera.configureServices() + handPublishedContext(camera) + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, () => { + throw thrown + }) + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, async () => { + throw rejected + }) + camera.on(CameraControllerEvents.OPERATING_MODE_CHANGED, ({ field }) => heard.push(field)) + + const active = camera.recordingManagement!.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive) + + await expect(active.handleSetRequest(0, HUB)).resolves.toBeUndefined() + await settle() + + expect(heard).toEqual(['homeKitCameraActive']) + expect(problems.map(problem => ({ ...problem, sentence: problem.sentence.split('\n')[0] }))).toEqual([ + { + accessoryUUID: NUMBERED_ACCESSORY_UUID, + error: thrown, + kind: 'plugin-failure', + level: 'error', + sentence: 'A listener of the camera controller\'s operating-mode-change event failed: Error: The listener failed.', + }, + { + accessoryUUID: NUMBERED_ACCESSORY_UUID, + error: rejected, + kind: 'plugin-failure', + level: 'error', + sentence: 'A listener of the camera controller\'s operating-mode-change event failed: Error: The listener rejected.', + }, + ]) + expect(error).not.toHaveBeenCalled() + }) + + it('answers a write of each mute whose first listener throws, on a camera without the block and one with it, keeping the characteristic\'s status, ' + + 'calling the next listener and logging the throw', async () => { + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined) + + const cameras = [ + createCameraControllerOptions(), + bufferCamera().options, + ] + + for (const options of cameras) { + const camera = new CameraController(options) + const map = camera.constructServices() + const heard: string[] = [] + + camera.configureServices() + + camera.on(CameraControllerEvents.MICROPHONE_PROPERTIES_CHANGED, () => { + throw new Error('The microphone-change listener failed.') + }) + camera.on(CameraControllerEvents.MICROPHONE_PROPERTIES_CHANGED, muted => heard.push(`microphone-change ${muted}`)) + camera.on(CameraControllerEvents.SPEAKER_PROPERTIES_CHANGED, () => { + throw new Error('The speaker-change listener failed.') + }) + camera.on(CameraControllerEvents.SPEAKER_PROPERTIES_CHANGED, muted => heard.push(`speaker-change ${muted}`)) + + const mutes = [map.microphone!, map.speaker!].map(service => service.getCharacteristic(Characteristic.Mute)) + + for (const mute of mutes) { + await expect(mute.handleSetRequest(true, HUB)).resolves.toBeUndefined() + } + + expect(mutes.map(({ statusCode, value }) => ({ statusCode, value }))).toEqual([ + { statusCode: HAPStatus.SUCCESS, value: true }, + { statusCode: HAPStatus.SUCCESS, value: true }, + ]) + expect(heard).toEqual([ + 'microphone-change true', + 'speaker-change true', + ]) + + camera.handleControllerRemoved() + } + + expect(error.mock.calls.map(([line]) => String(line).split('\n')[0])).toEqual([ + 'A listener of the camera controller\'s microphone-change event failed: Error: The microphone-change listener failed.', + 'A listener of the camera controller\'s speaker-change event failed: Error: The speaker-change listener failed.', + 'A listener of the camera controller\'s microphone-change event failed: Error: The microphone-change listener failed.', + 'A listener of the camera controller\'s speaker-change event failed: Error: The speaker-change listener failed.', + ]) + }) +}) diff --git a/src/lib/controller/eventDispatch.ts b/src/lib/controller/eventDispatch.ts new file mode 100644 index 000000000..7d5e31e2a --- /dev/null +++ b/src/lib/controller/eventDispatch.ts @@ -0,0 +1,29 @@ +import type { EventEmitter } from 'node:events' + +import type { CameraReporter } from '../camera/diagnostics/CameraReporter.js' + +import { callDelegate } from '../util/promise-utils.js' + +/** + * Dispatches one of a camera controller's guarded events: nothing is awaited, and each listener is called in turn, in the order it was added, through the guard, which + * means a throw or the rejection of a promise it returns is the listener's failure and the next listener is still called. A camera with the camera + * capabilities block hands its reporter, through which each failure is the plugin's on the camera's channel, and a camera without the block hands none: + * `callDelegate` logs it. A listener added with `once` is heard once, since its wrapper takes it off before it runs. The library's own work never waits on + * a plugin's listener, and a listener's failure stops nothing. + * @param emitter - The controller. + * @param event - The event's name. + * @param reporter - The camera's reporter, or none for a camera without the block. + * @param args - The event's arguments. + */ +export function dispatchEvent(emitter: EventEmitter, event: string, reporter: CameraReporter | undefined, ...args: readonly unknown[]): void { + for (const listener of emitter.rawListeners(event)) { + const call = (): unknown => Reflect.apply(listener, emitter, args) + const failure = `A listener of the camera controller's ${event} event failed` + + if (reporter) { + reporter.guard('plugin-failure', call, failure) + } else { + callDelegate(call, failure) + } + } +} diff --git a/src/test-utils/ReferenceSRTP.ts b/src/test-utils/ReferenceSRTP.ts new file mode 100644 index 000000000..b49962eef --- /dev/null +++ b/src/test-utils/ReferenceSRTP.ts @@ -0,0 +1,193 @@ +// The SRTP reference every spec that checks SRTP packets shares, in a module of its own. No spec carries its own copy. +import { Buffer } from 'node:buffer' +import crypto from 'node:crypto' + +// The rollover counter's 32-bit range, the modulus of RFC 3711 3.3.1's ROC arithmetic. +const ROC_RANGE = 0x100000000 + +/* The reference: a slow SRTP peer written from RFC 3711 sections 3.1, 3.3, 3.4, 4.1.1, 4.2 and 4.3.1 alone, importing nothing from the library. Each value + * is derived with a fresh AES-128-CTR cipher, each packet is decrypted or encrypted with a fresh AES-128-CTR cipher on its own IV, and each tag is a fresh + * HMAC-SHA1: it shares no code path with the SRTP context's keystream, its work buffers or its index arithmetic. One instance keeps one RTP index + * estimate, and a row protects RTP with it or unprotects RTP with it, never both. + */ +export class ReferenceSRTP { + private readonly rtpKey: Buffer + private readonly rtpAuthKey: Buffer + private readonly rtpSalt: Buffer + private readonly rtcpKey: Buffer + private readonly rtcpAuthKey: Buffer + private readonly rtcpSalt: Buffer + private highest?: number + private roc = 0 + private rtcpIndex = 0 + + constructor({ masterKey, masterSalt }: { masterKey: Buffer, masterSalt: Buffer }) { + this.rtpKey = ReferenceSRTP.derive(masterKey, masterSalt, 0x00, 16) + this.rtpAuthKey = ReferenceSRTP.derive(masterKey, masterSalt, 0x01, 20) + this.rtpSalt = ReferenceSRTP.derive(masterKey, masterSalt, 0x02, 14) + this.rtcpKey = ReferenceSRTP.derive(masterKey, masterSalt, 0x03, 16) + this.rtcpAuthKey = ReferenceSRTP.derive(masterKey, masterSalt, 0x04, 20) + this.rtcpSalt = ReferenceSRTP.derive(masterKey, masterSalt, 0x05, 14) + } + + // 4.3.1 at a key derivation rate of zero: key_id is the label then six zero octets, XORed into the salt's last seven octets, the result times 2^16 the + // counter-mode IV under the master key. + private static derive(masterKey: Buffer, masterSalt: Buffer, label: number, length: number): Buffer { + const keyId = Buffer.concat([ + Buffer.alloc(7), + Buffer.from([label]), + Buffer.alloc(6), + ]) + const x = Buffer.from(masterSalt.map((octet, index) => octet ^ keyId[index])) + + return ReferenceSRTP.ctr(masterKey, Buffer.concat([ + x, + Buffer.alloc(2), + ]), Buffer.alloc(length)) + } + + // 4.1.1: IV = (k_s * 2^16) XOR (SSRC * 2^64) XOR (i * 2^16), each term a 128-bit big-endian integer, computed here as bigints over whole blocks. + private static iv(salt: Buffer, ssrc: number, index: bigint): Buffer { + const value = (BigInt(`0x${salt.toString('hex')}`) << 16n) ^ (BigInt(ssrc) << 64n) ^ (index << 16n) + + return Buffer.from(value.toString(16).padStart(32, '0'), 'hex') + } + + private static ctr(key: Buffer, iv: Buffer, data: Buffer): Buffer { + const cipher = crypto.createCipheriv('aes-128-ctr', key, iv) + + return Buffer.concat([ + cipher.update(data), + cipher.final(), + ]) + } + + private static tag(authKey: Buffer, data: Buffer): Buffer { + return crypto.createHmac('sha1', authKey).update(data).digest().subarray(0, 10) + } + + // RFC 3550 5.1: the header is twelve octets, four per CSRC, and the extension the X bit announces, all of which RFC 3711 3.1 leaves clear. + private static headerLength(packet: Buffer): number { + let headerLength = 12 + 4 * (packet[0] & 0x0F) + + if (packet[0] & 0x10) { + headerLength += 4 + 4 * packet.readUInt16BE(headerLength + 2) + } + + return headerLength + } + + protect(packet: Buffer): Buffer { + const headerLength = ReferenceSRTP.headerLength(packet) + const sequence = packet.readUInt16BE(2) + const v = this.estimate(sequence) + const index = BigInt(v) * 65536n + BigInt(sequence) + + const payload = ReferenceSRTP.ctr(this.rtpKey, ReferenceSRTP.iv(this.rtpSalt, packet.readUInt32BE(8), index), packet.subarray(headerLength)) + const authenticated = Buffer.concat([ + packet.subarray(0, headerLength), + payload, + ]) + const roc = Buffer.alloc(4) + roc.writeUInt32BE(v) + + this.advance(sequence, v) + + return Buffer.concat([ + authenticated, + ReferenceSRTP.tag(this.rtpAuthKey, Buffer.concat([authenticated, roc])), + ]) + } + + // 3.3: the tag over the packet and the estimated ROC is checked, then the payload past the header is decrypted under the packet's index; only a packet + // whose tag verifies advances the estimate. + unprotect(packet: Buffer): Buffer | undefined { + const authenticated = packet.subarray(0, packet.length - 10) + const sequence = packet.readUInt16BE(2) + const v = this.estimate(sequence) + + const roc = Buffer.alloc(4) + roc.writeUInt32BE(v) + + if (!ReferenceSRTP.tag(this.rtpAuthKey, Buffer.concat([authenticated, roc])).equals(packet.subarray(packet.length - 10))) { + return undefined + } + + this.advance(sequence, v) + + const headerLength = ReferenceSRTP.headerLength(packet) + const index = BigInt(v) * 65536n + BigInt(sequence) + + return Buffer.concat([ + authenticated.subarray(0, headerLength), + ReferenceSRTP.ctr(this.rtpKey, ReferenceSRTP.iv(this.rtpSalt, packet.readUInt32BE(8), index), authenticated.subarray(headerLength)), + ]) + } + + // 3.4: the first eight octets stay clear, the rest is encrypted under the SRTCP index unless the E flag is clear, and E || index follows before the tag. + protectRTCP(packet: Buffer, encrypt = true): Buffer { + const body = encrypt + ? ReferenceSRTP.ctr(this.rtcpKey, ReferenceSRTP.iv(this.rtcpSalt, packet.readUInt32BE(4), BigInt(this.rtcpIndex)), packet.subarray(8)) + : packet.subarray(8) + const trailer = Buffer.alloc(4) + trailer.writeUInt32BE(((encrypt + ? 0x80000000 + : 0) | this.rtcpIndex) >>> 0) + this.rtcpIndex++ + + const authenticated = Buffer.concat([ + packet.subarray(0, 8), + body, + trailer, + ]) + + return Buffer.concat([ + authenticated, + ReferenceSRTP.tag(this.rtcpAuthKey, authenticated), + ]) + } + + // 3.4: the tag over the packet and its E flag and index is checked, then everything after the first eight octets is decrypted when E is set. + unprotectRTCP(packet: Buffer): Buffer | undefined { + const authenticated = packet.subarray(0, packet.length - 10) + + if (!ReferenceSRTP.tag(this.rtcpAuthKey, authenticated).equals(packet.subarray(packet.length - 10))) { + return undefined + } + + const trailer = authenticated.readUInt32BE(authenticated.length - 4) + const body = authenticated.subarray(8, authenticated.length - 4) + + return Buffer.concat([ + packet.subarray(0, 8), + trailer >= 0x80000000 + ? ReferenceSRTP.ctr(this.rtcpKey, ReferenceSRTP.iv(this.rtcpSalt, packet.readUInt32BE(4), BigInt(trailer - 0x80000000)), body) + : body, + ]) + } + + // 3.3.1: the index estimate from the highest sequence number seen and the ROC, each ROC step taken modulo the counter's range. The ROC before zero is its top. + private estimate(sequence: number): number { + if (this.highest === undefined) { + return this.roc + } + + if (this.highest < 32768) { + return sequence - this.highest > 32768 + ? (this.roc + ROC_RANGE - 1) % ROC_RANGE + : this.roc + } + + return this.highest - 32768 > sequence + ? (this.roc + 1) % ROC_RANGE + : this.roc + } + + // 3.3.1: a packet at the next ROC, or at this ROC past the highest sequence number, becomes the highest. + private advance(sequence: number, v: number): void { + if (this.highest === undefined || v === (this.roc + 1) % ROC_RANGE || (v === this.roc && sequence > this.highest)) { + this.highest = sequence + this.roc = v + } + } +} diff --git a/src/test-utils/cameraFixtures.ts b/src/test-utils/cameraFixtures.ts new file mode 100644 index 000000000..665c771c6 --- /dev/null +++ b/src/test-utils/cameraFixtures.ts @@ -0,0 +1,772 @@ +// The camera fixtures every camera spec shares, in a module of their own. No spec imports another and each spec's rows run once. +import type { Mock } from 'vitest' + +import type { SerializedAccessory } from '../lib/Accessory.js' +import type { + CameraRecordingOptions, + CameraStreamingOptions, + CameraVideoSensor, + CameraVideoTier, + MultiTierStreamingDelegate, + MultiTierStreamingOptions, + RecordingPacket, + SnapshotRequest, + TierStream, + WebRTCStreamingOptions, +} from '../lib/camera/index.js' +import type { SensorStreamTiers } from '../lib/camera/StreamingOptions.js' +import type { + CameraBufferRecordingOptions, + CameraCapabilitiesOptions, + CameraController, + CameraControllerCapabilitiesOptions, + CameraControllerLegacyOptions, + CameraControllerServiceMap, + CameraRecordingDelegate, + CameraStreamingDelegate, + SnapshotRequestCallback, +} from '../lib/controller/index.js' +import type { AccessoryInformation } from '../lib/definitions/index.js' +import type { HAPConnection } from '../lib/util/eventedhttp.js' +import type { SampleFixture } from './mp4Fixtures.js' +import type { Deferred } from './settle.js' + +import { Buffer } from 'node:buffer' +import crypto from 'node:crypto' + +import { onTestFinished, vi } from 'vitest' + +import { Accessory, Categories, MDNSAdvertiser } from '../lib/Accessory.js' +import { encodeSetupEndpointsRequest } from '../lib/camera/capabilities/setupEndpoints.js' +import { + AudioBitrate, + AudioRecordingCodecType, + AudioRecordingSamplerate, + AudioStreamingCodecType, + AudioStreamingSamplerate, + CameraSensorIntent, + CameraVideoQuality, + H264Level, + H264Profile, + MediaContainerType, + SRTPCryptoSuites, + VideoCodecType, +} from '../lib/camera/index.js' +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 { deferred } from './settle.js' + +export { buildEmitterConnection } from './connectionFixtures.js' +export { openingStamp } from './openingStamp.js' + +/** + * A multi-tier streaming delegate whose methods are mocks. A row reads each demand the library raised, writes the stream it handed out and reads the + * demand's end. A start the row does not script registers a fresh disposable bound to the stream it was handed, at its first line, whose disposal the + * delegate keeps by that stream, hears its signal, whose abort the delegate keeps by that stream too, and answers nothing. Each start's signal is the + * second argument its call recorded. A demand's end is read from the disposal alone, which the library makes once at every end, a withdrawal's among them. + */ +export interface ScriptedTierDelegate { + readonly aborts: Map void>> + readonly disposals: Map Promise>> + readonly talkbackStarted: Mock['talkbackStarted']> + readonly tierDemandStarted: Mock +} + +/** + * A camera that records from its camera buffer as a row builds it: its options, its scripted streaming delegate, and the stream that delegate's latest + * demand handed out, the recorded tier's while the recorder alone holds a tier. + */ +export interface BufferCamera { + readonly delegate: ScriptedTierDelegate + readonly options: CameraControllerCapabilitiesOptions & { cameraCapabilities: { streaming: { delegate: ScriptedTierDelegate } } } + readonly stream: () => TierStream +} + +// The ticks of a frame on a tier stream's 90 kHz picture track at 30 frames a second, and of a 20 ms sound on its 48 kHz sound track. +export const FRAME_TICKS = 3000 +export const SOUND_TICKS = 960 + +const FRAMES_PER_SECOND = 30 + +// 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. +const KEPT_STREAM_STEP = 500 + +// A sound's octets: by default a table-of-contents octet whose second frame's length runs past the packet, which means the voice reader reads no duration. For +// a readable sound the table-of-contents octet states a single frame of the speech layer's 20 ms. +export const UNREAD_SOUND = Buffer.alloc(40, 0x5A) +const READ_SOUND = Buffer.concat([ + Buffer.from([0x08]), + Buffer.alloc(39, 0x5A), +]) + +/** + * How {@link frames} writes a tier stream's frames. + */ +export interface FrameOptions { + // A keyframe every this many frames, counted from frame 0. + gop?: number + // Each picture's octets, and each keyframe's when it differs. + octets?: number + keyframeOctets?: number + // Whether each fragment carries the sound timed inside the frame before its own: the sound of a keyframe's frame arrives after the keyframe. + lag?: boolean + // Whether the stream carries sound. + sound?: boolean + // Whether each sound opens with a table-of-contents octet the voice reader reads as its 20 ms, where by default it reads none. + readable?: boolean + // Whether each keyframe carries the parameter sets in band. + inBand?: boolean + // The duration the last sample of each run states in place of its step, from that step and its index, as a muxer that cuts a fragment at every frame + // states 0 or half a step before the next fragment's decode time moves on by a whole one. A run's other samples state the steps their decode times are + // read from. + stated?: (step: number, index: number) => number + // 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 +} + +export const MOCK_IMAGE = crypto.randomBytes(64) + +export const mockStreamingOptions: CameraStreamingOptions = { + supportedCryptoSuites: [SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80], + video: { + codec: { + profiles: [H264Profile.BASELINE, H264Profile.MAIN, H264Profile.HIGH], + levels: [H264Level.LEVEL3_1, H264Level.LEVEL3_2, H264Level.LEVEL4_0], + }, + resolutions: [ + [1920, 1080, 30], // width, height, framerate + [1280, 960, 30], + [1280, 720, 30], + [1024, 768, 30], + [640, 480, 30], + [640, 360, 30], + [480, 360, 30], + [480, 270, 30], + [320, 240, 30], + [320, 240, 15], + [320, 180, 30], + ], + }, + audio: { + twoWayAudio: true, + codecs: [ + { + type: AudioStreamingCodecType.AAC_ELD, + samplerate: AudioStreamingSamplerate.KHZ_24, + }, + ], + }, +} + +export const mockRecordingOptions: CameraRecordingOptions = { + prebufferLength: 4000, + mediaContainerConfiguration: [ + { + type: MediaContainerType.FRAGMENTED_MP4, + fragmentLength: 8000, + }, + ], + + video: { + type: VideoCodecType.H264, + parameters: mockStreamingOptions.video.codec, + resolutions: mockStreamingOptions.video.resolutions, + }, + audio: { + codecs: [ + { + type: AudioRecordingCodecType.AAC_ELD, + audioChannels: 1, + bitrateMode: AudioBitrate.VARIABLE, + samplerate: AudioRecordingSamplerate.KHZ_48, + }, + ], + }, +} + +export class MockDelegate implements CameraStreamingDelegate, CameraRecordingDelegate { + handleSnapshotRequest(_request: SnapshotRequest, callback: SnapshotRequestCallback): void { + callback(undefined, MOCK_IMAGE) + } + + handleStreamRequest(): void { + throw new Error('Unsupported!') + } + + prepareStream(): void { + throw new Error('Unsupported!') + } + + async* handleRecordingStreamRequest(): AsyncGenerator { + yield { + data: Buffer.alloc(64, 0), + isLast: true, + } + } + + closeRecordingStream(): void { + // do nothing + } + + updateRecordingActive(): void { + // do nothing + } + + updateRecordingConfiguration(): void { + // do nothing + } +} + +export function createCameraControllerOptions( + recordingOptions: CameraRecordingOptions = mockRecordingOptions, + streamingOptions: CameraStreamingOptions = mockStreamingOptions, + cameraStreamCount = 2, + delegate: CameraStreamingDelegate & CameraRecordingDelegate = new MockDelegate(), +): CameraControllerLegacyOptions { + return { + cameraStreamCount, + delegate, + streamingOptions, + recording: { + options: recordingOptions, + delegate, + }, + sensors: { + motion: true, + occupancy: true, + }, + } +} + +// A block's snapshot function that answers every snapshot with the mock picture at once, a mock, which lets a row read each call it was made. +export function snapshotFunction(): Mock { + return vi.fn().mockResolvedValue(MOCK_IMAGE) +} + +/* The whole options of a camera with the camera capabilities block given, its snapshot function a fresh snapshotFunction() where the block gives none, + * and the controller's own motion and occupancy sensors, the motion sensor such a camera needs. Every camera with the block a spec builds takes its form + * from here. + */ +export function capabilitiesCameraOptions( + block: Omit & Partial>, +): CameraControllerCapabilitiesOptions { + return { + cameraCapabilities: { + snapshot: snapshotFunction(), + ...block, + }, + sensors: { + motion: true, + occupancy: true, + }, + } +} + +// A camera's service map without its undefined entries, taken from a given map or from the services a camera constructs: a row restores over it as over +// the map an accessory saved, which holds only the services. +export function definedEntries(map: CameraControllerServiceMap): CameraControllerServiceMap { + return Object.fromEntries(Object.entries(map).filter(([, service]) => service !== undefined)) +} + +export function savedMapOf(camera: CameraController): CameraControllerServiceMap { + return definedEntries(camera.constructServices()) +} + +// The Setup Endpoints golden vectors, computed by an independent TLV8 writer over the R15 tables and read by the codec's spec and the legacy stream +// management's. The hub request has the shape and length of a hub's write, and the hub answer the shape and length of an accessory's answer to it. +export const SETUP_ENDPOINTS_HUB_REQUEST = 'ARChssPUAABAAIAAAAAAAACxAxcBAQACCjE5Mi4wLjIuMTkDAlrDBAJcwwQlAQEAAhABAgMEBQYHCAkKCwwNDg8QAw4REhMUFRYXGBkaGxwdHgUlAQEAAhAhIiMkJ' + + 'SYnKCkqKywtLi8wAw4xMjM0NTY3ODk6Ozw9Pg==' +export const SETUP_ENDPOINTS_HUB_ANSWER = 'ARChssPUAABAAIAAAAAAAACxAgEAAxgBAQACCzE5Mi4wLjIuMTMwAwJCxwQCRMcEJQEBAAIQoaKjpKWmp6ipqqusra6vsAMOsbKztLW2t7i5uru8vb4FJQEBAAIQwc' + + 'LDxMXGx8jJysvMzc7P0AMO0dLT1NXW19jZ2tvc3d4GBA0MCwoHBBEQDw4=' +// RFC 3711 appendix B.3's master key and salt, from which the RFC derives its session values and under which ffmpeg protected the SRTP vectors. +export const SRTP_MASTER_KEY = Buffer.from('e1f97a0d3e018be0d64fa32c06de4139', 'hex') +export const SRTP_MASTER_SALT = Buffer.from('0ec675ad498afeebb6960b3aabe6', 'hex') + +// This is the fixture request without its port fields. +export const SETUP_ENDPOINTS_WITHOUT_PORTS = 'ARARERERERERERERERERERERAw4BAQACCTEyNy4wLjAuMQQlAQEAAhAAAAAAAAAAAAAAAAAAAAAAAw4AAAAAAAAAAAAAAAAAAAUlAQEAAhAAAAAAAAAAAAAAAAA' + + 'AAAAAAw4AAAAAAAAAAAAAAAAAAA==' +// This is an IPv6 request whose ports, 80 and 81, are each written at one byte. +export const SETUP_ENDPOINTS_NARROW_PORTS = 'ARAzMzMzMzMzMzMzMzMzMzMzAxIBAQECB2ZlODA6OjEDAVAEAVEEJQEBAAIQAAAAAAAAAAAAAAAAAAAAAAMOAAAAAAAAAAAAAAAAAAAFJQEBAAIQAAAAAAAAAAAA' + + 'AAAAAAAAAAMOAAAAAAAAAAAAAAAAAAA=' +// This is a request under the Disabled suite, its video parameters carrying no key or salt field and its audio parameters zero-length ones. +export const SETUP_ENDPOINTS_DISABLED_SUITE = 'ARBEREREREREREREREREREREAxUBAQACCDEwLjAuMC4yAwJwFwQCchcEAwEBAgUHAQECAgADAA==' + +// A Setup Endpoints request for the session given, or, without ports, the fixed request above, which names the default session. +export function buildSetupEndpointsTlv(withPorts = true, sessionIdentifier = '11111111-1111-1111-1111-111111111111'): string { + if (!withPorts) { + return SETUP_ENDPOINTS_WITHOUT_PORTS + } + + const srtp = { + cryptoSuite: SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80, + masterKey: Buffer.alloc(16), + masterSalt: Buffer.alloc(14), + } + + return encodeSetupEndpointsRequest({ + sessionIdentifier, + controllerAddress: { + addressVersion: 'ipv4', + address: '127.0.0.1', + videoRTPPort: 5000, + audioRTPPort: 5001, + }, + videoSRTPParameters: srtp, + audioSRTPParameters: srtp, + }) +} + +// Multi-tier streaming through a delegate that does nothing, for a camera whose rows raise no demand of their own. +export function idleStreaming(): MultiTierStreamingOptions { + return { + delegate: { + tierDemandStarted: () => undefined, + }, + } +} + +// A disposable bound to a stream, whose disposal the delegate keeps by that stream: what a scripted start registers, and what a row's own script registers. +export function disposableFor(delegate: Pick, stream: TierStream): AsyncDisposable { + const dispose = vi.fn<() => Promise>(async () => undefined) + + delegate.disposals.set(stream, dispose) + + return { [Symbol.asyncDispose]: dispose } +} + +// Hears a start's signal in the start's call, and a row reads the moment a withdrawal aborted it. +function hear(delegate: ScriptedTierDelegate, stream: TierStream, signal: AbortSignal): void { + const aborted = vi.fn<() => void>() + + delegate.aborts.set(stream, aborted) + signal.addEventListener('abort', aborted, { once: true }) +} + +export function scriptedTierDelegate(): ScriptedTierDelegate { + const delegate: ScriptedTierDelegate = { + aborts: new Map(), + disposals: new Map(), + talkbackStarted: vi.fn['talkbackStarted']>(() => undefined), + tierDemandStarted: vi.fn(async (stream, signal) => { + stream.use(disposableFor(delegate, stream)) + hear(delegate, stream, signal) + }), + } + + return delegate +} + +// The streams the delegate's starts were handed, in the order of the starts, those of one video tier where a row names it. +export function streamsOf(delegate: Pick, tierId?: number): TierStream[] { + return delegate.tierDemandStarted.mock.calls.map(([stream]) => stream).filter(stream => (tierId === undefined) || (stream.tier.id === tierId)) +} + +// The signal a stream's start was handed. +export function signalOf(delegate: Pick, stream: TierStream): AbortSignal { + return delegate.tierDemandStarted.mock.calls.find(([started]) => started === stream)![1] +} + +// How many times the library released the disposable a stream's start registered. +export function disposedOf(delegate: Pick, stream: TierStream): number { + return delegate.disposals.get(stream)?.mock.calls.length ?? 0 +} + +// Scripts the delegate's next start to register a disposable bound to its stream at its first line, and then to wait until the row resolves or rejects the +// deferred it answers, answering nothing. +export function pendingStart(delegate: ScriptedTierDelegate, pending: Deferred = deferred()): Deferred { + delegate.tierDemandStarted.mockImplementationOnce(async (stream, signal) => { + stream.use(disposableFor(delegate, stream)) + hear(delegate, stream, signal) + await pending.promise + }) + + return pending +} + +// The streams whose demands the library ended, in the order it ended them: each release of the disposable a stream's start registered. +export function endedOf(delegate: Pick): TierStream[] { + const moments = [...delegate.disposals].flatMap(([stream, end]) => end.mock.invocationCallOrder.map(order => [order, stream] as const)) + + return moments.sort(([first], [second]) => first - second).map(([, stream]) => stream) +} + +/* How many times the library ended the demands of a video tier, or of every tier where a row names none: each release of the disposable a stream's start + * registered, one at each end. A withdrawal's abort, which comes before its release, is not counted beside it. + */ +export function endsOf(delegate: Pick, tierId?: number): number { + return streamsOf(delegate, tierId).reduce((ends, stream) => ends + disposedOf(delegate, stream), 0) +} + +// The conformant video tiers, each within its class's maximum, which every fixture sensor offers. +const FIXTURE_TIERS: readonly CameraVideoTier[] = [ + { + bitrate: 1700, + frameRate: 30, + height: 1080, + id: 1, + quality: CameraVideoQuality.HIGH, + width: 1920, + }, + { + bitrate: 768, + frameRate: 30, + height: 720, + id: 2, + quality: CameraVideoQuality.MEDIUM, + width: 1280, + }, + { + bitrate: 180, + frameRate: 15, + height: 360, + id: 3, + quality: CameraVideoQuality.LOW, + width: 640, + }, +] + +// A video sensor entry at the given UUID with the fixture's tiers and audio and the first sensor's dimensions and intent, each changed as the row gives. +export function videoSensor(uuid: string, change: Partial = {}): CameraVideoSensor { + return { + audio: { bitrate: 24 }, + dimensions: { width: 1920, height: 1080 }, + intent: CameraSensorIntent.MAIN, + tiers: FIXTURE_TIERS.map(tier => ({ ...tier })), + uuid, + ...change, + } +} + +// A video sensor's tier set as the options boundary builds it from the sensor's entry. No row states a wire value. +export function tierSetOf(sensor: CameraVideoSensor): SensorStreamTiers { + return validateVideoSensors([sensor], idleStreaming(), false).tierSets[0] +} + +// The WebRTC settings of a camera that wires the block and opens no session, each at its default. +export function webRTCStreamingOptions(): WebRTCStreamingOptions { + return {} +} + +// The first video sensor of the two-sensor camera, whose dimensions differ from the second's. A row tells one sensor's bounds from the other's. +export const FIRST_VIDEO_SENSOR: CameraVideoSensor = videoSensor('D1000001-0000-4000-8000-000000000001') + +// The second video sensor of the two-sensor camera, set apart from the first by its smaller dimensions and its package intent, and Generic by its place. +export const SECOND_VIDEO_SENSOR: CameraVideoSensor = videoSensor('D2000002-0000-4000-8000-000000000002', { + dimensions: { width: 1280, height: 720 }, + intent: CameraSensorIntent.PACKAGE, +}) + +// The motionZones functions of the two-sensor camera's sensors, each given to its own sensor. +export interface TwoSensorZones { + readonly first?: CameraVideoSensor['motionZones'] + readonly second?: CameraVideoSensor['motionZones'] +} + +// A camera with the camera capabilities block over the first and the second video sensor, in that order, which records the primary sensor's best tier +// from its camera buffer and which the motion sensor's and the zones' wiring rows drive as a camera with more than one video sensor, each sensor taking +// the motionZones function given for it. +export function twoSensorCameraOptions(zones: TwoSensorZones = {}): CameraControllerCapabilitiesOptions { + return capabilitiesCameraOptions({ + videoSensors: [ + { ...FIRST_VIDEO_SENSOR, motionZones: zones.first }, + { ...SECOND_VIDEO_SENSOR, motionZones: zones.second }, + ], + streaming: idleStreaming(), + }) +} + +// The two-sensor camera with its block's recording option the one given, by default the primary sensor's best tier with the default prebuffer, and its +// streaming delegate a script. +export function bufferCamera(recording?: CameraBufferRecordingOptions): BufferCamera { + const options = twoSensorCameraOptions() + const block = options.cameraCapabilities! + const delegate = scriptedTierDelegate() + + return { + delegate, + options: { + ...options, + cameraCapabilities: { + ...block, + recording, + streaming: { ...block.streaming, delegate }, + }, + }, + stream: () => delegate.tierDemandStarted.mock.calls.at(-1)![0], + } +} + +// 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. +export function frames(stream: TierStream, from: number, to: number, options: FrameOptions = {}): void { + const { + gop = FRAMES_PER_SECOND, + inBand = false, + keyframeOctets, + lag = false, + octets = 100, + readable = false, + retimeSound, + sound = true, + stated, + } = options + const restated = (sample: SampleFixture, step: number, index: number): SampleFixture => stated === undefined + ? sample + : { + ...sample, + duration: stated(step, index), + } + + for (let index = from; index < to; index++) { + const keyframe = index % gop === 0 + const timed = lag + ? index - 1 + : index + // The sounds whose 20 ms start falls inside a frame of a thirtieth of a second, five for every three frames. + const first = Math.ceil(timed * 5 / 3) + const last = Math.ceil((timed + 1) * 5 / 3) + const pictureTime = index * FRAME_TICKS + const soundTime = Math.max(first, 0) * SOUND_TICKS + + stream.write(tierStreamFragment({ + picture: [ + restated(tierPicture({ + inBand, + keyframe, + octets: keyframe + ? keyframeOctets ?? octets + : octets, + }), FRAME_TICKS, index), + ], + pictureTime: BigInt(pictureTime), + sound: sound && (timed >= 0) + ? Array.from({ length: last - first }, (_, offset) => { + const sample = soundSample(readable + ? READ_SOUND + : UNREAD_SOUND) + + return first + offset === last - 1 + ? restated(sample, SOUND_TICKS, first + offset) + : sample + }) + : [], + soundTime: BigInt(retimeSound?.(index, soundTime) ?? soundTime), + })) + } +} + +// The fake clock's asynchronous advance, which runs each due timer's reactions before the next timer is due, for a row that keeps a stream through it. +export async function advanceAsync(step: number): Promise { + await vi.advanceTimersByTimeAsync(step) +} + +/** + * How {@link keepStreaming} keeps tier streams handing over pictures. + */ +export interface KeptStreamOptions { + // Moves the row's clock by one step: the fake clock's own synchronous advance by default, or an asynchronous one, whose promise the helper waits on + // before each next picture and answers a promise of its own for. + readonly advance?: (step: number) => unknown + // The decode time of the first picture, in microseconds from each stream's initialization segment, 0 by default, each later picture a step on: a row + // that keeps a stream again, or writes its own frame after, times it at or past the time the run before reached. + readonly from?: number +} + +/** + * Keeps tier streams handing over pictures while a row moves its clock, for a row whose subject is another timer, which means no silence bound of a + * stream's demand runs out: before each step of the kept stream, or the rest of the time where less is left, each stream is written one picture that is no + * keyframe, its decode time the step's distance from the one before. A viewer waiting for a keyframe is sent none of them, and each demand counts every + * one. Each picture keeps step with its arrival where the row fakes the steady clock, and runs ahead of it where the steady clock is real, the pacer then + * holding a later frame of the stream back by up to its ceiling. A stream the suites have written nothing to is written its initialization segment + * first, through writeTierFrame. + * @param streams - The streams, a view from away's every tier among them. + * @param time - How long the row's clock moves, in milliseconds. + * @param options - How the clock moves and where the pictures' decode times start. + * @returns A promise settled after the last step where the advance is asynchronous, and nothing where it is synchronous. + */ +export function keepStreaming(streams: readonly TierStream[], time: number, options: KeptStreamOptions & { readonly advance: (step: number) => Promise }): +Promise +export function keepStreaming(streams: readonly TierStream[], time: number, options?: KeptStreamOptions): void +export function keepStreaming(streams: readonly TierStream[], time: number, options: KeptStreamOptions = {}): Promise | void { + const { advance = (step: number): unknown => vi.advanceTimersByTime(step), from = 0 } = options + const { data } = tierPicture() + const run = (elapsed: number): Promise | void => { + let moved = elapsed + + while (moved < time) { + for (const stream of streams) { + writeTierFrame(stream, 'video', { data, time: from + moved * 1000 }) + } + + const step = Math.min(KEPT_STREAM_STEP, time - moved) + const reached = moved + step + const advanced = advance(step) + + if (advanced instanceof Promise) { + return advanced.then(() => run(reached)) + } + + moved = reached + } + } + + return run(0) +} + +// A sensor's motionZones function that applies every call at once, a mock, which lets a row read each call it was made. +export function motionZonesFunction(): Mock> { + return vi.fn>().mockResolvedValue(undefined) +} + +export function buildMockConnection(): HAPConnection { + return { + localAddress: '127.0.0.1', + getLocalAddress: vi.fn().mockReturnValue('127.0.0.1'), + setMaxListeners: vi.fn(), + getMaxListeners: vi.fn().mockReturnValue(10), + isAuthenticated: vi.fn().mockReturnValue(true), + on: vi.fn(), + removeListener: vi.fn(), + } as unknown as HAPConnection +} + +// The identity every numbered accessory of the camera specs takes where a row hands none. A row numbers over an identifier cache of its own, and no row +// reads another's numbers. +export const NUMBERED_ACCESSORY_UUID = uuid.generate('numbered camera accessory') +export const NUMBERED_USERNAME = 'AA:BB:CC:DD:EE:FF' + +/** + * Hands a camera the context of a published accessory: the numbered accessory's UUID, the username the row names or none, and a fresh Accessory Information service named + * `Camera`, as the numbered accessory is, which means a problem the camera prints opens with that name. A published context with no username is + * one no accessory hands: a row that reads neither the clip path's identity nor the restore-complete mark leaves each as its configure left it, and the + * camera's accessory reads published from here on. + * @param camera - The camera, configured. + * @param username - The username the context carries, none where the row names none. + * @param accessoryUUID - The accessory's UUID, the numbered accessory's where the row names none, which a row gives each of its cameras its own of where it + * reads each camera's problems apart. + */ +export function handPublishedContext(camera: CameraController, username?: string, accessoryUUID = NUMBERED_ACCESSORY_UUID): void { + camera.handleAccessoryContext({ + accessoryInformation: new Service.AccessoryInformation('Camera') as AccessoryInformation, + accessoryUUID, + published: true, + username, + }) +} + +// An accessory carrying the given camera, configured and then numbered over the given cache, as a publish numbers it. +export function numberedAccessory( + camera: CameraController, + cache = new IdentifierCache(NUMBERED_USERNAME), + accessory = new Accessory('Camera', NUMBERED_ACCESSORY_UUID), +): Accessory { + accessory.configureController(camera) + accessory._assignIDs(cache) + + return accessory +} + +// A saved accessory restored as a cached accessory restores at startup, carrying the given camera and numbered over the given cache. +export function restoredAccessory(saved: Accessory, camera: CameraController, cache = new IdentifierCache(NUMBERED_USERNAME)): Accessory { + return numberedAccessory(camera, cache, Accessory.deserialize(Accessory.serialize(saved))) +} + +// Every number an accessory holds: a service's under its identifier, and a characteristic's under its service's identifier and its own UUID. +export function numbersOf(accessory: Accessory): Record { + const numbers: Record = {} + + for (const service of accessory.services) { + const id = service.getServiceId() + numbers[id] = service.iid! + + for (const characteristic of service.characteristics) { + numbers[`${id}|${characteristic.UUID}`] = characteristic.iid! + } + } + + return numbers +} + +// The accessory's debounce of the configuration pass a configure enqueues, one second, and a margin past it, which lets a run read the number the pass leaves. +const CONFIGURATION_PASS_WAIT = 1100 + +/** + * One run of a camera's accessory in the restart harness: the accessory as the run left it, unpublished, and its configuration number at its publish and + * after the configure's debounced configuration pass. + */ +export interface RestartRun { + readonly accessory: Accessory + readonly atPublish: number + readonly afterPass: number +} + +/** + * A camera's accessory over restarts under one username of its own, each run as Homebridge runs one: the last run's accessory taken through + * `Accessory.serialize` and `Accessory.deserialize`, or a fresh accessory at the first run, the camera configured before or after the publish, the + * publish through the suite's mocked advertiser, what the row does on the running camera, the configure's debounced configuration pass run, then the + * accessory unpublished, its controller storage saved and the accessory serialized, since Homebridge's shutdown unpublishes each accessory before it saves + * the accessory cache. A run never destroys the accessory, since a destroy deletes the accessory record, the identifier cache and the controller data the + * next run restores. The row's end removes each run's camera and deletes the username's data. + */ +export interface RestartHarness { + readonly username: string + run: (camera: CameraController, configure: 'after' | 'before', act?: (accessory: Accessory) => void) => Promise +} + +export function restartHarness(): RestartHarness { + const username = Array.from(crypto.randomBytes(6), octet => octet.toString(16).padStart(2, '0').toUpperCase()).join(':') + const cameras: CameraController[] = [] + let saved: SerializedAccessory | undefined + + onTestFinished(() => { + for (const camera of cameras) { + camera.handleControllerRemoved() + } + + Accessory.cleanupAccessoryData(username) + }) + + return { + username, + run: async (camera, configure, act) => { + const accessory = saved + ? Accessory.deserialize(saved) + : new Accessory('Camera', NUMBERED_ACCESSORY_UUID) + + cameras.push(camera) + + if (configure === 'before') { + accessory.configureController(camera) + } + + await accessory.publish({ + advertiser: MDNSAdvertiser.BONJOUR, + category: Categories.CAMERA, + pincode: '031-45-154', + username, + }) + + const atPublish = accessory._accessoryInfo!.getConfigVersion() + + if (configure === 'after') { + accessory.configureController(camera) + } + + act?.(accessory) + await new Promise(resolve => setTimeout(resolve, CONFIGURATION_PASS_WAIT)) + + const afterPass = accessory._accessoryInfo!.getConfigVersion() + + await accessory.unpublish() + accessory.controllerStorage.save() + saved = Accessory.serialize(accessory) + + return { accessory, afterPass, atPublish } + }, + } +} diff --git a/src/test-utils/certificateAuthority.ts b/src/test-utils/certificateAuthority.ts new file mode 100644 index 000000000..19e24b565 --- /dev/null +++ b/src/test-utils/certificateAuthority.ts @@ -0,0 +1,140 @@ +/* A test certificate authority: a P-256 key with a self-signed certificate made at run time, which issues a leaf certificate for a signing request's public + * key between the dates a row names. The management makes its own key for each signing request, and no committed fixture can certify it. Each certificate + * is built with the library's DER writer and signed through node:crypto; the few primitives the writer does not carry, a time, a boolean and an octet + * string, are written here. + */ +import type { KeyObject } from 'node:crypto' + +import { Buffer } from 'node:buffer' +import { createPublicKey, generateKeyPairSync, sign, X509Certificate } from 'node:crypto' + +import * as der from '../lib/util/der.js' + +// ECDSA with SHA-256, a subject's common name, and the basic constraints extension. +const ECDSA_WITH_SHA256 = '1.2.840.10045.4.3.2' +const COMMON_NAME = '2.5.4.3' +const BASIC_CONSTRAINTS = '2.5.29.19' + +// A primitive element whose contents are shorter than 128 bytes, the only kind this helper writes itself. +function primitive(tag: number, contents: Uint8Array): Buffer { + return Buffer.concat([ + Buffer.from([tag, contents.length]), + contents, + ]) +} + +// A time as X.509 writes it: UTCTime through 2049, GeneralizedTime from 2050. +function time(date: Date): Buffer { + const text = date.toISOString().replace(/[-:T]/g, '').replace(/\.\d{3}Z$/, 'Z') + + return date.getUTCFullYear() < 2050 + ? primitive(0x17, Buffer.from(text.slice(2), 'latin1')) + : primitive(0x18, Buffer.from(text, 'latin1')) +} + +function name(commonName: string): Buffer { + return der.sequence(der.set(der.sequence(der.objectIdentifier(COMMON_NAME), der.utf8String(commonName)))) +} + +// One element of a DER buffer: its contents' offset and its end, for the few reads a signing request needs. +function element(data: Buffer, offset: number): { contents: number, end: number } { + const first = data[offset + 1] + + if (first < 0x80) { + return { contents: offset + 2, end: offset + 2 + first } + } + + const octets = first & 0x7F + const length = data.readUIntBE(offset + 2, octets) + + return { contents: offset + 2 + octets, end: offset + 2 + octets + length } +} + +/** + * The public key a signing request asks to be certified: the third element of its request information. + * @param csr - The request, in DER format. + * @returns The key. + */ +export function signingRequestKey(csr: Buffer): KeyObject { + const info = element(csr, element(csr, 0).contents) + const version = element(csr, info.contents) + const subject = element(csr, version.end) + const key = element(csr, subject.end) + + return createPublicKey({ + format: 'der', + key: csr.subarray(subject.end, key.end), + type: 'spki', + }) +} + +/** + * A certificate authority made for one suite. + */ +export class CertificateAuthority { + /** + * The authority's self-signed certificate, in DER format. + */ + readonly certificate: Buffer + + private readonly privateKey: KeyObject + + // The authority's name, its certificate's subject and each leaf's issuer. + private readonly name: Buffer + + private serial = 1n + + constructor(commonName = 'HAP-NodeJS Test Authority') { + const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' }) + const notBefore = new Date(Date.now() - 24 * 60 * 60 * 1000) + const notAfter = new Date(Date.now() + 10 * 365 * 24 * 60 * 60 * 1000) + + this.privateKey = privateKey + this.name = name(commonName) + this.certificate = this.signed(this.name, notBefore, notAfter, this.name, publicKey, [ + der.sequence(der.objectIdentifier(BASIC_CONSTRAINTS), primitive(0x01, Buffer.from([0xFF])), primitive(0x04, der.sequence(primitive(0x01, Buffer.from([0xFF]))))), + ]) + } + + /** + * The authority's certificate in PEM format, as TLS takes a CA. + */ + get pem(): string { + return new X509Certificate(this.certificate).toString() + } + + /** + * Issues a leaf certificate for a key between the dates given. + * @param subjectKey - The key the certificate certifies, or the signing request asking for it. + * @param notBefore - The start of the certificate's validity. + * @param notAfter - The end of the certificate's validity. + * @param commonName - The subject's common name. + * @returns The certificate, in DER format. + */ + issue(subjectKey: KeyObject | Buffer, notBefore: Date, notAfter: Date, commonName = 'Camera'): Buffer { + const key = Buffer.isBuffer(subjectKey) + ? signingRequestKey(subjectKey) + : subjectKey + + return this.signed(this.name, notBefore, notAfter, name(commonName), key, []) + } + + private signed(issuer: Buffer, notBefore: Date, notAfter: Date, subject: Buffer, key: KeyObject, extensions: Buffer[]): Buffer { + const tbs = der.sequence( + der.context(0, der.integer(2n)), + der.integer(this.serial++), + der.sequence(der.objectIdentifier(ECDSA_WITH_SHA256)), + issuer, + der.sequence(time(notBefore), time(notAfter)), + subject, + key.export({ format: 'der', type: 'spki' }), + ...(extensions.length === 0 + ? [] + : [ + der.context(3, der.sequence(...extensions)), + ]), + ) + + return der.sequence(tbs, der.sequence(der.objectIdentifier(ECDSA_WITH_SHA256)), der.bitString(sign('sha256', tbs, { dsaEncoding: 'der', key: this.privateKey }))) + } +} From cbbfeff946d623f2b39946ce396751a474b02151 Mon Sep 17 00:00:00 2001 From: HJD Date: Sat, 28 Nov 2026 15:26:39 -0600 Subject: [PATCH 16/16] feat(examples): add a runnable camera example in the modern form, with the guides to the iOS 27 camera features --- README.md | 6 + eslint.config.mjs | 32 + guides/HKSV3Protocol.md | 1036 +++++++++++++++++++++++ guides/UpgradingCameraPlugins.md | 316 +++++++ package.json | 3 +- src/accessories/ModernCamera_example.ts | 184 ++++ 6 files changed, 1576 insertions(+), 1 deletion(-) create mode 100644 guides/HKSV3Protocol.md create mode 100644 guides/UpgradingCameraPlugins.md create mode 100644 src/accessories/ModernCamera_example.ts diff --git a/README.md b/README.md index a40b0c402..2bf2d04e9 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,12 @@ There is also a pretty detailed guide on [how to start developing with HAP-NodeJ Or you may just have a look at our [examples][examples-repo] repository (or some of the old [accessory examples][example-accessories]). +The example camera in `src/accessories/ModernCamera_example.ts` streams and records ffmpeg's test pattern with the camera features Apple introduced with iOS 27. +It needs ffmpeg with `libx265` and `libopus`: run `npm run build`, then `node dist/accessories/ModernCamera_example.js`, and add it with the setup code it prints. + +Two guides cover those camera features. [Upgrading a Camera Plugin to HAP-NodeJS 2.4](guides/UpgradingCameraPlugins.md) is for plugin authors: what changed in the library and how a camera takes the new features. +[HomeKit Cameras in iOS 27](guides/HKSV3Protocol.md) describes the features themselves and how a home hub behaves around them. + The API documentation can be found [here](https://developers.homebridge.io/hap-nodejs/). See the FAQ on how to enable [debug output][faq-debug] for HAP-NodeJS. diff --git a/eslint.config.mjs b/eslint.config.mjs index 06938df91..fdfc23a9a 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -95,6 +95,16 @@ export default antfu( 'perfectionist/sort-named-imports': 'off', }, }) + .append({ + // A code sample in a guide shows a few lines of a plugin: the names around them are the reader's own, and its lines are laid out to be read. + files: ['guides/**/*.md/**'], + rules: { + 'antfu/reasonable-newline': 'off', + 'no-undef': 'off', + 'node/prefer-global/buffer': 'off', + 'unused-imports/no-unused-vars': 'off', + }, + }) .append({ files: ['src/**/*.spec.ts'], rules: { @@ -206,3 +216,25 @@ export default antfu( 'ts/no-redeclare': 'off', }, }) + .append({ + files: ['package.json'], + rules: { + // npm reads `files` in order and a negated entry keeps a file out only when it comes after the entry it narrows, which is why negated entries come last. + 'jsonc/sort-array-values': [ + 'error', + { + order: [ + { + order: { type: 'asc' }, + valuePattern: '^[^!]', + }, + { + order: { type: 'asc' }, + valuePattern: '^!', + }, + ], + pathPattern: '^files$', + }, + ], + }, + }) diff --git a/guides/HKSV3Protocol.md b/guides/HKSV3Protocol.md new file mode 100644 index 000000000..a7e636a21 --- /dev/null +++ b/guides/HKSV3Protocol.md @@ -0,0 +1,1036 @@ +# HomeKit Cameras in iOS 27: HKSV3 Recording and the New Live Views + +By [HJD](https://github.com/hjdhjd) + +## Part 1: The Story + +### What This Document Is, And Who It's For + +With iOS 27, Apple changed how HomeKit cameras stream and record. Apple also did something unusual and welcome: it published the _HomeKit Secure Video Open Source Compatibility Guide_, which describes the new camera services and the layout of every field in them. + +What the guide doesn't tell you is how the pieces behave once a real home hub is on the other end. Which request comes first? What does a hub do when it sees motion? What makes it keep a recording, and what makes it quietly walk away? Those answers decide whether a camera works or doesn't, and this document is my attempt to write them down. + +There are two parts: + +- **Part 1** is the story. If you want to understand what's going on between your camera, your home hub and iCloud, and you'd rather not read a field table to get there, this part is for you. +- **Part 2** is the specification. It's written for people building a camera, a plugin or a library: every exchange, field, size and status code, each with a short note on how I know it. + +Everything here is implemented in [HAP-NodeJS](https://github.com/homebridge/HAP-NodeJS), the library behind [Homebridge](https://homebridge.io). This is not an Apple document, and nothing in it speaks for Apple. + +### What Changed With iOS 27 + +Three things changed, and each one moves work from the home hub to the camera. + +- **Live video now comes in tiers.** A camera describes the streams it can offer, from a small one to a large one, in HEVC with Opus audio. Whoever is watching asks for the tier that suits its screen and its connection, instead of the camera guessing. +- **Watching from away now uses WebRTC.** When you open a camera from outside your home, the camera makes its own connection out to a relay Apple runs, and your phone picks up the video there. The camera sends every tier at once and the viewer chooses among them...which is why a view from away can change quality without stopping. +- **The camera uploads its own recordings.** This is the big one. The home hub still watches the video and decides what's worth keeping, but it no longer carries the recording to iCloud. The camera does that itself, encrypted, with credentials the hub hands it. + +Apple's guide doesn't give these features a name. Apple's own name for them is **HKSV3**, and it shows on the wire: the keys that protect a recording are addressed with the prefix `hksv3:`. + +There's more in the guide than those three things. A camera can describe more than one lens, for instance. In my testing the Home app shows such a camera as one camera with one live view, taken from whichever lens the camera listed first when it was paired. I'll leave the rest of that for Part 2. + +### The Big Picture + +Here's who talks to whom. + +```mermaid +flowchart LR + subgraph Home["Your home network"] + Camera["Camera"] + Hub["Home hub
(Apple TV or HomePod)"] + Near["iPhone, iPad or Mac
at home"] + end + Relay["Apple's relay"] + Far["iPhone, iPad or Mac
away from home"] + Cloud["iCloud
(your recordings)"] + + Hub -- "settings, credentials,
recording commands" --> Camera + Camera -- "video for analysis" --> Hub + Camera -- "live view (SRTP)" --> Near + Camera -- "live view (WebRTC),
every frame sealed" --> Relay + Relay --> Far + Camera -- "encrypted clips (HTTPS)" --> Cloud +``` + +The home hub is still the brain. It holds the long-lived connection to the camera, it writes the camera's settings, and it decides what gets recorded. What's new is how much the camera now does for itself: it sends live video straight to a viewer at home, it reaches out to Apple's relay for a viewer who's away, and it delivers its own recordings to iCloud. + +### How A Recording Gets From A Camera To iCloud + +It starts long before anything moves in front of the camera. + +**First, the hub gives the camera what it needs to upload.** Within seconds of you turning on recording, a home hub asks the camera to create a key pair and a certificate request. The hub answers with three things: a certificate that proves who the camera is, good for 60 days; a 32-byte secret called the Camera Key; and a web address in iCloud called the publishing point, which is where this camera's recordings go. When the certificate is close to running out, the camera raises its hand and the hub hands it a fresh set of all three. + +**Then, something moves.** The camera reports motion, and a hub connects within about 150 milliseconds and asks for video. The camera sends it in short pieces called fragments...four seconds each in my testing...beginning a few seconds _before_ the motion. That way the hub sees what led up to it. Think of it as a DVR that's always holding the last few seconds, just in case. + +**The hub watches, and gives a verdict on every fragment.** For each one it tells the camera either "should record" or "should not record". This is the hub doing what Apple's home hubs have always done for HomeKit Secure Video: deciding, by what you've asked it to record, whether there's a person, an animal, a vehicle or a package worth your attention. If every fragment comes back "should not record", that's the end of it, and nothing is kept. + +**When the hub sees something worth keeping, it tells the camera to start uploading.** The command names a moment in time, usually the start of the fragment just before the interesting one. From there the camera sends the recording to its publishing point as an ordinary HTTP Live Streaming clip: a playlist, then the video and audio in pieces, then a closing playlist. Every piece of video and audio is encrypted before it leaves, under a key derived from the Camera Key. iCloud stores it without being able to read it. + +**When the hub loses interest, it tells the camera to stop and finish the clip.** The camera sends the closing playlist, and a moment later the clip is in your Home app's timeline. If the action just keeps going, the hub cuts the recording into clips of five minutes each and carries on. + +Two things about this surprised me, and both are worth knowing. + +- **A recording only exists if the camera uploads it.** The hub watching the video is not enough. In every test where the upload failed, no clip ever appeared in the Home app, no matter what the hub had decided. +- **Once a clip is uploaded, it doesn't need the camera anymore.** A recorded clip plays while the camera is switched off. It keeps playing after the hub has replaced the camera's key, too, because each clip says which key it was sealed under. + +### How A Live View Works + +A live view takes one of two paths, depending on where you are. + +**At home, your device talks straight to the camera.** It reads what the camera offers, tells the camera where to send the video and which keys to protect it with, and asks for a tier. The video and audio then flow directly between the two over encrypted RTP, with nothing in between. If the camera has a speaker, the Home app shows a talk button, and your voice travels back to the camera the same way. + +**Away from home, a hub sets things up and then gets out of the way.** The hub asks the camera for an offer. The camera answers with a description of everything it will send, one video stream for each tier plus audio, along with a key. The other end of that connection turns out to be a relay Apple runs, not the hub and not your phone. Once the connection is up, the camera sends all of its tiers at once, and every frame is sealed with that key before it's sent. Your phone picks a tier and can change its mind at any moment. Talking back works here as well: your voice arrives at the camera sealed the same way. + +In both cases the viewer will occasionally ask the camera for a keyframe, which is a complete picture it can start decoding from. It asks when a view begins, and again whenever it loses part of the picture. How quickly a camera answers that request is most of what makes a live view feel instant or sluggish, and Part 2 spends real time on it. + +### How I Figured This Out + +Apple's guide is the foundation for everything here, and I'm grateful for it. Where the guide states something, I take it as given and say so. + +Everything else comes from testing against real home hubs running iOS 27, in my own home. I built a test camera whose every behavior could be changed one piece at a time, and then changed one piece at a time...a lot of times. When a hub accepted something, I wrote down what it accepted. When it refused something, I wrote down exactly how, because a refusal often teaches more than a success does. One malformed offer for a view from away was turned down 185 times out of 185, which settles the question rather nicely. + +I leaned on three kinds of evidence: what the hubs wrote to the camera and when, what iCloud answered to each upload, and what the Home app actually showed at the end. That last one matters more than it sounds. A clip that uploads perfectly and then plays as a black picture is not a working clip. + +It also helped to recognize what Apple built on. Very little of this is exotic. The recordings are HTTP Live Streaming over CMAF, the same family of formats that carries most video on the internet. The encryption is AES-GCM with keys derived through HKDF. Views from away are WebRTC, with each frame sealed using SFrame, which is a published standard. Where a piece of the protocol follows a standard, Part 2 names it, because knowing what something is based on is usually the fastest way to get it right. + +A word on how sure I am. **Unless Part 2 says otherwise, every statement in it is something I observed.** Where I'm reading between the lines of what I observed, the statement is marked _inferred_. Where something that matters hasn't been tried, it's marked _untested_, and those are gathered at the end so nobody has to hunt for them. + +I'm sure there's more to learn here, and that someone will find a corner I missed. When you do, I'd love to hear about it. + +## Part 2: The Specification + +### 1. Conventions + +A few words and habits hold for everything below. + +**Who's who.** + +- The **camera** is the accessory. Everything in this document is written from its side of the wire. +- A **hub** is a home hub: an Apple TV or a HomePod. A home can have several, and any of them may be the one talking to the camera at a given moment. +- A **viewer** is the device showing a live view or playing a clip. +- A view is **at home** when the viewing device holds its own connection to the camera, and **from away** when a hub sets the view up for it. Being on your home Wi-Fi is not quite the same thing as being at home: a device with no connection of its own to the camera views through a hub, exactly as it would from a cellular network. +- The **relay** is the server of Apple's that sits at the far end of a view from away. +- The **publishing point** is the iCloud address a camera uploads its recordings to. + +**Words for video.** + +- A **tier** is one encoding of a sensor's picture, at one size, frame rate and bitrate. A camera offers several. +- A **keyframe** is a picture that decodes without any other picture. +- A **recording** is the video a hub pulls from the camera to analyze. It arrives in **fragments**. +- A **clip** is what the camera uploads, and what you later see in the Home app's timeline. It's uploaded in **segments**. A fragment and a segment can hold the very same bytes...the two words just say which path they're on. + +**How sure I am.** Unless a statement is marked, I observed it. _Inferred_ means I'm reading between the lines of something I observed. _Untested_ means nobody tried it, and it matters enough to say so. Three more words appear where a test settled a question: something is **required** when I watched things fail without it, **accepted** when the far end took it, and **not required** when things worked without it. + +When I describe the form of something...an offer, a playlist, a box in a file...that's the form I tested. I haven't tried every variation of every form that works, and I don't list the ones I skipped. The open points in section 12 are the questions whose answers would change what you build. + +Where two tests disagreed, I give you both, with what was different about them. + +**Numbers.** Timings are what I measured in my home, on my network, against my hubs. They're there to give you a feel for the pace of things, and none of them is a promise. Sizes are in bytes. A **64-bit NTP timestamp** is the number of seconds since 1900 in its upper 32 bits and the fraction of a second in its lower 32. + +**Names.** Services, characteristics and fields carry the names Apple's guide gives them. Requests on the data stream carry the names the HomeKit Accessory Protocol specification gives them, and I'll call that specification HAP from here on. I don't repeat the guide's field tables. Where a field's meaning isn't in the guide, appendix A has it. + +**Examples** use made-up addresses, keys and identifiers. The tier sizes and bitrates in them are the guide's own. + +**Notes that begin "In HAP-NodeJS"** describe a choice this library made. They're one way that works, and not a requirement of the protocol. + +### 2. What A Camera Publishes + +#### The Services + +A camera that wants the iOS 27 features publishes the services below. Apple's guide defines the first ten, and HAP defines the rest. + +| Service | What It's For | +| --------------------------------------- | --------------------------------------------------------------------------------------------------------- | +| Camera Capabilities | Announces an iOS 27 camera, and lists each video sensor with its tiers. Its Version reads `17.99`. | +| Camera Global Operating Mode | The switches for the camera as a whole: HomeKit Camera Active, Streaming Enabled and the indicator light. | +| Motion Sensor | Motion Detected, with the new Motion Enabled and Contributing Sensors beside it. | +| Camera Motion Zones | The zones a user draws for motion. | +| Camera Multi-Tier RTP Stream Management | A live view at home. One for each sensor. | +| Camera WebRTC Stream Management | A live view from away. One for each sensor. | +| Camera Recording Management | Two switches: Active and Recording Audio Active. | +| Camera Buffer Management | The hub's verdicts and upload commands, and the publishing point. | +| Camera Key Management | The Camera Key. | +| Camera Client Certificate Management | The certificate request, the certificate and its status. | +| Data Stream Transport Management | The HomeKit Data Stream that recordings and snapshots travel over. | +| Microphone | The camera's sound. | +| Speaker | Optional. Publishing one is what makes the Home app show a talk button. | +| Doorbell | Optional. See section 10. | + +Two things about this list are easy to miss. + +- **No legacy stream is needed.** A camera can leave out HAP's older Camera RTP Stream Management entirely. I ran cameras with none, on a fresh pairing and as a new accessory behind an already paired bridge, and between them they got everything: provisioning, views at home and from away, talkback both ways, snapshots, recordings and notifications. +- **Camera Recording Management is slimmer than HAP's.** It carries Active and Recording Audio Active and nothing else. A hub arms recording by writing Active alone. It never writes a recording configuration, which leaves the choice of recording format to the camera. + +#### Which Stream A Viewer Takes + +A viewer chooses its stream service from the accessory database. It reads the whole database, and then writes Setup Endpoints on the one stream service it has chosen. + +If a camera publishes HAP's legacy stream services beside the new ones, **the instance IDs decide**. A viewer takes the multi-tier stream only when the new stream services carry lower instance IDs than the legacy ones. This is required, and it holds on a fresh pairing and a standing one alike. The same camera, published twice on fresh pairings, was given four legacy views and no multi-tier view with its new services numbered above the legacy streams, and three multi-tier sessions and no legacy view with them numbered below. + +- The order the services are listed in doesn't matter. Only the numbers do. +- The new services don't have to sit below the camera's other, older services. The Motion Sensor and the Microphone can keep their low numbers. +- A camera numbered for the legacy streams is served the legacy stream from away too, by a hub, and is never asked for a WebRTC offer. +- A viewer chooses again after a configuration number change, and a pairing survives the renumbering. + +This has a consequence for anyone upgrading a camera in place. Instance IDs are handed out once and only ever climb. A camera that was paired with legacy streams and later gains the new services holds them at higher numbers...and goes right on being shown through its legacy stream. Renumbering the legacy streams above the new services does move the view. One camera I did that to drew no recording at five motions later that day, though, and I can't say the renumbering wasn't why. I wouldn't renumber a paired camera. + +**In HAP-NodeJS** a camera is one form or the other, never both. A camera stated in the new form publishes no legacy stream service at all, and the question doesn't come up. + +#### Linked Services + +Each sensor's multi-tier stream service and WebRTC stream service must each be linked to the other, as HAP's linked services. This is required for a view from away. With the links in place a hub wrote WebRTC Solicit Offer for a viewer on cellular. Four minutes earlier, without them and with nothing else different, the same hub read the camera's tiers and stopped, and the viewer got no picture. Links to Data Stream Transport Management are not required. + +#### Tiers + +- **Three tiers are not required by the far end.** The guide asks for at least three concurrent encodings of each sensor. Cameras offering one tier, and two, were viewed at home, viewed from away and recorded just the same. +- **A size the guide doesn't list is accepted.** A tier at a size outside the guide's table was shown at home, asked for through a hub, and recorded. +- **HEVC is required.** A viewer at home accepts an H.264 tier, starts its stream, asks for a keyframe about four times a second and never shows a picture. None of the H.264 encodings I tried played, from two different encoders. From away, the viewer showed a spinner. +- **The audio tier is Opus**, one channel, in 20 millisecond packets, reported at 48 kHz. +- **A bitrate a little over the advertised peak plays.** A tier sent about 15 percent over its advertised peak played smoothly at home. A stream sent at about three times its advertised peak lost packets at home, though it played from away. The guide says its maximums should not be exceeded, and I'd take it at its word. +- **Raise the configuration number when the tiers change.** Once it rises, every device fetches the database again within about six seconds. I never tested whether a device notices a change without it. + +#### More Than One Sensor + +The guide lets Camera Capabilities list several sensors, each with a type, an intent, and stream services of its own. Here's what the Home app does with a second one today: nothing. + +- A camera of two sensors is shown as one camera with one live view, and that view is the sensor whose stream services carry the lowest instance IDs. On a fresh pairing that's the sensor listed first. +- A sensor's type and intent decide nothing. A Generic sensor listed first was shown ahead of a Primary one listed second. A second sensor with the Package intent was treated no differently, on a plain camera and on a video doorbell. +- The second sensor's stream services are written to for one thing only: a hub's Streaming Enabled. +- On a paired camera the view follows the instance IDs. Reordering Camera Capabilities, or raising the configuration number, moves nothing. +- The camera is provisioned once, with one certificate, one Camera Key and one publishing point. Nothing in provisioning names a sensor. + +So list your main view first, and give it the lowest numbers. A camera that lists a package view ahead of its main view shows the package view alone. + +A clip may say which sensor it came from, with one line in its multivariant playlist (appendix A). Clips with the line and without it were accepted and looked the same in the Home app. + +#### Behind A Bridge + +A camera behind a bridge is provisioned, viewed, commanded and recorded as a camera published by itself is. The one visible difference is in provisioning: the certificate request such a camera answers with names its bridge as the subject, and a hub issues the certificate all the same. + +#### Things That Turned Out Not To Matter + +- A control point doesn't need a Status in its value before anything has been written to it. Cameras whose RTP Streaming Control and WebRTC control points read empty were viewed normally. +- Manually Disabled on Camera Global Operating Mode is optional. Where a camera has it, a hub subscribes to it. +- A camera doesn't need a new Firmware Revision for a hub to take up its new services. Hubs provisioned, commanded and recorded cameras whose revision never changed. + +### 3. The Settings A Hub Writes + +A hub writes a camera's settings far more often than you'd guess, and almost always with the values the camera already holds. + +#### When A Camera Is First Paired + +On the fresh pairing I read this on, a hub wrote one round of settings within two seconds of pairing, three times over: + +- Camera Operating Mode Indicator, on. +- Streaming Enabled, true, on Camera Global Operating Mode, on the multi-tier stream service and on the WebRTC stream service. +- HomeKit Camera Active, on. +- Camera Recording Management's Active, off. + +Most fresh pairings also open with Camera Client Certificate and Camera Recording Publishing Point each written with an empty value, one to four seconds after pairing, and sometimes again about ten seconds in. An empty value means "you have none". + +#### When Recording Is Allowed + +When the user picks a recording option in the Home app, a hub writes Camera Recording Management's Active on. Provisioning, in section 6, comes with it. + +#### The Round A Hub Repeats + +A hub repeats a routine on the connection it holds open. It renews its subscriptions, and writes HomeKit Camera Active and every Streaming Enabled on. + +- On a camera whose recording is off, the round comes about every half minute, and it also writes Camera Recording Management's Active off and clears the certificate and the publishing point. +- On a camera whose recording is on, the round comes every 35 to 50 seconds and clears nothing. + +The values don't change, which leaves the camera with no notification to send. The practical lesson: a write of the value you already hold should cost nothing and restart nothing. + +#### After A Restart + +At its first connection after a camera restarts, a hub writes the camera's settings again within about a second, each at the value it already reads: HomeKit Camera Active, Streaming Enabled, Motion Enabled and Camera Recording Management's Active. These are the values the camera reports, handed back to it. + +#### When A Camera Is Turned Off + +Turning a camera off in the Home app makes a hub write HomeKit Camera Active off and every Streaming Enabled off, and clear the certificate and the publishing point. The Home app then asks the camera for no stream at all. + +The guide adds a rule of its own here: a stream service's Status Active must read false whenever streaming is switched off on that service or on the camera, HomeKit Camera Active is off, or the camera is manually disabled, and a camera must reject a request to start a stream while it does. + +### 4. A Live View At Home + +At home the viewer and the camera talk to each other directly, over the Camera Multi-Tier RTP Stream Management service. + +#### The Exchange + +```mermaid +sequenceDiagram + participant V as Viewer + participant C as Camera + V->>C: Read the accessory database + V->>C: Write Setup Endpoints + C-->>V: Where to send, and the SRTP keys + V->>C: Write RTP Streaming Control, Start + C->>V: Video and audio (SRTP) + V->>C: RTCP, keyframe requests, talkback + V->>C: Write RTP Streaming Control, End +``` + +- The viewer writes Setup Endpoints within 50 to 70 milliseconds of reading the database. +- Start names a video tier and the audio tier by their identifiers, with an SSRC for each. +- The media is SRTP under `AES_CM_128_HMAC_SHA1_80`, which the guide requires. +- The guide requires at least five sessions at once, and says outright that several viewers can share one encoding. There's no one-to-one tie between an encoder and a session. +- A full camera view takes the top tier with the audio tier. Right after pairing I also saw three short sessions, of a few seconds each, on the smallest tier. _Inferred_: the Home app's own setup opens them. +- The viewer sends RTCP to both of the ports the camera answered with. + +#### The Packets + +What a viewer at home plays: + +- **HEVC** as RFC 7798 lays it out. A keyframe's video, sequence and picture parameter sets travel together in one aggregation packet. A NAL unit too large for a packet is sent as fragmentation units. A unit that fits is sent as a single NAL unit packet. The marker bit is set on the last packet of each frame. +- **Opus**, one 20 millisecond frame to a packet, timestamps 960 apart on a 48 kHz clock. +- The payload types are the ones the camera advertises. + +A viewer at home does not smooth out uneven delivery. Frames handed over three at a time, every 100 milliseconds or so, all arrived and all played, and the picture moved visibly less smoothly than the same frames sent one at a time. Send each frame when it's due. + +#### How A View Starts + +A viewer can show nothing until it has a keyframe, and it says so: it asks for one 50 to 80 milliseconds after its Start, and again every second until one arrives. On a stream whose keyframes come five seconds apart, that was four to six requests and a spinner for a couple of seconds. + +There are two ways to do better. + +- **Make a keyframe when asked.** With a keyframe produced on request, views on a five-second stream started within a second or two and played smoothly. +- **Keep the recent video, and start the viewer from the latest keyframe you hold.** A view handed a keyframe as its very first picture usually asks for nothing at all, though now and then one asks in its first tenth of a second anyway. + +The second way has a catch, and it cost me a few days: **the timestamps have to be right.** + +- Pictures sent with the timestamps they were first given, which by then are a few seconds old, play jumpily...and the view stays jumpy for its whole length, long after the camera has caught up to live. _Inferred_: the viewer ends up playing behind what it receives. +- The same pictures stamped with the live clock as each one is sent play properly. +- A keyframe must carry a timestamp above every timestamp that viewer has already been sent. A keyframe stamped with the same timestamp as the last live picture was not taken, and the viewer went on asking. Stamped one millisecond later, 90 ticks of the video clock, it was taken every time. + +How fast you hand the buffered stretch over is yours to choose. At twice the stream's speed the viewer sees a fast-forward. At fifty times it sees nothing but a view that starts at once. + +**In HAP-NodeJS** every running tier keeps its video back to the latest keyframe. A view opens from that keyframe, stamped past everything already sent, at up to fifty times the stream's speed, and a plugin is never asked to make a keyframe. + +#### When A Packet Is Lost + +A viewer at home that loses a video packet freezes on its last good picture until it can decode a keyframe. + +- It usually asks for one within a tenth of a second of the loss. I measured 15 to 341 milliseconds across most views. Twice, on a stream far heavier than it advertised, a request came a full four seconds later. +- It keeps asking, anywhere from a few times a second to once a second, until a keyframe arrives. +- If nothing answers, the freeze lasts until the stream's next keyframe. + +A keyframe made on request ends the freeze as soon as the encoder delivers it. A keyframe from a buffer ends it immediately, at the price of the viewer seeing the stretch since that keyframe again, briefly. + +#### Talkback At Home + +A camera that publishes a Speaker gets a talk button in the Home app. A camera with a Microphone and no Speaker doesn't. + +- The viewer's voice arrives as RTP on the session's own audio port, the one the camera answered with in Setup Endpoints. No second session opens for it. +- It's SRTP under the **viewer's** keys, the audio key and salt the viewer supplied in Setup Endpoints, and not under the camera's own. +- It's the camera's own advertised audio tier coming back: Opus, one channel, 20 millisecond frames on a 48 kHz clock, on the camera's audio payload type, from the one SSRC the viewer named for its audio. A camera needs no second audio format for talkback. +- **Mask the marker bit before you test the payload type.** The marker is set on the packet that opens each stretch of talk, not only the first packet of the session. A camera that compares the whole second byte of the RTP header drops exactly the packets that begin a sentence. +- A viewer that isn't holding the talk button sends nothing. + +### 5. A Live View From Away + +From away, a hub arranges the view and then steps aside. The camera's connection goes to a relay of Apple's, over WebRTC, through the Camera WebRTC Stream Management service. + +Apple's guide defines the characteristics and their fields. It never mentions DTLS, an ICE role, RTCP, a single SDP attribute, the SFrame cipher suite or talkback. Everything in this section beyond the field layouts comes from testing. + +One piece of background first, and it's the one thing in this section that comes from my own analysis rather than from a test. _Inferred_: a view from away appears to reuse the machinery behind Apple's group calls. That would explain three things that otherwise look odd: the relay in the middle, the 16-bit stream IDs, and a viewer's voice arriving on two streams that no SDP announces. You don't need to know this to build a camera. It did help me stop being surprised. + +#### The Exchange + +```mermaid +sequenceDiagram + participant H as Hub + participant C as Camera + participant R as Apple's relay + H->>C: Write WebRTC Solicit Offer (empty) + C-->>H: SDP offer, SFrame key and key ID + H->>C: Write WebRTC Provide Answer (the relay's SDP) + C->>R: ICE, then DTLS + C->>R: Every tier and the sound, each frame sealed + H->>C: Write WebRTC Update Session (a viewer's key) + R->>C: Keyframe requests, the viewer's voice + H->>C: Write WebRTC Reoffer (a viewer's audio section) + H->>C: Write WebRTC Update Session (keys removed) + H->>C: Write WebRTC Streaming Control, End +``` + +- A hub writes Solicit Offer only for a view through a hub. The value it writes is empty: no Options field, and so no request for SFrame. Every solicit I've seen was like this. +- The far end of the connection is neither the hub nor the viewer's device. It's a relay of Apple's that speaks ICE-lite and offers one public address in Apple's 17.0.0.0/8 block, on a UDP port and on TCP port 80. The relay, its port and its DTLS fingerprint change from view to view. +- The answer usually comes back within a quarter of a second of the solicit. Once it took most of a second. +- The hub ends the session with Streaming Control. A session that's being watched lasts as long as the view does. I've watched for more than seven minutes. + +#### The Offer + +The camera is the offerer. Here's the form that plays, and for each part, what the far end did when I got it wrong. + +| Part | The Form That Plays | What Else I Tried | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Sections | One bundle: a video section for each tier, largest first, then one audio section. | One video section stating every tier as a layer is answered and plays, but the viewer is given one stream and can never change tier. | +| Session lines | `a=group:BUNDLE` naming every section, `a=setup:actpass`, `a=rtcp-mux`. | | +| Each video section | `m=video 9 UDP/TLS/RTP/SAVPF `, send-only, `a=rtpmap: H265/90000`, the feedback lines `nack`, `nack pli` and `ccm fir`, and no format parameters. | H.265 format parameters were echoed back in the answer and changed nothing. | +| Its SSRC | Exactly one `a=ssrc` line, naming an SSRC that belongs to that section alone. | A video section that names no SSRC was ended unanswered, 185 times out of 185. | +| Its tier | `a=rid: send max-width=;max-height=;max-fps=;max-br=`, with `a=simulcast:send `. | A rid line with no restrictions is answered, and the hub then ends the session within eight seconds. A single-stream video section, with no rid line and no header extensions, is ended unanswered within a second. _Inferred_: it's the missing rid line. | +| Header extensions | Every section lists `sdes:mid` and `sdes:rtp-stream-id`. | | +| The audio section | `m=audio 9 UDP/TLS/RTP/SAVPF `, send-only, one `a=ssrc` line, `a=rtpmap: opus/48000`, and `a=fmtp: minptime=20;useinbandfec=0`. | `opus/48000/2` with no format parameters was answered and then ended inside about a second, 59 times out of 59. AAC in place of Opus was ended unanswered, 142 times out of 142. AAC listed after Opus was answered with Opus alone. | +| Candidates | Host candidates, written in the SDP. The Additional Candidates list is empty. | | + +A few things the table can't hold: + +- **The payload types and the tiers are the ones the camera advertises** in WebRTC Supported Video Stream Tiers and WebRTC Supported Audio Stream Tiers. My camera used 99 and 110. Those aren't fixed numbers. +- **The rid restrictions follow RFC 8851**, and `max-br` matters more than it looks. It's the bitrate a viewer budgets against when it picks a tier. +- **A camera can offer fewer tiers.** Offers of one video section and of two were answered, section for section, and played. +- **Every candidate goes in the offer.** The protocol has no way to send one later. Finish gathering before you answer the solicit. I never needed a STUN or TURN server: the camera reaches out to a public address. +- **Make the SSRCs of one offer differ in their low sixteen bits.** _Inferred_: a viewer knows each stream by a 16-bit stream ID, which is the low sixteen bits of its SSRC. I've never let two collide. +- **Answer quickly.** Gather your candidates before a solicit arrives, and the offer can go back in a millisecond or two. + +#### The Key That Goes Back With The Offer + +The response to Solicit Offer carries an SFrame Configuration: a key of 32 random bytes and a 64-bit key ID, both fresh for every session. Everything the camera sends is sealed under that key. + +- **Return a key with every offer, whatever the solicit says.** No solicit has ever asked for SFrame, and no video sent without it was ever shown, in any form I tried. The response is the viewer's only way to learn the camera's key. +- A hub keeps a session whose response carries no key. The viewer just never shows a picture. +- My key IDs carry `0x8000` in their low sixteen bits, as the hub's own do. Nothing I found requires it. + +#### The Answer, And Connecting + +The answer arrives as a Provide Answer write. It keeps every section in one bundle, adds a lip-sync group and `a=rtcp-rsize`, returns each video section receive-only with `a=rid: recv` and `a=simulcast:recv `, keeps the `sdes:rtp-stream-id` extension, drops `sdes:mid`, and carries two candidates for the relay, one UDP and one TCP. + +- **The camera is the ICE controlling agent and the DTLS server.** The relay sets `a=setup:active`. +- **Be listening for DTLS before ICE finishes.** The relay's ClientHello arrives within a millisecond of ICE connecting. A camera that isn't ready yet loses it and waits a full second for the retry. Hold on to that first record and hand it to your DTLS server the moment you have one. +- The transport is DTLS 1.2 with `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`, and the SRTP profile is `AEAD_AES_128_GCM`. +- **A viewing remembers its first offer.** The far end forms its answer from the first offer a viewing makes, and gives that same answer to every later session of the viewing...even when a later offer is different. A viewing that opened on a bad offer stays broken for good offers too. A gap of 95 seconds without a solicit began a new viewing, and a gap of 24 seconds did not. If you're experimenting with offers, wait a couple of minutes between tries, or you'll be testing your first one again. + +#### The Keys A Hub Writes + +After the answer, a hub writes WebRTC Update Session with the keys the camera needs to open what a viewer sends: 32-byte keys under 64-bit key IDs, each with `0x8000` in its low sixteen bits. + +- Each viewer has a key ID of its own. A viewer's packets name their key by that ID. +- The first key usually arrives 0.2 to 0.5 seconds after the answer. It has also arrived 10, 17 and 40 seconds into a session. +- A viewer's first packets can reach the camera before the key they name has been written. That's not a fault. Drop them, or hold them within a small bound, and open what follows. +- The camera's own key is never among the keys a hub writes. +- A hub removes a session's keys shortly before it ends the session, typically a fifth of a second before. Once the gap was two seconds, and once it was forty. **A session is over when the hub ends it, and never when its keys are removed.** +- Hold every key by its ID, wipe it when the hub removes it and when the session ends, and keep its bytes out of your logs. + +#### Sending The Picture + +- **Send every tier you offered, all the time.** Each tier goes out on the SSRC its section names. The viewer chooses among them, and the camera is never told which one is on screen. +- **One frame is one SFrame ciphertext.** The plaintext is the frame's NAL units, each preceded by its length as four bytes, big-endian, with the parameter sets ahead of a keyframe's picture. Video uses the cipher suite with the ten-byte tag. Video sealed with the four-byte tag showed nothing. +- **The ciphertext is cut across RTP packets**, and each piece gets one byte in front of it: `0x80` on the first packet of a frame, `0x00` in the middle, `0x40` on the last, and `0xC0` when one packet holds the whole thing. The marker bit goes on the last packet. Every packet of a frame carries the frame's timestamp, on the codec's 90 kHz clock. +- **No packet carries a stream ID.** The offer lists the `sdes:rtp-stream-id` extension, and the camera must not actually put it on a packet. With it there, a viewer refused every video packet and the session died at about a minute. Without it, nothing was refused. +- **Every tier shares one RTP clock.** One moment in time carries one timestamp on every tier. When I stamped each tier from its own source's start, a viewer played the first tier it took and threw away every frame of the next one as too old. With the tiers on one clock it moved among them freely. +- **Never reuse a counter.** Each stream counts its ciphertexts from zero and keeps counting for the life of the session's key, through a source that restarts, a keyframe request and a Reoffer. A counter used twice under one key breaks the encryption. +- Each stream sends RTCP sender reports for the clock its packets carry. + +#### Sending The Sound + +The camera's sound is Opus, one channel, 20 milliseconds to a packet, 960 ticks apart on a 48 kHz clock. Each packet's payload is one whole SFrame ciphertext with `0xC0` in front of it, sealed with the four-byte tag. The sound plays beside the picture and goes on playing if the picture freezes. A viewer that isn't taking the video plays no sound either. + +#### How SFrame Is Built + +The construction is RFC 9605's, with three differences. One construction serves every stream in both directions. + +- **Each stream has its own secret**, derived from the session key and the stream's SSRC. It stands where the RFC has its base key. +- **The two cipher suites are outside the RFC's registry.** Both are AES-256 in counter mode with an HMAC-SHA-512 tag, a 32-byte encryption key and a 64-byte authentication key. Suite 6 has a ten-byte tag and is for video. Suite 8 has a four-byte tag and is for audio. The suite's number is part of the key derivation, which means changing suites changes the keys. +- **The byte in front of each RTP payload** is the SFrame RTP header of `draft-ietf-avtcore-rtp-sframe-01`: its first bit marks the first packet of a ciphertext, and its second bit the last. + +Here it is exactly. `BE32`, `BE64` and `BE16` write a number big-endian in that many bits, and `||` joins bytes. Every derivation is HKDF in full, extract and then expand. The two `Secret` labels end in a space, and the stream label doesn't. + +```text +stream secret = HKDF-SHA-512(key: session key, salt: BE32(SSRC), info: "SFrame 1.0 RTP Stream", 64 bytes) +D = HKDF-SHA-512(key: stream secret, salt: empty, info: "SFrame 1.0 Secret key " || BE64(key ID) || BE16(suite), 96 bytes) +Kenc, Kmac = D[0..32], D[32..96] +S = HKDF-SHA-512(key: stream secret, salt: empty, info: "SFrame 1.0 Secret salt " || BE64(key ID) || BE16(suite), 12 bytes) +N = S XOR (00 00 00 00 || BE64(counter)) +C = AES-256-CTR(Kenc, counter block: N || 00 00 00 00, plaintext) +tag = HMAC-SHA-512(Kmac, BE64(len(H)) || BE64(len(C)) || BE64(tag length) || N || H || C), cut to the tag length +ciphertext = H || C || tag +``` + +`H` is the SFrame header, exactly as RFC 9605 defines it. The far end writes an eight-byte key ID, and carries its counter inside the first byte for as long as it fits. No SFrame metadata is sent. The tag covers the lengths, the nonce, the header and the encrypted frame, in the order of RFC 9605 section 4.5.1. It doesn't cover the RTP header or the byte in front of the payload. + +The **session key** is the camera's own key for what it sends, and a viewer's key from Update Session for what that viewer sends. The **SSRC** is the one the stream was set up with: the SSRC the offer names for a section the camera sends, and the SSRC a viewer's voice arrives on. + +An implementation of this passes RFC 9605's own test vectors for the RFC's suites, opened everything the far end sent, and sealed everything a viewer played. + +#### How A Viewer Picks A Tier + +The viewer chooses, by its own estimate of its connection. The camera sends everything and is told almost nothing. + +- **A viewer budgets by the bitrate you state**, not by what arrives. It takes a tier when that tier's `max-br` plus the sound's 35,200 bits a second fits its budget. +- The budget moves in fixed steps. A tier stating 1,700,000 was passed over at a budget of 1,681,000 and taken at the next step, 1,949,000. A tier stating 768,000 was passed over at 802,000 and taken at 930,000. +- **A view climbs.** It starts on the smallest tier and reaches the largest about six seconds in. It steps down when its connection sags, and back up when it recovers. +- **Low Data Mode caps the budget at 1,078,000.** Beyond its smallest tier, such a viewer takes nothing that states more than about a megabit, however good its connection really is. +- Viewers on cellular took a tier stating 1,700,000 and, on another camera, never asked for a larger one. A viewer on the home network, viewing through a hub, did ask for that larger tier. +- _Inferred_: where the Home app plays a view smaller than full size, it holds that view to the smaller tiers, and the full camera view may take any. An iPhone's tile isn't such a view. Watched from away, it asked the camera for nothing until it was tapped. + +So state each tier's bitrate honestly. Understating one to coax a viewer onto it just hands that viewer a stream its connection can't carry. + +#### Keyframe Requests + +A keyframe request from away is an RTCP Full Intra Request. The stream it wants is named by the SSRC in its one entry. Its media source field reads zero, and the SSRC it's sent from routes nothing. + +- **A request names a tier to refresh. It doesn't tell you what's on screen.** A viewer asks a tier for a keyframe before it switches to it, and that request is the only sign of a move a camera ever gets. Answer a request for any tier you send. +- A viewer asks each tier in turn as a view opens: the smallest within about a second of its key arriving, the middle one a second or two in, and the largest five to six seconds in. +- After a lost packet a viewer asks 0.3 to 1.2 seconds later, slower than at home. It asks again, a few times a second, until that tier's next keyframe. +- Requests come in bursts, and a request can be lost on the way. A viewer that asked once, and whose request never reached the camera, did not ask again for four seconds. +- No request to resend a lost packet has ever reached the camera. A lost packet costs the viewer its whole frame, since a frame is one ciphertext. + +Everything in section 4 about timestamps holds here too. A keyframe answered from a buffer must be stamped past everything already sent. + +#### A Second Viewer, And The Reoffer + +After the first seconds of a view a hub writes WebRTC Reoffer. The controller is the offerer this time, and the camera answers inside the write's response. + +- Every Reoffer I've seen left the camera's sections alone and added or switched an audio section belonging to a viewer: send-only at first, later inactive, and sometimes back again. +- A Reoffer changes neither the camera's key nor how it seals. +- **Two devices watching the same camera share one session.** The second joins the first's session through a Reoffer that adds an audio section of its own, and the hub writes a second key ID for it. There's no second solicit. +- A device that closes the camera and opens it again comes back as a new viewer, under a new key ID. +- In every view I watched, a Reoffer arrived when a picture was showing and none arrived when it wasn't. It's the best sign of success the camera has. + +Answer every Reoffer, whenever it comes, and apply what it negotiates. + +#### Talkback From Away + +A viewer's voice simply starts arriving. No SDP names it. + +- It comes as **two Opus streams**, each on an SSRC of its own, both counting time on one 48 kHz clock. Payload type 119 is the dependable one: wideband, one 20 millisecond frame to a packet, about 24 kbit/s. Payload type 97 is the better one: super-wideband, two 20 millisecond frames to a packet, about 48 kbit/s. They're the same voice, encoded twice. +- Each packet is one SFrame ciphertext with `0xC0` in front, sealed with the four-byte tag under that viewer's key from Update Session. +- **Find the voice by its payload type and by whether it opens**, never by looking for its SSRC in an SDP. Neither SSRC is named anywhere, and a Reoffer can assign payload type 97 to retransmission on some other section. +- **Viewers send voice packets with nobody talking.** An iPhone and an iPad send about a third of a second of both streams as a view opens: 15 or 16 packets on 119 and 8 on 97. A Mac sent them on 119 for half a minute, and in one session on both streams for a full minute. A stream's first packet is not the start of its talk. +- **Read talk from the Opus voice flag**, not from packet sizes. A silent packet on 119 can be as large as a spoken one. The flag drops out for a packet or three in the middle of speech. Don't end a sentence on one unvoiced packet. +- A viewer keeps sending through a pause in talk, and stops sending when talk is switched off. The first packet after a stop carries the marker bit, and its timestamp has moved ahead by the time that wasn't sent. +- For a second or more after talk is switched on, packets say voice and hold no speech. +- The better stream trails the dependable one by about 25 milliseconds. A second device joining a view sent its talk on the dependable stream alone. +- Voice packets arrive in clumps, and a few in a hundred arrive more than a tenth of a second late. A camera that plays them needs a little buffering. + +You may also see RTCP feedback of format 9. It's RFC 7728's PAUSED indication for the viewer's own voice stream, and it asks nothing of the camera. I only saw it on offers that had no audio section. + +**In HAP-NodeJS** a plugin is handed each viewer's voice as one continuous Opus stream. The library starts on whichever stream speaks first, moves to the better one when it carries the talk, and falls back when it stops. A plugin that would rather have the dependable stream alone can say so. + +#### Reading The Signs + +A camera is never told whether a picture is on screen. These are the signs that went with each outcome in my testing. None of them is a viewer's own word for what it shows. + +| What The Camera Sees | What It Meant | +| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| A Reoffer in the first few seconds, and few keyframe requests | A picture is showing. | +| A handful of keyframe requests naming another tier | The viewer wants that tier refreshed, most often because it's about to move to it. | +| A keyframe request every five seconds | Nothing is showing. Nothing arrives, or what arrives can't be opened. | +| Two to four keyframe requests a second | Frames arrive and can't be shown whole. Packets are being lost, or the codec isn't one the viewer plays. | +| No Reoffer and no keyframe request | The viewer isn't taking the video at all. | +| The session's keys removed | The end is coming, usually in a fifth of a second. | + +#### How A Session Ends + +- A hub ends a session that shows no picture after about a minute. +- A stream that stopped for 5, 15 and 25 seconds came back each time, and the picture with it. About 36 seconds after a stream stopped, the hub removed the session's keys, and a stream that came back after that was not shown. +- A view with three packets in a hundred lost stayed open, and choppy. Views whose loss climbed to ten and then thirty in a hundred were ended about half a minute after it first rose. +- While a view stays open, the hub solicits again after a session ends, usually within a second. + +#### When A Camera Refuses + +A camera that can't serve a view answers Solicit Offer with a Status of Error. What the hub does next varied more than anything else I measured. After one refusal a hub wrote no second solicit for 70 seconds. In other views it asked again about once a second. In one it asked 9,885 times in under nine minutes, a median of 35 milliseconds apart. Plan for the fast one: a refusal has to be cheap, and has to release everything it took. The viewer sees a still picture, or the camera crossed out. + +### 6. Recording: Provisioning + +Before a camera can upload anything, a hub hands it three things: a client certificate, the Camera Key and the publishing point. + +#### The Exchange + +```mermaid +sequenceDiagram + participant H as Hub + participant C as Camera + H->>C: Write Camera Client CSR (a 32-byte nonce) + C-->>H: Certificate request, and the nonce's signature + H->>C: Write Camera Client Certificate + H->>C: Write Camera Key + H->>C: Write Camera Recording Publishing Point + H->>C: Write Camera Recording Management, Active on +``` + +The four provisioning writes land inside two seconds, one write each. Active follows six or seven seconds later. + +- **The certificate request** is on an EC P-256 key, signed with ECDSA and SHA-256. A subject of one common name is enough, and what it says isn't checked. +- **The nonce's signature** is the raw `r` and `s` values, 64 bytes, and not a DER-encoded signature. The request and the signature go back in the response to the write. +- **The certificate** arrives with its issuing authority, and is valid for 60 days. +- **The Camera Key** is 32 bytes, with a key number beside it. The guide types the number as 64 bits. Every one I've been handed fits in 48, and they follow no order. Don't treat the number as a counter. +- **The publishing point** is an HTTPS address that ends in a slash, with a list of server authority certificates. + +#### When It Happens + +- A camera paired with recording already allowed is provisioned within seconds of pairing. +- A camera whose user allows recording later is provisioned when they do. One camera paired with recording not allowed was left unprovisioned until recording was allowed. +- One observation may differ. A camera in the new form alone was provisioned about 35 seconds after pairing, and its recording switch was written on seven seconds after that. Seven seconds is the usual gap between provisioning and the switch. That may simply have been the moment recording was allowed...or a hub may provision such a camera before anyone allows anything. I can't tell the two apart from what I recorded. +- Either way, the provisioning arrives ahead of the switch. A camera sees its four writes first, and Active six or seven seconds later. +- A camera that was already recording the older way, and gains the new services on its standing pairing, is provisioned by itself within three seconds of advertising again. Nobody has to touch the Home app. + +#### Renewal + +**Camera Client Certificate Status is how a camera asks for new credentials.** When its Needs Update reads true, a hub provisions the camera again, and it does so whole: a new certificate, a new Camera Key and a new publishing point, in the same four writes. + +- A hub acts on Needs Update when it finds it set as it connects, and when it's notified of it on a connection it already holds. +- An empty value doesn't bring one. A camera that answered an empty certificate, an empty key ID or an empty publishing point, with its status reading clear, was left exactly as it was for the minutes I watched. A camera that has lost any of the three gets them back by raising Needs Update. +- The new publishing point is on the same host as the old one, with a different path. +- Removing the pairing clears the key ID, the certificate and the publishing point. + +**In HAP-NodeJS** a camera raises Needs Update a week before its certificate runs out, and whenever it holds less than the full set. + +#### A New Key, Unasked + +A hub also replaces a camera's Camera Key by itself, outside any renewal. It writes Camera Key alone, with a new key and a new key number, and leaves the certificate and the publishing point as they are. I've seen it twice on one camera: about 25 hours after the camera was provisioned, and again about 37 hours after that. It keeps no fixed schedule. + +Use the newest key for the next clip. **Clips sealed under a replaced key go on playing**, after one replacement and after two, because each clip names the key it was sealed under. + +#### When The Service Says No + +Once, a camera that had kept its credentials through a short spell in the legacy form had its next upload refused with status 401. A hub provisioned it again within three seconds, in the middle of the event, and the following clip was accepted. The start of that event, its first two fragments, reached no clip. I don't know how the hub learned of the refusal, and I don't know whether the refusal came from the spell or from the credentials' age. Both are in section 12. + +### 7. Recording: What A Hub Does At Motion + +```mermaid +sequenceDiagram + participant C as Camera + participant H as Hub + participant P as Publishing point + C->>H: Motion Detected + H->>C: Open a data stream, ask for a recording + C->>H: Initialization segment, then fragments + H->>C: Buffer Activity Command, once for each fragment + H->>C: Buffer Upload Command, Start + C->>P: Playlists, initialization segment, segments + H->>C: Close the recording + H->>C: Buffer Upload Command, Stop + C->>P: Closing playlist +``` + +#### The Request + +A hub connects within about 150 milliseconds of Motion Detected rising. It reads Camera Recording Management's Active, subscribes to Motion Detected, Contributing Sensors, Active and Manually Disabled, writes Setup Data Stream Transport, and opens a HomeKit Data Stream. Over that stream it sends the request HAP already defines for recordings: `dataSend.open` with the type `ipcamera.recording`, the target `controller` and the reason `record`. From motion to that request is usually 50 to 250 milliseconds. + +- **Motion only brings the hub. It doesn't decide anything.** With Motion Detected raised and nothing moving in the picture, a hub pulled five fragments, judged every one not worth recording, and kept nothing. The verdict turned at the very fragment in which a person walked into view. +- A hub asks even when the Motion Sensor's Status Active reads false. +- A camera with no Data Stream Transport Management is connected to at motion, subscribed to, and left alone about five seconds later. + +#### The Recording A Hub Pulls + +The recording is fragmented MP4, sent as HAP's data stream recordings always have been: an initialization segment, then fragments, in chunks, until the hub closes the stream itself with the reason NORMAL. + +- The initialization segment is an `ftyp` box and a `moov` box. +- Each fragment is a `prft` box, a `moof` box and an `mdat` box. +- A fragment opens on a keyframe. Four-second fragments are what HAP asks for, and five-second fragments from a camera whose keyframes come five seconds apart were taken as well. +- The recording starts before the motion does. The first fragment is the camera's prebuffer, and the first two fragments usually leave together. +- H.264 under the `avc1` sample entry and HEVC under `hvc1` are both judged, with AAC-LC or Opus sound. + +**The `prft` box is required**, and it's the single most important thing in this section that isn't written down anywhere. It's the producer reference time box of the ISO base media file format, and it tells the hub what time on the clock a fragment began. With it in front of every fragment, a hub analyzes each fragment and tells the camera what it thinks. Without it, a hub pulls the same recording to the same normal close, says nothing, and nothing is kept. Appendix A has its layout. + +A hub takes the clock time of the **first** fragment from its box, and counts forward from there by each fragment's duration. It doesn't use the times in the later boxes. + +One recording was refused outright. Its samples had been nudged by a tick to keep their decode times apart, which left some composition offsets below zero, and more than one hub closed it at once with the reason UNEXPECTED_FAILURE. The same picture and sound, cut cleanly by duration, was taken. I didn't work out which detail the hubs objected to. Give every sample its true time. + +#### The Verdicts + +For every fragment it analyzes, a hub writes Buffer Activity Command: + +- **Start**, a 64-bit NTP timestamp. The first one equals the first fragment's `prft` time to the millisecond, and each later one adds the previous fragment's duration exactly. +- **Duration**, the fragment's own, in milliseconds. +- **Activity**: 1 for Should Record, 2 for Should Not Record. + +A verdict follows its fragment by 0.26 to 0.92 seconds, most often about 0.3, and always arrives before the next fragment is sent. + +#### The Upload Commands + +At the first fragment it judges Should Record, a hub writes **Buffer Upload Command** with Command 1, Start: a Session ID, and a Start timestamp. + +- The Start timestamp names the beginning of the fragment **before** the one that earned the verdict, which is how the clip comes to include the lead-up. When the very first fragment of a recording is the one judged Should Record, it names that fragment. +- Start and Stop are the same 64-bit NTP timestamps the verdicts carry. The guide doesn't state their unit. +- The camera answers with a Clip ID. Nothing I tried depends on its value. The hub's own Session ID, handed back, works fine. +- The Start arrives 5 to 11 milliseconds after its verdict, typically two to four seconds after the motion. + +When the hub is done it writes Command 3, Stop, for the same Session ID, with a Stop timestamp and the Stop Action Finalize. The Stop timestamp names the end of the last fragment judged Should Record. + +So a clip is always a run of whole fragments of the recording the hub just pulled, and a camera finds them by counting fragment durations from its first fragment's `prft` time. + +- **Keep your fragments until the commands settle.** A hub closes the recording a few milliseconds _before_ it writes its last verdict, and the Stop comes 5 to 38 milliseconds after the close. A verdict, and any Start it draws, can arrive after the recording it's about has ended. +- **One recording can hold several clips.** Verdicts of record, record, record, don't, record, record, record drew a Stop when the fourth fragment was judged, and a new Start under a new Session ID when the fifth was. +- **A long recording is cut into clips of 300 seconds.** At exactly 300 seconds a hub writes Stop for the running clip, and 12 milliseconds later a Start under a new Session ID whose timestamp is that same instant. +- A recording judged Should Not Record from end to end draws no upload command at all. +- If the camera ends the recording stream itself, the hub writes its upload command at once and the clip can still be finalized. +- After Stop, a hub asks nothing more about the clip. + +I've never seen a hub write the StartAndStop command or the Pause stop action, and no hub has ever read the event queue: none subscribed to Buffer Event Sequence Number or wrote Buffer Event Command. + +**A recording a hub pulled, judged and commanded leaves no clip unless the camera uploads one.** The pulled recording is the hub's analysis feed, and it supplies the picture you see in a notification and beside an event in the timeline. The clip itself is the upload. + +#### Declining A Recording + +A camera that won't serve a recording should say so in its answer to the `dataSend.open`, with one of HAP's protocol errors. + +- **Not Allowed**: every hub in the home asks once for that motion, one after another, and none asks twice. +- **Busy**: one hub asks once, and no other hub asks. +- Either way no stream is left open, and the hubs ask again at the next motion. Four refusals in a row changed nothing about the fifth. +- Don't answer the open with success and then send an empty end of stream. A hub neither acknowledges that nor closes it, and the stream hangs until the camera gives up on it. + +The Home app showed nothing in its timeline for a declined motion. I checked that on the form I've just told you not to use, and not on the two refusals. + +### 8. Recording: The Clip Upload + +A clip goes to the publishing point as HTTP Live Streaming over CMAF: playlists and media, each object its own request. + +#### The Connection + +- **HTTP/2 only.** A request over HTTP/1.1 is answered 426. +- **Mutual TLS**, with the client certificate the hub issued and the key the camera made for its certificate request. +- The ordinary public root certificates verify the service. The server authority list the hub hands over completes a handshake too. +- **The method is `PUT`.** The same object sent by `POST` is answered 404 and never reaches the service. +- **The `User-Agent` must read `HKSV/3.0 (; ; )`**, as in `HKSV/3.0 ExampleCam/1.2.0 (Example; Model One; 4.5.6)`. A plain one is answered 400. The service doesn't hold those fields to the camera it provisioned: a made-up vendor and a vendor of `Unknown` were both accepted. + +#### The Objects + +Every clip lives in a folder of its own beneath the publishing point, `session_/`. Here's a whole clip, in the order it's sent. + +| Order | Path Under `session_/` | What It Is | Content Type | +| ----- | ------------------------------ | ---------------------------------------------------------------------------- | ------------------------------- | +| 1 | `index.m3u8` | The multivariant playlist. | `application/vnd.apple.mpegurl` | +| 2 | `high/index.m3u8` | The media playlist, listing no segments yet. | `application/vnd.apple.mpegurl` | +| 3 | `high/high.init` | The initialization segment. | `video/mp4` | +| 4 | `high/segment_1001.m4s` and on | The media segments, in order. | `video/iso.segment` | +| 5 | `high/index.m3u8` | The media playlist again, listing every segment and ending `#EXT-X-ENDLIST`. | `application/vnd.apple.mpegurl` | + +Each of these is answered 201. + +- **The picture and the sound can share one track file**, as above, or go as a video track and an audio track with a playlist each. Both play. +- The names aren't fixed. Tracks called `video` and `audio`, and segments numbered from 1, were accepted. So were segments without the `x-extinf-duration` header my uploads carry, and playlists without `#EXT-X-PLAYLIST-TYPE:EVENT`. +- A segment may be the very bytes the camera served the hub: a `prft`, a `moof` and an `mdat`. Segments that open with `styp` and `sidx` boxes are accepted as well. +- **A camera can upload while the hub is still pulling.** Send the playlists and the initialization segment at the Start, each segment as it's produced, and the closing playlist after the Stop. There's no need to hold a clip until it's whole. + +The playlists are in appendix A. + +#### Encryption + +Every media segment is sealed, whole, before it's sent. The initialization segment is not. + +- **A sealed segment** is a 16-byte IV, then the AES-256-GCM ciphertext of the entire segment, then the 16-byte tag. There's no additional authenticated data. Each segment gets a fresh random IV. +- **The key is not the Camera Key itself.** It's a content key derived from it: HKDF-SHA-256 with the Camera Key as the input, an empty salt, the info `HomeKit 1.0 CMAF Content`, and 32 bytes out. +- **The playlists say which key.** Each media playlist carries `#EXT-X-KEY:METHOD=AES-256-GCM,URI="hksv3:.key"` straight after its `#EXT-X-MAP` line, in the opening playlist and the closing one. The multivariant playlist carries the same attributes on an `#EXT-X-SESSION-KEY` line. +- **The identifier** is the Camera Key's key number shifted left 16 bits, with `0x4000` set in the low bits, written in hexadecimal with no prefix. +- No key is ever uploaded. The Home app supplies the key itself, by the identifier the playlist names. + +This is the part of the protocol that took longest to find, because the service is no help: it answers 201 to media it can't possibly parse. A clip sealed under the wrong key, or naming its key with the wrong address, uploads perfectly and then refuses to play. Three things told me this form is right. The Home app's own player asks for a key at exactly the address a playlist names. A clip built this way plays, picture and sound, where every other form I tried showed a struck-through play button, a black picture or nothing at all. And it plays in every shape I've sent since: one track file or two, H.264 or HEVC, AAC or Opus, commanded by a hub or not, and from more than one camera's key. + +The service also accepts a clip with no encryption at all, and the Home app plays it. Please don't. HomeKit Secure Video promises recordings only your own devices can read, and the hub hands you a key for a reason. **In HAP-NodeJS** there is no unencrypted upload: a camera without a usable key declines the hub's Start and uploads nothing. + +#### What The Service Answers + +| Status | What It Means | +| ------ | ---------------------------------------------------------------------------------------------------------------------- | +| 201 | Taken. | +| 208 | The folder already holds this object. Harmless while the folder is open. | +| 400 | Refused: a plain `User-Agent`, an empty playlist, or media sent into a folder that's already closed. | +| 401 | The credentials were refused. A `GET` is answered this way too. | +| 404 | The request never reached the service: the wrong method, or the publishing point's own address with no session folder. | +| 413 | The segment is too large. | +| 426 | The request came over HTTP/1.1. | +| 503 | A fault on the service's side. Try the object again. | + +#### Folders + +- **A folder's number belongs to the camera, and it must keep climbing**, through a renewal and a new publishing point too. A camera that started again at `session_1/` with fresh credentials had its clip refused: 208 for the multivariant playlist it had sent days before, and 400 for the first media playlist. +- **The closing playlist closes the folder.** After it, the folder takes no more media. +- While a folder is open, an object sent twice is answered 201 and then 208. The opening media playlist is the exception: it's replaced, and answered 201 both times. +- **A folder can be picked up again.** After a 503 on one object, the rest of the clip was accepted in the same folder half an hour later. +- **An object cut off mid-flight leaves nothing behind.** A segment whose connection dropped halfway was sent again on a new connection a second later, sealed afresh under a new IV, and answered 201. The clip plays. + +#### Sizes + +- **A media segment larger than about 10 MB is refused with 413.** I measured the limit between 9.10 MB, accepted, and 11.92 MB, refused. For scale, four seconds at the guide's highest 4K bitrate is about 2.5 MB. +- HEVC clips at 1920 by 1080 and at 3840 by 2160 are accepted and play. So is a camera's own stream passed straight through, untouched, at a size the guide doesn't list. +- Opus sound plays, and so does AAC-LC. A `CODECS` attribute naming Opus is taken. + +#### What The Home App Does With A Clip + +- **A clip is placed in the timeline at the moment its first object arrives.** Nothing moves it: not the times in its `prft` boxes, not an `#EXT-X-PROGRAM-DATE-TIME` line, not the timestamps of the hub's command. A clip sent ten minutes after its command stood ten minutes late. +- The Home app ties a hub's event to an uploaded recording that starts within 5.0 seconds of where it expects one. Since a clip is dated by its arrival, it sits later than the hub's own reckoning of where the recording began, and one event whose expected start fell eight seconds before the upload arrived was dropped. Start uploading the moment the Start comes. +- Clips that overlap in time show as one clip. +- **A clip needs nothing from the camera to play.** It plays while the camera is switched off. +- The timeline shows the clips of whichever recording path the camera's current services belong to. A camera that moves from HAP's older recording to HKSV3 seems to lose its old clips, and gets them back if it returns. They're hidden, not deleted. +- **Before you doubt an upload, restart things.** More than once the Home app showed a fresh clip's event and played nothing until the app was restarted. Once a single phone showed a clip as a black picture, while another device played it, until that phone was restarted. + +**In HAP-NodeJS** a clip's upload is given 15 seconds after its recording ends to finish. A process that exits sooner loses the end of the clip. + +### 9. Snapshots + +A camera that publishes the new services is asked for its snapshots over the HomeKit Data Stream, and only there. HAP's older `/resource` request is never used for such a camera. Neither Apple's guide nor HAP describes this exchange. + +**The request** is `dataSend.open` with the type `ipcamera.snapshot`, the target `controller` and the reason `snapshot`. Its metadata carries `imageWidth` and `imageHeight`, and usually a `reason`. + +**The reply** is shaped like one chunk of a recording: + +- Answer the open with status 0. +- Send one data event whose packet carries the picture, a JPEG, with `dataSequenceNumber` 1, `dataChunkSequenceNumber` 1, `isLastDataChunk` true and `dataTotalSize`, and with `endOfStream` true. +- The asker acknowledges the stream, and the Home app shows the picture. + +What to expect: + +- Two sizes are asked for: 1280 by 720 while a viewer at home has the camera on screen, about every ten seconds, and 640 by 360 for a viewer who's away. A hub fetches snapshots on behalf of a viewer who is away. +- On an iPhone, a camera's tile in the Home app is drawn from snapshots, not from a live stream. +- The reply I tested carried no `dataType` field. +- A doorbell press brings a burst: eleven snapshots inside five seconds. +- **There's no fallback.** A request that goes unanswered is closed about five seconds later, and no snapshot shows. A camera that lists the new services and doesn't serve snapshots this way shows none at all. +- The picture in a motion notification is not a snapshot. It's a frame of the recording the hub pulled. + +### 10. Doorbells + +A doorbell is a camera with HAP's Doorbell service on the same accessory. A press is a single press on Programmable Switch Event, which viewers subscribe to. + +- **A press brings a recording by itself.** With no motion raised, a hub opened a data stream and asked for a recording 50 milliseconds after a press, commanded an upload, and kept the clip. The new services carry no list of recording triggers, and none is needed. +- A press brings the alert's snapshots at once, as section 9 describes. +- A doorbell records on motion exactly as a camera does. +- A doorbell with two sensors is shown as a plain camera with two sensors is: one view, the first sensor's. + +### 11. Refusals And Failures In One Place + +What the far end does when a camera says no, or gets something wrong. + +| What The Camera Does | What Comes Back | +| ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Refuses Setup Endpoints with a Status of Error, its Status Active reading false | At home the Home app shows the camera as in use, and asks again about every three seconds while the camera is on screen. | +| Refuses WebRTC Solicit Offer with a Status of Error | From away the Home app shows the last picture, frozen, or the camera crossed out. The hub asks again, at anything from not at all to dozens of times a second. | +| Answers its stream services' reads and writes with HAP status -70402 | The Home app shows No Response, at home and from away, and asks far less often. | +| Offers a video section with no SSRC, a single-stream video section with no rid line and no header extensions, or AAC in place of Opus | The session is ended unanswered, within a second. | +| Offers a rid line with no restrictions, or Opus written `opus/48000/2` with no format parameters | The offer is answered, and the hub ends the session within seconds. | +| Sends video without SFrame, or under the four-byte tag | The session is kept, nothing is shown, and the hub ends it at about a minute. | +| Puts a stream ID on its RTP packets | The viewer refuses every video packet. The hub ends the session at about a minute. | +| Stamps each tier on a clock of its own | The viewer plays the first tier it takes, and discards every frame of the next. | +| Advertises an H.264 tier | Sessions start, keyframe requests come several times a second, and no picture is ever shown. | +| Sends a keyframe stamped the same as the last picture it sent | The viewer doesn't take it, and keeps asking until the stream's next keyframe. | +| Serves a recording without `prft` boxes | The hub pulls it to a normal close, writes no verdict and no command, and nothing is kept. | +| Refuses a recording with Not Allowed | Every hub in the home asks once for that motion. | +| Refuses a recording with Busy | One hub asks once. | +| Answers a recording's open with success, then an empty end of stream | The hub neither acknowledges nor closes it. | +| Declines a snapshot, or doesn't answer one | The stream is closed, and no snapshot shows. | +| Uploads nothing after a Start | No clip appears, whatever the hub decided. | +| Uploads over HTTP/1.1, by `POST`, or with a plain `User-Agent` | 426, 404 and 400. | +| Reuses a session folder's number | 208 for the multivariant playlist, and 400 for the media. | +| Uploads a segment larger than about 10 MB | 413 for that segment. | +| Uploads a clip sealed under the wrong key, or naming its key at the wrong address | 201 for every object, and a clip that stands in the timeline and won't play. | + +### 12. Open Points + +These are the questions whose answers would change what you build, or explain something your users will see. For every one of them, a working camera was confirmed without the answer. + +**Provisioning and credentials** + +- _Untested_: how long a publishing point stays good, and what else can spoil it. Uploads were accepted 34 and 99 hours after an address was written. Once, though, a camera's kept credentials were refused with a 401 after a short spell in the legacy form, and I don't know why, or how the hub knew to provision it again. +- _Untested_: what happens to a clip that's still uploading when a hub provisions the camera again. The worst case is the end of one clip. +- _Untested_: whether the session folder count starts over when a camera is unpaired and paired again. Keep counting through an unpairing if you can. +- _Untested_: a pairing that has never held a certificate, given the new services without a change of Firmware Revision. Every camera I upgraded this way had been provisioned at least once before. _Inferred_: it's provisioned like any other. + +**Recording** + +- _Untested_: what a hub's analysis counts as worth keeping. A person walking into view turns the verdict, and so does a moving shape. One still, dark picture was also judged worth recording, and I can't say why. +- _Untested_: the exact segment size limit, somewhere between 9.10 and 11.92 MB. +- _Untested_: why some clips open late. Two clips of a camera's own stream, passed through at more than twice the guide's highest bitrate for its size, opened at their second segment, though they play whole when you seek back. One ordinary 60-second clip opened 24 seconds in. Clips at the guide's bitrates otherwise open at their start. +- _Untested_: the StartAndStop command and the Pause stop action, which no hub has written. +- _Untested_: whether a doorbell press over a perfectly still picture makes a hub keep a clip. Mine had something moving in view. + +**Live views** + +- _Untested_: a Solicit Offer that carries Options, asking for SFrame or refusing it. The guide defines the field and no hub has sent it. _Inferred_: seal, and return a key, regardless. +- _Untested_: any network but mine. Every view from away left one home network, where host candidates were enough. +- _Untested_: six WebRTC sessions at once, which the guide requires. Two devices watching together share one session, and I never had more than a few. +- _Untested_: a request to resend a lost packet. None has ever arrived. +- _Untested_: whether any Apple device shows a second sensor. None I tried does. +- _Untested_: motion zones. I publish the service, and I haven't tested what a hub writes to it. +- _Untested_: the Privacy Mode Active answer to a Solicit Offer, which the guide defines. I've only refused with Error. +- _Untested_: how talkback from away sounds when a camera plays it as it arrives. Everything I listened to had been laid end to end first. + +## Appendices + +### A. Field Layouts + +#### The `prft` Box + +The producer reference time box that goes in front of every fragment of a recording. All numbers are big-endian. + +| Bytes | Field | Value | +| -------- | ------------------ | ----------------------------------------------------------------- | +| 0 to 3 | Size | 32 | +| 4 to 7 | Type | `prft` | +| 8 | Version | 1 | +| 9 to 11 | Flags | 24 | +| 12 to 15 | Reference track ID | The video track's ID. | +| 16 to 23 | NTP timestamp | The clock time the fragment begins, as a 64-bit NTP timestamp. | +| 24 to 31 | Media time | The fragment's first decode time, in the video track's timescale. | + +#### Timestamps In The Hub's Commands + +Start in Buffer Activity Command, and Start and Stop in Buffer Upload Command, are 64-bit NTP timestamps: seconds since 1900 in the upper 32 bits, and the fraction of a second in the lower 32. Duration in Buffer Activity Command is in milliseconds. + +#### A Sealed Media Segment + +| Bytes | Field | +| ----------------- | ----------------------------------------------------------------------------------- | +| 0 to 15 | IV, random, fresh for each segment. | +| 16 to the last 17 | AES-256-GCM ciphertext of the whole segment, with no additional authenticated data. | +| The last 16 | Authentication tag. | + +```text +content key = HKDF-SHA-256(key: Camera Key, salt: empty, info: "HomeKit 1.0 CMAF Content", 32 bytes) +key identifier = (key number << 16) | 0x4000, written in hexadecimal +key address = "hksv3:" || key identifier || ".key" +``` + +#### The Playlists + +A multivariant playlist, for one track file that holds picture and sound: + +```text +#EXTM3U +#EXT-X-VERSION:7 +#EXT-X-INDEPENDENT-SEGMENTS +#EXT-X-SESSION-KEY:METHOD=AES-256-GCM,URI="hksv3:3a94c1f07be24000.key" + +#EXT-X-STREAM-INF:BANDWIDTH=1800000,AVERAGE-BANDWIDTH=1700000,RESOLUTION=1920x1080,CODECS="hvc1.1.6.L120.b0,Opus" +high/index.m3u8 +``` + +Its media playlist, as it reads when the clip closes. The opening one is the same down to the `#EXT-X-KEY` line, and stops there. + +```text +#EXTM3U +#EXT-X-VERSION:7 +#EXT-X-TARGETDURATION:4 +#EXT-X-MEDIA-SEQUENCE:1001 +#EXT-X-PLAYLIST-TYPE:EVENT +#EXT-X-INDEPENDENT-SEGMENTS +#EXT-X-MAP:URI="high.init" +#EXT-X-KEY:METHOD=AES-256-GCM,URI="hksv3:3a94c1f07be24000.key" +#EXTINF:4.000000, +segment_1001.m4s +#EXTINF:4.000000, +segment_1002.m4s +#EXT-X-ENDLIST +``` + +A clip may name the sensor it came from with one more line in the multivariant playlist, after `#EXT-X-INDEPENDENT-SEGMENTS`: + +```text +#EXT-X-SESSION-DATA:DATA-ID="com.apple.homekit.sensor-id",VALUE="" +``` + +#### The Byte In Front Of An SFrame Payload + +| Value | Meaning | +| ------ | ---------------------------------------------- | +| `0x80` | The first packet of a ciphertext. | +| `0x00` | A middle packet. | +| `0x40` | The last packet. | +| `0xC0` | The only packet: the whole ciphertext is here. | + +#### Key IDs + +| Key | Form | +| ---------------------------------------- | ------------------------------------------------------------------------------------ | +| A clip's content key | The Camera Key's key number, shifted left 16 bits, with `0x4000` in the low sixteen. | +| A viewer's receive key, written by a hub | 64 bits, with `0x8000` in the low sixteen. | +| The camera's own SFrame key | 64 bits of the camera's choosing. Mine carry `0x8000` in the low sixteen. | + +### B. A Worked Offer + +An offer for a camera of three tiers, with made-up addresses, credentials and SSRCs. Lines every WebRTC stack writes for itself are left as they'd ordinarily appear. + +```text +v=0 +o=- 4611731400430051336 2 IN IP4 127.0.0.1 +s=- +t=0 0 +a=group:BUNDLE 0 1 2 3 +m=video 9 UDP/TLS/RTP/SAVPF 99 +c=IN IP4 0.0.0.0 +a=mid:0 +a=sendonly +a=rtcp-mux +a=setup:actpass +a=ice-ufrag:Zq3x +a=ice-pwd:u1Hc9mWq0fTn2RkV7yLbXe4d +a=fingerprint:sha-256 4A:1F:...:9C +a=rtpmap:99 H265/90000 +a=rtcp-fb:99 nack +a=rtcp-fb:99 nack pli +a=rtcp-fb:99 ccm fir +a=extmap:1 urn:ietf:params:rtp-hdrext:sdes:mid +a=extmap:2 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id +a=rid:1 send max-width=1920;max-height=1080;max-fps=30;max-br=1700000 +a=simulcast:send 1 +a=ssrc:2890137601 cname:camera +a=candidate:1 1 udp 2130706431 192.0.2.10 50112 typ host +m=video 9 UDP/TLS/RTP/SAVPF 99 +a=mid:1 +a=sendonly +a=rtpmap:99 H265/90000 +a=rid:2 send max-width=1280;max-height=720;max-fps=30;max-br=768000 +a=simulcast:send 2 +a=ssrc:1177460482 cname:camera +m=video 9 UDP/TLS/RTP/SAVPF 99 +a=mid:2 +a=sendonly +a=rtpmap:99 H265/90000 +a=rid:3 send max-width=640;max-height=360;max-fps=15;max-br=180000 +a=simulcast:send 3 +a=ssrc:3406022915 cname:camera +m=audio 9 UDP/TLS/RTP/SAVPF 110 +a=mid:3 +a=sendonly +a=rtpmap:110 opus/48000 +a=fmtp:110 minptime=20;useinbandfec=0 +a=ssrc:902114308 cname:camera +``` + +The second and third video sections and the audio section repeat the transport, feedback and extension lines of the first. They're left out here to keep the example readable. Notice that the four SSRCs differ in their low sixteen bits. + +The answer that comes back keeps the four sections. What's worth recognizing in it: + +```text +a=group:BUNDLE 0 1 2 3 +a=ice-lite +m=video 9 UDP/TLS/RTP/SAVPF 99 +a=recvonly +a=setup:active +a=rtcp-mux +a=rtcp-rsize +a=rtpmap:99 H265/90000 +a=fmtp:99 +a=rid:1 recv +a=simulcast:recv 1 +a=end-of-candidates +``` + +Ahead of `a=end-of-candidates` come two host candidates for the relay, on one address in Apple's 17.0.0.0/8 block: one on a UDP port that changes from view to view, and one on TCP port 80. + +### C. Timings I Observed + +All from my home, my network and my hubs. They show the pace of things and promise nothing. + +| From | To | Time | +| ------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------- | +| Pairing | The hub's first round of settings | Within 2 seconds | +| The first provisioning write | The fourth | Within 2 seconds | +| Provisioning | Recording switched on | 6 to 7 seconds | +| Motion Detected | The hub's connection | About 150 milliseconds | +| Motion Detected | The hub's request for a recording | Usually 50 to 250 milliseconds | +| A fragment sent | Its verdict | 0.26 to 0.92 seconds, most often about 0.3 | +| A Should Record verdict | The Start command | 5 to 11 milliseconds | +| Motion Detected | The Start command | Typically 2 to 4 seconds | +| The hub closing a recording | The Stop command | 5 to 38 milliseconds | +| A clip's Start | A forced cut to a new clip | 300 seconds | +| A viewer at home reading the database | Its Setup Endpoints write | 50 to 70 milliseconds | +| A view's Start at home | Its first keyframe request, when it isn't handed a keyframe first | 50 to 80 milliseconds | +| A lost packet at home | A keyframe request | Usually within 0.1 seconds | +| Solicit Offer | The answer | Usually 0.12 to 0.25 seconds | +| The answer | The viewer's first key | Usually 0.2 to 0.5 seconds. As long as 40 | +| A viewer's key | Keyframe requests on the smallest, middle and largest tier | Within about 1 second, 1 to 2 seconds, and 5 to 6 seconds | +| A lost packet from away | A keyframe request | 0.3 to 1.2 seconds | +| A session's keys removed | The session ended | Usually 0.2 seconds | +| A session with no picture | The hub ending it | About a minute | +| An unanswered snapshot request | Its stream closed | About 5 seconds | +| A certificate issued | Its expiry | 60 days | diff --git a/guides/UpgradingCameraPlugins.md b/guides/UpgradingCameraPlugins.md new file mode 100644 index 000000000..3c24a9b3c --- /dev/null +++ b/guides/UpgradingCameraPlugins.md @@ -0,0 +1,316 @@ +# Upgrading a Camera Plugin to HAP-NodeJS 2.4 + +HAP-NodeJS 2.4 adds the camera features Apple introduced with iOS 27, which Apple calls HKSV3 internally: live video in tiers, views from away over WebRTC, and recordings the camera uploads itself. What those are, and how a home hub behaves around them, is written up in [HomeKit Cameras in iOS 27](HKSV3Protocol.md). This guide is the other half: what changed in the library, and what a plugin author does about it. + +Two terms come up throughout. A camera in the **modern form** is a camera set up for iOS 27 and later, with those features. A camera in the **legacy form** is a camera set up the way it always has been. A plugin chooses the form for each camera. + +## The Short Version + +Moving a camera to the modern form means writing less code, not more. The library now does most of the work a camera plugin used to carry. + +**What you provide:** + +- **A description of the camera**: the video sizes and bitrates it offers. +- **A video stream for each of those**: fragmented MP4, with HEVC video and Opus audio, handed to the library as it arrives. `ffmpeg` writes it with two options. +- **A snapshot function** that answers a JPEG. +- **Motion**, reported with one call. +- **Optionally, somewhere to send a visitor's voice**, if the camera has a speaker. + +**What you no longer write:** + +- **Stream negotiation.** No `prepareStream`, no ports, no SRTP keys, no session for each viewer. The library runs every session, at home and from away. +- **A process for each viewer.** Each of the camera's streams runs once, however many people are watching it. +- **Recording.** No recording delegate, no prebuffer of your own, no fragments to cut. The library keeps the recent video, hands a hub what it asks for, and encrypts and uploads each clip. +- **Mute, session limits and requests for a fresh picture.** The library handles each. +- **Shutdown code.** You register what you start, and the library releases it when it's no longer needed. + +Most of a camera plugin's streaming and recording code goes away. What's left is the part only you can do: getting video out of your camera. + +And nothing forces the move. A camera in the legacy form keeps working as it does today. + +## Who Needs To Do What + +- **Your plugin has no camera.** Check the Node.js version below. Two other items in [What Changed For Every Plugin](#what-changed-for-every-plugin) can reach you, and both are rare: a `Characteristic` subclass that declares a name the class now uses, and a `DataStreamServer` used after it's destroyed. +- **Your plugin has a camera and you want it to keep working as it does.** Read [What Changed For Every Plugin](#what-changed-for-every-plugin). It's a short list, and most plugins will find nothing in it that touches them. +- **You want the iOS 27 features.** Read the whole guide. A camera takes the modern form by stating a new block of options, and that camera then streams and records through the library. + +## What Changed For Every Plugin + +### Requirements + +- **Node.js `^22.20.0 || ^24 || ^26`.** The floor was `^22.12.0`. Node 22.12 through 22.19 are now outside the supported range. +- **A new dependency, `werift`.** It's the WebRTC stack behind views from away. It installs with the library for everyone and is loaded only when a camera in the new form is built. A plugin without one never loads it. + +### Changes You Can Meet At Compile Time + +No name the library exported in 2.3.1 was removed or renamed. A few declared shapes changed, and TypeScript will tell you if one of them reaches your code. + +- **`CameraControllerOptions` is now a union** of two forms, `CameraControllerLegacyOptions` and `CameraControllerCapabilitiesOptions`. Building a controller from an object literal compiles as before. What stops compiling is an interface that `extends` it, a class that `implements` it, and a read of a member through a value typed as the union, such as `options.streamingOptions.video`. Type such a value as `CameraControllerLegacyOptions` and it compiles again. +- **`RTPStreamManagement.setupEndpointsResponse` is gone.** The answer to Setup Endpoints is now served to the connection that asked and is never stored. +- **`RecordingManagement.options` is optional**, and so are five fields of `RecordingManagementState`: `recordingActive`, `recordingAudioActive`, `eventSnapshotsActive`, `homeKitCameraActive` and `periodicSnapshotsActive`. A read of one into a plain `boolean`, or of `recordingManagement.options.prebufferLength`, needs a check first. +- **`CameraRecordingDelegate.handleRecordingStreamRequest` returns `AsyncIterable`**, where it returned `AsyncGenerator`. A delegate you implement is unaffected. Code that calls `.next()` or `.return()` on the result is. +- **`CameraControllerEvents` has more members.** A `switch` that proves it covers every event needs the new ones. +- **`CameraController` has new members**: `recordingAllowed`, `streamingAllowed`, `latestKeyframe`, `updateMotionDetected`, `updateSourceState` and `handleAccessoryContext`. A subclass that declares one of those names, `motionSensorRequired`, or a name the class now keeps privately, such as `snapshot` or `streaming`, stops compiling. +- **`CharacteristicProps` gains `transient` and `sensitive`, and `Characteristic` gains `releaseTransientAnswers`.** A subclass that declares that name stops compiling. + +### Changes To A Camera At Run Time + +These apply to a camera set up exactly as it was in 2.3.1. + +- **A controller with no `delegate` or no `streamingOptions` throws when it's constructed**, and so does a `recording` given without its `options`. In 2.3.1 and earlier these were assigned unchecked. TypeScript already refused them. This reaches JavaScript callers alone. +- **`microphone-change` and `speaker-change` no longer go through `emit`.** Listeners added with `on` hear them as before, each called in turn and guarded: one that throws doesn't stop the next. A subclass that overrides `emit`, or a test that spies on it, no longer sees these two events. +- **A recording delegate can hear `updateRecordingActive` at more moments**: when the camera finishes restoring its saved state with a value that differs from the stored one, before the first recording if it hasn't been told yet, and when the value changes by something other than a write. The configuration is still handed over before it. +- **Setup Endpoints keeps no value.** `characteristic.value` reads nothing for it, and a serialized accessory stores `null` there. A hub's write and read are served as before. +- **A snapshot handler whose promise rejects fails its snapshot at once.** In 2.3.1 and earlier the rejection went unhandled and the request waited out its 25 seconds. The warning at 8 seconds and the failure at 25 are unchanged. + +One more applies wherever a HomeKit Data Stream is used, a remote with Siri as much as a camera: + +- **A destroyed `DataStreamServer` stays destroyed.** A later `prepareSession` is answered with the error `The data stream server was destroyed.`, which is also the error now given to a session that was waiting when the server was destroyed. + +## The Two Forms Of A Camera + +A camera is now set up in one of two forms, and the options you hand `CameraController` decide which. + +- **The legacy form** is the camera you already have: a streaming delegate that negotiates SRTP, and for HomeKit Secure Video a recording delegate that hands a hub fragments. Nothing about it is deprecated. +- **The modern form** is a camera that states a `cameraCapabilities` block. It offers its video in tiers, answers views from away over WebRTC, and uploads its own recordings. It's for a home on iOS 27 or later. + +A camera is one or the other, never both. The two forms publish different services, and a controller picks its stream by what it finds. A camera that published both would be shown through whichever stream services carry the lower instance IDs, which is rarely the one you'd choose. The types refuse a mix, and so does the constructor. + +Two things decide whether a camera can take the modern form: + +- **It hands you HEVC video and Opus audio.** The modern form advertises nothing else. A camera that can only produce H.264 stays in the legacy form. +- **Its home is on iOS 27 or later.** The services behind the modern form are an iOS 27 feature. + +## Moving A Camera To The Modern Form + +### What Replaces What + +| In the legacy form | In the modern form | +| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `delegate.prepareStream` and `handleStreamRequest` | `cameraCapabilities.streaming.delegate.tierDemandStarted`. The library owns the sessions, ports, keys and SRTP. | +| `delegate.handleSnapshotRequest(request, callback)` | `cameraCapabilities.snapshot(request, signal)`, which answers a promise. | +| `streamingOptions`, with its resolutions, codecs and crypto suites | `cameraCapabilities.videoSensors`, each with its `tiers` and `audio`. | +| `cameraStreamCount` | `streaming.maxSessions`, 5 by default, and `webrtc.maxSessions`, 6 by default. | +| `recording.options` and `recording.delegate` | `cameraCapabilities.recording`, with `prebuffer` and `shouldRecord`. The library builds every recording and uploads every clip. | +| `sensors.motion`, optional | `sensors.motion`, required unless the camera is a doorbell, since a hub starts a recording at motion. | +| Muting your own streams on `microphone-change` and `speaker-change` | Nothing. The library applies mute itself. | +| `controller.streamManagements` and `controller.recordingManagement.options` | Empty and `undefined`. A modern camera has no legacy stream or recording options to read. | + +### State The Camera + +A camera describes each of its video sensors once: its size, its tiers and its sound. Everything else the library fills in. + +The new types, `TierStream` and `MultiTierStreamingDelegate` among them, come from `@homebridge/hap-nodejs` with `import type`. Homebridge doesn't re-export them. Values, such as `CameraSensorIntent`, are reached through `api.hap` as always. + +```ts +const camera = new hap.CameraController({ + cameraCapabilities: { + snapshot: async (request, signal): Promise => await device.snapshot(request, { signal }), + streaming: { delegate }, + videoSensors: [{ + audio: { bitrate: 24 }, + dimensions: { height: 2160, width: 3840 }, + intent: hap.CameraSensorIntent.MAIN, + tiers: [ + { bitrate: 4500, frameRate: 30, height: 2160, id: 1, quality: hap.CameraVideoQuality.HIGH, recorded: true, width: 3840 }, + { bitrate: 768, frameRate: 30, height: 720, id: 2, quality: hap.CameraVideoQuality.MEDIUM, width: 1280 }, + { bitrate: 180, frameRate: 15, height: 360, id: 3, quality: hap.CameraVideoQuality.LOW, width: 640 }, + ], + uuid: hap.uuid.generate(device.mac), + }], + }, + sensors: { motion: true }, +}) +``` + +- **A sensor's `uuid`** must be a UUID and must stay the same across restarts. Derive it from something that identifies the device. +- **A tier** is one encoding of the sensor's picture: `id`, `width`, `height`, `frameRate`, `bitrate` in kbps and `quality`. Apple's guide asks for three, and its highest bitrates are 5000 kbps for 4K, 3000 for 2K, 1800 for 1080p, 800 for 720p and 190 for 360p and 240p. `peakBitrate` defaults to that maximum, or to the tier's `bitrate` when the tier is above it or its size isn't listed. +- **`recorded: true`** marks the one tier the camera records. With none marked, it's the first sensor's best tier. +- **A tier runs on demand or all the time, and the choice is yours.** By default the library asks for a tier's stream when its first viewer arrives and ends it when the last one leaves, and the stream runs only while someone is watching. Mark a tier `keepRunning: true` and the library keeps it running whenever streaming is allowed. A view of it then opens at once, from pictures the library already holds, at the cost of a stream that never stops. The recorded tier is kept running whenever recording is allowed, whatever its mark. +- **Start with tiers on demand.** Leave `keepRunning` off at first. See how quickly views open at home and from away, and only then decide whether any tier is worth keeping on all the time. A tier that never stops puts load on the camera or its controller and on the network around the clock, and on your processor too if you encode it yourself. Most cameras don't need that for every tier. +- **The order of `videoSensors` matters.** The first is the one a controller shows and the one snapshots are asked for. +- **The library copies your sensors and tiers.** Changing them afterwards changes nothing. Your delegate and your functions are kept as they are. + +A mistake in the block throws a `TypeError` from the constructor, whose sentence names the sensor and, for most mistakes, the member or tier at fault. A sensor's `intent` and a tier's `quality` must each be a member of its set: a value outside it, or one a JavaScript caller leaves out, is refused the same way. Falling below one of Apple's minimums, such as fewer than three tiers, is only a debug event unless you set `strict: true`, which turns the first one into a throw. + +### The New Sets Are Constant Objects + +`CameraSensorIntent`, `CameraVideoQuality` and `CameraZoneApplicationMethod` aren't enums. Each is a plain object of names and numbers, with a type of the same name. You use one as you'd use an enum, `hap.CameraVideoQuality.HIGH` as a value and `CameraVideoQuality` as a type, and four things differ: + +- **No name from a number.** `hap.CameraVideoQuality[2]` is `undefined`, where an enum answers `'HIGH'`. TypeScript refuses the lookup. Plain JavaScript reads `undefined` and says nothing. +- **Walking the set gives one direction.** `Object.values` lists the numbers alone and `Object.keys` the names alone, where a numeric enum lists both in each. +- **A computed number needs a member or a cast.** `const quality: CameraVideoQuality = n` compiles against an enum and is refused here. +- **Two sets with the same numbers aren't told apart.** Another set's member with the same number is accepted where one of these is expected. Between two enums the compiler refuses that. + +One rarer case: a member used as a type is written `typeof hap.CameraSensorIntent.MAIN`. + +This is the form every set of named constants takes from 2.4 on. A constant object is plain JavaScript, with nothing generated for it at build time, and its type is exactly the set of its values. The enums the library has already released stay enums through 2.x, because changing their kind would break the plugins that use them. The project intends to move them to this form in the next major version. + +### Feed Each Tier + +`tierDemandStarted` is called when a tier gains its first consumer, whether that's a viewer or the library holding the tier for recording. You start the tier's video, from an encoder or straight from the camera, and write its bytes to the stream you're handed. + +```ts +const delegate: MultiTierStreamingDelegate = { + tierDemandStarted: (stream: TierStream): void => { + const encoder = stream.use(spawn('ffmpeg', argsFor(stream.tier))) + + encoder.on('error', (error: Error) => stream.fail(error.message)) + encoder.on('exit', (code, signal) => stream.fail(`The encoder ended with ${signal ?? `code ${code}`}.`)) + encoder.stdout.on('data', (chunk: Buffer) => stream.write(chunk)) + }, +} +``` + +- **The stream is fragmented MP4**: an initialization segment, then fragments in the `default_base_moof` layout. The picture is the first video track, HEVC under `hvc1` or `hev1`. The sound is the first Opus track. From ffmpeg that's `-movflags empty_moov+default_base_moof` with `-frag_duration`. Fragments without `default_base_moof` fail the tier. +- **Short fragments mean a short delay.** The library sends a fragment once its last byte arrives, which makes the fragment's length the delay a viewer sees. One frame per fragment is the shortest. +- **Register what you start.** `stream.use(value)` takes anything with `[Symbol.dispose]` or `[Symbol.asyncDispose]`, a child process among them, and `stream.defer(fn)` takes a function. The library releases every registration once, when the tier loses its last consumer, and whenever the camera goes out of service. You write no shutdown code. +- **A start may be asynchronous.** It's handed an abort `signal` as its second argument. Return a promise and hand that signal to what you await. A start that hasn't settled in 30 seconds is withdrawn. A rejection refuses the demand. +- **`stream.discontinuity()`** marks a restart of your source, at a reconnect. **`stream.fail(reason)`** ends the tier for everyone on it and raises one problem. +- **Report an encoder that dies.** Fail the tier when your encoder exits, as the example does. An exit you report ends the tier at once. The library also catches an encoder that stops writing without exiting: a stream that hands over no picture for 10 seconds, or no first picture within 30 seconds of your start settling, fails the tier as `stream.fail` does, whoever is on it. Sound alone doesn't count. The library raises one problem for that silence, and it asks again for a tier it keeps running. A view that was open on the tier can keep showing its last picture until it's closed, and the next view starts fresh. A failure reported after the library has ended the stream does nothing, which makes the exit its own shutdown causes harmless. A signal that stops your process can reach your encoder too, and its exit can then come before the library has ended the stream: once your own stop has begun, don't fail the tier for an exit, as the example does. +- **`stream.tier.sound`** says whether this tier's stream must carry sound. Read it at each start. +- **Stay within the tier's bitrates.** A heavier stream is accepted, never refused, but a view of it can start rough. + +### ffmpeg Recipes + +If ffmpeg produces a tier's stream, its arguments are three parts put together: what happens to the video, what happens to the sound, and an output part that never changes. Every part below was run with the ffmpeg that `ffmpeg-for-homebridge` ships, and its output read by the library's own stream reader. + +**The output part** is the same for every tier: + +```sh +-f mp4 -movflags empty_moov+default_base_moof -frag_duration 33333 pipe:1 +``` + +- **`-frag_duration` is the length of one frame in microseconds**: 33333 at 30 frames per second, 66666 at 15. +- **Don't use `frag_every_frame` on a tier that carries sound.** ffmpeg then writes pairs of sound samples at one time, the first with no length, and the library fails the tier. `-frag_duration` gives the same one-frame delay without that. + +**The video part** is one of two: + +- **The camera gives HEVC.** Copy it: `-map 0:v:0 -c:v copy`. Nothing is encoded, and the keyframes are the camera's own. ffmpeg can't move them. +- **The camera gives anything else.** Encode it to HEVC: + +```sh +-map 0:v:0 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 -x265-params keyint=30:min-keyint=30:scenecut=0:log-level=error -b:v 768k -maxrate 800k -bufsize 800k +``` + +- **Set `keyint` and `min-keyint` to the tier's frame rate** for a keyframe every second, and the three rates from the tier's `bitrate` and `peakBitrate`. +- **For a smaller tier, scale after the `-map`**: `-vf fps=15,scale=640:360`. + +**The sound part** is one of three: + +- **No sound**: `-an`. +- **The camera gives Opus.** Copy it: `-map 0:a:0 -c:a copy`. +- **The camera gives anything else.** Encode it to Opus: `-map 0:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000`. AAC copied through isn't read as sound. The library reads Opus alone. + +Three whole commands, with `` standing for however you read your camera. + +A camera that gives HEVC and Opus, both copied: + +```sh +ffmpeg \ + -map 0:v:0 -c:v copy \ + -map 0:a:0 -c:a copy \ + -f mp4 -movflags empty_moov+default_base_moof -frag_duration 33333 pipe:1 +``` + +A camera that gives H.264 and AAC, encoded for a 1280 by 720 tier at 30 frames per second: + +```sh +ffmpeg \ + -map 0:v:0 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 \ + -x265-params keyint=30:min-keyint=30:scenecut=0:log-level=error -b:v 768k -maxrate 800k -bufsize 800k \ + -map 0:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000 \ + -f mp4 -movflags empty_moov+default_base_moof -frag_duration 33333 pipe:1 +``` + +The same camera's 640 by 360 tier at 15 frames per second: + +```sh +ffmpeg \ + -map 0:v:0 -vf fps=15,scale=640:360 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 \ + -x265-params keyint=15:min-keyint=15:scenecut=0:log-level=error -b:v 180k -maxrate 190k -bufsize 190k \ + -map 0:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000 \ + -f mp4 -movflags empty_moov+default_base_moof -frag_duration 66666 pipe:1 +``` + +- **Keyframes come from the encoder, or from the camera.** The encoded recipes ask for one every second. With copied video, set the interval on the camera itself. +- **A fragment can hold no picture, or two.** A source that counts time in milliseconds doesn't line up with `-frag_duration` exactly, and a tier with sound has fragments that hold sound alone. The library reads all of these. + +### Sound And Talkback + +- **Sound is Opus**, one channel in 20 millisecond packets unless you state otherwise. With `audio.source` left at `'tier'`, every tier's stream carries its own Opus track. With `'shared'`, one tier carries the sound for the whole sensor, which saves encoding it several times. +- **The Microphone is always published.** The Speaker is published exactly when your delegate has a `talkbackStarted` method. Give a camera that method only if it has a speaker. +- **`talkbackStarted(talker)`** is called once for each talker in a view, and answers a sink with a `write(packet)` method. Each packet is a plain RTP packet carrying Opus. From away a packet can hold 40 milliseconds where one at home holds 20, and packets can arrive in clumps: read each packet's length from the packet and pace by its timestamp. Answer `undefined` to decline that talker. The call must answer at once: a promise is treated as a decline. + +```ts +if (device.hasSpeaker) { + delegate.talkbackStarted = (talker: Talker): TalkbackSink => talker.use(new TalkbackDecoder(talker.sensorUUID)) +} +``` + +- **Mute is the library's job.** A muted Microphone sends no live sound and a muted Speaker gets no talkback, without any code of yours. + +### Snapshots + +`snapshot(request, signal)` answers a promise of a JPEG at the size asked. The library refuses a snapshot itself, without calling you, while the user has the camera switched off or the camera is out of service. The `signal` aborts at 25 seconds, when whoever asked has gone, and when the camera is removed. + +The request carries `keyframe` when a running tier has one: an MP4 holding a single HEVC picture, with its `age`. Decoding it is often faster than asking the camera for a picture. + +### Recording + +In the modern form you build no recording and no clip. While the user allows recording, the library keeps the recorded tier running, holds its recent video, hands a hub what it asks for, and uploads the clip when the hub says to keep it. + +- **`prebuffer`** is how far back each recording reaches, in milliseconds: 5000 by default, 30000 at most. +- **`shouldRecord(start)`** lets you decline a recording. It's asked once, and must answer `true` or `false` on the spot. +- **The recorded tier's stream is what gets uploaded.** It has to be what Apple's guide accepts: HEVC at up to 3840 by 2160 and 24 or 30 frames per second, with Opus audio. The guide asks for recorded sound captured at 16 or 24 kHz. Opus counts time at 48 kHz whatever rate the sound was captured at, and that's what the library advertises. Keep the stream within the guide's bitrates. Apple's service refuses a segment that's too large, and in testing the cap was 10 MB. The library cuts segments at keyframes to stay under that, and can only do it if the stream has keyframes often enough. +- **`recording-started` and `recording-ended`** tell you of each recording. + +### Motion + +- **Report motion with `camera.updateMotionDetected(detected, sensorUUIDs)`.** The second argument says which sensors saw it, and may be left out. +- **The user's Motion Enabled setting is honored for you.** While it's off, motion you report is held back: it's never stored and never sent to a hub. Clearing motion always goes through, and the library clears any standing motion itself when the setting turns off. +- **Motion zones are opt-in.** Give a sensor a `motionZones(zones, reason, signal)` function and the library publishes that sensor's zones service. You're handed the zones a user draws, and handed them again when the camera restores its saved state and when it's reset. + +### Tell The Library When The Camera Goes Away + +`camera.updateSourceState(state)` tells the library what your source is doing. + +- **`'away'`**: the camera is unreachable. Every view and recording ends, and requests are refused without calling you. +- **`'recovering'`**: you're reconnecting. Every running tier is held for up to 30 seconds from your call, whoever is on it, and the tiers the library keeps running, the recorded tier and each `keepRunning` tier, report no stall meanwhile. The tier's next picture ends the wait, and a tier that hands over none by then fails. +- **`'available'`**: the camera is back. + +### Hear From The Library + +- **Events** on the controller: `operating-mode-change`, `streaming-enabled-change`, `recording-started`, `recording-ended`, `live-view-started` and `live-view-ended`, beside the two mute events. `operating-mode-change` carries each of the user's camera settings as it changes, with the field, its value and why it changed, and it's the event to read the camera's whole state at, typed `OperatingModeState`. A listener that throws is reported and doesn't stop the next. +- **Manually Disabled.** If you add Manually Disabled to a modern camera, a hub can now switch it with a timed write. While it's set, nothing streams or records, and `operating-mode-change` reports the field `manuallyDisabled`. +- **Problems.** `hap.onCameraProblem(accessoryUUID, listener)` hands you every problem a camera raises, each with a `kind`, a `level` and a `sentence`: a failed tier, a stalled stream, a failed upload, and a failure in your own code among them. It answers a disposable. While nothing is subscribed, the library prints each problem itself. Subscribe, and you decide how they're logged. Subscribe before you configure the controller, or you'll miss a problem raised while the camera restores its saved state. +- **Debug output** is under names that begin `HAP-NodeJS:Camera:`, plus `HAP-NodeJS:RecordingProvisioning` and `HAP-NodeJS:HKSV`, read from `DEBUG` when the library loads. + +One caution. `HAP-NodeJS:Camera:WebRTC:werift` turns on the WebRTC stack's own output, which carries network addresses and session keys. It's off unless you name it exactly, and it shouldn't be pasted into a public issue. + +The accessory's own debug lines print `` for the camera's key material, including Setup Endpoints, and print other TLV8 values by size. + +## A Plugin That Serves Both Forms + +Most plugins will serve both: the modern form where a camera and the user's home can take it, and the legacy form everywhere else. That's one branch, at the point you construct the controller. + +```ts +const controller = wantsModernForm(device) + ? new hap.CameraController({ cameraCapabilities: capabilitiesFor(device), sensors: { motion: true } }) + : new hap.CameraController(legacyOptionsFor(device)) +``` + +- **Check the library before you take the branch.** Homebridge pins HAP-NodeJS at one version, and your plugin will run on libraries with and without the modern form. Read the version from `api.hap.HAPLibraryVersion()` and take the modern form only at the first version that carries it, 2.4.0 or the beta you're testing against. +- **Fall back if the constructor throws.** Wrap the modern construction, and on a throw build the legacy camera instead. A mistake the constructor catches then never takes a user's cameras away. +- **Say so when the modern form is in use.** Users look for that line to see whether it worked. +- **To change a camera's form, construct it in the other form at the next start.** The library adds and removes the services to match and tells HomeKit the configuration changed. A camera's settings aren't read again while it runs. +- **A modern camera run on a library before 2.4 is half-working until the library moves forward again.** Nothing crashes and no setting is reset, but the older library lists the camera's new services with no code behind them: motion can read inactive, snapshots can go unanswered and a live view can fail to start. Going forward to 2.4 again restores it, and a camera that never used the modern form isn't affected. + +[homebridge-unifi-protect](https://github.com/hjdhjd/homebridge-unifi-protect) serves both forms this way, and is a working example to read. + +## A Checklist + +- Node.js is 22.20 or a later 22, or 24, or 26. +- Your plugin compiles against 2.4. +- For each camera you move: it produces HEVC and Opus, it states its sensors and tiers, its delegate feeds fragmented MP4, it has a motion sensor unless it's a doorbell, and it answers snapshots through the new function. +- Your plugin checks the library's version, falls back to the legacy form on a throw, and logs when the modern form is in use. diff --git a/package.json b/package.json index 8df5377db..fbe54d4aa 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,8 @@ "files": [ "LICENSE", "README.md", - "dist" + "dist", + "!dist/accessories/ModernCamera_example.*" ], "engines": { "node": "^22.20.0 || ^24 || ^26" diff --git a/src/accessories/ModernCamera_example.ts b/src/accessories/ModernCamera_example.ts new file mode 100644 index 000000000..4c6501525 --- /dev/null +++ b/src/accessories/ModernCamera_example.ts @@ -0,0 +1,184 @@ +/* A camera in the modern form, stated through the camera capabilities block, which carries the camera features Apple introduced with iOS 27: a video + * sensor whose tiers serve live view at home and from away, recording from the camera buffer, snapshots, and a motion sensor raised by a switch on the + * accessory. Its picture and sound are ffmpeg's test pattern and tone, encoded as each tier is asked for, which is why it needs ffmpeg on the PATH with the + * libx265 and libopus encoders, and a home on iOS 27 or later to add it to. + * + * Run `npm run build`, then `node dist/accessories/ModernCamera_example.js`, and add the camera in the Home app with the setup code it prints. An interrupt + * unpublishes it and the process ends by itself. The pairing is kept in `persist` under the directory it runs from, and a later run from there reuses it... + * removing `persist` lets the camera be added afresh. + * + * It leaves out what a camera adds only where it needs it: talkback, a doorbell, a second sensor, motion zones, shared sound, a tier marked `keepRunning`, + * and `strict`. + */ +import type { CameraSnapshotRequest, TierStream } from '../index.js' + +import { Buffer } from 'node:buffer' +import { spawn, spawnSync } from 'node:child_process' +import { once } from 'node:events' +import process from 'node:process' + +import { Accessory, CameraController, CameraSensorIntent, CameraVideoQuality, Categories, Characteristic, onCameraProblem, Service, uuid } from '../index.js' + +// The setup code the camera is added with, which the program prints once it is published. +const PINCODE = '031-45-154' + +// The arguments of one tier's encoder: ffmpeg's test pattern at the tier's size and frame rate and its tone, encoded to HEVC with a keyframe each second +// and to Opus, and written as fragmented MP4 one frame to a fragment, which keeps the delay a viewer sees to one frame. +function encoderArguments(tier: TierStream['tier']): string[] { + const fragment = Math.round(1000000 / tier.frameRate) + const rate = tier.frameRate + + return [ + `-hide_banner -loglevel error -re -f lavfi -i testsrc2=size=${tier.width}x${tier.height}:rate=${rate}`, + '-re -f lavfi -i sine=frequency=440:sample_rate=48000', + `-map 0:v:0 -c:v libx265 -preset ultrafast -tune zerolatency -forced-idr 1 -x265-params keyint=${rate}:min-keyint=${rate}:scenecut=0:log-level=error`, + `-b:v ${tier.bitrate}k -maxrate ${tier.peakBitrate}k -bufsize ${tier.peakBitrate}k`, + '-map 1:a:0 -c:a libopus -application lowdelay -frame_duration 20 -ar 48000 -ac 1 -b:a 24000', + `-f mp4 -movflags empty_moov+default_base_moof -frag_duration ${fragment} pipe:1`, + ].join(' ').split(' ') +} + +// Whether the program's own stop has begun, from which on an encoder's exit is the stop's doing and fails no tier. +let stopping = false + +// A tier's encoder runs from its demand's start to its end: the library kills the registered process where the demand ends, whichever way it ends. An +// encoder that cannot start or that ends by itself fails its tier, and the exit the library's own kill brings reaches a stream already ended, which ignores it. +// An interrupt typed at a terminal reaches the encoder as well as the program, and the encoder's exit can come before the library has ended its stream, +// which is why an exit fails no tier once the program's own stop has begun. +function tierDemandStarted(stream: TierStream): void { + const encoder = stream.use(spawn('ffmpeg', encoderArguments(stream.tier), { + stdio: ['ignore', 'pipe', 'pipe'], + })) + + encoder.on('error', (error: Error) => stream.fail(error.message)) + encoder.on('exit', (code, signal) => { + if (!stopping) { + stream.fail(`The tier's encoder ended with ${signal ?? `code ${code}`}.`) + } + }) + encoder.stdout.on('data', (chunk: Buffer) => stream.write(chunk)) + // The encoder's own errors are printed as they come, until the program's stop has begun: an encoder the interrupt has reached is ending as the + // library's kill arrives, and it reports that second signal as a run of errors. + encoder.stderr.on('data', (chunk: Buffer) => { + if (!stopping) { + process.stderr.write(chunk) + } + }) +} + +// A snapshot is the newest keyframe decoded to a JPEG at the asked size where the library hands one, and the test pattern at that size where it does not. +async function snapshot({ height, keyframe, width }: CameraSnapshotRequest, signal: AbortSignal): Promise { + const input = keyframe + ? `-i pipe:0 -frames:v 1 -s ${width}x${height}` + : `-f lavfi -i testsrc2=size=${width}x${height} -frames:v 1` + // The child is started with the signal, and an abort ends it with an error, which the wait on its close takes as its rejection. + const ffmpeg = spawn('ffmpeg', `-hide_banner -loglevel error ${input} -f mjpeg pipe:1`.split(' '), { + signal, + stdio: ['pipe', 'pipe', 'inherit'], + }) + const chunks: Buffer[] = [] + + ffmpeg.stdout.on('data', (chunk: Buffer) => chunks.push(chunk)) + // An abort can fail a write still going to the child's input, and an error there ends the process unless a listener hears it. + ffmpeg.stdin.on('error', () => undefined) + ffmpeg.stdin.end(keyframe?.movie) + + const [code] = await once(ffmpeg, 'close') + const picture = Buffer.concat(chunks) + + if ((code !== 0) || (picture.length === 0)) { + throw new Error(`The snapshot's ffmpeg exited with code ${code} without a picture.`) + } + + return picture +} + +async function main(): Promise { + // ffmpeg and the encoders the tiers need are checked before anything is built, which means a missing one ends the program with nothing published and + // nothing stored. + const listing = spawnSync('ffmpeg', ['-hide_banner', '-encoders']) + + if ((listing.status !== 0) || !['libx265', 'libopus'].every(encoder => listing.stdout.includes(encoder))) { + console.error('The example camera needs ffmpeg on the PATH with the libx265 and libopus encoders.') + process.exitCode = 1 + + return + } + + const accessory = new Accessory('Modern Camera', uuid.generate('hap-nodejs:accessories:modern-camera')) + + // The subscription comes before the controller is configured, which means it hears a problem the camera's restore of its saved state raises. + onCameraProblem(accessory.UUID, (problem) => { + if (problem.level === 'error') { + console.error(problem.sentence) + } else { + console.warn(problem.sentence) + } + }) + + const camera = new CameraController({ + cameraCapabilities: { + snapshot, + streaming: { + delegate: { tierDemandStarted }, + }, + videoSensors: [ + { + audio: { bitrate: 24 }, + dimensions: { height: 1080, width: 1920 }, + intent: CameraSensorIntent.MAIN, + tiers: [ + { + bitrate: 1700, + frameRate: 30, + height: 1080, + id: 1, + quality: CameraVideoQuality.HIGH, + width: 1920, + }, + { + bitrate: 768, + frameRate: 30, + height: 720, + id: 2, + quality: CameraVideoQuality.MEDIUM, + width: 1280, + }, + { + bitrate: 180, + frameRate: 15, + height: 360, + id: 3, + quality: CameraVideoQuality.LOW, + width: 640, + }, + ], + uuid: uuid.generate('hap-nodejs:accessories:modern-camera:sensor'), + }, + ], + }, + sensors: { motion: true }, + }) + + accessory.configureController(camera) + + // The switch stands in for a camera's own motion detection: turning it on reports motion, which a home hub records while the camera's recording is on, + // and turning it off clears it. + accessory.addService(Service.Switch, 'Motion Trigger') + .getCharacteristic(Characteristic.On) + .onSet(value => camera.updateMotionDetected(value === true)) + + // Unpublishing keeps the pairing, where destroying the accessory would remove it, and the process ends once the camera's servers and encoders have closed. + // The handler is registered for one interrupt, which means a second one ends the process straight away. It marks the stop as begun before it + // unpublishes, since the interrupt may have reached the encoders too. + process.once('SIGINT', () => { + stopping = true + void accessory.unpublish() + }) + + await accessory.publish({ category: Categories.CAMERA, pincode: PINCODE, username: 'C2:5E:7A:31:94:D8' }) + console.log(`${accessory.displayName} is published. Add it in the Home app with the setup code ${PINCODE}.`) +} + +// A failure of the start is left unhandled, which ends the process with its stack. +void main()