@kubohiroya/turbowarp-camera-source 0.9.1 → 0.11.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.
@@ -171,6 +171,21 @@
171
171
  "defaultValue": "{}"
172
172
  } }
173
173
  },
174
+ {
175
+ "opcode": "registerCameraProfileAs",
176
+ "blockType": "COMMAND",
177
+ "text": "register camera profile [PROFILE_JSON] as [CAMERA_ID]",
178
+ "arguments": {
179
+ "PROFILE_JSON": {
180
+ "type": "STRING",
181
+ "defaultValue": "{}"
182
+ },
183
+ "CAMERA_ID": {
184
+ "type": "STRING",
185
+ "defaultValue": "default"
186
+ }
187
+ }
188
+ },
174
189
  {
175
190
  "opcode": "forgetCameraProfile",
176
191
  "blockType": "COMMAND",
@@ -198,6 +213,15 @@
198
213
  "defaultValue": "default"
199
214
  } }
200
215
  },
216
+ {
217
+ "opcode": "cameraProfileYaml",
218
+ "blockType": "REPORTER",
219
+ "text": "camera profile YAML for [CAMERA_ID]",
220
+ "arguments": { "CAMERA_ID": {
221
+ "type": "STRING",
222
+ "defaultValue": "default"
223
+ } }
224
+ },
201
225
  {
202
226
  "opcode": "cameraProfileError",
203
227
  "blockType": "REPORTER",
@@ -263,6 +287,48 @@
263
287
  "type": "STRING",
264
288
  "defaultValue": "default"
265
289
  } }
290
+ },
291
+ {
292
+ "opcode": "saveCameraProfile",
293
+ "blockType": "COMMAND",
294
+ "text": "save camera profile for [CAMERA_ID] to browser storage",
295
+ "arguments": { "CAMERA_ID": {
296
+ "type": "STRING",
297
+ "defaultValue": "default"
298
+ } }
299
+ },
300
+ {
301
+ "opcode": "restoreStoredCameraProfile",
302
+ "blockType": "COMMAND",
303
+ "text": "restore stored camera profile for [CAMERA_ID]",
304
+ "arguments": { "CAMERA_ID": {
305
+ "type": "STRING",
306
+ "defaultValue": "default"
307
+ } }
308
+ },
309
+ {
310
+ "opcode": "storedCameraProfileResult",
311
+ "blockType": "REPORTER",
312
+ "text": "stored camera profile result for [CAMERA_ID]",
313
+ "arguments": { "CAMERA_ID": {
314
+ "type": "STRING",
315
+ "defaultValue": "default"
316
+ } }
317
+ },
318
+ {
319
+ "opcode": "storedCameraProfileDetail",
320
+ "blockType": "REPORTER",
321
+ "text": "stored camera profile detail for [CAMERA_ID]",
322
+ "arguments": { "CAMERA_ID": {
323
+ "type": "STRING",
324
+ "defaultValue": "default"
325
+ } }
326
+ },
327
+ {
328
+ "opcode": "storedCameraProfilesGeneration",
329
+ "blockType": "REPORTER",
330
+ "text": "stored camera profiles generation",
331
+ "arguments": {}
266
332
  }
267
333
  ],
268
334
  menus: { "flips": {
@@ -685,7 +751,7 @@
685
751
  skew: requireBounded(record["skew"], member(path, "skew"), -1e7, MAXIMUM_PIXEL_MAGNITUDE)
686
752
  };
687
753
  }
688
- function readDistortion(value, path) {
754
+ function readDistortion$1(value, path) {
689
755
  const record = requireRecord(value, path);
690
756
  requireExactKeys(record, path, ["model", "coefficients"]);
691
757
  const modelPath = member(path, "model");
@@ -773,7 +839,7 @@
773
839
  "device"
774
840
  ]);
775
841
  const image = readImage(record["image"], "image");
776
- const distortion = readDistortion(record["distortion"], "distortion");
842
+ const distortion = readDistortion$1(record["distortion"], "distortion");
777
843
  if (image.undistorted && distortion.model !== "none") reject("inconsistent-profile", "distortion.model", "A profile for an already undistorted image cannot also carry distortion coefficients.");
778
844
  const capture = "capture" in record ? readCapture(record["capture"], "capture") : void 0;
779
845
  const quality = "quality" in record ? readQuality(record["quality"], "quality") : void 0;
@@ -1022,6 +1088,871 @@
1022
1088
  }
1023
1089
  };
1024
1090
  //#endregion
1091
+ //#region src/calibration/yaml.ts
1092
+ var YamlError = class extends Error {
1093
+ constructor(message, line) {
1094
+ super(line > 0 ? `Line ${line}: ${message}` : message);
1095
+ this.name = "YamlError";
1096
+ this.line = line;
1097
+ }
1098
+ };
1099
+ var MAXIMUM_DEPTH = 16;
1100
+ var MAXIMUM_LENGTH = 65536;
1101
+ function parseYaml(source) {
1102
+ if (source.length > MAXIMUM_LENGTH) throw new YamlError("The document is longer than a calibration file ever is.", 0);
1103
+ const lines = splitLines(source);
1104
+ if (lines.length === 0) throw new YamlError("The document is empty.", 0);
1105
+ const reader = new BlockReader(lines);
1106
+ const value = reader.readBlock(lines[0].indent, 0);
1107
+ if (!reader.done()) throw new YamlError("Unexpected indentation.", reader.peek().number);
1108
+ return value;
1109
+ }
1110
+ function splitLines(source) {
1111
+ const lines = [];
1112
+ let started = false;
1113
+ source.replace(/^\uFEFF/, "").split(/\r\n|\r|\n/).forEach((raw, index) => {
1114
+ const number = index + 1;
1115
+ if (/\t/.test(raw.match(/^\s*/)[0])) throw new YamlError("Tabs cannot indent YAML.", number);
1116
+ const text = stripComment(raw).trimEnd();
1117
+ const content = text.trimStart();
1118
+ if (content.length === 0) return;
1119
+ if (!started && content.startsWith("%")) return;
1120
+ if (content === "---" || content.startsWith("--- ")) {
1121
+ if (started) throw new YamlError("Only one document is read from a calibration file.", number);
1122
+ started = true;
1123
+ const rest = content.slice(3).trim();
1124
+ if (rest.length > 0) lines.push({
1125
+ number,
1126
+ indent: 0,
1127
+ text: rest
1128
+ });
1129
+ return;
1130
+ }
1131
+ if (content === "...") {
1132
+ started = true;
1133
+ return;
1134
+ }
1135
+ started = true;
1136
+ lines.push({
1137
+ number,
1138
+ indent: text.length - content.length,
1139
+ text: content
1140
+ });
1141
+ });
1142
+ return lines;
1143
+ }
1144
+ /** Removes a `#` comment that is not inside quotes. A `#` only starts one after whitespace. */
1145
+ function stripComment(raw) {
1146
+ let quote;
1147
+ for (let index = 0; index < raw.length; index += 1) {
1148
+ const character = raw[index];
1149
+ if (quote) {
1150
+ if (character === "\\" && quote === "\"") index += 1;
1151
+ else if (character === quote) quote = void 0;
1152
+ continue;
1153
+ }
1154
+ if (character === "\"" || character === "'") quote = character;
1155
+ else if (character === "#" && (index === 0 || /\s/.test(raw[index - 1]))) return raw.slice(0, index);
1156
+ }
1157
+ return raw;
1158
+ }
1159
+ var BlockReader = class {
1160
+ constructor(lines) {
1161
+ this.lines = lines;
1162
+ this.index = 0;
1163
+ }
1164
+ done() {
1165
+ return this.index >= this.lines.length;
1166
+ }
1167
+ peek() {
1168
+ return this.lines[this.index];
1169
+ }
1170
+ readBlock(indent, depth) {
1171
+ if (depth > MAXIMUM_DEPTH) throw new YamlError("The document is nested too deeply.", this.peek()?.number ?? 0);
1172
+ const first = this.peek();
1173
+ if (!first) throw new YamlError("Expected a value.", 0);
1174
+ if (first.text === "-" || first.text.startsWith("- ")) return this.readSequence(indent, depth);
1175
+ if (findMappingColon(first.text) >= 0) return this.readMapping(indent, depth);
1176
+ this.index += 1;
1177
+ return this.readInline(first.text, first.number, first.indent);
1178
+ }
1179
+ readMapping(indent, depth) {
1180
+ const mapping = {};
1181
+ while (!this.done()) {
1182
+ const line = this.peek();
1183
+ if (line.indent < indent) break;
1184
+ if (line.indent > indent) throw new YamlError("Unexpected indentation.", line.number);
1185
+ const colon = findMappingColon(line.text);
1186
+ if (colon < 0) throw new YamlError("Expected a \"key: value\" pair.", line.number);
1187
+ const key = readKey(line.text.slice(0, colon).trim(), line.number);
1188
+ if (Object.prototype.hasOwnProperty.call(mapping, key)) throw new YamlError(`The key "${key}" appears twice.`, line.number);
1189
+ const rest = line.text.slice(colon + 1).trim();
1190
+ this.index += 1;
1191
+ if (rest.length > 0) {
1192
+ mapping[key] = this.readInline(rest, line.number, line.indent);
1193
+ continue;
1194
+ }
1195
+ const next = this.peek();
1196
+ const nestedSequence = next !== void 0 && next.indent === indent && (next.text === "-" || next.text.startsWith("- "));
1197
+ if (next === void 0 || next.indent <= indent && !nestedSequence) mapping[key] = null;
1198
+ else mapping[key] = this.readBlock(next.indent, depth + 1);
1199
+ }
1200
+ return mapping;
1201
+ }
1202
+ readSequence(indent, depth) {
1203
+ const sequence = [];
1204
+ while (!this.done()) {
1205
+ const line = this.peek();
1206
+ if (line.indent < indent || !(line.text === "-" || line.text.startsWith("- "))) break;
1207
+ if (line.indent > indent) throw new YamlError("Unexpected indentation.", line.number);
1208
+ const rest = line.text.slice(1).trim();
1209
+ this.index += 1;
1210
+ if (rest.length === 0) {
1211
+ const next = this.peek();
1212
+ sequence.push(next !== void 0 && next.indent > indent ? this.readBlock(next.indent, depth + 1) : null);
1213
+ } else if (findMappingColon(rest) >= 0 && !/^[[{"']/.test(rest)) throw new YamlError("A mapping inside a block sequence is not part of a calibration file.", line.number);
1214
+ else sequence.push(this.readInline(rest, line.number, line.indent));
1215
+ }
1216
+ return sequence;
1217
+ }
1218
+ /**
1219
+ * Reads a value that starts on one line. A flow collection may continue on the lines after it, as
1220
+ * PyYAML writes long matrices, so those lines are drawn in until the brackets balance.
1221
+ */
1222
+ readInline(text, number, indent) {
1223
+ if (text.startsWith("[") || text.startsWith("{")) {
1224
+ let joined = text;
1225
+ while (!flowClosed(joined)) {
1226
+ const next = this.peek();
1227
+ if (!next || next.indent <= indent) throw new YamlError("A bracket is never closed.", number);
1228
+ joined += ` ${next.text}`;
1229
+ this.index += 1;
1230
+ }
1231
+ const flow = new FlowReader(joined, number);
1232
+ const value = flow.readValue(0);
1233
+ flow.expectEnd();
1234
+ return value;
1235
+ }
1236
+ return readScalar(text, number);
1237
+ }
1238
+ };
1239
+ /** Where the `: ` separating a key from its value is, or -1. Colons inside quotes do not count. */
1240
+ function findMappingColon(text) {
1241
+ let quote;
1242
+ for (let index = 0; index < text.length; index += 1) {
1243
+ const character = text[index];
1244
+ if (quote) {
1245
+ if (character === "\\" && quote === "\"") index += 1;
1246
+ else if (character === quote) quote = void 0;
1247
+ continue;
1248
+ }
1249
+ if (index === 0 && (character === "[" || character === "{")) return -1;
1250
+ if (character === "\"" || character === "'") quote = character;
1251
+ else if (character === ":" && (index === text.length - 1 || text[index + 1] === " ")) return index;
1252
+ }
1253
+ return -1;
1254
+ }
1255
+ function flowClosed(text) {
1256
+ let depth = 0;
1257
+ let quote;
1258
+ for (let index = 0; index < text.length; index += 1) {
1259
+ const character = text[index];
1260
+ if (quote) {
1261
+ if (character === "\\" && quote === "\"") index += 1;
1262
+ else if (character === quote) quote = void 0;
1263
+ continue;
1264
+ }
1265
+ if (character === "\"" || character === "'") quote = character;
1266
+ else if (character === "[" || character === "{") depth += 1;
1267
+ else if (character === "]" || character === "}") depth -= 1;
1268
+ }
1269
+ return depth <= 0;
1270
+ }
1271
+ function readKey(text, number) {
1272
+ const value = readScalar(text, number);
1273
+ if (typeof value !== "string") return String(value);
1274
+ return value;
1275
+ }
1276
+ var FlowReader = class {
1277
+ constructor(text, number) {
1278
+ this.text = text;
1279
+ this.number = number;
1280
+ this.index = 0;
1281
+ }
1282
+ readValue(depth) {
1283
+ if (depth > MAXIMUM_DEPTH) throw new YamlError("The document is nested too deeply.", this.number);
1284
+ this.skipSpace();
1285
+ const character = this.text[this.index];
1286
+ if (character === "[") return this.readSequence(depth);
1287
+ if (character === "{") return this.readMapping(depth);
1288
+ return readScalar(this.readToken(), this.number);
1289
+ }
1290
+ expectEnd() {
1291
+ this.skipSpace();
1292
+ if (this.index < this.text.length) throw new YamlError("Unexpected text after a closing bracket.", this.number);
1293
+ }
1294
+ readSequence(depth) {
1295
+ this.index += 1;
1296
+ const sequence = [];
1297
+ this.skipSpace();
1298
+ if (this.text[this.index] === "]") {
1299
+ this.index += 1;
1300
+ return sequence;
1301
+ }
1302
+ for (;;) {
1303
+ sequence.push(this.readValue(depth + 1));
1304
+ this.skipSpace();
1305
+ const separator = this.text[this.index];
1306
+ this.index += 1;
1307
+ if (separator === "]") return sequence;
1308
+ if (separator !== ",") throw new YamlError("Expected \",\" or \"]\" in a sequence.", this.number);
1309
+ this.skipSpace();
1310
+ if (this.text[this.index] === "]") {
1311
+ this.index += 1;
1312
+ return sequence;
1313
+ }
1314
+ }
1315
+ }
1316
+ readMapping(depth) {
1317
+ this.index += 1;
1318
+ const mapping = {};
1319
+ this.skipSpace();
1320
+ if (this.text[this.index] === "}") {
1321
+ this.index += 1;
1322
+ return mapping;
1323
+ }
1324
+ for (;;) {
1325
+ this.skipSpace();
1326
+ const key = readKey(this.readToken(":"), this.number);
1327
+ this.skipSpace();
1328
+ if (this.text[this.index] !== ":") throw new YamlError("Expected \":\" after a key.", this.number);
1329
+ this.index += 1;
1330
+ if (Object.prototype.hasOwnProperty.call(mapping, key)) throw new YamlError(`The key "${key}" appears twice.`, this.number);
1331
+ mapping[key] = this.readValue(depth + 1);
1332
+ this.skipSpace();
1333
+ const separator = this.text[this.index];
1334
+ this.index += 1;
1335
+ if (separator === "}") return mapping;
1336
+ if (separator !== ",") throw new YamlError("Expected \",\" or \"}\" in a mapping.", this.number);
1337
+ this.skipSpace();
1338
+ if (this.text[this.index] === "}") {
1339
+ this.index += 1;
1340
+ return mapping;
1341
+ }
1342
+ }
1343
+ }
1344
+ /** A quoted string, or plain text up to the next flow delimiter. */
1345
+ readToken(stopAlso = "") {
1346
+ this.skipSpace();
1347
+ const start = this.index;
1348
+ const character = this.text[this.index];
1349
+ if (character === "\"" || character === "'") {
1350
+ this.index += 1;
1351
+ while (this.index < this.text.length) {
1352
+ const current = this.text[this.index];
1353
+ if (current === "\\" && character === "\"") {
1354
+ this.index += 2;
1355
+ continue;
1356
+ }
1357
+ if (current === character) {
1358
+ if (character === "'" && this.text[this.index + 1] === "'") {
1359
+ this.index += 2;
1360
+ continue;
1361
+ }
1362
+ this.index += 1;
1363
+ return this.text.slice(start, this.index);
1364
+ }
1365
+ this.index += 1;
1366
+ }
1367
+ throw new YamlError("A quoted string is never closed.", this.number);
1368
+ }
1369
+ while (this.index < this.text.length && !`,]}${stopAlso}`.includes(this.text[this.index])) this.index += 1;
1370
+ return this.text.slice(start, this.index).trim();
1371
+ }
1372
+ skipSpace() {
1373
+ while (this.index < this.text.length && /\s/.test(this.text[this.index])) this.index += 1;
1374
+ }
1375
+ };
1376
+ var INTEGER = /^[-+]?(?:0|[1-9][0-9_]*)$/;
1377
+ var FLOAT = /^[-+]?(?:[0-9][0-9_]*)?\.?[0-9]*(?:[eE][-+]?[0-9]+)?$/;
1378
+ function readScalar(text, number) {
1379
+ const value = text.trim();
1380
+ if (value.length === 0) return null;
1381
+ const first = value[0];
1382
+ if (first === "\"") return readDoubleQuoted(value, number);
1383
+ if (first === "'") {
1384
+ if (value.length < 2 || !value.endsWith("'")) throw new YamlError("A quoted string is never closed.", number);
1385
+ return value.slice(1, -1).replace(/''/g, "'");
1386
+ }
1387
+ if (first === "&" || first === "*") throw new YamlError("Anchors and aliases are not read.", number);
1388
+ if (first === "!") throw new YamlError("Tags are not read.", number);
1389
+ if (first === "|" || first === ">") throw new YamlError("Block scalars are not read.", number);
1390
+ if (first === "@" || first === "`") throw new YamlError(`A plain value cannot start with "${first}".`, number);
1391
+ if (value === "~" || value === "null" || value === "Null" || value === "NULL") return null;
1392
+ if (value === "true" || value === "True" || value === "TRUE") return true;
1393
+ if (value === "false" || value === "False" || value === "FALSE") return false;
1394
+ if (/^[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN)$/.test(value)) throw new YamlError("Infinity and NaN are not calibration values.", number);
1395
+ if (INTEGER.test(value)) return Number(value.replace(/_/g, ""));
1396
+ if (/[0-9]/.test(value) && FLOAT.test(value)) {
1397
+ const parsed = Number(value.replace(/_/g, ""));
1398
+ if (Number.isFinite(parsed)) return parsed;
1399
+ }
1400
+ return value;
1401
+ }
1402
+ function readDoubleQuoted(value, number) {
1403
+ if (value.length < 2 || !value.endsWith("\"")) throw new YamlError("A quoted string is never closed.", number);
1404
+ const body = value.slice(1, -1);
1405
+ let result = "";
1406
+ for (let index = 0; index < body.length; index += 1) {
1407
+ const character = body[index];
1408
+ if (character !== "\\") {
1409
+ result += character;
1410
+ continue;
1411
+ }
1412
+ const escape = body[index + 1];
1413
+ index += 1;
1414
+ switch (escape) {
1415
+ case "\"":
1416
+ case "\\":
1417
+ case "/":
1418
+ result += escape;
1419
+ break;
1420
+ case "n":
1421
+ result += "\n";
1422
+ break;
1423
+ case "t":
1424
+ result += " ";
1425
+ break;
1426
+ case "r":
1427
+ result += "\r";
1428
+ break;
1429
+ case "0":
1430
+ result += "\0";
1431
+ break;
1432
+ case "u": {
1433
+ const hex = body.slice(index + 1, index + 5);
1434
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw new YamlError("Invalid \\u escape.", number);
1435
+ result += String.fromCharCode(parseInt(hex, 16));
1436
+ index += 4;
1437
+ break;
1438
+ }
1439
+ default: throw new YamlError(`Unsupported escape "\\${escape ?? ""}".`, number);
1440
+ }
1441
+ }
1442
+ return result;
1443
+ }
1444
+ //#endregion
1445
+ //#region src/calibration/camera-info.ts
1446
+ /**
1447
+ * The file a calibration is exchanged in: a ROS `camera_info` YAML document.
1448
+ *
1449
+ * The profile contract is how this extension holds a calibration; it is not a format anyone outside
1450
+ * this family reads. A file an operator carries between machines is better written in the format
1451
+ * the tools they will meet already read, and for one camera's intrinsics that is the YAML that
1452
+ * ROS's `camera_calibration_parsers` reads and writes -- OpenCV-based pipelines, ROS and ROS 2
1453
+ * drivers, and SLAM tools load it as it is.
1454
+ *
1455
+ * ROS carries what projection needs and nothing about when or how the camera was configured, which
1456
+ * is exactly what deciding whether a profile still fits requires. Those members travel in one extra
1457
+ * top-level mapping, `turbowarp_camera_source`, named after their owner. ROS's reader looks keys up
1458
+ * by name and never enumerates the document, so a file with the extra mapping still loads there,
1459
+ * and a file without it is still ROS.
1460
+ *
1461
+ * A file that lacks the mapping altogether cannot become a profile: when it was calibrated and which
1462
+ * run it was are required members, and inventing either would turn "unknown" into a record.
1463
+ */
1464
+ /** The top-level key holding the members ROS has no place for. */
1465
+ var CAMERA_INFO_EXTENSION_KEY = "turbowarp_camera_source";
1466
+ var MATRIX_TOLERANCE = 1e-6;
1467
+ /**
1468
+ * Every top-level key a ROS file may have, and the extra mapping.
1469
+ *
1470
+ * Anything else is refused rather than dropped. A calibration file that carries a key nobody reads
1471
+ * is either from a tool that means something by it or has had something pasted into it, and a
1472
+ * profile validator that fails closed does not start ignoring members because they arrived in YAML.
1473
+ */
1474
+ var ROOT_KEYS = /* @__PURE__ */ new Set([
1475
+ "image_width",
1476
+ "image_height",
1477
+ "camera_name",
1478
+ "camera_matrix",
1479
+ "distortion_model",
1480
+ "distortion_coefficients",
1481
+ "rectification_matrix",
1482
+ "projection_matrix",
1483
+ "binning_x",
1484
+ "binning_y",
1485
+ "roi",
1486
+ CAMERA_INFO_EXTENSION_KEY
1487
+ ]);
1488
+ /** ROS distortion model names, as `sensor_msgs/distortion_models.hpp` spells them. */
1489
+ var PLUMB_BOB = "plumb_bob";
1490
+ var RATIONAL_POLYNOMIAL = "rational_polynomial";
1491
+ var EQUIDISTANT = "equidistant";
1492
+ var CameraInfoRejection = class extends Error {
1493
+ constructor(detail) {
1494
+ super(detail.message);
1495
+ this.detail = detail;
1496
+ }
1497
+ };
1498
+ function refuse(code, path, message) {
1499
+ throw new CameraInfoRejection({
1500
+ code,
1501
+ path,
1502
+ message
1503
+ });
1504
+ }
1505
+ /**
1506
+ * Renders a profile as a ROS `camera_info` YAML document.
1507
+ *
1508
+ * The layout follows what `camera_calibration_parsers` writes, key for key and in the same order, so
1509
+ * the file reads like one ROS produced. The projection matrix is the calibration matrix with a zero
1510
+ * fourth column, which is what a monocular camera with no rectification has; binning and region of
1511
+ * interest are left out, as ROS treats them as optional.
1512
+ *
1513
+ * Strings in the extra mapping are always double-quoted. A timestamp left plain is read as a date
1514
+ * by YAML 1.1 readers such as PyYAML, and an id made only of digits as a number.
1515
+ */
1516
+ function serializeCameraInfoYaml(profile) {
1517
+ const { fx, fy, cx, cy, skew } = profile.intrinsics;
1518
+ const { model, coefficients } = rosDistortion(profile);
1519
+ const lines = [
1520
+ `image_width: ${profile.image.width}`,
1521
+ `image_height: ${profile.image.height}`,
1522
+ `camera_name: ${plainOrQuoted(profile.cameraId)}`,
1523
+ ...matrix("camera_matrix", 3, 3, [
1524
+ fx,
1525
+ skew,
1526
+ cx,
1527
+ 0,
1528
+ fy,
1529
+ cy,
1530
+ 0,
1531
+ 0,
1532
+ 1
1533
+ ]),
1534
+ `distortion_model: ${model}`,
1535
+ ...matrix("distortion_coefficients", 1, coefficients.length, coefficients),
1536
+ ...matrix("rectification_matrix", 3, 3, [
1537
+ 1,
1538
+ 0,
1539
+ 0,
1540
+ 0,
1541
+ 1,
1542
+ 0,
1543
+ 0,
1544
+ 0,
1545
+ 1
1546
+ ]),
1547
+ ...matrix("projection_matrix", 3, 4, [
1548
+ fx,
1549
+ skew,
1550
+ cx,
1551
+ 0,
1552
+ 0,
1553
+ fy,
1554
+ cy,
1555
+ 0,
1556
+ 0,
1557
+ 0,
1558
+ 1,
1559
+ 0
1560
+ ]),
1561
+ `${CAMERA_INFO_EXTENSION_KEY}:`,
1562
+ ` schema: ${quoted(profile.schema)}`,
1563
+ ` version: ${profile.version}`,
1564
+ ` profileId: ${quoted(profile.profileId)}`,
1565
+ ` calibratedAt: ${quoted(profile.calibratedAt)}`,
1566
+ ` producer: ${quoted(profile.producer)}`,
1567
+ ` undistorted: ${profile.image.undistorted}`
1568
+ ];
1569
+ const capture = profile.capture;
1570
+ if (capture !== void 0) {
1571
+ lines.push(" capture:");
1572
+ if (Object.keys(capture).length === 0) lines[lines.length - 1] += " {}";
1573
+ appendMember(lines, "frameRate", capture.frameRate);
1574
+ appendMember(lines, "facingMode", capture.facingMode);
1575
+ appendMember(lines, "resizeMode", capture.resizeMode);
1576
+ appendMember(lines, "zoom", capture.zoom);
1577
+ appendMember(lines, "focusMode", capture.focusMode);
1578
+ appendMember(lines, "focusDistance", capture.focusDistance);
1579
+ }
1580
+ if (profile.quality !== void 0) {
1581
+ lines.push(" quality:");
1582
+ appendMember(lines, "sampleCount", profile.quality.sampleCount);
1583
+ appendMember(lines, "reprojectionErrorPx", profile.quality.reprojectionErrorPx);
1584
+ }
1585
+ if (profile.device !== void 0) {
1586
+ lines.push(" device:");
1587
+ if (Object.keys(profile.device).length === 0) lines[lines.length - 1] += " {}";
1588
+ appendMember(lines, "label", profile.device.label);
1589
+ appendMember(lines, "deviceId", profile.device.deviceId);
1590
+ }
1591
+ return `${lines.join("\n")}\n`;
1592
+ }
1593
+ /**
1594
+ * Turns a ROS `camera_info` YAML document into a profile document, ready to be validated.
1595
+ *
1596
+ * Only the shape ROS defines is checked here -- matrix sizes, the fixed entries of the calibration
1597
+ * matrix, a rectification that does nothing, a distortion model ROS names. Everything the profile
1598
+ * contract says about the values themselves is left to the profile validator, so there is one
1599
+ * place that decides whether a calibration is acceptable.
1600
+ */
1601
+ function readCameraInfoYaml(text) {
1602
+ let parsed;
1603
+ try {
1604
+ parsed = parseYaml(text);
1605
+ } catch (error) {
1606
+ if (error instanceof YamlError) return {
1607
+ ok: false,
1608
+ error: {
1609
+ code: "not-an-object",
1610
+ path: "",
1611
+ message: `The profile is not valid YAML. ${error.message}`
1612
+ }
1613
+ };
1614
+ throw error;
1615
+ }
1616
+ try {
1617
+ return {
1618
+ ok: true,
1619
+ document: toProfileDocument(parsed)
1620
+ };
1621
+ } catch (error) {
1622
+ if (error instanceof CameraInfoRejection) return {
1623
+ ok: false,
1624
+ error: error.detail
1625
+ };
1626
+ throw error;
1627
+ }
1628
+ }
1629
+ function toProfileDocument(parsed) {
1630
+ const root = record(parsed, "");
1631
+ for (const key of Object.keys(root)) if (!ROOT_KEYS.has(key)) refuse("unexpected-field", key, "Unknown member.");
1632
+ readBinningAndRoi(root);
1633
+ const width = root["image_width"];
1634
+ const height = root["image_height"];
1635
+ if (width === void 0) refuse("missing-field", "image_width", "Required member is missing.");
1636
+ if (height === void 0) refuse("missing-field", "image_height", "Required member is missing.");
1637
+ const k = readMatrix(root, "camera_matrix", 3, 3);
1638
+ expectEntries(k, "camera_matrix", [
1639
+ [3, 0],
1640
+ [6, 0],
1641
+ [7, 0],
1642
+ [8, 1]
1643
+ ]);
1644
+ if ("rectification_matrix" in root) expectEntries(readMatrix(root, "rectification_matrix", 3, 3), "rectification_matrix", [
1645
+ 1,
1646
+ 0,
1647
+ 0,
1648
+ 0,
1649
+ 1,
1650
+ 0,
1651
+ 0,
1652
+ 0,
1653
+ 1
1654
+ ].map((value, index) => [index, value]), "A rectification other than identity belongs to a stereo pair, not to one camera's intrinsics.");
1655
+ if ("projection_matrix" in root) readMatrix(root, "projection_matrix", 3, 4);
1656
+ const distortion = readDistortion(root);
1657
+ const extension = root[CAMERA_INFO_EXTENSION_KEY];
1658
+ if (extension === void 0) refuse("missing-field", CAMERA_INFO_EXTENSION_KEY, "The file is a ROS camera_info document without the calibration record: when it was calibrated and under which camera settings are not known.");
1659
+ const extra = record(extension, CAMERA_INFO_EXTENSION_KEY);
1660
+ const known = /* @__PURE__ */ new Set([
1661
+ "schema",
1662
+ "version",
1663
+ "profileId",
1664
+ "calibratedAt",
1665
+ "producer",
1666
+ "undistorted",
1667
+ "capture",
1668
+ "quality",
1669
+ "device"
1670
+ ]);
1671
+ for (const key of Object.keys(extra)) if (!known.has(key)) refuse("unexpected-field", `${CAMERA_INFO_EXTENSION_KEY}.${key}`, "Unknown member.");
1672
+ if (extra["schema"] !== "twcs/camera-intrinsics") refuse("unsupported-schema", `${CAMERA_INFO_EXTENSION_KEY}.schema`, `Expected ${JSON.stringify(CAMERA_INTRINSIC_PROFILE_SCHEMA)}.`);
1673
+ if (extra["version"] !== 1) refuse("unsupported-version", `${CAMERA_INFO_EXTENSION_KEY}.version`, `Expected 1.`);
1674
+ const undistorted = extra["undistorted"] ?? false;
1675
+ return {
1676
+ schema: CAMERA_INTRINSIC_PROFILE_SCHEMA,
1677
+ version: 1,
1678
+ profileId: extra["profileId"],
1679
+ cameraId: root["camera_name"],
1680
+ calibratedAt: extra["calibratedAt"],
1681
+ producer: extra["producer"],
1682
+ cameraModel: "pinhole",
1683
+ image: {
1684
+ width,
1685
+ height,
1686
+ undistorted
1687
+ },
1688
+ intrinsics: {
1689
+ fx: k[0],
1690
+ fy: k[4],
1691
+ cx: k[2],
1692
+ cy: k[5],
1693
+ skew: k[1]
1694
+ },
1695
+ distortion,
1696
+ ..."capture" in extra ? { capture: extra["capture"] } : {},
1697
+ ..."quality" in extra ? { quality: extra["quality"] } : {},
1698
+ ..."device" in extra ? { device: extra["device"] } : {}
1699
+ };
1700
+ }
1701
+ /**
1702
+ * Maps a ROS distortion model onto the profile's.
1703
+ *
1704
+ * `plumb_bob` coefficients that are all zero read as no distortion. ROS has no model for "none"; a
1705
+ * lens-free image is written as plumb_bob with five zeros, and reading it back must not invent a
1706
+ * Brown-Conrady lens that happens to do nothing.
1707
+ */
1708
+ function readDistortion(root) {
1709
+ const rawModel = root["distortion_model"] ?? PLUMB_BOB;
1710
+ const coefficients = readMatrix(root, "distortion_coefficients", 1, void 0);
1711
+ switch (rawModel) {
1712
+ case PLUMB_BOB:
1713
+ if (coefficients.length !== 4 && coefficients.length !== 5) refuse("invalid-distortion", "distortion_coefficients", `plumb_bob takes 5 coefficients, not ${coefficients.length}.`);
1714
+ return isAllZero(coefficients) ? {
1715
+ model: "none",
1716
+ coefficients: []
1717
+ } : {
1718
+ model: "brown-conrady",
1719
+ coefficients
1720
+ };
1721
+ case RATIONAL_POLYNOMIAL:
1722
+ if (coefficients.length !== 8) refuse("invalid-distortion", "distortion_coefficients", `rational_polynomial takes 8 coefficients, not ${coefficients.length}.`);
1723
+ return {
1724
+ model: "brown-conrady",
1725
+ coefficients
1726
+ };
1727
+ case EQUIDISTANT:
1728
+ if (coefficients.length !== 4) refuse("invalid-distortion", "distortion_coefficients", `equidistant takes 4 coefficients, not ${coefficients.length}.`);
1729
+ return {
1730
+ model: "kannala-brandt",
1731
+ coefficients
1732
+ };
1733
+ default: refuse("invalid-distortion", "distortion_model", `Expected ${PLUMB_BOB}, ${RATIONAL_POLYNOMIAL} or ${EQUIDISTANT}.`);
1734
+ }
1735
+ }
1736
+ /**
1737
+ * Binning and a region of interest change which pixels the calibration describes. ROS writes both
1738
+ * with their do-nothing values, and only those are accepted: a calibration of a binned or cropped
1739
+ * image is a different calibration, and reading it as the full frame's would move the principal
1740
+ * point without anyone noticing.
1741
+ */
1742
+ function readBinningAndRoi(root) {
1743
+ for (const name of ["binning_x", "binning_y"]) {
1744
+ const value = root[name];
1745
+ if (value !== void 0 && value !== 0 && value !== 1) refuse("inconsistent-profile", name, "A binned image is not the image the calibration describes.");
1746
+ }
1747
+ const roi = root["roi"];
1748
+ if (roi === void 0) return;
1749
+ const region = record(roi, "roi");
1750
+ const width = region["width"] ?? 0;
1751
+ const height = region["height"] ?? 0;
1752
+ const offsetX = region["x_offset"] ?? 0;
1753
+ const offsetY = region["y_offset"] ?? 0;
1754
+ const whole = width === 0 && height === 0;
1755
+ const full = width === root["image_width"] && height === root["image_height"];
1756
+ if (offsetX !== 0 || offsetY !== 0 || !(whole || full)) refuse("inconsistent-profile", "roi", "A region of interest is not the image the calibration describes.");
1757
+ }
1758
+ function rosDistortion(profile) {
1759
+ const coefficients = [...profile.distortion.coefficients];
1760
+ switch (profile.distortion.model) {
1761
+ case "none": return {
1762
+ model: PLUMB_BOB,
1763
+ coefficients: [
1764
+ 0,
1765
+ 0,
1766
+ 0,
1767
+ 0,
1768
+ 0
1769
+ ]
1770
+ };
1771
+ case "kannala-brandt": return {
1772
+ model: EQUIDISTANT,
1773
+ coefficients
1774
+ };
1775
+ case "brown-conrady":
1776
+ if (coefficients.length === 8) return {
1777
+ model: RATIONAL_POLYNOMIAL,
1778
+ coefficients
1779
+ };
1780
+ return {
1781
+ model: PLUMB_BOB,
1782
+ coefficients: coefficients.length === 4 ? [...coefficients, 0] : coefficients
1783
+ };
1784
+ }
1785
+ }
1786
+ function readMatrix(root, name, rows, cols) {
1787
+ const value = root[name];
1788
+ if (value === void 0) refuse("missing-field", name, "Required member is missing.");
1789
+ const matrix = record(value, name);
1790
+ const declaredRows = matrix["rows"];
1791
+ const declaredCols = matrix["cols"];
1792
+ const data = matrix["data"];
1793
+ if (declaredRows !== rows) refuse("invalid-value", `${name}.rows`, `Expected ${rows}.`);
1794
+ if (cols !== void 0 && declaredCols !== cols) refuse("invalid-value", `${name}.cols`, `Expected ${cols}.`);
1795
+ if (typeof declaredCols !== "number" || !Number.isInteger(declaredCols) || declaredCols < 0) refuse("invalid-value", `${name}.cols`, "Expected a column count.");
1796
+ if (!Array.isArray(data)) refuse("invalid-type", `${name}.data`, "Expected a sequence of numbers.");
1797
+ if (data.length !== rows * declaredCols) refuse("invalid-value", `${name}.data`, `Expected ${rows * declaredCols} numbers for a ${rows}x${declaredCols} matrix, not ${data.length}.`);
1798
+ return data.map((entry, index) => {
1799
+ if (typeof entry !== "number" || !Number.isFinite(entry)) refuse("invalid-type", `${name}.data[${index}]`, "Expected a number.");
1800
+ return entry;
1801
+ });
1802
+ }
1803
+ function expectEntries(data, name, entries, message) {
1804
+ for (const [index, expected] of entries) if (Math.abs(data[index] - expected) > MATRIX_TOLERANCE) refuse("inconsistent-profile", `${name}.data[${index}]`, message ?? `Expected ${expected}; the value read as ${data[index]}.`);
1805
+ }
1806
+ function record(value, path) {
1807
+ if (typeof value !== "object" || value === null || Array.isArray(value)) refuse("not-an-object", path, "Expected a mapping.");
1808
+ return value;
1809
+ }
1810
+ function isAllZero(values) {
1811
+ return values.every((value) => value === 0);
1812
+ }
1813
+ function matrix(name, rows, cols, data) {
1814
+ return [
1815
+ `${name}:`,
1816
+ ` rows: ${rows}`,
1817
+ ` cols: ${cols}`,
1818
+ ` data: [${data.map(number).join(", ")}]`
1819
+ ];
1820
+ }
1821
+ /** Numbers as JavaScript writes them, which is the shortest text that reads back to the same value. */
1822
+ function number(value) {
1823
+ return Object.is(value, -0) ? "0" : String(value);
1824
+ }
1825
+ function quoted(text) {
1826
+ return JSON.stringify(text);
1827
+ }
1828
+ /** Camera names are identifiers and read the same plain, which is how ROS writes them. */
1829
+ function plainOrQuoted(text) {
1830
+ return /^[A-Za-z][A-Za-z0-9._-]*$/.test(text) && !/^(?:true|false|null|yes|no|on|off|y|n)$/i.test(text) ? text : quoted(text);
1831
+ }
1832
+ function appendMember(lines, name, value) {
1833
+ if (value === void 0) return;
1834
+ lines.push(` ${name}: ${typeof value === "string" ? quoted(value) : number(value)}`);
1835
+ }
1836
+ //#endregion
1837
+ //#region src/calibration/profile-text.ts
1838
+ /**
1839
+ * Profile text as an operator hands it over: a ROS `camera_info` YAML file, or profile JSON.
1840
+ *
1841
+ * The operator does not know which one a file is and should not have to. JSON always starts with a
1842
+ * brace; a calibration YAML file never does, because its top level is a block mapping. That one
1843
+ * character decides, and each branch names what it expected when the text is not what it looked
1844
+ * like.
1845
+ */
1846
+ function readProfileText(text) {
1847
+ const trimmed = text.trim();
1848
+ if (trimmed.length === 0) return {
1849
+ ok: false,
1850
+ error: {
1851
+ code: "not-an-object",
1852
+ path: "",
1853
+ message: "The profile is empty."
1854
+ }
1855
+ };
1856
+ if (trimmed.startsWith("{")) try {
1857
+ return {
1858
+ ok: true,
1859
+ document: JSON.parse(trimmed)
1860
+ };
1861
+ } catch {
1862
+ return {
1863
+ ok: false,
1864
+ error: {
1865
+ code: "not-an-object",
1866
+ path: "",
1867
+ message: "The profile is not valid JSON."
1868
+ }
1869
+ };
1870
+ }
1871
+ return readCameraInfoYaml(trimmed);
1872
+ }
1873
+ //#endregion
1874
+ //#region src/calibration/store.ts
1875
+ /**
1876
+ * Profiles kept in the browser between sessions.
1877
+ *
1878
+ * A cache, not a backup. IndexedDB belongs to one origin in one browser profile, and the browser may
1879
+ * evict it; the exported file stays the thing an operator keeps. What this buys is the common case:
1880
+ * the calibration app and the app that uses its result are served from the same origin, so a solve
1881
+ * saved in one window can be picked up by the other without a file changing hands.
1882
+ *
1883
+ * The store holds documents and says nothing about whether one fits a camera. That is decided when
1884
+ * a profile is restored, against the camera as it is then, by the same validation and compatibility
1885
+ * rules every other way in goes through.
1886
+ */
1887
+ var cameraProfileDatabaseName = "kubohiroya-camera-source";
1888
+ var cameraProfileObjectStoreName = "camera-profiles";
1889
+ /** Other windows on the same origin hear about a save here. The message is `{profileId}`. */
1890
+ var cameraProfileChannelName = "kubohiroya-camera-source:camera-profiles";
1891
+ function isText(value) {
1892
+ return typeof value === "string";
1893
+ }
1894
+ /**
1895
+ * Whether a value read back has the shape of a record.
1896
+ *
1897
+ * The database outlives this build. Anything another version, or a developer console, left behind is
1898
+ * skipped here rather than handed on as if this build had written it.
1899
+ */
1900
+ function isStoredCameraProfile(value) {
1901
+ if (typeof value !== "object" || value === null) return false;
1902
+ const record = value;
1903
+ return isText(record["profileId"]) && isText(record["cameraId"]) && isText(record["calibratedAt"]) && isText(record["savedAt"]) && isText(record["document"]) && (record["deviceLabel"] === void 0 || isText(record["deviceLabel"]));
1904
+ }
1905
+ function settle(request) {
1906
+ return new Promise((resolve, reject) => {
1907
+ request.onsuccess = () => resolve(request.result);
1908
+ request.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error("IndexedDB request failed."));
1909
+ });
1910
+ }
1911
+ /**
1912
+ * The IndexedDB store.
1913
+ *
1914
+ * The database is opened on first use, not on construction: every project that loads this extension
1915
+ * would otherwise create it, including the ones that never save a profile. A failed open is not
1916
+ * remembered, so a later call gets another attempt instead of inheriting one bad moment for good.
1917
+ */
1918
+ function createIndexedDbCameraProfileStore(factory = globalThis.indexedDB) {
1919
+ let opening;
1920
+ const database = () => {
1921
+ if (!factory) return Promise.reject(/* @__PURE__ */ new Error("IndexedDB is not available."));
1922
+ if (!opening) {
1923
+ const request = factory.open(cameraProfileDatabaseName, 1);
1924
+ request.onupgradeneeded = () => {
1925
+ if (!request.result.objectStoreNames.contains("camera-profiles")) request.result.createObjectStore(cameraProfileObjectStoreName, { keyPath: "profileId" });
1926
+ };
1927
+ opening = settle(request).then((db) => {
1928
+ db.onversionchange = () => {
1929
+ db.close();
1930
+ opening = void 0;
1931
+ };
1932
+ return db;
1933
+ });
1934
+ opening.catch(() => {
1935
+ opening = void 0;
1936
+ });
1937
+ }
1938
+ return opening;
1939
+ };
1940
+ return {
1941
+ async list() {
1942
+ return (await settle((await database()).transaction(cameraProfileObjectStoreName, "readonly").objectStore(cameraProfileObjectStoreName).getAll())).filter(isStoredCameraProfile);
1943
+ },
1944
+ async put(record) {
1945
+ const transaction = (await database()).transaction(cameraProfileObjectStoreName, "readwrite");
1946
+ transaction.objectStore(cameraProfileObjectStoreName).put(record);
1947
+ await new Promise((resolve, reject) => {
1948
+ transaction.oncomplete = () => resolve();
1949
+ transaction.onerror = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB write failed."));
1950
+ transaction.onabort = () => reject(transaction.error ?? /* @__PURE__ */ new Error("IndexedDB write aborted."));
1951
+ });
1952
+ }
1953
+ };
1954
+ }
1955
+ //#endregion
1025
1956
  //#region src/runtime.ts
1026
1957
  /**
1027
1958
  * Where the extension instance puts itself on the VM runtime.
@@ -1316,6 +2247,49 @@
1316
2247
  function previewFlipOf(options) {
1317
2248
  return toFlip(options.previewFlip);
1318
2249
  }
2250
+ /** The document with its camera id replaced, or the value untouched when it is not an object. */
2251
+ function rebindCameraId(document, cameraId) {
2252
+ if (typeof document !== "object" || document === null || Array.isArray(document)) return document;
2253
+ return {
2254
+ ...document,
2255
+ cameraId
2256
+ };
2257
+ }
2258
+ function parseJson(text) {
2259
+ try {
2260
+ return {
2261
+ ok: true,
2262
+ value: JSON.parse(text)
2263
+ };
2264
+ } catch {
2265
+ return { ok: false };
2266
+ }
2267
+ }
2268
+ /** Which saved profile, in words an operator can match against the file they exported. */
2269
+ function describeStoredProfile(profile) {
2270
+ const label = profile.device?.label;
2271
+ return `Profile ${profile.profileId} calibrated at ${profile.calibratedAt}${label ? ` on ${label}` : ""}.`;
2272
+ }
2273
+ function compatibilityDetail(report) {
2274
+ const findings = decisiveFindings(report);
2275
+ if (findings.length === 0) return "The profile matches the camera as configured.";
2276
+ return findings.map((entry) => entry.detail).join(" ");
2277
+ }
2278
+ /**
2279
+ * Newest calibration first.
2280
+ *
2281
+ * Timestamps are compared as instants, so an offset other than `Z` still sorts where it belongs. One
2282
+ * that does not parse sorts last: it cannot be shown to be newer than anything.
2283
+ */
2284
+ function newestFirst(left, right) {
2285
+ const instant = (text) => {
2286
+ const value = Date.parse(text);
2287
+ return Number.isFinite(value) ? value : Number.NEGATIVE_INFINITY;
2288
+ };
2289
+ const byCalibration = instant(right.calibratedAt) - instant(left.calibratedAt);
2290
+ if (byCalibration !== 0 && !Number.isNaN(byCalibration)) return byCalibration;
2291
+ return instant(right.savedAt) - instant(left.savedAt) || 0;
2292
+ }
1319
2293
  function cameraFailure(error) {
1320
2294
  if (error instanceof Error) return {
1321
2295
  code: error.name || "Error",
@@ -1327,7 +2301,7 @@
1327
2301
  };
1328
2302
  }
1329
2303
  var CameraSourceExtension = class {
1330
- constructor() {
2304
+ constructor(options = {}) {
1331
2305
  this.sessions = /* @__PURE__ */ new Map();
1332
2306
  this.blockLeases = /* @__PURE__ */ new Map();
1333
2307
  this.blockPreviewLeases = /* @__PURE__ */ new Map();
@@ -1338,10 +2312,13 @@
1338
2312
  this.lastConditions = /* @__PURE__ */ new Map();
1339
2313
  this.assessments = /* @__PURE__ */ new Map();
1340
2314
  this.devices = [];
2315
+ this.storedProfileOutcomes = /* @__PURE__ */ new Map();
2316
+ this.storedProfilesGeneration = 0;
1341
2317
  this.dispose = () => {
1342
2318
  this.stopAllCameras();
1343
2319
  const runtime = Scratch.vm.runtime;
1344
2320
  if (runtime["kubohiroyaCameraSourceCapability"] === this.capability) delete runtime[cameraSourceCapabilityKey];
2321
+ this.profileChannel?.close();
1345
2322
  Scratch.vm.runtime.off?.("PROJECT_STOP_ALL", this.handleProjectBoundary);
1346
2323
  Scratch.vm.runtime.off?.("PROJECT_LOADED", this.handleProjectBoundary);
1347
2324
  Scratch.vm.runtime.off?.("RUNTIME_DISPOSED", this.dispose);
@@ -1349,7 +2326,10 @@
1349
2326
  this.handleProjectBoundary = () => {
1350
2327
  this.stopAllCameras();
1351
2328
  this.profileError = void 0;
2329
+ this.storedProfileOutcomes.clear();
1352
2330
  };
2331
+ this.profileStore = options.profileStore ?? createIndexedDbCameraProfileStore();
2332
+ this.profileChannel = this.openProfileChannel();
1353
2333
  Scratch.vm.runtime[cameraSourceRuntimeKey] = this;
1354
2334
  this.capability = createRuntimeCapability({
1355
2335
  registerProfile: (document) => this.profiles.register(document),
@@ -1505,20 +2485,132 @@
1505
2485
  this.blockPreviewLeases.clear();
1506
2486
  }
1507
2487
  registerCameraProfile(args = {}) {
1508
- const text = Scratch.Cast.toString(args.PROFILE_JSON ?? "");
1509
- let document;
2488
+ this.registerProfileText(args.PROFILE_JSON, (document) => document);
2489
+ }
2490
+ /**
2491
+ * Registers a profile under the camera id the project names, whatever id the document carries.
2492
+ *
2493
+ * The id in a document is the name the camera had where it was solved. A calibration app knows one
2494
+ * camera and calls it `default`; the app that uses the result may call the same camera `pose`.
2495
+ * Rebinding happens before validation, so the document is checked as the profile it is about to
2496
+ * become rather than as the one it was.
2497
+ */
2498
+ registerCameraProfileAs(args = {}) {
2499
+ const cameraId = normalizeId(args.CAMERA_ID);
2500
+ this.registerProfileText(args.PROFILE_JSON, (document) => rebindCameraId(document, cameraId));
2501
+ }
2502
+ /**
2503
+ * Writes the profile registered for a camera to browser storage.
2504
+ *
2505
+ * Only a registered profile can be saved, so whatever reaches storage has already passed
2506
+ * validation. Other windows on the origin are told once the write has committed, not before: a
2507
+ * window that went looking on the strength of an uncommitted write would find nothing and conclude
2508
+ * there was nothing to find.
2509
+ */
2510
+ async saveCameraProfile(args = {}) {
2511
+ const cameraId = normalizeId(args.CAMERA_ID);
2512
+ const profile = this.profiles.get(cameraId);
2513
+ if (!profile) {
2514
+ this.storedProfileOutcomes.set(cameraId, {
2515
+ state: "no-profile",
2516
+ detail: ""
2517
+ });
2518
+ return;
2519
+ }
2520
+ const label = profile.device?.label;
2521
+ const record = {
2522
+ profileId: profile.profileId,
2523
+ cameraId: profile.cameraId,
2524
+ calibratedAt: profile.calibratedAt,
2525
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
2526
+ ...label === void 0 ? {} : { deviceLabel: label },
2527
+ document: serializeCameraIntrinsicProfile(profile)
2528
+ };
1510
2529
  try {
1511
- document = JSON.parse(text);
2530
+ await this.profileStore.put(record);
1512
2531
  } catch {
1513
- this.profileError = {
1514
- code: "not-an-object",
1515
- path: "",
1516
- message: "The profile is not valid JSON."
1517
- };
2532
+ this.storedProfileOutcomes.set(cameraId, {
2533
+ state: "unavailable",
2534
+ detail: ""
2535
+ });
1518
2536
  return;
1519
2537
  }
1520
- const result = this.profiles.register(document);
1521
- this.profileError = result.ok ? void 0 : result.error;
2538
+ this.storedProfilesGeneration += 1;
2539
+ this.storedProfileOutcomes.set(cameraId, {
2540
+ state: "saved",
2541
+ detail: describeStoredProfile(profile)
2542
+ });
2543
+ try {
2544
+ this.profileChannel?.postMessage({ profileId: profile.profileId });
2545
+ } catch {}
2546
+ }
2547
+ /**
2548
+ * Registers the newest saved profile that fits the camera as it is configured now.
2549
+ *
2550
+ * Fails closed. Only a `compatible` verdict registers anything; `undetermined` is not a weaker yes,
2551
+ * and a camera that has not delivered a frame yet cannot be shown to match any calibration. When
2552
+ * nothing qualifies, whatever is already registered for the camera stays exactly as it was: a
2553
+ * restore that found nothing usable has no business taking away a profile that was.
2554
+ *
2555
+ * Every candidate is judged against the conditions directly, without going through the registry,
2556
+ * so trying a candidate that loses never displaces the registered one even for a moment.
2557
+ */
2558
+ async restoreStoredCameraProfile(args = {}) {
2559
+ const cameraId = normalizeId(args.CAMERA_ID);
2560
+ let records;
2561
+ try {
2562
+ records = await this.profileStore.list();
2563
+ } catch {
2564
+ this.storedProfileOutcomes.set(cameraId, {
2565
+ state: "unavailable",
2566
+ detail: ""
2567
+ });
2568
+ return;
2569
+ }
2570
+ const conditions = this.conditionsOf(cameraId);
2571
+ let incompatible;
2572
+ let undetermined;
2573
+ for (const record of [...records].sort(newestFirst)) {
2574
+ const parsed = parseJson(record.document);
2575
+ if (!parsed.ok) continue;
2576
+ const document = rebindCameraId(parsed.value, cameraId);
2577
+ const result = readCameraProfileDocument(document);
2578
+ if (!result.ok) continue;
2579
+ const report = evaluateProfileCompatibility(result.profile, conditions);
2580
+ if (report.state === "compatible") {
2581
+ this.profiles.register(document);
2582
+ this.storedProfileOutcomes.set(cameraId, {
2583
+ state: "restored",
2584
+ detail: describeStoredProfile(result.profile)
2585
+ });
2586
+ return;
2587
+ }
2588
+ if (report.state === "incompatible") incompatible ?? (incompatible = report);
2589
+ else undetermined ?? (undetermined = report);
2590
+ }
2591
+ const decisive = incompatible ?? undetermined;
2592
+ this.storedProfileOutcomes.set(cameraId, decisive === void 0 ? {
2593
+ state: "none",
2594
+ detail: ""
2595
+ } : {
2596
+ state: decisive.state,
2597
+ detail: compatibilityDetail(decisive)
2598
+ });
2599
+ }
2600
+ storedCameraProfileResult(args = {}) {
2601
+ return this.storedProfileOutcomes.get(normalizeId(args.CAMERA_ID))?.state ?? "";
2602
+ }
2603
+ storedCameraProfileDetail(args = {}) {
2604
+ return this.storedProfileOutcomes.get(normalizeId(args.CAMERA_ID))?.detail ?? "";
2605
+ }
2606
+ /**
2607
+ * A counter that moves whenever a profile is saved, here or in another window on this origin.
2608
+ *
2609
+ * A project waiting for the calibration app compares this integer rather than polling storage: it
2610
+ * restores when the number moves, and the restore decides whether what arrived is usable.
2611
+ */
2612
+ storedCameraProfilesGeneration() {
2613
+ return this.storedProfilesGeneration;
1522
2614
  }
1523
2615
  forgetCameraProfile(args = {}) {
1524
2616
  this.profiles.forget(normalizeId(args.CAMERA_ID));
@@ -1530,6 +2622,18 @@
1530
2622
  const profile = this.profiles.get(normalizeId(args.CAMERA_ID));
1531
2623
  return profile ? serializeCameraIntrinsicProfile(profile) : "";
1532
2624
  }
2625
+ /**
2626
+ * The registered profile as a ROS `camera_info` YAML document, which is how a calibration is
2627
+ * written to a file or handed to another machine.
2628
+ *
2629
+ * The standard part loads in ROS and OpenCV-based tools as it is. What deciding compatibility needs
2630
+ * and ROS has no place for travels in the `turbowarp_camera_source` mapping, which ROS's reader
2631
+ * does not look at.
2632
+ */
2633
+ cameraProfileYaml(args = {}) {
2634
+ const profile = this.profiles.get(normalizeId(args.CAMERA_ID));
2635
+ return profile ? serializeCameraInfoYaml(profile) : "";
2636
+ }
1533
2637
  cameraProfileError() {
1534
2638
  return this.profileError?.code ?? "";
1535
2639
  }
@@ -1545,10 +2649,7 @@
1545
2649
  cameraProfileCompatibilityDetail(args = {}) {
1546
2650
  const cameraId = normalizeId(args.CAMERA_ID);
1547
2651
  const assessment = this.assessmentOf(cameraId);
1548
- if (assessment === void 0) return "";
1549
- const findings = decisiveFindings(assessment.compatibility);
1550
- if (findings.length === 0) return "The profile matches the camera as configured.";
1551
- return findings.map((entry) => entry.detail).join(" ");
2652
+ return assessment === void 0 ? "" : compatibilityDetail(assessment.compatibility);
1552
2653
  }
1553
2654
  cameraProfileAdaptation(args = {}) {
1554
2655
  const cameraId = normalizeId(args.CAMERA_ID);
@@ -1565,6 +2666,41 @@
1565
2666
  cameraConditionsGeneration(args = {}) {
1566
2667
  return this.generationOf(normalizeId(args.CAMERA_ID));
1567
2668
  }
2669
+ /**
2670
+ * Registers profile text, whichever of the two forms an operator was handed.
2671
+ *
2672
+ * A ROS `camera_info` YAML file is what the calibration app writes and what leaves the PC; profile
2673
+ * JSON is what this extension renders and stores. Both reach the same validator, so a file is
2674
+ * accepted or refused for the same reasons whichever form it came in.
2675
+ */
2676
+ registerProfileText(value, prepare) {
2677
+ const parsed = readProfileText(Scratch.Cast.toString(value ?? ""));
2678
+ if (!parsed.ok) {
2679
+ this.profileError = parsed.error;
2680
+ return;
2681
+ }
2682
+ const result = this.profiles.register(prepare(parsed.document));
2683
+ this.profileError = result.ok ? void 0 : result.error;
2684
+ }
2685
+ /**
2686
+ * Listens for saves made in other windows on this origin.
2687
+ *
2688
+ * Absent where the browser has no BroadcastChannel. The generation then moves only for saves made
2689
+ * here, and a project still finds another window's profile the next time it restores.
2690
+ */
2691
+ openProfileChannel() {
2692
+ const Channel = globalThis.BroadcastChannel;
2693
+ if (typeof Channel !== "function") return void 0;
2694
+ try {
2695
+ const channel = new Channel(cameraProfileChannelName);
2696
+ channel.onmessage = () => {
2697
+ this.storedProfilesGeneration += 1;
2698
+ };
2699
+ return channel;
2700
+ } catch {
2701
+ return;
2702
+ }
2703
+ }
1568
2704
  /** What the track reports about itself right now. Read only. */
1569
2705
  intrinsicsOf(cameraId) {
1570
2706
  const id = normalizeId(cameraId);