@photivra/engine 2.19.0 → 2.21.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.
Files changed (242) hide show
  1. package/CHANGELOG.md +289 -1
  2. package/CITATION.cff +1 -1
  3. package/NODE_SUPPORT.md +7 -5
  4. package/README.md +7 -6
  5. package/SECURITY.md +1 -1
  6. package/THIRD_PARTY.md +21 -10
  7. package/dist/capture/dng-lens-correction-opcodes.d.ts +32 -0
  8. package/dist/capture/dng-lens-correction-opcodes.js +119 -0
  9. package/dist/capture/dng-lens-correction-opcodes.js.map +1 -0
  10. package/dist/capture/exposure-build-up-stage.d.ts +16 -0
  11. package/dist/capture/exposure-build-up-stage.js +4 -0
  12. package/dist/capture/exposure-build-up-stage.js.map +1 -0
  13. package/dist/capture/native-environment-lean.d.ts +2 -1
  14. package/dist/capture/native-environment-lean.js +42 -78
  15. package/dist/capture/native-environment-lean.js.map +1 -1
  16. package/dist/capture/native-environment-tabulated.js +4 -3
  17. package/dist/capture/native-environment-tabulated.js.map +1 -1
  18. package/dist/capture/native-raw-dng.d.ts +6 -0
  19. package/dist/capture/native-raw-dng.js +16 -2
  20. package/dist/capture/native-raw-dng.js.map +1 -1
  21. package/dist/capture/native-raw.d.ts +3 -2
  22. package/dist/capture/native-raw.js +5 -4
  23. package/dist/capture/native-raw.js.map +1 -1
  24. package/dist/capture/sensor-raw-producer.d.ts +4 -1
  25. package/dist/capture/sensor-raw-producer.js +15 -8
  26. package/dist/capture/sensor-raw-producer.js.map +1 -1
  27. package/dist/core/shared-helpers.d.ts +2 -0
  28. package/dist/core/shared-helpers.js +4 -0
  29. package/dist/core/shared-helpers.js.map +1 -1
  30. package/dist/core/version.d.ts +1 -1
  31. package/dist/core/version.js +1 -1
  32. package/dist/core/version.js.map +1 -1
  33. package/dist/equipment/generic-lens-catalogue.d.ts +11 -4
  34. package/dist/equipment/generic-lens-catalogue.js +49 -7
  35. package/dist/equipment/generic-lens-catalogue.js.map +1 -1
  36. package/dist/equipment/generic-tier-assets.d.ts +32 -0
  37. package/dist/equipment/generic-tier-assets.js +18 -14
  38. package/dist/equipment/generic-tier-assets.js.map +1 -1
  39. package/dist/equipment/generic-tier-presets.js +2 -3
  40. package/dist/equipment/generic-tier-presets.js.map +1 -1
  41. package/dist/equipment/sensor-profile-body.d.ts +78 -0
  42. package/dist/equipment/sensor-profile-body.js +77 -0
  43. package/dist/equipment/sensor-profile-body.js.map +1 -0
  44. package/dist/equipment/sensor-profiles.d.ts +8 -0
  45. package/dist/equipment/sensor-profiles.js +82 -0
  46. package/dist/equipment/sensor-profiles.js.map +1 -0
  47. package/dist/facade/catalogue-lens-signal.d.ts +2 -2
  48. package/dist/facade/catalogue-lens-signal.js +58 -71
  49. package/dist/facade/catalogue-lens-signal.js.map +1 -1
  50. package/dist/facade/chart-radiance-batch.js +2 -1
  51. package/dist/facade/chart-radiance-batch.js.map +1 -1
  52. package/dist/facade/defocus-image-space-provider.d.ts +7 -0
  53. package/dist/facade/defocus-image-space-provider.js +64 -76
  54. package/dist/facade/defocus-image-space-provider.js.map +1 -1
  55. package/dist/facade/display-view-gpu-session.js +2 -0
  56. package/dist/facade/display-view-gpu-session.js.map +1 -1
  57. package/dist/facade/display-view-gpu.d.ts +13 -5
  58. package/dist/facade/display-view-gpu.js +4 -4
  59. package/dist/facade/display-view-gpu.js.map +1 -1
  60. package/dist/facade/display-view-lens-signal.d.ts +1 -1
  61. package/dist/facade/display-view-lens-signal.js +30 -26
  62. package/dist/facade/display-view-lens-signal.js.map +1 -1
  63. package/dist/facade/display-view.d.ts +3 -1
  64. package/dist/facade/display-view.js +6 -24
  65. package/dist/facade/display-view.js.map +1 -1
  66. package/dist/facade/expected-signal-setup.d.ts +3 -1
  67. package/dist/facade/expected-signal-setup.js +1 -1
  68. package/dist/facade/expected-signal-setup.js.map +1 -1
  69. package/dist/facade/expected-signal.d.ts +47 -14
  70. package/dist/facade/expected-signal.js +117 -112
  71. package/dist/facade/expected-signal.js.map +1 -1
  72. package/dist/facade/exposure-build-up.d.ts +70 -0
  73. package/dist/facade/exposure-build-up.js +164 -0
  74. package/dist/facade/exposure-build-up.js.map +1 -0
  75. package/dist/facade/fast-methods.d.ts +50 -0
  76. package/dist/facade/fast-methods.js +58 -0
  77. package/dist/facade/fast-methods.js.map +1 -0
  78. package/dist/facade/fast-resolution.d.ts +12 -0
  79. package/dist/facade/fast-resolution.js +18 -0
  80. package/dist/facade/fast-resolution.js.map +1 -0
  81. package/dist/facade/generic-lens-capture.d.ts +5 -4
  82. package/dist/facade/generic-lens-capture.js +5 -4
  83. package/dist/facade/generic-lens-capture.js.map +1 -1
  84. package/dist/facade/image-plane-enable.d.ts +7 -0
  85. package/dist/facade/image-plane-enable.js +17 -0
  86. package/dist/facade/image-plane-enable.js.map +1 -0
  87. package/dist/facade/image-plane-lattice-data.d.ts +6 -0
  88. package/dist/facade/image-plane-lattice-data.js +10 -0
  89. package/dist/facade/image-plane-lattice-data.js.map +1 -0
  90. package/dist/facade/image-plane-support.d.ts +33 -0
  91. package/dist/facade/image-plane-support.js +11 -0
  92. package/dist/facade/image-plane-support.js.map +1 -0
  93. package/dist/facade/image-plane.d.ts +36 -0
  94. package/dist/facade/image-plane.js +353 -0
  95. package/dist/facade/image-plane.js.map +1 -0
  96. package/dist/facade/mixed-illumination.d.ts +108 -0
  97. package/dist/facade/mixed-illumination.js +174 -0
  98. package/dist/facade/mixed-illumination.js.map +1 -0
  99. package/dist/facade/representative-light-sources.d.ts +72 -0
  100. package/dist/facade/representative-light-sources.js +124 -0
  101. package/dist/facade/representative-light-sources.js.map +1 -0
  102. package/dist/facade/scene-radiance.d.ts +129 -4
  103. package/dist/facade/scene-radiance.js +48 -13
  104. package/dist/facade/scene-radiance.js.map +1 -1
  105. package/dist/facade/simulate-capture.d.ts +88 -19
  106. package/dist/facade/simulate-capture.js +374 -145
  107. package/dist/facade/simulate-capture.js.map +1 -1
  108. package/dist/facade/simulate-display-view.d.ts +3 -2
  109. package/dist/facade/simulate-display-view.js +36 -18
  110. package/dist/facade/simulate-display-view.js.map +1 -1
  111. package/dist/gpu/chart-composite-gpu.d.ts +13 -1
  112. package/dist/gpu/chart-composite-gpu.js +48 -9
  113. package/dist/gpu/chart-composite-gpu.js.map +1 -1
  114. package/dist/gpu/chart-radiance-gpu.js +4 -30
  115. package/dist/gpu/chart-radiance-gpu.js.map +1 -1
  116. package/dist/gpu/display-view-composite-material-module.d.ts +10 -4
  117. package/dist/gpu/display-view-composite-material-module.js +39 -13
  118. package/dist/gpu/display-view-composite-material-module.js.map +1 -1
  119. package/dist/gpu/display-view-image-material-module.d.ts +86 -0
  120. package/dist/gpu/display-view-image-material-module.js +339 -0
  121. package/dist/gpu/display-view-image-material-module.js.map +1 -0
  122. package/dist/gpu/display-view-image-quality.d.ts +45 -0
  123. package/dist/gpu/display-view-image-quality.js +380 -0
  124. package/dist/gpu/display-view-image-quality.js.map +1 -0
  125. package/dist/gpu/display-view-quality-gpu.d.ts +67 -1
  126. package/dist/gpu/display-view-quality-gpu.js +136 -205
  127. package/dist/gpu/display-view-quality-gpu.js.map +1 -1
  128. package/dist/gpu/display-view-speed-gpu.d.ts +51 -3
  129. package/dist/gpu/display-view-speed-gpu.js +131 -93
  130. package/dist/gpu/display-view-speed-gpu.js.map +1 -1
  131. package/dist/gpu/wgsl-display-view-quality-kernel.d.ts +29 -15
  132. package/dist/gpu/wgsl-display-view-quality-kernel.js +58 -36
  133. package/dist/gpu/wgsl-display-view-quality-kernel.js.map +1 -1
  134. package/dist/gpu/wgsl-display-view-speed-kernel.d.ts +21 -6
  135. package/dist/gpu/wgsl-display-view-speed-kernel.js +46 -11
  136. package/dist/gpu/wgsl-display-view-speed-kernel.js.map +1 -1
  137. package/dist/gpu/wgsl-exact-sum.d.ts +20 -0
  138. package/dist/gpu/wgsl-exact-sum.js +42 -0
  139. package/dist/gpu/wgsl-exact-sum.js.map +1 -0
  140. package/dist/index.d.ts +18 -3
  141. package/dist/index.js +12 -1
  142. package/dist/index.js.map +1 -1
  143. package/dist/motion/subject-motion.d.ts +66 -0
  144. package/dist/motion/subject-motion.js +52 -0
  145. package/dist/motion/subject-motion.js.map +1 -0
  146. package/dist/optics/aperture-diameter.d.ts +47 -0
  147. package/dist/optics/aperture-diameter.js +50 -0
  148. package/dist/optics/aperture-diameter.js.map +1 -0
  149. package/dist/optics/detail-limit.d.ts +182 -0
  150. package/dist/optics/detail-limit.js +336 -0
  151. package/dist/optics/detail-limit.js.map +1 -0
  152. package/dist/optics/generic-lens-lateral-color.d.ts +83 -0
  153. package/dist/optics/generic-lens-lateral-color.js +77 -0
  154. package/dist/optics/generic-lens-lateral-color.js.map +1 -0
  155. package/dist/optics/generic-lens-psf.d.ts +18 -2
  156. package/dist/optics/generic-lens-psf.js +79 -48
  157. package/dist/optics/generic-lens-psf.js.map +1 -1
  158. package/dist/optics/lens-psf-profile.d.ts +7 -0
  159. package/dist/optics/lens-psf-profile.js +2 -1
  160. package/dist/optics/lens-psf-profile.js.map +1 -1
  161. package/dist/optics/scene-to-sensor-irradiance.d.ts +13 -0
  162. package/dist/optics/scene-to-sensor-irradiance.js +7 -0
  163. package/dist/optics/scene-to-sensor-irradiance.js.map +1 -1
  164. package/dist/output/crop-to-match-focal-length.d.ts +62 -0
  165. package/dist/output/crop-to-match-focal-length.js +63 -0
  166. package/dist/output/crop-to-match-focal-length.js.map +1 -0
  167. package/dist/output/developed-lens-corrections.d.ts +19 -5
  168. package/dist/output/developed-lens-corrections.js +30 -11
  169. package/dist/output/developed-lens-corrections.js.map +1 -1
  170. package/dist/output/generic-lens-corrections.d.ts +41 -3
  171. package/dist/output/generic-lens-corrections.js +57 -9
  172. package/dist/output/generic-lens-corrections.js.map +1 -1
  173. package/dist/output/lens-corrections.d.ts +12 -2
  174. package/dist/output/lens-corrections.js +22 -7
  175. package/dist/output/lens-corrections.js.map +1 -1
  176. package/dist/output/print-contrast-reference.js +1 -1
  177. package/dist/output/print-contrast-reference.js.map +1 -1
  178. package/dist/output/print-plan.d.ts +41 -5
  179. package/dist/output/print-plan.js +59 -14
  180. package/dist/output/print-plan.js.map +1 -1
  181. package/dist/output/print-size-blur-noise.d.ts +110 -0
  182. package/dist/output/print-size-blur-noise.js +138 -0
  183. package/dist/output/print-size-blur-noise.js.map +1 -0
  184. package/dist/sensor/binomial-sample.d.ts +3 -0
  185. package/dist/sensor/binomial-sample.js +86 -0
  186. package/dist/sensor/binomial-sample.js.map +1 -0
  187. package/dist/sensor/eqe-electron-rate.js +1 -7
  188. package/dist/sensor/eqe-electron-rate.js.map +1 -1
  189. package/dist/sensor/exposure-window.d.ts +2 -0
  190. package/dist/sensor/exposure-window.js +2 -2
  191. package/dist/sensor/exposure-window.js.map +1 -1
  192. package/dist/sensor/readout-timing.js +2 -23
  193. package/dist/sensor/readout-timing.js.map +1 -1
  194. package/dist/sensor/response-application-compatibility.js +1 -6
  195. package/dist/sensor/response-application-compatibility.js.map +1 -1
  196. package/dist/sensor/responsivity-photocurrent.js +1 -7
  197. package/dist/sensor/responsivity-photocurrent.js.map +1 -1
  198. package/dist/sensor/sensor-characteristics.d.ts +147 -0
  199. package/dist/sensor/sensor-characteristics.js +126 -0
  200. package/dist/sensor/sensor-characteristics.js.map +1 -0
  201. package/dist/sensor/spatial-sample-reduction.js +1 -5
  202. package/dist/sensor/spatial-sample-reduction.js.map +1 -1
  203. package/dist/sensor/spectral-quadrature.js +1 -6
  204. package/dist/sensor/spectral-quadrature.js.map +1 -1
  205. package/dist/sensor/temporal-photo-signal.d.ts +3 -0
  206. package/dist/sensor/temporal-photo-signal.js +5 -2
  207. package/dist/sensor/temporal-photo-signal.js.map +1 -1
  208. package/dist/stabilization/system.d.ts +9 -0
  209. package/dist/stabilization/system.js +5 -6
  210. package/dist/stabilization/system.js.map +1 -1
  211. package/docs/AGENT_GUIDE.md +5 -0
  212. package/docs/API_REFERENCE.md +173 -2
  213. package/docs/QUICK_START.md +213 -6
  214. package/docs/USAGE.md +157 -3
  215. package/docs/api/capture-native-raw-dng.md +6 -0
  216. package/docs/api/core-version.md +1 -1
  217. package/docs/api/equipment-generic-lens-catalogue.md +17 -7
  218. package/docs/api/equipment-sensor-profile-body.md +64 -0
  219. package/docs/api/equipment-sensor-profiles.md +86 -0
  220. package/docs/api/exports.json +357 -2
  221. package/docs/api/facade-display-view-gpu.md +5 -2
  222. package/docs/api/facade-exposure-build-up.md +105 -0
  223. package/docs/api/facade-fast-methods.md +99 -0
  224. package/docs/api/facade-image-plane-enable.md +16 -0
  225. package/docs/api/facade-mixed-illumination.md +67 -0
  226. package/docs/api/facade-representative-light-sources.md +131 -0
  227. package/docs/api/facade-scene-radiance.md +54 -3
  228. package/docs/api/facade-simulate-capture.md +60 -15
  229. package/docs/api/facade-simulate-display-view.md +3 -2
  230. package/docs/api/motion-subject-motion.md +23 -0
  231. package/docs/api/optics-aperture-diameter.md +51 -0
  232. package/docs/api/optics-detail-limit.md +203 -0
  233. package/docs/api/optics-generic-lens-lateral-color.md +79 -0
  234. package/docs/api/output-crop-to-match-focal-length.md +67 -0
  235. package/docs/api/output-developed-lens-corrections.md +10 -1
  236. package/docs/api/output-generic-lens-corrections.md +40 -2
  237. package/docs/api/output-lens-corrections.md +11 -1
  238. package/docs/api/output-print-plan.md +35 -1
  239. package/docs/api/output-print-size-blur-noise.md +115 -0
  240. package/docs/api/sensor-sensor-characteristics.md +105 -0
  241. package/llms.txt +6 -0
  242. package/package.json +1 -1
@@ -7,6 +7,7 @@ import { admitNativeEnvironmentInput } from "./native-environment-raw.js";
7
7
  import { composeNativeEnvironmentSensorSite } from "./native-environment-optical-stage.js";
8
8
  import { calculateNativeRawSite, parseNativeRawProducerSite } from "./sensor-raw-producer.js";
9
9
  import { calculateSiteEffectiveSaturationCode, createPhaseWhiteLevelAccumulator } from "./raw-white-level.js";
10
+ import { EXPOSURE_BUILD_UP_STAGES } from "./exposure-build-up-stage.js";
10
11
  import { createVerifiedNativeSiteReadout } from "./native-environment-lean.js";
11
12
  /** Largest relative difference between a verification site's tabulated and chain electrons: rounding only (a few ulps of each term). */
12
13
  export const TABULATED_RELATIVE_TOLERANCE = 1e-9;
@@ -51,7 +52,7 @@ export async function renderTabulatedNativeRaw(t) {
51
52
  const region = t.region ?? { x: 0, y: 0, width: W, height: native.pixelHeight };
52
53
  if (region.width < 2 || region.height < 2)
53
54
  return undefined;
54
- const seed = plan.exposure.noise.seedUint32, schedule = plan.exposureWindow, memo = createEnvironmentRawFrameCanonicalMemo(plan.frame, schedule);
55
+ const seed = plan.exposure.noise.seedUint32, b = EXPOSURE_BUILD_UP_STAGES.get(t.input.raw), schedule = plan.exposureWindow, memo = createEnvironmentRawFrameCanonicalMemo(plan.frame, schedule);
55
56
  let evaluations = 0;
56
57
  const evaluate = (request) => { evaluations++; return t.evaluateRadiance(request); };
57
58
  // The counting wrapper returns the evaluator's own results, so they are engine-built exactly when the evaluator is.
@@ -70,9 +71,9 @@ export async function renderTabulatedNativeRaw(t) {
70
71
  testHook.fullPhoto(photoResult, executeEnvironmentSensorPhotoSignal(full, t.evaluateRadiance, undefined, "photo-only").value.photo);
71
72
  const timing = calculateCaptureExposureWindows({ ...schedule, nativeRaster: native, samplePointsNative: [{ x: x + 0.5, y: y + 0.5 }] }).value.samples[0];
72
73
  const parsed = parseNativeRawProducerSite(composeNativeEnvironmentSensorSite(site, photo), index, plan.frame, timing);
73
- const result = calculateNativeRawSite(parsed, seed, index);
74
+ const result = calculateNativeRawSite(parsed, seed, index, b);
74
75
  const whiteCode = calculateSiteEffectiveSaturationCode(result.readout.value, parsed.readoutProfile, parsed.regimeId);
75
- const readout = createVerifiedNativeSiteReadout(parsed, result, whiteCode, photo, x, y, index, seed);
76
+ const readout = createVerifiedNativeSiteReadout(parsed, result, whiteCode, photo, x, y, index, seed, b);
76
77
  if (!readout)
77
78
  return undefined;
78
79
  t.electrons.window(x, y, x + 1, y + 1);
@@ -1 +1 @@
1
- {"version":3,"file":"native-environment-tabulated.js","sourceRoot":"","sources":["../../src/capture/native-environment-tabulated.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YACnC,CAAC;YACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;YACnD,IAAI,CAAC,KAAK,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,IAAI,QAAQ,EAAE,CAAC;gBAAC,MAAM,CAAC,CAAC,YAAY,EAAE,CAAC;gBAAC,CAAC,CAAC,UAAU,EAAE,CAAC;gBAAC,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAAC,CAAC;QACzI,CAAC;IACH,CAAC;IACD,GAAG,CAAC,wBAAwB,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;IAC9E,OAAO,EAAE,GAAG,EAAE,uBAAuB,EAAE,WAAW,GAAG,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE,8BAA8B,EAAE,KAAK,EAAE,CAAC;AACpH,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Internal (#394 step 2, not exported from the package): the native RAW of an engine-built planar scene (a chart preset or a\n * caller material scene, still camera, rectilinear, no distortion, vignetting, pupil rays or caller PSF) from tabulated\n * expected electrons instead of the per-site environment chain.\n *\n * Each site's expected photo electrons come from the display view's tabulated expected signal (`createDisplayViewExpectedSignal`):\n * the same sum over pixel-aperture nodes, anti-aliasing spots, diffraction taps and spectral nodes as the environment chain,\n * formed in another order, so the value differs from the chain's only in the last bits. The sensor stage is the native one:\n * dark charge, both Poisson draws, read noise and the ADC with the site's own seeds (`createVerifiedNativeSiteReadout`). A\n * site whose expected electrons differ in the last bit can therefore, rarely, draw a different integer; the statistics are\n * unchanged.\n *\n * Verification at run time: one site of each CFA phase runs the full chain (planning, the evaluator's callbacks, composition,\n * parsing and `calculateNativeRawSite`). Its readout template must reproduce that site bit for bit, and its tabulated\n * electrons must agree with the chain's within `TABULATED_RELATIVE_TOLERANCE`; otherwise the caller runs the environment task.\n * #453: the chain's photo signal comes from `executeEngineOwnedEnvironmentPhotoSignal`, the same operations and values as\n * `executeEnvironmentSensorPhotoSignal` for these engine-built records, without re-validating records that cannot have changed.\n */\n\nimport type { EnvironmentRadianceEvaluator } from \"../sensor/environment-photo-signal.js\";\nimport { executeEngineOwnedEnvironmentPhotoSignal, executeEnvironmentSensorPhotoSignal } from \"../sensor/environment-photo-signal.js\";\nimport { isInternalSceneRadianceEvaluator } from \"../core/internal-radiance-evaluator.js\";\nimport { calculateCaptureExposureWindows, prepareCaptureExposureWindowSampler } from \"../sensor/exposure-window.js\";\nimport { createEnvironmentRawFrameCanonicalMemo, planEnvironmentRawSite, type SimulateEnvironmentSensorRawFrameInput } from \"./environment-raw-producer.js\";\nimport { admitNativeEnvironmentInput, type NativeEnvironmentRawInput } from \"./native-environment-raw.js\";\nimport { composeNativeEnvironmentSensorSite } from \"./native-environment-optical-stage.js\";\nimport { calculateNativeRawSite, parseNativeRawProducerSite } from \"./sensor-raw-producer.js\";\nimport { calculateSiteEffectiveSaturationCode, createPhaseWhiteLevelAccumulator } from \"./raw-white-level.js\";\nimport { createVerifiedNativeSiteReadout, type NativeSiteReadout } from \"./native-environment-lean.js\";\nimport type { NativeRawOutput } from \"./native-raw.js\";\n\n/** Largest relative difference between a verification site's tabulated and chain electrons: rounding only (a few ulps of each term). */\nexport const TABULATED_RELATIVE_TOLERANCE = 1e-9;\n/** Rows per expected-signal cache window. */\nconst BAND_ROWS = 32;\n/** Host-yield budget in milliseconds (the native task's cadence); the task also yields after its last row. */\nconst YIELD_MS = 8;\n\n/** Internal counters (tests assert how many verification sites ran the chain per call; four, one per CFA phase). */\nexport const tabulatedVerificationStatistics = { chainExecutions: 0 };\n\n/**\n * Internal test hook (never set by the engine): `fullPhoto` also runs each verification site through\n * `executeEnvironmentSensorPhotoSignal` (with the uncounted evaluator) and hands both photo signals to the test;\n * `tabulatedElectrons` replaces the tabulated electrons the gate compares, to show that a wrong fast path is rejected.\n */\nexport interface TabulatedVerificationTestHook {\n fullPhoto?(engineOwned: unknown, full: unknown): void;\n tabulatedElectrons?(value: number, x: number, y: number): number;\n}\nlet testHook: TabulatedVerificationTestHook | undefined;\nexport function setTabulatedVerificationTestHook(hook: TabulatedVerificationTestHook | undefined): void { testHook = hook; }\n\nlet tabulatedDisabled = false;\n/** Disables the tabulated path process-wide (internal; tests of the environment path itself turn it off). */\nexport function setTabulatedNativeRawEnabled(enabled: boolean): void { tabulatedDisabled = !enabled; }\n\nexport interface TabulatedNativeRawInput {\n input: NativeEnvironmentRawInput;\n /** Native rectangle to render (region rendering); absent: the whole raster. */\n region?: { x: number; y: number; width: number; height: number } | undefined;\n /** The engine-built site record of a native index (the facade's `siteInput`). */\n siteInput(index: number): SimulateEnvironmentSensorRawFrameInput[\"sites\"][number];\n /** The evaluator the environment task would use (for the verification sites). */\n evaluateRadiance: EnvironmentRadianceEvaluator;\n /** Expected photo electrons of native sites (`createDisplayViewExpectedSignal`). */\n electrons: { window(x0: number, y0: number, x1: number, y1: number): void; site(x: number, y: number): number; readonly lookups: number };\n /** Called once per native tile-equivalent (progress), as the environment task reads its tiles. */\n onTile?: () => void;\n tileWidth: number;\n /**\n * #568: the largest relative difference the verification accepts (default `TABULATED_RELATIVE_TOLERANCE`): a fast method that\n * approximates the chain (`lens.catalogue`'s field-grid PSF) passes its own measured bound.\n */\n relativeTolerance?: number;\n yieldControl(): Promise<void>;\n checkAbort(): void;\n}\n\nexport interface TabulatedNativeRawResult {\n raw: NativeRawOutput;\n /** Evaluator callbacks of the verification sites plus the tabulated signal's scene lookups. */\n providerEvaluationCount: number;\n /** Largest relative difference between tabulated and chain electrons over the verification sites. */\n verificationRelativeDifference: number;\n}\n\n/**\n * #449: the local exposure duration shared by every site of `region`, or undefined when the sampler must run per site. With\n * simultaneous opening and closing boundaries both boundary phases are 0 at every point (exposure-window.ts, boundaryPhase), so\n * each site's duration is the nominal one the sampler gives at the region's first site. The sampler's only other per-point step\n * is its check that the point lies in the active capture rectangle; the region's first and last site centres bound every other\n * centre, so when both pass every site passes. When either throws, the per-site path runs (and throws where it did).\n */\nexport function simultaneousExposureDuration(schedule: { opening: unknown; closing: unknown }, sampler: (point: { x: number; y: number }) => { localExposureDurationSeconds: number },\n region: { x: number; y: number; width: number; height: number }): number | undefined {\n if ((schedule.opening as { kind?: unknown }).kind !== \"simultaneous\" || (schedule.closing as { kind?: unknown }).kind !== \"simultaneous\") return undefined;\n try {\n const first = sampler({ x: region.x + 0.5, y: region.y + 0.5 }).localExposureDurationSeconds;\n const last = sampler({ x: region.x + region.width - 0.5, y: region.y + region.height - 0.5 }).localExposureDurationSeconds;\n return Object.is(first, last) ? first : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Renders the native RAW from tabulated expected electrons, or returns undefined when verification fails (see the module comment). */\nexport async function renderTabulatedNativeRaw(t: TabulatedNativeRawInput): Promise<TabulatedNativeRawResult | undefined> {\n if (tabulatedDisabled) return undefined;\n const { plan, sceneBinding } = admitNativeEnvironmentInput(t.input);\n const native = plan.exposure.geometry.nativeRaster, W = native.pixelWidth, layout = plan.frame.colorSamplingProfile.layout;\n if (layout.kind !== \"periodic-mosaic\" || layout.repeatWidthSites !== 2 || layout.repeatHeightSites !== 2 || !plan.exposureWindow) return undefined;\n const region = t.region ?? { x: 0, y: 0, width: W, height: native.pixelHeight };\n if (region.width < 2 || region.height < 2) return undefined;\n const seed = plan.exposure.noise.seedUint32, schedule = plan.exposureWindow, memo = createEnvironmentRawFrameCanonicalMemo(plan.frame, schedule);\n let evaluations = 0;\n const evaluate: EnvironmentRadianceEvaluator = (request) => { evaluations++; return t.evaluateRadiance(request); };\n // The counting wrapper returns the evaluator's own results, so they are engine-built exactly when the evaluator is.\n const engineBuiltResults = isInternalSceneRadianceEvaluator(t.evaluateRadiance);\n // Verification: the region's top-left 2 × 2 block, one site per CFA phase, through the full chain.\n const readouts: NativeSiteReadout[] = [];\n let worst = 0;\n for (let k = 0; k < 4; k++) {\n const x = region.x + (k & 1), y = region.y + (k >> 1), index = y * W + x, site = t.siteInput(index);\n const full = planEnvironmentRawSite(site, index, plan.frame, sceneBinding, schedule, \"engine-owned\", memo, \"photo-only\");\n // #453: the chain for these engine-built site records (the same operations and values as executeEnvironmentSensorPhotoSignal,\n // without re-validating records that have not changed; see executeEngineOwnedEnvironmentPhotoSignal).\n const photoResult = executeEngineOwnedEnvironmentPhotoSignal(full, evaluate, engineBuiltResults), photo = photoResult.value.photoSignal;\n tabulatedVerificationStatistics.chainExecutions++;\n if (testHook?.fullPhoto) testHook.fullPhoto(photoResult, executeEnvironmentSensorPhotoSignal(full, t.evaluateRadiance, undefined, \"photo-only\").value.photo);\n const timing = calculateCaptureExposureWindows({ ...schedule, nativeRaster: native, samplePointsNative: [{ x: x + 0.5, y: y + 0.5 }] }).value.samples[0];\n const parsed = parseNativeRawProducerSite(composeNativeEnvironmentSensorSite(site, photo), index, plan.frame, timing);\n const result = calculateNativeRawSite(parsed, seed, index);\n const whiteCode = calculateSiteEffectiveSaturationCode(result.readout.value, parsed.readoutProfile, parsed.regimeId);\n const readout = createVerifiedNativeSiteReadout(parsed, result, whiteCode, photo, x, y, index, seed);\n if (!readout) return undefined;\n t.electrons.window(x, y, x + 1, y + 1);\n const chain = photo.expectedGeneratedElectronCount, tabulated = testHook?.tabulatedElectrons ? testHook.tabulatedElectrons(t.electrons.site(x, y), x, y) : t.electrons.site(x, y);\n const difference = chain === tabulated ? 0 : Math.abs(tabulated - chain) / Math.max(Math.abs(chain), Number.MIN_VALUE);\n if (!(difference <= (t.relativeTolerance ?? TABULATED_RELATIVE_TOLERANCE))) return undefined;\n worst = Math.max(worst, difference);\n readouts[(y & 1) * 2 + (x & 1)] = readout;\n }\n const length = region.width * region.height;\n const raw: NativeRawOutput = { plan, codes: new Uint16Array(length), blackLevels: new Uint16Array(length), digitalSaturationCodes: new Uint16Array(length),\n saturationFlags: new Uint8Array(length), effectiveSaturationCodes: new Uint16Array(4) };\n const white = createPhaseWhiteLevelAccumulator(W, 2, 2), sampler = prepareCaptureExposureWindowSampler({ ...schedule, nativeRaster: native });\n const tilesPerRow = Math.ceil(region.width / t.tileWidth), point = { x: 0, y: 0 };\n const constantDuration = simultaneousExposureDuration(schedule, sampler, region);\n let last = Date.now();\n for (let y0 = region.y; y0 < region.y + region.height; y0 += BAND_ROWS) {\n const y1 = Math.min(region.y + region.height, y0 + BAND_ROWS);\n t.electrons.window(region.x, y0, region.x + region.width, y1);\n for (let y = y0; y < y1; y++) {\n for (let x = region.x; x < region.x + region.width; x++) {\n const index = y * W + x, at = (y - region.y) * region.width + x - region.x;\n let duration = constantDuration;\n if (duration === undefined) { point.x = x + 0.5; point.y = y + 0.5; duration = sampler(point).localExposureDurationSeconds; }\n const o = readouts[(y & 1) * 2 + (x & 1)]!.compute(t.electrons.site(x, y), duration, x, y, index, seed);\n // A check of the full path failed for this site: let the environment task decide (it throws its own error).\n if (!o) return undefined;\n raw.codes[at] = o.rawCode; raw.blackLevels[at] = o.blackLevelCode; raw.digitalSaturationCodes[at] = o.digitalSaturationCode; raw.saturationFlags[at] = o.flags;\n white.record(index, o.whiteCode);\n }\n for (let k = 0; k < tilesPerRow; k++) t.onTile?.();\n if (y === region.y + region.height - 1 || Date.now() - last >= YIELD_MS) { await t.yieldControl(); t.checkAbort(); last = Date.now(); }\n }\n }\n raw.effectiveSaturationCodes.set(t.region ? white.partial() : white.finish());\n return { raw, providerEvaluationCount: evaluations + t.electrons.lookups, verificationRelativeDifference: worst };\n}\n"]}
1
+ {"version":3,"file":"native-environment-tabulated.js","sourceRoot":"","sources":["../../src/capture/native-environment-tabulated.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAsBtC,OAAO,EAAE,wCAAwC,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AACtI,OAAO,E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KAAK,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC;YACnC,CAAC;YACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;YACnD,IAAI,CAAC,KAAK,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,IAAI,QAAQ,EAAE,CAAC;gBAAC,MAAM,CAAC,CAAC,YAAY,EAAE,CAAC;gBAAC,CAAC,CAAC,UAAU,EAAE,CAAC;gBAAC,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAAC,CAAC;QACzI,CAAC;IACH,CAAC;IACD,GAAG,CAAC,wBAAwB,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;IAC9E,OAAO,EAAE,GAAG,EAAE,uBAAuB,EAAE,WAAW,GAAG,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE,8BAA8B,EAAE,KAAK,EAAE,CAAC;AACpH,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Internal (#394 step 2, not exported from the package): the native RAW of an engine-built planar scene (a chart preset or a\n * caller material scene, still camera, rectilinear, no distortion, vignetting, pupil rays or caller PSF) from tabulated\n * expected electrons instead of the per-site environment chain.\n *\n * Each site's expected photo electrons come from the display view's tabulated expected signal (`createDisplayViewExpectedSignal`):\n * the same sum over pixel-aperture nodes, anti-aliasing spots, diffraction taps and spectral nodes as the environment chain,\n * formed in another order, so the value differs from the chain's only in the last bits. The sensor stage is the native one:\n * dark charge, both Poisson draws, read noise and the ADC with the site's own seeds (`createVerifiedNativeSiteReadout`). A\n * site whose expected electrons differ in the last bit can therefore, rarely, draw a different integer; the statistics are\n * unchanged.\n *\n * Verification at run time: one site of each CFA phase runs the full chain (planning, the evaluator's callbacks, composition,\n * parsing and `calculateNativeRawSite`). Its readout template must reproduce that site bit for bit, and its tabulated\n * electrons must agree with the chain's within `TABULATED_RELATIVE_TOLERANCE`; otherwise the caller runs the environment task.\n * #453: the chain's photo signal comes from `executeEngineOwnedEnvironmentPhotoSignal`, the same operations and values as\n * `executeEnvironmentSensorPhotoSignal` for these engine-built records, without re-validating records that cannot have changed.\n */\n\nimport type { EnvironmentRadianceEvaluator } from \"../sensor/environment-photo-signal.js\";\nimport { executeEngineOwnedEnvironmentPhotoSignal, executeEnvironmentSensorPhotoSignal } from \"../sensor/environment-photo-signal.js\";\nimport { isInternalSceneRadianceEvaluator } from \"../core/internal-radiance-evaluator.js\";\nimport { calculateCaptureExposureWindows, prepareCaptureExposureWindowSampler } from \"../sensor/exposure-window.js\";\nimport { createEnvironmentRawFrameCanonicalMemo, planEnvironmentRawSite, type SimulateEnvironmentSensorRawFrameInput } from \"./environment-raw-producer.js\";\nimport { admitNativeEnvironmentInput, type NativeEnvironmentRawInput } from \"./native-environment-raw.js\";\nimport { composeNativeEnvironmentSensorSite } from \"./native-environment-optical-stage.js\";\nimport { calculateNativeRawSite, parseNativeRawProducerSite } from \"./sensor-raw-producer.js\";\nimport { calculateSiteEffectiveSaturationCode, createPhaseWhiteLevelAccumulator } from \"./raw-white-level.js\";\nimport { EXPOSURE_BUILD_UP_STAGES } from \"./exposure-build-up-stage.js\";\nimport { createVerifiedNativeSiteReadout, type NativeSiteReadout } from \"./native-environment-lean.js\";\nimport type { NativeRawOutput } from \"./native-raw.js\";\n\n/** Largest relative difference between a verification site's tabulated and chain electrons: rounding only (a few ulps of each term). */\nexport const TABULATED_RELATIVE_TOLERANCE = 1e-9;\n/** Rows per expected-signal cache window. */\nconst BAND_ROWS = 32;\n/** Host-yield budget in milliseconds (the native task's cadence); the task also yields after its last row. */\nconst YIELD_MS = 8;\n\n/** Internal counters (tests assert how many verification sites ran the chain per call; four, one per CFA phase). */\nexport const tabulatedVerificationStatistics = { chainExecutions: 0 };\n\n/**\n * Internal test hook (never set by the engine): `fullPhoto` also runs each verification site through\n * `executeEnvironmentSensorPhotoSignal` (with the uncounted evaluator) and hands both photo signals to the test;\n * `tabulatedElectrons` replaces the tabulated electrons the gate compares, to show that a wrong fast path is rejected.\n */\nexport interface TabulatedVerificationTestHook {\n fullPhoto?(engineOwned: unknown, full: unknown): void;\n tabulatedElectrons?(value: number, x: number, y: number): number;\n}\nlet testHook: TabulatedVerificationTestHook | undefined;\nexport function setTabulatedVerificationTestHook(hook: TabulatedVerificationTestHook | undefined): void { testHook = hook; }\n\nlet tabulatedDisabled = false;\n/** Disables the tabulated path process-wide (internal; tests of the environment path itself turn it off). */\nexport function setTabulatedNativeRawEnabled(enabled: boolean): void { tabulatedDisabled = !enabled; }\n\nexport interface TabulatedNativeRawInput {\n input: NativeEnvironmentRawInput;\n /** Native rectangle to render (region rendering); absent: the whole raster. */\n region?: { x: number; y: number; width: number; height: number } | undefined;\n /** The engine-built site record of a native index (the facade's `siteInput`). */\n siteInput(index: number): SimulateEnvironmentSensorRawFrameInput[\"sites\"][number];\n /** The evaluator the environment task would use (for the verification sites). */\n evaluateRadiance: EnvironmentRadianceEvaluator;\n /** Expected photo electrons of native sites (`createDisplayViewExpectedSignal`). */\n electrons: { window(x0: number, y0: number, x1: number, y1: number): void; site(x: number, y: number): number; readonly lookups: number };\n /** Called once per native tile-equivalent (progress), as the environment task reads its tiles. */\n onTile?: () => void;\n tileWidth: number;\n /**\n * #568: the largest relative difference the verification accepts (default `TABULATED_RELATIVE_TOLERANCE`): a fast method that\n * approximates the chain (`lens.catalogue`'s field-grid PSF) passes its own measured bound.\n */\n relativeTolerance?: number;\n yieldControl(): Promise<void>;\n checkAbort(): void;\n}\n\nexport interface TabulatedNativeRawResult {\n raw: NativeRawOutput;\n /** Evaluator callbacks of the verification sites plus the tabulated signal's scene lookups. */\n providerEvaluationCount: number;\n /** Largest relative difference between tabulated and chain electrons over the verification sites. */\n verificationRelativeDifference: number;\n}\n\n/**\n * #449: the local exposure duration shared by every site of `region`, or undefined when the sampler must run per site. With\n * simultaneous opening and closing boundaries both boundary phases are 0 at every point (exposure-window.ts, boundaryPhase), so\n * each site's duration is the nominal one the sampler gives at the region's first site. The sampler's only other per-point step\n * is its check that the point lies in the active capture rectangle; the region's first and last site centres bound every other\n * centre, so when both pass every site passes. When either throws, the per-site path runs (and throws where it did).\n */\nexport function simultaneousExposureDuration(schedule: { opening: unknown; closing: unknown }, sampler: (point: { x: number; y: number }) => { localExposureDurationSeconds: number },\n region: { x: number; y: number; width: number; height: number }): number | undefined {\n if ((schedule.opening as { kind?: unknown }).kind !== \"simultaneous\" || (schedule.closing as { kind?: unknown }).kind !== \"simultaneous\") return undefined;\n try {\n const first = sampler({ x: region.x + 0.5, y: region.y + 0.5 }).localExposureDurationSeconds;\n const last = sampler({ x: region.x + region.width - 0.5, y: region.y + region.height - 0.5 }).localExposureDurationSeconds;\n return Object.is(first, last) ? first : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Renders the native RAW from tabulated expected electrons, or returns undefined when verification fails (see the module comment). */\nexport async function renderTabulatedNativeRaw(t: TabulatedNativeRawInput): Promise<TabulatedNativeRawResult | undefined> {\n if (tabulatedDisabled) return undefined;\n const { plan, sceneBinding } = admitNativeEnvironmentInput(t.input);\n const native = plan.exposure.geometry.nativeRaster, W = native.pixelWidth, layout = plan.frame.colorSamplingProfile.layout;\n if (layout.kind !== \"periodic-mosaic\" || layout.repeatWidthSites !== 2 || layout.repeatHeightSites !== 2 || !plan.exposureWindow) return undefined;\n const region = t.region ?? { x: 0, y: 0, width: W, height: native.pixelHeight };\n if (region.width < 2 || region.height < 2) return undefined;\n const seed = plan.exposure.noise.seedUint32, b = EXPOSURE_BUILD_UP_STAGES.get(t.input.raw), schedule = plan.exposureWindow, memo = createEnvironmentRawFrameCanonicalMemo(plan.frame, schedule);\n let evaluations = 0;\n const evaluate: EnvironmentRadianceEvaluator = (request) => { evaluations++; return t.evaluateRadiance(request); };\n // The counting wrapper returns the evaluator's own results, so they are engine-built exactly when the evaluator is.\n const engineBuiltResults = isInternalSceneRadianceEvaluator(t.evaluateRadiance);\n // Verification: the region's top-left 2 × 2 block, one site per CFA phase, through the full chain.\n const readouts: NativeSiteReadout[] = [];\n let worst = 0;\n for (let k = 0; k < 4; k++) {\n const x = region.x + (k & 1), y = region.y + (k >> 1), index = y * W + x, site = t.siteInput(index);\n const full = planEnvironmentRawSite(site, index, plan.frame, sceneBinding, schedule, \"engine-owned\", memo, \"photo-only\");\n // #453: the chain for these engine-built site records (the same operations and values as executeEnvironmentSensorPhotoSignal,\n // without re-validating records that have not changed; see executeEngineOwnedEnvironmentPhotoSignal).\n const photoResult = executeEngineOwnedEnvironmentPhotoSignal(full, evaluate, engineBuiltResults), photo = photoResult.value.photoSignal;\n tabulatedVerificationStatistics.chainExecutions++;\n if (testHook?.fullPhoto) testHook.fullPhoto(photoResult, executeEnvironmentSensorPhotoSignal(full, t.evaluateRadiance, undefined, \"photo-only\").value.photo);\n const timing = calculateCaptureExposureWindows({ ...schedule, nativeRaster: native, samplePointsNative: [{ x: x + 0.5, y: y + 0.5 }] }).value.samples[0];\n const parsed = parseNativeRawProducerSite(composeNativeEnvironmentSensorSite(site, photo), index, plan.frame, timing);\n const result = calculateNativeRawSite(parsed, seed, index, b);\n const whiteCode = calculateSiteEffectiveSaturationCode(result.readout.value, parsed.readoutProfile, parsed.regimeId);\n const readout = createVerifiedNativeSiteReadout(parsed, result, whiteCode, photo, x, y, index, seed, b);\n if (!readout) return undefined;\n t.electrons.window(x, y, x + 1, y + 1);\n const chain = photo.expectedGeneratedElectronCount, tabulated = testHook?.tabulatedElectrons ? testHook.tabulatedElectrons(t.electrons.site(x, y), x, y) : t.electrons.site(x, y);\n const difference = chain === tabulated ? 0 : Math.abs(tabulated - chain) / Math.max(Math.abs(chain), Number.MIN_VALUE);\n if (!(difference <= (t.relativeTolerance ?? TABULATED_RELATIVE_TOLERANCE))) return undefined;\n worst = Math.max(worst, difference);\n readouts[(y & 1) * 2 + (x & 1)] = readout;\n }\n const length = region.width * region.height;\n const raw: NativeRawOutput = { plan, codes: new Uint16Array(length), blackLevels: new Uint16Array(length), digitalSaturationCodes: new Uint16Array(length),\n saturationFlags: new Uint8Array(length), effectiveSaturationCodes: new Uint16Array(4) };\n const white = createPhaseWhiteLevelAccumulator(W, 2, 2), sampler = prepareCaptureExposureWindowSampler({ ...schedule, nativeRaster: native });\n const tilesPerRow = Math.ceil(region.width / t.tileWidth), point = { x: 0, y: 0 };\n const constantDuration = simultaneousExposureDuration(schedule, sampler, region);\n let last = Date.now();\n for (let y0 = region.y; y0 < region.y + region.height; y0 += BAND_ROWS) {\n const y1 = Math.min(region.y + region.height, y0 + BAND_ROWS);\n t.electrons.window(region.x, y0, region.x + region.width, y1);\n for (let y = y0; y < y1; y++) {\n for (let x = region.x; x < region.x + region.width; x++) {\n const index = y * W + x, at = (y - region.y) * region.width + x - region.x;\n let duration = constantDuration;\n if (duration === undefined) { point.x = x + 0.5; point.y = y + 0.5; duration = sampler(point).localExposureDurationSeconds; }\n const o = readouts[(y & 1) * 2 + (x & 1)]!.compute(t.electrons.site(x, y), duration, x, y, index, seed);\n // A check of the full path failed for this site: let the environment task decide (it throws its own error).\n if (!o) return undefined;\n raw.codes[at] = o.rawCode; raw.blackLevels[at] = o.blackLevelCode; raw.digitalSaturationCodes[at] = o.digitalSaturationCode; raw.saturationFlags[at] = o.flags;\n white.record(index, o.whiteCode);\n }\n for (let k = 0; k < tilesPerRow; k++) t.onTile?.();\n if (y === region.y + region.height - 1 || Date.now() - last >= YIELD_MS) { await t.yieldControl(); t.checkAbort(); last = Date.now(); }\n }\n }\n raw.effectiveSaturationCodes.set(t.region ? white.partial() : white.finish());\n return { raw, providerEvaluationCount: evaluations + t.electrons.lookups, verificationRelativeDifference: worst };\n}\n"]}
@@ -22,6 +22,12 @@ export interface SerializeNativeRawDngInput {
22
22
  capturedAtUtc?: string;
23
23
  /** Optional (2.4) caller text: description, software, copyright, comment (see the module notes). If omitted, no text is added. */
24
24
  textMetadata?: OutputTextMetadata;
25
+ /**
26
+ * Optional (#587) OpcodeList3 (tag 51022) bytes, for example `createDngLensCorrectionOpcodes(...).opcodeList3`: a big-endian DNG
27
+ * opcode list (DNG 1.3.0.0+, "Opcode List Processing") that readers apply to the demosaiced stage-3 image. Only its framing is
28
+ * checked (count, per-opcode headers and parameter sizes filling the bytes exactly). The RAW codes are unchanged. If omitted, no tag.
29
+ */
30
+ opcodeList3?: Uint8Array;
25
31
  }
26
32
  export interface NativeRawDng {
27
33
  schemaVersion: typeof NATIVE_RAW_DNG_SCHEMA_VERSION;
@@ -31,6 +31,8 @@
31
31
  * §1.1.6, Table 13) always carries every given field in UTF-8: `dc:description` (the full ImageDescription text,
32
32
  * statement first, as XMP Part 3 §3.2.3 maps tag 270), `dc:rights`, `xmp:CreatorTool` and `exif:UserComment`.
33
33
  * The Software tag keeps naming the engine's writer. Without `textMetadata` the bytes are unchanged.
34
+ * - Opcodes (#587, only with `opcodeList3`): the caller's big-endian DNG opcode list as OpcodeList3 (51022, UNDEFINED), framing checked
35
+ * (count, 16-byte headers, parameter sizes filling the bytes). Without it the bytes are unchanged.
34
36
  * @see docs/NATIVE_RAW_AND_PRINT.md for the tag table, limits and the round trip through parseDngRawImage.
35
37
  */
36
38
  import { InvalidConfigurationError } from "../core/configuration-error.js";
@@ -64,7 +66,19 @@ const ORIENTATION = { landscape: 1, "portrait-clockwise": 6, "landscape-inverted
64
66
  * where its value comes from. The input arrays are copied before the first await.
65
67
  */
66
68
  export async function serializeNativeRawDng(input) {
67
- const r = requireAllowlistedRecord(input, ["raw", "colorProfile", "noise", "baselineExposureEv", "capturedAtUtc", "textMetadata"], "Invalid native RAW DNG input.");
69
+ const r = requireAllowlistedRecord(input, ["raw", "colorProfile", "noise", "baselineExposureEv", "capturedAtUtc", "textMetadata", "opcodeList3"], "Invalid native RAW DNG input.");
70
+ let opcodeList3;
71
+ if (r.opcodeList3 !== undefined) {
72
+ if (!(r.opcodeList3 instanceof Uint8Array) || r.opcodeList3.length < 4)
73
+ fail("opcodeList3 must be a Uint8Array opcode list.");
74
+ opcodeList3 = r.opcodeList3.slice();
75
+ const v = new DataView(opcodeList3.buffer);
76
+ let at = 4;
77
+ for (let n = v.getUint32(0); n > 0 && at <= opcodeList3.length; n--)
78
+ at = at + 16 > opcodeList3.length ? Infinity : at + 16 + v.getUint32(at + 12);
79
+ if (at !== opcodeList3.length)
80
+ fail("opcodeList3 is not a whole DNG opcode list (big-endian count, 16-byte headers, parameter sizes).");
81
+ }
68
82
  const raw = r.raw, plan = validatePackedNativeRaw(raw);
69
83
  const mosaic = plan.frame.colorSamplingProfile.layout;
70
84
  if (mosaic.kind === "periodic-mosaic")
@@ -179,7 +193,7 @@ export async function serializeNativeRawDng(input) {
179
193
  rationals(50730, true, [baseline]), numbers(50778, 3, [21]),
180
194
  rawBytes(50781, 1, Uint8Array.from(rawDataUniqueId.match(/../g).map((s) => parseInt(s, 16)))),
181
195
  numbers(50829, 4, [active.y, active.x, active.y + active.height, active.x + active.width]),
182
- rationals(50964, true, forward.flat()), ...(noiseProfile ? [doubles(51041, noiseProfile)] : []), ...textTags], exif, pixels);
196
+ rationals(50964, true, forward.flat()), ...(noiseProfile ? [doubles(51041, noiseProfile)] : []), ...(opcodeList3 ? [rawBytes(51022, 7, opcodeList3)] : []), ...textTags], exif, pixels);
183
197
  return Object.freeze({ schemaVersion: NATIVE_RAW_DNG_SCHEMA_VERSION, mediaType: "image/dng", bytes, sha256: await sha256(bytes), rawDataUniqueId, uniqueCameraModel,
184
198
  activeArea: { ...active }, defaultCrop: { ...crop }, orientation, blackLevels, whiteLevel, cfaPattern, colorMatrix1: stored(colorMatrixTag), asShotNeutral: stored(neutralTag),
185
199
  noiseProfile, unrepresentedSaturationFlagCount: unrepresented, source: "packed-native-raw", linearMasterDeclared: false });
@@ -1 +1 @@
1
- {"version":3,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AM,CAAC,KAAK,CAAC,CAAC;QAC1F,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IAC/H,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,aAAa,EAAE,6BAA6B,EAAE,SAAS,EAAE,WAAoB,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC,KAAK,CAAC,EAAE,eAAe,EAAE,iBAAiB;QAC1K,UAAU,EAAE,EAAE,GAAG,MAAM,EAAE,EAAE,WAAW,EAAE,EAAE,GAAG,IAAI,EAAE,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,CAAC,cAAc,CAAC,EAAE,aAAa,EAAE,MAAM,CAAC,UAAU,CAAC;QAC9K,YAAY,EAAE,gCAAgC,EAAE,aAAa,EAAE,MAAM,EAAE,mBAA4B,EAAE,oBAAoB,EAAE,KAAc,EAAE,CAAC,CAAC;AACjJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n// This product includes DNG technology under license by Adobe.\n\n/**\n * Writes a packed native RAW (`NativeRawOutput`, from the native RAW or native environment RAW tasks) as a\n * lossless, uncompressed 16-bit DNG with a CFA (colour filter array) mosaic.\n *\n * The file describes only what the packed RAW, the caller's declared colour profile and noise model\n * contain. It never claims a linear float master as its source, or a developed image. The tag layout reuses\n * the TIFF/DNG writers of the paired photographic export (`packExportTiff`, DNG 1.4 tags, Adobe DNG\n * Specification 1.7.1.0):\n *\n * - CFA geometry: CFARepeatPatternDim 2×2, CFAPattern and BlackLevel phases relative to the ActiveArea\n * origin (DNG applies them to the stage-2, ActiveArea-cropped image); DefaultCropOrigin/Size are the\n * capture's oriented output crop mapped back to stored (native) coordinates; Orientation from the capture.\n * - Levels: BlackLevel per 2×2 phase (the packed per-site black levels must repeat with the CFA tile).\n * WhiteLevel is the smallest per-phase effective white code, so no channel is reported as unsaturated\n * above its own saturation point. DNG cannot represent a saturation flag on a site whose code is below\n * WhiteLevel; such sites are counted in `unrepresentedSaturationFlagCount`.\n * - Colour: ColorMatrix1 = (camera→XYZ)⁻¹ with CalibrationIlluminant1 D65 (21), ForwardMatrix1 =\n * Bradford(D65→D50)·M·diag(w), AnalogBalance 1, AsShotNeutral from the capture's white-balance intent\n * (the same operator native development uses), BaselineExposure as declared (default 0).\n * - Noise: NoiseProfile (51041) per CFA plane, var(x) = S·x + O for x = (code − black)/(WhiteLevel − black),\n * S = 1/(G·span), O = (σ_read²/G² + 1/12)/span², written only when the caller supplies each channel's\n * output-referred conversion gain G (electrons per code) and read noise σ_read (electrons). The model\n * covers only Poisson photo and dark shot noise, Gaussian read noise and uniform quantization. It is an\n * approximation: PRNU (photo-response non-uniformity), DSNU (dark-signal non-uniformity) and other\n * fixed-pattern noise are not included.\n * - Text (2.4, only with `textMetadata`): the caller's description is appended to ImageDescription after the\n * simulated-RAW statement and the copyright is written as Copyright (33432), each only when it is printable\n * ASCII (TIFF 6.0 §2: ASCII fields hold 7-bit codes). An XMP packet in tag 700 (BYTE; XMP Specification Part 3\n * §1.1.6, Table 13) always carries every given field in UTF-8: `dc:description` (the full ImageDescription text,\n * statement first, as XMP Part 3 §3.2.3 maps tag 270), `dc:rights`, `xmp:CreatorTool` and `exif:UserComment`.\n * The Software tag keeps naming the engine's writer. Without `textMetadata` the bytes are unchanged.\n * @see docs/NATIVE_RAW_AND_PRINT.md for the tag table, limits and the round trip through parseDngRawImage.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { ENGINE_API_VERSION } from \"../core/version.js\";\nimport { resolveCaptureColorModel } from \"../color/capture-color.js\";\nimport { invertSensorColorMatrix, prepareSensorColorDevelopment, sensorColorReferenceWhite } from \"../color/sensor-color-development.js\";\nimport { ICC_D50_WHITE_XYZ } from \"../color/srgb-icc.js\";\nimport { chromaticAdaptationMatrix } from \"../color/chromatic-adaptation.js\";\nimport { transformOrientedRasterRectToNative } from \"../output/capture-geometry.js\";\nimport type { NativeRawOutput } from \"./native-raw.js\";\nimport { checkNativeRawIntegrity, validatePackedNativeRaw } from \"./native-raw-development.js\";\nimport { parseExportSensorColorProfile, type ExportSensorColorProfile } from \"./photographic-export.js\";\nimport { parseOutputTextMetadata, xmpTextMetadataPacket, type OutputTextMetadata } from \"../output/text-metadata.js\";\nimport { packExportTiff, exportTiffAscii as ascii, exportTiffNumbers as numbers, exportTiffRationals as rationals,\n exportTiffBytes as rawBytes, exportTiffDoubles as doubles } from \"./export-tiff.js\";\n\nexport const NATIVE_RAW_DNG_SCHEMA_VERSION = \"1.0.0\" as const;\n\n/** Output-referred noise parameters of one CFA channel (see the module notes). */\nexport interface NativeRawDngChannelNoise {\n /** Electrons per output RAW code (system conversion gain divided by any post-ADC digital gain). */\n conversionGainElectronsPerCode: number;\n /** Combined RMS read noise, electrons. */\n readNoiseRmsElectrons: number;\n}\nexport interface SerializeNativeRawDngInput {\n /** Packed native RAW. It is read, never taken over or modified. */\n raw: NativeRawOutput;\n /** Declared camera→XYZ (D65) colour profile for the RAW's CFA. Native development uses the same profile. */\n colorProfile: ExportSensorColorProfile;\n /** Optional NoiseProfile parameters by channel ID. If omitted, no NoiseProfile tag is written. */\n noise?: Readonly<Record<string, NativeRawDngChannelNoise>>;\n /** BaselineExposure in EV (exposure value stops). Default 0: the RAW white level maps to display white, as in native development. */\n baselineExposureEv?: number;\n /** Optional UTC time of the capture, exactly YYYY-MM-DDTHH:mm:ss.sssZ. If omitted, no date tags are written; the engine never makes up a clock time. */\n capturedAtUtc?: string;\n /** Optional (2.4) caller text: description, software, copyright, comment (see the module notes). If omitted, no text is added. */\n textMetadata?: OutputTextMetadata;\n}\nexport interface NativeRawDng {\n schemaVersion: typeof NATIVE_RAW_DNG_SCHEMA_VERSION;\n mediaType: \"image/dng\";\n bytes: Uint8Array;\n sha256: string;\n /** RawDataUniqueID (32 hex digits): the first 128 bits of SHA-256 over a fixed header and the little-endian codes. */\n rawDataUniqueId: string;\n uniqueCameraModel: string;\n /** Stored geometry, levels and colour values exactly as written (rationals as numerator/denominator). */\n activeArea: { x: number; y: number; width: number; height: number };\n defaultCrop: { x: number; y: number; width: number; height: number };\n orientation: number;\n blackLevels: readonly number[];\n whiteLevel: number;\n cfaPattern: readonly number[];\n colorMatrix1: readonly number[];\n asShotNeutral: readonly number[];\n noiseProfile: readonly number[] | null;\n /** Sites flagged saturated whose code is below WhiteLevel; DNG has no field for them. */\n unrepresentedSaturationFlagCount: number;\n source: \"packed-native-raw\";\n linearMasterDeclared: false;\n}\n\nfunction fail(message: string): never { throw new InvalidConfigurationError(\"Native RAW DNG: \" + message); }\nasync function sha256(bytes: Uint8Array): Promise<string> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) fail(\"needs crypto.subtle (a secure browser context or Node 22+).\");\n return Array.from(new Uint8Array(await subtle.digest(\"SHA-256\", bytes as Uint8Array<ArrayBuffer>)), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/** Values exactly as stored by a RATIONAL/SRATIONAL tag (numerator / denominator), so reported metadata equals what a reader decodes. */\nfunction stored(tag: ReturnType<typeof rationals>): number[] {\n const view = new DataView(tag.data.buffer, tag.data.byteOffset, tag.data.byteLength);\n return Array.from({ length: tag.count }, (_, i) => (tag.type === 10 ? view.getInt32(i * 8, true) : view.getUint32(i * 8, true)) / view.getUint32(i * 8 + 4, true));\n}\nconst ORIENTATION = { landscape: 1, \"portrait-clockwise\": 6, \"landscape-inverted\": 3, \"portrait-counter-clockwise\": 8 } as const;\n\n/**\n * Writes packed native RAW codes as a lossless, uncompressed CFA DNG. The module notes list every tag and\n * where its value comes from. The input arrays are copied before the first await.\n */\nexport async function serializeNativeRawDng(input: SerializeNativeRawDngInput): Promise<NativeRawDng> {\n const r = requireAllowlistedRecord(input, [\"raw\", \"colorProfile\", \"noise\", \"baselineExposureEv\", \"capturedAtUtc\", \"textMetadata\"], \"Invalid native RAW DNG input.\");\n const raw = r.raw as NativeRawOutput, plan = validatePackedNativeRaw(raw);\n const mosaic = plan.frame.colorSamplingProfile.layout;\n if (mosaic.kind === \"periodic-mosaic\") checkNativeRawIntegrity(raw, plan.exposure.geometry.nativeRaster.pixelWidth, mosaic.repeatWidthSites, mosaic.repeatHeightSites, 0, plan.exposure.geometry.nativeRaster.pixelHeight);\n const color = parseExportSensorColorProfile(r.colorProfile), frame = plan.frame, layout = frame.colorSamplingProfile.layout;\n if (layout.kind !== \"periodic-mosaic\" || layout.repeatWidthSites !== 2 || layout.repeatHeightSites !== 2 ||\n [...layout.siteChannelIds].sort().join() !== \"blue,green,green,red\" || color.channelIds.join() !== \"red,green,blue\")\n fail(\"supports 2×2 RGB Bayer CFAs with red, green, blue colour-profile channels only.\");\n if (color.colorSamplingProfileId !== frame.colorSamplingProfile.profileId) fail(\"colour profile is not bound to the RAW's CFA.\");\n const baseline = r.baselineExposureEv === undefined ? 0 : r.baselineExposureEv;\n if (typeof baseline !== \"number\" || !Number.isFinite(baseline) || Math.abs(baseline) > 16) fail(\"baselineExposureEv must be finite within ±16.\");\n const capturedAtUtc = r.capturedAtUtc as string | undefined;\n if (capturedAtUtc !== undefined && (typeof capturedAtUtc !== \"string\" || !/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z$/.test(capturedAtUtc) || Number.isNaN(Date.parse(capturedAtUtc))))\n fail(\"capturedAtUtc must be YYYY-MM-DDTHH:mm:ss.sssZ.\");\n let text: Readonly<OutputTextMetadata> | undefined;\n try { text = parseOutputTextMetadata(r.textMetadata, \"textMetadata\"); } catch (error) { fail((error as Error).message); }\n\n const native = plan.exposure.geometry.nativeRaster, width = native.pixelWidth, height = native.pixelHeight, g = plan.exposure.resolvedGeometry;\n const active = g.activeCapture.nativeRect;\n const crop = transformOrientedRasterRectToNative({ rect: g.output.cropRect, nativeRaster: g.activeCapture.raster, orientation: plan.exposure.geometry.orientation });\n // Copy before any await: the caller keeps ownership of the packed arrays.\n const codes = raw.codes.slice(), blacks = raw.blackLevels.slice(), flags = raw.saturationFlags.slice(), whiteByPhase = Array.from(raw.effectiveSaturationCodes);\n\n // Levels per CFA phase, relative to the active area. The black-level tile must repeat exactly.\n const blackLevels: number[] = [], cfaPattern: number[] = [], whites: number[] = [], phaseChannel: string[] = [];\n for (let py = 0; py < 2; py++) for (let px = 0; px < 2; px++) {\n const ax = (active.x + px) % 2, ay = (active.y + py) % 2;\n const black = blacks[ay * width + ax]!;\n for (let y = ay; y < height; y += 2) for (let x = ax; x < width; x += 2) if (blacks[y * width + x] !== black) fail(\"per-site black levels do not repeat with the 2×2 CFA tile.\");\n const channel = layout.siteChannelIds[ay * 2 + ax]!;\n blackLevels.push(black); whites.push(whiteByPhase[ay * 2 + ax]!); phaseChannel.push(channel); cfaPattern.push([\"red\", \"green\", \"blue\"].indexOf(channel));\n }\n const whiteLevel = Math.min(...whites);\n if (blackLevels.some((b) => b >= whiteLevel)) fail(\"black level must be below the effective WhiteLevel.\");\n let unrepresented = 0;\n for (let i = 0; i < codes.length; i++) if (flags[i] !== 0 && codes[i]! < whiteLevel) unrepresented++;\n\n // NoiseProfile: one (S, O) pair per CFA plane colour, only when every phase of a channel shares its black level.\n let noiseProfile: number[] | null = null;\n if (r.noise !== undefined) {\n const noise = requireAllowlistedRecord(r.noise, [\"red\", \"green\", \"blue\"], \"Invalid native RAW DNG noise.\") as Record<string, NativeRawDngChannelNoise>;\n noiseProfile = [];\n for (const channel of [\"red\", \"green\", \"blue\"]) {\n const n = noise[channel];\n if (!n) fail(\"noise needs red, green and blue entries.\");\n requireAllowlistedRecord(n, [\"conversionGainElectronsPerCode\", \"readNoiseRmsElectrons\"], \"Invalid native RAW DNG channel noise.\");\n const gain = n.conversionGainElectronsPerCode, read = n.readNoiseRmsElectrons;\n if (typeof gain !== \"number\" || !Number.isFinite(gain) || gain <= 0 || typeof read !== \"number\" || !Number.isFinite(read) || read < 0) fail(\"noise gain must be positive and read noise non-negative.\");\n const phaseBlacks = blackLevels.filter((_, i) => phaseChannel[i] === channel);\n if (phaseBlacks.some((b) => b !== phaseBlacks[0])) { noiseProfile = null; break; }\n const span = whiteLevel - phaseBlacks[0]!;\n noiseProfile.push(1 / (gain * span), (read * read / (gain * gain) + 1 / 12) / (span * span));\n }\n }\n\n // Colour tags from the declared profile and the capture's white-balance intent.\n const m = color.normalizedCameraChannelsToXyz, colorMatrix = invertSensorColorMatrix(m), intent = plan.exposure.whiteBalanceIntent;\n const development = prepareSensorColorDevelopment(m, intent ? [intent.channelGains.red, intent.channelGains.green, intent.channelGains.blue] : null);\n const cameraWhite = sensorColorReferenceWhite(colorMatrix);\n const chad = chromaticAdaptationMatrix({ transform: \"bradford\", sourceWhiteXyz: resolveCaptureColorModel().referenceWhiteXyz,\n destinationWhiteXyz: { x: ICC_D50_WHITE_XYZ[0], y: 1, z: ICC_D50_WHITE_XYZ[2] } }).matrix;\n const forward = chad.map((row) => [0, 1, 2].map((j) => row.reduce((sum, x, k) => sum + x * m[k]![j]! * cameraWhite[j]!, 0)));\n\n const pixels = new Uint8Array(codes.length * 2), view = new DataView(pixels.buffer);\n codes.forEach((c, i) => view.setUint16(i * 2, c, true));\n const header = new TextEncoder().encode(JSON.stringify({ schema: \"photivra-native-raw-data-id-0.1\", width, height, cfa: layout.siteChannelIds, containerBitDepth: 16 }));\n const idInput = new Uint8Array(header.length + pixels.length); idInput.set(header); idInput.set(pixels, header.length);\n const rawDataUniqueId = (await sha256(idInput)).slice(0, 32);\n const colorHash = (await sha256(new TextEncoder().encode(JSON.stringify(color)))).slice(0, 16);\n const uniqueCameraModel = \"Photivra Virtual Camera \" + color.profileId + \" \" + color.profileVersion + \" \" + colorHash;\n const orientation = ORIENTATION[plan.exposure.geometry.orientation];\n const e = plan.exposure.exposure, software = \"Photivra \" + ENGINE_API_VERSION;\n const statement = \"Simulated capture: packed native RAW from the Photivra engine (\" + frame.frameId + \"). Source \" + plan.exposure.source.kind +\n \"; no linear master image or developed rendering is stored.\";\n const printableAscii = (value: string | undefined): value is string => value !== undefined && /^[\\x20-\\x7e]*$/.test(value);\n const description = printableAscii(text?.description) ? statement + \" \" + text.description : statement;\n const textTags = text === undefined ? [] : [\n ...(printableAscii(text.copyright) ? [ascii(33432, text.copyright)] : []),\n rawBytes(700, 1, xmpTextMetadataPacket({ ...text, description: text.description === undefined ? statement : statement + \" \" + text.description }))];\n\n const exif = [rawBytes(36864, 7, new TextEncoder().encode(\"0232\")), rationals(33434, false, [e.shutterSeconds]), rationals(33437, false, [e.aperture]),\n ...(Number.isInteger(e.iso) && e.iso >= 1 && e.iso <= 65535 ? [numbers(34855, 3, [e.iso]), numbers(34864, 3, [2]), numbers(34866, 4, [e.iso])] : []),\n rationals(37386, false, [e.focalLengthMm]), numbers(40961, 3, [65535]), numbers(40962, 4, [crop.width]), numbers(40963, 4, [crop.height]),\n ...(capturedAtUtc === undefined ? [] : [ascii(36867, capturedAtUtc.slice(0, 19).replaceAll(\"-\", \":\").replace(\"T\", \" \")), ascii(36881, \"+00:00\"), ascii(37521, capturedAtUtc.slice(20, 23))])];\n const colorMatrixTag = rationals(50721, true, colorMatrix.flat()), neutralTag = rationals(50728, false, [...development.asShotNeutral]);\n const bytes = packExportTiff([ascii(270, description), ascii(271, \"Photivra\"), ascii(272, \"Photivra Virtual Camera\"), ascii(305, software), numbers(274, 3, [orientation]),\n numbers(254, 4, [0]), numbers(256, 4, [width]), numbers(257, 4, [height]), numbers(258, 3, [16]), numbers(259, 3, [1]), numbers(262, 3, [32803]),\n { ...numbers(273, 4, [0]), pointer: \"pixels\" as const }, numbers(277, 3, [1]), numbers(278, 4, [height]), numbers(279, 4, [pixels.length]),\n numbers(284, 3, [1]), numbers(339, 3, [1]), numbers(33421, 3, [2, 2]), numbers(33422, 1, cfaPattern),\n numbers(50706, 1, [1, 4, 0, 0]), numbers(50707, 1, [1, 1, 0, 0]), ascii(50708, uniqueCameraModel), numbers(50710, 1, [0, 1, 2]), numbers(50711, 3, [1]),\n numbers(50713, 3, [2, 2]), rationals(50714, false, blackLevels), numbers(50717, 4, [whiteLevel]), numbers(50719, 4, [crop.x, crop.y]), numbers(50720, 4, [crop.width, crop.height]),\n colorMatrixTag, rationals(50727, false, [1, 1, 1]), neutralTag,\n rationals(50730, true, [baseline]), numbers(50778, 3, [21]),\n rawBytes(50781, 1, Uint8Array.from(rawDataUniqueId.match(/../g)!.map((s) => parseInt(s, 16)))),\n numbers(50829, 4, [active.y, active.x, active.y + active.height, active.x + active.width]),\n rationals(50964, true, forward.flat()), ...(noiseProfile ? [doubles(51041, noiseProfile)] : []), ...textTags], exif, pixels);\n return Object.freeze({ schemaVersion: NATIVE_RAW_DNG_SCHEMA_VERSION, mediaType: \"image/dng\" as const, bytes, sha256: await sha256(bytes), rawDataUniqueId, uniqueCameraModel,\n activeArea: { ...active }, defaultCrop: { ...crop }, orientation, blackLevels, whiteLevel, cfaPattern, colorMatrix1: stored(colorMatrixTag), asShotNeutral: stored(neutralTag),\n noiseProfile, unrepresentedSaturationFlagCount: unrepresented, source: \"packed-native-raw\" as const, linearMasterDeclared: false as const });\n}\n"]}
1
+ {"version":3,"file":"native-raw-dng.js","sourceRoot":"","sources":["../../src/capture/native-raw-dng.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,+DAA+D;AAE/D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2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AAc,CAAC,EAAE,aAAa,EAAE,MAAM,CAAC,UAAU,CAAC;QAC9K,YAAY,EAAE,gCAAgC,EAAE,aAAa,EAAE,MAAM,EAAE,mBAA4B,EAAE,oBAAoB,EAAE,KAAc,EAAE,CAAC,CAAC;AACjJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n// This product includes DNG technology under license by Adobe.\n\n/**\n * Writes a packed native RAW (`NativeRawOutput`, from the native RAW or native environment RAW tasks) as a\n * lossless, uncompressed 16-bit DNG with a CFA (colour filter array) mosaic.\n *\n * The file describes only what the packed RAW, the caller's declared colour profile and noise model\n * contain. It never claims a linear float master as its source, or a developed image. The tag layout reuses\n * the TIFF/DNG writers of the paired photographic export (`packExportTiff`, DNG 1.4 tags, Adobe DNG\n * Specification 1.7.1.0):\n *\n * - CFA geometry: CFARepeatPatternDim 2×2, CFAPattern and BlackLevel phases relative to the ActiveArea\n * origin (DNG applies them to the stage-2, ActiveArea-cropped image); DefaultCropOrigin/Size are the\n * capture's oriented output crop mapped back to stored (native) coordinates; Orientation from the capture.\n * - Levels: BlackLevel per 2×2 phase (the packed per-site black levels must repeat with the CFA tile).\n * WhiteLevel is the smallest per-phase effective white code, so no channel is reported as unsaturated\n * above its own saturation point. DNG cannot represent a saturation flag on a site whose code is below\n * WhiteLevel; such sites are counted in `unrepresentedSaturationFlagCount`.\n * - Colour: ColorMatrix1 = (camera→XYZ)⁻¹ with CalibrationIlluminant1 D65 (21), ForwardMatrix1 =\n * Bradford(D65→D50)·M·diag(w), AnalogBalance 1, AsShotNeutral from the capture's white-balance intent\n * (the same operator native development uses), BaselineExposure as declared (default 0).\n * - Noise: NoiseProfile (51041) per CFA plane, var(x) = S·x + O for x = (code − black)/(WhiteLevel − black),\n * S = 1/(G·span), O = (σ_read²/G² + 1/12)/span², written only when the caller supplies each channel's\n * output-referred conversion gain G (electrons per code) and read noise σ_read (electrons). The model\n * covers only Poisson photo and dark shot noise, Gaussian read noise and uniform quantization. It is an\n * approximation: PRNU (photo-response non-uniformity), DSNU (dark-signal non-uniformity) and other\n * fixed-pattern noise are not included.\n * - Text (2.4, only with `textMetadata`): the caller's description is appended to ImageDescription after the\n * simulated-RAW statement and the copyright is written as Copyright (33432), each only when it is printable\n * ASCII (TIFF 6.0 §2: ASCII fields hold 7-bit codes). An XMP packet in tag 700 (BYTE; XMP Specification Part 3\n * §1.1.6, Table 13) always carries every given field in UTF-8: `dc:description` (the full ImageDescription text,\n * statement first, as XMP Part 3 §3.2.3 maps tag 270), `dc:rights`, `xmp:CreatorTool` and `exif:UserComment`.\n * The Software tag keeps naming the engine's writer. Without `textMetadata` the bytes are unchanged.\n * - Opcodes (#587, only with `opcodeList3`): the caller's big-endian DNG opcode list as OpcodeList3 (51022, UNDEFINED), framing checked\n * (count, 16-byte headers, parameter sizes filling the bytes). Without it the bytes are unchanged.\n * @see docs/NATIVE_RAW_AND_PRINT.md for the tag table, limits and the round trip through parseDngRawImage.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { ENGINE_API_VERSION } from \"../core/version.js\";\nimport { resolveCaptureColorModel } from \"../color/capture-color.js\";\nimport { invertSensorColorMatrix, prepareSensorColorDevelopment, sensorColorReferenceWhite } from \"../color/sensor-color-development.js\";\nimport { ICC_D50_WHITE_XYZ } from \"../color/srgb-icc.js\";\nimport { chromaticAdaptationMatrix } from \"../color/chromatic-adaptation.js\";\nimport { transformOrientedRasterRectToNative } from \"../output/capture-geometry.js\";\nimport type { NativeRawOutput } from \"./native-raw.js\";\nimport { checkNativeRawIntegrity, validatePackedNativeRaw } from \"./native-raw-development.js\";\nimport { parseExportSensorColorProfile, type ExportSensorColorProfile } from \"./photographic-export.js\";\nimport { parseOutputTextMetadata, xmpTextMetadataPacket, type OutputTextMetadata } from \"../output/text-metadata.js\";\nimport { packExportTiff, exportTiffAscii as ascii, exportTiffNumbers as numbers, exportTiffRationals as rationals,\n exportTiffBytes as rawBytes, exportTiffDoubles as doubles } from \"./export-tiff.js\";\n\nexport const NATIVE_RAW_DNG_SCHEMA_VERSION = \"1.0.0\" as const;\n\n/** Output-referred noise parameters of one CFA channel (see the module notes). */\nexport interface NativeRawDngChannelNoise {\n /** Electrons per output RAW code (system conversion gain divided by any post-ADC digital gain). */\n conversionGainElectronsPerCode: number;\n /** Combined RMS read noise, electrons. */\n readNoiseRmsElectrons: number;\n}\nexport interface SerializeNativeRawDngInput {\n /** Packed native RAW. It is read, never taken over or modified. */\n raw: NativeRawOutput;\n /** Declared camera→XYZ (D65) colour profile for the RAW's CFA. Native development uses the same profile. */\n colorProfile: ExportSensorColorProfile;\n /** Optional NoiseProfile parameters by channel ID. If omitted, no NoiseProfile tag is written. */\n noise?: Readonly<Record<string, NativeRawDngChannelNoise>>;\n /** BaselineExposure in EV (exposure value stops). Default 0: the RAW white level maps to display white, as in native development. */\n baselineExposureEv?: number;\n /** Optional UTC time of the capture, exactly YYYY-MM-DDTHH:mm:ss.sssZ. If omitted, no date tags are written; the engine never makes up a clock time. */\n capturedAtUtc?: string;\n /** Optional (2.4) caller text: description, software, copyright, comment (see the module notes). If omitted, no text is added. */\n textMetadata?: OutputTextMetadata;\n /**\n * Optional (#587) OpcodeList3 (tag 51022) bytes, for example `createDngLensCorrectionOpcodes(...).opcodeList3`: a big-endian DNG\n * opcode list (DNG 1.3.0.0+, \"Opcode List Processing\") that readers apply to the demosaiced stage-3 image. Only its framing is\n * checked (count, per-opcode headers and parameter sizes filling the bytes exactly). The RAW codes are unchanged. If omitted, no tag.\n */\n opcodeList3?: Uint8Array;\n}\nexport interface NativeRawDng {\n schemaVersion: typeof NATIVE_RAW_DNG_SCHEMA_VERSION;\n mediaType: \"image/dng\";\n bytes: Uint8Array;\n sha256: string;\n /** RawDataUniqueID (32 hex digits): the first 128 bits of SHA-256 over a fixed header and the little-endian codes. */\n rawDataUniqueId: string;\n uniqueCameraModel: string;\n /** Stored geometry, levels and colour values exactly as written (rationals as numerator/denominator). */\n activeArea: { x: number; y: number; width: number; height: number };\n defaultCrop: { x: number; y: number; width: number; height: number };\n orientation: number;\n blackLevels: readonly number[];\n whiteLevel: number;\n cfaPattern: readonly number[];\n colorMatrix1: readonly number[];\n asShotNeutral: readonly number[];\n noiseProfile: readonly number[] | null;\n /** Sites flagged saturated whose code is below WhiteLevel; DNG has no field for them. */\n unrepresentedSaturationFlagCount: number;\n source: \"packed-native-raw\";\n linearMasterDeclared: false;\n}\n\nfunction fail(message: string): never { throw new InvalidConfigurationError(\"Native RAW DNG: \" + message); }\nasync function sha256(bytes: Uint8Array): Promise<string> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) fail(\"needs crypto.subtle (a secure browser context or Node 22+).\");\n return Array.from(new Uint8Array(await subtle.digest(\"SHA-256\", bytes as Uint8Array<ArrayBuffer>)), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/** Values exactly as stored by a RATIONAL/SRATIONAL tag (numerator / denominator), so reported metadata equals what a reader decodes. */\nfunction stored(tag: ReturnType<typeof rationals>): number[] {\n const view = new DataView(tag.data.buffer, tag.data.byteOffset, tag.data.byteLength);\n return Array.from({ length: tag.count }, (_, i) => (tag.type === 10 ? view.getInt32(i * 8, true) : view.getUint32(i * 8, true)) / view.getUint32(i * 8 + 4, true));\n}\nconst ORIENTATION = { landscape: 1, \"portrait-clockwise\": 6, \"landscape-inverted\": 3, \"portrait-counter-clockwise\": 8 } as const;\n\n/**\n * Writes packed native RAW codes as a lossless, uncompressed CFA DNG. The module notes list every tag and\n * where its value comes from. The input arrays are copied before the first await.\n */\nexport async function serializeNativeRawDng(input: SerializeNativeRawDngInput): Promise<NativeRawDng> {\n const r = requireAllowlistedRecord(input, [\"raw\", \"colorProfile\", \"noise\", \"baselineExposureEv\", \"capturedAtUtc\", \"textMetadata\", \"opcodeList3\"], \"Invalid native RAW DNG input.\");\n let opcodeList3: Uint8Array | undefined;\n if (r.opcodeList3 !== undefined) {\n if (!(r.opcodeList3 instanceof Uint8Array) || r.opcodeList3.length < 4) fail(\"opcodeList3 must be a Uint8Array opcode list.\");\n opcodeList3 = r.opcodeList3.slice();\n const v = new DataView(opcodeList3.buffer);\n let at = 4;\n for (let n = v.getUint32(0); n > 0 && at <= opcodeList3.length; n--) at = at + 16 > opcodeList3.length ? Infinity : at + 16 + v.getUint32(at + 12);\n if (at !== opcodeList3.length) fail(\"opcodeList3 is not a whole DNG opcode list (big-endian count, 16-byte headers, parameter sizes).\");\n }\n const raw = r.raw as NativeRawOutput, plan = validatePackedNativeRaw(raw);\n const mosaic = plan.frame.colorSamplingProfile.layout;\n if (mosaic.kind === \"periodic-mosaic\") checkNativeRawIntegrity(raw, plan.exposure.geometry.nativeRaster.pixelWidth, mosaic.repeatWidthSites, mosaic.repeatHeightSites, 0, plan.exposure.geometry.nativeRaster.pixelHeight);\n const color = parseExportSensorColorProfile(r.colorProfile), frame = plan.frame, layout = frame.colorSamplingProfile.layout;\n if (layout.kind !== \"periodic-mosaic\" || layout.repeatWidthSites !== 2 || layout.repeatHeightSites !== 2 ||\n [...layout.siteChannelIds].sort().join() !== \"blue,green,green,red\" || color.channelIds.join() !== \"red,green,blue\")\n fail(\"supports 2×2 RGB Bayer CFAs with red, green, blue colour-profile channels only.\");\n if (color.colorSamplingProfileId !== frame.colorSamplingProfile.profileId) fail(\"colour profile is not bound to the RAW's CFA.\");\n const baseline = r.baselineExposureEv === undefined ? 0 : r.baselineExposureEv;\n if (typeof baseline !== \"number\" || !Number.isFinite(baseline) || Math.abs(baseline) > 16) fail(\"baselineExposureEv must be finite within ±16.\");\n const capturedAtUtc = r.capturedAtUtc as string | undefined;\n if (capturedAtUtc !== undefined && (typeof capturedAtUtc !== \"string\" || !/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z$/.test(capturedAtUtc) || Number.isNaN(Date.parse(capturedAtUtc))))\n fail(\"capturedAtUtc must be YYYY-MM-DDTHH:mm:ss.sssZ.\");\n let text: Readonly<OutputTextMetadata> | undefined;\n try { text = parseOutputTextMetadata(r.textMetadata, \"textMetadata\"); } catch (error) { fail((error as Error).message); }\n\n const native = plan.exposure.geometry.nativeRaster, width = native.pixelWidth, height = native.pixelHeight, g = plan.exposure.resolvedGeometry;\n const active = g.activeCapture.nativeRect;\n const crop = transformOrientedRasterRectToNative({ rect: g.output.cropRect, nativeRaster: g.activeCapture.raster, orientation: plan.exposure.geometry.orientation });\n // Copy before any await: the caller keeps ownership of the packed arrays.\n const codes = raw.codes.slice(), blacks = raw.blackLevels.slice(), flags = raw.saturationFlags.slice(), whiteByPhase = Array.from(raw.effectiveSaturationCodes);\n\n // Levels per CFA phase, relative to the active area. The black-level tile must repeat exactly.\n const blackLevels: number[] = [], cfaPattern: number[] = [], whites: number[] = [], phaseChannel: string[] = [];\n for (let py = 0; py < 2; py++) for (let px = 0; px < 2; px++) {\n const ax = (active.x + px) % 2, ay = (active.y + py) % 2;\n const black = blacks[ay * width + ax]!;\n for (let y = ay; y < height; y += 2) for (let x = ax; x < width; x += 2) if (blacks[y * width + x] !== black) fail(\"per-site black levels do not repeat with the 2×2 CFA tile.\");\n const channel = layout.siteChannelIds[ay * 2 + ax]!;\n blackLevels.push(black); whites.push(whiteByPhase[ay * 2 + ax]!); phaseChannel.push(channel); cfaPattern.push([\"red\", \"green\", \"blue\"].indexOf(channel));\n }\n const whiteLevel = Math.min(...whites);\n if (blackLevels.some((b) => b >= whiteLevel)) fail(\"black level must be below the effective WhiteLevel.\");\n let unrepresented = 0;\n for (let i = 0; i < codes.length; i++) if (flags[i] !== 0 && codes[i]! < whiteLevel) unrepresented++;\n\n // NoiseProfile: one (S, O) pair per CFA plane colour, only when every phase of a channel shares its black level.\n let noiseProfile: number[] | null = null;\n if (r.noise !== undefined) {\n const noise = requireAllowlistedRecord(r.noise, [\"red\", \"green\", \"blue\"], \"Invalid native RAW DNG noise.\") as Record<string, NativeRawDngChannelNoise>;\n noiseProfile = [];\n for (const channel of [\"red\", \"green\", \"blue\"]) {\n const n = noise[channel];\n if (!n) fail(\"noise needs red, green and blue entries.\");\n requireAllowlistedRecord(n, [\"conversionGainElectronsPerCode\", \"readNoiseRmsElectrons\"], \"Invalid native RAW DNG channel noise.\");\n const gain = n.conversionGainElectronsPerCode, read = n.readNoiseRmsElectrons;\n if (typeof gain !== \"number\" || !Number.isFinite(gain) || gain <= 0 || typeof read !== \"number\" || !Number.isFinite(read) || read < 0) fail(\"noise gain must be positive and read noise non-negative.\");\n const phaseBlacks = blackLevels.filter((_, i) => phaseChannel[i] === channel);\n if (phaseBlacks.some((b) => b !== phaseBlacks[0])) { noiseProfile = null; break; }\n const span = whiteLevel - phaseBlacks[0]!;\n noiseProfile.push(1 / (gain * span), (read * read / (gain * gain) + 1 / 12) / (span * span));\n }\n }\n\n // Colour tags from the declared profile and the capture's white-balance intent.\n const m = color.normalizedCameraChannelsToXyz, colorMatrix = invertSensorColorMatrix(m), intent = plan.exposure.whiteBalanceIntent;\n const development = prepareSensorColorDevelopment(m, intent ? [intent.channelGains.red, intent.channelGains.green, intent.channelGains.blue] : null);\n const cameraWhite = sensorColorReferenceWhite(colorMatrix);\n const chad = chromaticAdaptationMatrix({ transform: \"bradford\", sourceWhiteXyz: resolveCaptureColorModel().referenceWhiteXyz,\n destinationWhiteXyz: { x: ICC_D50_WHITE_XYZ[0], y: 1, z: ICC_D50_WHITE_XYZ[2] } }).matrix;\n const forward = chad.map((row) => [0, 1, 2].map((j) => row.reduce((sum, x, k) => sum + x * m[k]![j]! * cameraWhite[j]!, 0)));\n\n const pixels = new Uint8Array(codes.length * 2), view = new DataView(pixels.buffer);\n codes.forEach((c, i) => view.setUint16(i * 2, c, true));\n const header = new TextEncoder().encode(JSON.stringify({ schema: \"photivra-native-raw-data-id-0.1\", width, height, cfa: layout.siteChannelIds, containerBitDepth: 16 }));\n const idInput = new Uint8Array(header.length + pixels.length); idInput.set(header); idInput.set(pixels, header.length);\n const rawDataUniqueId = (await sha256(idInput)).slice(0, 32);\n const colorHash = (await sha256(new TextEncoder().encode(JSON.stringify(color)))).slice(0, 16);\n const uniqueCameraModel = \"Photivra Virtual Camera \" + color.profileId + \" \" + color.profileVersion + \" \" + colorHash;\n const orientation = ORIENTATION[plan.exposure.geometry.orientation];\n const e = plan.exposure.exposure, software = \"Photivra \" + ENGINE_API_VERSION;\n const statement = \"Simulated capture: packed native RAW from the Photivra engine (\" + frame.frameId + \"). Source \" + plan.exposure.source.kind +\n \"; no linear master image or developed rendering is stored.\";\n const printableAscii = (value: string | undefined): value is string => value !== undefined && /^[\\x20-\\x7e]*$/.test(value);\n const description = printableAscii(text?.description) ? statement + \" \" + text.description : statement;\n const textTags = text === undefined ? [] : [\n ...(printableAscii(text.copyright) ? [ascii(33432, text.copyright)] : []),\n rawBytes(700, 1, xmpTextMetadataPacket({ ...text, description: text.description === undefined ? statement : statement + \" \" + text.description }))];\n\n const exif = [rawBytes(36864, 7, new TextEncoder().encode(\"0232\")), rationals(33434, false, [e.shutterSeconds]), rationals(33437, false, [e.aperture]),\n ...(Number.isInteger(e.iso) && e.iso >= 1 && e.iso <= 65535 ? [numbers(34855, 3, [e.iso]), numbers(34864, 3, [2]), numbers(34866, 4, [e.iso])] : []),\n rationals(37386, false, [e.focalLengthMm]), numbers(40961, 3, [65535]), numbers(40962, 4, [crop.width]), numbers(40963, 4, [crop.height]),\n ...(capturedAtUtc === undefined ? [] : [ascii(36867, capturedAtUtc.slice(0, 19).replaceAll(\"-\", \":\").replace(\"T\", \" \")), ascii(36881, \"+00:00\"), ascii(37521, capturedAtUtc.slice(20, 23))])];\n const colorMatrixTag = rationals(50721, true, colorMatrix.flat()), neutralTag = rationals(50728, false, [...development.asShotNeutral]);\n const bytes = packExportTiff([ascii(270, description), ascii(271, \"Photivra\"), ascii(272, \"Photivra Virtual Camera\"), ascii(305, software), numbers(274, 3, [orientation]),\n numbers(254, 4, [0]), numbers(256, 4, [width]), numbers(257, 4, [height]), numbers(258, 3, [16]), numbers(259, 3, [1]), numbers(262, 3, [32803]),\n { ...numbers(273, 4, [0]), pointer: \"pixels\" as const }, numbers(277, 3, [1]), numbers(278, 4, [height]), numbers(279, 4, [pixels.length]),\n numbers(284, 3, [1]), numbers(339, 3, [1]), numbers(33421, 3, [2, 2]), numbers(33422, 1, cfaPattern),\n numbers(50706, 1, [1, 4, 0, 0]), numbers(50707, 1, [1, 1, 0, 0]), ascii(50708, uniqueCameraModel), numbers(50710, 1, [0, 1, 2]), numbers(50711, 3, [1]),\n numbers(50713, 3, [2, 2]), rationals(50714, false, blackLevels), numbers(50717, 4, [whiteLevel]), numbers(50719, 4, [crop.x, crop.y]), numbers(50720, 4, [crop.width, crop.height]),\n colorMatrixTag, rationals(50727, false, [1, 1, 1]), neutralTag,\n rationals(50730, true, [baseline]), numbers(50778, 3, [21]),\n rawBytes(50781, 1, Uint8Array.from(rawDataUniqueId.match(/../g)!.map((s) => parseInt(s, 16)))),\n numbers(50829, 4, [active.y, active.x, active.y + active.height, active.x + active.width]),\n rationals(50964, true, forward.flat()), ...(noiseProfile ? [doubles(51041, noiseProfile)] : []), ...(opcodeList3 ? [rawBytes(51022, 7, opcodeList3)] : []), ...textTags], exif, pixels);\n return Object.freeze({ schemaVersion: NATIVE_RAW_DNG_SCHEMA_VERSION, mediaType: \"image/dng\" as const, bytes, sha256: await sha256(bytes), rawDataUniqueId, uniqueCameraModel,\n activeArea: { ...active }, defaultCrop: { ...crop }, orientation, blackLevels, whiteLevel, cfaPattern, colorMatrix1: stored(colorMatrixTag), asShotNeutral: stored(neutralTag),\n noiseProfile, unrepresentedSaturationFlagCount: unrepresented, source: \"packed-native-raw\" as const, linearMasterDeclared: false as const });\n}\n"]}
@@ -2,6 +2,7 @@
2
2
  * Native RAW capture with the existing per-site (scalar) RAW model: an up-front plan and limit check from
3
3
  * metadata only, then bounded tile-by-tile execution.
4
4
  */
5
+ import { type ExposureBuildUpStage } from "./exposure-build-up-stage.js";
5
6
  import { type SimulatedCaptureInput, type SimulatedCapture, type CaptureExposureSource } from "./simulated-capture.js";
6
7
  import { type HostYieldCadence, type HostYieldGate } from "./host-yield-cadence.js";
7
8
  import { calculateCaptureExposureWindows } from "../sensor/exposure-window.js";
@@ -105,8 +106,8 @@ export interface NativeRawLeanOutput {
105
106
  */
106
107
  export interface NativeRawLeanSensorHook {
107
108
  claim(site: unknown): object | undefined;
108
- compute(handle: object, index: number, seed: number, timing: ReturnType<typeof calculateCaptureExposureWindows>["value"]["samples"][number] | undefined): NativeRawLeanOutput;
109
- observe(index: number, parsed: SensorRawProducerSiteInput, result: ReturnType<typeof calculateNativeRawSite>, whiteCode: number, seed: number): void;
109
+ compute(handle: object, index: number, seed: number, timing: ReturnType<typeof calculateCaptureExposureWindows>["value"]["samples"][number] | undefined, b?: ExposureBuildUpStage): NativeRawLeanOutput;
110
+ observe(index: number, parsed: SensorRawProducerSiteInput, result: ReturnType<typeof calculateNativeRawSite>, whiteCode: number, seed: number, b?: ExposureBuildUpStage): void;
110
111
  }
111
112
  export type NativeRawTaskState = "ready" | "running" | "completed" | "cancelled" | "failed" | "disposed" | "transferred";
112
113
  export interface NativeRawTask {
@@ -3,6 +3,7 @@
3
3
  * Native RAW capture with the existing per-site (scalar) RAW model: an up-front plan and limit check from
4
4
  * metadata only, then bounded tile-by-tile execution.
5
5
  */
6
+ import { EXPOSURE_BUILD_UP_STAGES } from "./exposure-build-up-stage.js";
6
7
  import { normalizeCaptureExposureMetadata } from "./simulated-capture.js";
7
8
  import { ENGINE_API_VERSION } from "../core/version.js";
8
9
  import { InvalidConfigurationError } from "../core/configuration-error.js";
@@ -163,12 +164,12 @@ rows) {
163
164
  if (s)
164
165
  validateNativeRawReadoutIdentity(s, first);
165
166
  // Every site in this tile is validated before any output is written. A failure never returns partial output.
166
- const seed = plan.exposure.noise.seedUint32;
167
+ const seed = plan.exposure.noise.seedUint32, b = EXPOSURE_BUILD_UP_STAGES.get(input);
167
168
  for (let j = 0; j < sites.length; j++) {
168
169
  // index: absolute native index (seeds, CFA phase); at: position in this task's output arrays.
169
170
  const index = y * native.pixelWidth + x + j, at = (y - rowStart) * bandWidth + x + j - colStart, handle = lean?.[j];
170
171
  if (handle) {
171
- const o = leanSensor.compute(handle, index, seed, timing?.samples[j]);
172
+ const o = leanSensor.compute(handle, index, seed, timing?.samples[j], b);
172
173
  output.codes[at] = o.rawCode;
173
174
  output.blackLevels[at] = o.blackLevelCode;
174
175
  output.digitalSaturationCodes[at] = o.digitalSaturationCode;
@@ -176,14 +177,14 @@ rows) {
176
177
  white.record(index, o.whiteCode);
177
178
  continue;
178
179
  }
179
- const result = calculateNativeRawSite(sites[j], seed, index), r = result.readout.value;
180
+ const result = calculateNativeRawSite(sites[j], seed, index, b), r = result.readout.value;
180
181
  output.codes[at] = r.rawCode;
181
182
  output.blackLevels[at] = r.blackLevelCode;
182
183
  output.digitalSaturationCodes[at] = r.digitalSaturationCode;
183
184
  output.saturationFlags[at] = Number(r.physicalScalarSaturationApplied) | Number(r.preAdcSaturationApplied) << 1 | Number(r.digitalSaturationApplied) << 2;
184
185
  const whiteCode = calculateSiteEffectiveSaturationCode(r, sites[j].readoutProfile, sites[j].regimeId);
185
186
  white.record(index, whiteCode);
186
- leanSensor?.observe(index, sites[j], result, whiteCode, seed);
187
+ leanSensor?.observe(index, sites[j], result, whiteCode, seed, b);
187
188
  }
188
189
  count++;
189
190
  }
@@ -1 +1 @@
1
- {"version":3,"file":"native-raw.js","sourceRoot":"","sources":["../../src/capture/native-raw.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;GAGG;AACH,OAAO,EAAE,gCAAgC,EAAiF,MAAM,wBAAwB,CAAC;AACzJ,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,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,GAAC,WAAW,CAAC;YAC7G,CAAC;YAAA,OAAM,KAAK,EAAC,CAAC;gBAAA,OAAO,EAAE,CAAC;gBAAA,IAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAC,CAAC;oBAAA,KAAK,GAAC,QAAQ,CAAC;oBAAA,KAAK,CAAC,KAAK,EAAE,CAAC;gBAAA,CAAC;gBAAA,MAAM,KAAK,CAAC;YAAA,CAAC;QAC/F,CAAC;QACD,MAAM,KAAU,IAAG,KAAK,KAAG,OAAO,IAAE,KAAK,KAAG,SAAS,IAAE,KAAK,KAAG,WAAW,EAAC,CAAC;YAAA,KAAK,GAAC,WAAW,CAAC;YAAA,KAAK,CAAC,KAAK,EAAE,CAAC;YAAA,OAAO,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC;QACxH,OAAO,KAAU,IAAG,KAAK,KAAG,aAAa,EAAC,CAAC;YAAA,KAAK,GAAC,UAAU,CAAC;YAAA,KAAK,CAAC,KAAK,EAAE,CAAC;YAAA,OAAO,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC;QACtF,UAAU,KAAqB,IAAG,KAAK,KAAG,WAAW,IAAE,CAAC,MAAM;YAAC,MAAM,IAAI,yBAAyB,CAAC,gCAAgC,CAAC,CAAC,CAAA,MAAM,MAAM,GAAC,MAAM,CAAC,CAAA,MAAM,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,SAAS,CAAC,CAAA,KAAK,GAAC,aAAa,CAAC,CAAA,OAAO,MAAM,CAAC,CAAA,CAAC;KACzN,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW capture with the existing per-site (scalar) RAW model: an up-front plan and limit check from\n * metadata only, then bounded tile-by-tile execution.\n */\nimport { normalizeCaptureExposureMetadata, type SimulatedCaptureInput, type SimulatedCapture, type CaptureExposureSource } from \"./simulated-capture.js\";\nimport { ENGINE_API_VERSION } from \"../core/version.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord, requirePublicOpaqueId } from \"../core/record-validation.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit, scaleBudgetCeiling } from \"../core/pixel-limits.js\";\nimport { calculateSiteEffectiveSaturationCode, createPhaseWhiteLevelAccumulator } from \"./raw-white-level.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence, type HostYieldGate } from \"./host-yield-cadence.js\";\nimport { parseCaptureModeProfile } from \"../sensor/capture-mode.js\";\nimport { parseSensorColorSamplingProfile } from \"../sensor/color-sampling.js\";\nimport { parseNativeEffectiveRasterColorSamplingBindingProfile, resolveCaptureModeColorSamplingContributors } from \"../sensor/capture-color-sampling-binding.js\";\nimport { calculateCaptureExposureWindows } from \"../sensor/exposure-window.js\";\nimport { SENSOR_RAW_PRODUCER_NOISE_MODEL, calculateNativeRawSite, parseNativeRawProducerSite,\n validateNativeRawReadoutIdentity, type NativeRawProducerFrameContext, type SensorRawProducerSiteInput,\n type SensorRawProducerExposureWindowInput } from \"./sensor-raw-producer.js\";\n\nexport const NATIVE_RAW_SCHEMA_VERSION = \"0.1.0\" as const;\n/** `maximumPixels` is the default pixel limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */\nexport const NATIVE_RAW_LIMITS = /* @__PURE__ */ Object.freeze({ maximumPixels: 24_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS, maximumDimension: 16_384,\n tileWidth: 256, tileHeight: 1, outputBytesPerPixel: 7 });\n/** Default whole-event radiance query budget ceiling of the native environment tasks; it scales with a raised `maximumPixels`. */\nconst DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS = 2_000_000_000;\n/** A shooting event and where its source came from. Not a finished float master or committed RAW frame. */\nexport type NativeRawExposureInput = Omit<SimulatedCaptureInput, \"planes\" | \"source\"> & {source:CaptureExposureSource};\nexport type NativeRawExposure = Omit<SimulatedCapture, \"schemaVersion\" | \"planes\" | \"source\"> & {source:CaptureExposureSource};\nexport interface NativeRawInput {\n exposure: NativeRawExposureInput;\n frameId: string;\n modeId: string;\n captureModeProfile: NativeRawProducerFrameContext[\"captureModeProfile\"];\n colorSamplingProfile: NativeRawProducerFrameContext[\"colorSamplingProfile\"];\n bindingProfile: NativeRawProducerFrameContext[\"bindingProfile\"];\n exposureWindow?: SensorRawProducerExposureWindowInput;\n maximumOutputBytes: number;\n /** Optional tile width for execution, in native sites, 1–256. Default 256. It does not affect sampling. */\n tileWidth?: number;\n /**\n * Optional opt-in pixel limit for large sensors: an integer from 1 to `NATIVE_RAW_LIMITS.ceilingPixels`.\n * Default `NATIVE_RAW_LIMITS.maximumPixels` (24 000 000). `maximumOutputBytes` still applies. A raised limit\n * also raises the native environment tasks' whole-event query budget ceiling in proportion\n * (2 000 000 000 per 24 000 000 pixels). It does not affect sampling.\n */\n maximumPixels?: number;\n}\nexport interface NativeRawPlan {\n schemaVersion: typeof NATIVE_RAW_SCHEMA_VERSION;\n exposure: NativeRawExposure;\n frame: NativeRawProducerFrameContext;\n exposureWindow?: SensorRawProducerExposureWindowInput;\n pixelCount: number;\n outputBytes: number;\n tileCount: number;\n /** Present only when an execution tile width was given. Otherwise the plan keeps its earlier shape. */\n tileWidth?: number;\n /** Present only when a pixel limit was given. Otherwise the plan keeps its earlier shape. */\n maximumPixels?: number;\n upstreamRadiometryVerified: false;\n seedSchedule: \"murmur3-capture-seed-native-index-stream-v2\";\n}\n/** Tile rectangle, in absolute full-sensor CFA coordinates, before orientation, active-area crop or output scaling. */\nexport interface NativeRawTileRequest { captureId: string; frameId: string; x: number; y: number; width: number; height: number }\nexport interface NativeRawTile extends NativeRawTileRequest { sites: readonly SensorRawProducerSiteInput[] }\nexport interface NativeRawProvider {\n readTile(request: Readonly<NativeRawTileRequest>, signal: AbortSignal): Promise<NativeRawTile>;\n yieldControl(signal: AbortSignal): Promise<void>;\n}\n/** Row-major arrays owned only by the output. They cannot be attached to the bounded SensorRawFrame type. */\nexport interface NativeRawOutput {\n plan: NativeRawPlan;\n codes: Uint16Array;\n blackLevels: Uint16Array;\n digitalSaturationCodes: Uint16Array;\n /** Saturation flags. Bit 0: physical charge clamp; bit 1: pre-ADC clamp; bit 2: digital saturation. */\n saturationFlags: Uint8Array;\n /**\n * Effective white (full-saturation) code for each absolute CFA repeat phase, indexed\n * `phaseY*repeatWidthSites+phaseX`: min(digital saturation, round(black + min(capacity, pre-ADC\n * saturation)/gain)). See `calculateEffectiveSaturationCode`. A few bytes, not one value per pixel.\n */\n effectiveSaturationCodes: Uint16Array;\n}\n/** Internal: lean per-site outputs of an engine-built site (see native-environment-lean.ts). */\nexport interface NativeRawLeanOutput { rawCode: number; blackLevelCode: number; digitalSaturationCode: number; flags: number; whiteCode: number }\n/**\n * Internal hook for tiles the engine builds itself (native environment RAW).\n *\n * claim() recognizes only entries the hook itself created, for sites whose parsing and identity checks are\n * provably redundant. compute() returns the outputs calculateNativeRawSite would produce, falling back to it\n * internally. observe() sees every fully computed site.\n */\nexport interface NativeRawLeanSensorHook {\n claim(site: unknown): object | undefined;\n compute(handle: object, index: number, seed: number, timing: ReturnType<typeof calculateCaptureExposureWindows>[\"value\"][\"samples\"][number] | undefined): NativeRawLeanOutput;\n observe(index: number, parsed: SensorRawProducerSiteInput, result: ReturnType<typeof calculateNativeRawSite>, whiteCode: number, seed: number): void;\n}\nexport type NativeRawTaskState = \"ready\" | \"running\" | \"completed\" | \"cancelled\" | \"failed\" | \"disposed\" | \"transferred\";\nexport interface NativeRawTask {\n readonly plan: NativeRawPlan;\n readonly state: NativeRawTaskState;\n readonly completedTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n takeOutput(): NativeRawOutput;\n}\nfunction windows(exposure: NativeRawExposure, schedule: SensorRawProducerExposureWindowInput,\n points: readonly {x:number;y:number}[]): ReturnType<typeof calculateCaptureExposureWindows>[\"value\"] {\n const r=requireAllowlistedRecord(schedule,[\"shutterMechanism\",\"nominalExposureDurationSeconds\",\"opening\",\"closing\"],\"Invalid RAW exposure schedule.\");\n requireAllowlistedRecord(r.nominalExposureDurationSeconds,[\"value\",\"unit\",\"evidence\"],\"Invalid RAW nominal exposure.\");\n for(const boundary of [r.opening,r.closing]){\n const b=requireAllowlistedRecord(boundary,[\"kind\",\"directionNative\",\"traversalDurationSeconds\"],\"Invalid RAW exposure boundary.\");\n if(b.directionNative!==undefined)requireAllowlistedRecord(b.directionNative,[\"value\",\"evidence\"],\"Invalid RAW scan direction.\");\n if(b.traversalDurationSeconds!==undefined)requireAllowlistedRecord(b.traversalDurationSeconds,[\"value\",\"unit\",\"evidence\"],\"Invalid RAW scan duration.\");\n }\n const result=calculateCaptureExposureWindows({...schedule,nativeRaster:exposure.geometry.nativeRaster,samplePointsNative:points});\n if(result.value.nominalExposureDurationSeconds.value!==exposure.exposure.shutterSeconds)throw new InvalidConfigurationError(\"RAW schedule differs from exposure duration.\");\n return result.value;\n}\n/** Plans the task and checks the image size, resources and profiles before any callback or output allocation. No placeholder plane is made. */\nexport function calculateNativeRawPlan(input: NativeRawInput): NativeRawPlan {\n const r=requireAllowlistedRecord(input,[\"exposure\",\"frameId\",\"modeId\",\"captureModeProfile\",\"colorSamplingProfile\",\"bindingProfile\",\"exposureWindow\",\"maximumOutputBytes\",\"tileWidth\",\"maximumPixels\"],\"Invalid native RAW input.\");\n if(r.tileWidth!==undefined&&(typeof r.tileWidth!==\"number\"||!Number.isSafeInteger(r.tileWidth)||r.tileWidth<1||r.tileWidth>NATIVE_RAW_LIMITS.tileWidth))\n throw new InvalidConfigurationError(\"Native RAW tile width must be an integer from 1 to 256.\");\n const tileWidth=(r.tileWidth as number|undefined)??NATIVE_RAW_LIMITS.tileWidth;\n const maximumPixels=resolveRaisedLimit(r.maximumPixels,NATIVE_RAW_LIMITS.maximumPixels,NATIVE_RAW_LIMITS.ceilingPixels,\n \"Native RAW maximumPixels must be an integer from 1 to \"+NATIVE_RAW_LIMITS.ceilingPixels+\".\");\n const exposure=normalizeCaptureExposureMetadata(r.exposure,ENGINE_API_VERSION,true),native=exposure.geometry.nativeRaster;\n const pixelCount=native.pixelWidth*native.pixelHeight,outputBytes=pixelCount*NATIVE_RAW_LIMITS.outputBytesPerPixel;\n if(pixelCount>maximumPixels||native.pixelWidth>NATIVE_RAW_LIMITS.maximumDimension||native.pixelHeight>NATIVE_RAW_LIMITS.maximumDimension||\n !Number.isSafeInteger(r.maximumOutputBytes)||typeof r.maximumOutputBytes!==\"number\"||r.maximumOutputBytes<outputBytes)throw new InvalidConfigurationError(\"Native RAW raster exceeds output admission budget.\");\n const frame={frameId:requirePublicOpaqueId(r.frameId,\"Invalid RAW frame ID.\"),capture:exposure,\n modeId:requirePublicOpaqueId(r.modeId,\"Invalid RAW mode ID.\"),containerBitDepth:16 as const,\n captureModeProfile:parseCaptureModeProfile(r.captureModeProfile),colorSamplingProfile:parseSensorColorSamplingProfile(r.colorSamplingProfile),\n bindingProfile:parseNativeEffectiveRasterColorSamplingBindingProfile(r.bindingProfile)};\n const mode=frame.captureModeProfile.modes.find(m=>m.modeId===frame.modeId);\n if(exposure.noise.model.id!==SENSOR_RAW_PRODUCER_NOISE_MODEL.id||exposure.noise.model.version!==SENSOR_RAW_PRODUCER_NOISE_MODEL.version||\n frame.colorSamplingProfile.layout.kind!==\"periodic-mosaic\"||mode?.acquisition.kind!==\"single-frame\"||mode.perFrameSampling.kind!==\"native-effective-raster\"||(mode.reconstructionStages?.length??0)!==0)\n throw new InvalidConfigurationError(\"Native RAW requires exact noise identity and single-frame native periodic CFA.\");\n // The binding is one affine mapping for the whole frame, so checking both corners covers it. Do this before any provider work.\n for(const p of [{x:0,y:0},{x:native.pixelWidth-1,y:native.pixelHeight-1}]){\n const c=resolveCaptureModeColorSamplingContributors({nativeRaster:native,captureModeProfile:frame.captureModeProfile,modeId:frame.modeId,colorSamplingProfile:frame.colorSamplingProfile,bindingProfile:frame.bindingProfile,modeSampleIndexFullFrame:p});\n if(c.totalContributorSites!==1||c.channelComposition.kind!==\"single-channel\")throw new InvalidConfigurationError(\"Native RAW must preserve one native CFA site per sample.\");\n }\n const schedule=r.exposureWindow===undefined?undefined:structuredClone(r.exposureWindow) as SensorRawProducerExposureWindowInput;\n // For the supported linear scans, the extreme values occur at the image corners. Check them before capture.\n if(schedule)windows(exposure,schedule,[{x:.5,y:.5},{x:native.pixelWidth-.5,y:.5},{x:.5,y:native.pixelHeight-.5},{x:native.pixelWidth-.5,y:native.pixelHeight-.5}]);\n return freezeOwnedData({schemaVersion:NATIVE_RAW_SCHEMA_VERSION,exposure,frame,pixelCount,outputBytes,\n tileCount:Math.ceil(native.pixelWidth/tileWidth)*native.pixelHeight,\n ...(r.tileWidth===undefined?{}:{tileWidth}),\n ...(r.maximumPixels===undefined?{}:{maximumPixels}),\n ...(schedule?{exposureWindow:schedule}:{}),upstreamRadiometryVerified:false as const,\n seedSchedule:\"murmur3-capture-seed-native-index-stream-v2\" as const});\n}\n/**\n * Internal: the largest whole-event radiance query budget a native environment task admits for this plan:\n * 2 000 000 000, scaled in proportion when the plan raised its pixel limit above 24 000 000. Not exported from the package.\n */\nexport function nativeRawMaximumProviderEvaluations(plan: Pick<NativeRawPlan,\"maximumPixels\">): number {\n return plan.maximumPixels===undefined?DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS:scaleBudgetCeiling(DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS,plan.maximumPixels);\n}\n/**\n * Runs validated per-site events (EQE photo signal, dark signal, charge completeness) through the shared\n * reference per-site physics.\n *\n * Tiles are read and committed one at a time. The task yields to the host at tile boundaries once about\n * 8 ms of work has passed since the last yield, and after the final tile. It checks for cancellation\n * before every tile, after every read and after every yield.\n */\nexport function createNativeRawTask(input: NativeRawInput,provider: NativeRawProvider): NativeRawTask {\n return createNativeRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes tiles, seeds or output. Not exported from the package. */\nexport function createNativeRawTaskWithCadence(input: NativeRawInput,provider: NativeRawProvider,cadence: HostYieldCadence,\n /** Internal: a yield timer shared with a provider that also yields inside readTile, so both use one time budget. */\n sharedGate?: HostYieldGate,\n /** Internal: faster (\"lean\") per-site sensor execution for engine-built tiles. It never changes output or errors. */\n leanSensor?: NativeRawLeanSensorHook,\n /**\n * Internal: run only native rows [y, y + height) (a partition). The output arrays then hold just those rows, and\n * effectiveSaturationCodes holds 0 for CFA phases the rows do not contain; the merge step completes them.\n * Seeds, tiles and per-site values are those of the whole-frame task.\n */\n rows?: { readonly y: number; readonly height: number; readonly firstSite?: (site: SensorRawProducerSiteInput) => void;\n /** Internal (2.3 region rendering): also restrict to native columns [x, x + width). The output arrays are then that rectangle, row-major. */\n readonly x?: number; readonly width?: number }): NativeRawTask {\n const plan=calculateNativeRawPlan(input);\n if(!provider||typeof provider.readTile!==\"function\"||typeof provider.yieldControl!==\"function\")throw new InvalidConfigurationError(\"Native RAW requires reader and host event-loop yield.\");\n const read=provider.readTile.bind(provider),yieldControl=provider.yieldControl.bind(provider),abort=new AbortController();\n const native=plan.exposure.geometry.nativeRaster,tileWidth=plan.tileWidth??NATIVE_RAW_LIMITS.tileWidth;\n const rowStart=rows?.y??0,rowEnd=rowStart+(rows?.height??native.pixelHeight),colStart=rows?.x??0,colEnd=colStart+(rows?.width??native.pixelWidth);\n if(colStart<0||colEnd>native.pixelWidth||colEnd<=colStart)throw new InvalidConfigurationError(\"Native RAW column band must lie inside the native raster.\");\n const bandWidth=colEnd-colStart,length=(rowEnd-rowStart)*bandWidth;\n let state:NativeRawTaskState=\"ready\",count=0,output:NativeRawOutput|null=null,first:SensorRawProducerSiteInput|undefined;\n function release(): void {if(output){output.codes.fill(0);output.blackLevels.fill(0);output.digitalSaturationCodes.fill(0);output.saturationFlags.fill(0);output.effectiveSaturationCodes.fill(0);}output=null;first=undefined;}\n function active(): void {if(abort.signal.aborted)throw new InvalidConfigurationError(\"Native RAW execution aborted.\");}\n return {plan,get state(): NativeRawTaskState {return state;},get completedTileCount(): number {return count;},\n async run(): Promise<void> {\n if(state!==\"ready\")throw new InvalidConfigurationError(\"Native RAW task is single-use.\");state=\"running\";\n try{\n const gate=sharedGate??createHostYieldGate(cadence);sharedGate?.restart();\n const layout=plan.frame.colorSamplingProfile.layout;if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Native RAW requires periodic CFA.\");\n const white=createPhaseWhiteLevelAccumulator(native.pixelWidth,layout.repeatWidthSites,layout.repeatHeightSites);\n output={plan,codes:new Uint16Array(length),blackLevels:new Uint16Array(length),digitalSaturationCodes:new Uint16Array(length),saturationFlags:new Uint8Array(length),effectiveSaturationCodes:new Uint16Array(layout.repeatWidthSites*layout.repeatHeightSites)};\n for(let y=rowStart;y<rowEnd;y++)for(let x=colStart;x<colEnd;x+=tileWidth){\n active();const request=Object.freeze({captureId:plan.exposure.captureId,frameId:plan.frame.frameId,x,y,width:Math.min(tileWidth,colEnd-x),height:1});\n {\n const supplied=await read(request,abort.signal);active();\n const tile=requireAllowlistedRecord(supplied,[\"captureId\",\"frameId\",\"x\",\"y\",\"width\",\"height\",\"sites\"],\"Invalid native RAW tile.\");\n for(const key of Object.keys(request) as (keyof NativeRawTileRequest)[])if(tile[key]!==request[key])throw new InvalidConfigurationError(\"Native RAW tile identity mismatch.\");\n if(!Array.isArray(tile.sites)||tile.sites.length!==request.width||Array.from({length:request.width},(_,i)=>i in (tile.sites as unknown[])).includes(false))throw new InvalidConfigurationError(\"Native RAW tile needs exact dense coverage.\");\n const timing=plan.exposureWindow?windows(plan.exposure,plan.exposureWindow,Array.from({length:request.width},(_,i)=>({x:x+i+.5,y:y+.5}))):undefined;\n // Lean entries (built by the engine, provably valid against an earlier verified template) skip parsing and\n // identity checks. They are only claimed once the frame's first site is fixed.\n const lean=leanSensor&&first!==undefined?(tile.sites as unknown[]).map(site=>leanSensor.claim(site)):undefined;\n const sites=tile.sites.map((site,j)=>lean?.[j]?undefined:parseNativeRawProducerSite(site,y*native.pixelWidth+x+j,plan.frame,timing?.samples[j]));\n if(first===undefined){first=sites[0];if(first)rows?.firstSite?.(first);}for(const s of sites)if(s)validateNativeRawReadoutIdentity(s,first!);\n // Every site in this tile is validated before any output is written. A failure never returns partial output.\n const seed=plan.exposure.noise.seedUint32;\n for(let j=0;j<sites.length;j++){\n // index: absolute native index (seeds, CFA phase); at: position in this task's output arrays.\n const index=y*native.pixelWidth+x+j,at=(y-rowStart)*bandWidth+x+j-colStart,handle=lean?.[j];\n if(handle){\n const o=leanSensor!.compute(handle,index,seed,timing?.samples[j]);\n output.codes[at]=o.rawCode;output.blackLevels[at]=o.blackLevelCode;output.digitalSaturationCodes[at]=o.digitalSaturationCode;\n output.saturationFlags[at]=o.flags;white.record(index,o.whiteCode);continue;\n }\n const result=calculateNativeRawSite(sites[j]!,seed,index),r=result.readout.value;\n output.codes[at]=r.rawCode;output.blackLevels[at]=r.blackLevelCode;output.digitalSaturationCodes[at]=r.digitalSaturationCode;\n output.saturationFlags[at]=Number(r.physicalScalarSaturationApplied)|Number(r.preAdcSaturationApplied)<<1|Number(r.digitalSaturationApplied)<<2;\n const whiteCode=calculateSiteEffectiveSaturationCode(r,sites[j]!.readoutProfile,sites[j]!.regimeId);\n white.record(index,whiteCode);\n leanSensor?.observe(index,sites[j]!,result,whiteCode,seed);\n }\n count++;\n }\n // Yield when the time budget is spent, and always after the final tile. Yield timing never changes output.\n if(gate.due()||(y===rowEnd-1&&x+tileWidth>=colEnd)){await yieldControl(abort.signal);active();gate.restart();}\n }\n output.effectiveSaturationCodes.set(rows?white.partial():white.finish());first=undefined;state=\"completed\";\n }catch(error){release();if(!abort.signal.aborted){state=\"failed\";abort.abort();}throw error;}\n },\n cancel(): void {if(state===\"ready\"||state===\"running\"||state===\"completed\"){state=\"cancelled\";abort.abort();release();}},\n dispose(): void {if(state!==\"transferred\"){state=\"disposed\";abort.abort();release();}},\n takeOutput(): NativeRawOutput {if(state!==\"completed\"||!output)throw new InvalidConfigurationError(\"Native RAW output unavailable.\");const result=output;output=null;first=undefined;state=\"transferred\";return result;}\n };\n}\n"]}
1
+ {"version":3,"file":"native-raw.js","sourceRoot":"","sources":["../../src/capture/native-raw.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;GAGG;AACH,OAAO,EAAE,wBAAwB,EAA6B,MAAM,8BAA8B,CAAC;AACnG,OAAO,EAAE,gCAAgC,EAAiF,MAAM,wBAAwB,CAAC;AACzJ,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AACjH,OAAO,EAAE,oCAAoC,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAC9G,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAA6C,MAAM,yBAAyB,CAAC;AACrI,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAC9E,OAAO,EAAE,qDAAqD,EAAE,2CAA2C,EAAE,MAAM,6CAA6C,CAAC;AACjK,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAC/E,OAAO,EAAE,+BAA+B,EAAE,sBAAsB,EAAE,0BAA0B,EAC1F,gCAAgC,EACW,MAAM,0BAA0B,CAAC;AAE9E,MAAM,CAAC,MAAM,yBAAyB,GAAG,OAAgB,CAAC;AAC1D,8HAA8H;AAC9H,MAAM,CAAC,MAAM,iBAAiB,GAAG,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,aAAa,EAAE,UAAU,EAAE,aAAa,EA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,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC;QACtF,UAAU,KAAqB,IAAG,KAAK,KAAG,WAAW,IAAE,CAAC,MAAM;YAAC,MAAM,IAAI,yBAAyB,CAAC,gCAAgC,CAAC,CAAC,CAAA,MAAM,MAAM,GAAC,MAAM,CAAC,CAAA,MAAM,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,SAAS,CAAC,CAAA,KAAK,GAAC,aAAa,CAAC,CAAA,OAAO,MAAM,CAAC,CAAA,CAAC;KACzN,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW capture with the existing per-site (scalar) RAW model: an up-front plan and limit check from\n * metadata only, then bounded tile-by-tile execution.\n */\nimport { EXPOSURE_BUILD_UP_STAGES, type ExposureBuildUpStage } from \"./exposure-build-up-stage.js\";\nimport { normalizeCaptureExposureMetadata, type SimulatedCaptureInput, type SimulatedCapture, type CaptureExposureSource } from \"./simulated-capture.js\";\nimport { ENGINE_API_VERSION } from \"../core/version.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord, requirePublicOpaqueId } from \"../core/record-validation.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit, scaleBudgetCeiling } from \"../core/pixel-limits.js\";\nimport { calculateSiteEffectiveSaturationCode, createPhaseWhiteLevelAccumulator } from \"./raw-white-level.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence, type HostYieldGate } from \"./host-yield-cadence.js\";\nimport { parseCaptureModeProfile } from \"../sensor/capture-mode.js\";\nimport { parseSensorColorSamplingProfile } from \"../sensor/color-sampling.js\";\nimport { parseNativeEffectiveRasterColorSamplingBindingProfile, resolveCaptureModeColorSamplingContributors } from \"../sensor/capture-color-sampling-binding.js\";\nimport { calculateCaptureExposureWindows } from \"../sensor/exposure-window.js\";\nimport { SENSOR_RAW_PRODUCER_NOISE_MODEL, calculateNativeRawSite, parseNativeRawProducerSite,\n validateNativeRawReadoutIdentity, type NativeRawProducerFrameContext, type SensorRawProducerSiteInput,\n type SensorRawProducerExposureWindowInput } from \"./sensor-raw-producer.js\";\n\nexport const NATIVE_RAW_SCHEMA_VERSION = \"0.1.0\" as const;\n/** `maximumPixels` is the default pixel limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */\nexport const NATIVE_RAW_LIMITS = /* @__PURE__ */ Object.freeze({ maximumPixels: 24_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS, maximumDimension: 16_384,\n tileWidth: 256, tileHeight: 1, outputBytesPerPixel: 7 });\n/** Default whole-event radiance query budget ceiling of the native environment tasks; it scales with a raised `maximumPixels`. */\nconst DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS = 2_000_000_000;\n/** A shooting event and where its source came from. Not a finished float master or committed RAW frame. */\nexport type NativeRawExposureInput = Omit<SimulatedCaptureInput, \"planes\" | \"source\"> & {source:CaptureExposureSource};\nexport type NativeRawExposure = Omit<SimulatedCapture, \"schemaVersion\" | \"planes\" | \"source\"> & {source:CaptureExposureSource};\nexport interface NativeRawInput {\n exposure: NativeRawExposureInput;\n frameId: string;\n modeId: string;\n captureModeProfile: NativeRawProducerFrameContext[\"captureModeProfile\"];\n colorSamplingProfile: NativeRawProducerFrameContext[\"colorSamplingProfile\"];\n bindingProfile: NativeRawProducerFrameContext[\"bindingProfile\"];\n exposureWindow?: SensorRawProducerExposureWindowInput;\n maximumOutputBytes: number;\n /** Optional tile width for execution, in native sites, 1–256. Default 256. It does not affect sampling. */\n tileWidth?: number;\n /**\n * Optional opt-in pixel limit for large sensors: an integer from 1 to `NATIVE_RAW_LIMITS.ceilingPixels`.\n * Default `NATIVE_RAW_LIMITS.maximumPixels` (24 000 000). `maximumOutputBytes` still applies. A raised limit\n * also raises the native environment tasks' whole-event query budget ceiling in proportion\n * (2 000 000 000 per 24 000 000 pixels). It does not affect sampling.\n */\n maximumPixels?: number;\n}\nexport interface NativeRawPlan {\n schemaVersion: typeof NATIVE_RAW_SCHEMA_VERSION;\n exposure: NativeRawExposure;\n frame: NativeRawProducerFrameContext;\n exposureWindow?: SensorRawProducerExposureWindowInput;\n pixelCount: number;\n outputBytes: number;\n tileCount: number;\n /** Present only when an execution tile width was given. Otherwise the plan keeps its earlier shape. */\n tileWidth?: number;\n /** Present only when a pixel limit was given. Otherwise the plan keeps its earlier shape. */\n maximumPixels?: number;\n upstreamRadiometryVerified: false;\n seedSchedule: \"murmur3-capture-seed-native-index-stream-v2\";\n}\n/** Tile rectangle, in absolute full-sensor CFA coordinates, before orientation, active-area crop or output scaling. */\nexport interface NativeRawTileRequest { captureId: string; frameId: string; x: number; y: number; width: number; height: number }\nexport interface NativeRawTile extends NativeRawTileRequest { sites: readonly SensorRawProducerSiteInput[] }\nexport interface NativeRawProvider {\n readTile(request: Readonly<NativeRawTileRequest>, signal: AbortSignal): Promise<NativeRawTile>;\n yieldControl(signal: AbortSignal): Promise<void>;\n}\n/** Row-major arrays owned only by the output. They cannot be attached to the bounded SensorRawFrame type. */\nexport interface NativeRawOutput {\n plan: NativeRawPlan;\n codes: Uint16Array;\n blackLevels: Uint16Array;\n digitalSaturationCodes: Uint16Array;\n /** Saturation flags. Bit 0: physical charge clamp; bit 1: pre-ADC clamp; bit 2: digital saturation. */\n saturationFlags: Uint8Array;\n /**\n * Effective white (full-saturation) code for each absolute CFA repeat phase, indexed\n * `phaseY*repeatWidthSites+phaseX`: min(digital saturation, round(black + min(capacity, pre-ADC\n * saturation)/gain)). See `calculateEffectiveSaturationCode`. A few bytes, not one value per pixel.\n */\n effectiveSaturationCodes: Uint16Array;\n}\n/** Internal: lean per-site outputs of an engine-built site (see native-environment-lean.ts). */\nexport interface NativeRawLeanOutput { rawCode: number; blackLevelCode: number; digitalSaturationCode: number; flags: number; whiteCode: number }\n/**\n * Internal hook for tiles the engine builds itself (native environment RAW).\n *\n * claim() recognizes only entries the hook itself created, for sites whose parsing and identity checks are\n * provably redundant. compute() returns the outputs calculateNativeRawSite would produce, falling back to it\n * internally. observe() sees every fully computed site.\n */\nexport interface NativeRawLeanSensorHook {\n claim(site: unknown): object | undefined;\n compute(handle: object, index: number, seed: number, timing: ReturnType<typeof calculateCaptureExposureWindows>[\"value\"][\"samples\"][number] | undefined, b?: ExposureBuildUpStage): NativeRawLeanOutput;\n observe(index: number, parsed: SensorRawProducerSiteInput, result: ReturnType<typeof calculateNativeRawSite>, whiteCode: number, seed: number, b?: ExposureBuildUpStage): void;\n}\nexport type NativeRawTaskState = \"ready\" | \"running\" | \"completed\" | \"cancelled\" | \"failed\" | \"disposed\" | \"transferred\";\nexport interface NativeRawTask {\n readonly plan: NativeRawPlan;\n readonly state: NativeRawTaskState;\n readonly completedTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n takeOutput(): NativeRawOutput;\n}\nfunction windows(exposure: NativeRawExposure, schedule: SensorRawProducerExposureWindowInput,\n points: readonly {x:number;y:number}[]): ReturnType<typeof calculateCaptureExposureWindows>[\"value\"] {\n const r=requireAllowlistedRecord(schedule,[\"shutterMechanism\",\"nominalExposureDurationSeconds\",\"opening\",\"closing\"],\"Invalid RAW exposure schedule.\");\n requireAllowlistedRecord(r.nominalExposureDurationSeconds,[\"value\",\"unit\",\"evidence\"],\"Invalid RAW nominal exposure.\");\n for(const boundary of [r.opening,r.closing]){\n const b=requireAllowlistedRecord(boundary,[\"kind\",\"directionNative\",\"traversalDurationSeconds\"],\"Invalid RAW exposure boundary.\");\n if(b.directionNative!==undefined)requireAllowlistedRecord(b.directionNative,[\"value\",\"evidence\"],\"Invalid RAW scan direction.\");\n if(b.traversalDurationSeconds!==undefined)requireAllowlistedRecord(b.traversalDurationSeconds,[\"value\",\"unit\",\"evidence\"],\"Invalid RAW scan duration.\");\n }\n const result=calculateCaptureExposureWindows({...schedule,nativeRaster:exposure.geometry.nativeRaster,samplePointsNative:points});\n if(result.value.nominalExposureDurationSeconds.value!==exposure.exposure.shutterSeconds)throw new InvalidConfigurationError(\"RAW schedule differs from exposure duration.\");\n return result.value;\n}\n/** Plans the task and checks the image size, resources and profiles before any callback or output allocation. No placeholder plane is made. */\nexport function calculateNativeRawPlan(input: NativeRawInput): NativeRawPlan {\n const r=requireAllowlistedRecord(input,[\"exposure\",\"frameId\",\"modeId\",\"captureModeProfile\",\"colorSamplingProfile\",\"bindingProfile\",\"exposureWindow\",\"maximumOutputBytes\",\"tileWidth\",\"maximumPixels\"],\"Invalid native RAW input.\");\n if(r.tileWidth!==undefined&&(typeof r.tileWidth!==\"number\"||!Number.isSafeInteger(r.tileWidth)||r.tileWidth<1||r.tileWidth>NATIVE_RAW_LIMITS.tileWidth))\n throw new InvalidConfigurationError(\"Native RAW tile width must be an integer from 1 to 256.\");\n const tileWidth=(r.tileWidth as number|undefined)??NATIVE_RAW_LIMITS.tileWidth;\n const maximumPixels=resolveRaisedLimit(r.maximumPixels,NATIVE_RAW_LIMITS.maximumPixels,NATIVE_RAW_LIMITS.ceilingPixels,\n \"Native RAW maximumPixels must be an integer from 1 to \"+NATIVE_RAW_LIMITS.ceilingPixels+\".\");\n const exposure=normalizeCaptureExposureMetadata(r.exposure,ENGINE_API_VERSION,true),native=exposure.geometry.nativeRaster;\n const pixelCount=native.pixelWidth*native.pixelHeight,outputBytes=pixelCount*NATIVE_RAW_LIMITS.outputBytesPerPixel;\n if(pixelCount>maximumPixels||native.pixelWidth>NATIVE_RAW_LIMITS.maximumDimension||native.pixelHeight>NATIVE_RAW_LIMITS.maximumDimension||\n !Number.isSafeInteger(r.maximumOutputBytes)||typeof r.maximumOutputBytes!==\"number\"||r.maximumOutputBytes<outputBytes)throw new InvalidConfigurationError(\"Native RAW raster exceeds output admission budget.\");\n const frame={frameId:requirePublicOpaqueId(r.frameId,\"Invalid RAW frame ID.\"),capture:exposure,\n modeId:requirePublicOpaqueId(r.modeId,\"Invalid RAW mode ID.\"),containerBitDepth:16 as const,\n captureModeProfile:parseCaptureModeProfile(r.captureModeProfile),colorSamplingProfile:parseSensorColorSamplingProfile(r.colorSamplingProfile),\n bindingProfile:parseNativeEffectiveRasterColorSamplingBindingProfile(r.bindingProfile)};\n const mode=frame.captureModeProfile.modes.find(m=>m.modeId===frame.modeId);\n if(exposure.noise.model.id!==SENSOR_RAW_PRODUCER_NOISE_MODEL.id||exposure.noise.model.version!==SENSOR_RAW_PRODUCER_NOISE_MODEL.version||\n frame.colorSamplingProfile.layout.kind!==\"periodic-mosaic\"||mode?.acquisition.kind!==\"single-frame\"||mode.perFrameSampling.kind!==\"native-effective-raster\"||(mode.reconstructionStages?.length??0)!==0)\n throw new InvalidConfigurationError(\"Native RAW requires exact noise identity and single-frame native periodic CFA.\");\n // The binding is one affine mapping for the whole frame, so checking both corners covers it. Do this before any provider work.\n for(const p of [{x:0,y:0},{x:native.pixelWidth-1,y:native.pixelHeight-1}]){\n const c=resolveCaptureModeColorSamplingContributors({nativeRaster:native,captureModeProfile:frame.captureModeProfile,modeId:frame.modeId,colorSamplingProfile:frame.colorSamplingProfile,bindingProfile:frame.bindingProfile,modeSampleIndexFullFrame:p});\n if(c.totalContributorSites!==1||c.channelComposition.kind!==\"single-channel\")throw new InvalidConfigurationError(\"Native RAW must preserve one native CFA site per sample.\");\n }\n const schedule=r.exposureWindow===undefined?undefined:structuredClone(r.exposureWindow) as SensorRawProducerExposureWindowInput;\n // For the supported linear scans, the extreme values occur at the image corners. Check them before capture.\n if(schedule)windows(exposure,schedule,[{x:.5,y:.5},{x:native.pixelWidth-.5,y:.5},{x:.5,y:native.pixelHeight-.5},{x:native.pixelWidth-.5,y:native.pixelHeight-.5}]);\n return freezeOwnedData({schemaVersion:NATIVE_RAW_SCHEMA_VERSION,exposure,frame,pixelCount,outputBytes,\n tileCount:Math.ceil(native.pixelWidth/tileWidth)*native.pixelHeight,\n ...(r.tileWidth===undefined?{}:{tileWidth}),\n ...(r.maximumPixels===undefined?{}:{maximumPixels}),\n ...(schedule?{exposureWindow:schedule}:{}),upstreamRadiometryVerified:false as const,\n seedSchedule:\"murmur3-capture-seed-native-index-stream-v2\" as const});\n}\n/**\n * Internal: the largest whole-event radiance query budget a native environment task admits for this plan:\n * 2 000 000 000, scaled in proportion when the plan raised its pixel limit above 24 000 000. Not exported from the package.\n */\nexport function nativeRawMaximumProviderEvaluations(plan: Pick<NativeRawPlan,\"maximumPixels\">): number {\n return plan.maximumPixels===undefined?DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS:scaleBudgetCeiling(DEFAULT_MAXIMUM_PROVIDER_EVALUATIONS,plan.maximumPixels);\n}\n/**\n * Runs validated per-site events (EQE photo signal, dark signal, charge completeness) through the shared\n * reference per-site physics.\n *\n * Tiles are read and committed one at a time. The task yields to the host at tile boundaries once about\n * 8 ms of work has passed since the last yield, and after the final tile. It checks for cancellation\n * before every tile, after every read and after every yield.\n */\nexport function createNativeRawTask(input: NativeRawInput,provider: NativeRawProvider): NativeRawTask {\n return createNativeRawTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes tiles, seeds or output. Not exported from the package. */\nexport function createNativeRawTaskWithCadence(input: NativeRawInput,provider: NativeRawProvider,cadence: HostYieldCadence,\n /** Internal: a yield timer shared with a provider that also yields inside readTile, so both use one time budget. */\n sharedGate?: HostYieldGate,\n /** Internal: faster (\"lean\") per-site sensor execution for engine-built tiles. It never changes output or errors. */\n leanSensor?: NativeRawLeanSensorHook,\n /**\n * Internal: run only native rows [y, y + height) (a partition). The output arrays then hold just those rows, and\n * effectiveSaturationCodes holds 0 for CFA phases the rows do not contain; the merge step completes them.\n * Seeds, tiles and per-site values are those of the whole-frame task.\n */\n rows?: { readonly y: number; readonly height: number; readonly firstSite?: (site: SensorRawProducerSiteInput) => void;\n /** Internal (2.3 region rendering): also restrict to native columns [x, x + width). The output arrays are then that rectangle, row-major. */\n readonly x?: number; readonly width?: number }): NativeRawTask {\n const plan=calculateNativeRawPlan(input);\n if(!provider||typeof provider.readTile!==\"function\"||typeof provider.yieldControl!==\"function\")throw new InvalidConfigurationError(\"Native RAW requires reader and host event-loop yield.\");\n const read=provider.readTile.bind(provider),yieldControl=provider.yieldControl.bind(provider),abort=new AbortController();\n const native=plan.exposure.geometry.nativeRaster,tileWidth=plan.tileWidth??NATIVE_RAW_LIMITS.tileWidth;\n const rowStart=rows?.y??0,rowEnd=rowStart+(rows?.height??native.pixelHeight),colStart=rows?.x??0,colEnd=colStart+(rows?.width??native.pixelWidth);\n if(colStart<0||colEnd>native.pixelWidth||colEnd<=colStart)throw new InvalidConfigurationError(\"Native RAW column band must lie inside the native raster.\");\n const bandWidth=colEnd-colStart,length=(rowEnd-rowStart)*bandWidth;\n let state:NativeRawTaskState=\"ready\",count=0,output:NativeRawOutput|null=null,first:SensorRawProducerSiteInput|undefined;\n function release(): void {if(output){output.codes.fill(0);output.blackLevels.fill(0);output.digitalSaturationCodes.fill(0);output.saturationFlags.fill(0);output.effectiveSaturationCodes.fill(0);}output=null;first=undefined;}\n function active(): void {if(abort.signal.aborted)throw new InvalidConfigurationError(\"Native RAW execution aborted.\");}\n return {plan,get state(): NativeRawTaskState {return state;},get completedTileCount(): number {return count;},\n async run(): Promise<void> {\n if(state!==\"ready\")throw new InvalidConfigurationError(\"Native RAW task is single-use.\");state=\"running\";\n try{\n const gate=sharedGate??createHostYieldGate(cadence);sharedGate?.restart();\n const layout=plan.frame.colorSamplingProfile.layout;if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Native RAW requires periodic CFA.\");\n const white=createPhaseWhiteLevelAccumulator(native.pixelWidth,layout.repeatWidthSites,layout.repeatHeightSites);\n output={plan,codes:new Uint16Array(length),blackLevels:new Uint16Array(length),digitalSaturationCodes:new Uint16Array(length),saturationFlags:new Uint8Array(length),effectiveSaturationCodes:new Uint16Array(layout.repeatWidthSites*layout.repeatHeightSites)};\n for(let y=rowStart;y<rowEnd;y++)for(let x=colStart;x<colEnd;x+=tileWidth){\n active();const request=Object.freeze({captureId:plan.exposure.captureId,frameId:plan.frame.frameId,x,y,width:Math.min(tileWidth,colEnd-x),height:1});\n {\n const supplied=await read(request,abort.signal);active();\n const tile=requireAllowlistedRecord(supplied,[\"captureId\",\"frameId\",\"x\",\"y\",\"width\",\"height\",\"sites\"],\"Invalid native RAW tile.\");\n for(const key of Object.keys(request) as (keyof NativeRawTileRequest)[])if(tile[key]!==request[key])throw new InvalidConfigurationError(\"Native RAW tile identity mismatch.\");\n if(!Array.isArray(tile.sites)||tile.sites.length!==request.width||Array.from({length:request.width},(_,i)=>i in (tile.sites as unknown[])).includes(false))throw new InvalidConfigurationError(\"Native RAW tile needs exact dense coverage.\");\n const timing=plan.exposureWindow?windows(plan.exposure,plan.exposureWindow,Array.from({length:request.width},(_,i)=>({x:x+i+.5,y:y+.5}))):undefined;\n // Lean entries (built by the engine, provably valid against an earlier verified template) skip parsing and\n // identity checks. They are only claimed once the frame's first site is fixed.\n const lean=leanSensor&&first!==undefined?(tile.sites as unknown[]).map(site=>leanSensor.claim(site)):undefined;\n const sites=tile.sites.map((site,j)=>lean?.[j]?undefined:parseNativeRawProducerSite(site,y*native.pixelWidth+x+j,plan.frame,timing?.samples[j]));\n if(first===undefined){first=sites[0];if(first)rows?.firstSite?.(first);}for(const s of sites)if(s)validateNativeRawReadoutIdentity(s,first!);\n // Every site in this tile is validated before any output is written. A failure never returns partial output.\n const seed=plan.exposure.noise.seedUint32,b=EXPOSURE_BUILD_UP_STAGES.get(input);\n for(let j=0;j<sites.length;j++){\n // index: absolute native index (seeds, CFA phase); at: position in this task's output arrays.\n const index=y*native.pixelWidth+x+j,at=(y-rowStart)*bandWidth+x+j-colStart,handle=lean?.[j];\n if(handle){\n const o=leanSensor!.compute(handle,index,seed,timing?.samples[j],b);\n output.codes[at]=o.rawCode;output.blackLevels[at]=o.blackLevelCode;output.digitalSaturationCodes[at]=o.digitalSaturationCode;\n output.saturationFlags[at]=o.flags;white.record(index,o.whiteCode);continue;\n }\n const result=calculateNativeRawSite(sites[j]!,seed,index,b),r=result.readout.value;\n output.codes[at]=r.rawCode;output.blackLevels[at]=r.blackLevelCode;output.digitalSaturationCodes[at]=r.digitalSaturationCode;\n output.saturationFlags[at]=Number(r.physicalScalarSaturationApplied)|Number(r.preAdcSaturationApplied)<<1|Number(r.digitalSaturationApplied)<<2;\n const whiteCode=calculateSiteEffectiveSaturationCode(r,sites[j]!.readoutProfile,sites[j]!.regimeId);\n white.record(index,whiteCode);\n leanSensor?.observe(index,sites[j]!,result,whiteCode,seed,b);\n }\n count++;\n }\n // Yield when the time budget is spent, and always after the final tile. Yield timing never changes output.\n if(gate.due()||(y===rowEnd-1&&x+tileWidth>=colEnd)){await yieldControl(abort.signal);active();gate.restart();}\n }\n output.effectiveSaturationCodes.set(rows?white.partial():white.finish());first=undefined;state=\"completed\";\n }catch(error){release();if(!abort.signal.aborted){state=\"failed\";abort.abort();}throw error;}\n },\n cancel(): void {if(state===\"ready\"||state===\"running\"||state===\"completed\"){state=\"cancelled\";abort.abort();release();}},\n dispose(): void {if(state!==\"transferred\"){state=\"disposed\";abort.abort();release();}},\n takeOutput(): NativeRawOutput {if(state!==\"completed\"||!output)throw new InvalidConfigurationError(\"Native RAW output unavailable.\");const result=output;output=null;first=undefined;state=\"transferred\";return result;}\n };\n}\n"]}