@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,717 @@
1
+ import {
2
+ CALIBRATION_LEASE_OWNER,
3
+ CameraSourceError,
4
+ requireCameraSource,
5
+ requireProfileRegistry,
6
+ type CameraFrameSourcePort,
7
+ type CameraLeasePort
8
+ } from './camera-source.js';
9
+ import {
10
+ assertCameraIntrinsics,
11
+ CalibrationProfileError,
12
+ parseCalibrationProfile,
13
+ type CameraIntrinsicsV1
14
+ } from './profile.js';
15
+ import type {
16
+ CalibrationBackendFactory,
17
+ CalibrationBackendPort,
18
+ CalibrationBoard,
19
+ CalibrationSample
20
+ } from './types.js';
21
+
22
+ const MINIMUM_SAMPLES = 8;
23
+ const MAXIMUM_SAMPLES = 40;
24
+ const MINIMUM_SAMPLE_QUALITY = 0.2;
25
+ const MINIMUM_NORMALIZED_NOVELTY = 0.015;
26
+
27
+ /** Codes a profile validation can produce, and therefore can clear. */
28
+ const PROFILE_ERROR_CODES: ReadonlySet<string> = new Set([
29
+ 'invalid-calibration',
30
+ 'credential-forbidden',
31
+ 'calibration-not-applicable'
32
+ ]);
33
+
34
+ export type CalibrationState =
35
+ | 'idle'
36
+ | 'acquiring-camera'
37
+ | 'sampling'
38
+ | 'ready'
39
+ | 'solving'
40
+ | 'solved'
41
+ | 'cancelling'
42
+ | 'error';
43
+
44
+ export type CalibrationErrorCode =
45
+ | ''
46
+ | 'dependency-missing'
47
+ | 'api-version-mismatch'
48
+ | 'invalid-board'
49
+ | 'camera-unavailable'
50
+ | 'camera-ended'
51
+ | 'resolution-mismatch'
52
+ | 'capture-condition-mismatch'
53
+ | 'board-not-found'
54
+ | 'sample-low-quality'
55
+ | 'sample-too-similar'
56
+ | 'sample-limit'
57
+ | 'sample-insufficient'
58
+ | 'sample-failed'
59
+ | 'solve-failed'
60
+ | 'reprojection-too-high'
61
+ | 'invalid-calibration'
62
+ | 'credential-forbidden'
63
+ | 'calibration-not-applicable'
64
+ | 'not-calibrated'
65
+ | 'publish-failed';
66
+
67
+ export interface CalibrationStartOptions {
68
+ cameraId: string;
69
+ calibrationId: string;
70
+ board: CalibrationBoard;
71
+ maximumReprojectionErrorPx: number;
72
+ }
73
+
74
+ export interface CameraCalibrationControllerOptions {
75
+ runtime: TurboWarpRuntime;
76
+ backend: CalibrationBackendFactory;
77
+ nowMilliseconds?: () => number;
78
+ }
79
+
80
+ interface CalibrationSession {
81
+ readonly calibrationId: string;
82
+ readonly board: CalibrationBoard;
83
+ readonly maximumReprojectionErrorPx: number;
84
+ readonly imageWidth: number;
85
+ readonly imageHeight: number;
86
+ readonly deviceId: string;
87
+ readonly mirrored: boolean;
88
+ }
89
+
90
+ /**
91
+ * One camera's calibration. Every shared camera gets its own instance so that
92
+ * calibrating one camera never disturbs another camera's session or lease.
93
+ */
94
+ class CameraCalibration {
95
+ private session: CalibrationSession | undefined;
96
+ private lease: CameraLeasePort | undefined;
97
+ private samples: CalibrationSample[] = [];
98
+ private acquiring: Promise<void> | undefined;
99
+ private sampling: Promise<void> | undefined;
100
+ private solving: Promise<void> | undefined;
101
+ private profile: CameraIntrinsicsV1 | undefined;
102
+ private sessionSampleCount = 0;
103
+ private sampleQuality = 0;
104
+ private reprojectionError = 0;
105
+ private calibrationState: CalibrationState = 'idle';
106
+ private calibrationErrorCode: CalibrationErrorCode = '';
107
+ private calibrationErrorMessage = '';
108
+ private operation = 0;
109
+
110
+ public constructor(
111
+ public readonly cameraId: string,
112
+ private readonly runtime: TurboWarpRuntime,
113
+ private readonly resolveBackend: () => Promise<CalibrationBackendPort>,
114
+ private readonly nowMilliseconds: () => number
115
+ ) {}
116
+
117
+ public async start(options: CalibrationStartOptions): Promise<void> {
118
+ // Validate before cancelling. A mistyped board must not cost the caller the
119
+ // session and the samples it already collected.
120
+ let normalized: CalibrationStartOptions;
121
+ try {
122
+ normalized = normalizeStartOptions(options);
123
+ } catch (error) {
124
+ this.refuse('invalid-board', error instanceof Error ? error.message : String(error));
125
+ }
126
+ await this.cancel();
127
+ const acquiring = this.acquireSession(normalized);
128
+ this.acquiring = acquiring;
129
+ const clear = () => {
130
+ if (this.acquiring === acquiring) this.acquiring = undefined;
131
+ };
132
+ void acquiring.then(clear, clear);
133
+ await acquiring;
134
+ }
135
+
136
+ private async acquireSession(normalized: CalibrationStartOptions): Promise<void> {
137
+ const operation = ++this.operation;
138
+ this.calibrationState = 'acquiring-camera';
139
+ this.clearError();
140
+ let lease: CameraLeasePort;
141
+ try {
142
+ lease = await requireCameraSource(this.runtime).acquireCamera({
143
+ owner: CALIBRATION_LEASE_OWNER,
144
+ cameraId: normalized.cameraId
145
+ });
146
+ } catch (error) {
147
+ this.fail(
148
+ error instanceof CameraSourceError ? error.code : 'camera-unavailable',
149
+ error
150
+ );
151
+ }
152
+ if (operation !== this.operation) {
153
+ // A cancel arrived while the camera was starting. The lease belongs to
154
+ // nobody now, so release it instead of retaining an orphan.
155
+ await lease.release();
156
+ return;
157
+ }
158
+ let frame: CameraFrameSourcePort;
159
+ try {
160
+ frame = requireVideoFrame(lease);
161
+ } catch (error) {
162
+ await lease.release();
163
+ this.fail('camera-ended', error);
164
+ }
165
+ this.session = {
166
+ calibrationId: normalized.calibrationId,
167
+ board: normalized.board,
168
+ maximumReprojectionErrorPx: normalized.maximumReprojectionErrorPx,
169
+ imageWidth: frame.width,
170
+ imageHeight: frame.height,
171
+ deviceId: frame.deviceId,
172
+ mirrored: frame.mirrored
173
+ };
174
+ this.lease = lease;
175
+ this.samples = [];
176
+ this.sessionSampleCount = 0;
177
+ this.sampleQuality = 0;
178
+ this.reprojectionError = 0;
179
+ this.calibrationState = 'ready';
180
+ }
181
+
182
+ public addSample(): Promise<void> {
183
+ if (this.sampling) return this.sampling;
184
+ if (!this.session || !this.lease || this.calibrationState !== 'ready') {
185
+ throw new Error(`Camera ${this.cameraId} calibration is not ready to sample.`);
186
+ }
187
+ const sampling = this.captureSample(this.operation);
188
+ this.sampling = sampling;
189
+ const clear = () => {
190
+ if (this.sampling === sampling) this.sampling = undefined;
191
+ };
192
+ void sampling.then(clear, clear);
193
+ return sampling;
194
+ }
195
+
196
+ public solve(): Promise<void> {
197
+ if (this.solving) return this.solving;
198
+ if (!this.session || !this.lease || this.calibrationState !== 'ready') {
199
+ throw new Error(`Camera ${this.cameraId} calibration is not ready to solve.`);
200
+ }
201
+ if (this.samples.length < MINIMUM_SAMPLES) {
202
+ this.reject('sample-insufficient', `At least ${MINIMUM_SAMPLES} accepted samples are required.`);
203
+ }
204
+ const solving = this.solveSession(this.operation);
205
+ this.solving = solving;
206
+ const clear = () => {
207
+ if (this.solving === solving) this.solving = undefined;
208
+ };
209
+ void solving.then(clear, clear);
210
+ return solving;
211
+ }
212
+
213
+ public async cancel(): Promise<void> {
214
+ this.operation += 1;
215
+ if (this.lease || this.acquiring || this.sampling || this.solving) {
216
+ this.calibrationState = 'cancelling';
217
+ }
218
+ // The acquisition is awaited too, so that a start racing this cancel has
219
+ // handed its lease back by the time cancel resolves.
220
+ const pending = [this.acquiring, this.sampling, this.solving].filter(isPromise);
221
+ const lease = this.lease;
222
+ this.lease = undefined;
223
+ this.session = undefined;
224
+ await Promise.allSettled(pending);
225
+ await lease?.release();
226
+ this.samples = [];
227
+ this.sessionSampleCount = 0;
228
+ this.sampleQuality = 0;
229
+ this.reprojectionError = 0;
230
+ this.calibrationState = 'idle';
231
+ this.clearError();
232
+ }
233
+
234
+ public async cleanup(): Promise<void> {
235
+ await this.cancel();
236
+ this.profile = undefined;
237
+ }
238
+
239
+ public async importProfile(json: string): Promise<void> {
240
+ let profile: CameraIntrinsicsV1;
241
+ try {
242
+ profile = parseCalibrationProfile(json);
243
+ } catch (error) {
244
+ this.failValidation(error);
245
+ }
246
+ if (profile.cameraId !== this.cameraId) {
247
+ this.failValidation(
248
+ new CalibrationApplicabilityError(
249
+ `The profile calibrates camera ${profile.cameraId} and cannot be applied to camera ${this.cameraId}.`
250
+ )
251
+ );
252
+ }
253
+ const session = this.session;
254
+ if (
255
+ session &&
256
+ (session.imageWidth !== profile.imageWidth || session.imageHeight !== profile.imageHeight)
257
+ ) {
258
+ this.failValidation(
259
+ new CalibrationApplicabilityError(
260
+ `The profile calibrates ${profile.imageWidth}x${profile.imageHeight}, but camera ${this.cameraId} is capturing ${session.imageWidth}x${session.imageHeight}.`
261
+ )
262
+ );
263
+ }
264
+ await this.cancel();
265
+ this.profile = profile;
266
+ this.reprojectionError = profile.quality?.reprojectionErrorPx ?? 0;
267
+ this.sessionSampleCount = profile.quality?.sampleCount ?? 0;
268
+ this.calibrationState = 'solved';
269
+ }
270
+
271
+ public validateProfile(json: string): boolean {
272
+ try {
273
+ parseCalibrationProfile(json);
274
+ // Only a previous validation failure is answered here. A session
275
+ // diagnostic, such as a refused solve, is not resolved by some other
276
+ // JSON turning out to be valid.
277
+ if (PROFILE_ERROR_CODES.has(this.calibrationErrorCode)) this.clearError();
278
+ return true;
279
+ } catch (error) {
280
+ this.recordError(errorCodeFor(error), error);
281
+ return false;
282
+ }
283
+ }
284
+
285
+ /** Hands the solved profile to Camera Source, which owns the contract. */
286
+ public async publishProfile(): Promise<void> {
287
+ const profile = this.profile;
288
+ // Publishing is not a session operation. A refused publication records its
289
+ // code and leaves the calibration state alone: a solved profile that Camera
290
+ // Source could not accept is still solved, and a session that already
291
+ // failed is not repaired by asking to publish.
292
+ if (!profile) {
293
+ this.refuse('not-calibrated', `Camera ${this.cameraId} has no calibration profile to publish.`);
294
+ }
295
+ let registry;
296
+ try {
297
+ registry = requireProfileRegistry(this.runtime);
298
+ } catch (error) {
299
+ this.refuseWith(errorCodeFor(error), error);
300
+ }
301
+ try {
302
+ await registry.registerCalibrationProfile(profile);
303
+ } catch (error) {
304
+ this.refuseWith('publish-failed', error);
305
+ }
306
+ this.clearError();
307
+ }
308
+
309
+ public state(): CalibrationState {
310
+ return this.calibrationState;
311
+ }
312
+
313
+ public ready(): boolean {
314
+ return this.calibrationState === 'ready';
315
+ }
316
+
317
+ public sampleCount(): number {
318
+ return this.sessionSampleCount;
319
+ }
320
+
321
+ public latestSampleQuality(): number {
322
+ return this.sampleQuality;
323
+ }
324
+
325
+ public latestReprojectionError(): number {
326
+ return this.reprojectionError;
327
+ }
328
+
329
+ public errorCode(): CalibrationErrorCode {
330
+ return this.calibrationErrorCode;
331
+ }
332
+
333
+ public errorMessage(): string {
334
+ return this.calibrationErrorMessage;
335
+ }
336
+
337
+ public profileJson(): string {
338
+ return this.profile ? JSON.stringify(this.profile) : '';
339
+ }
340
+
341
+ private async captureSample(operation: number): Promise<void> {
342
+ const session = this.session;
343
+ const lease = this.lease;
344
+ if (!session || !lease) return;
345
+ if (this.samples.length >= MAXIMUM_SAMPLES) {
346
+ this.reject('sample-limit', `At most ${MAXIMUM_SAMPLES} samples may be retained.`);
347
+ }
348
+ this.calibrationState = 'sampling';
349
+ let frame: CameraFrameSourcePort;
350
+ try {
351
+ frame = requireVideoFrame(lease);
352
+ } catch (error) {
353
+ // The device went away mid-session. Release before reporting so that a
354
+ // disconnected camera cannot strand a lease other consumers share.
355
+ await this.releaseSession();
356
+ this.fail('camera-ended', error);
357
+ }
358
+ if (frame.width !== session.imageWidth || frame.height !== session.imageHeight) {
359
+ this.reject(
360
+ 'resolution-mismatch',
361
+ `Expected ${session.imageWidth}x${session.imageHeight}, received ${frame.width}x${frame.height}.`
362
+ );
363
+ }
364
+ if (frame.deviceId !== session.deviceId || frame.mirrored !== session.mirrored) {
365
+ this.reject(
366
+ 'capture-condition-mismatch',
367
+ `The capture conditions changed after the session started. Restart the calibration for camera ${this.cameraId}.`
368
+ );
369
+ }
370
+ let sample: CalibrationSample | undefined;
371
+ try {
372
+ const backend = await this.resolveBackend();
373
+ sample = await backend.captureSample(
374
+ {element: frame.element, width: frame.width, height: frame.height},
375
+ session.board
376
+ );
377
+ } catch (error) {
378
+ this.fail('sample-failed', error);
379
+ }
380
+ if (operation !== this.operation) return;
381
+ if (!sample) this.reject('board-not-found', 'The complete chessboard was not found.');
382
+ const expectedCorners = session.board.columns * session.board.rows;
383
+ if (
384
+ sample.corners.length !== expectedCorners ||
385
+ !Number.isFinite(sample.quality) ||
386
+ sample.quality < MINIMUM_SAMPLE_QUALITY
387
+ ) {
388
+ this.reject('sample-low-quality', `Sample quality must be at least ${MINIMUM_SAMPLE_QUALITY}.`);
389
+ }
390
+ const accepted = sample;
391
+ if (
392
+ this.samples.some(
393
+ (previous) =>
394
+ normalizedCornerDistance(previous, accepted, session.imageWidth, session.imageHeight) <
395
+ MINIMUM_NORMALIZED_NOVELTY
396
+ )
397
+ ) {
398
+ this.reject('sample-too-similar', 'Move or tilt the board before capturing another sample.');
399
+ }
400
+ this.samples.push(accepted);
401
+ this.sessionSampleCount = this.samples.length;
402
+ this.sampleQuality = accepted.quality;
403
+ this.calibrationState = 'ready';
404
+ this.clearError();
405
+ }
406
+
407
+ private async solveSession(operation: number): Promise<void> {
408
+ const session = this.session;
409
+ const lease = this.lease;
410
+ if (!session || !lease) return;
411
+ this.calibrationState = 'solving';
412
+ let solution;
413
+ try {
414
+ const backend = await this.resolveBackend();
415
+ solution = await backend.solve(
416
+ [...this.samples],
417
+ session.board,
418
+ session.imageWidth,
419
+ session.imageHeight
420
+ );
421
+ } catch (error) {
422
+ this.fail('solve-failed', error);
423
+ }
424
+ if (operation !== this.operation) return;
425
+ this.reprojectionError = solution.reprojectionErrorPx;
426
+ if (
427
+ !Number.isFinite(this.reprojectionError) ||
428
+ this.reprojectionError > session.maximumReprojectionErrorPx
429
+ ) {
430
+ this.calibrationState = 'ready';
431
+ this.reject(
432
+ 'reprojection-too-high',
433
+ `Reprojection RMS ${this.reprojectionError} px exceeds ${session.maximumReprojectionErrorPx} px.`
434
+ );
435
+ }
436
+ const sampleCount = this.samples.length;
437
+ let profile: CameraIntrinsicsV1;
438
+ try {
439
+ profile = assertCameraIntrinsics({
440
+ schema: 'camerasource/camera-intrinsics',
441
+ version: 1,
442
+ calibrationId: session.calibrationId,
443
+ cameraId: this.cameraId,
444
+ cameraModel: 'pinhole',
445
+ imageWidth: session.imageWidth,
446
+ imageHeight: session.imageHeight,
447
+ imageState: 'raw',
448
+ intrinsicMatrix: solution.intrinsicMatrix,
449
+ distortionModel: solution.distortionModel,
450
+ distortionCoefficients: solution.distortionCoefficients,
451
+ quality: {sampleCount, reprojectionErrorPx: solution.reprojectionErrorPx},
452
+ calibratedAt: new Date(this.nowMilliseconds()).toISOString()
453
+ });
454
+ } catch (error) {
455
+ this.fail('invalid-calibration', error);
456
+ }
457
+ this.profile = profile;
458
+ this.sessionSampleCount = sampleCount;
459
+ this.samples = [];
460
+ this.lease = undefined;
461
+ this.session = undefined;
462
+ // The solve is complete whether or not Camera Source can complete the
463
+ // release, so record it before handing the lease back.
464
+ this.calibrationState = 'solved';
465
+ this.clearError();
466
+ await lease.release();
467
+ }
468
+
469
+ /** Drops the session and releases its lease without touching diagnostics. */
470
+ private async releaseSession(): Promise<void> {
471
+ const lease = this.lease;
472
+ this.lease = undefined;
473
+ this.session = undefined;
474
+ this.samples = [];
475
+ await lease?.release();
476
+ }
477
+
478
+ /** Refuses a session step and returns the live session to `ready`. */
479
+ private reject(code: CalibrationErrorCode, message: string): never {
480
+ if (this.calibrationState !== 'ready' && this.lease) this.calibrationState = 'ready';
481
+ this.refuse(code, message);
482
+ }
483
+
484
+ /** Records why an operation was refused, without touching the state. */
485
+ private refuse(code: CalibrationErrorCode, message: string): never {
486
+ this.calibrationErrorCode = code;
487
+ this.calibrationErrorMessage = `${code}: ${message}`;
488
+ throw new Error(this.calibrationErrorMessage);
489
+ }
490
+
491
+ private refuseWith(code: CalibrationErrorCode, cause: unknown): never {
492
+ this.recordError(code, cause);
493
+ throw new Error(this.calibrationErrorMessage, {cause});
494
+ }
495
+
496
+ private fail(code: CalibrationErrorCode, cause: unknown): never {
497
+ this.calibrationState = 'error';
498
+ this.recordError(code, cause);
499
+ throw new Error(this.calibrationErrorMessage, {cause});
500
+ }
501
+
502
+ /** Reports a rejected profile without disturbing the session or the state. */
503
+ private failValidation(error: unknown): never {
504
+ this.refuseWith(errorCodeFor(error), error);
505
+ }
506
+
507
+ private recordError(code: CalibrationErrorCode, cause: unknown): void {
508
+ const detail = cause instanceof Error ? cause.message : String(cause);
509
+ this.calibrationErrorCode = code;
510
+ this.calibrationErrorMessage = `${code}: ${detail}`;
511
+ }
512
+
513
+ private clearError(): void {
514
+ this.calibrationErrorCode = '';
515
+ this.calibrationErrorMessage = '';
516
+ }
517
+ }
518
+
519
+ /**
520
+ * Routes calibration blocks to one `CameraCalibration` per shared camera and
521
+ * owns the solver, which is created on first use and never at load time.
522
+ */
523
+ export class CameraCalibrationController {
524
+ private readonly cameras = new Map<string, CameraCalibration>();
525
+ private readonly runtime: TurboWarpRuntime;
526
+ private readonly backendFactory: CalibrationBackendFactory;
527
+ private readonly nowMilliseconds: () => number;
528
+ private backendPromise: Promise<CalibrationBackendPort> | undefined;
529
+
530
+ public constructor(options: CameraCalibrationControllerOptions) {
531
+ this.runtime = options.runtime;
532
+ this.backendFactory = options.backend;
533
+ this.nowMilliseconds = options.nowMilliseconds ?? Date.now;
534
+ }
535
+
536
+ public start(options: CalibrationStartOptions): Promise<void> {
537
+ return this.camera(options.cameraId).start(options);
538
+ }
539
+
540
+ public addSample(cameraId: string): Promise<void> {
541
+ return this.camera(cameraId).addSample();
542
+ }
543
+
544
+ public solve(cameraId: string): Promise<void> {
545
+ return this.camera(cameraId).solve();
546
+ }
547
+
548
+ public cancel(cameraId: string): Promise<void> {
549
+ return this.existing(cameraId)?.cancel() ?? Promise.resolve();
550
+ }
551
+
552
+ public cleanup(cameraId: string): Promise<void> {
553
+ return this.existing(cameraId)?.cleanup() ?? Promise.resolve();
554
+ }
555
+
556
+ public importProfile(cameraId: string, json: string): Promise<void> {
557
+ return this.camera(cameraId).importProfile(json);
558
+ }
559
+
560
+ public publishProfile(cameraId: string): Promise<void> {
561
+ return this.camera(cameraId).publishProfile();
562
+ }
563
+
564
+ public validateProfile(cameraId: string, json: string): boolean {
565
+ return this.camera(cameraId).validateProfile(json);
566
+ }
567
+
568
+ /** Releases every lease. Used for project stop, reload, and disposal. */
569
+ public async cancelAll(): Promise<void> {
570
+ await Promise.allSettled([...this.cameras.values()].map((camera) => camera.cancel()));
571
+ }
572
+
573
+ /** Releases every lease and forgets every in-memory profile. */
574
+ public async cleanupAll(): Promise<void> {
575
+ await Promise.allSettled([...this.cameras.values()].map((camera) => camera.cleanup()));
576
+ this.cameras.clear();
577
+ }
578
+
579
+ public backend(): string {
580
+ return this.backendFactory.name;
581
+ }
582
+
583
+ public state(cameraId: string): CalibrationState {
584
+ return this.existing(cameraId)?.state() ?? 'idle';
585
+ }
586
+
587
+ public ready(cameraId: string): boolean {
588
+ return this.existing(cameraId)?.ready() ?? false;
589
+ }
590
+
591
+ public sampleCount(cameraId: string): number {
592
+ return this.existing(cameraId)?.sampleCount() ?? 0;
593
+ }
594
+
595
+ public latestSampleQuality(cameraId: string): number {
596
+ return this.existing(cameraId)?.latestSampleQuality() ?? 0;
597
+ }
598
+
599
+ public latestReprojectionError(cameraId: string): number {
600
+ return this.existing(cameraId)?.latestReprojectionError() ?? 0;
601
+ }
602
+
603
+ public errorCode(cameraId: string): CalibrationErrorCode {
604
+ return this.existing(cameraId)?.errorCode() ?? '';
605
+ }
606
+
607
+ public errorMessage(cameraId: string): string {
608
+ return this.existing(cameraId)?.errorMessage() ?? '';
609
+ }
610
+
611
+ public profileJson(cameraId: string): string {
612
+ return this.existing(cameraId)?.profileJson() ?? '';
613
+ }
614
+
615
+ private existing(cameraId: string): CameraCalibration | undefined {
616
+ return this.cameras.get(cameraId.trim());
617
+ }
618
+
619
+ private camera(cameraId: string): CameraCalibration {
620
+ // The lease and the published profile both use the trimmed identifier, so
621
+ // the record is keyed the same way rather than by whatever the caller typed.
622
+ const key = cameraId.trim();
623
+ const existing = this.cameras.get(key);
624
+ if (existing) return existing;
625
+ const created = new CameraCalibration(
626
+ key,
627
+ this.runtime,
628
+ () => this.resolveBackend(),
629
+ this.nowMilliseconds
630
+ );
631
+ this.cameras.set(key, created);
632
+ return created;
633
+ }
634
+
635
+ /** Creates the solver once, on the first sample or solve of any camera. */
636
+ private resolveBackend(): Promise<CalibrationBackendPort> {
637
+ this.backendPromise ??= this.backendFactory.create();
638
+ return this.backendPromise;
639
+ }
640
+ }
641
+
642
+ class CalibrationApplicabilityError extends Error {
643
+ public readonly code = 'calibration-not-applicable' as const;
644
+ }
645
+
646
+ function errorCodeFor(error: unknown): CalibrationErrorCode {
647
+ if (error instanceof CalibrationApplicabilityError) return error.code;
648
+ if (error instanceof CalibrationProfileError) return error.code;
649
+ if (error instanceof CameraSourceError) return error.code;
650
+ return 'invalid-calibration';
651
+ }
652
+
653
+ function requireVideoFrame(lease: CameraLeasePort): CameraFrameSourcePort {
654
+ const frame = lease.getFrameSource();
655
+ if (frame.kind !== 'video' || frame.width < 1 || frame.height < 1) {
656
+ throw new Error('Camera Source has no current video frame.');
657
+ }
658
+ return frame;
659
+ }
660
+
661
+ function normalizeStartOptions(options: CalibrationStartOptions): CalibrationStartOptions {
662
+ const columns = integerInRange(options.board.columns, 3, 20, 'columns');
663
+ const rows = integerInRange(options.board.rows, 3, 20, 'rows');
664
+ if (
665
+ !Number.isFinite(options.board.squareSizeMeters) ||
666
+ options.board.squareSizeMeters <= 0 ||
667
+ options.board.squareSizeMeters > 1
668
+ ) {
669
+ throw new Error('square size must be within (0, 1] meter.');
670
+ }
671
+ if (
672
+ !Number.isFinite(options.maximumReprojectionErrorPx) ||
673
+ options.maximumReprojectionErrorPx <= 0 ||
674
+ options.maximumReprojectionErrorPx > 100
675
+ ) {
676
+ throw new Error('maximum reprojection error must be within (0, 100] px.');
677
+ }
678
+ return {
679
+ cameraId: identifier(options.cameraId, 'camera ID'),
680
+ calibrationId: identifier(options.calibrationId, 'calibration ID'),
681
+ board: {columns, rows, squareSizeMeters: options.board.squareSizeMeters},
682
+ maximumReprojectionErrorPx: options.maximumReprojectionErrorPx
683
+ };
684
+ }
685
+
686
+ function normalizedCornerDistance(
687
+ left: CalibrationSample,
688
+ right: CalibrationSample,
689
+ width: number,
690
+ height: number
691
+ ): number {
692
+ let squared = 0;
693
+ for (let index = 0; index < left.corners.length; index += 1) {
694
+ const a = left.corners[index];
695
+ const b = right.corners[index];
696
+ if (!a || !b) return Number.POSITIVE_INFINITY;
697
+ squared += (a.x - b.x) ** 2 + (a.y - b.y) ** 2;
698
+ }
699
+ return Math.sqrt(squared / left.corners.length) / Math.hypot(width, height);
700
+ }
701
+
702
+ function identifier(value: string, label: string): string {
703
+ const text = value.trim();
704
+ if (!/^[A-Za-z0-9._-]{1,64}$/u.test(text)) throw new Error(`invalid ${label}.`);
705
+ return text;
706
+ }
707
+
708
+ function integerInRange(value: number, minimum: number, maximum: number, label: string): number {
709
+ if (!Number.isInteger(value) || value < minimum || value > maximum) {
710
+ throw new Error(`${label} must be an integer from ${minimum} to ${maximum}.`);
711
+ }
712
+ return value;
713
+ }
714
+
715
+ function isPromise(value: Promise<void> | undefined): value is Promise<void> {
716
+ return value !== undefined;
717
+ }