@photivra/engine 2.20.0 → 2.22.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 (275) hide show
  1. package/CHANGELOG.md +295 -1
  2. package/CITATION.cff +1 -1
  3. package/README.md +7 -6
  4. package/SECURITY.md +1 -1
  5. package/THIRD_PARTY.md +18 -0
  6. package/dist/capture/c2pa-embed.d.ts +116 -0
  7. package/dist/capture/c2pa-embed.js +493 -0
  8. package/dist/capture/c2pa-embed.js.map +1 -0
  9. package/dist/capture/dng-import.d.ts +73 -8
  10. package/dist/capture/dng-import.js +315 -80
  11. package/dist/capture/dng-import.js.map +1 -1
  12. package/dist/capture/dng-lens-correction-opcodes.d.ts +2 -2
  13. package/dist/capture/dng-lens-correction-opcodes.js +2 -2
  14. package/dist/capture/dng-lens-correction-opcodes.js.map +1 -1
  15. package/dist/capture/dng-opcodes.d.ts +96 -0
  16. package/dist/capture/dng-opcodes.js +391 -0
  17. package/dist/capture/dng-opcodes.js.map +1 -0
  18. package/dist/capture/dng-profile-maps.d.ts +99 -0
  19. package/dist/capture/dng-profile-maps.js +381 -0
  20. package/dist/capture/dng-profile-maps.js.map +1 -0
  21. package/dist/capture/dng-stage-image.d.ts +23 -0
  22. package/dist/capture/dng-stage-image.js +65 -0
  23. package/dist/capture/dng-stage-image.js.map +1 -0
  24. package/dist/capture/exposure-build-up-stage.d.ts +16 -0
  25. package/dist/capture/exposure-build-up-stage.js +4 -0
  26. package/dist/capture/exposure-build-up-stage.js.map +1 -0
  27. package/dist/capture/jpeg-xl-tiles.d.ts +22 -0
  28. package/dist/capture/jpeg-xl-tiles.js +151 -0
  29. package/dist/capture/jpeg-xl-tiles.js.map +1 -0
  30. package/dist/capture/lossy-jpeg.d.ts +17 -0
  31. package/dist/capture/lossy-jpeg.js +369 -0
  32. package/dist/capture/lossy-jpeg.js.map +1 -0
  33. package/dist/capture/native-environment-lean.d.ts +2 -1
  34. package/dist/capture/native-environment-lean.js +41 -73
  35. package/dist/capture/native-environment-lean.js.map +1 -1
  36. package/dist/capture/native-environment-tabulated.js +4 -3
  37. package/dist/capture/native-environment-tabulated.js.map +1 -1
  38. package/dist/capture/native-raw-development.d.ts +2 -1
  39. package/dist/capture/native-raw-development.js.map +1 -1
  40. package/dist/capture/native-raw.d.ts +3 -2
  41. package/dist/capture/native-raw.js +5 -4
  42. package/dist/capture/native-raw.js.map +1 -1
  43. package/dist/capture/sensor-raw-producer.d.ts +4 -1
  44. package/dist/capture/sensor-raw-producer.js +12 -3
  45. package/dist/capture/sensor-raw-producer.js.map +1 -1
  46. package/dist/color/neighbor-highlight-reconstruction.d.ts +66 -0
  47. package/dist/color/neighbor-highlight-reconstruction.js +234 -0
  48. package/dist/color/neighbor-highlight-reconstruction.js.map +1 -0
  49. package/dist/color/sensor-color-development.d.ts +5 -0
  50. package/dist/color/sensor-color-development.js +7 -1
  51. package/dist/color/sensor-color-development.js.map +1 -1
  52. package/dist/color/spectral-spikiness.d.ts +11 -0
  53. package/dist/color/spectral-spikiness.js +23 -0
  54. package/dist/color/spectral-spikiness.js.map +1 -0
  55. package/dist/core/execution-error.d.ts +21 -0
  56. package/dist/core/execution-error.js +12 -0
  57. package/dist/core/execution-error.js.map +1 -0
  58. package/dist/core/version.d.ts +1 -1
  59. package/dist/core/version.js +1 -1
  60. package/dist/core/version.js.map +1 -1
  61. package/dist/equipment/generic-lens-catalogue.d.ts +3 -2
  62. package/dist/equipment/generic-lens-catalogue.js +18 -5
  63. package/dist/equipment/generic-lens-catalogue.js.map +1 -1
  64. package/dist/equipment/generic-tier-assets.d.ts +32 -0
  65. package/dist/equipment/generic-tier-assets.js +16 -11
  66. package/dist/equipment/generic-tier-assets.js.map +1 -1
  67. package/dist/equipment/sensor-profile-body.d.ts +78 -0
  68. package/dist/equipment/sensor-profile-body.js +77 -0
  69. package/dist/equipment/sensor-profile-body.js.map +1 -0
  70. package/dist/equipment/sensor-profiles.d.ts +8 -0
  71. package/dist/equipment/sensor-profiles.js +82 -0
  72. package/dist/equipment/sensor-profiles.js.map +1 -0
  73. package/dist/facade/catalogue-lens-signal.d.ts +28 -3
  74. package/dist/facade/catalogue-lens-signal.js +83 -78
  75. package/dist/facade/catalogue-lens-signal.js.map +1 -1
  76. package/dist/facade/chart-radiance-batch.js +2 -1
  77. package/dist/facade/chart-radiance-batch.js.map +1 -1
  78. package/dist/facade/defocus-image-space-provider.d.ts +7 -0
  79. package/dist/facade/defocus-image-space-provider.js +64 -76
  80. package/dist/facade/defocus-image-space-provider.js.map +1 -1
  81. package/dist/facade/diffraction-provider.d.ts +1 -1
  82. package/dist/facade/diffraction-provider.js +4 -4
  83. package/dist/facade/diffraction-provider.js.map +1 -1
  84. package/dist/facade/display-view-gpu-session.js +39 -5
  85. package/dist/facade/display-view-gpu-session.js.map +1 -1
  86. package/dist/facade/display-view-gpu.d.ts +19 -6
  87. package/dist/facade/display-view-gpu.js.map +1 -1
  88. package/dist/facade/display-view-lens-signal.js +25 -23
  89. package/dist/facade/display-view-lens-signal.js.map +1 -1
  90. package/dist/facade/display-view-normal.d.ts +15 -0
  91. package/dist/facade/display-view-normal.js +44 -0
  92. package/dist/facade/display-view-normal.js.map +1 -0
  93. package/dist/facade/display-view-rendering.d.ts +97 -0
  94. package/dist/facade/display-view-rendering.js +598 -0
  95. package/dist/facade/display-view-rendering.js.map +1 -0
  96. package/dist/facade/display-view.d.ts +37 -65
  97. package/dist/facade/display-view.js +152 -499
  98. package/dist/facade/display-view.js.map +1 -1
  99. package/dist/facade/expected-signal-setup.d.ts +3 -1
  100. package/dist/facade/expected-signal-setup.js +3 -3
  101. package/dist/facade/expected-signal-setup.js.map +1 -1
  102. package/dist/facade/expected-signal.d.ts +47 -14
  103. package/dist/facade/expected-signal.js +117 -112
  104. package/dist/facade/expected-signal.js.map +1 -1
  105. package/dist/facade/exposure-build-up.d.ts +70 -0
  106. package/dist/facade/exposure-build-up.js +164 -0
  107. package/dist/facade/exposure-build-up.js.map +1 -0
  108. package/dist/facade/fast-methods.d.ts +1 -1
  109. package/dist/facade/fast-methods.js +46 -9
  110. package/dist/facade/fast-methods.js.map +1 -1
  111. package/dist/facade/generic-lens-capture.d.ts +3 -3
  112. package/dist/facade/generic-lens-capture.js +3 -3
  113. package/dist/facade/generic-lens-capture.js.map +1 -1
  114. package/dist/facade/image-plane-enable.d.ts +7 -0
  115. package/dist/facade/image-plane-enable.js +17 -0
  116. package/dist/facade/image-plane-enable.js.map +1 -0
  117. package/dist/facade/image-plane-lattice-data.d.ts +6 -0
  118. package/dist/facade/image-plane-lattice-data.js +10 -0
  119. package/dist/facade/image-plane-lattice-data.js.map +1 -0
  120. package/dist/facade/image-plane-support.d.ts +33 -0
  121. package/dist/facade/image-plane-support.js +11 -0
  122. package/dist/facade/image-plane-support.js.map +1 -0
  123. package/dist/facade/image-plane.d.ts +36 -0
  124. package/dist/facade/image-plane.js +384 -0
  125. package/dist/facade/image-plane.js.map +1 -0
  126. package/dist/facade/mixed-illumination.d.ts +108 -0
  127. package/dist/facade/mixed-illumination.js +174 -0
  128. package/dist/facade/mixed-illumination.js.map +1 -0
  129. package/dist/facade/on-demand-kits.d.ts +14 -0
  130. package/dist/facade/on-demand-kits.js +36 -0
  131. package/dist/facade/on-demand-kits.js.map +1 -0
  132. package/dist/facade/opt-in-kit.d.ts +9 -0
  133. package/dist/facade/opt-in-kit.js +11 -0
  134. package/dist/facade/opt-in-kit.js.map +1 -0
  135. package/dist/facade/quality-kit.d.ts +21 -0
  136. package/dist/facade/quality-kit.js +23 -0
  137. package/dist/facade/quality-kit.js.map +1 -0
  138. package/dist/facade/quality-paths.d.ts +22 -0
  139. package/dist/facade/quality-paths.js +44 -0
  140. package/dist/facade/quality-paths.js.map +1 -0
  141. package/dist/facade/representative-light-sources.d.ts +72 -0
  142. package/dist/facade/representative-light-sources.js +124 -0
  143. package/dist/facade/representative-light-sources.js.map +1 -0
  144. package/dist/facade/scene-radiance.d.ts +145 -4
  145. package/dist/facade/scene-radiance.js +50 -13
  146. package/dist/facade/scene-radiance.js.map +1 -1
  147. package/dist/facade/simulate-capture.d.ts +68 -20
  148. package/dist/facade/simulate-capture.js +399 -146
  149. package/dist/facade/simulate-capture.js.map +1 -1
  150. package/dist/facade/simulate-display-view.d.ts +10 -12
  151. package/dist/facade/simulate-display-view.js +70 -53
  152. package/dist/facade/simulate-display-view.js.map +1 -1
  153. package/dist/gpu/chart-composite-gpu.d.ts +13 -1
  154. package/dist/gpu/chart-composite-gpu.js +48 -9
  155. package/dist/gpu/chart-composite-gpu.js.map +1 -1
  156. package/dist/gpu/chart-radiance-gpu.js +4 -30
  157. package/dist/gpu/chart-radiance-gpu.js.map +1 -1
  158. package/dist/gpu/display-view-composite-material-module.d.ts +10 -4
  159. package/dist/gpu/display-view-composite-material-module.js +39 -13
  160. package/dist/gpu/display-view-composite-material-module.js.map +1 -1
  161. package/dist/gpu/display-view-gpu-renderer.d.ts +43 -0
  162. package/dist/gpu/display-view-gpu-renderer.js +134 -0
  163. package/dist/gpu/display-view-gpu-renderer.js.map +1 -0
  164. package/dist/gpu/display-view-image-material-module.d.ts +87 -0
  165. package/dist/gpu/display-view-image-material-module.js +361 -0
  166. package/dist/gpu/display-view-image-material-module.js.map +1 -0
  167. package/dist/gpu/display-view-image-quality.d.ts +87 -0
  168. package/dist/gpu/display-view-image-quality.js +625 -0
  169. package/dist/gpu/display-view-image-quality.js.map +1 -0
  170. package/dist/gpu/display-view-quality-gpu.d.ts +80 -65
  171. package/dist/gpu/display-view-quality-gpu.js +187 -445
  172. package/dist/gpu/display-view-quality-gpu.js.map +1 -1
  173. package/dist/gpu/display-view-speed-gpu.d.ts +67 -19
  174. package/dist/gpu/display-view-speed-gpu.js +181 -105
  175. package/dist/gpu/display-view-speed-gpu.js.map +1 -1
  176. package/dist/gpu/image-kernel-accelerator.js +3 -0
  177. package/dist/gpu/image-kernel-accelerator.js.map +1 -1
  178. package/dist/gpu/image-kernel-execution.d.ts +2 -13
  179. package/dist/gpu/image-kernel-execution.js +2 -10
  180. package/dist/gpu/image-kernel-execution.js.map +1 -1
  181. package/dist/gpu/wgsl-display-view-coupled-stub.d.ts +8 -0
  182. package/dist/gpu/wgsl-display-view-coupled-stub.js +21 -0
  183. package/dist/gpu/wgsl-display-view-coupled-stub.js.map +1 -0
  184. package/dist/gpu/wgsl-display-view-coupled.d.ts +88 -0
  185. package/dist/gpu/wgsl-display-view-coupled.js +353 -0
  186. package/dist/gpu/wgsl-display-view-coupled.js.map +1 -0
  187. package/dist/gpu/wgsl-display-view-quality-kernel.d.ts +33 -24
  188. package/dist/gpu/wgsl-display-view-quality-kernel.js +166 -146
  189. package/dist/gpu/wgsl-display-view-quality-kernel.js.map +1 -1
  190. package/dist/gpu/wgsl-display-view-speed-kernel.d.ts +19 -44
  191. package/dist/gpu/wgsl-display-view-speed-kernel.js +116 -18
  192. package/dist/gpu/wgsl-display-view-speed-kernel.js.map +1 -1
  193. package/dist/gpu/wgsl-exact-sum.d.ts +20 -0
  194. package/dist/gpu/wgsl-exact-sum.js +42 -0
  195. package/dist/gpu/wgsl-exact-sum.js.map +1 -0
  196. package/dist/index.d.ts +22 -6
  197. package/dist/index.js +16 -2
  198. package/dist/index.js.map +1 -1
  199. package/dist/motion/subject-motion.d.ts +66 -0
  200. package/dist/motion/subject-motion.js +52 -0
  201. package/dist/motion/subject-motion.js.map +1 -0
  202. package/dist/optics/generic-lens-lateral-color.d.ts +83 -0
  203. package/dist/optics/generic-lens-lateral-color.js +77 -0
  204. package/dist/optics/generic-lens-lateral-color.js.map +1 -0
  205. package/dist/optics/generic-lens-psf.js +54 -46
  206. package/dist/optics/generic-lens-psf.js.map +1 -1
  207. package/dist/optics/lens-psf-profile.d.ts +7 -0
  208. package/dist/optics/lens-psf-profile.js +2 -1
  209. package/dist/optics/lens-psf-profile.js.map +1 -1
  210. package/dist/output/camera-channel-response.d.ts +50 -0
  211. package/dist/output/camera-channel-response.js +69 -0
  212. package/dist/output/camera-channel-response.js.map +1 -0
  213. package/dist/output/developed-lens-corrections.d.ts +19 -5
  214. package/dist/output/developed-lens-corrections.js +28 -9
  215. package/dist/output/developed-lens-corrections.js.map +1 -1
  216. package/dist/output/generic-lens-corrections.d.ts +41 -5
  217. package/dist/output/generic-lens-corrections.js +52 -8
  218. package/dist/output/generic-lens-corrections.js.map +1 -1
  219. package/dist/output/native-capture-sdr.js +5 -2
  220. package/dist/output/native-capture-sdr.js.map +1 -1
  221. package/dist/output/print-plan.d.ts +41 -5
  222. package/dist/output/print-plan.js +59 -14
  223. package/dist/output/print-plan.js.map +1 -1
  224. package/dist/output/sdr-rendering.d.ts +18 -1
  225. package/dist/output/sdr-rendering.js +39 -2
  226. package/dist/output/sdr-rendering.js.map +1 -1
  227. package/dist/sensor/binomial-sample.d.ts +3 -0
  228. package/dist/sensor/binomial-sample.js +86 -0
  229. package/dist/sensor/binomial-sample.js.map +1 -0
  230. package/dist/sensor/native-sensor-report.d.ts +10 -0
  231. package/dist/sensor/native-sensor-report.js +16 -0
  232. package/dist/sensor/native-sensor-report.js.map +1 -0
  233. package/dist/sensor/sensor-characteristics.d.ts +91 -13
  234. package/dist/sensor/sensor-characteristics.js +30 -15
  235. package/dist/sensor/sensor-characteristics.js.map +1 -1
  236. package/docs/AGENT_GUIDE.md +1 -0
  237. package/docs/API_REFERENCE.md +214 -4
  238. package/docs/QUICK_START.md +162 -8
  239. package/docs/USAGE.md +195 -22
  240. package/docs/api/capture-c2pa-embed.md +177 -0
  241. package/docs/api/capture-dng-import.md +86 -10
  242. package/docs/api/capture-dng-opcodes.md +93 -0
  243. package/docs/api/capture-dng-profile-maps.md +141 -0
  244. package/docs/api/capture-dng-stage-image.md +43 -0
  245. package/docs/api/capture-jpeg-xl-tiles.md +33 -0
  246. package/docs/api/capture-lossy-jpeg.md +41 -0
  247. package/docs/api/capture-native-raw-development.md +2 -1
  248. package/docs/api/core-execution-error.md +43 -0
  249. package/docs/api/core-version.md +1 -1
  250. package/docs/api/equipment-generic-lens-catalogue.md +10 -5
  251. package/docs/api/equipment-sensor-profile-body.md +64 -0
  252. package/docs/api/equipment-sensor-profiles.md +86 -0
  253. package/docs/api/exports.json +460 -5
  254. package/docs/api/facade-display-view-gpu.md +5 -2
  255. package/docs/api/facade-display-view.md +11 -15
  256. package/docs/api/facade-exposure-build-up.md +105 -0
  257. package/docs/api/facade-fast-methods.md +47 -10
  258. package/docs/api/facade-image-plane-enable.md +16 -0
  259. package/docs/api/facade-mixed-illumination.md +67 -0
  260. package/docs/api/facade-quality-paths.md +24 -0
  261. package/docs/api/facade-representative-light-sources.md +131 -0
  262. package/docs/api/facade-scene-radiance.md +54 -3
  263. package/docs/api/facade-simulate-capture.md +48 -11
  264. package/docs/api/facade-simulate-display-view.md +10 -12
  265. package/docs/api/gpu-image-kernel-execution.md +0 -36
  266. package/docs/api/motion-subject-motion.md +23 -0
  267. package/docs/api/optics-generic-lens-lateral-color.md +79 -0
  268. package/docs/api/output-camera-channel-response.md +55 -0
  269. package/docs/api/output-developed-lens-corrections.md +10 -1
  270. package/docs/api/output-generic-lens-corrections.md +40 -4
  271. package/docs/api/output-print-plan.md +35 -1
  272. package/docs/api/output-sdr-rendering.md +6 -1
  273. package/docs/api/sensor-sensor-characteristics.md +54 -2
  274. package/llms.txt +3 -0
  275. package/package.json +6 -5
@@ -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.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAsBtC,OAAO,EAAE,wCAAwC,EAAE,mCAAmC,EAAE,MAAM,uCA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BAAE,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,EAAE,gCAAgC,EAAE,MAAM,wCAAwC,CAAC;AAC1F,OAAO,EAAE,+BAA+B,EAAE,mCAAmC,EAAE,MA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AAE,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"]}
@@ -44,7 +44,8 @@ export interface NativeRawDevelopmentInput {
44
44
  }
45
45
  /** RAW saturation handled before white balance. Counts are pixels or samples of the developed output. */
46
46
  export interface RawHighlightDiagnostics {
47
- mode: RawHighlightMode;
47
+ /** #602: "reconstruct-neighbors" from `simulateCapture`'s whole-image neighbor reconstruction. */
48
+ mode: RawHighlightMode | "reconstruct-neighbors";
48
49
  /** Output pixels with at least one contributing site at or above its white level, or flagged as saturated. */
49
50
  saturatedPixelCount: number;
50
51
  /** `clip`: WB-scaled samples clipped at the smallest gain. Always 0 for `reconstruct`. */
@@ -1 +1 @@
1
- {"version":3,"file":"native-raw-development.js","sourceRoot":"","sources":["../../src/capture/native-raw-development.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;GAIG;AACH,OAAO,EAAE,sBAAsB,EAAsE,MAAM,iBAAiB,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAA2C,MAAM,+BAA+B,CAAC;AAC7H,OAAO,EAAE,iCAAiC,EAAE,4BAA4B,EAAE,kCAAkC,EACpE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,6BAA6B,EAAiC,MAAM,0BAA0B,CAAC;AACxG,OAAO,EAAE,6BAA6B,EAAsD,MAAM,sCAAsC,CAAC;AACzI,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,mBAAmB,EAAqD,MAAM,4BAA4B,CAAC;AACrK,OAAO,EAAE,gBAAgB,EAAgD,MAAM,iCAAiC,CAAC;AACjH,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAAyB,MAAM,yBAAyB,CAAC;AACjH,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,E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O,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,KAAQ,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;QACtH,OAAO,KAAQ,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;QACpF,UAAU,KAA8B,IAAG,KAAK,KAAG,WAAW,IAAE,CAAC,MAAM;YAAC,MAAM,IAAI,yBAAyB,CAAC,iCAAiC,CAAC,CAAC,CAAA,MAAM,KAAK,GAAC,MAAM,CAAC,CAAA,MAAM,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,aAAa,CAAC,CAAA,OAAO,KAAK,CAAC,CAAA,CAAC;KAC5N,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW development: turns packed RAW codes into an SDR image. It reconstructs full colour from\n * the CFA (colour filter array) mosaic exactly, then applies the shared colour, white-balance and SDR\n * steps, in bounded pixel tiles.\n */\nimport { calculateNativeRawPlan, type NativeRawInput, type NativeRawOutput, type NativeRawTaskState } from \"./native-raw.js\";\nimport { parseRawReconstructionPhaseProfiles, type RawFrameReconstructionPhaseProfile } from \"./raw-frame-reconstruction.js\";\nimport { calculateRawReconstructionChannel, rawReconstructionKernelReach, validateMirrorBorderCfaConsistency,\n type RawReconstructionBorderHandling } from \"../sensor/raw-reconstruction.js\";\nimport { equalWithinUlps } from \"../core/portable-math.js\";\nimport { resolveColorSamplingSite } from \"../sensor/color-sampling.js\";\nimport { parseExportSensorColorProfile, type ExportSensorColorProfile } from \"./photographic-export.js\";\nimport { prepareSensorColorDevelopment, type RawHighlightMode, type SensorColorDevelopment } from \"../color/sensor-color-development.js\";\nimport { calculateSdrRendering, parseSdrRenderingProfile, prepareSdrPixelTone, type SdrRenderingProfile, type SdrRenderingResult } from \"../output/sdr-rendering.js\";\nimport { renderSdrRunInto, type NativeTaskProgress, type SdrPixelCounts } from \"../output/native-capture-sdr.js\";\nimport { transformOrientedRasterPointToNative } from \"../output/capture-geometry.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence } from \"./host-yield-cadence.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { stringifyCanonicalJson } from \"../core/canonical-json.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { createRawDevelopmentCounts, createRawPixelDeveloper, normalizedRawSite, rawSiteSaturated,\n type RawDevelopmentCounts, type RawDevelopmentSource } from \"./raw-development-kernel.js\";\n\nexport interface NativeRawDevelopmentInput {\n /**\n * Packed RAW. Ownership passes to the task. On creation its five typed arrays are detached with\n * `ArrayBuffer.prototype.transfer` (no copy; the caller's arrays become length 0), or copied when\n * the runtime has no `transfer`. The developed output hands back the same RAW, now owned by the output.\n */\n raw: NativeRawOutput;\n phaseProfiles: readonly RawFrameReconstructionPhaseProfile[];\n colorProfile: ExportSensorColorProfile;\n whiteBalance: \"not-required\" | \"apply-resolved-sensor-gains\";\n rendering: SdrRenderingProfile;\n /** Highlight handling. `clip` (default): clipped highlights become neutral. `reconstruct`: the documented blend toward neutral. */\n highlightMode?: RawHighlightMode;\n /**\n * Frame-edge handling. `reject` (default): every reconstruction neighbourhood must lie inside the\n * native RAW frame. `mirror`: a site outside the frame is read from its mirror image (reflect-101,\n * edge not repeated). This is allowed only when the mirrored site has the same CFA colour, which is\n * always true for a 2×2 Bayer pattern. Interior pixels are unchanged.\n */\n borderHandling?: RawReconstructionBorderHandling;\n /**\n * Development exposure push in stops (#556), from {@link NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS} −2 to +5; default 0.\n * Each site's black-subtracted, white-normalized value is multiplied by 2^stops before demosaic, white balance, the\n * highlight mode, colour and the tone curve, like a raw editor's exposure slider. A site whose pushed value reaches the\n * white level is clipped there and counted as saturated (so `highlightMode: \"reconstruct\"` rolls it off); values below\n * black stay signed. The RAW codes are not changed. 0 (or omitted) develops exactly as before, byte for byte.\n */\n exposureCompensationStops?: number;\n /** Counts the kept packed RAW plus the integer output. It does not count caller buffers, process heap or GPU memory. */\n maximumRetainedPayloadBytes: number;\n}\n/** RAW saturation handled before white balance. Counts are pixels or samples of the developed output. */\nexport interface RawHighlightDiagnostics {\n mode: RawHighlightMode;\n /** Output pixels with at least one contributing site at or above its white level, or flagged as saturated. */\n saturatedPixelCount: number;\n /** `clip`: WB-scaled samples clipped at the smallest gain. Always 0 for `reconstruct`. */\n whiteBalanceClippedSampleCount: number;\n /** `reconstruct`: pixels blended toward neutral. Always 0 for `clip`. */\n reconstructedPixelCount: number;\n}\nexport interface NativeRawDevelopmentOutput {\n raw: NativeRawOutput;\n phaseProfiles: readonly RawFrameReconstructionPhaseProfile[];\n colorProfile: ExportSensorColorProfile;\n whiteBalance: NativeRawDevelopmentInput[\"whiteBalance\"];\n width: number;\n height: number;\n integerSamples: Uint8Array | Uint16Array;\n diagnostics: SdrRenderingResult[\"diagnostics\"];\n highlight: RawHighlightDiagnostics;\n borderHandling: RawReconstructionBorderHandling;\n outputEncoding: SdrRenderingResult[\"outputEncoding\"];\n rendering: SdrRenderingProfile;\n displayAdaptation: SdrRenderingResult[\"displayAdaptation\"];\n imageDataPairing: \"derived-from-exact-packed-native-raw\";\n producerOriginVerified: false;\n}\n/** Host callbacks, the same shape as the other native task providers but without a tile reader. */\nexport interface NativeRawDevelopmentProvider {\n /** Must yield to the host event loop, so cancellation and input events can run between tiles. */\n yieldControl(signal: AbortSignal): Promise<void>;\n /** Optional callback after each committed 256-pixel output tile. It cannot change the output. */\n onProgress?(progress: NativeTaskProgress): void;\n}\nexport interface NativeRawDevelopmentTask {\n readonly state: NativeRawTaskState;\n readonly completedTileCount: number;\n readonly totalTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n takeOutput(): NativeRawDevelopmentOutput;\n}\nconst TILE_WIDTH = 256;\n/** Accepted range of `NativeRawDevelopmentInput.exposureCompensationStops` and `simulateCapture`'s `output.exposureCompensationStops` (#556). */\nexport const NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS = /* @__PURE__ */ Object.freeze({ minimum: -2, maximum: 5 } as const);\n/** Sites checked per integrity chunk before checking whether it is time to yield. */\nconst INTEGRITY_CHUNK_SITES = 1 << 18;\nfunction canonical(value: unknown): string {\n return stringifyCanonicalJson(value,{undefinedObjectProperties:\"reject\",nonFiniteNumberMessage:\"Invalid RAW metadata.\",unsupportedValueMessage:\"Invalid RAW metadata.\"});\n}\n/** Validates packed RAW storage and recomputes its plan. Shared with the native DNG writer. Not exported from the package. */\nexport function validatePackedNativeRaw(raw: NativeRawOutput): NativeRawOutput[\"plan\"] {\n requireAllowlistedRecord(raw,[\"plan\",\"codes\",\"blackLevels\",\"digitalSaturationCodes\",\"saturationFlags\",\"effectiveSaturationCodes\"],\"Invalid packed RAW output.\");\n const p=raw.plan;\n if(!p?.exposure||!p.frame)throw new InvalidConfigurationError(\"Packed RAW requires complete exposure and frame metadata.\");\n const {engineApiVersion,resolvedGeometry,equivalentFocalLength35Mm,...exposure}=p.exposure;\n void engineApiVersion;void resolvedGeometry;\n const {capture,containerBitDepth,...frame}=p.frame;void containerBitDepth;\n const input: NativeRawInput={exposure,...frame,maximumOutputBytes:p.outputBytes,...(p.tileWidth===undefined?{}:{tileWidth:p.tileWidth}),...(p.maximumPixels===undefined?{}:{maximumPixels:p.maximumPixels}),...(p.exposureWindow?{exposureWindow:p.exposureWindow}:{})};\n const plan=calculateNativeRawPlan(input);\n // The recomputed 35 mm-equivalent focal length (also inside frame.capture, the same exposure record) may\n // differ by a few ULPs, so records parse in every JavaScript engine. Every other field must match exactly.\n const eq=plan.exposure.equivalentFocalLength35Mm,archivedFrameEq=(capture as unknown as Record<string,unknown>|undefined)?.equivalentFocalLength35Mm;\n if(typeof equivalentFocalLength35Mm!==\"number\"||!equalWithinUlps(equivalentFocalLength35Mm,eq,8)||typeof archivedFrameEq!==\"number\"||!equalWithinUlps(archivedFrameEq,eq,8)||\n canonical({...p,exposure:{...p.exposure,equivalentFocalLength35Mm:eq},frame:{...p.frame,capture:{...p.frame.capture,equivalentFocalLength35Mm:eq}}})!==canonical(plan))\n throw new InvalidConfigurationError(\"Packed RAW metadata is stale or inconsistent.\");\n const layout=plan.frame.colorSamplingProfile.layout,phaseCount=layout.kind===\"periodic-mosaic\"?layout.repeatWidthSites*layout.repeatHeightSites:0;\n const buffers=new Set<ArrayBufferLike>();\n for(const [a,type,length] of [[raw.codes,Uint16Array,plan.pixelCount],[raw.blackLevels,Uint16Array,plan.pixelCount],[raw.digitalSaturationCodes,Uint16Array,plan.pixelCount],\n [raw.saturationFlags,Uint8Array,plan.pixelCount],[raw.effectiveSaturationCodes,Uint16Array,phaseCount]] as const){\n if(!(a instanceof type)||!(a.buffer instanceof ArrayBuffer)||a.length!==length||a.buffer.byteLength!==a.byteLength||buffers.has(a.buffer))throw new InvalidConfigurationError(\"Packed RAW storage must be exact owned native arrays.\");\n buffers.add(a.buffer);\n }\n return plan;\n}\n/** Takes sole ownership: detaches without copying when the runtime supports ArrayBuffer transfer, otherwise copies. */\nfunction own<T extends Uint8Array<ArrayBuffer>|Uint16Array<ArrayBuffer>>(array: T, make: (buffer: ArrayBuffer)=>T): T {\n const buffer=array.buffer as ArrayBuffer&{transfer?:()=>ArrayBuffer};\n return typeof buffer.transfer===\"function\"?make(buffer.transfer()):make(buffer.slice(0));\n}\n/** Takes the validated packed RAW's arrays (without copying where supported). Not exported from the package. */\nexport function takeNativeRawOwnership(given: NativeRawOutput, plan: NativeRawOutput[\"plan\"]): NativeRawOutput {\n return {plan,codes:own(given.codes as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),blackLevels:own(given.blackLevels as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),\n digitalSaturationCodes:own(given.digitalSaturationCodes as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),saturationFlags:own(given.saturationFlags as Uint8Array<ArrayBuffer>,b=>new Uint8Array(b)),\n effectiveSaturationCodes:given.effectiveSaturationCodes.slice()};\n}\n/** Validated development metadata (internal; shared with the image-kernel accelerator). Not exported from the package. */\nexport interface PreparedDevelopment {\n plan: NativeRawOutput[\"plan\"]; phases: RawFrameReconstructionPhaseProfile[]; color: ExportSensorColorProfile; profile: SdrRenderingProfile;\n whiteBalance: NativeRawDevelopmentInput[\"whiteBalance\"]; highlightMode: RawHighlightMode; development: SensorColorDevelopment;\n crop: {x:number;y:number;width:number;height:number}; raster: {pixelWidth:number;pixelHeight:number};\n border: RawReconstructionBorderHandling; mirror: {nativeHeight:number;reach:number}|undefined;\n /** Development exposure gain 2^exposureCompensationStops; exactly 1 without a push. */\n exposureGain: number;\n}\n/**\n * Synchronous checks of metadata, kernel halo (the neighbourhood each pixel reads) and CFA, shared by the\n * task, the reference and the accelerator. No pixel loop. Not exported from the package.\n */\nexport function prepareNativeRawDevelopment(input: NativeRawDevelopmentInput): PreparedDevelopment {\n const r=requireAllowlistedRecord(input,[\"raw\",\"phaseProfiles\",\"colorProfile\",\"whiteBalance\",\"rendering\",\"highlightMode\",\"borderHandling\",\"exposureCompensationStops\",\"maximumRetainedPayloadBytes\"],\"Invalid native RAW development input.\");\n const plan=validatePackedNativeRaw(input.raw),g=plan.exposure.resolvedGeometry,native=plan.exposure.geometry.nativeRaster;\n const phases=freezeOwnedData(parseRawReconstructionPhaseProfiles(r.phaseProfiles,plan.frame.modeId,plan.frame.colorSamplingProfile));\n const color=freezeOwnedData(parseExportSensorColorProfile(r.colorProfile)),profile=freezeOwnedData(parseSdrRenderingProfile(r.rendering));\n const crop=g.output.cropRect,raster=g.output.raster,active=g.activeCapture.nativeRect,intent=plan.exposure.whiteBalanceIntent;\n const highlightMode=r.highlightMode===undefined?\"clip\":r.highlightMode;\n if(highlightMode!==\"clip\"&&highlightMode!==\"reconstruct\")throw new InvalidConfigurationError(\"Unsupported RAW highlight mode.\");\n const border=r.borderHandling===undefined?\"reject\":r.borderHandling;\n if(border!==\"reject\"&&border!==\"mirror\")throw new InvalidConfigurationError(\"Unsupported RAW border handling.\");\n const stops=r.exposureCompensationStops===undefined?0:r.exposureCompensationStops;\n if(typeof stops!==\"number\"||!Number.isFinite(stops)||stops<NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS.minimum||stops>NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS.maximum)\n throw new InvalidConfigurationError(\"RAW development exposureCompensationStops must be a finite number from -2 to +5.\");\n const exposureGain=stops===0?1:2**stops;\n if(color.colorSamplingProfileId!==plan.frame.colorSamplingProfile.profileId||phases.some(p=>canonical(p.profile.kernels.map(k=>k.outputChannelId))!==canonical(color.channelIds))||\n (r.whiteBalance!==\"not-required\"&&r.whiteBalance!==\"apply-resolved-sensor-gains\")||(intent!==null)!==(r.whiteBalance===\"apply-resolved-sensor-gains\")||\n raster.pixelWidth!==crop.width||raster.pixelHeight!==crop.height)throw new InvalidConfigurationError(\"Development requires bound sensor RGB, explicit one-time WB and 1:1 output crop.\");\n const bytes=plan.outputBytes+raster.pixelWidth*raster.pixelHeight*3*profile.bitDepth/8;\n if(typeof r.maximumRetainedPayloadBytes!==\"number\"||!Number.isSafeInteger(r.maximumRetainedPayloadBytes)||r.maximumRetainedPayloadBytes<bytes)throw new InvalidConfigurationError(\"Development exceeds retained output budget.\");\n const gains=intent?[intent.channelGains.red,intent.channelGains.green,intent.channelGains.blue]:null;\n const development=prepareSensorColorDevelopment(color.normalizedCameraChannelsToXyz,gains,highlightMode),layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Development requires periodic CFA.\");\n const nativeCorners=[{x:crop.x+.5,y:crop.y+.5},{x:crop.x+crop.width-.5,y:crop.y+crop.height-.5}].map(point=>{\n const p=transformOrientedRasterPointToNative({point,nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});return {x:Math.floor(p.x)+active.x,y:Math.floor(p.y)+active.y};\n });\n const minX=Math.min(...nativeCorners.map(p=>p.x)),maxX=Math.max(...nativeCorners.map(p=>p.x)),minY=Math.min(...nativeCorners.map(p=>p.y)),maxY=Math.max(...nativeCorners.map(p=>p.y));\n for(const phase of phases){\n const firstX=minX+(phase.phaseX-minX%layout.repeatWidthSites+layout.repeatWidthSites)%layout.repeatWidthSites;\n const firstY=minY+(phase.phaseY-minY%layout.repeatHeightSites+layout.repeatHeightSites)%layout.repeatHeightSites;\n if(firstX>maxX||firstY>maxY)continue;\n const lastX=maxX-(maxX-phase.phaseX+layout.repeatWidthSites)%layout.repeatWidthSites,lastY=maxY-(maxY-phase.phaseY+layout.repeatHeightSites)%layout.repeatHeightSites;\n for(const kernel of phase.profile.kernels)for(const c of kernel.contributions){\n if(firstX+c.offsetX<0||firstY+c.offsetY<0||lastX+c.offsetX>=native.pixelWidth||lastY+c.offsetY>=native.pixelHeight){\n if(border===\"reject\")throw new InvalidConfigurationError(\"Reconstruction halo leaves native RAW; no padding or renormalization.\");\n // Mirror: check the virtual site from the repeating pattern; validateMirrorBorderCfaConsistency proves mirrored reads agree with it.\n const vx=phase.phaseX+c.offsetX,vy=phase.phaseY+c.offsetY;\n if(layout.siteChannelIds[((vy%layout.repeatHeightSites)+layout.repeatHeightSites)%layout.repeatHeightSites*layout.repeatWidthSites+((vx%layout.repeatWidthSites)+layout.repeatWidthSites)%layout.repeatWidthSites]!==c.sourceChannelId)\n throw new InvalidConfigurationError(\"Reconstruction source channel disagrees with absolute CFA phase.\");\n continue;\n }\n const channel=resolveColorSamplingSite({profile:plan.frame.colorSamplingProfile,site:{x:firstX+c.offsetX,y:firstY+c.offsetY}}).mapping.channelId;\n if(channel!==c.sourceChannelId)throw new InvalidConfigurationError(\"Reconstruction source channel disagrees with absolute CFA phase.\");\n }\n }\n let mirror:PreparedDevelopment[\"mirror\"];\n if(border===\"mirror\"){\n const reach=rawReconstructionKernelReach(phases);\n validateMirrorBorderCfaConsistency(layout,native.pixelWidth,native.pixelHeight,reach);\n mirror={nativeHeight:native.pixelHeight,reach};\n }\n return {plan,phases,color,profile,whiteBalance:r.whiteBalance,highlightMode,development,crop,raster,border,mirror,exposureGain};\n}\n/** Checks the numbers in rows [y0,y1). Values below black stay signed; each white-minus-black span is positive. Not exported from the package. */\nexport function checkNativeRawIntegrity(raw: NativeRawOutput, nativeWidth: number, repeatWidth: number, repeatHeight: number, y0: number, y1: number): void {\n const codes=raw.codes,blacks=raw.blackLevels,digital=raw.digitalSaturationCodes,flags=raw.saturationFlags,white=raw.effectiveSaturationCodes;\n for(let y=y0;y<y1;y++){\n const row=(y%repeatHeight)*repeatWidth;\n for(let x=0,i=y*nativeWidth;x<nativeWidth;x++,i++){\n const d=digital[i]!,w=white[row+x%repeatWidth]!,b=blacks[i]!;\n if(b>=w||w>d||codes[i]!>d||flags[i]!>7)throw new InvalidConfigurationError(\"Invalid packed RAW code span, white level or saturation flags.\");\n }\n }\n}\nfunction source(raw: NativeRawOutput, plan: NativeRawOutput[\"plan\"], exposureGain: number): RawDevelopmentSource {\n const layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Development requires periodic CFA.\");\n return {nativeWidth:plan.exposure.geometry.nativeRaster.pixelWidth,repeatWidth:layout.repeatWidthSites,repeatHeight:layout.repeatHeightSites,\n codes:raw.codes,blackLevels:raw.blackLevels,saturationFlags:raw.saturationFlags,whiteByPhase:raw.effectiveSaturationCodes,...(exposureGain===1?{}:{exposureGain})};\n}\nfunction emptyDiagnostics(): SdrRenderingResult[\"diagnostics\"] {\n return {renderingNegativeSampleCount:0,renderingAboveReferenceSampleCount:0,toneChangedSampleCount:0,gamutClippedLowSampleCount:0,gamutClippedHighSampleCount:0,captureSaturation:\"consumed-in-raw-development\"};\n}\nfunction highlightOf(mode: RawHighlightMode, counts: RawDevelopmentCounts): RawHighlightDiagnostics {\n return {mode,saturatedPixelCount:counts.saturatedPixelCount,whiteBalanceClippedSampleCount:counts.whiteBalanceClippedSampleCount,reconstructedPixelCount:counts.reconstructedPixelCount};\n}\n/**\n * Internal, slow reference development using one object per step (not exported from the package). It is\n * kept to prove that the fast typed kernel gives byte-identical output.\n *\n * For each pixel it maps orientation with `transformOrientedRasterPointToNative`, gathers each channel\n * with `calculateRawReconstructionChannel`, develops with the shared colour operator, and renders\n * 256-pixel rows with the reference `calculateSdrRendering`. It does not take ownership of the RAW.\n */\nexport function developNativeRawReference(input: NativeRawDevelopmentInput): {integerSamples:number[];diagnostics:SdrRenderingResult[\"diagnostics\"];highlight:RawHighlightDiagnostics} {\n const v=prepareNativeRawDevelopment(input),plan=v.plan,g=plan.exposure.resolvedGeometry,active=g.activeCapture.nativeRect,src=source(input.raw,plan,v.exposureGain);\n checkNativeRawIntegrity(input.raw,src.nativeWidth,src.repeatWidth,src.repeatHeight,0,plan.exposure.geometry.nativeRaster.pixelHeight);\n const counts=createRawDevelopmentCounts(),diagnostics=emptyDiagnostics(),out:number[]=[];\n for(let y=0;y<v.raster.pixelHeight;y++)for(let x=0;x<v.raster.pixelWidth;x+=TILE_WIDTH){\n const width=Math.min(TILE_WIDTH,v.raster.pixelWidth-x),rgb:number[]=[];\n for(let j=0;j<width;j++){\n const q=transformOrientedRasterPointToNative({point:{x:v.crop.x+x+j+.5,y:v.crop.y+y+.5},nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});\n const point={x:Math.floor(q.x)+active.x,y:Math.floor(q.y)+active.y};\n const phase=v.phases[(point.y%src.repeatHeight)*src.repeatWidth+point.x%src.repeatWidth]!;\n let saturated=false;\n const values=phase.profile.kernels.map(kernel=>calculateRawReconstructionChannel(kernel,point,(sx,sy)=>{\n if(rawSiteSaturated(src,sx,sy))saturated=true;return normalizedRawSite(src,sx,sy);\n },v.mirror===undefined?undefined:{width:src.nativeWidth,height:v.mirror.nativeHeight}).linearBlackSubtractedNormalizedValue);\n if(saturated)counts.saturatedPixelCount++;\n const developed=[0,0,0];v.development.developInto(values[0]!,values[1]!,values[2]!,developed,0,counts);rgb.push(...developed);\n }\n const rendered=calculateSdrRendering({sourceImageStateId:plan.frame.frameId+\":developed\",inputImageState:\"color-transformed-linear-rgb\",inputColorSpace:\"linear-srgb-d65\",whiteBalanceHandling:plan.exposure.whiteBalanceIntent?\"already-applied-upstream\":\"not-required\",pixelWidth:width,pixelHeight:1,referenceWhiteValue:1,samples:rgb,profile:v.profile}).value;\n out.push(...rendered.integerSamples);\n for(const key of [\"renderingNegativeSampleCount\",\"renderingAboveReferenceSampleCount\",\"toneChangedSampleCount\",\"gamutClippedLowSampleCount\",\"gamutClippedHighSampleCount\"] as const)diagnostics[key]+=rendered.diagnostics[key];\n }\n return {integerSamples:out,diagnostics,highlight:highlightOf(v.highlightMode,counts)};\n}\nfunction sdrOutputEncoding(maximum: number): SdrRenderingResult[\"outputEncoding\"] {\n return {imageState:\"output-referred-sdr\",colorSpace:\"srgb\",primariesXy:{red:[.64,.33],green:[.30,.60],blue:[.15,.06]},whitePointXy:[.3127,.3290],referenceWhiteLuminanceCdM2:80,codeMinimum:0,codeMaximum:maximum};\n}\n/**\n * Creates a native RAW development task.\n *\n * It checks that every CFA phase has a reconstruction kernel and that every kernel neighbourhood is\n * available, takes ownership of the packed RAW (without copying where supported), and renders 256-pixel\n * output tiles with the fast typed kernel. Development scales each site to its CFA phase's effective white\n * level, clips flagged or white-level sites before white balance, and applies the selected highlight mode\n * (see `prepareSensorColorDevelopment`).\n *\n * The RAW numbers are checked in bounded chunks at the start of `run()`, with host yields, so creating the\n * task costs only as much as reading the metadata. The task yields to the host at chunk and tile boundaries\n * once about 8 ms of work has passed since the last yield, and after the final tile. Yield timing never\n * changes the output.\n *\n * `provider` is `{ yieldControl, onProgress? }`, the same shape as the other native task providers. A bare\n * yield function is still accepted in 2.x but is deprecated.\n *\n * The tile width used at capture is kept when rebuilding the exact packed plan. That width changes neither\n * CFA or noise-seed coordinates nor the developed pixels, and says nothing about transport or what a device\n * can handle.\n */\nexport function createNativeRawDevelopmentTask(input: NativeRawDevelopmentInput,\n provider: NativeRawDevelopmentProvider | ((signal:AbortSignal)=>Promise<void>)): NativeRawDevelopmentTask {\n return createNativeRawDevelopmentTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes output. Not exported from the package. */\nexport function createNativeRawDevelopmentTaskWithCadence(input: NativeRawDevelopmentInput,\n provider: NativeRawDevelopmentProvider | ((signal:AbortSignal)=>Promise<void>),cadence: HostYieldCadence): NativeRawDevelopmentTask {\n const hooks=typeof provider===\"function\"?{yieldControl:provider}:provider;\n if(!hooks||typeof hooks.yieldControl!==\"function\"||(hooks.onProgress!==undefined&&typeof hooks.onProgress!==\"function\"))throw new InvalidConfigurationError(\"Development requires a host event-loop yield.\");\n const yieldControl=hooks.yieldControl.bind(hooks),onProgress=hooks.onProgress?.bind(hooks);\n const v=prepareNativeRawDevelopment(input),plan=v.plan,g=plan.exposure.resolvedGeometry,active=g.activeCapture.nativeRect,raster=v.raster,crop=v.crop;\n const nativeHeight=plan.exposure.geometry.nativeRaster.pixelHeight;\n // Ownership is transferred only after every synchronous check has passed.\n const raw=takeNativeRawOwnership(input.raw,plan);\n const src=source(raw,plan,v.exposureGain),tilesPerRow=Math.ceil(raster.pixelWidth/TILE_WIDTH),totalTileCount=tilesPerRow*raster.pixelHeight;\n const abort=new AbortController();let state:NativeRawTaskState=\"ready\",output:NativeRawDevelopmentOutput|null=null,codes:Uint8Array|Uint16Array|null=null,completed=0;\n function release(): void {raw.codes.fill(0);raw.blackLevels.fill(0);raw.digitalSaturationCodes.fill(0);raw.saturationFlags.fill(0);raw.effectiveSaturationCodes.fill(0);codes?.fill(0);codes=null;output=null;}\n function check(): void {if(abort.signal.aborted)throw new InvalidConfigurationError(\"Native RAW development aborted.\");}\n /** Native coordinates of oriented output pixel (x, y) and the step to (x+1, y), both integer. */\n function rowMapping(x: number, y: number, width: number): {nx:number;ny:number;dx:number;dy:number} {\n const at=(j:number):{x:number;y:number}=>{const q=transformOrientedRasterPointToNative({point:{x:crop.x+x+j+.5,y:crop.y+y+.5},nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});return {x:Math.floor(q.x)+active.x,y:Math.floor(q.y)+active.y};};\n const first=at(0),second=width>1?at(1):first,dx=second.x-first.x,dy=second.y-first.y,last=at(width-1);\n if(Math.abs(dx)+Math.abs(dy)!==(width>1?1:0)||last.x!==first.x+dx*(width-1)||last.y!==first.y+dy*(width-1))throw new InvalidConfigurationError(\"Development orientation mapping is not a unit native step.\");\n return {nx:first.x,ny:first.y,dx,dy};\n }\n return {get state():NativeRawTaskState{return state;},get completedTileCount():number{return completed;},totalTileCount,\n async run():Promise<void>{\n if(state!==\"ready\")throw new InvalidConfigurationError(\"Development task is single-use.\");state=\"running\";\n try{\n const gate=createHostYieldGate(cadence);\n const rowsPerChunk=Math.max(1,Math.floor(INTEGRITY_CHUNK_SITES/src.nativeWidth));\n for(let y=0;y<nativeHeight;y+=rowsPerChunk){\n check();checkNativeRawIntegrity(raw,src.nativeWidth,src.repeatWidth,src.repeatHeight,y,Math.min(nativeHeight,y+rowsPerChunk));\n if(gate.due()){await yieldControl(abort.signal);check();gate.restart();}\n }\n codes=v.profile.bitDepth===8?new Uint8Array(raster.pixelWidth*raster.pixelHeight*3):new Uint16Array(raster.pixelWidth*raster.pixelHeight*3);\n const diagnostics=emptyDiagnostics(),developer=createRawPixelDeveloper(src,v.phases,v.development,v.mirror),tone=prepareSdrPixelTone(v.profile);\n const scale=2**v.profile.renderingExposureEv,maximum=2**v.profile.bitDepth-1,rgb=new Float64Array(TILE_WIDTH*3),scratch=new Float64Array(3);\n if(!Number.isFinite(scale)||scale<=0)throw new InvalidConfigurationError(\"Rendering scale is unrepresentable.\");\n for(let y=0;y<raster.pixelHeight;y++)for(let x=0;x<raster.pixelWidth;x+=TILE_WIDTH){\n check();const width=Math.min(TILE_WIDTH,raster.pixelWidth-x),map=rowMapping(x,y,width);\n const counts:SdrPixelCounts={negative:0,above:0,changed:0,low:0,high:0,outOfGamut:false};\n developer.developRun(map.nx,map.ny,map.dx,map.dy,width,rgb);\n renderSdrRunInto(rgb,0,width,v.profile,tone,scale,maximum,codes,(y*raster.pixelWidth+x)*3,scratch,counts);\n // Same 256-pixel granularity as the reference rows, so exposure errors come before gamut rejection.\n if(counts.outOfGamut)throw new InvalidConfigurationError(\"Tone output exceeds the declared SDR gamut range.\");\n diagnostics.renderingNegativeSampleCount+=counts.negative;diagnostics.renderingAboveReferenceSampleCount+=counts.above;diagnostics.toneChangedSampleCount+=counts.changed;\n diagnostics.gamutClippedLowSampleCount+=counts.low;diagnostics.gamutClippedHighSampleCount+=counts.high;\n completed++;onProgress?.({completedTileCount:completed,totalTileCount});\n if(gate.due()||(y===raster.pixelHeight-1&&x+TILE_WIDTH>=raster.pixelWidth)){await yieldControl(abort.signal);check();gate.restart();}\n }\n output={raw,phaseProfiles:v.phases,colorProfile:v.color,whiteBalance:v.whiteBalance,width:raster.pixelWidth,height:raster.pixelHeight,integerSamples:codes,diagnostics,\n highlight:highlightOf(v.highlightMode,developer.counts),borderHandling:v.border,rendering:v.profile,displayAdaptation:{kind:\"external-platform\",applied:false,displayCapabilities:\"unknown\"},\n outputEncoding:sdrOutputEncoding(maximum),imageDataPairing:\"derived-from-exact-packed-native-raw\",producerOriginVerified:false};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():NativeRawDevelopmentOutput{if(state!==\"completed\"||!output)throw new InvalidConfigurationError(\"Development output unavailable.\");const value=output;output=null;codes=null;state=\"transferred\";return value;}\n };\n}\n"]}
1
+ {"version":3,"file":"native-raw-development.js","sourceRoot":"","sources":["../../src/capture/native-raw-development.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;GAIG;AACH,OAAO,EAAE,sBAAsB,EAAsE,MAAM,iBAAiB,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAA2C,MAAM,+BAA+B,CAAC;AAC7H,OAAO,EAAE,iCAAiC,EAAE,4BAA4B,EAAE,kCAAkC,EACpE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,6BAA6B,EAAiC,MAAM,0BAA0B,CAAC;AACxG,OAAO,EAAE,6BAA6B,EAAsD,MAAM,sCAAsC,CAAC;AACzI,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,mBAAmB,EAAqD,MAAM,4BAA4B,CAAC;AACrK,OAAO,EAAE,gBAAgB,EAAgD,MAAM,iCAAiC,CAAC;AACjH,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,mBAAmB,EAAyB,MAAM,yBAAyB,CAAC;AACjH,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,s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EAAC,CAAC;gBAAA,KAAK,GAAC,WAAW,CAAC;YACtJ,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,KAAQ,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;QACtH,OAAO,KAAQ,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;QACpF,UAAU,KAA8B,IAAG,KAAK,KAAG,WAAW,IAAE,CAAC,MAAM;YAAC,MAAM,IAAI,yBAAyB,CAAC,iCAAiC,CAAC,CAAC,CAAA,MAAM,KAAK,GAAC,MAAM,CAAC,CAAA,MAAM,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,aAAa,CAAC,CAAA,OAAO,KAAK,CAAC,CAAA,CAAC;KAC5N,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW development: turns packed RAW codes into an SDR image. It reconstructs full colour from\n * the CFA (colour filter array) mosaic exactly, then applies the shared colour, white-balance and SDR\n * steps, in bounded pixel tiles.\n */\nimport { calculateNativeRawPlan, type NativeRawInput, type NativeRawOutput, type NativeRawTaskState } from \"./native-raw.js\";\nimport { parseRawReconstructionPhaseProfiles, type RawFrameReconstructionPhaseProfile } from \"./raw-frame-reconstruction.js\";\nimport { calculateRawReconstructionChannel, rawReconstructionKernelReach, validateMirrorBorderCfaConsistency,\n type RawReconstructionBorderHandling } from \"../sensor/raw-reconstruction.js\";\nimport { equalWithinUlps } from \"../core/portable-math.js\";\nimport { resolveColorSamplingSite } from \"../sensor/color-sampling.js\";\nimport { parseExportSensorColorProfile, type ExportSensorColorProfile } from \"./photographic-export.js\";\nimport { prepareSensorColorDevelopment, type RawHighlightMode, type SensorColorDevelopment } from \"../color/sensor-color-development.js\";\nimport { calculateSdrRendering, parseSdrRenderingProfile, prepareSdrPixelTone, type SdrRenderingProfile, type SdrRenderingResult } from \"../output/sdr-rendering.js\";\nimport { renderSdrRunInto, type NativeTaskProgress, type SdrPixelCounts } from \"../output/native-capture-sdr.js\";\nimport { transformOrientedRasterPointToNative } from \"../output/capture-geometry.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence } from \"./host-yield-cadence.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { stringifyCanonicalJson } from \"../core/canonical-json.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { createRawDevelopmentCounts, createRawPixelDeveloper, normalizedRawSite, rawSiteSaturated,\n type RawDevelopmentCounts, type RawDevelopmentSource } from \"./raw-development-kernel.js\";\n\nexport interface NativeRawDevelopmentInput {\n /**\n * Packed RAW. Ownership passes to the task. On creation its five typed arrays are detached with\n * `ArrayBuffer.prototype.transfer` (no copy; the caller's arrays become length 0), or copied when\n * the runtime has no `transfer`. The developed output hands back the same RAW, now owned by the output.\n */\n raw: NativeRawOutput;\n phaseProfiles: readonly RawFrameReconstructionPhaseProfile[];\n colorProfile: ExportSensorColorProfile;\n whiteBalance: \"not-required\" | \"apply-resolved-sensor-gains\";\n rendering: SdrRenderingProfile;\n /** Highlight handling. `clip` (default): clipped highlights become neutral. `reconstruct`: the documented blend toward neutral. */\n highlightMode?: RawHighlightMode;\n /**\n * Frame-edge handling. `reject` (default): every reconstruction neighbourhood must lie inside the\n * native RAW frame. `mirror`: a site outside the frame is read from its mirror image (reflect-101,\n * edge not repeated). This is allowed only when the mirrored site has the same CFA colour, which is\n * always true for a 2×2 Bayer pattern. Interior pixels are unchanged.\n */\n borderHandling?: RawReconstructionBorderHandling;\n /**\n * Development exposure push in stops (#556), from {@link NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS} −2 to +5; default 0.\n * Each site's black-subtracted, white-normalized value is multiplied by 2^stops before demosaic, white balance, the\n * highlight mode, colour and the tone curve, like a raw editor's exposure slider. A site whose pushed value reaches the\n * white level is clipped there and counted as saturated (so `highlightMode: \"reconstruct\"` rolls it off); values below\n * black stay signed. The RAW codes are not changed. 0 (or omitted) develops exactly as before, byte for byte.\n */\n exposureCompensationStops?: number;\n /** Counts the kept packed RAW plus the integer output. It does not count caller buffers, process heap or GPU memory. */\n maximumRetainedPayloadBytes: number;\n}\n/** RAW saturation handled before white balance. Counts are pixels or samples of the developed output. */\nexport interface RawHighlightDiagnostics {\n /** #602: \"reconstruct-neighbors\" from `simulateCapture`'s whole-image neighbor reconstruction. */\n mode: RawHighlightMode | \"reconstruct-neighbors\";\n /** Output pixels with at least one contributing site at or above its white level, or flagged as saturated. */\n saturatedPixelCount: number;\n /** `clip`: WB-scaled samples clipped at the smallest gain. Always 0 for `reconstruct`. */\n whiteBalanceClippedSampleCount: number;\n /** `reconstruct`: pixels blended toward neutral. Always 0 for `clip`. */\n reconstructedPixelCount: number;\n}\nexport interface NativeRawDevelopmentOutput {\n raw: NativeRawOutput;\n phaseProfiles: readonly RawFrameReconstructionPhaseProfile[];\n colorProfile: ExportSensorColorProfile;\n whiteBalance: NativeRawDevelopmentInput[\"whiteBalance\"];\n width: number;\n height: number;\n integerSamples: Uint8Array | Uint16Array;\n diagnostics: SdrRenderingResult[\"diagnostics\"];\n highlight: RawHighlightDiagnostics;\n borderHandling: RawReconstructionBorderHandling;\n outputEncoding: SdrRenderingResult[\"outputEncoding\"];\n rendering: SdrRenderingProfile;\n displayAdaptation: SdrRenderingResult[\"displayAdaptation\"];\n imageDataPairing: \"derived-from-exact-packed-native-raw\";\n producerOriginVerified: false;\n}\n/** Host callbacks, the same shape as the other native task providers but without a tile reader. */\nexport interface NativeRawDevelopmentProvider {\n /** Must yield to the host event loop, so cancellation and input events can run between tiles. */\n yieldControl(signal: AbortSignal): Promise<void>;\n /** Optional callback after each committed 256-pixel output tile. It cannot change the output. */\n onProgress?(progress: NativeTaskProgress): void;\n}\nexport interface NativeRawDevelopmentTask {\n readonly state: NativeRawTaskState;\n readonly completedTileCount: number;\n readonly totalTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n takeOutput(): NativeRawDevelopmentOutput;\n}\nconst TILE_WIDTH = 256;\n/** Accepted range of `NativeRawDevelopmentInput.exposureCompensationStops` and `simulateCapture`'s `output.exposureCompensationStops` (#556). */\nexport const NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS = /* @__PURE__ */ Object.freeze({ minimum: -2, maximum: 5 } as const);\n/** Sites checked per integrity chunk before checking whether it is time to yield. */\nconst INTEGRITY_CHUNK_SITES = 1 << 18;\nfunction canonical(value: unknown): string {\n return stringifyCanonicalJson(value,{undefinedObjectProperties:\"reject\",nonFiniteNumberMessage:\"Invalid RAW metadata.\",unsupportedValueMessage:\"Invalid RAW metadata.\"});\n}\n/** Validates packed RAW storage and recomputes its plan. Shared with the native DNG writer. Not exported from the package. */\nexport function validatePackedNativeRaw(raw: NativeRawOutput): NativeRawOutput[\"plan\"] {\n requireAllowlistedRecord(raw,[\"plan\",\"codes\",\"blackLevels\",\"digitalSaturationCodes\",\"saturationFlags\",\"effectiveSaturationCodes\"],\"Invalid packed RAW output.\");\n const p=raw.plan;\n if(!p?.exposure||!p.frame)throw new InvalidConfigurationError(\"Packed RAW requires complete exposure and frame metadata.\");\n const {engineApiVersion,resolvedGeometry,equivalentFocalLength35Mm,...exposure}=p.exposure;\n void engineApiVersion;void resolvedGeometry;\n const {capture,containerBitDepth,...frame}=p.frame;void containerBitDepth;\n const input: NativeRawInput={exposure,...frame,maximumOutputBytes:p.outputBytes,...(p.tileWidth===undefined?{}:{tileWidth:p.tileWidth}),...(p.maximumPixels===undefined?{}:{maximumPixels:p.maximumPixels}),...(p.exposureWindow?{exposureWindow:p.exposureWindow}:{})};\n const plan=calculateNativeRawPlan(input);\n // The recomputed 35 mm-equivalent focal length (also inside frame.capture, the same exposure record) may\n // differ by a few ULPs, so records parse in every JavaScript engine. Every other field must match exactly.\n const eq=plan.exposure.equivalentFocalLength35Mm,archivedFrameEq=(capture as unknown as Record<string,unknown>|undefined)?.equivalentFocalLength35Mm;\n if(typeof equivalentFocalLength35Mm!==\"number\"||!equalWithinUlps(equivalentFocalLength35Mm,eq,8)||typeof archivedFrameEq!==\"number\"||!equalWithinUlps(archivedFrameEq,eq,8)||\n canonical({...p,exposure:{...p.exposure,equivalentFocalLength35Mm:eq},frame:{...p.frame,capture:{...p.frame.capture,equivalentFocalLength35Mm:eq}}})!==canonical(plan))\n throw new InvalidConfigurationError(\"Packed RAW metadata is stale or inconsistent.\");\n const layout=plan.frame.colorSamplingProfile.layout,phaseCount=layout.kind===\"periodic-mosaic\"?layout.repeatWidthSites*layout.repeatHeightSites:0;\n const buffers=new Set<ArrayBufferLike>();\n for(const [a,type,length] of [[raw.codes,Uint16Array,plan.pixelCount],[raw.blackLevels,Uint16Array,plan.pixelCount],[raw.digitalSaturationCodes,Uint16Array,plan.pixelCount],\n [raw.saturationFlags,Uint8Array,plan.pixelCount],[raw.effectiveSaturationCodes,Uint16Array,phaseCount]] as const){\n if(!(a instanceof type)||!(a.buffer instanceof ArrayBuffer)||a.length!==length||a.buffer.byteLength!==a.byteLength||buffers.has(a.buffer))throw new InvalidConfigurationError(\"Packed RAW storage must be exact owned native arrays.\");\n buffers.add(a.buffer);\n }\n return plan;\n}\n/** Takes sole ownership: detaches without copying when the runtime supports ArrayBuffer transfer, otherwise copies. */\nfunction own<T extends Uint8Array<ArrayBuffer>|Uint16Array<ArrayBuffer>>(array: T, make: (buffer: ArrayBuffer)=>T): T {\n const buffer=array.buffer as ArrayBuffer&{transfer?:()=>ArrayBuffer};\n return typeof buffer.transfer===\"function\"?make(buffer.transfer()):make(buffer.slice(0));\n}\n/** Takes the validated packed RAW's arrays (without copying where supported). Not exported from the package. */\nexport function takeNativeRawOwnership(given: NativeRawOutput, plan: NativeRawOutput[\"plan\"]): NativeRawOutput {\n return {plan,codes:own(given.codes as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),blackLevels:own(given.blackLevels as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),\n digitalSaturationCodes:own(given.digitalSaturationCodes as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),saturationFlags:own(given.saturationFlags as Uint8Array<ArrayBuffer>,b=>new Uint8Array(b)),\n effectiveSaturationCodes:given.effectiveSaturationCodes.slice()};\n}\n/** Validated development metadata (internal; shared with the image-kernel accelerator). Not exported from the package. */\nexport interface PreparedDevelopment {\n plan: NativeRawOutput[\"plan\"]; phases: RawFrameReconstructionPhaseProfile[]; color: ExportSensorColorProfile; profile: SdrRenderingProfile;\n whiteBalance: NativeRawDevelopmentInput[\"whiteBalance\"]; highlightMode: RawHighlightMode; development: SensorColorDevelopment;\n crop: {x:number;y:number;width:number;height:number}; raster: {pixelWidth:number;pixelHeight:number};\n border: RawReconstructionBorderHandling; mirror: {nativeHeight:number;reach:number}|undefined;\n /** Development exposure gain 2^exposureCompensationStops; exactly 1 without a push. */\n exposureGain: number;\n}\n/**\n * Synchronous checks of metadata, kernel halo (the neighbourhood each pixel reads) and CFA, shared by the\n * task, the reference and the accelerator. No pixel loop. Not exported from the package.\n */\nexport function prepareNativeRawDevelopment(input: NativeRawDevelopmentInput): PreparedDevelopment {\n const r=requireAllowlistedRecord(input,[\"raw\",\"phaseProfiles\",\"colorProfile\",\"whiteBalance\",\"rendering\",\"highlightMode\",\"borderHandling\",\"exposureCompensationStops\",\"maximumRetainedPayloadBytes\"],\"Invalid native RAW development input.\");\n const plan=validatePackedNativeRaw(input.raw),g=plan.exposure.resolvedGeometry,native=plan.exposure.geometry.nativeRaster;\n const phases=freezeOwnedData(parseRawReconstructionPhaseProfiles(r.phaseProfiles,plan.frame.modeId,plan.frame.colorSamplingProfile));\n const color=freezeOwnedData(parseExportSensorColorProfile(r.colorProfile)),profile=freezeOwnedData(parseSdrRenderingProfile(r.rendering));\n const crop=g.output.cropRect,raster=g.output.raster,active=g.activeCapture.nativeRect,intent=plan.exposure.whiteBalanceIntent;\n const highlightMode=r.highlightMode===undefined?\"clip\":r.highlightMode;\n if(highlightMode!==\"clip\"&&highlightMode!==\"reconstruct\")throw new InvalidConfigurationError(\"Unsupported RAW highlight mode.\");\n const border=r.borderHandling===undefined?\"reject\":r.borderHandling;\n if(border!==\"reject\"&&border!==\"mirror\")throw new InvalidConfigurationError(\"Unsupported RAW border handling.\");\n const stops=r.exposureCompensationStops===undefined?0:r.exposureCompensationStops;\n if(typeof stops!==\"number\"||!Number.isFinite(stops)||stops<NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS.minimum||stops>NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS.maximum)\n throw new InvalidConfigurationError(\"RAW development exposureCompensationStops must be a finite number from -2 to +5.\");\n const exposureGain=stops===0?1:2**stops;\n if(color.colorSamplingProfileId!==plan.frame.colorSamplingProfile.profileId||phases.some(p=>canonical(p.profile.kernels.map(k=>k.outputChannelId))!==canonical(color.channelIds))||\n (r.whiteBalance!==\"not-required\"&&r.whiteBalance!==\"apply-resolved-sensor-gains\")||(intent!==null)!==(r.whiteBalance===\"apply-resolved-sensor-gains\")||\n raster.pixelWidth!==crop.width||raster.pixelHeight!==crop.height)throw new InvalidConfigurationError(\"Development requires bound sensor RGB, explicit one-time WB and 1:1 output crop.\");\n const bytes=plan.outputBytes+raster.pixelWidth*raster.pixelHeight*3*profile.bitDepth/8;\n if(typeof r.maximumRetainedPayloadBytes!==\"number\"||!Number.isSafeInteger(r.maximumRetainedPayloadBytes)||r.maximumRetainedPayloadBytes<bytes)throw new InvalidConfigurationError(\"Development exceeds retained output budget.\");\n const gains=intent?[intent.channelGains.red,intent.channelGains.green,intent.channelGains.blue]:null;\n const development=prepareSensorColorDevelopment(color.normalizedCameraChannelsToXyz,gains,highlightMode),layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Development requires periodic CFA.\");\n const nativeCorners=[{x:crop.x+.5,y:crop.y+.5},{x:crop.x+crop.width-.5,y:crop.y+crop.height-.5}].map(point=>{\n const p=transformOrientedRasterPointToNative({point,nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});return {x:Math.floor(p.x)+active.x,y:Math.floor(p.y)+active.y};\n });\n const minX=Math.min(...nativeCorners.map(p=>p.x)),maxX=Math.max(...nativeCorners.map(p=>p.x)),minY=Math.min(...nativeCorners.map(p=>p.y)),maxY=Math.max(...nativeCorners.map(p=>p.y));\n for(const phase of phases){\n const firstX=minX+(phase.phaseX-minX%layout.repeatWidthSites+layout.repeatWidthSites)%layout.repeatWidthSites;\n const firstY=minY+(phase.phaseY-minY%layout.repeatHeightSites+layout.repeatHeightSites)%layout.repeatHeightSites;\n if(firstX>maxX||firstY>maxY)continue;\n const lastX=maxX-(maxX-phase.phaseX+layout.repeatWidthSites)%layout.repeatWidthSites,lastY=maxY-(maxY-phase.phaseY+layout.repeatHeightSites)%layout.repeatHeightSites;\n for(const kernel of phase.profile.kernels)for(const c of kernel.contributions){\n if(firstX+c.offsetX<0||firstY+c.offsetY<0||lastX+c.offsetX>=native.pixelWidth||lastY+c.offsetY>=native.pixelHeight){\n if(border===\"reject\")throw new InvalidConfigurationError(\"Reconstruction halo leaves native RAW; no padding or renormalization.\");\n // Mirror: check the virtual site from the repeating pattern; validateMirrorBorderCfaConsistency proves mirrored reads agree with it.\n const vx=phase.phaseX+c.offsetX,vy=phase.phaseY+c.offsetY;\n if(layout.siteChannelIds[((vy%layout.repeatHeightSites)+layout.repeatHeightSites)%layout.repeatHeightSites*layout.repeatWidthSites+((vx%layout.repeatWidthSites)+layout.repeatWidthSites)%layout.repeatWidthSites]!==c.sourceChannelId)\n throw new InvalidConfigurationError(\"Reconstruction source channel disagrees with absolute CFA phase.\");\n continue;\n }\n const channel=resolveColorSamplingSite({profile:plan.frame.colorSamplingProfile,site:{x:firstX+c.offsetX,y:firstY+c.offsetY}}).mapping.channelId;\n if(channel!==c.sourceChannelId)throw new InvalidConfigurationError(\"Reconstruction source channel disagrees with absolute CFA phase.\");\n }\n }\n let mirror:PreparedDevelopment[\"mirror\"];\n if(border===\"mirror\"){\n const reach=rawReconstructionKernelReach(phases);\n validateMirrorBorderCfaConsistency(layout,native.pixelWidth,native.pixelHeight,reach);\n mirror={nativeHeight:native.pixelHeight,reach};\n }\n return {plan,phases,color,profile,whiteBalance:r.whiteBalance,highlightMode,development,crop,raster,border,mirror,exposureGain};\n}\n/** Checks the numbers in rows [y0,y1). Values below black stay signed; each white-minus-black span is positive. Not exported from the package. */\nexport function checkNativeRawIntegrity(raw: NativeRawOutput, nativeWidth: number, repeatWidth: number, repeatHeight: number, y0: number, y1: number): void {\n const codes=raw.codes,blacks=raw.blackLevels,digital=raw.digitalSaturationCodes,flags=raw.saturationFlags,white=raw.effectiveSaturationCodes;\n for(let y=y0;y<y1;y++){\n const row=(y%repeatHeight)*repeatWidth;\n for(let x=0,i=y*nativeWidth;x<nativeWidth;x++,i++){\n const d=digital[i]!,w=white[row+x%repeatWidth]!,b=blacks[i]!;\n if(b>=w||w>d||codes[i]!>d||flags[i]!>7)throw new InvalidConfigurationError(\"Invalid packed RAW code span, white level or saturation flags.\");\n }\n }\n}\nfunction source(raw: NativeRawOutput, plan: NativeRawOutput[\"plan\"], exposureGain: number): RawDevelopmentSource {\n const layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Development requires periodic CFA.\");\n return {nativeWidth:plan.exposure.geometry.nativeRaster.pixelWidth,repeatWidth:layout.repeatWidthSites,repeatHeight:layout.repeatHeightSites,\n codes:raw.codes,blackLevels:raw.blackLevels,saturationFlags:raw.saturationFlags,whiteByPhase:raw.effectiveSaturationCodes,...(exposureGain===1?{}:{exposureGain})};\n}\nfunction emptyDiagnostics(): SdrRenderingResult[\"diagnostics\"] {\n return {renderingNegativeSampleCount:0,renderingAboveReferenceSampleCount:0,toneChangedSampleCount:0,gamutClippedLowSampleCount:0,gamutClippedHighSampleCount:0,captureSaturation:\"consumed-in-raw-development\"};\n}\nfunction highlightOf(mode: RawHighlightMode, counts: RawDevelopmentCounts): RawHighlightDiagnostics {\n return {mode,saturatedPixelCount:counts.saturatedPixelCount,whiteBalanceClippedSampleCount:counts.whiteBalanceClippedSampleCount,reconstructedPixelCount:counts.reconstructedPixelCount};\n}\n/**\n * Internal, slow reference development using one object per step (not exported from the package). It is\n * kept to prove that the fast typed kernel gives byte-identical output.\n *\n * For each pixel it maps orientation with `transformOrientedRasterPointToNative`, gathers each channel\n * with `calculateRawReconstructionChannel`, develops with the shared colour operator, and renders\n * 256-pixel rows with the reference `calculateSdrRendering`. It does not take ownership of the RAW.\n */\nexport function developNativeRawReference(input: NativeRawDevelopmentInput): {integerSamples:number[];diagnostics:SdrRenderingResult[\"diagnostics\"];highlight:RawHighlightDiagnostics} {\n const v=prepareNativeRawDevelopment(input),plan=v.plan,g=plan.exposure.resolvedGeometry,active=g.activeCapture.nativeRect,src=source(input.raw,plan,v.exposureGain);\n checkNativeRawIntegrity(input.raw,src.nativeWidth,src.repeatWidth,src.repeatHeight,0,plan.exposure.geometry.nativeRaster.pixelHeight);\n const counts=createRawDevelopmentCounts(),diagnostics=emptyDiagnostics(),out:number[]=[];\n for(let y=0;y<v.raster.pixelHeight;y++)for(let x=0;x<v.raster.pixelWidth;x+=TILE_WIDTH){\n const width=Math.min(TILE_WIDTH,v.raster.pixelWidth-x),rgb:number[]=[];\n for(let j=0;j<width;j++){\n const q=transformOrientedRasterPointToNative({point:{x:v.crop.x+x+j+.5,y:v.crop.y+y+.5},nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});\n const point={x:Math.floor(q.x)+active.x,y:Math.floor(q.y)+active.y};\n const phase=v.phases[(point.y%src.repeatHeight)*src.repeatWidth+point.x%src.repeatWidth]!;\n let saturated=false;\n const values=phase.profile.kernels.map(kernel=>calculateRawReconstructionChannel(kernel,point,(sx,sy)=>{\n if(rawSiteSaturated(src,sx,sy))saturated=true;return normalizedRawSite(src,sx,sy);\n },v.mirror===undefined?undefined:{width:src.nativeWidth,height:v.mirror.nativeHeight}).linearBlackSubtractedNormalizedValue);\n if(saturated)counts.saturatedPixelCount++;\n const developed=[0,0,0];v.development.developInto(values[0]!,values[1]!,values[2]!,developed,0,counts);rgb.push(...developed);\n }\n const rendered=calculateSdrRendering({sourceImageStateId:plan.frame.frameId+\":developed\",inputImageState:\"color-transformed-linear-rgb\",inputColorSpace:\"linear-srgb-d65\",whiteBalanceHandling:plan.exposure.whiteBalanceIntent?\"already-applied-upstream\":\"not-required\",pixelWidth:width,pixelHeight:1,referenceWhiteValue:1,samples:rgb,profile:v.profile}).value;\n out.push(...rendered.integerSamples);\n for(const key of [\"renderingNegativeSampleCount\",\"renderingAboveReferenceSampleCount\",\"toneChangedSampleCount\",\"gamutClippedLowSampleCount\",\"gamutClippedHighSampleCount\"] as const)diagnostics[key]+=rendered.diagnostics[key];\n }\n return {integerSamples:out,diagnostics,highlight:highlightOf(v.highlightMode,counts)};\n}\nfunction sdrOutputEncoding(maximum: number): SdrRenderingResult[\"outputEncoding\"] {\n return {imageState:\"output-referred-sdr\",colorSpace:\"srgb\",primariesXy:{red:[.64,.33],green:[.30,.60],blue:[.15,.06]},whitePointXy:[.3127,.3290],referenceWhiteLuminanceCdM2:80,codeMinimum:0,codeMaximum:maximum};\n}\n/**\n * Creates a native RAW development task.\n *\n * It checks that every CFA phase has a reconstruction kernel and that every kernel neighbourhood is\n * available, takes ownership of the packed RAW (without copying where supported), and renders 256-pixel\n * output tiles with the fast typed kernel. Development scales each site to its CFA phase's effective white\n * level, clips flagged or white-level sites before white balance, and applies the selected highlight mode\n * (see `prepareSensorColorDevelopment`).\n *\n * The RAW numbers are checked in bounded chunks at the start of `run()`, with host yields, so creating the\n * task costs only as much as reading the metadata. The task yields to the host at chunk and tile boundaries\n * once about 8 ms of work has passed since the last yield, and after the final tile. Yield timing never\n * changes the output.\n *\n * `provider` is `{ yieldControl, onProgress? }`, the same shape as the other native task providers. A bare\n * yield function is still accepted in 2.x but is deprecated.\n *\n * The tile width used at capture is kept when rebuilding the exact packed plan. That width changes neither\n * CFA or noise-seed coordinates nor the developed pixels, and says nothing about transport or what a device\n * can handle.\n */\nexport function createNativeRawDevelopmentTask(input: NativeRawDevelopmentInput,\n provider: NativeRawDevelopmentProvider | ((signal:AbortSignal)=>Promise<void>)): NativeRawDevelopmentTask {\n return createNativeRawDevelopmentTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes output. Not exported from the package. */\nexport function createNativeRawDevelopmentTaskWithCadence(input: NativeRawDevelopmentInput,\n provider: NativeRawDevelopmentProvider | ((signal:AbortSignal)=>Promise<void>),cadence: HostYieldCadence): NativeRawDevelopmentTask {\n const hooks=typeof provider===\"function\"?{yieldControl:provider}:provider;\n if(!hooks||typeof hooks.yieldControl!==\"function\"||(hooks.onProgress!==undefined&&typeof hooks.onProgress!==\"function\"))throw new InvalidConfigurationError(\"Development requires a host event-loop yield.\");\n const yieldControl=hooks.yieldControl.bind(hooks),onProgress=hooks.onProgress?.bind(hooks);\n const v=prepareNativeRawDevelopment(input),plan=v.plan,g=plan.exposure.resolvedGeometry,active=g.activeCapture.nativeRect,raster=v.raster,crop=v.crop;\n const nativeHeight=plan.exposure.geometry.nativeRaster.pixelHeight;\n // Ownership is transferred only after every synchronous check has passed.\n const raw=takeNativeRawOwnership(input.raw,plan);\n const src=source(raw,plan,v.exposureGain),tilesPerRow=Math.ceil(raster.pixelWidth/TILE_WIDTH),totalTileCount=tilesPerRow*raster.pixelHeight;\n const abort=new AbortController();let state:NativeRawTaskState=\"ready\",output:NativeRawDevelopmentOutput|null=null,codes:Uint8Array|Uint16Array|null=null,completed=0;\n function release(): void {raw.codes.fill(0);raw.blackLevels.fill(0);raw.digitalSaturationCodes.fill(0);raw.saturationFlags.fill(0);raw.effectiveSaturationCodes.fill(0);codes?.fill(0);codes=null;output=null;}\n function check(): void {if(abort.signal.aborted)throw new InvalidConfigurationError(\"Native RAW development aborted.\");}\n /** Native coordinates of oriented output pixel (x, y) and the step to (x+1, y), both integer. */\n function rowMapping(x: number, y: number, width: number): {nx:number;ny:number;dx:number;dy:number} {\n const at=(j:number):{x:number;y:number}=>{const q=transformOrientedRasterPointToNative({point:{x:crop.x+x+j+.5,y:crop.y+y+.5},nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});return {x:Math.floor(q.x)+active.x,y:Math.floor(q.y)+active.y};};\n const first=at(0),second=width>1?at(1):first,dx=second.x-first.x,dy=second.y-first.y,last=at(width-1);\n if(Math.abs(dx)+Math.abs(dy)!==(width>1?1:0)||last.x!==first.x+dx*(width-1)||last.y!==first.y+dy*(width-1))throw new InvalidConfigurationError(\"Development orientation mapping is not a unit native step.\");\n return {nx:first.x,ny:first.y,dx,dy};\n }\n return {get state():NativeRawTaskState{return state;},get completedTileCount():number{return completed;},totalTileCount,\n async run():Promise<void>{\n if(state!==\"ready\")throw new InvalidConfigurationError(\"Development task is single-use.\");state=\"running\";\n try{\n const gate=createHostYieldGate(cadence);\n const rowsPerChunk=Math.max(1,Math.floor(INTEGRITY_CHUNK_SITES/src.nativeWidth));\n for(let y=0;y<nativeHeight;y+=rowsPerChunk){\n check();checkNativeRawIntegrity(raw,src.nativeWidth,src.repeatWidth,src.repeatHeight,y,Math.min(nativeHeight,y+rowsPerChunk));\n if(gate.due()){await yieldControl(abort.signal);check();gate.restart();}\n }\n codes=v.profile.bitDepth===8?new Uint8Array(raster.pixelWidth*raster.pixelHeight*3):new Uint16Array(raster.pixelWidth*raster.pixelHeight*3);\n const diagnostics=emptyDiagnostics(),developer=createRawPixelDeveloper(src,v.phases,v.development,v.mirror),tone=prepareSdrPixelTone(v.profile);\n const scale=2**v.profile.renderingExposureEv,maximum=2**v.profile.bitDepth-1,rgb=new Float64Array(TILE_WIDTH*3),scratch=new Float64Array(3);\n if(!Number.isFinite(scale)||scale<=0)throw new InvalidConfigurationError(\"Rendering scale is unrepresentable.\");\n for(let y=0;y<raster.pixelHeight;y++)for(let x=0;x<raster.pixelWidth;x+=TILE_WIDTH){\n check();const width=Math.min(TILE_WIDTH,raster.pixelWidth-x),map=rowMapping(x,y,width);\n const counts:SdrPixelCounts={negative:0,above:0,changed:0,low:0,high:0,outOfGamut:false};\n developer.developRun(map.nx,map.ny,map.dx,map.dy,width,rgb);\n renderSdrRunInto(rgb,0,width,v.profile,tone,scale,maximum,codes,(y*raster.pixelWidth+x)*3,scratch,counts);\n // Same 256-pixel granularity as the reference rows, so exposure errors come before gamut rejection.\n if(counts.outOfGamut)throw new InvalidConfigurationError(\"Tone output exceeds the declared SDR gamut range.\");\n diagnostics.renderingNegativeSampleCount+=counts.negative;diagnostics.renderingAboveReferenceSampleCount+=counts.above;diagnostics.toneChangedSampleCount+=counts.changed;\n diagnostics.gamutClippedLowSampleCount+=counts.low;diagnostics.gamutClippedHighSampleCount+=counts.high;\n completed++;onProgress?.({completedTileCount:completed,totalTileCount});\n if(gate.due()||(y===raster.pixelHeight-1&&x+TILE_WIDTH>=raster.pixelWidth)){await yieldControl(abort.signal);check();gate.restart();}\n }\n output={raw,phaseProfiles:v.phases,colorProfile:v.color,whiteBalance:v.whiteBalance,width:raster.pixelWidth,height:raster.pixelHeight,integerSamples:codes,diagnostics,\n highlight:highlightOf(v.highlightMode,developer.counts),borderHandling:v.border,rendering:v.profile,displayAdaptation:{kind:\"external-platform\",applied:false,displayCapabilities:\"unknown\"},\n outputEncoding:sdrOutputEncoding(maximum),imageDataPairing:\"derived-from-exact-packed-native-raw\",producerOriginVerified:false};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():NativeRawDevelopmentOutput{if(state!==\"completed\"||!output)throw new InvalidConfigurationError(\"Development output unavailable.\");const value=output;output=null;codes=null;state=\"transferred\";return value;}\n };\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
  }