@kubohiroya/turbowarp-camera-calibration 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,304 @@
1
+ import {distortionModelForCoefficientCount} from './profile.js';
2
+ import type {
3
+ CalibrationBackendFactory,
4
+ CalibrationBackendPort,
5
+ CalibrationBoard,
6
+ CalibrationCorner,
7
+ CalibrationFrame,
8
+ CalibrationSample,
9
+ CalibrationSolveResult
10
+ } from './types.js';
11
+
12
+ /**
13
+ * The single pinned production solver. The version is part of the identifier so
14
+ * that a project can record which build produced a profile.
15
+ */
16
+ export const OPENCV_BACKEND_NAME = 'opencv-js-wasm-4.12.0';
17
+
18
+ interface CvMat {
19
+ readonly rows: number;
20
+ readonly cols: number;
21
+ readonly data32F: Float32Array;
22
+ readonly data64F: Float64Array;
23
+ doubleAt(row: number, column: number): number;
24
+ delete(): void;
25
+ }
26
+
27
+ interface CvMatConstructor {
28
+ new (): CvMat;
29
+ eye(rows: number, columns: number, type: number): CvMat;
30
+ zeros(rows: number, columns: number, type: number): CvMat;
31
+ }
32
+
33
+ interface CvMatVector {
34
+ push_back(value: CvMat): void;
35
+ get(index: number): CvMat;
36
+ delete(): void;
37
+ }
38
+
39
+ interface CvApi {
40
+ Mat: CvMatConstructor;
41
+ MatVector: new () => CvMatVector;
42
+ Size: new (width: number, height: number) => unknown;
43
+ CV_32FC2: number;
44
+ CV_32FC3: number;
45
+ CV_64F: number;
46
+ COLOR_RGBA2GRAY: number;
47
+ CALIB_CB_ADAPTIVE_THRESH: number;
48
+ CALIB_CB_NORMALIZE_IMAGE: number;
49
+ TermCriteria_EPS: number;
50
+ TermCriteria_MAX_ITER: number;
51
+ TermCriteria: new (type: number, maxCount: number, epsilon: number) => unknown;
52
+ imread(source: HTMLCanvasElement): CvMat;
53
+ cvtColor(source: CvMat, destination: CvMat, code: number): void;
54
+ findChessboardCorners(
55
+ image: CvMat,
56
+ patternSize: unknown,
57
+ corners: CvMat,
58
+ flags: number
59
+ ): boolean;
60
+ cornerSubPix(
61
+ image: CvMat,
62
+ corners: CvMat,
63
+ window: unknown,
64
+ zeroZone: unknown,
65
+ criteria: unknown
66
+ ): void;
67
+ Laplacian(source: CvMat, destination: CvMat, depth: number): void;
68
+ meanStdDev(source: CvMat, mean: CvMat, standardDeviation: CvMat): void;
69
+ matFromArray(
70
+ rows: number,
71
+ columns: number,
72
+ type: number,
73
+ values: readonly number[]
74
+ ): CvMat;
75
+ calibrateCamera(
76
+ objectPoints: CvMatVector,
77
+ imagePoints: CvMatVector,
78
+ imageSize: unknown,
79
+ cameraMatrix: CvMat,
80
+ distortionCoefficients: CvMat,
81
+ rotationVectors: CvMatVector,
82
+ translationVectors: CvMatVector
83
+ ): number;
84
+ getBuildInformation(): string;
85
+ }
86
+
87
+ let openCvPromise: Promise<CvApi> | undefined;
88
+
89
+ /**
90
+ * Detects the chessboard and solves the camera intrinsics with OpenCV.
91
+ *
92
+ * The per-view rotation and translation OpenCV also produces are deliberately
93
+ * discarded. They describe where the board happened to sit during calibration,
94
+ * not where the camera stands, and this extension publishes intrinsics only.
95
+ */
96
+ export class OpenCvChessboardCalibrationBackend implements CalibrationBackendPort {
97
+ public readonly name = OPENCV_BACKEND_NAME;
98
+
99
+ public async captureSample(
100
+ frame: CalibrationFrame,
101
+ board: CalibrationBoard
102
+ ): Promise<CalibrationSample | undefined> {
103
+ const cv = await getOpenCv();
104
+ const canvas = document.createElement('canvas');
105
+ canvas.width = frame.width;
106
+ canvas.height = frame.height;
107
+ const context = canvas.getContext('2d', {willReadFrequently: true});
108
+ if (!context) throw new Error('A 2D canvas context is unavailable.');
109
+ context.drawImage(frame.element, 0, 0, frame.width, frame.height);
110
+
111
+ const source = cv.imread(canvas);
112
+ const gray = new cv.Mat();
113
+ const corners = new cv.Mat();
114
+ const laplacian = new cv.Mat();
115
+ const mean = new cv.Mat();
116
+ const standardDeviation = new cv.Mat();
117
+ try {
118
+ cv.cvtColor(source, gray, cv.COLOR_RGBA2GRAY);
119
+ const found = cv.findChessboardCorners(
120
+ gray,
121
+ new cv.Size(board.columns, board.rows),
122
+ corners,
123
+ cv.CALIB_CB_ADAPTIVE_THRESH | cv.CALIB_CB_NORMALIZE_IMAGE
124
+ );
125
+ if (!found) return undefined;
126
+ cv.cornerSubPix(
127
+ gray,
128
+ corners,
129
+ new cv.Size(11, 11),
130
+ new cv.Size(-1, -1),
131
+ new cv.TermCriteria(cv.TermCriteria_EPS | cv.TermCriteria_MAX_ITER, 30, 0.01)
132
+ );
133
+ const points = readPointPairs(corners.data32F);
134
+ cv.Laplacian(gray, laplacian, cv.CV_64F);
135
+ cv.meanStdDev(laplacian, mean, standardDeviation);
136
+ const sharpness = standardDeviation.doubleAt(0, 0) ** 2;
137
+ const coverage = boardCoverage(points, frame.width, frame.height);
138
+ const quality = clamp01(
139
+ 0.7 * Math.min(1, coverage / 0.25) + 0.3 * Math.min(1, sharpness / 100)
140
+ );
141
+ return {corners: points, quality, coverage, sharpness};
142
+ } finally {
143
+ standardDeviation.delete();
144
+ mean.delete();
145
+ laplacian.delete();
146
+ corners.delete();
147
+ gray.delete();
148
+ source.delete();
149
+ canvas.width = 0;
150
+ canvas.height = 0;
151
+ }
152
+ }
153
+
154
+ public async solve(
155
+ samples: readonly CalibrationSample[],
156
+ board: CalibrationBoard,
157
+ imageWidth: number,
158
+ imageHeight: number
159
+ ): Promise<CalibrationSolveResult> {
160
+ const cv = await getOpenCv();
161
+ const objectPoints = new cv.MatVector();
162
+ const imagePoints = new cv.MatVector();
163
+ const rotationVectors = new cv.MatVector();
164
+ const translationVectors = new cv.MatVector();
165
+ const cameraMatrix = cv.Mat.eye(3, 3, cv.CV_64F);
166
+ const distortionCoefficients = cv.Mat.zeros(8, 1, cv.CV_64F);
167
+ const retainedMats: CvMat[] = [];
168
+ try {
169
+ const worldPoints = chessboardWorldPoints(board);
170
+ for (const sample of samples) {
171
+ const objectPoint = cv.matFromArray(
172
+ sample.corners.length,
173
+ 1,
174
+ cv.CV_32FC3,
175
+ worldPoints
176
+ );
177
+ const imagePoint = cv.matFromArray(
178
+ sample.corners.length,
179
+ 1,
180
+ cv.CV_32FC2,
181
+ sample.corners.flatMap(({x, y}) => [x, y])
182
+ );
183
+ retainedMats.push(objectPoint, imagePoint);
184
+ objectPoints.push_back(objectPoint);
185
+ imagePoints.push_back(imagePoint);
186
+ }
187
+ const reprojectionErrorPx = cv.calibrateCamera(
188
+ objectPoints,
189
+ imagePoints,
190
+ new cv.Size(imageWidth, imageHeight),
191
+ cameraMatrix,
192
+ distortionCoefficients,
193
+ rotationVectors,
194
+ translationVectors
195
+ );
196
+ // OpenCV resizes the coefficient matrix to the model it actually fitted,
197
+ // so the returned length identifies the distortion model.
198
+ const coefficientCount = distortionCoefficients.rows * distortionCoefficients.cols;
199
+ return {
200
+ intrinsicMatrix: readMatrix(cameraMatrix, 9),
201
+ distortionModel: distortionModelForCoefficientCount(coefficientCount),
202
+ distortionCoefficients: readMatrix(distortionCoefficients, coefficientCount),
203
+ reprojectionErrorPx
204
+ };
205
+ } finally {
206
+ for (const matrix of retainedMats) matrix.delete();
207
+ distortionCoefficients.delete();
208
+ cameraMatrix.delete();
209
+ translationVectors.delete();
210
+ rotationVectors.delete();
211
+ imagePoints.delete();
212
+ objectPoints.delete();
213
+ }
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Names the solver without constructing it, so that reading the backend
219
+ * reporter — or loading the extension at all — never initializes the OpenCV
220
+ * WebAssembly runtime.
221
+ */
222
+ export const openCvBackendFactory: CalibrationBackendFactory = {
223
+ name: OPENCV_BACKEND_NAME,
224
+ async create(): Promise<CalibrationBackendPort> {
225
+ return new OpenCvChessboardCalibrationBackend();
226
+ }
227
+ };
228
+
229
+ function getOpenCv(): Promise<CvApi> {
230
+ openCvPromise ??= initializeOpenCv();
231
+ return openCvPromise;
232
+ }
233
+
234
+ async function initializeOpenCv(): Promise<CvApi> {
235
+ const importedOpenCv = await import('@techstark/opencv-js');
236
+ const imported = importedOpenCv as unknown as {default?: unknown; then?: unknown};
237
+ const candidate = imported.default ?? imported;
238
+ const resolved = isThenable(candidate) ? await candidate : candidate;
239
+ if (!isCvApi(resolved)) {
240
+ throw new Error('The pinned OpenCV.js WASM module did not initialize.');
241
+ }
242
+ return resolved;
243
+ }
244
+
245
+ function isThenable(value: unknown): value is Promise<unknown> {
246
+ return (
247
+ typeof value === 'object' &&
248
+ value !== null &&
249
+ 'then' in value &&
250
+ typeof value.then === 'function'
251
+ );
252
+ }
253
+
254
+ function isCvApi(value: unknown): value is CvApi {
255
+ return (
256
+ typeof value === 'object' &&
257
+ value !== null &&
258
+ 'getBuildInformation' in value &&
259
+ typeof (value as {getBuildInformation: unknown}).getBuildInformation === 'function'
260
+ );
261
+ }
262
+
263
+ function readPointPairs(values: Float32Array): CalibrationCorner[] {
264
+ const result: CalibrationCorner[] = [];
265
+ for (let index = 0; index + 1 < values.length; index += 2) {
266
+ result.push({x: values[index] ?? 0, y: values[index + 1] ?? 0});
267
+ }
268
+ return result;
269
+ }
270
+
271
+ function boardCoverage(
272
+ points: readonly CalibrationCorner[],
273
+ width: number,
274
+ height: number
275
+ ): number {
276
+ const xs = points.map(({x}) => x);
277
+ const ys = points.map(({y}) => y);
278
+ return (
279
+ ((Math.max(...xs) - Math.min(...xs)) * (Math.max(...ys) - Math.min(...ys))) /
280
+ (width * height)
281
+ );
282
+ }
283
+
284
+ function chessboardWorldPoints(board: CalibrationBoard): number[] {
285
+ const points: number[] = [];
286
+ for (let row = 0; row < board.rows; row += 1) {
287
+ for (let column = 0; column < board.columns; column += 1) {
288
+ points.push(column * board.squareSizeMeters, row * board.squareSizeMeters, 0);
289
+ }
290
+ }
291
+ return points;
292
+ }
293
+
294
+ function readMatrix(matrix: CvMat, expected: number): number[] {
295
+ const values = Array.from(matrix.data64F.slice(0, expected));
296
+ if (values.length !== expected || values.some((value) => !Number.isFinite(value))) {
297
+ throw new Error(`OpenCV returned an invalid ${expected}-element matrix.`);
298
+ }
299
+ return values;
300
+ }
301
+
302
+ function clamp01(value: number): number {
303
+ return Math.min(1, Math.max(0, value));
304
+ }
@@ -0,0 +1,356 @@
1
+ import {DISTORTION_COEFFICIENT_COUNTS, type DistortionModel} from './types.js';
2
+
3
+ /**
4
+ * The intrinsic calibration profile.
5
+ *
6
+ * Camera Source owns this contract; see
7
+ * https://github.com/kubohiroya/turbowarp-camera-source/issues/14. Until that
8
+ * contract ships, this module is the producer-side definition and the schema is
9
+ * published from this repository. The identifiers below are the migration
10
+ * surface: when Camera Source publishes the contract, only `schema` and the
11
+ * JSON Schema `$id` move.
12
+ *
13
+ * Intrinsics and external pose stay separate. A profile describes one camera's
14
+ * optics at one image size. It never carries a world pose, and importing a
15
+ * legacy profile that mixes the two drops the pose rather than reinterpreting
16
+ * it.
17
+ */
18
+ export const CAMERA_INTRINSICS_SCHEMA_ID = 'camerasource/camera-intrinsics';
19
+ export const CAMERA_INTRINSICS_VERSION = 1;
20
+
21
+ /** The pre-migration profile, which mixed intrinsics with a world pose. */
22
+ export const LEGACY_CALIBRATION_SCHEMA_ID = 'twrmc/camera-calibration';
23
+
24
+ export type CameraModel = 'pinhole';
25
+
26
+ /**
27
+ * Whether the pixels the profile describes are the raw sensor image or an
28
+ * already-undistorted image. The base contract is an uncorrected image plus
29
+ * calibration values; `undistorted` states that a consumer must not apply the
30
+ * coefficients again.
31
+ */
32
+ export type ImageState = 'raw' | 'undistorted';
33
+
34
+ export interface CalibrationQuality {
35
+ sampleCount: number;
36
+ reprojectionErrorPx: number;
37
+ }
38
+
39
+ export interface CameraIntrinsicsV1 {
40
+ schema: typeof CAMERA_INTRINSICS_SCHEMA_ID;
41
+ version: typeof CAMERA_INTRINSICS_VERSION;
42
+ calibrationId: string;
43
+ cameraId: string;
44
+ cameraModel: CameraModel;
45
+ imageWidth: number;
46
+ imageHeight: number;
47
+ imageState: ImageState;
48
+ intrinsicMatrix: number[];
49
+ distortionModel: DistortionModel;
50
+ distortionCoefficients: number[];
51
+ /** Absent when the source of the profile did not measure it. */
52
+ quality?: CalibrationQuality;
53
+ calibratedAt: string;
54
+ }
55
+
56
+ export type CalibrationProfileErrorCode = 'invalid-calibration' | 'credential-forbidden';
57
+
58
+ export class CalibrationProfileError extends Error {
59
+ public constructor(
60
+ public readonly code: CalibrationProfileErrorCode,
61
+ message: string
62
+ ) {
63
+ super(message);
64
+ this.name = 'CalibrationProfileError';
65
+ }
66
+ }
67
+
68
+ /** Property names of the v1 profile, in the order the JSON Schema lists them. */
69
+ export const CAMERA_INTRINSICS_PROPERTIES = [
70
+ 'schema',
71
+ 'version',
72
+ 'calibrationId',
73
+ 'cameraId',
74
+ 'cameraModel',
75
+ 'imageWidth',
76
+ 'imageHeight',
77
+ 'imageState',
78
+ 'intrinsicMatrix',
79
+ 'distortionModel',
80
+ 'distortionCoefficients',
81
+ 'quality',
82
+ 'calibratedAt'
83
+ ] as const;
84
+
85
+ /** Every property except `quality`, which is absent when it was not measured. */
86
+ export const CAMERA_INTRINSICS_REQUIRED = CAMERA_INTRINSICS_PROPERTIES.filter(
87
+ (name) => name !== 'quality'
88
+ );
89
+
90
+ export const CAMERA_MODELS: readonly CameraModel[] = ['pinhole'];
91
+ export const IMAGE_STATES: readonly ImageState[] = ['raw', 'undistorted'];
92
+ export const DISTORTION_MODELS = Object.keys(
93
+ DISTORTION_COEFFICIENT_COUNTS
94
+ ) as readonly DistortionModel[];
95
+
96
+ const IDENTIFIER = /^[A-Za-z0-9._-]{1,64}$/u;
97
+ const UTC_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u;
98
+ const MAXIMUM_IMAGE_SIZE = 16_384;
99
+ const MAXIMUM_MAGNITUDE = 1_000_000;
100
+ const CREDENTIAL_KEY =
101
+ /^(?:offer|answer|sdp|icecandidate|icecandidates|icepwd|iceufrag|dtlsfingerprint|credential|credentials)$/u;
102
+
103
+ /**
104
+ * Parses a calibration profile. Accepts the v1 intrinsic contract and the
105
+ * pre-migration profile, and never returns a partially validated object: the
106
+ * caller may replace state only once this resolves.
107
+ */
108
+ export function parseCalibrationProfile(json: string): CameraIntrinsicsV1 {
109
+ let value: unknown;
110
+ try {
111
+ value = JSON.parse(json);
112
+ } catch (error) {
113
+ throw new CalibrationProfileError('invalid-calibration', String(error));
114
+ }
115
+ const credentialPath = findPairingCredential(value);
116
+ if (credentialPath) {
117
+ throw new CalibrationProfileError(
118
+ 'credential-forbidden',
119
+ `Pairing credential is forbidden at ${credentialPath}.`
120
+ );
121
+ }
122
+ const record = requireRecord(value, '/');
123
+ if (record.schema === LEGACY_CALIBRATION_SCHEMA_ID) {
124
+ return parseLegacyProfile(record);
125
+ }
126
+ return parseIntrinsicsProfile(record);
127
+ }
128
+
129
+ /** Validates a value this extension just produced, before it becomes state. */
130
+ export function assertCameraIntrinsics(value: unknown): CameraIntrinsicsV1 {
131
+ return parseIntrinsicsProfile(requireRecord(value, '/'));
132
+ }
133
+
134
+ /** Reports the distortion model OpenCV implied by returning `count` values. */
135
+ export function distortionModelForCoefficientCount(count: number): DistortionModel {
136
+ for (const [model, counts] of Object.entries(DISTORTION_COEFFICIENT_COUNTS)) {
137
+ if (counts.includes(count)) return model as DistortionModel;
138
+ }
139
+ throw new Error(`No distortion model uses ${count} coefficients.`);
140
+ }
141
+
142
+ function parseIntrinsicsProfile(record: Record<string, unknown>): CameraIntrinsicsV1 {
143
+ for (const key of Object.keys(record)) {
144
+ if (!(CAMERA_INTRINSICS_PROPERTIES as readonly string[]).includes(key)) {
145
+ throw invalid(`/${key}`, 'is not part of the v1 intrinsic profile');
146
+ }
147
+ }
148
+ literal(record.schema, CAMERA_INTRINSICS_SCHEMA_ID, '/schema');
149
+ literal(record.version, CAMERA_INTRINSICS_VERSION, '/version');
150
+ const calibrationId = identifier(record.calibrationId, '/calibrationId');
151
+ const cameraId = identifier(record.cameraId, '/cameraId');
152
+ const cameraModel = member(record.cameraModel, CAMERA_MODELS, '/cameraModel');
153
+ const imageWidth = imageSize(record.imageWidth, '/imageWidth');
154
+ const imageHeight = imageSize(record.imageHeight, '/imageHeight');
155
+ const imageState = member(record.imageState, IMAGE_STATES, '/imageState');
156
+ const intrinsicMatrix = parseIntrinsicMatrix(record.intrinsicMatrix, imageWidth, imageHeight);
157
+ const distortionModel = member(record.distortionModel, DISTORTION_MODELS, '/distortionModel');
158
+ const distortionCoefficients = parseDistortionCoefficients(
159
+ record.distortionCoefficients,
160
+ distortionModel
161
+ );
162
+ const calibratedAt = utcDateTime(record.calibratedAt, '/calibratedAt');
163
+ const quality = record.quality === undefined ? undefined : parseQuality(record.quality);
164
+ const profile: CameraIntrinsicsV1 = {
165
+ schema: CAMERA_INTRINSICS_SCHEMA_ID,
166
+ version: CAMERA_INTRINSICS_VERSION,
167
+ calibrationId,
168
+ cameraId,
169
+ cameraModel,
170
+ imageWidth,
171
+ imageHeight,
172
+ imageState,
173
+ intrinsicMatrix,
174
+ distortionModel,
175
+ distortionCoefficients,
176
+ calibratedAt
177
+ };
178
+ return quality === undefined ? profile : {...profile, quality};
179
+ }
180
+
181
+ /**
182
+ * Reads the pre-migration profile. `worldFromCameraMatrix` is validated as part
183
+ * of that profile but is not carried over: this extension publishes intrinsics
184
+ * only, and a missing pose is never filled in with identity.
185
+ */
186
+ function parseLegacyProfile(record: Record<string, unknown>): CameraIntrinsicsV1 {
187
+ literal(record.version, 1, '/version');
188
+ const calibrationId = identifier(record.calibrationId, '/calibrationId');
189
+ const cameraId = identifier(record.cameraId, '/cameraId');
190
+ const imageWidth = imageSize(record.imageWidth, '/imageWidth');
191
+ const imageHeight = imageSize(record.imageHeight, '/imageHeight');
192
+ const intrinsicMatrix = parseIntrinsicMatrix(record.intrinsicMatrix, imageWidth, imageHeight);
193
+ const coefficients = numberArray(record.distortionCoefficients, '/distortionCoefficients');
194
+ let distortionModel: DistortionModel;
195
+ try {
196
+ distortionModel = distortionModelForCoefficientCount(coefficients.length);
197
+ } catch {
198
+ throw invalid('/distortionCoefficients', 'has no matching OpenCV distortion model');
199
+ }
200
+ literal(record.worldUnit, 'meter', '/worldUnit');
201
+ const calibratedAt = utcDateTime(record.calibratedAt, '/calibratedAt');
202
+ // The legacy profile stated no capture state and no solve quality. Both stay
203
+ // unstated rather than guessed: `raw` is the contract's base case.
204
+ return {
205
+ schema: CAMERA_INTRINSICS_SCHEMA_ID,
206
+ version: CAMERA_INTRINSICS_VERSION,
207
+ calibrationId,
208
+ cameraId,
209
+ cameraModel: 'pinhole',
210
+ imageWidth,
211
+ imageHeight,
212
+ imageState: 'raw',
213
+ intrinsicMatrix,
214
+ distortionModel,
215
+ distortionCoefficients: coefficients,
216
+ calibratedAt
217
+ };
218
+ }
219
+
220
+ function parseIntrinsicMatrix(value: unknown, width: number, height: number): number[] {
221
+ const matrix = numberArray(value, '/intrinsicMatrix');
222
+ if (matrix.length !== 9) {
223
+ throw invalid('/intrinsicMatrix', 'must hold nine row-major values');
224
+ }
225
+ const [fx, skew, cx, zeroX, fy, cy, zeroZ, zeroY, one] = matrix as [
226
+ number,
227
+ number,
228
+ number,
229
+ number,
230
+ number,
231
+ number,
232
+ number,
233
+ number,
234
+ number
235
+ ];
236
+ if (skew !== 0 || zeroX !== 0 || zeroZ !== 0 || zeroY !== 0 || one !== 1) {
237
+ throw invalid('/intrinsicMatrix', 'must be a zero-skew pinhole matrix');
238
+ }
239
+ if (fx <= 0 || fy <= 0) {
240
+ throw invalid('/intrinsicMatrix', 'must hold positive focal lengths');
241
+ }
242
+ if (cx < 0 || cx > width || cy < 0 || cy > height) {
243
+ throw invalid('/intrinsicMatrix', 'principal point must fall inside the calibrated image');
244
+ }
245
+ return matrix;
246
+ }
247
+
248
+ function parseDistortionCoefficients(value: unknown, model: DistortionModel): number[] {
249
+ const coefficients = numberArray(value, '/distortionCoefficients');
250
+ const allowed = DISTORTION_COEFFICIENT_COUNTS[model];
251
+ if (!allowed.includes(coefficients.length)) {
252
+ throw invalid(
253
+ '/distortionCoefficients',
254
+ `must hold ${allowed.join(' or ')} values for ${model}`
255
+ );
256
+ }
257
+ return coefficients;
258
+ }
259
+
260
+ function parseQuality(value: unknown): CalibrationQuality {
261
+ const record = requireRecord(value, '/quality');
262
+ for (const key of Object.keys(record)) {
263
+ if (key !== 'sampleCount' && key !== 'reprojectionErrorPx') {
264
+ throw invalid(`/quality/${key}`, 'is not part of the v1 quality record');
265
+ }
266
+ }
267
+ const sampleCount = record.sampleCount;
268
+ if (!Number.isInteger(sampleCount) || (sampleCount as number) < 0) {
269
+ throw invalid('/quality/sampleCount', 'must be a non-negative integer');
270
+ }
271
+ const reprojectionErrorPx = boundedNumber(
272
+ record.reprojectionErrorPx,
273
+ '/quality/reprojectionErrorPx'
274
+ );
275
+ if (reprojectionErrorPx < 0) {
276
+ throw invalid('/quality/reprojectionErrorPx', 'must not be negative');
277
+ }
278
+ return {sampleCount: sampleCount as number, reprojectionErrorPx};
279
+ }
280
+
281
+ function findPairingCredential(value: unknown, path = ''): string | undefined {
282
+ if (Array.isArray(value)) {
283
+ for (const [index, item] of value.entries()) {
284
+ const found = findPairingCredential(item, `${path}/${index}`);
285
+ if (found) return found;
286
+ }
287
+ return undefined;
288
+ }
289
+ if (typeof value !== 'object' || value === null) return undefined;
290
+ for (const [key, item] of Object.entries(value)) {
291
+ const itemPath = `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`;
292
+ if (CREDENTIAL_KEY.test(key.toLowerCase().replaceAll(/[^a-z]/gu, ''))) return itemPath;
293
+ const found = findPairingCredential(item, itemPath);
294
+ if (found) return found;
295
+ }
296
+ return undefined;
297
+ }
298
+
299
+ function requireRecord(value: unknown, path: string): Record<string, unknown> {
300
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
301
+ throw invalid(path, 'must be an object');
302
+ }
303
+ return value as Record<string, unknown>;
304
+ }
305
+
306
+ function literal(value: unknown, expected: string | number, path: string): void {
307
+ if (value !== expected) throw invalid(path, `must be ${JSON.stringify(expected)}`);
308
+ }
309
+
310
+ function member<T extends string>(value: unknown, allowed: readonly T[], path: string): T {
311
+ if (typeof value !== 'string' || !(allowed as readonly string[]).includes(value)) {
312
+ throw invalid(path, `must be one of ${allowed.join(', ')}`);
313
+ }
314
+ return value as T;
315
+ }
316
+
317
+ function identifier(value: unknown, path: string): string {
318
+ if (typeof value !== 'string' || !IDENTIFIER.test(value)) {
319
+ throw invalid(path, 'must be 1 to 64 characters of A-Z a-z 0-9 . _ -');
320
+ }
321
+ return value;
322
+ }
323
+
324
+ function imageSize(value: unknown, path: string): number {
325
+ if (!Number.isInteger(value) || (value as number) < 1 || (value as number) > MAXIMUM_IMAGE_SIZE) {
326
+ throw invalid(path, `must be an integer from 1 to ${MAXIMUM_IMAGE_SIZE}`);
327
+ }
328
+ return value as number;
329
+ }
330
+
331
+ function boundedNumber(value: unknown, path: string): number {
332
+ if (
333
+ typeof value !== 'number' ||
334
+ !Number.isFinite(value) ||
335
+ Math.abs(value) > MAXIMUM_MAGNITUDE
336
+ ) {
337
+ throw invalid(path, `must be a finite number within ${MAXIMUM_MAGNITUDE}`);
338
+ }
339
+ return value;
340
+ }
341
+
342
+ function numberArray(value: unknown, path: string): number[] {
343
+ if (!Array.isArray(value)) throw invalid(path, 'must be an array of numbers');
344
+ return value.map((item, index) => boundedNumber(item, `${path}/${index}`));
345
+ }
346
+
347
+ function invalid(path: string, reason: string): CalibrationProfileError {
348
+ return new CalibrationProfileError('invalid-calibration', `${path}: ${reason}.`);
349
+ }
350
+
351
+ function utcDateTime(value: unknown, path: string): string {
352
+ if (typeof value !== 'string' || !UTC_DATE_TIME.test(value)) {
353
+ throw invalid(path, 'must be a UTC ISO 8601 timestamp');
354
+ }
355
+ return value;
356
+ }