@kubohiroya/turbowarp-camera-source 0.16.0 → 0.17.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,479 @@
1
+ export const CAMERA_INTRINSIC_PROFILE_SCHEMA = 'twcs/camera-intrinsics';
2
+ export const CAMERA_INTRINSIC_PROFILE_VERSION = 1;
3
+ /** The application-specific format this contract replaces. Read for migration, never written. */
4
+ export const LEGACY_CALIBRATION_SCHEMA = 'twrmc/camera-calibration';
5
+ const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
6
+ const UTC_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$/;
7
+ const MAXIMUM_IMAGE_EDGE = 16_384;
8
+ const MAXIMUM_PIXEL_MAGNITUDE = 1e7;
9
+ const MAXIMUM_DISTORTION_MAGNITUDE = 1e4;
10
+ const MAXIMUM_SAMPLE_COUNT = 10_000;
11
+ const MAXIMUM_REPROJECTION_ERROR_PX = 1e4;
12
+ const MAXIMUM_TEXT_LENGTH = 256;
13
+ const MAXIMUM_FRAME_RATE = 1000;
14
+ const MAXIMUM_ZOOM = 1000;
15
+ const MAXIMUM_FOCUS_DISTANCE = 1e4;
16
+ const MAXIMUM_SCAN_DEPTH = 16;
17
+ const AFFINE_ROW_TOLERANCE = 1e-6;
18
+ const DISTORTION_MODELS = ['none', 'brown-conrady', 'kannala-brandt'];
19
+ const RESIZE_MODES = ['none', 'crop-and-scale'];
20
+ const FOCUS_MODES = ['none', 'manual', 'single-shot', 'continuous'];
21
+ /**
22
+ * Coefficient counts each model accepts.
23
+ *
24
+ * The Brown-Conrady lengths are the OpenCV sets that consumers already handle: four, the usual five
25
+ * with k3, and eight for the rational model. Longer OpenCV vectors (thin prism, tilted sensor) are
26
+ * rejected rather than carried, because no consumer in this family implements them and a profile
27
+ * that is accepted but only partly applied is worse than one that is refused.
28
+ */
29
+ const DISTORTION_COEFFICIENT_LENGTHS = {
30
+ none: [0],
31
+ 'brown-conrady': [4, 5, 8],
32
+ 'kannala-brandt': [4]
33
+ };
34
+ /**
35
+ * Key names that carry pairing or authentication material.
36
+ *
37
+ * Signaling data is short-lived session state and a calibration profile is a document operators keep
38
+ * and copy between venues. Rejecting the whole document is deliberate: a profile that reached here
39
+ * carrying an SDP is evidence that something upstream is mixing the two, and quietly stripping the
40
+ * key would hide that.
41
+ */
42
+ const FORBIDDEN_KEYS = new Set([
43
+ 'accesstoken',
44
+ 'answer',
45
+ 'apikey',
46
+ 'authorization',
47
+ 'candidate',
48
+ 'credential',
49
+ 'credentials',
50
+ 'ice',
51
+ 'icecandidate',
52
+ 'offer',
53
+ 'passphrase',
54
+ 'password',
55
+ 'secret',
56
+ 'sdp',
57
+ 'token'
58
+ ]);
59
+ class ProfileRejection extends Error {
60
+ detail;
61
+ constructor(detail) {
62
+ super(detail.message);
63
+ this.name = 'ProfileRejection';
64
+ this.detail = detail;
65
+ }
66
+ }
67
+ function reject(code, path, message) {
68
+ throw new ProfileRejection({ code, path, message });
69
+ }
70
+ function isRecord(value) {
71
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
72
+ }
73
+ function member(path, name) {
74
+ return path.length === 0 ? name : `${path}.${name}`;
75
+ }
76
+ /** Normalizes a key so `ICE-Candidate`, `iceCandidate` and `ice_candidate` all match one entry. */
77
+ function comparableKey(key) {
78
+ return key.toLowerCase().replace(/[^a-z0-9]/g, '');
79
+ }
80
+ function assertNoForbiddenKeys(value, path, depth, seen) {
81
+ if (depth > MAXIMUM_SCAN_DEPTH) {
82
+ reject('invalid-value', path, 'The document is nested more deeply than a profile ever is.');
83
+ }
84
+ if (typeof value !== 'object' || value === null)
85
+ return;
86
+ if (seen.has(value))
87
+ reject('invalid-value', path, 'The document contains a cycle.');
88
+ seen.add(value);
89
+ if (Array.isArray(value)) {
90
+ value.forEach((item, index) => assertNoForbiddenKeys(item, `${path}[${index}]`, depth + 1, seen));
91
+ return;
92
+ }
93
+ for (const [key, child] of Object.entries(value)) {
94
+ if (FORBIDDEN_KEYS.has(comparableKey(key))) {
95
+ reject('forbidden-field', member(path, key), 'Pairing and authentication material must not travel inside a calibration profile.');
96
+ }
97
+ assertNoForbiddenKeys(child, member(path, key), depth + 1, seen);
98
+ }
99
+ }
100
+ function requireRecord(value, path) {
101
+ if (!isRecord(value)) {
102
+ reject(path.length === 0 ? 'not-an-object' : 'invalid-type', path, 'Expected an object.');
103
+ }
104
+ return value;
105
+ }
106
+ /** Rejects unknown members as well as missing ones, so an unrecognized field is never ignored. */
107
+ function requireExactKeys(record, path, required, optional = []) {
108
+ const known = new Set([...required, ...optional]);
109
+ for (const key of Object.keys(record)) {
110
+ if (!known.has(key))
111
+ reject('unexpected-field', member(path, key), 'Unknown member.');
112
+ }
113
+ for (const key of required) {
114
+ if (!(key in record))
115
+ reject('missing-field', member(path, key), 'Required member is missing.');
116
+ }
117
+ }
118
+ function requireText(value, path) {
119
+ if (typeof value !== 'string')
120
+ reject('invalid-type', path, 'Expected a string.');
121
+ if (value.length === 0 || value.length > MAXIMUM_TEXT_LENGTH) {
122
+ reject('out-of-range', path, `Expected between 1 and ${MAXIMUM_TEXT_LENGTH} characters.`);
123
+ }
124
+ return value;
125
+ }
126
+ function requireIdentifier(value, path) {
127
+ const text = requireText(value, path);
128
+ if (!IDENTIFIER_PATTERN.test(text)) {
129
+ reject('invalid-value', path, 'Expected letters, digits, dot, underscore, colon or hyphen.');
130
+ }
131
+ return text;
132
+ }
133
+ function requireUtcTimestamp(value, path) {
134
+ const text = requireText(value, path);
135
+ if (!UTC_TIMESTAMP_PATTERN.test(text) || !Number.isFinite(Date.parse(text))) {
136
+ reject('invalid-value', path, 'Expected an RFC 3339 timestamp in UTC, such as 2026-09-15T04:05:06Z.');
137
+ }
138
+ return text;
139
+ }
140
+ function requireBoolean(value, path) {
141
+ if (typeof value !== 'boolean')
142
+ reject('invalid-type', path, 'Expected a boolean.');
143
+ return value;
144
+ }
145
+ function requireFinite(value, path) {
146
+ if (typeof value !== 'number')
147
+ reject('invalid-type', path, 'Expected a number.');
148
+ if (!Number.isFinite(value))
149
+ reject('invalid-value', path, 'Expected a finite number.');
150
+ return value;
151
+ }
152
+ function requireInteger(value, path, minimum, maximum) {
153
+ const numeric = requireFinite(value, path);
154
+ if (!Number.isInteger(numeric))
155
+ reject('invalid-value', path, 'Expected an integer.');
156
+ if (numeric < minimum || numeric > maximum) {
157
+ reject('out-of-range', path, `Expected between ${minimum} and ${maximum}.`);
158
+ }
159
+ return numeric;
160
+ }
161
+ function requireBounded(value, path, minimum, maximum) {
162
+ const numeric = requireFinite(value, path);
163
+ if (numeric < minimum || numeric > maximum) {
164
+ reject('out-of-range', path, `Expected between ${minimum} and ${maximum}.`);
165
+ }
166
+ return numeric;
167
+ }
168
+ function requireLiteral(value, path, expected, code) {
169
+ if (value !== expected)
170
+ reject(code, path, `Expected ${JSON.stringify(expected)}.`);
171
+ return expected;
172
+ }
173
+ function readImage(value, path) {
174
+ const record = requireRecord(value, path);
175
+ requireExactKeys(record, path, ['width', 'height', 'undistorted']);
176
+ return {
177
+ width: requireInteger(record['width'], member(path, 'width'), 1, MAXIMUM_IMAGE_EDGE),
178
+ height: requireInteger(record['height'], member(path, 'height'), 1, MAXIMUM_IMAGE_EDGE),
179
+ undistorted: requireBoolean(record['undistorted'], member(path, 'undistorted'))
180
+ };
181
+ }
182
+ /**
183
+ * Reads the pinhole parameters.
184
+ *
185
+ * The principal point is allowed to sit outside the frame — a cropped or shifted sensor puts it
186
+ * there legitimately — but not arbitrarily far, because a principal point far outside the image is
187
+ * the signature of values given in the wrong unit rather than of an unusual lens.
188
+ */
189
+ function readIntrinsics(value, path, image) {
190
+ const record = requireRecord(value, path);
191
+ requireExactKeys(record, path, ['fx', 'fy', 'cx', 'cy', 'skew']);
192
+ return {
193
+ fx: requireBounded(record['fx'], member(path, 'fx'), Number.MIN_VALUE, MAXIMUM_PIXEL_MAGNITUDE),
194
+ fy: requireBounded(record['fy'], member(path, 'fy'), Number.MIN_VALUE, MAXIMUM_PIXEL_MAGNITUDE),
195
+ cx: requireBounded(record['cx'], member(path, 'cx'), -image.width, image.width * 2),
196
+ cy: requireBounded(record['cy'], member(path, 'cy'), -image.height, image.height * 2),
197
+ skew: requireBounded(record['skew'], member(path, 'skew'), -MAXIMUM_PIXEL_MAGNITUDE, MAXIMUM_PIXEL_MAGNITUDE)
198
+ };
199
+ }
200
+ function readDistortion(value, path) {
201
+ const record = requireRecord(value, path);
202
+ requireExactKeys(record, path, ['model', 'coefficients']);
203
+ const modelPath = member(path, 'model');
204
+ const rawModel = record['model'];
205
+ if (typeof rawModel !== 'string' || !DISTORTION_MODELS.includes(rawModel)) {
206
+ reject('invalid-distortion', modelPath, `Expected one of ${DISTORTION_MODELS.join(', ')}.`);
207
+ }
208
+ const model = rawModel;
209
+ const coefficientsPath = member(path, 'coefficients');
210
+ const rawCoefficients = record['coefficients'];
211
+ if (!Array.isArray(rawCoefficients)) {
212
+ reject('invalid-type', coefficientsPath, 'Expected an array.');
213
+ }
214
+ const allowed = DISTORTION_COEFFICIENT_LENGTHS[model];
215
+ if (!allowed.includes(rawCoefficients.length)) {
216
+ reject('invalid-distortion', coefficientsPath, `The ${model} model takes ${allowed.join(' or ')} coefficients, not ${rawCoefficients.length}.`);
217
+ }
218
+ const coefficients = rawCoefficients.map((coefficient, index) => requireBounded(coefficient, `${coefficientsPath}[${index}]`, -MAXIMUM_DISTORTION_MAGNITUDE, MAXIMUM_DISTORTION_MAGNITUDE));
219
+ return { model, coefficients };
220
+ }
221
+ function requireEnum(value, path, allowed) {
222
+ const text = requireText(value, path);
223
+ if (!allowed.includes(text))
224
+ reject('invalid-value', path, `Expected one of ${allowed.join(', ')}.`);
225
+ return text;
226
+ }
227
+ function readCapture(value, path) {
228
+ const record = requireRecord(value, path);
229
+ requireExactKeys(record, path, [], ['frameRate', 'facingMode', 'resizeMode', 'zoom', 'focusMode', 'focusDistance']);
230
+ const read = (name, reader) => name in record ? reader(record[name], member(path, name)) : undefined;
231
+ const frameRate = read('frameRate', (raw, at) => requireBounded(raw, at, Number.MIN_VALUE, MAXIMUM_FRAME_RATE));
232
+ const facingMode = read('facingMode', requireText);
233
+ const resizeMode = read('resizeMode', (raw, at) => requireEnum(raw, at, RESIZE_MODES));
234
+ const zoom = read('zoom', (raw, at) => requireBounded(raw, at, Number.MIN_VALUE, MAXIMUM_ZOOM));
235
+ const focusMode = read('focusMode', (raw, at) => requireEnum(raw, at, FOCUS_MODES));
236
+ const focusDistance = read('focusDistance', (raw, at) => requireBounded(raw, at, 0, MAXIMUM_FOCUS_DISTANCE));
237
+ return {
238
+ ...(frameRate === undefined ? {} : { frameRate }),
239
+ ...(facingMode === undefined ? {} : { facingMode }),
240
+ ...(resizeMode === undefined ? {} : { resizeMode }),
241
+ ...(zoom === undefined ? {} : { zoom }),
242
+ ...(focusMode === undefined ? {} : { focusMode }),
243
+ ...(focusDistance === undefined ? {} : { focusDistance })
244
+ };
245
+ }
246
+ function readQuality(value, path) {
247
+ const record = requireRecord(value, path);
248
+ requireExactKeys(record, path, ['sampleCount', 'reprojectionErrorPx']);
249
+ return {
250
+ sampleCount: requireInteger(record['sampleCount'], member(path, 'sampleCount'), 1, MAXIMUM_SAMPLE_COUNT),
251
+ reprojectionErrorPx: requireBounded(record['reprojectionErrorPx'], member(path, 'reprojectionErrorPx'), 0, MAXIMUM_REPROJECTION_ERROR_PX)
252
+ };
253
+ }
254
+ function readDevice(value, path) {
255
+ const record = requireRecord(value, path);
256
+ requireExactKeys(record, path, [], ['label', 'deviceId']);
257
+ const label = 'label' in record ? requireText(record['label'], member(path, 'label')) : undefined;
258
+ const deviceId = 'deviceId' in record ? requireText(record['deviceId'], member(path, 'deviceId')) : undefined;
259
+ return {
260
+ ...(label === undefined ? {} : { label }),
261
+ ...(deviceId === undefined ? {} : { deviceId })
262
+ };
263
+ }
264
+ function readProfile(input) {
265
+ assertNoForbiddenKeys(input, '', 0, new WeakSet());
266
+ const record = requireRecord(input, '');
267
+ requireLiteral(record['schema'], 'schema', CAMERA_INTRINSIC_PROFILE_SCHEMA, 'unsupported-schema');
268
+ requireLiteral(record['version'], 'version', CAMERA_INTRINSIC_PROFILE_VERSION, 'unsupported-version');
269
+ requireExactKeys(record, '', [
270
+ 'schema',
271
+ 'version',
272
+ 'profileId',
273
+ 'cameraId',
274
+ 'calibratedAt',
275
+ 'producer',
276
+ 'cameraModel',
277
+ 'image',
278
+ 'intrinsics',
279
+ 'distortion'
280
+ ], ['capture', 'quality', 'device']);
281
+ const image = readImage(record['image'], 'image');
282
+ const distortion = readDistortion(record['distortion'], 'distortion');
283
+ if (image.undistorted && distortion.model !== 'none') {
284
+ reject('inconsistent-profile', 'distortion.model', 'A profile for an already undistorted image cannot also carry distortion coefficients.');
285
+ }
286
+ const capture = 'capture' in record ? readCapture(record['capture'], 'capture') : undefined;
287
+ const quality = 'quality' in record ? readQuality(record['quality'], 'quality') : undefined;
288
+ const device = 'device' in record ? readDevice(record['device'], 'device') : undefined;
289
+ return {
290
+ schema: CAMERA_INTRINSIC_PROFILE_SCHEMA,
291
+ version: CAMERA_INTRINSIC_PROFILE_VERSION,
292
+ profileId: requireIdentifier(record['profileId'], 'profileId'),
293
+ cameraId: requireIdentifier(record['cameraId'], 'cameraId'),
294
+ calibratedAt: requireUtcTimestamp(record['calibratedAt'], 'calibratedAt'),
295
+ producer: requireText(record['producer'], 'producer'),
296
+ cameraModel: requireLiteral(record['cameraModel'], 'cameraModel', 'pinhole', 'invalid-value'),
297
+ image,
298
+ intrinsics: readIntrinsics(record['intrinsics'], 'intrinsics', image),
299
+ distortion,
300
+ ...(capture === undefined ? {} : { capture }),
301
+ ...(quality === undefined ? {} : { quality }),
302
+ ...(device === undefined ? {} : { device })
303
+ };
304
+ }
305
+ function toResult(read) {
306
+ try {
307
+ return { ok: true, profile: read() };
308
+ }
309
+ catch (error) {
310
+ if (error instanceof ProfileRejection)
311
+ return { ok: false, error: error.detail };
312
+ throw error;
313
+ }
314
+ }
315
+ /**
316
+ * Reads whichever profile format a document is written in.
317
+ *
318
+ * An operator holding a file does not know, and should not have to know, which of two schemas it
319
+ * uses; they know they calibrated this camera once and kept the result. Dispatching on the document
320
+ * itself means one entry point accepts both, and the profile that comes out records where it came
321
+ * from in `producer`, so nothing about the conversion is hidden.
322
+ *
323
+ * Only the declared schema decides. A document that says nothing recognizable is refused by the
324
+ * current parser, which names what it expected.
325
+ */
326
+ export function readCameraProfileDocument(input) {
327
+ if (isRecord(input) && input['schema'] === LEGACY_CALIBRATION_SCHEMA) {
328
+ return adoptLegacyCameraCalibration(input);
329
+ }
330
+ return parseCameraIntrinsicProfile(input);
331
+ }
332
+ /** Validates a parsed document and returns a normalized profile, or the reason it was refused. */
333
+ export function parseCameraIntrinsicProfile(input) {
334
+ return toResult(() => readProfile(input));
335
+ }
336
+ /** Validates profile JSON. Text that is not JSON at all is refused like any other invalid input. */
337
+ export function parseCameraIntrinsicProfileJson(text) {
338
+ let parsed;
339
+ try {
340
+ parsed = JSON.parse(text);
341
+ }
342
+ catch {
343
+ return {
344
+ ok: false,
345
+ error: { code: 'not-an-object', path: '', message: 'The profile is not valid JSON.' }
346
+ };
347
+ }
348
+ return parseCameraIntrinsicProfile(parsed);
349
+ }
350
+ /**
351
+ * Renders a profile as JSON with a fixed member order.
352
+ *
353
+ * Stable output means the same profile always produces the same bytes, so a file can be compared or
354
+ * hashed to tell whether two machines really hold the same calibration.
355
+ */
356
+ function orderedCapture(capture) {
357
+ const members = [
358
+ ['frameRate', capture.frameRate],
359
+ ['facingMode', capture.facingMode],
360
+ ['resizeMode', capture.resizeMode],
361
+ ['zoom', capture.zoom],
362
+ ['focusMode', capture.focusMode],
363
+ ['focusDistance', capture.focusDistance]
364
+ ];
365
+ return Object.fromEntries(members.filter((entry) => entry[1] !== undefined));
366
+ }
367
+ export function serializeCameraIntrinsicProfile(profile) {
368
+ const ordered = {
369
+ schema: profile.schema,
370
+ version: profile.version,
371
+ profileId: profile.profileId,
372
+ cameraId: profile.cameraId,
373
+ calibratedAt: profile.calibratedAt,
374
+ producer: profile.producer,
375
+ cameraModel: profile.cameraModel,
376
+ image: {
377
+ width: profile.image.width,
378
+ height: profile.image.height,
379
+ undistorted: profile.image.undistorted
380
+ },
381
+ intrinsics: {
382
+ fx: profile.intrinsics.fx,
383
+ fy: profile.intrinsics.fy,
384
+ cx: profile.intrinsics.cx,
385
+ cy: profile.intrinsics.cy,
386
+ skew: profile.intrinsics.skew
387
+ },
388
+ distortion: { model: profile.distortion.model, coefficients: [...profile.distortion.coefficients] },
389
+ ...(profile.capture === undefined ? {} : { capture: orderedCapture(profile.capture) }),
390
+ ...(profile.quality === undefined
391
+ ? {}
392
+ : {
393
+ quality: {
394
+ sampleCount: profile.quality.sampleCount,
395
+ reprojectionErrorPx: profile.quality.reprojectionErrorPx
396
+ }
397
+ }),
398
+ ...(profile.device === undefined
399
+ ? {}
400
+ : {
401
+ device: {
402
+ ...(profile.device.label === undefined ? {} : { label: profile.device.label }),
403
+ ...(profile.device.deviceId === undefined ? {} : { deviceId: profile.device.deviceId })
404
+ }
405
+ })
406
+ };
407
+ return `${JSON.stringify(ordered, null, 2)}\n`;
408
+ }
409
+ function readLegacyMatrixRow(matrix, offset, expected) {
410
+ expected.forEach((value, index) => {
411
+ const actual = requireFinite(matrix[offset + index], `intrinsicMatrix[${offset + index}]`);
412
+ if (Math.abs(actual - value) > AFFINE_ROW_TOLERANCE) {
413
+ reject('inconsistent-profile', `intrinsicMatrix[${offset + index}]`, `Expected ${value} in the intrinsic matrix; the value read as ${actual}.`);
414
+ }
415
+ });
416
+ }
417
+ /**
418
+ * Converts a `twrmc/camera-calibration` v1 document into this contract.
419
+ *
420
+ * The world pose the old format carried is deliberately dropped. It was the extrinsic of whichever
421
+ * calibration sample happened to be last, so treating it as a placement in a shared world frame puts
422
+ * a camera somewhere it has never been. Placement belongs to whoever solves it against a common
423
+ * reference, and a profile that simply lacks it is honest about what it knows.
424
+ *
425
+ * Quality is dropped for the same reason: the old format recorded none, and inventing a sample count
426
+ * or a reprojection error would turn "unknown" into a measurement.
427
+ */
428
+ export function adoptLegacyCameraCalibration(input) {
429
+ return toResult(() => {
430
+ assertNoForbiddenKeys(input, '', 0, new WeakSet());
431
+ const record = requireRecord(input, '');
432
+ requireLiteral(record['schema'], 'schema', LEGACY_CALIBRATION_SCHEMA, 'unsupported-schema');
433
+ requireLiteral(record['version'], 'version', 1, 'unsupported-version');
434
+ requireExactKeys(record, '', [
435
+ 'schema',
436
+ 'version',
437
+ 'calibrationId',
438
+ 'cameraId',
439
+ 'imageWidth',
440
+ 'imageHeight',
441
+ 'intrinsicMatrix',
442
+ 'distortionCoefficients',
443
+ 'calibratedAt'
444
+ ], ['worldFromCameraMatrix', 'worldUnit']);
445
+ const matrix = record['intrinsicMatrix'];
446
+ if (!Array.isArray(matrix) || matrix.length !== 9) {
447
+ reject('invalid-value', 'intrinsicMatrix', 'Expected nine numbers in row-major order.');
448
+ }
449
+ readLegacyMatrixRow(matrix, 3, [0]);
450
+ readLegacyMatrixRow(matrix, 6, [0, 0, 1]);
451
+ const rawCoefficients = record['distortionCoefficients'];
452
+ if (!Array.isArray(rawCoefficients)) {
453
+ reject('invalid-type', 'distortionCoefficients', 'Expected an array.');
454
+ }
455
+ const model = rawCoefficients.length === 0 ? 'none' : 'brown-conrady';
456
+ return readProfile({
457
+ schema: CAMERA_INTRINSIC_PROFILE_SCHEMA,
458
+ version: CAMERA_INTRINSIC_PROFILE_VERSION,
459
+ profileId: record['calibrationId'],
460
+ cameraId: record['cameraId'],
461
+ calibratedAt: record['calibratedAt'],
462
+ producer: `${LEGACY_CALIBRATION_SCHEMA} v1`,
463
+ cameraModel: 'pinhole',
464
+ image: {
465
+ width: record['imageWidth'],
466
+ height: record['imageHeight'],
467
+ undistorted: false
468
+ },
469
+ intrinsics: {
470
+ fx: matrix[0],
471
+ fy: matrix[4],
472
+ cx: matrix[2],
473
+ cy: matrix[5],
474
+ skew: matrix[1]
475
+ },
476
+ distortion: { model, coefficients: rawCoefficients }
477
+ });
478
+ });
479
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The intrinsic calibration profile contract.
3
+ *
4
+ * A profile describes how one camera projects the world onto its own captured image. It says nothing
5
+ * about where that camera stands: the pose of a camera in a shared world frame belongs to whichever
6
+ * extension solves placement, and mixing the two into one document is what made the earlier
7
+ * `twrmc/camera-calibration` format unusable for anything but the application it came from.
8
+ *
9
+ * Camera Source owns the contract but never produces a profile. Chessboard calibration, an operator
10
+ * supplying JSON, or a future calibrator are all just producers of a document that passes validation.
11
+ */
12
+ /** Projection model of the lens. Version 1 defines the pinhole model only. */
13
+ export type CameraModel = 'pinhole';
14
+ /**
15
+ * Lens distortion model.
16
+ *
17
+ * `brown-conrady` carries the OpenCV radial and tangential coefficients in their usual order
18
+ * (k1, k2, p1, p2 with optional k3, and k4-k6 for the rational model). `kannala-brandt` carries the
19
+ * four fisheye coefficients. `none` means the image is free of lens distortion.
20
+ */
21
+ export type DistortionModel = 'none' | 'brown-conrady' | 'kannala-brandt';
22
+ /**
23
+ * The pinhole parameters, in pixels of the calibration image.
24
+ *
25
+ * Named rather than packed into a matrix because a nine-number array cannot say whether it is stored
26
+ * row-major or column-major, and a reader that guesses wrong produces a plausible, wrong projection.
27
+ * The equivalent row-major 3x3 matrix is `[fx, skew, cx, 0, fy, cy, 0, 0, 1]`.
28
+ *
29
+ * Pixel coordinates run from the top-left corner of the image, x to the right and y downward.
30
+ */
31
+ export interface CameraIntrinsics {
32
+ readonly fx: number;
33
+ readonly fy: number;
34
+ readonly cx: number;
35
+ readonly cy: number;
36
+ /** Axis skew. Zero for every square-pixel sensor; kept explicit so it is never assumed. */
37
+ readonly skew: number;
38
+ }
39
+ export interface CameraDistortion {
40
+ readonly model: DistortionModel;
41
+ readonly coefficients: readonly number[];
42
+ }
43
+ /**
44
+ * The image the calibration was solved against.
45
+ *
46
+ * `undistorted` is false for the base contract: a profile describes the raw captured frame, and a
47
+ * consumer applies the distortion model itself. A producer that hands over already corrected images
48
+ * sets it to true, which then requires the intrinsics to describe the corrected image and forbids
49
+ * leftover distortion coefficients.
50
+ *
51
+ * The image is always the camera's own capture. Preview mirroring is a display choice made by
52
+ * whoever shows the frame and never changes the calibration.
53
+ */
54
+ export interface CalibrationImage {
55
+ readonly width: number;
56
+ readonly height: number;
57
+ readonly undistorted: boolean;
58
+ }
59
+ /**
60
+ * How good the calibration is.
61
+ *
62
+ * Optional, because a profile can arrive from a producer that does not report it — an operator's
63
+ * hand-written JSON, or the legacy format, which carried no quality fields at all. Absent means
64
+ * unknown. A consumer that needs a quality bound must treat absence as unknown and say so, rather
65
+ * than reading it as a measured zero.
66
+ */
67
+ export interface CalibrationQuality {
68
+ readonly sampleCount: number;
69
+ readonly reprojectionErrorPx: number;
70
+ }
71
+ /**
72
+ * Hints for recognizing the physical camera again.
73
+ *
74
+ * `deviceId` is a hint and not an identity: browsers scope it per origin and per profile, so it
75
+ * changes without the camera changing. Matching is done on the operator-assigned `cameraId`.
76
+ */
77
+ export interface CalibrationDeviceHint {
78
+ readonly label?: string;
79
+ readonly deviceId?: string;
80
+ }
81
+ /**
82
+ * The capture configuration the calibration was solved under.
83
+ *
84
+ * Optional as a whole, and optional member by member, but the difference between the two matters.
85
+ * When the block is absent nothing was recorded and compatibility cannot be decided. When it is
86
+ * present, a member that is absent means the device reported no such control at calibration time,
87
+ * which is something a later check can compare against.
88
+ *
89
+ * `frameRate` and `facingMode` are recorded for the operator; neither changes how the lens projects,
90
+ * so neither decides compatibility.
91
+ */
92
+ export interface CalibrationCapture {
93
+ readonly frameRate?: number;
94
+ readonly facingMode?: string;
95
+ /** `none` or `crop-and-scale`. Cropping changes the effective intrinsics at the same resolution. */
96
+ readonly resizeMode?: string;
97
+ readonly zoom?: number;
98
+ /** `none`, `manual`, `single-shot` or `continuous`. */
99
+ readonly focusMode?: string;
100
+ readonly focusDistance?: number;
101
+ }
102
+ export interface CameraIntrinsicProfileV1 {
103
+ readonly schema: 'twcs/camera-intrinsics';
104
+ readonly version: 1;
105
+ /** Identifies this calibration run. A new solve produces a new id. */
106
+ readonly profileId: string;
107
+ /** The operator-assigned camera name, such as `stage-left`. Stable across calibration runs. */
108
+ readonly cameraId: string;
109
+ /** When the calibration was solved, as an RFC 3339 timestamp in UTC. */
110
+ readonly calibratedAt: string;
111
+ /** Free text naming whatever produced the profile. Recorded for diagnostics only. */
112
+ readonly producer: string;
113
+ readonly cameraModel: CameraModel;
114
+ readonly image: CalibrationImage;
115
+ readonly intrinsics: CameraIntrinsics;
116
+ readonly distortion: CameraDistortion;
117
+ readonly capture?: CalibrationCapture;
118
+ readonly quality?: CalibrationQuality;
119
+ readonly device?: CalibrationDeviceHint;
120
+ }
121
+ export type ProfileErrorCode = 'not-an-object' | 'unsupported-schema' | 'unsupported-version' | 'missing-field' | 'unexpected-field' | 'invalid-type' | 'invalid-value' | 'out-of-range' | 'invalid-distortion' | 'inconsistent-profile' | 'forbidden-field';
122
+ export interface ProfileError {
123
+ readonly code: ProfileErrorCode;
124
+ /** Dotted path to the offending member, or an empty string for the document itself. */
125
+ readonly path: string;
126
+ readonly message: string;
127
+ }
128
+ export type ProfileResult = {
129
+ readonly ok: true;
130
+ readonly profile: CameraIntrinsicProfileV1;
131
+ } | {
132
+ readonly ok: false;
133
+ readonly error: ProfileError;
134
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The intrinsic calibration profile contract.
3
+ *
4
+ * A profile describes how one camera projects the world onto its own captured image. It says nothing
5
+ * about where that camera stands: the pose of a camera in a shared world frame belongs to whichever
6
+ * extension solves placement, and mixing the two into one document is what made the earlier
7
+ * `twrmc/camera-calibration` format unusable for anything but the application it came from.
8
+ *
9
+ * Camera Source owns the contract but never produces a profile. Chessboard calibration, an operator
10
+ * supplying JSON, or a future calibrator are all just producers of a document that passes validation.
11
+ */
12
+ export {};
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The part of YAML that camera calibration files are written in.
3
+ *
4
+ * ROS `camera_info` files come out of yaml-cpp's emitter, PyYAML's `dump`, and people's editors, so
5
+ * the reader accepts what those produce: block mappings, block and flow sequences, flow mappings,
6
+ * plain and quoted scalars, comments, and a `%YAML` directive or `---` marker. It refuses what a
7
+ * calibration never needs and a careless reader gets wrong -- anchors and aliases, tags, block
8
+ * scalars, several documents in one file -- by name, rather than guessing.
9
+ *
10
+ * Hand-written for the same reason the profile validator is: a YAML library is larger than this whole
11
+ * extension, and every extension that needs a camera loads this bundle.
12
+ */
13
+ export type YamlValue = string | number | boolean | null | YamlValue[] | {
14
+ [key: string]: YamlValue;
15
+ };
16
+ export declare class YamlError extends Error {
17
+ readonly line: number;
18
+ constructor(message: string, line: number);
19
+ }
20
+ export declare function parseYaml(source: string): YamlValue;