@photivra/engine 2.1.0 → 2.2.1

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 (70) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/CITATION.cff +1 -1
  3. package/README.md +6 -6
  4. package/SECURITY.md +1 -1
  5. package/dist/capture/export-jpeg.js +7 -1
  6. package/dist/capture/export-jpeg.js.map +1 -1
  7. package/dist/capture/native-environment-lean.js +5 -2
  8. package/dist/capture/native-environment-lean.js.map +1 -1
  9. package/dist/capture/native-environment-raw.js +2 -2
  10. package/dist/capture/native-environment-raw.js.map +1 -1
  11. package/dist/capture/native-raw-development.js +1 -1
  12. package/dist/capture/native-raw-development.js.map +1 -1
  13. package/dist/capture/native-raw.d.ts +16 -0
  14. package/dist/capture/native-raw.js +16 -3
  15. package/dist/capture/native-raw.js.map +1 -1
  16. package/dist/capture/packed-sensor-raw.d.ts +7 -0
  17. package/dist/capture/packed-sensor-raw.js +6 -2
  18. package/dist/capture/packed-sensor-raw.js.map +1 -1
  19. package/dist/core/pixel-limits.d.ts +14 -0
  20. package/dist/core/pixel-limits.js +40 -0
  21. package/dist/core/pixel-limits.js.map +1 -0
  22. package/dist/core/version.d.ts +1 -1
  23. package/dist/core/version.js +1 -1
  24. package/dist/core/version.js.map +1 -1
  25. package/dist/facade/chart-radiance-batch.d.ts +7 -0
  26. package/dist/facade/chart-radiance-batch.js +7 -3
  27. package/dist/facade/chart-radiance-batch.js.map +1 -1
  28. package/dist/facade/simulate-capture.d.ts +8 -1
  29. package/dist/facade/simulate-capture.js +69 -18
  30. package/dist/facade/simulate-capture.js.map +1 -1
  31. package/dist/index.d.ts +2 -1
  32. package/dist/index.js +2 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/motion/temporal-exposure-sum.d.ts +7 -0
  35. package/dist/motion/temporal-exposure-sum.js +6 -2
  36. package/dist/motion/temporal-exposure-sum.js.map +1 -1
  37. package/dist/optics/irradiance-convolution.d.ts +7 -0
  38. package/dist/optics/irradiance-convolution.js +6 -2
  39. package/dist/optics/irradiance-convolution.js.map +1 -1
  40. package/dist/optics/lens-psf-kernels.d.ts +3 -1
  41. package/dist/optics/lens-psf-kernels.js +7 -2
  42. package/dist/optics/lens-psf-kernels.js.map +1 -1
  43. package/dist/output/native-capture-sdr.d.ts +7 -0
  44. package/dist/output/native-capture-sdr.js +6 -3
  45. package/dist/output/native-capture-sdr.js.map +1 -1
  46. package/dist/output/png-encoder.d.ts +10 -1
  47. package/dist/output/png-encoder.js +10 -4
  48. package/dist/output/png-encoder.js.map +1 -1
  49. package/dist/output/print-jpeg.d.ts +18 -0
  50. package/dist/output/print-jpeg.js +15 -4
  51. package/dist/output/print-jpeg.js.map +1 -1
  52. package/dist/sensor/sampling-aperture.d.ts +15 -0
  53. package/dist/sensor/sampling-aperture.js +31 -10
  54. package/dist/sensor/sampling-aperture.js.map +1 -1
  55. package/docs/API_REFERENCE.md +11 -1
  56. package/docs/QUICK_START.md +112 -4
  57. package/docs/USAGE.md +3 -1
  58. package/docs/api/capture-native-raw.md +11 -2
  59. package/docs/api/capture-packed-sensor-raw.md +7 -1
  60. package/docs/api/core-pixel-limits.md +19 -0
  61. package/docs/api/core-version.md +1 -1
  62. package/docs/api/exports.json +17 -2
  63. package/docs/api/facade-chart-radiance-batch.md +8 -2
  64. package/docs/api/facade-simulate-capture.md +8 -1
  65. package/docs/api/motion-temporal-exposure-sum.md +7 -1
  66. package/docs/api/optics-irradiance-convolution.md +7 -1
  67. package/docs/api/output-native-capture-sdr.md +7 -2
  68. package/docs/api/output-png-encoder.md +8 -1
  69. package/docs/api/output-print-jpeg.md +17 -0
  70. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
1
  export declare const IRRADIANCE_CONVOLUTION_SCHEMA_VERSION: "0.1.0";
2
+ /** `maximumPixels` is the default grid limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */
2
3
  export declare const IRRADIANCE_CONVOLUTION_LIMITS: Readonly<{
3
4
  maximumPixels: 24000000;
5
+ ceilingPixels: 134217728;
4
6
  maximumDimension: 16384;
5
7
  maximumKernelRadius: 32;
6
8
  maximumPatchCount: 4096;
@@ -27,6 +29,11 @@ export interface IrradianceConvolutionInput {
27
29
  */
28
30
  kernels: Float32Array | Float64Array;
29
31
  boundary: "zero-outside-grid";
32
+ /**
33
+ * Optional opt-in grid limit for large images: an integer from 1 to `IRRADIANCE_CONVOLUTION_LIMITS.ceilingPixels`.
34
+ * Default `IRRADIANCE_CONVOLUTION_LIMITS.maximumPixels` (24 000 000). It does not change the result.
35
+ */
36
+ maximumPixels?: number;
30
37
  }
31
38
  /** Validated, immutable geometry of a convolution request. Sample arrays are borrowed, not copied. */
32
39
  export interface IrradianceConvolutionPlan {
@@ -28,9 +28,12 @@
28
28
  */
29
29
  import { InvalidConfigurationError } from "../core/configuration-error.js";
30
30
  import { requireAllowlistedRecord } from "../core/record-validation.js";
31
+ import { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit } from "../core/pixel-limits.js";
31
32
  export const IRRADIANCE_CONVOLUTION_SCHEMA_VERSION = "0.1.0";
33
+ /** `maximumPixels` is the default grid limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */
32
34
  export const IRRADIANCE_CONVOLUTION_LIMITS = Object.freeze({
33
35
  maximumPixels: 24_000_000,
36
+ ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS,
34
37
  maximumDimension: 16_384,
35
38
  maximumKernelRadius: 32,
36
39
  maximumPatchCount: 4_096,
@@ -49,13 +52,14 @@ function positiveInteger(value, maximum) {
49
52
  /** Validates the request and returns its plan. Every sample and weight is checked once. */
50
53
  export function calculateIrradianceConvolutionPlan(input) {
51
54
  const r = requireAllowlistedRecord(input, ["schemaVersion", "width", "height", "samples", "kernelRadius", "patchWidth",
52
- "patchHeight", "kernels", "boundary"], "Invalid irradiance convolution input.");
55
+ "patchHeight", "kernels", "boundary", "maximumPixels"], "Invalid irradiance convolution input.");
53
56
  const L = IRRADIANCE_CONVOLUTION_LIMITS;
54
57
  if (r.schemaVersion !== IRRADIANCE_CONVOLUTION_SCHEMA_VERSION || r.boundary !== "zero-outside-grid") {
55
58
  throw new InvalidConfigurationError("Unsupported irradiance convolution schema or boundary.");
56
59
  }
57
60
  const width = positiveInteger(r.width, L.maximumDimension), height = positiveInteger(r.height, L.maximumDimension);
58
- if (width * height > L.maximumPixels)
61
+ const maximumPixels = resolveRaisedLimit(r.maximumPixels, L.maximumPixels, L.ceilingPixels, "Irradiance convolution maximumPixels must be an integer from 1 to " + L.ceilingPixels + ".");
62
+ if (width * height > maximumPixels)
59
63
  throw new InvalidConfigurationError("Irradiance convolution grid exceeds the pixel limit.");
60
64
  const radius = r.kernelRadius;
61
65
  if (typeof radius !== "number" || !Number.isSafeInteger(radius) || radius < 0 || radius > L.maximumKernelRadius) {
@@ -1 +1 @@
1
- {"version":3,"file":"irradiance-convolution.js","sourceRoot":"","sources":["../../src/optics/irradiance-convolution.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAExE,MAAM,CAAC,MAAM,qCAAqC,GAAG,OAAgB,CAAC;AACtE,MAAM,CAAC,MAAM,6BAA6B,GAAG,MAAM,CAAC,MAAM,CAAC;IACzD,aAAa,EAAE,UAAU;IACzB,gBAAgB,EAAE,MAAM;IACxB,mBAAmB,EAAE,EAAE;IACvB,iBAAiB,EAAE,KAAK;IACxB,oBAAoB,EAAE,SAAS;IAC/B,wGAAwG;IACxG,gBAAgB,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;IAC9B,sFAAsF;IACtF,sBAAsB,EAAE,CAAC,IAAI,GAAG;CACjC,CAAC,CAAC;AAqCH,SAAS,eAAe,CAAC,KAAc,EAAE,OAAe;IACtD,I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AC,CAAC,CAAC;oBACrF,GAAG,IAAI,OAAO,CAAC,SAAS,GAAG,EAAE,CAAE,GAAG,OAAO,CAAC,KAAK,GAAG,QAAQ,GAAG,SAAS,GAAG,CAAC,CAAE,CAAC;gBAC/E,CAAC;YACH,CAAC;YACD,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;QACrC,CAAC;IACH,CAAC;AACH,CAAC;AAED,yGAAyG;AACzG,MAAM,UAAU,8BAA8B,CAAC,KAAiC;IAC9E,MAAM,IAAI,GAAG,kCAAkC,CAAC,KAAK,CAAC,CAAC;IACvD,MAAM,MAAM,GAAG,IAAI,YAAY,CAAC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1D,sBAAsB,CAAC,IAAI,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnF,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Blurs a sampled image-plane quantity with caller-supplied PSF (point-spread function) kernels, one\n * kernel per patch of the image. The quantity must be linear and additive (for example irradiance).\n * Each patch is treated as shift-invariant (\"isoplanatic\"): the same PSF applies everywhere inside it.\n * The PSFs are incoherent intensity PSFs.\n *\n * This is the CPU float64 reference for the optics-as-convolution step (#277). The `webgpu-f32`\n * path runs the same equation; see docs/WEBGPU.md.\n *\n * Equation (indexed by source site; an energy-conserving scatter written as a gather):\n * out(x, y) = Σ_{v=-r..r} Σ_{u=-r..r} in(x − u, y − v) · K_{p(x − u, y − v)}(u, v)\n * where `p(s)` is the patch containing the **source** site and `K_p(u, v)` is the fraction of the source\n * site's quantity that lands at displacement (+u right, +v down), in grid sites.\n *\n * Incoherent imaging is a linear sum of intensity PSFs: the output intensity is the input intensity\n * convolved with the intensity PSF (MIT OpenCourseWare 2.71 Optics, Spring 2009, lecture 22, free).\n * A PSF that varies across the field is approximated as constant inside each patch, as in methods\n * that divide the image into isoplanatic subsections (van de Ketterij et al., arXiv:2011.01738,\n * sec. 1, free). Also see: Goodman, Introduction to Fourier Optics, 4th ed., 2017, §6.1. Camera\n * simulators such as ISETCam use the same piecewise shift-invariant method\n * (Farrell et al., Proc. SPIE 8299, 2012). The caller chooses the patch size and kernels, and so\n * owns the patch approximation.\n *\n * Edges: the grid holds every source. Sources outside the grid are not represented. Anything\n * scattered outside the grid is lost; compare `inputSum` with `outputSum` to see how much. There is no\n * padding, reflection or renormalization.\n */\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\n\nexport const IRRADIANCE_CONVOLUTION_SCHEMA_VERSION = \"0.1.0\" as const;\nexport const IRRADIANCE_CONVOLUTION_LIMITS = Object.freeze({\n maximumPixels: 24_000_000,\n maximumDimension: 16_384,\n maximumKernelRadius: 32,\n maximumPatchCount: 4_096,\n maximumKernelWeights: 4_194_304,\n /** A kernel may lose energy (vignetting, transmission) but may not create it, beyond rounding slack. */\n maximumKernelSum: 1 + 2 ** -20,\n /** Inputs larger than this are rejected so that float32 execution cannot overflow. */\n maximumSampleMagnitude: 2 ** 100\n});\n\nexport interface IrradianceConvolutionInput {\n schemaVersion: typeof IRRADIANCE_CONVOLUTION_SCHEMA_VERSION;\n width: number;\n height: number;\n /** Row-major samples. Finite, non-negative, linear and additive (for example irradiance, or expected photons per site). */\n samples: Float32Array | Float64Array;\n /** Kernel half-width in grid sites. Each kernel is (2r+1)×(2r+1). */\n kernelRadius: number;\n /** Patch size in grid sites. The last row and column of patches may be partial. */\n patchWidth: number;\n patchHeight: number;\n /**\n * Finite non-negative weights, `[patchRow][patchColumn][v + r][u + r]`, one kernel per patch in\n * row-major patch order. Each kernel sums to at most 1 (+2^-20 rounding slack).\n */\n kernels: Float32Array | Float64Array;\n boundary: \"zero-outside-grid\";\n}\n\n/** Validated, immutable geometry of a convolution request. Sample arrays are borrowed, not copied. */\nexport interface IrradianceConvolutionPlan {\n width: number;\n height: number;\n kernelRadius: number;\n kernelSize: number;\n tapCount: number;\n patchWidth: number;\n patchHeight: number;\n patchColumns: number;\n patchRows: number;\n /** Largest kernel sum and largest input magnitude. The float32 error bound uses them. */\n maximumKernelSum: number;\n maximumSampleMagnitude: number;\n}\n\nfunction positiveInteger(value: unknown, maximum: number): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0 || value > maximum) {\n throw new InvalidConfigurationError(\"Invalid irradiance convolution geometry.\");\n }\n return value;\n}\n\n/** Validates the request and returns its plan. Every sample and weight is checked once. */\nexport function calculateIrradianceConvolutionPlan(input: IrradianceConvolutionInput): IrradianceConvolutionPlan {\n const r = requireAllowlistedRecord(input, [\"schemaVersion\", \"width\", \"height\", \"samples\", \"kernelRadius\", \"patchWidth\",\n \"patchHeight\", \"kernels\", \"boundary\"], \"Invalid irradiance convolution input.\");\n const L = IRRADIANCE_CONVOLUTION_LIMITS;\n if (r.schemaVersion !== IRRADIANCE_CONVOLUTION_SCHEMA_VERSION || r.boundary !== \"zero-outside-grid\") {\n throw new InvalidConfigurationError(\"Unsupported irradiance convolution schema or boundary.\");\n }\n const width = positiveInteger(r.width, L.maximumDimension), height = positiveInteger(r.height, L.maximumDimension);\n if (width * height > L.maximumPixels) throw new InvalidConfigurationError(\"Irradiance convolution grid exceeds the pixel limit.\");\n const radius = r.kernelRadius;\n if (typeof radius !== \"number\" || !Number.isSafeInteger(radius) || radius < 0 || radius > L.maximumKernelRadius) {\n throw new InvalidConfigurationError(\"Invalid irradiance convolution kernel radius.\");\n }\n const patchWidth = positiveInteger(r.patchWidth, width), patchHeight = positiveInteger(r.patchHeight, height);\n const patchColumns = Math.ceil(width / patchWidth), patchRows = Math.ceil(height / patchHeight);\n const kernelSize = 2 * radius + 1, tapCount = kernelSize * kernelSize, patchCount = patchColumns * patchRows;\n if (patchCount > L.maximumPatchCount || patchCount * tapCount > L.maximumKernelWeights) {\n throw new InvalidConfigurationError(\"Irradiance convolution kernels exceed the declared limits.\");\n }\n const samples = r.samples, kernels = r.kernels;\n if (!(samples instanceof Float32Array || samples instanceof Float64Array) || samples.length !== width * height ||\n !(kernels instanceof Float32Array || kernels instanceof Float64Array) || kernels.length !== patchCount * tapCount) {\n throw new InvalidConfigurationError(\"Irradiance convolution arrays do not match the declared geometry.\");\n }\n let maximumSampleMagnitude = 0;\n for (let i = 0; i < samples.length; i++) {\n const v = samples[i]!;\n // Negated comparison also rejects NaN.\n if (!(v >= 0 && v <= L.maximumSampleMagnitude)) {\n throw new InvalidConfigurationError(\"Irradiance samples must be finite, non-negative and within the declared magnitude.\");\n }\n if (v > maximumSampleMagnitude) maximumSampleMagnitude = v;\n }\n let maximumKernelSum = 0;\n for (let p = 0; p < patchCount; p++) {\n let sum = 0;\n for (let t = p * tapCount, end = t + tapCount; t < end; t++) {\n const w = kernels[t]!;\n if (!(w >= 0 && w <= 1)) throw new InvalidConfigurationError(\"PSF kernel weights must be finite and within [0, 1].\");\n sum += w;\n }\n if (sum > L.maximumKernelSum) throw new InvalidConfigurationError(\"A PSF kernel may not create energy (sum exceeds 1).\");\n if (sum > maximumKernelSum) maximumKernelSum = sum;\n }\n return Object.freeze({ width, height, kernelRadius: radius, kernelSize, tapCount, patchWidth, patchHeight, patchColumns, patchRows,\n maximumKernelSum, maximumSampleMagnitude });\n}\n\n/**\n * Reference gather for output rows `[y0, y1)`, written into `output` at `(y - y0) * width + x`.\n * The summation order (v outer, u inner, both ascending) is part of the contract shared with the\n * WGSL (WebGPU shader) kernel.\n * @internal\n */\nexport function convolveIrradianceRows(plan: IrradianceConvolutionPlan, samples: Float32Array | Float64Array,\n kernels: Float32Array | Float64Array, y0: number, y1: number, output: Float64Array): void {\n const { width, height, kernelRadius: r, kernelSize, tapCount, patchWidth, patchHeight, patchColumns, patchRows } = plan;\n for (let y = y0; y < y1; y++) {\n for (let x = 0; x < width; x++) {\n let sum = 0;\n for (let v = -r; v <= r; v++) {\n const sy = y - v;\n if (sy < 0 || sy >= height) continue;\n const patchRowBase = Math.min(Math.floor(sy / patchHeight), patchRows - 1) * patchColumns;\n const kernelRow = (v + r) * kernelSize + r, sampleRow = sy * width;\n for (let u = -r; u <= r; u++) {\n const sx = x - u;\n if (sx < 0 || sx >= width) continue;\n const patch = patchRowBase + Math.min(Math.floor(sx / patchWidth), patchColumns - 1);\n sum += samples[sampleRow + sx]! * kernels[patch * tapCount + kernelRow + u]!;\n }\n }\n output[(y - y0) * width + x] = sum;\n }\n }\n}\n\n/** Synchronous float64 reference for bounded grids. Use the image-kernel accelerator for large grids. */\nexport function calculateIrradianceConvolution(input: IrradianceConvolutionInput): { plan: IrradianceConvolutionPlan; values: Float64Array } {\n const plan = calculateIrradianceConvolutionPlan(input);\n const values = new Float64Array(plan.width * plan.height);\n convolveIrradianceRows(plan, input.samples, input.kernels, 0, plan.height, values);\n return { plan, values };\n}\n"]}
1
+ {"version":3,"file":"irradiance-convolution.js","sourceRoot":"","sources":["../../src/optics/irradiance-convolution.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7F,MAAM,CAAC,MAAM,qCAAqC,GAAG,OAAgB,CAAC;AACtE,6HAA6H;AAC7H,MAAM,CAAC,MAAM,6BAA6B,GAAG,MAAM,CAAC,MAAM,CAAC;IACzD,aAAa,EAAE,UAAU;IACzB,aAAa,EAAE,8BAA8B;IAC7C,gBAAgB,EAAE,MAAM;IACxB,mBAAmB,EAAE,EAAE;IACvB,iBAAiB,EAAE,KAAK;IACxB,oBAAoB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AAG,EAAE,GAAG,KAAK,CAAC;gBACnE,KAAK,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;oBAC7B,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;oBACjB,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,IAAI,KAAK;wBAAE,SAAS;oBACpC,MAAM,KAAK,GAAG,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,UAAU,CAAC,EAAE,YAAY,GAAG,CAAC,CAAC,CAAC;oBACrF,GAAG,IAAI,OAAO,CAAC,SAAS,GAAG,EAAE,CAAE,GAAG,OAAO,CAAC,KAAK,GAAG,QAAQ,GAAG,SAAS,GAAG,CAAC,CAAE,CAAC;gBAC/E,CAAC;YACH,CAAC;YACD,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC;QACrC,CAAC;IACH,CAAC;AACH,CAAC;AAED,yGAAyG;AACzG,MAAM,UAAU,8BAA8B,CAAC,KAAiC;IAC9E,MAAM,IAAI,GAAG,kCAAkC,CAAC,KAAK,CAAC,CAAC;IACvD,MAAM,MAAM,GAAG,IAAI,YAAY,CAAC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1D,sBAAsB,CAAC,IAAI,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnF,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Blurs a sampled image-plane quantity with caller-supplied PSF (point-spread function) kernels, one\n * kernel per patch of the image. The quantity must be linear and additive (for example irradiance).\n * Each patch is treated as shift-invariant (\"isoplanatic\"): the same PSF applies everywhere inside it.\n * The PSFs are incoherent intensity PSFs.\n *\n * This is the CPU float64 reference for the optics-as-convolution step (#277). The `webgpu-f32`\n * path runs the same equation; see docs/WEBGPU.md.\n *\n * Equation (indexed by source site; an energy-conserving scatter written as a gather):\n * out(x, y) = Σ_{v=-r..r} Σ_{u=-r..r} in(x − u, y − v) · K_{p(x − u, y − v)}(u, v)\n * where `p(s)` is the patch containing the **source** site and `K_p(u, v)` is the fraction of the source\n * site's quantity that lands at displacement (+u right, +v down), in grid sites.\n *\n * Incoherent imaging is a linear sum of intensity PSFs: the output intensity is the input intensity\n * convolved with the intensity PSF (MIT OpenCourseWare 2.71 Optics, Spring 2009, lecture 22, free).\n * A PSF that varies across the field is approximated as constant inside each patch, as in methods\n * that divide the image into isoplanatic subsections (van de Ketterij et al., arXiv:2011.01738,\n * sec. 1, free). Also see: Goodman, Introduction to Fourier Optics, 4th ed., 2017, §6.1. Camera\n * simulators such as ISETCam use the same piecewise shift-invariant method\n * (Farrell et al., Proc. SPIE 8299, 2012). The caller chooses the patch size and kernels, and so\n * owns the patch approximation.\n *\n * Edges: the grid holds every source. Sources outside the grid are not represented. Anything\n * scattered outside the grid is lost; compare `inputSum` with `outputSum` to see how much. There is no\n * padding, reflection or renormalization.\n */\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit } from \"../core/pixel-limits.js\";\n\nexport const IRRADIANCE_CONVOLUTION_SCHEMA_VERSION = \"0.1.0\" as const;\n/** `maximumPixels` is the default grid limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */\nexport const IRRADIANCE_CONVOLUTION_LIMITS = Object.freeze({\n maximumPixels: 24_000_000,\n ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS,\n maximumDimension: 16_384,\n maximumKernelRadius: 32,\n maximumPatchCount: 4_096,\n maximumKernelWeights: 4_194_304,\n /** A kernel may lose energy (vignetting, transmission) but may not create it, beyond rounding slack. */\n maximumKernelSum: 1 + 2 ** -20,\n /** Inputs larger than this are rejected so that float32 execution cannot overflow. */\n maximumSampleMagnitude: 2 ** 100\n});\n\nexport interface IrradianceConvolutionInput {\n schemaVersion: typeof IRRADIANCE_CONVOLUTION_SCHEMA_VERSION;\n width: number;\n height: number;\n /** Row-major samples. Finite, non-negative, linear and additive (for example irradiance, or expected photons per site). */\n samples: Float32Array | Float64Array;\n /** Kernel half-width in grid sites. Each kernel is (2r+1)×(2r+1). */\n kernelRadius: number;\n /** Patch size in grid sites. The last row and column of patches may be partial. */\n patchWidth: number;\n patchHeight: number;\n /**\n * Finite non-negative weights, `[patchRow][patchColumn][v + r][u + r]`, one kernel per patch in\n * row-major patch order. Each kernel sums to at most 1 (+2^-20 rounding slack).\n */\n kernels: Float32Array | Float64Array;\n boundary: \"zero-outside-grid\";\n /**\n * Optional opt-in grid limit for large images: an integer from 1 to `IRRADIANCE_CONVOLUTION_LIMITS.ceilingPixels`.\n * Default `IRRADIANCE_CONVOLUTION_LIMITS.maximumPixels` (24 000 000). It does not change the result.\n */\n maximumPixels?: number;\n}\n\n/** Validated, immutable geometry of a convolution request. Sample arrays are borrowed, not copied. */\nexport interface IrradianceConvolutionPlan {\n width: number;\n height: number;\n kernelRadius: number;\n kernelSize: number;\n tapCount: number;\n patchWidth: number;\n patchHeight: number;\n patchColumns: number;\n patchRows: number;\n /** Largest kernel sum and largest input magnitude. The float32 error bound uses them. */\n maximumKernelSum: number;\n maximumSampleMagnitude: number;\n}\n\nfunction positiveInteger(value: unknown, maximum: number): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0 || value > maximum) {\n throw new InvalidConfigurationError(\"Invalid irradiance convolution geometry.\");\n }\n return value;\n}\n\n/** Validates the request and returns its plan. Every sample and weight is checked once. */\nexport function calculateIrradianceConvolutionPlan(input: IrradianceConvolutionInput): IrradianceConvolutionPlan {\n const r = requireAllowlistedRecord(input, [\"schemaVersion\", \"width\", \"height\", \"samples\", \"kernelRadius\", \"patchWidth\",\n \"patchHeight\", \"kernels\", \"boundary\", \"maximumPixels\"], \"Invalid irradiance convolution input.\");\n const L = IRRADIANCE_CONVOLUTION_LIMITS;\n if (r.schemaVersion !== IRRADIANCE_CONVOLUTION_SCHEMA_VERSION || r.boundary !== \"zero-outside-grid\") {\n throw new InvalidConfigurationError(\"Unsupported irradiance convolution schema or boundary.\");\n }\n const width = positiveInteger(r.width, L.maximumDimension), height = positiveInteger(r.height, L.maximumDimension);\n const maximumPixels = resolveRaisedLimit(r.maximumPixels, L.maximumPixels, L.ceilingPixels,\n \"Irradiance convolution maximumPixels must be an integer from 1 to \" + L.ceilingPixels + \".\");\n if (width * height > maximumPixels) throw new InvalidConfigurationError(\"Irradiance convolution grid exceeds the pixel limit.\");\n const radius = r.kernelRadius;\n if (typeof radius !== \"number\" || !Number.isSafeInteger(radius) || radius < 0 || radius > L.maximumKernelRadius) {\n throw new InvalidConfigurationError(\"Invalid irradiance convolution kernel radius.\");\n }\n const patchWidth = positiveInteger(r.patchWidth, width), patchHeight = positiveInteger(r.patchHeight, height);\n const patchColumns = Math.ceil(width / patchWidth), patchRows = Math.ceil(height / patchHeight);\n const kernelSize = 2 * radius + 1, tapCount = kernelSize * kernelSize, patchCount = patchColumns * patchRows;\n if (patchCount > L.maximumPatchCount || patchCount * tapCount > L.maximumKernelWeights) {\n throw new InvalidConfigurationError(\"Irradiance convolution kernels exceed the declared limits.\");\n }\n const samples = r.samples, kernels = r.kernels;\n if (!(samples instanceof Float32Array || samples instanceof Float64Array) || samples.length !== width * height ||\n !(kernels instanceof Float32Array || kernels instanceof Float64Array) || kernels.length !== patchCount * tapCount) {\n throw new InvalidConfigurationError(\"Irradiance convolution arrays do not match the declared geometry.\");\n }\n let maximumSampleMagnitude = 0;\n for (let i = 0; i < samples.length; i++) {\n const v = samples[i]!;\n // Negated comparison also rejects NaN.\n if (!(v >= 0 && v <= L.maximumSampleMagnitude)) {\n throw new InvalidConfigurationError(\"Irradiance samples must be finite, non-negative and within the declared magnitude.\");\n }\n if (v > maximumSampleMagnitude) maximumSampleMagnitude = v;\n }\n let maximumKernelSum = 0;\n for (let p = 0; p < patchCount; p++) {\n let sum = 0;\n for (let t = p * tapCount, end = t + tapCount; t < end; t++) {\n const w = kernels[t]!;\n if (!(w >= 0 && w <= 1)) throw new InvalidConfigurationError(\"PSF kernel weights must be finite and within [0, 1].\");\n sum += w;\n }\n if (sum > L.maximumKernelSum) throw new InvalidConfigurationError(\"A PSF kernel may not create energy (sum exceeds 1).\");\n if (sum > maximumKernelSum) maximumKernelSum = sum;\n }\n return Object.freeze({ width, height, kernelRadius: radius, kernelSize, tapCount, patchWidth, patchHeight, patchColumns, patchRows,\n maximumKernelSum, maximumSampleMagnitude });\n}\n\n/**\n * Reference gather for output rows `[y0, y1)`, written into `output` at `(y - y0) * width + x`.\n * The summation order (v outer, u inner, both ascending) is part of the contract shared with the\n * WGSL (WebGPU shader) kernel.\n * @internal\n */\nexport function convolveIrradianceRows(plan: IrradianceConvolutionPlan, samples: Float32Array | Float64Array,\n kernels: Float32Array | Float64Array, y0: number, y1: number, output: Float64Array): void {\n const { width, height, kernelRadius: r, kernelSize, tapCount, patchWidth, patchHeight, patchColumns, patchRows } = plan;\n for (let y = y0; y < y1; y++) {\n for (let x = 0; x < width; x++) {\n let sum = 0;\n for (let v = -r; v <= r; v++) {\n const sy = y - v;\n if (sy < 0 || sy >= height) continue;\n const patchRowBase = Math.min(Math.floor(sy / patchHeight), patchRows - 1) * patchColumns;\n const kernelRow = (v + r) * kernelSize + r, sampleRow = sy * width;\n for (let u = -r; u <= r; u++) {\n const sx = x - u;\n if (sx < 0 || sx >= width) continue;\n const patch = patchRowBase + Math.min(Math.floor(sx / patchWidth), patchColumns - 1);\n sum += samples[sampleRow + sx]! * kernels[patch * tapCount + kernelRow + u]!;\n }\n }\n output[(y - y0) * width + x] = sum;\n }\n }\n}\n\n/** Synchronous float64 reference for bounded grids. Use the image-kernel accelerator for large grids. */\nexport function calculateIrradianceConvolution(input: IrradianceConvolutionInput): { plan: IrradianceConvolutionPlan; values: Float64Array } {\n const plan = calculateIrradianceConvolutionPlan(input);\n const values = new Float64Array(plan.width * plan.height);\n convolveIrradianceRows(plan, input.samples, input.kernels, 0, plan.height, values);\n return { plan, values };\n}\n"]}
@@ -7,7 +7,9 @@
7
7
  * PSF tap then maps to a site displacement with the per-site quadrature's inverse support
8
8
  * (`sensorPsfSourcePoint`): tap (kx, ky) is the source at native offset (−(kx − cx)·pₓ, +(ky − cy)·p_y)
9
9
  * from the destination, so its weight lands at displacement u = (kx − cx)·pₓ/sₓ, v = −(ky − cy)·p_y/s_y
10
- * sites (p: PSF sample pitch, s: site pitch).
10
+ * sites (p: PSF sample pitch, s: site pitch). When p equals s the displacement is taken as the tap offset itself
11
+ * (kx − cx, −(ky − cy)): the rounded quotient (n·p)/p misses the integer n by one unit in the last place for some
12
+ * pitches (for example 3 · 1.6 / 1.6), which split the tap bilinearly or reached one site past the window (2.2.1).
11
13
  *
12
14
  * - **Exact site sampling.** When every displacement is an integer (equal pitches, integer centre), each
13
15
  * tap's weight goes to one kernel cell. For a destination whose PSF equals its patch's, the
@@ -8,7 +8,9 @@
8
8
  * PSF tap then maps to a site displacement with the per-site quadrature's inverse support
9
9
  * (`sensorPsfSourcePoint`): tap (kx, ky) is the source at native offset (−(kx − cx)·pₓ, +(ky − cy)·p_y)
10
10
  * from the destination, so its weight lands at displacement u = (kx − cx)·pₓ/sₓ, v = −(ky − cy)·p_y/s_y
11
- * sites (p: PSF sample pitch, s: site pitch).
11
+ * sites (p: PSF sample pitch, s: site pitch). When p equals s the displacement is taken as the tap offset itself
12
+ * (kx − cx, −(ky − cy)): the rounded quotient (n·p)/p misses the integer n by one unit in the last place for some
13
+ * pitches (for example 3 · 1.6 / 1.6), which split the tap bilinearly or reached one site past the window (2.2.1).
12
14
  *
13
15
  * - **Exact site sampling.** When every displacement is an integer (equal pitches, integer centre), each
14
16
  * tap's weight goes to one kernel cell. For a destination whose PSF equals its patch's, the
@@ -105,12 +107,15 @@ export function resolveLensPsfConvolutionKernels(input) {
105
107
  throughput += share * resolved.relativePupilThroughputFactor;
106
108
  if (resolved.resolutionStatus !== "exact-grid-sample")
107
109
  interpolated = true;
110
+ const equalX = k.samplePitchMicrometersX === sx, equalY = k.samplePitchMicrometersY === sy;
108
111
  for (let ky = 0; ky < k.heightSamples; ky++)
109
112
  for (let kx = 0; kx < k.widthSamples; kx++) {
110
113
  const intensity = k.normalizedIntensity[ky * k.widthSamples + kx];
111
114
  if (intensity === 0)
112
115
  continue;
113
- const u = (kx - k.centerSampleX) * k.samplePitchMicrometersX / sx, v = -(ky - k.centerSampleY) * k.samplePitchMicrometersY / sy;
116
+ // With equal pitches the displacement is the tap offset itself: (n·p)/p can miss n by one unit in the last place.
117
+ const u = equalX ? kx - k.centerSampleX : (kx - k.centerSampleX) * k.samplePitchMicrometersX / sx;
118
+ const v = equalY ? -(ky - k.centerSampleY) : -(ky - k.centerSampleY) * k.samplePitchMicrometersY / sy;
114
119
  const u0 = Math.floor(u), v0 = Math.floor(v), fu = u - u0, fv = v - v0, w = share * intensity;
115
120
  if (fu !== 0 || fv !== 0)
116
121
  exact = false;
@@ -1 +1 @@
1
- {"version":3,"file":"lens-psf-kernels.js","sourceRoot":"","sources":["../../src/optics/lens-psf-kernels.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,mBAAmB,EAA0B,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,oCAAoC,EAAE,qBAAqB,EAAmC,MAAM,uBAAuB,CAAC;AAEr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AC,CAAC;QAC9H,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE;YAAE,GAAG,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAE,CAAC;QAC7D,gBAAgB,GAAG,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;IACH,IAAI,gBAAgB,GAAG,CAAC,CAAC,gBAAgB;QAAE,MAAM,IAAI,yBAAyB,CAAC,qCAAqC,CAAC,CAAC;IACtH,OAAO,mBAAmB,CAAC,EAAE,aAAa,EAAE,2CAA2C,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW;QACpI,YAAY,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,EAChI,8BAA8B,EAAE,2CAA2C,EAAE;QAC3E,8IAA8I;QAC9I,KAAK,CAAC,CAAC,CAAC,4EAA4E,CAAC,CAAC;YACpF,uIAAuI;QACzI,6FAA6F;KAC9F,CAAC,CAAC;AACL,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Samples the engine's lens PSFs (`LensSampledPsfProfile`, resolved with `resolveLensSampledPsf`) into\n * the per-patch kernels of the isoplanatic convolution (`calculateIrradianceConvolution`, #277).\n *\n * For each patch, the PSF is resolved at the patch centre's field point, in the per-site engine's own\n * coordinates: native sensor millimetres from the optical axis (+Y down), field point (x, −y). Every\n * PSF tap then maps to a site displacement with the per-site quadrature's inverse support\n * (`sensorPsfSourcePoint`): tap (kx, ky) is the source at native offset (−(kx − cx)·pₓ, +(ky − cy)·p_y)\n * from the destination, so its weight lands at displacement u = (kx − cx)·pₓ/sₓ, v = −(ky − cy)·p_y/s_y\n * sites (p: PSF sample pitch, s: site pitch).\n *\n * - **Exact site sampling.** When every displacement is an integer (equal pitches, integer centre), each\n * tap's weight goes to one kernel cell. For a destination whose PSF equals its patch's, the\n * convolution then equals the per-site PSF quadrature at site-centre sources term by term.\n * - **Otherwise (labelled approximation): bilinear splatting.** Each weight is split over the four\n * surrounding integer displacements with bilinear weights. This is the exact adjoint of bilinear\n * interpolation, so the convolution equals the per-site quadrature applied to the bilinear interpolant of\n * the site-centre samples (tested). Weights are conserved.\n *\n * With several wavelengths the kernel is the weight-normalized sum of the per-wavelength kernels. For a\n * spectrally neutral scene that is exactly the per-site engine's spectral sum when the weights are its\n * spectral quadrature weights times the scene spectrum (see docs/WEBGPU.md).\n *\n * The patch approximation (one PSF per patch, indexed by source site) is the caller's choice of patch\n * size; its method error is measured, not bounded (docs/WEBGPU.md, \"Per-fixture rollout\"). Relative\n * pupil throughput stays a separate factor and is reported, never folded into the unit-energy kernels.\n */\n\nimport { approximationResult, type CalculationResult } from \"../core/calculation-result.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { IRRADIANCE_CONVOLUTION_LIMITS } from \"./irradiance-convolution.js\";\nimport { markEngineOwnedLensSampledPsfProfile, resolveLensSampledPsf, type ResolveLensSampledPsfInput } from \"./lens-psf-profile.js\";\n\nexport const LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION = \"0.1.0\" as const;\n/** At most this many wavelengths per call. */\nexport const LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS = 64;\n\nexport interface LensPsfConvolutionKernelsInput {\n schemaVersion: typeof LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION;\n /** The optical state, as for `resolveLensSampledPsf`, without the field point and wavelength. */\n psf: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /** One or more wavelengths with non-negative weights (at least one positive). */\n spectralWeights: readonly { wavelengthNm: number; weight: number }[];\n /** The convolution grid: sites, their pitch, and the optical axis in site units (site centres at i + 0.5). */\n grid: { width: number; height: number; sitePitchMicrometers: { x: number; y: number }; opticalAxisSite: { x: number; y: number } };\n /** Patch size in sites; the last row and column of patches may be partial. */\n patchWidth: number;\n patchHeight: number;\n /** Kernel radius to use; omitted, the smallest radius that holds every tap. A radius too small to hold the PSF is rejected. */\n kernelRadius?: number;\n}\n\nexport interface LensPsfConvolutionKernels {\n schemaVersion: typeof LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION;\n kernelRadius: number;\n patchWidth: number;\n patchHeight: number;\n patchColumns: number;\n patchRows: number;\n /** `[patchRow][patchColumn][v + r][u + r]`, ready for `IrradianceConvolutionInput.kernels`. */\n kernels: Float64Array;\n /** True when every tap landed on one integer displacement (no bilinear splatting). */\n exactSiteSampling: boolean;\n maximumKernelSum: number;\n /** Per patch, row-major: the field point used and the weight-averaged relative pupil throughput (not applied). */\n patches: readonly { fieldPointMm: { x: number; y: number }; relativePupilThroughputFactor: number; interpolated: boolean }[];\n}\n\nfunction positive(value: unknown, message: string): number {\n if (typeof value !== \"number\" || !(value > 0 && value <= Number.MAX_VALUE)) throw new InvalidConfigurationError(message);\n return value;\n}\nfunction integer(value: unknown, minimum: number, maximum: number, message: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw new InvalidConfigurationError(message);\n return value;\n}\n\n/**\n * Builds the per-patch convolution kernels from a sampled lens PSF profile.\n * @param input - See `LensPsfConvolutionKernelsInput`.\n * @returns The kernels and per-patch field points. Success does not imply calibration.\n * @see docs/WEBGPU.md, \"Kernels from a lens PSF profile\".\n */\nexport function resolveLensPsfConvolutionKernels(input: LensPsfConvolutionKernelsInput): CalculationResult<LensPsfConvolutionKernels> {\n const r = requireAllowlistedRecord(input, [\"schemaVersion\", \"psf\", \"spectralWeights\", \"grid\", \"patchWidth\", \"patchHeight\", \"kernelRadius\"],\n \"Invalid lens PSF convolution kernel input.\");\n if (r.schemaVersion !== LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION) throw new InvalidConfigurationError(\"Unsupported lens PSF convolution kernel schema.\");\n const L = IRRADIANCE_CONVOLUTION_LIMITS;\n const g = requireAllowlistedRecord(r.grid, [\"width\", \"height\", \"sitePitchMicrometers\", \"opticalAxisSite\"], \"Invalid convolution grid.\");\n const width = integer(g.width, 1, L.maximumDimension, \"Invalid convolution grid size.\"), height = integer(g.height, 1, L.maximumDimension, \"Invalid convolution grid size.\");\n const pitch = requireAllowlistedRecord(g.sitePitchMicrometers, [\"x\", \"y\"], \"Invalid site pitch.\");\n const sx = positive(pitch.x, \"Site pitch must be positive.\"), sy = positive(pitch.y, \"Site pitch must be positive.\");\n const axis = requireAllowlistedRecord(g.opticalAxisSite, [\"x\", \"y\"], \"Invalid optical axis.\");\n if (typeof axis.x !== \"number\" || typeof axis.y !== \"number\" || !Number.isFinite(axis.x) || !Number.isFinite(axis.y)) {\n throw new InvalidConfigurationError(\"The optical axis must be finite site coordinates.\");\n }\n const patchWidth = integer(r.patchWidth, 1, width, \"Invalid patch size.\"), patchHeight = integer(r.patchHeight, 1, height, \"Invalid patch size.\");\n const columns = Math.ceil(width / patchWidth), rows = Math.ceil(height / patchHeight);\n if (columns * rows > L.maximumPatchCount) throw new InvalidConfigurationError(\"Too many patches.\");\n const list = r.spectralWeights;\n if (!Array.isArray(list) || list.length < 1 || list.length > LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS) {\n throw new InvalidConfigurationError(\"spectralWeights must list 1 to 64 wavelengths.\");\n }\n const spectral = list.map((entry: unknown) => {\n const e = requireAllowlistedRecord(entry, [\"wavelengthNm\", \"weight\"], \"Invalid spectral weight.\");\n if (typeof e.weight !== \"number\" || !(e.weight >= 0 && e.weight <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"Spectral weights must be finite and non-negative.\");\n return { wavelengthNm: positive(e.wavelengthNm, \"Wavelengths must be positive.\"), weight: e.weight };\n });\n const totalWeight = spectral.reduce((s, e) => s + e.weight, 0);\n if (!(totalWeight > 0 && totalWeight <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"At least one spectral weight must be positive.\");\n const psf = requireAllowlistedRecord(r.psf, [\"profile\", \"focalLengthMm\", \"focus\", \"apertureFNumber\", \"signedDefocusImagePlaneMicrometers\"], \"Invalid PSF state.\");\n // One private parse of the profile for every patch and wavelength.\n const profile = structuredClone(psf.profile);\n markEngineOwnedLensSampledPsfProfile(profile);\n const state = { ...(psf as unknown as Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">), profile } as Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n\n // Resolve every patch and wavelength, splatting straight into one scratch displacement map sized for the largest\n // allowed radius; each patch keeps a copy cropped to its own reach. The common radius is known only at the end.\n // Every cell receives its weights in the same order as a direct sum (taps in kernel order, then the four\n // bilinear corners), so the kernels do not depend on the scratch layout.\n const M = L.maximumKernelRadius, scratchSize = 2 * M + 1, scratch = new Float64Array(scratchSize * scratchSize);\n const cropped: { reach: number; values: Float64Array }[] = [], patches: LensPsfConvolutionKernels[\"patches\"][number][] = [];\n let reach = 0, exact = true, overflow = false;\n for (let pr = 0; pr < rows; pr++) for (let pc = 0; pc < columns; pc++) {\n const x0 = pc * patchWidth, y0 = pr * patchHeight, x1 = Math.min(width, x0 + patchWidth), y1 = Math.min(height, y0 + patchHeight);\n const nativeX = ((x0 + x1) / 2 - axis.x) * sx / 1000, nativeY = ((y0 + y1) / 2 - axis.y) * sy / 1000;\n const fieldPointMm = { x: nativeX, y: -nativeY };\n let throughput = 0, interpolated = false, patchReach = 0;\n for (const { wavelengthNm, weight } of spectral) {\n if (weight === 0) continue;\n const resolved = resolveLensSampledPsf({ ...state, fieldPointMm, wavelengthNm }).value, k = resolved.kernel, share = weight / totalWeight;\n throughput += share * resolved.relativePupilThroughputFactor;\n if (resolved.resolutionStatus !== \"exact-grid-sample\") interpolated = true;\n for (let ky = 0; ky < k.heightSamples; ky++) for (let kx = 0; kx < k.widthSamples; kx++) {\n const intensity = k.normalizedIntensity[ky * k.widthSamples + kx]!;\n if (intensity === 0) continue;\n const u = (kx - k.centerSampleX) * k.samplePitchMicrometersX / sx, v = -(ky - k.centerSampleY) * k.samplePitchMicrometersY / sy;\n const u0 = Math.floor(u), v0 = Math.floor(v), fu = u - u0, fv = v - v0, w = share * intensity;\n if (fu !== 0 || fv !== 0) exact = false;\n for (let corner = 0; corner < 4; corner++) {\n const du = corner & 1, dv = corner >> 1;\n const b = du === 0 ? (dv === 0 ? (1 - fu) * (1 - fv) : (1 - fu) * fv) : (dv === 0 ? fu * (1 - fv) : fu * fv);\n if (b === 0) continue;\n const cu = u0 + du, cv = v0 + dv;\n patchReach = Math.max(patchReach, Math.abs(cu), Math.abs(cv));\n // Past the largest radius the call is rejected below; resolving continues so errors keep their order.\n if (patchReach > M) { overflow = true; continue; }\n if (!overflow) scratch[(cv + M) * scratchSize + cu + M]! += w * b;\n }\n }\n }\n reach = Math.max(reach, patchReach);\n if (!overflow) {\n const n = 2 * patchReach + 1, values = new Float64Array(n * n);\n for (let v = -patchReach; v <= patchReach; v++) {\n const row = (v + M) * scratchSize + M;\n values.set(scratch.subarray(row - patchReach, row + patchReach + 1), (v + patchReach) * n);\n scratch.fill(0, row - patchReach, row + patchReach + 1);\n }\n cropped.push({ reach: patchReach, values });\n }\n patches.push(Object.freeze({ fieldPointMm: Object.freeze(fieldPointMm), relativePupilThroughputFactor: throughput, interpolated }));\n }\n const radius = r.kernelRadius === undefined ? reach : integer(r.kernelRadius, 0, L.maximumKernelRadius, \"Invalid kernel radius.\");\n if (reach > radius) throw new InvalidConfigurationError(\"The kernel radius is too small for the PSF support; no tap is dropped.\");\n if (radius > L.maximumKernelRadius) throw new InvalidConfigurationError(\"The PSF support needs a kernel radius above 32 sites.\");\n const size = 2 * radius + 1, taps = size * size;\n if (columns * rows * taps > L.maximumKernelWeights) throw new InvalidConfigurationError(\"Too many kernel weights.\");\n const kernels = new Float64Array(columns * rows * taps);\n let maximumKernelSum = 0;\n cropped.forEach(({ reach: q, values }, p) => {\n const n = 2 * q + 1;\n let sum = 0;\n for (let v = 0; v < n; v++) kernels.set(values.subarray(v * n, (v + 1) * n), p * taps + (v - q + radius) * size + radius - q);\n for (let t = 0; t < taps; t++) sum += kernels[p * taps + t]!;\n maximumKernelSum = Math.max(maximumKernelSum, sum);\n });\n if (maximumKernelSum > L.maximumKernelSum) throw new InvalidConfigurationError(\"Sampled kernels exceed unit energy.\");\n return approximationResult({ schemaVersion: LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION, kernelRadius: radius, patchWidth, patchHeight,\n patchColumns: columns, patchRows: rows, kernels, exactSiteSampling: exact, maximumKernelSum, patches: Object.freeze(patches) },\n \"lens-psf-convolution-kernels\", LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION, [\n \"One PSF per patch, resolved at the patch centre with resolveLensSampledPsf; indexed by source site in the convolution (isoplanatic patches).\",\n exact ? \"Every PSF tap maps to one integer site displacement (exact site sampling).\" :\n \"PSF taps between sites are split bilinearly (the adjoint of bilinear interpolation of site-centre samples); a labelled approximation.\",\n \"Relative pupil throughput is reported per patch and not applied to the unit-energy kernels.\"\n ]);\n}\n"]}
1
+ {"version":3,"file":"lens-psf-kernels.js","sourceRoot":"","sources":["../../src/optics/lens-psf-kernels.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAE,mBAAmB,EAA0B,MAAM,+BAA+B,CAAC;AAC5F,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,oCAAoC,EAAE,qBAAqB,EAAmC,MAAM,uBAAuB,CAAC;AAErI,MAAM,CAAC,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GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;YAAE,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,GAAG,IAAI,GAAG,MAAM,GAAG,CAAC,CAAC,CAAC;QAC9H,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE;YAAE,GAAG,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAE,CAAC;QAC7D,gBAAgB,GAAG,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;IACH,IAAI,gBAAgB,GAAG,CAAC,CAAC,gBAAgB;QAAE,MAAM,IAAI,yBAAyB,CAAC,qCAAqC,CAAC,CAAC;IACtH,OAAO,mBAAmB,CAAC,EAAE,aAAa,EAAE,2CAA2C,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW;QACpI,YAAY,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,EAChI,8BAA8B,EAAE,2CAA2C,EAAE;QAC3E,8IAA8I;QAC9I,KAAK,CAAC,CAAC,CAAC,4EAA4E,CAAC,CAAC;YACpF,uIAAuI;QACzI,6FAA6F;KAC9F,CAAC,CAAC;AACL,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Samples the engine's lens PSFs (`LensSampledPsfProfile`, resolved with `resolveLensSampledPsf`) into\n * the per-patch kernels of the isoplanatic convolution (`calculateIrradianceConvolution`, #277).\n *\n * For each patch, the PSF is resolved at the patch centre's field point, in the per-site engine's own\n * coordinates: native sensor millimetres from the optical axis (+Y down), field point (x, −y). Every\n * PSF tap then maps to a site displacement with the per-site quadrature's inverse support\n * (`sensorPsfSourcePoint`): tap (kx, ky) is the source at native offset (−(kx − cx)·pₓ, +(ky − cy)·p_y)\n * from the destination, so its weight lands at displacement u = (kx − cx)·pₓ/sₓ, v = −(ky − cy)·p_y/s_y\n * sites (p: PSF sample pitch, s: site pitch). When p equals s the displacement is taken as the tap offset itself\n * (kx − cx, −(ky − cy)): the rounded quotient (n·p)/p misses the integer n by one unit in the last place for some\n * pitches (for example 3 · 1.6 / 1.6), which split the tap bilinearly or reached one site past the window (2.2.1).\n *\n * - **Exact site sampling.** When every displacement is an integer (equal pitches, integer centre), each\n * tap's weight goes to one kernel cell. For a destination whose PSF equals its patch's, the\n * convolution then equals the per-site PSF quadrature at site-centre sources term by term.\n * - **Otherwise (labelled approximation): bilinear splatting.** Each weight is split over the four\n * surrounding integer displacements with bilinear weights. This is the exact adjoint of bilinear\n * interpolation, so the convolution equals the per-site quadrature applied to the bilinear interpolant of\n * the site-centre samples (tested). Weights are conserved.\n *\n * With several wavelengths the kernel is the weight-normalized sum of the per-wavelength kernels. For a\n * spectrally neutral scene that is exactly the per-site engine's spectral sum when the weights are its\n * spectral quadrature weights times the scene spectrum (see docs/WEBGPU.md).\n *\n * The patch approximation (one PSF per patch, indexed by source site) is the caller's choice of patch\n * size; its method error is measured, not bounded (docs/WEBGPU.md, \"Per-fixture rollout\"). Relative\n * pupil throughput stays a separate factor and is reported, never folded into the unit-energy kernels.\n */\n\nimport { approximationResult, type CalculationResult } from \"../core/calculation-result.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { IRRADIANCE_CONVOLUTION_LIMITS } from \"./irradiance-convolution.js\";\nimport { markEngineOwnedLensSampledPsfProfile, resolveLensSampledPsf, type ResolveLensSampledPsfInput } from \"./lens-psf-profile.js\";\n\nexport const LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION = \"0.1.0\" as const;\n/** At most this many wavelengths per call. */\nexport const LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS = 64;\n\nexport interface LensPsfConvolutionKernelsInput {\n schemaVersion: typeof LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION;\n /** The optical state, as for `resolveLensSampledPsf`, without the field point and wavelength. */\n psf: Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n /** One or more wavelengths with non-negative weights (at least one positive). */\n spectralWeights: readonly { wavelengthNm: number; weight: number }[];\n /** The convolution grid: sites, their pitch, and the optical axis in site units (site centres at i + 0.5). */\n grid: { width: number; height: number; sitePitchMicrometers: { x: number; y: number }; opticalAxisSite: { x: number; y: number } };\n /** Patch size in sites; the last row and column of patches may be partial. */\n patchWidth: number;\n patchHeight: number;\n /** Kernel radius to use; omitted, the smallest radius that holds every tap. A radius too small to hold the PSF is rejected. */\n kernelRadius?: number;\n}\n\nexport interface LensPsfConvolutionKernels {\n schemaVersion: typeof LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION;\n kernelRadius: number;\n patchWidth: number;\n patchHeight: number;\n patchColumns: number;\n patchRows: number;\n /** `[patchRow][patchColumn][v + r][u + r]`, ready for `IrradianceConvolutionInput.kernels`. */\n kernels: Float64Array;\n /** True when every tap landed on one integer displacement (no bilinear splatting). */\n exactSiteSampling: boolean;\n maximumKernelSum: number;\n /** Per patch, row-major: the field point used and the weight-averaged relative pupil throughput (not applied). */\n patches: readonly { fieldPointMm: { x: number; y: number }; relativePupilThroughputFactor: number; interpolated: boolean }[];\n}\n\nfunction positive(value: unknown, message: string): number {\n if (typeof value !== \"number\" || !(value > 0 && value <= Number.MAX_VALUE)) throw new InvalidConfigurationError(message);\n return value;\n}\nfunction integer(value: unknown, minimum: number, maximum: number, message: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw new InvalidConfigurationError(message);\n return value;\n}\n\n/**\n * Builds the per-patch convolution kernels from a sampled lens PSF profile.\n * @param input - See `LensPsfConvolutionKernelsInput`.\n * @returns The kernels and per-patch field points. Success does not imply calibration.\n * @see docs/WEBGPU.md, \"Kernels from a lens PSF profile\".\n */\nexport function resolveLensPsfConvolutionKernels(input: LensPsfConvolutionKernelsInput): CalculationResult<LensPsfConvolutionKernels> {\n const r = requireAllowlistedRecord(input, [\"schemaVersion\", \"psf\", \"spectralWeights\", \"grid\", \"patchWidth\", \"patchHeight\", \"kernelRadius\"],\n \"Invalid lens PSF convolution kernel input.\");\n if (r.schemaVersion !== LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION) throw new InvalidConfigurationError(\"Unsupported lens PSF convolution kernel schema.\");\n const L = IRRADIANCE_CONVOLUTION_LIMITS;\n const g = requireAllowlistedRecord(r.grid, [\"width\", \"height\", \"sitePitchMicrometers\", \"opticalAxisSite\"], \"Invalid convolution grid.\");\n const width = integer(g.width, 1, L.maximumDimension, \"Invalid convolution grid size.\"), height = integer(g.height, 1, L.maximumDimension, \"Invalid convolution grid size.\");\n const pitch = requireAllowlistedRecord(g.sitePitchMicrometers, [\"x\", \"y\"], \"Invalid site pitch.\");\n const sx = positive(pitch.x, \"Site pitch must be positive.\"), sy = positive(pitch.y, \"Site pitch must be positive.\");\n const axis = requireAllowlistedRecord(g.opticalAxisSite, [\"x\", \"y\"], \"Invalid optical axis.\");\n if (typeof axis.x !== \"number\" || typeof axis.y !== \"number\" || !Number.isFinite(axis.x) || !Number.isFinite(axis.y)) {\n throw new InvalidConfigurationError(\"The optical axis must be finite site coordinates.\");\n }\n const patchWidth = integer(r.patchWidth, 1, width, \"Invalid patch size.\"), patchHeight = integer(r.patchHeight, 1, height, \"Invalid patch size.\");\n const columns = Math.ceil(width / patchWidth), rows = Math.ceil(height / patchHeight);\n if (columns * rows > L.maximumPatchCount) throw new InvalidConfigurationError(\"Too many patches.\");\n const list = r.spectralWeights;\n if (!Array.isArray(list) || list.length < 1 || list.length > LENS_PSF_CONVOLUTION_KERNELS_MAXIMUM_WAVELENGTHS) {\n throw new InvalidConfigurationError(\"spectralWeights must list 1 to 64 wavelengths.\");\n }\n const spectral = list.map((entry: unknown) => {\n const e = requireAllowlistedRecord(entry, [\"wavelengthNm\", \"weight\"], \"Invalid spectral weight.\");\n if (typeof e.weight !== \"number\" || !(e.weight >= 0 && e.weight <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"Spectral weights must be finite and non-negative.\");\n return { wavelengthNm: positive(e.wavelengthNm, \"Wavelengths must be positive.\"), weight: e.weight };\n });\n const totalWeight = spectral.reduce((s, e) => s + e.weight, 0);\n if (!(totalWeight > 0 && totalWeight <= Number.MAX_VALUE)) throw new InvalidConfigurationError(\"At least one spectral weight must be positive.\");\n const psf = requireAllowlistedRecord(r.psf, [\"profile\", \"focalLengthMm\", \"focus\", \"apertureFNumber\", \"signedDefocusImagePlaneMicrometers\"], \"Invalid PSF state.\");\n // One private parse of the profile for every patch and wavelength.\n const profile = structuredClone(psf.profile);\n markEngineOwnedLensSampledPsfProfile(profile);\n const state = { ...(psf as unknown as Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">), profile } as Omit<ResolveLensSampledPsfInput, \"fieldPointMm\" | \"wavelengthNm\">;\n\n // Resolve every patch and wavelength, splatting straight into one scratch displacement map sized for the largest\n // allowed radius; each patch keeps a copy cropped to its own reach. The common radius is known only at the end.\n // Every cell receives its weights in the same order as a direct sum (taps in kernel order, then the four\n // bilinear corners), so the kernels do not depend on the scratch layout.\n const M = L.maximumKernelRadius, scratchSize = 2 * M + 1, scratch = new Float64Array(scratchSize * scratchSize);\n const cropped: { reach: number; values: Float64Array }[] = [], patches: LensPsfConvolutionKernels[\"patches\"][number][] = [];\n let reach = 0, exact = true, overflow = false;\n for (let pr = 0; pr < rows; pr++) for (let pc = 0; pc < columns; pc++) {\n const x0 = pc * patchWidth, y0 = pr * patchHeight, x1 = Math.min(width, x0 + patchWidth), y1 = Math.min(height, y0 + patchHeight);\n const nativeX = ((x0 + x1) / 2 - axis.x) * sx / 1000, nativeY = ((y0 + y1) / 2 - axis.y) * sy / 1000;\n const fieldPointMm = { x: nativeX, y: -nativeY };\n let throughput = 0, interpolated = false, patchReach = 0;\n for (const { wavelengthNm, weight } of spectral) {\n if (weight === 0) continue;\n const resolved = resolveLensSampledPsf({ ...state, fieldPointMm, wavelengthNm }).value, k = resolved.kernel, share = weight / totalWeight;\n throughput += share * resolved.relativePupilThroughputFactor;\n if (resolved.resolutionStatus !== \"exact-grid-sample\") interpolated = true;\n const equalX = k.samplePitchMicrometersX === sx, equalY = k.samplePitchMicrometersY === sy;\n for (let ky = 0; ky < k.heightSamples; ky++) for (let kx = 0; kx < k.widthSamples; kx++) {\n const intensity = k.normalizedIntensity[ky * k.widthSamples + kx]!;\n if (intensity === 0) continue;\n // With equal pitches the displacement is the tap offset itself: (n·p)/p can miss n by one unit in the last place.\n const u = equalX ? kx - k.centerSampleX : (kx - k.centerSampleX) * k.samplePitchMicrometersX / sx;\n const v = equalY ? -(ky - k.centerSampleY) : -(ky - k.centerSampleY) * k.samplePitchMicrometersY / sy;\n const u0 = Math.floor(u), v0 = Math.floor(v), fu = u - u0, fv = v - v0, w = share * intensity;\n if (fu !== 0 || fv !== 0) exact = false;\n for (let corner = 0; corner < 4; corner++) {\n const du = corner & 1, dv = corner >> 1;\n const b = du === 0 ? (dv === 0 ? (1 - fu) * (1 - fv) : (1 - fu) * fv) : (dv === 0 ? fu * (1 - fv) : fu * fv);\n if (b === 0) continue;\n const cu = u0 + du, cv = v0 + dv;\n patchReach = Math.max(patchReach, Math.abs(cu), Math.abs(cv));\n // Past the largest radius the call is rejected below; resolving continues so errors keep their order.\n if (patchReach > M) { overflow = true; continue; }\n if (!overflow) scratch[(cv + M) * scratchSize + cu + M]! += w * b;\n }\n }\n }\n reach = Math.max(reach, patchReach);\n if (!overflow) {\n const n = 2 * patchReach + 1, values = new Float64Array(n * n);\n for (let v = -patchReach; v <= patchReach; v++) {\n const row = (v + M) * scratchSize + M;\n values.set(scratch.subarray(row - patchReach, row + patchReach + 1), (v + patchReach) * n);\n scratch.fill(0, row - patchReach, row + patchReach + 1);\n }\n cropped.push({ reach: patchReach, values });\n }\n patches.push(Object.freeze({ fieldPointMm: Object.freeze(fieldPointMm), relativePupilThroughputFactor: throughput, interpolated }));\n }\n const radius = r.kernelRadius === undefined ? reach : integer(r.kernelRadius, 0, L.maximumKernelRadius, \"Invalid kernel radius.\");\n if (reach > radius) throw new InvalidConfigurationError(\"The kernel radius is too small for the PSF support; no tap is dropped.\");\n if (radius > L.maximumKernelRadius) throw new InvalidConfigurationError(\"The PSF support needs a kernel radius above 32 sites.\");\n const size = 2 * radius + 1, taps = size * size;\n if (columns * rows * taps > L.maximumKernelWeights) throw new InvalidConfigurationError(\"Too many kernel weights.\");\n const kernels = new Float64Array(columns * rows * taps);\n let maximumKernelSum = 0;\n cropped.forEach(({ reach: q, values }, p) => {\n const n = 2 * q + 1;\n let sum = 0;\n for (let v = 0; v < n; v++) kernels.set(values.subarray(v * n, (v + 1) * n), p * taps + (v - q + radius) * size + radius - q);\n for (let t = 0; t < taps; t++) sum += kernels[p * taps + t]!;\n maximumKernelSum = Math.max(maximumKernelSum, sum);\n });\n if (maximumKernelSum > L.maximumKernelSum) throw new InvalidConfigurationError(\"Sampled kernels exceed unit energy.\");\n return approximationResult({ schemaVersion: LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION, kernelRadius: radius, patchWidth, patchHeight,\n patchColumns: columns, patchRows: rows, kernels, exactSiteSampling: exact, maximumKernelSum, patches: Object.freeze(patches) },\n \"lens-psf-convolution-kernels\", LENS_PSF_CONVOLUTION_KERNELS_SCHEMA_VERSION, [\n \"One PSF per patch, resolved at the patch centre with resolveLensSampledPsf; indexed by source site in the convolution (isoplanatic patches).\",\n exact ? \"Every PSF tap maps to one integer site displacement (exact site sampling).\" :\n \"PSF taps between sites are split bilinearly (the adjoint of bilinear interpolation of site-centre samples); a labelled approximation.\",\n \"Relative pupil throughput is reported per patch and not applied to the unit-energy kernels.\"\n ]);\n}\n"]}
@@ -5,8 +5,10 @@
5
5
  import { type SimulatedCapture, type CaptureLinearPlane } from "../capture/simulated-capture.js";
6
6
  import { type SdrPixelTone, type SdrRenderingProfile, type SdrRenderingResult } from "./sdr-rendering.js";
7
7
  export declare const NATIVE_CAPTURE_SDR_SCHEMA_VERSION: "0.1.0";
8
+ /** `maximumPixels` is the default pixel limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */
8
9
  export declare const NATIVE_CAPTURE_SDR_LIMITS: Readonly<{
9
10
  maximumPixels: 24000000;
11
+ ceilingPixels: 134217728;
10
12
  maximumDimension: 16384;
11
13
  tileWidth: 256;
12
14
  tileHeight: 32;
@@ -20,6 +22,11 @@ export interface NativeCaptureSdrInput {
20
22
  profile: SdrRenderingProfile;
21
23
  /** Limit on the size of the integer output. Checked before anything is allocated or any tile is read. */
22
24
  maximumOutputBytes: number;
25
+ /**
26
+ * Optional opt-in pixel limit for large captures: an integer from 1 to `NATIVE_CAPTURE_SDR_LIMITS.ceilingPixels`.
27
+ * Default `NATIVE_CAPTURE_SDR_LIMITS.maximumPixels` (24 000 000). `maximumOutputBytes` still applies.
28
+ */
29
+ maximumPixels?: number;
23
30
  }
24
31
  /** Tile request. Coordinates are absolute in the selected plane's declared pixel grid, never relative to a crop. */
25
32
  export interface NativeCaptureSdrTileRequest {
@@ -8,15 +8,18 @@ import { LINEAR_CAPTURE_RGB_PROFILE, resolveCaptureColorModel } from "../color/c
8
8
  import { InvalidConfigurationError } from "../core/configuration-error.js";
9
9
  import { requireAllowlistedRecord, requirePublicOpaqueId } from "../core/record-validation.js";
10
10
  import { freezeOwnedData } from "../core/owned-data.js";
11
+ import { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit } from "../core/pixel-limits.js";
11
12
  import { encodeSrgbComponent } from "../color/srgb-transfer.js";
12
13
  import { InvalidScientificResultError } from "../core/validation.js";
13
14
  import { parseSdrRenderingProfile, prepareSdrPixelTone } from "./sdr-rendering.js";
14
15
  export const NATIVE_CAPTURE_SDR_SCHEMA_VERSION = "0.1.0";
15
- export const NATIVE_CAPTURE_SDR_LIMITS = Object.freeze({ maximumPixels: 24_000_000,
16
+ /** `maximumPixels` is the default pixel limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */
17
+ export const NATIVE_CAPTURE_SDR_LIMITS = Object.freeze({ maximumPixels: 24_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS,
16
18
  maximumDimension: 16_384, tileWidth: 256, tileHeight: 32, maximumTileStorageSamples: 32_768 });
17
19
  /** Validates the input and plans the task, including its limits, without reading samples or allocating an image. */
18
20
  export function calculateNativeCaptureSdrPlan(input) {
19
- const r = requireAllowlistedRecord(input, ["capture", "sourcePlaneId", "outputImageStateId", "profile", "maximumOutputBytes"], "Invalid native SDR input.");
21
+ const r = requireAllowlistedRecord(input, ["capture", "sourcePlaneId", "outputImageStateId", "profile", "maximumOutputBytes", "maximumPixels"], "Invalid native SDR input.");
22
+ const maximumPixels = resolveRaisedLimit(r.maximumPixels, NATIVE_CAPTURE_SDR_LIMITS.maximumPixels, NATIVE_CAPTURE_SDR_LIMITS.ceilingPixels, "Native SDR maximumPixels must be an integer from 1 to " + NATIVE_CAPTURE_SDR_LIMITS.ceilingPixels + ".");
20
23
  // Only external-storage manifests are accepted, so unrelated inline sample buffers are never copied.
21
24
  const c = r.capture;
22
25
  if (!c || !Array.isArray(c.planes) || c.planes.length > 32 || c.planes.some(p => !p || p.storage?.kind === "inline-float64")) {
@@ -39,7 +42,7 @@ export function calculateNativeCaptureSdrPlan(input) {
39
42
  const scale = 2 ** profile.renderingExposureEv / plane.referenceWhiteValue;
40
43
  if (!Number.isFinite(scale) || scale <= 0)
41
44
  throw new InvalidConfigurationError("Native SDR scale is unrepresentable.");
42
- if (pixels > NATIVE_CAPTURE_SDR_LIMITS.maximumPixels || plane.pixelWidth > NATIVE_CAPTURE_SDR_LIMITS.maximumDimension ||
45
+ if (pixels > maximumPixels || plane.pixelWidth > NATIVE_CAPTURE_SDR_LIMITS.maximumDimension ||
43
46
  plane.pixelHeight > NATIVE_CAPTURE_SDR_LIMITS.maximumDimension || typeof r.maximumOutputBytes !== "number" ||
44
47
  !Number.isSafeInteger(r.maximumOutputBytes) || r.maximumOutputBytes < outputBytes) {
45
48
  throw new InvalidConfigurationError("Native SDR raster/output exceeds declared admission limits.");
@@ -1 +1 @@
1
- {"version":3,"file":"native-capture-sdr.js","sourceRoot":"","sources":["../../src/output/native-capture-sdr.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;GAGG;AACH,OAAO,EAAE,qBAAqB,EAAkD,MAAM,iCAAiC,CAAC;AACxH,OAAO,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACjG,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAwE,MAAM,oBAAoB,CAAC;AAEzJ,MAAM,CAAC,MAAM,iCAAiC,GAAG,OAAgB,CAAC;AAClE,MAAM,CAAC,MAAM,yBAAyB,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,aAAa,EAAE,UAAU;IAChF,gBAAgB,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE,yBAAyB,EAAE,MAAM,EAAE,CAAC,CAAC;AAyDjG,oHAAoH;AACpH,MAAM,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,KAAK,GAAG,UAAU,CAAC;YAAC,KAAK,CAAC,KAAK,EAAE,CAAC;YAAC,OAAO,EAAE,CAAC;QAAC,CAAC,CAAC,CAAC;QAClG,UAAU;YACR,IAAI,KAAK,KAAK,WAAW,IAAI,CAAC,MAAM;gBAAE,MAAM,IAAI,yBAAyB,CAAC,mCAAmC,CAAC,CAAC;YAC/G,MAAM,MAAM,GAAG,MAAM,CAAC;YAAC,MAAM,GAAG,IAAI,CAAC;YAAC,KAAK,GAAG,IAAI,CAAC;YAAC,KAAK,GAAG,aAAa,CAAC;YAC1E,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native SDR rendering of large captures, tile by tile, within fixed memory limits. The engine\n * owns the task; the caller supplies the pixel tiles. See docs/NATIVE_CAPTURE_SDR.md.\n */\nimport { parseSimulatedCapture, type SimulatedCapture, type CaptureLinearPlane } from \"../capture/simulated-capture.js\";\nimport { LINEAR_CAPTURE_RGB_PROFILE, resolveCaptureColorModel } from \"../color/capture-color.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord, requirePublicOpaqueId } from \"../core/record-validation.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { encodeSrgbComponent } from \"../color/srgb-transfer.js\";\nimport { InvalidScientificResultError } from \"../core/validation.js\";\nimport { parseSdrRenderingProfile, prepareSdrPixelTone, type SdrPixelTone, type SdrRenderingProfile, type SdrRenderingResult } from \"./sdr-rendering.js\";\n\nexport const NATIVE_CAPTURE_SDR_SCHEMA_VERSION = \"0.1.0\" as const;\nexport const NATIVE_CAPTURE_SDR_LIMITS = Object.freeze({ maximumPixels: 24_000_000,\n maximumDimension: 16_384, tileWidth: 256, tileHeight: 32, maximumTileStorageSamples: 32_768 });\n/** Input. The capture holds only metadata; float samples are read from external storage. Samples must already have colour and white balance applied. */\nexport interface NativeCaptureSdrInput {\n capture: SimulatedCapture;\n sourcePlaneId: string;\n outputImageStateId: string;\n profile: SdrRenderingProfile;\n /** Limit on the size of the integer output. Checked before anything is allocated or any tile is read. */\n maximumOutputBytes: number;\n}\n/** Tile request. Coordinates are absolute in the selected plane's declared pixel grid, never relative to a crop. */\nexport interface NativeCaptureSdrTileRequest {\n captureId: string;\n sourcePlaneId: string;\n artifactId: string;\n sha256: string;\n x: number; y: number; width: number; height: number;\n}\n/** A tile returned by the provider. It belongs to this call alone; do not change or reuse it. Row padding is not image data. */\nexport interface NativeCaptureSdrTile extends NativeCaptureSdrTileRequest {\n rowStrideSamples: number;\n samples: Float32Array | Float64Array;\n}\n/** Supplies tiles, one call at a time. The caller must release decoder and GPU resources when the task aborts or finishes. */\nexport interface NativeCaptureSdrProvider {\n readTile(request: Readonly<NativeCaptureSdrTileRequest>, signal: AbortSignal): Promise<NativeCaptureSdrTile>;\n /** Must yield to the host event loop, so cancellation and input events can run between tiles. */\n yieldControl(signal: AbortSignal): Promise<void>;\n /**\n * Optional progress observer, called synchronously after each committed tile. It cannot change\n * output; an exception it throws fails the task like any other error.\n */\n onProgress?(progress: NativeTaskProgress): void;\n}\n/** Tile progress of a native task: `completedTileCount` of `totalTileCount` tiles are committed. */\nexport interface NativeTaskProgress { readonly completedTileCount: number; readonly totalTileCount: number }\nexport interface NativeCaptureSdrPlan {\n schemaVersion: typeof NATIVE_CAPTURE_SDR_SCHEMA_VERSION;\n capture: SimulatedCapture;\n sourcePlaneId: string;\n outputImageStateId: string;\n profile: SdrRenderingProfile;\n outputBytes: number;\n /** Upper bound on the bytes held in working arrays. It is not peak JavaScript heap, GPU or process memory, and does not show that a device can run the task. */\n maximumScratchPayloadBytes: number;\n tileCount: number;\n}\nexport interface NativeCaptureSdrOutput {\n plan: NativeCaptureSdrPlan;\n /** Packed RGB codes in row-major order, owned by the caller. 16-bit codes are numbers, not bytes in a particular byte order. */\n integerSamples: Uint8Array | Uint16Array;\n diagnostics: SdrRenderingResult[\"diagnostics\"];\n outputEncoding: SdrRenderingResult[\"outputEncoding\"];\n displayAdaptation: SdrRenderingResult[\"displayAdaptation\"];\n}\nexport type NativeCaptureSdrTaskState = \"ready\" | \"running\" | \"completed\" | \"cancelled\" | \"failed\" | \"disposed\" | \"transferred\";\n\n/** Validates the input and plans the task, including its limits, without reading samples or allocating an image. */\nexport function calculateNativeCaptureSdrPlan(input: NativeCaptureSdrInput): NativeCaptureSdrPlan {\n const r = requireAllowlistedRecord(input, [\"capture\", \"sourcePlaneId\", \"outputImageStateId\", \"profile\", \"maximumOutputBytes\"], \"Invalid native SDR input.\");\n // Only external-storage manifests are accepted, so unrelated inline sample buffers are never copied.\n const c = r.capture as SimulatedCapture | undefined;\n if (!c || !Array.isArray(c.planes) || c.planes.length > 32 || c.planes.some(p => !p || p.storage?.kind === \"inline-float64\")) {\n throw new InvalidConfigurationError(\"Native SDR requires external-only capture manifests.\");\n }\n const capture = parseSimulatedCapture(c);\n const sourcePlaneId = requirePublicOpaqueId(r.sourcePlaneId, \"Invalid native SDR plane ID.\");\n const outputImageStateId = requirePublicOpaqueId(r.outputImageStateId, \"Invalid native SDR output state ID.\");\n const plane = capture.planes.find(p => p.id === sourcePlaneId);\n const white = resolveCaptureColorModel().referenceWhiteXyz;\n if (!plane || plane.imageState !== \"color-transformed-linear-rgb\" ||\n plane.colorProfile?.id !== LINEAR_CAPTURE_RGB_PROFILE.id || plane.colorProfile.version !== LINEAR_CAPTURE_RGB_PROFILE.version ||\n plane.encodingReferenceWhiteXyz?.x !== white.x || plane.encodingReferenceWhiteXyz.y !== white.y || plane.encodingReferenceWhiteXyz.z !== white.z ||\n plane.whiteBalanceApplication === \"intent-only\" || (plane.whiteBalanceApplication === \"not-applicable\" && capture.whiteBalanceIntent !== null) ||\n capture.planes.some(p => p.imageStateId === outputImageStateId)) {\n throw new InvalidConfigurationError(\"Native SDR requires exact resolved linear-sRGB/D65 and a new output state ID.\");\n }\n const pixels = plane.pixelWidth * plane.pixelHeight, profile = parseSdrRenderingProfile(r.profile);\n const outputBytes = pixels * 3 * (profile.bitDepth / 8);\n const scale = 2 ** profile.renderingExposureEv / plane.referenceWhiteValue;\n if (!Number.isFinite(scale) || scale <= 0) throw new InvalidConfigurationError(\"Native SDR scale is unrepresentable.\");\n if (pixels > NATIVE_CAPTURE_SDR_LIMITS.maximumPixels || plane.pixelWidth > NATIVE_CAPTURE_SDR_LIMITS.maximumDimension ||\n plane.pixelHeight > NATIVE_CAPTURE_SDR_LIMITS.maximumDimension || typeof r.maximumOutputBytes !== \"number\" ||\n !Number.isSafeInteger(r.maximumOutputBytes) || r.maximumOutputBytes < outputBytes) {\n throw new InvalidConfigurationError(\"Native SDR raster/output exceeds declared admission limits.\");\n }\n // A cautious declared bound, kept from the earlier executor that called the reference renderer: provider payload +\n // packed copy + reference parser copy + four reference output arrays. The typed kernel itself keeps only the provider payload.\n const maximumScratchPayloadBytes = NATIVE_CAPTURE_SDR_LIMITS.maximumTileStorageSamples * 8 +\n NATIVE_CAPTURE_SDR_LIMITS.tileWidth * NATIVE_CAPTURE_SDR_LIMITS.tileHeight * 3 * 8 * 6;\n return freezeOwnedData({ schemaVersion: NATIVE_CAPTURE_SDR_SCHEMA_VERSION, capture, sourcePlaneId, outputImageStateId, profile,\n outputBytes, maximumScratchPayloadBytes,\n tileCount: Math.ceil(plane.pixelWidth / NATIVE_CAPTURE_SDR_LIMITS.tileWidth) * Math.ceil(plane.pixelHeight / NATIVE_CAPTURE_SDR_LIMITS.tileHeight) });\n}\n\n/**\n * Tile checks shared by every native SDR backend: identity, precision, row stride, storage and valid\n * input values. Returns a view of the provider's samples (not a copy). Padding is not checked for\n * finite values. Not exported from the package.\n */\nexport function validateNativeCaptureSdrTile(tile: NativeCaptureSdrTile, request: NativeCaptureSdrTileRequest,\n plane: CaptureLinearPlane): { source: Float32Array | Float64Array; stride: number } {\n const r = requireAllowlistedRecord(tile, [\"captureId\", \"sourcePlaneId\", \"artifactId\", \"sha256\", \"x\", \"y\", \"width\", \"height\", \"rowStrideSamples\", \"samples\"], \"Invalid native SDR tile.\");\n for (const key of Object.keys(request) as (keyof NativeCaptureSdrTileRequest)[]) {\n if (r[key] !== request[key]) throw new InvalidConfigurationError(\"Native SDR tile identity/rectangle mismatch.\");\n }\n const samples = r.samples;\n const expectedType = plane.storage.kind === \"external-float32\" ? Float32Array : Float64Array;\n if (!(samples instanceof expectedType) || !(samples.buffer instanceof ArrayBuffer) ||\n samples.buffer.byteLength > NATIVE_CAPTURE_SDR_LIMITS.maximumTileStorageSamples * expectedType.BYTES_PER_ELEMENT ||\n typeof r.rowStrideSamples !== \"number\" || !Number.isSafeInteger(r.rowStrideSamples) || r.rowStrideSamples < request.width * 3 ||\n samples.length !== r.rowStrideSamples * request.height || samples.length > NATIVE_CAPTURE_SDR_LIMITS.maximumTileStorageSamples) {\n throw new InvalidConfigurationError(\"Native SDR tile precision/stride/storage mismatch.\");\n }\n const source: Float32Array | Float64Array = samples, stride = r.rowStrideSamples, rowLength = request.width * 3;\n // Check every image sample (not padding) against the reference renderer's input rules before any rendering.\n for (let y = 0; y < request.height; y++) {\n for (let i = y * stride, end = i + rowLength; i < end; i++) {\n if (!Number.isFinite(source[i]!)) throw new InvalidConfigurationError(\"Unsupported SDR input domain/raster.\");\n }\n }\n return { source, stride };\n}\n\ntype NativeSdrDiagnosticCounts = Omit<SdrRenderingResult[\"diagnostics\"], \"captureSaturation\">;\n/**\n * Fast tile kernel on typed arrays. It applies the same equations as the SDR reference renderer\n * (`calculateSdrRendering`), with the same floating-point operation order per sample and the same\n * error precedence, and writes integer codes straight into the packed output.\n *\n * Steps: input check → rendering exposure → tone → gamut → sRGB transfer → quantization (round to\n * nearest, ties up). `test/native-capture-sdr-kernel-parity.test.ts` shows that codes and diagnostics\n * match the unchanged reference exactly.\n */\nfunction renderTileInto(tile: NativeCaptureSdrTile, request: NativeCaptureSdrTileRequest, plane: CaptureLinearPlane,\n profile: SdrRenderingProfile, tone: SdrPixelTone, scale: number, maximum: number, codes: Uint8Array | Uint16Array, diagnostics: NativeSdrDiagnosticCounts): void {\n const { source, stride } = validateNativeCaptureSdrTile(tile, request, plane);\n // Tiling is safe because every supported rendering operation works on one pixel at a time.\n const outputRowStride = plane.pixelWidth * 3;\n const counts = { negative: 0, above: 0, changed: 0, low: 0, high: 0, outOfGamut: false }, scratch = new Float64Array(3);\n for (let y = 0; y < request.height; y++) {\n renderSdrRunInto(source, y * stride, request.width, profile, tone, scale, maximum, codes, (request.y + y) * outputRowStride + request.x * 3, scratch, counts);\n }\n if (counts.outOfGamut) throw new InvalidConfigurationError(\"Tone output exceeds the declared SDR gamut range.\");\n diagnostics.renderingNegativeSampleCount += counts.negative; diagnostics.renderingAboveReferenceSampleCount += counts.above;\n diagnostics.toneChangedSampleCount += counts.changed; diagnostics.gamutClippedLowSampleCount += counts.low; diagnostics.gamutClippedHighSampleCount += counts.high;\n}\n/** Reference 8-bit code of a linear sample in [0,1]: Math.round(encodeSrgbComponent(x)·255). */\nfunction referenceSrgb8(linear: number): number { return Math.round(encodeSrgbComponent(linear) * 255); }\n/** Exact 8-bit sRGB quantizer tables; see {@link srgb8Quantizer}. */\nexport interface Srgb8Quantizer {\n /** t[k]: smallest binary64 x in [0,1] with referenceSrgb8(x) ≥ k; t[256] = +∞ sentinel. */\n readonly thresholds: Float64Array;\n /** start[b]: reference code of b/4096, the first code of bucket [b/4096, (b+1)/4096). */\n readonly start: Uint8Array;\n}\nlet srgb8: Srgb8Quantizer | null | undefined;\n/**\n * Exact 8-bit sRGB quantization without evaluating the transfer curve for each sample.\n *\n * The code thresholds are found by bisection on this engine's own `encodeSrgbComponent`. Comparing\n * against them gives Math.round(encodeSrgbComponent(x)·255) for every x, provided that function never\n * decreases (true when pow is monotone). Construction checks every threshold and the 16 neighbouring\n * doubles on each side. If any check fails, the direct transfer is used instead, so output never\n * silently depends on that assumption.\n *\n * A 4097-entry bucket index (x·4096 is exact) gives the starting code. Even the steepest part of the\n * curve (slope 12.92·255) covers less than one code per bucket, so one or two comparisons finish.\n */\nfunction srgb8Quantizer(): Srgb8Quantizer | null {\n if (srgb8 !== undefined) return srgb8;\n const t = new Float64Array(257), bits = new Float64Array(1), word = new BigUint64Array(bits.buffer);\n const step = (x: number, n: number): number => { bits[0] = x; word[0] = word[0]! + BigInt(n); return bits[0]!; };\n for (let k = 1; k < 256; k++) {\n let lo = t[k - 1]!, hi = 1;\n for (;;) {\n const mid = lo + (hi - lo) / 2;\n if (mid === lo || mid === hi) break;\n if (referenceSrgb8(mid) >= k) hi = mid; else lo = mid;\n }\n t[k] = hi;\n }\n t[256] = Infinity;\n let valid = referenceSrgb8(0) === 0 && referenceSrgb8(1) === 255;\n for (let k = 1; valid && k < 256; k++) {\n const x = t[k]!;\n if (!(x > t[k - 1]!) || referenceSrgb8(x) !== k) valid = false;\n for (let n = 1; valid && n <= 16; n++) {\n const below = step(x, -n), above = step(x, n);\n if ((below >= 0 && referenceSrgb8(below) >= k) || (above <= 1 && referenceSrgb8(above) < k)) valid = false;\n }\n }\n const start = new Uint8Array(4097);\n for (let i = 0; valid && i <= 4096; i++) { start[i] = referenceSrgb8(i / 4096); if (i > 0 && start[i]! < start[i - 1]!) valid = false; }\n srgb8 = valid ? { thresholds: t, start } : null;\n return srgb8;\n}\n/** Largest k with t[k] ≤ x for x in [0,1]. */\nfunction quantizeSrgb8(q: Srgb8Quantizer, x: number): number {\n const t = q.thresholds;\n let k = q.start[(x * 4096) | 0]!;\n while (x >= t[k + 1]!) k++;\n return k;\n}\n/** Internal, for tests: the exact quantizer (null when its construction check failed). */\nexport function nativeSrgb8QuantizerForTest(): { quantizer: Srgb8Quantizer | null; quantize(x: number): number } {\n const quantizer = srgb8Quantizer();\n return { quantizer, quantize: (x) => quantizer ? quantizeSrgb8(quantizer, x) : referenceSrgb8(x) };\n}\n/** Per-tile counters for {@link renderSdrRunInto}. `outOfGamut` delays the rejection, as the reference does. */\nexport interface SdrPixelCounts { negative: number; above: number; changed: number; low: number; high: number; outOfGamut: boolean }\n/**\n * Internal SDR kernel on typed arrays, shared by native SDR and RAW development.\n *\n * For `pixelCount` interleaved linear-sRGB pixels starting at `source[start]`, it runs exactly the\n * reference (`calculateSdrRendering`) operations in the same order per pixel: -0 → +0 → rendering\n * exposure → shared tone operator → gamut → sRGB transfer → quantization (nearest, ties up) into\n * `codes[outOffset]`. A gamut rejection is delayed via `counts.outOfGamut`, because the reference\n * finishes the whole tone pass (and its exposure errors) first. `scratch` must hold at least 3\n * values. Not exported from the package.\n */\nexport function renderSdrRunInto(source: Float32Array | Float64Array, start: number, pixelCount: number, profile: SdrRenderingProfile,\n tone: SdrPixelTone, scale: number, maximum: number, codes: Uint8Array | Uint16Array, outOffset: number, scratch: Float64Array, counts: SdrPixelCounts): void {\n const reject = profile.gamutHandling === \"reject-out-of-range\", quantizer = maximum === 255 ? srgb8Quantizer() : null;\n let negative = 0, above = 0, changed = 0, low = 0, high = 0, outOfGamut = false;\n for (let p = 0, i = start, o = outOffset; p < pixelCount; p++, i += 3) {\n // The reference parser normalizes -0 to +0 before exposure.\n const red = source[i]!, green = source[i + 1]!, blue = source[i + 2]!;\n const er = (red === 0 ? 0 : red) * scale, eg = (green === 0 ? 0 : green) * scale, eb = (blue === 0 ? 0 : blue) * scale;\n if (!Number.isFinite(er) || !Number.isFinite(eg) || !Number.isFinite(eb)) throw new InvalidScientificResultError(\"Rendering exposure produced a non-finite sample.\");\n tone(er, eg, eb, scratch);\n for (let c = 0; c < 3; c++, o++) {\n const exposed = c === 0 ? er : c === 1 ? eg : eb;\n if (exposed < 0) negative++;\n if (exposed > 1) above++;\n let mapped = scratch[c]!;\n if (mapped !== exposed) changed++;\n if (mapped === 0) mapped = 0;\n let linear = mapped;\n if (mapped < 0 || mapped > 1) {\n if (reject) outOfGamut = true;\n else if (mapped < 0) { low++; linear = 0; }\n else { high++; linear = 1; }\n }\n // Encoded values are in [0,1]: Math.round is exact nearest-ties-up here.\n codes[o] = quantizer ? quantizeSrgb8(quantizer, linear) : Math.round(encodeSrgbComponent(linear) * maximum);\n }\n }\n counts.negative += negative; counts.above += above; counts.changed += changed; counts.low += low; counts.high += high;\n if (outOfGamut) counts.outOfGamut = true;\n}\n\n/** The reference's output-encoding declaration for the given code maximum. */\nexport function sdrOutputEncoding(maximum: number): SdrRenderingResult[\"outputEncoding\"] {\n return { imageState: \"output-referred-sdr\", colorSpace: \"srgb\", primariesXy: { red: [.64, .33], green: [.30, .60], blue: [.15, .06] },\n whitePointXy: [.3127, .3290], referenceWhiteLuminanceCdM2: 80, codeMinimum: 0, codeMaximum: maximum };\n}\n\n/** A single-use task. No partial output is ever returned, and cancel or dispose stops a late result from being published. */\nexport interface NativeCaptureSdrTask {\n readonly plan: NativeCaptureSdrPlan;\n readonly state: NativeCaptureSdrTaskState;\n readonly completedTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n /** Hands over the only copy of the output buffer, once. Dispose cannot take back a buffer already handed over. */\n takeOutput(): NativeCaptureSdrOutput;\n}\n/** Creates a single-use task. Limits are checked before any buffer is allocated or tile is read. */\nexport function createNativeCaptureSdrTask(input: NativeCaptureSdrInput, provider: NativeCaptureSdrProvider): NativeCaptureSdrTask {\n const plan = calculateNativeCaptureSdrPlan(input);\n if (!provider || typeof provider.readTile !== \"function\" || typeof provider.yieldControl !== \"function\") {\n throw new InvalidConfigurationError(\"Native SDR requires a tile reader and event-loop yield.\");\n }\n if (provider.onProgress !== undefined && typeof provider.onProgress !== \"function\") throw new InvalidConfigurationError(\"Native SDR onProgress must be a function.\");\n // Also capture the callback functions now, so later app changes cannot swap the reader mid-task.\n const readTile = provider.readTile.bind(provider), yieldControl = provider.yieldControl.bind(provider),\n onProgress = provider.onProgress?.bind(provider);\n const plane = plan.capture.planes.find(p => p.id === plan.sourcePlaneId)!;\n if (plane.storage.kind === \"inline-float64\") throw new InvalidConfigurationError(\"External native source required.\");\n const storage = plane.storage, abort = new AbortController();\n let state: NativeCaptureSdrTaskState = \"ready\", count = 0, output: NativeCaptureSdrOutput | null = null;\n let codes: Uint8Array | Uint16Array | null = null;\n function release(): void { codes?.fill(0); codes = null; output = null; }\n function checkActive(): void {\n if (abort.signal.aborted) throw new InvalidConfigurationError(\"Native SDR task cancelled/disposed; no output available.\");\n }\n return {\n plan,\n get state(): NativeCaptureSdrTaskState { return state; },\n get completedTileCount(): number { return count; },\n async run(): Promise<void> {\n if (state !== \"ready\") throw new InvalidConfigurationError(\"Native SDR task is single-use.\");\n state = \"running\";\n try {\n codes = plan.profile.bitDepth === 8 ? new Uint8Array(plan.outputBytes) : new Uint16Array(plan.outputBytes / 2);\n const diagnostics: SdrRenderingResult[\"diagnostics\"] = { renderingNegativeSampleCount: 0, renderingAboveReferenceSampleCount: 0,\n toneChangedSampleCount: 0, gamutClippedLowSampleCount: 0, gamutClippedHighSampleCount: 0, captureSaturation: \"not-consumed\" };\n // Same scale expression and code range as the reference. The plan already rejected a scale that cannot be represented.\n const scale = 2 ** plan.profile.renderingExposureEv / plane.referenceWhiteValue, maximum = 2 ** plan.profile.bitDepth - 1,\n tone = prepareSdrPixelTone(plan.profile);\n for (let y = 0; y < plane.pixelHeight; y += NATIVE_CAPTURE_SDR_LIMITS.tileHeight) {\n for (let x = 0; x < plane.pixelWidth; x += NATIVE_CAPTURE_SDR_LIMITS.tileWidth) {\n checkActive();\n const request = Object.freeze({ captureId: plan.capture.captureId, sourcePlaneId: plane.id,\n artifactId: storage.artifactId, sha256: storage.sha256, x, y,\n width: Math.min(NATIVE_CAPTURE_SDR_LIMITS.tileWidth, plane.pixelWidth - x),\n height: Math.min(NATIVE_CAPTURE_SDR_LIMITS.tileHeight, plane.pixelHeight - y) });\n {\n const tile = await readTile(request, abort.signal);\n checkActive();\n // Diagnostics are aggregated only after the whole tile renders.\n renderTileInto(tile, request, plane, plan.profile, tone, scale, maximum, codes!, diagnostics);\n count++;\n onProgress?.({ completedTileCount: count, totalTileCount: plan.tileCount });\n }\n // Do not keep tile or reference arrays past the next tile read or host yield.\n await yieldControl(abort.signal);\n checkActive();\n }\n }\n output = { plan, integerSamples: codes!, diagnostics, outputEncoding: sdrOutputEncoding(maximum),\n displayAdaptation: { kind: \"external-platform\", applied: false, displayCapabilities: \"unknown\" } };\n state = \"completed\";\n } catch (error) {\n release();\n if (!abort.signal.aborted) { state = \"failed\"; abort.abort(); }\n throw error;\n }\n },\n cancel(): void {\n if (state === \"ready\" || state === \"running\" || state === \"completed\") { state = \"cancelled\"; abort.abort(); release(); }\n },\n dispose(): void { if (state !== \"transferred\") { state = \"disposed\"; abort.abort(); release(); } },\n takeOutput(): NativeCaptureSdrOutput {\n if (state !== \"completed\" || !output) throw new InvalidConfigurationError(\"Native SDR output is unavailable.\");\n const result = output; output = null; codes = null; state = \"transferred\";\n return result;\n }\n };\n}\n"]}
1
+ {"version":3,"file":"native-capture-sdr.js","sourceRoot":"","sources":["../../src/output/native-capture-sdr.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;GAGG;AACH,OAAO,EAAE,qBAAqB,EAAkD,MAAM,iCAAiC,CAAC;AACxH,OAAO,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACjG,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAC/F,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,8BAA8B,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7F,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAChE,OAAO,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAwE,MAAM,oBAAoB,CAAC;AAEzJ,MAAM,CAAC,MAAM,iCAAiC,GAAG,OAAgB,CAAC;AAClE,8HAA8H;AAC9H,MAAM,CAAC,MAAM,yBAAyB,GAAG,MAAM,CAAC,MAA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AAC;oBAAC,KAAK,CAAC,KAAK,EAAE,CAAC;gBAAC,CAAC;gBAC/D,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;QACD,MAAM;YACJ,IAAI,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,WAAW,EAAE,CAAC;gBAAC,KAAK,GAAG,WAAW,CAAC;gBAAC,KAAK,CAAC,KAAK,EAAE,CAAC;gBAAC,OAAO,EAAE,CAAC;YAAC,CAAC;QAC3H,CAAC;QACD,OAAO,KAAW,IAAI,KAAK,KAAK,aAAa,EAAE,CAAC;YAAC,KAAK,GAAG,UAAU,CAAC;YAAC,KAAK,CAAC,KAAK,EAAE,CAAC;YAAC,OAAO,EAAE,CAAC;QAAC,CAAC,CAAC,CAAC;QAClG,UAAU;YACR,IAAI,KAAK,KAAK,WAAW,IAAI,CAAC,MAAM;gBAAE,MAAM,IAAI,yBAAyB,CAAC,mCAAmC,CAAC,CAAC;YAC/G,MAAM,MAAM,GAAG,MAAM,CAAC;YAAC,MAAM,GAAG,IAAI,CAAC;YAAC,KAAK,GAAG,IAAI,CAAC;YAAC,KAAK,GAAG,aAAa,CAAC;YAC1E,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native SDR rendering of large captures, tile by tile, within fixed memory limits. The engine\n * owns the task; the caller supplies the pixel tiles. See docs/NATIVE_CAPTURE_SDR.md.\n */\nimport { parseSimulatedCapture, type SimulatedCapture, type CaptureLinearPlane } from \"../capture/simulated-capture.js\";\nimport { LINEAR_CAPTURE_RGB_PROFILE, resolveCaptureColorModel } from \"../color/capture-color.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { requireAllowlistedRecord, requirePublicOpaqueId } from \"../core/record-validation.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit } from \"../core/pixel-limits.js\";\nimport { encodeSrgbComponent } from \"../color/srgb-transfer.js\";\nimport { InvalidScientificResultError } from \"../core/validation.js\";\nimport { parseSdrRenderingProfile, prepareSdrPixelTone, type SdrPixelTone, type SdrRenderingProfile, type SdrRenderingResult } from \"./sdr-rendering.js\";\n\nexport const NATIVE_CAPTURE_SDR_SCHEMA_VERSION = \"0.1.0\" as const;\n/** `maximumPixels` is the default pixel limit; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`. */\nexport const NATIVE_CAPTURE_SDR_LIMITS = Object.freeze({ maximumPixels: 24_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS,\n maximumDimension: 16_384, tileWidth: 256, tileHeight: 32, maximumTileStorageSamples: 32_768 });\n/** Input. The capture holds only metadata; float samples are read from external storage. Samples must already have colour and white balance applied. */\nexport interface NativeCaptureSdrInput {\n capture: SimulatedCapture;\n sourcePlaneId: string;\n outputImageStateId: string;\n profile: SdrRenderingProfile;\n /** Limit on the size of the integer output. Checked before anything is allocated or any tile is read. */\n maximumOutputBytes: number;\n /**\n * Optional opt-in pixel limit for large captures: an integer from 1 to `NATIVE_CAPTURE_SDR_LIMITS.ceilingPixels`.\n * Default `NATIVE_CAPTURE_SDR_LIMITS.maximumPixels` (24 000 000). `maximumOutputBytes` still applies.\n */\n maximumPixels?: number;\n}\n/** Tile request. Coordinates are absolute in the selected plane's declared pixel grid, never relative to a crop. */\nexport interface NativeCaptureSdrTileRequest {\n captureId: string;\n sourcePlaneId: string;\n artifactId: string;\n sha256: string;\n x: number; y: number; width: number; height: number;\n}\n/** A tile returned by the provider. It belongs to this call alone; do not change or reuse it. Row padding is not image data. */\nexport interface NativeCaptureSdrTile extends NativeCaptureSdrTileRequest {\n rowStrideSamples: number;\n samples: Float32Array | Float64Array;\n}\n/** Supplies tiles, one call at a time. The caller must release decoder and GPU resources when the task aborts or finishes. */\nexport interface NativeCaptureSdrProvider {\n readTile(request: Readonly<NativeCaptureSdrTileRequest>, signal: AbortSignal): Promise<NativeCaptureSdrTile>;\n /** Must yield to the host event loop, so cancellation and input events can run between tiles. */\n yieldControl(signal: AbortSignal): Promise<void>;\n /**\n * Optional progress observer, called synchronously after each committed tile. It cannot change\n * output; an exception it throws fails the task like any other error.\n */\n onProgress?(progress: NativeTaskProgress): void;\n}\n/** Tile progress of a native task: `completedTileCount` of `totalTileCount` tiles are committed. */\nexport interface NativeTaskProgress { readonly completedTileCount: number; readonly totalTileCount: number }\nexport interface NativeCaptureSdrPlan {\n schemaVersion: typeof NATIVE_CAPTURE_SDR_SCHEMA_VERSION;\n capture: SimulatedCapture;\n sourcePlaneId: string;\n outputImageStateId: string;\n profile: SdrRenderingProfile;\n outputBytes: number;\n /** Upper bound on the bytes held in working arrays. It is not peak JavaScript heap, GPU or process memory, and does not show that a device can run the task. */\n maximumScratchPayloadBytes: number;\n tileCount: number;\n}\nexport interface NativeCaptureSdrOutput {\n plan: NativeCaptureSdrPlan;\n /** Packed RGB codes in row-major order, owned by the caller. 16-bit codes are numbers, not bytes in a particular byte order. */\n integerSamples: Uint8Array | Uint16Array;\n diagnostics: SdrRenderingResult[\"diagnostics\"];\n outputEncoding: SdrRenderingResult[\"outputEncoding\"];\n displayAdaptation: SdrRenderingResult[\"displayAdaptation\"];\n}\nexport type NativeCaptureSdrTaskState = \"ready\" | \"running\" | \"completed\" | \"cancelled\" | \"failed\" | \"disposed\" | \"transferred\";\n\n/** Validates the input and plans the task, including its limits, without reading samples or allocating an image. */\nexport function calculateNativeCaptureSdrPlan(input: NativeCaptureSdrInput): NativeCaptureSdrPlan {\n const r = requireAllowlistedRecord(input, [\"capture\", \"sourcePlaneId\", \"outputImageStateId\", \"profile\", \"maximumOutputBytes\", \"maximumPixels\"], \"Invalid native SDR input.\");\n const maximumPixels = resolveRaisedLimit(r.maximumPixels, NATIVE_CAPTURE_SDR_LIMITS.maximumPixels, NATIVE_CAPTURE_SDR_LIMITS.ceilingPixels,\n \"Native SDR maximumPixels must be an integer from 1 to \" + NATIVE_CAPTURE_SDR_LIMITS.ceilingPixels + \".\");\n // Only external-storage manifests are accepted, so unrelated inline sample buffers are never copied.\n const c = r.capture as SimulatedCapture | undefined;\n if (!c || !Array.isArray(c.planes) || c.planes.length > 32 || c.planes.some(p => !p || p.storage?.kind === \"inline-float64\")) {\n throw new InvalidConfigurationError(\"Native SDR requires external-only capture manifests.\");\n }\n const capture = parseSimulatedCapture(c);\n const sourcePlaneId = requirePublicOpaqueId(r.sourcePlaneId, \"Invalid native SDR plane ID.\");\n const outputImageStateId = requirePublicOpaqueId(r.outputImageStateId, \"Invalid native SDR output state ID.\");\n const plane = capture.planes.find(p => p.id === sourcePlaneId);\n const white = resolveCaptureColorModel().referenceWhiteXyz;\n if (!plane || plane.imageState !== \"color-transformed-linear-rgb\" ||\n plane.colorProfile?.id !== LINEAR_CAPTURE_RGB_PROFILE.id || plane.colorProfile.version !== LINEAR_CAPTURE_RGB_PROFILE.version ||\n plane.encodingReferenceWhiteXyz?.x !== white.x || plane.encodingReferenceWhiteXyz.y !== white.y || plane.encodingReferenceWhiteXyz.z !== white.z ||\n plane.whiteBalanceApplication === \"intent-only\" || (plane.whiteBalanceApplication === \"not-applicable\" && capture.whiteBalanceIntent !== null) ||\n capture.planes.some(p => p.imageStateId === outputImageStateId)) {\n throw new InvalidConfigurationError(\"Native SDR requires exact resolved linear-sRGB/D65 and a new output state ID.\");\n }\n const pixels = plane.pixelWidth * plane.pixelHeight, profile = parseSdrRenderingProfile(r.profile);\n const outputBytes = pixels * 3 * (profile.bitDepth / 8);\n const scale = 2 ** profile.renderingExposureEv / plane.referenceWhiteValue;\n if (!Number.isFinite(scale) || scale <= 0) throw new InvalidConfigurationError(\"Native SDR scale is unrepresentable.\");\n if (pixels > maximumPixels || plane.pixelWidth > NATIVE_CAPTURE_SDR_LIMITS.maximumDimension ||\n plane.pixelHeight > NATIVE_CAPTURE_SDR_LIMITS.maximumDimension || typeof r.maximumOutputBytes !== \"number\" ||\n !Number.isSafeInteger(r.maximumOutputBytes) || r.maximumOutputBytes < outputBytes) {\n throw new InvalidConfigurationError(\"Native SDR raster/output exceeds declared admission limits.\");\n }\n // A cautious declared bound, kept from the earlier executor that called the reference renderer: provider payload +\n // packed copy + reference parser copy + four reference output arrays. The typed kernel itself keeps only the provider payload.\n const maximumScratchPayloadBytes = NATIVE_CAPTURE_SDR_LIMITS.maximumTileStorageSamples * 8 +\n NATIVE_CAPTURE_SDR_LIMITS.tileWidth * NATIVE_CAPTURE_SDR_LIMITS.tileHeight * 3 * 8 * 6;\n return freezeOwnedData({ schemaVersion: NATIVE_CAPTURE_SDR_SCHEMA_VERSION, capture, sourcePlaneId, outputImageStateId, profile,\n outputBytes, maximumScratchPayloadBytes,\n tileCount: Math.ceil(plane.pixelWidth / NATIVE_CAPTURE_SDR_LIMITS.tileWidth) * Math.ceil(plane.pixelHeight / NATIVE_CAPTURE_SDR_LIMITS.tileHeight) });\n}\n\n/**\n * Tile checks shared by every native SDR backend: identity, precision, row stride, storage and valid\n * input values. Returns a view of the provider's samples (not a copy). Padding is not checked for\n * finite values. Not exported from the package.\n */\nexport function validateNativeCaptureSdrTile(tile: NativeCaptureSdrTile, request: NativeCaptureSdrTileRequest,\n plane: CaptureLinearPlane): { source: Float32Array | Float64Array; stride: number } {\n const r = requireAllowlistedRecord(tile, [\"captureId\", \"sourcePlaneId\", \"artifactId\", \"sha256\", \"x\", \"y\", \"width\", \"height\", \"rowStrideSamples\", \"samples\"], \"Invalid native SDR tile.\");\n for (const key of Object.keys(request) as (keyof NativeCaptureSdrTileRequest)[]) {\n if (r[key] !== request[key]) throw new InvalidConfigurationError(\"Native SDR tile identity/rectangle mismatch.\");\n }\n const samples = r.samples;\n const expectedType = plane.storage.kind === \"external-float32\" ? Float32Array : Float64Array;\n if (!(samples instanceof expectedType) || !(samples.buffer instanceof ArrayBuffer) ||\n samples.buffer.byteLength > NATIVE_CAPTURE_SDR_LIMITS.maximumTileStorageSamples * expectedType.BYTES_PER_ELEMENT ||\n typeof r.rowStrideSamples !== \"number\" || !Number.isSafeInteger(r.rowStrideSamples) || r.rowStrideSamples < request.width * 3 ||\n samples.length !== r.rowStrideSamples * request.height || samples.length > NATIVE_CAPTURE_SDR_LIMITS.maximumTileStorageSamples) {\n throw new InvalidConfigurationError(\"Native SDR tile precision/stride/storage mismatch.\");\n }\n const source: Float32Array | Float64Array = samples, stride = r.rowStrideSamples, rowLength = request.width * 3;\n // Check every image sample (not padding) against the reference renderer's input rules before any rendering.\n for (let y = 0; y < request.height; y++) {\n for (let i = y * stride, end = i + rowLength; i < end; i++) {\n if (!Number.isFinite(source[i]!)) throw new InvalidConfigurationError(\"Unsupported SDR input domain/raster.\");\n }\n }\n return { source, stride };\n}\n\ntype NativeSdrDiagnosticCounts = Omit<SdrRenderingResult[\"diagnostics\"], \"captureSaturation\">;\n/**\n * Fast tile kernel on typed arrays. It applies the same equations as the SDR reference renderer\n * (`calculateSdrRendering`), with the same floating-point operation order per sample and the same\n * error precedence, and writes integer codes straight into the packed output.\n *\n * Steps: input check → rendering exposure → tone → gamut → sRGB transfer → quantization (round to\n * nearest, ties up). `test/native-capture-sdr-kernel-parity.test.ts` shows that codes and diagnostics\n * match the unchanged reference exactly.\n */\nfunction renderTileInto(tile: NativeCaptureSdrTile, request: NativeCaptureSdrTileRequest, plane: CaptureLinearPlane,\n profile: SdrRenderingProfile, tone: SdrPixelTone, scale: number, maximum: number, codes: Uint8Array | Uint16Array, diagnostics: NativeSdrDiagnosticCounts): void {\n const { source, stride } = validateNativeCaptureSdrTile(tile, request, plane);\n // Tiling is safe because every supported rendering operation works on one pixel at a time.\n const outputRowStride = plane.pixelWidth * 3;\n const counts = { negative: 0, above: 0, changed: 0, low: 0, high: 0, outOfGamut: false }, scratch = new Float64Array(3);\n for (let y = 0; y < request.height; y++) {\n renderSdrRunInto(source, y * stride, request.width, profile, tone, scale, maximum, codes, (request.y + y) * outputRowStride + request.x * 3, scratch, counts);\n }\n if (counts.outOfGamut) throw new InvalidConfigurationError(\"Tone output exceeds the declared SDR gamut range.\");\n diagnostics.renderingNegativeSampleCount += counts.negative; diagnostics.renderingAboveReferenceSampleCount += counts.above;\n diagnostics.toneChangedSampleCount += counts.changed; diagnostics.gamutClippedLowSampleCount += counts.low; diagnostics.gamutClippedHighSampleCount += counts.high;\n}\n/** Reference 8-bit code of a linear sample in [0,1]: Math.round(encodeSrgbComponent(x)·255). */\nfunction referenceSrgb8(linear: number): number { return Math.round(encodeSrgbComponent(linear) * 255); }\n/** Exact 8-bit sRGB quantizer tables; see {@link srgb8Quantizer}. */\nexport interface Srgb8Quantizer {\n /** t[k]: smallest binary64 x in [0,1] with referenceSrgb8(x) ≥ k; t[256] = +∞ sentinel. */\n readonly thresholds: Float64Array;\n /** start[b]: reference code of b/4096, the first code of bucket [b/4096, (b+1)/4096). */\n readonly start: Uint8Array;\n}\nlet srgb8: Srgb8Quantizer | null | undefined;\n/**\n * Exact 8-bit sRGB quantization without evaluating the transfer curve for each sample.\n *\n * The code thresholds are found by bisection on this engine's own `encodeSrgbComponent`. Comparing\n * against them gives Math.round(encodeSrgbComponent(x)·255) for every x, provided that function never\n * decreases (true when pow is monotone). Construction checks every threshold and the 16 neighbouring\n * doubles on each side. If any check fails, the direct transfer is used instead, so output never\n * silently depends on that assumption.\n *\n * A 4097-entry bucket index (x·4096 is exact) gives the starting code. Even the steepest part of the\n * curve (slope 12.92·255) covers less than one code per bucket, so one or two comparisons finish.\n */\nfunction srgb8Quantizer(): Srgb8Quantizer | null {\n if (srgb8 !== undefined) return srgb8;\n const t = new Float64Array(257), bits = new Float64Array(1), word = new BigUint64Array(bits.buffer);\n const step = (x: number, n: number): number => { bits[0] = x; word[0] = word[0]! + BigInt(n); return bits[0]!; };\n for (let k = 1; k < 256; k++) {\n let lo = t[k - 1]!, hi = 1;\n for (;;) {\n const mid = lo + (hi - lo) / 2;\n if (mid === lo || mid === hi) break;\n if (referenceSrgb8(mid) >= k) hi = mid; else lo = mid;\n }\n t[k] = hi;\n }\n t[256] = Infinity;\n let valid = referenceSrgb8(0) === 0 && referenceSrgb8(1) === 255;\n for (let k = 1; valid && k < 256; k++) {\n const x = t[k]!;\n if (!(x > t[k - 1]!) || referenceSrgb8(x) !== k) valid = false;\n for (let n = 1; valid && n <= 16; n++) {\n const below = step(x, -n), above = step(x, n);\n if ((below >= 0 && referenceSrgb8(below) >= k) || (above <= 1 && referenceSrgb8(above) < k)) valid = false;\n }\n }\n const start = new Uint8Array(4097);\n for (let i = 0; valid && i <= 4096; i++) { start[i] = referenceSrgb8(i / 4096); if (i > 0 && start[i]! < start[i - 1]!) valid = false; }\n srgb8 = valid ? { thresholds: t, start } : null;\n return srgb8;\n}\n/** Largest k with t[k] ≤ x for x in [0,1]. */\nfunction quantizeSrgb8(q: Srgb8Quantizer, x: number): number {\n const t = q.thresholds;\n let k = q.start[(x * 4096) | 0]!;\n while (x >= t[k + 1]!) k++;\n return k;\n}\n/** Internal, for tests: the exact quantizer (null when its construction check failed). */\nexport function nativeSrgb8QuantizerForTest(): { quantizer: Srgb8Quantizer | null; quantize(x: number): number } {\n const quantizer = srgb8Quantizer();\n return { quantizer, quantize: (x) => quantizer ? quantizeSrgb8(quantizer, x) : referenceSrgb8(x) };\n}\n/** Per-tile counters for {@link renderSdrRunInto}. `outOfGamut` delays the rejection, as the reference does. */\nexport interface SdrPixelCounts { negative: number; above: number; changed: number; low: number; high: number; outOfGamut: boolean }\n/**\n * Internal SDR kernel on typed arrays, shared by native SDR and RAW development.\n *\n * For `pixelCount` interleaved linear-sRGB pixels starting at `source[start]`, it runs exactly the\n * reference (`calculateSdrRendering`) operations in the same order per pixel: -0 → +0 → rendering\n * exposure → shared tone operator → gamut → sRGB transfer → quantization (nearest, ties up) into\n * `codes[outOffset]`. A gamut rejection is delayed via `counts.outOfGamut`, because the reference\n * finishes the whole tone pass (and its exposure errors) first. `scratch` must hold at least 3\n * values. Not exported from the package.\n */\nexport function renderSdrRunInto(source: Float32Array | Float64Array, start: number, pixelCount: number, profile: SdrRenderingProfile,\n tone: SdrPixelTone, scale: number, maximum: number, codes: Uint8Array | Uint16Array, outOffset: number, scratch: Float64Array, counts: SdrPixelCounts): void {\n const reject = profile.gamutHandling === \"reject-out-of-range\", quantizer = maximum === 255 ? srgb8Quantizer() : null;\n let negative = 0, above = 0, changed = 0, low = 0, high = 0, outOfGamut = false;\n for (let p = 0, i = start, o = outOffset; p < pixelCount; p++, i += 3) {\n // The reference parser normalizes -0 to +0 before exposure.\n const red = source[i]!, green = source[i + 1]!, blue = source[i + 2]!;\n const er = (red === 0 ? 0 : red) * scale, eg = (green === 0 ? 0 : green) * scale, eb = (blue === 0 ? 0 : blue) * scale;\n if (!Number.isFinite(er) || !Number.isFinite(eg) || !Number.isFinite(eb)) throw new InvalidScientificResultError(\"Rendering exposure produced a non-finite sample.\");\n tone(er, eg, eb, scratch);\n for (let c = 0; c < 3; c++, o++) {\n const exposed = c === 0 ? er : c === 1 ? eg : eb;\n if (exposed < 0) negative++;\n if (exposed > 1) above++;\n let mapped = scratch[c]!;\n if (mapped !== exposed) changed++;\n if (mapped === 0) mapped = 0;\n let linear = mapped;\n if (mapped < 0 || mapped > 1) {\n if (reject) outOfGamut = true;\n else if (mapped < 0) { low++; linear = 0; }\n else { high++; linear = 1; }\n }\n // Encoded values are in [0,1]: Math.round is exact nearest-ties-up here.\n codes[o] = quantizer ? quantizeSrgb8(quantizer, linear) : Math.round(encodeSrgbComponent(linear) * maximum);\n }\n }\n counts.negative += negative; counts.above += above; counts.changed += changed; counts.low += low; counts.high += high;\n if (outOfGamut) counts.outOfGamut = true;\n}\n\n/** The reference's output-encoding declaration for the given code maximum. */\nexport function sdrOutputEncoding(maximum: number): SdrRenderingResult[\"outputEncoding\"] {\n return { imageState: \"output-referred-sdr\", colorSpace: \"srgb\", primariesXy: { red: [.64, .33], green: [.30, .60], blue: [.15, .06] },\n whitePointXy: [.3127, .3290], referenceWhiteLuminanceCdM2: 80, codeMinimum: 0, codeMaximum: maximum };\n}\n\n/** A single-use task. No partial output is ever returned, and cancel or dispose stops a late result from being published. */\nexport interface NativeCaptureSdrTask {\n readonly plan: NativeCaptureSdrPlan;\n readonly state: NativeCaptureSdrTaskState;\n readonly completedTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n /** Hands over the only copy of the output buffer, once. Dispose cannot take back a buffer already handed over. */\n takeOutput(): NativeCaptureSdrOutput;\n}\n/** Creates a single-use task. Limits are checked before any buffer is allocated or tile is read. */\nexport function createNativeCaptureSdrTask(input: NativeCaptureSdrInput, provider: NativeCaptureSdrProvider): NativeCaptureSdrTask {\n const plan = calculateNativeCaptureSdrPlan(input);\n if (!provider || typeof provider.readTile !== \"function\" || typeof provider.yieldControl !== \"function\") {\n throw new InvalidConfigurationError(\"Native SDR requires a tile reader and event-loop yield.\");\n }\n if (provider.onProgress !== undefined && typeof provider.onProgress !== \"function\") throw new InvalidConfigurationError(\"Native SDR onProgress must be a function.\");\n // Also capture the callback functions now, so later app changes cannot swap the reader mid-task.\n const readTile = provider.readTile.bind(provider), yieldControl = provider.yieldControl.bind(provider),\n onProgress = provider.onProgress?.bind(provider);\n const plane = plan.capture.planes.find(p => p.id === plan.sourcePlaneId)!;\n if (plane.storage.kind === \"inline-float64\") throw new InvalidConfigurationError(\"External native source required.\");\n const storage = plane.storage, abort = new AbortController();\n let state: NativeCaptureSdrTaskState = \"ready\", count = 0, output: NativeCaptureSdrOutput | null = null;\n let codes: Uint8Array | Uint16Array | null = null;\n function release(): void { codes?.fill(0); codes = null; output = null; }\n function checkActive(): void {\n if (abort.signal.aborted) throw new InvalidConfigurationError(\"Native SDR task cancelled/disposed; no output available.\");\n }\n return {\n plan,\n get state(): NativeCaptureSdrTaskState { return state; },\n get completedTileCount(): number { return count; },\n async run(): Promise<void> {\n if (state !== \"ready\") throw new InvalidConfigurationError(\"Native SDR task is single-use.\");\n state = \"running\";\n try {\n codes = plan.profile.bitDepth === 8 ? new Uint8Array(plan.outputBytes) : new Uint16Array(plan.outputBytes / 2);\n const diagnostics: SdrRenderingResult[\"diagnostics\"] = { renderingNegativeSampleCount: 0, renderingAboveReferenceSampleCount: 0,\n toneChangedSampleCount: 0, gamutClippedLowSampleCount: 0, gamutClippedHighSampleCount: 0, captureSaturation: \"not-consumed\" };\n // Same scale expression and code range as the reference. The plan already rejected a scale that cannot be represented.\n const scale = 2 ** plan.profile.renderingExposureEv / plane.referenceWhiteValue, maximum = 2 ** plan.profile.bitDepth - 1,\n tone = prepareSdrPixelTone(plan.profile);\n for (let y = 0; y < plane.pixelHeight; y += NATIVE_CAPTURE_SDR_LIMITS.tileHeight) {\n for (let x = 0; x < plane.pixelWidth; x += NATIVE_CAPTURE_SDR_LIMITS.tileWidth) {\n checkActive();\n const request = Object.freeze({ captureId: plan.capture.captureId, sourcePlaneId: plane.id,\n artifactId: storage.artifactId, sha256: storage.sha256, x, y,\n width: Math.min(NATIVE_CAPTURE_SDR_LIMITS.tileWidth, plane.pixelWidth - x),\n height: Math.min(NATIVE_CAPTURE_SDR_LIMITS.tileHeight, plane.pixelHeight - y) });\n {\n const tile = await readTile(request, abort.signal);\n checkActive();\n // Diagnostics are aggregated only after the whole tile renders.\n renderTileInto(tile, request, plane, plan.profile, tone, scale, maximum, codes!, diagnostics);\n count++;\n onProgress?.({ completedTileCount: count, totalTileCount: plan.tileCount });\n }\n // Do not keep tile or reference arrays past the next tile read or host yield.\n await yieldControl(abort.signal);\n checkActive();\n }\n }\n output = { plan, integerSamples: codes!, diagnostics, outputEncoding: sdrOutputEncoding(maximum),\n displayAdaptation: { kind: \"external-platform\", applied: false, displayCapabilities: \"unknown\" } };\n state = \"completed\";\n } catch (error) {\n release();\n if (!abort.signal.aborted) { state = \"failed\"; abort.abort(); }\n throw error;\n }\n },\n cancel(): void {\n if (state === \"ready\" || state === \"running\" || state === \"completed\") { state = \"cancelled\"; abort.abort(); release(); }\n },\n dispose(): void { if (state !== \"transferred\") { state = \"disposed\"; abort.abort(); release(); } },\n takeOutput(): NativeCaptureSdrOutput {\n if (state !== \"completed\" || !output) throw new InvalidConfigurationError(\"Native SDR output is unavailable.\");\n const result = output; output = null; codes = null; state = \"transferred\";\n return result;\n }\n };\n}\n"]}
@@ -1,8 +1,12 @@
1
1
  export declare const PNG_ENCODER_ID: "photivra-png-rgb-v1";
2
- /** Limits, checked before allocation. 100 MP (megapixels) of 16-bit RGB is about 600 MB of filtered scanlines. */
2
+ /**
3
+ * Limits, checked before allocation. 100 MP (megapixels) of 16-bit RGB is about 600 MB of filtered scanlines.
4
+ * `maximumPixels` is the default; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`.
5
+ */
3
6
  export declare const PNG_ENCODER_LIMITS: Readonly<{
4
7
  maximumDimension: 65535;
5
8
  maximumPixels: 100000000;
9
+ ceilingPixels: 134217728;
6
10
  maximumIccProfileBytes: 4000000;
7
11
  }>;
8
12
  /** ITU-T H.273 ColourPrimaries: bt709 = 1 (also sRGB), display-p3 = 12 (P3 primaries with D65 white; W3C CSS Color 4, also SMPTE EG 432-1), bt2020 = 9 (BT.2020). */
@@ -49,6 +53,11 @@ export interface PngEncodeInput {
49
53
  compression?: "stored" | "fixed-huffman";
50
54
  /** PNG filter type 0..4 for every row, or the specification's minimum-sum-of-absolute-differences heuristic. Default "adaptive". */
51
55
  filter?: "none" | "sub" | "up" | "average" | "paeth" | "adaptive";
56
+ /**
57
+ * Optional opt-in pixel limit: an integer from 1 to `PNG_ENCODER_LIMITS.ceilingPixels`. Default
58
+ * `PNG_ENCODER_LIMITS.maximumPixels` (100 000 000). It does not change the encoded bytes.
59
+ */
60
+ maximumPixels?: number;
52
61
  }
53
62
  /** CRC-32 (ISO 3309 / ITU-T V.42 polynomial 0xEDB88320, reflected), as specified for PNG chunks. */
54
63
  export declare function pngCrc32(data: Uint8Array, initial?: number): number;
@@ -19,9 +19,14 @@
19
19
  * @see docs/IMPORT_AND_PNG.md for chunk layouts, code points and limits.
20
20
  */
21
21
  import { InvalidConfigurationError } from "../core/configuration-error.js";
22
+ import { FULL_RESOLUTION_CEILING_PIXELS, resolveRaisedLimit } from "../core/pixel-limits.js";
22
23
  export const PNG_ENCODER_ID = "photivra-png-rgb-v1";
23
- /** Limits, checked before allocation. 100 MP (megapixels) of 16-bit RGB is about 600 MB of filtered scanlines. */
24
- export const PNG_ENCODER_LIMITS = Object.freeze({ maximumDimension: 65535, maximumPixels: 100_000_000, maximumIccProfileBytes: 4_000_000 });
24
+ /**
25
+ * Limits, checked before allocation. 100 MP (megapixels) of 16-bit RGB is about 600 MB of filtered scanlines.
26
+ * `maximumPixels` is the default; a request may raise it with its own `maximumPixels`, up to `ceilingPixels`.
27
+ */
28
+ export const PNG_ENCODER_LIMITS = Object.freeze({ maximumDimension: 65535, maximumPixels: 100_000_000, ceilingPixels: FULL_RESOLUTION_CEILING_PIXELS,
29
+ maximumIccProfileBytes: 4_000_000 });
25
30
  // Maps, not plain objects: a lookup must never reach Object.prototype names such as "constructor" or "toString".
26
31
  const PRIMARIES = new Map([["bt709", 1], ["display-p3", 12], ["bt2020", 9]]);
27
32
  const TRANSFER = new Map([["bt709", 1], ["linear", 8], ["srgb", 13]]);
@@ -311,10 +316,11 @@ export function serializePngImage(input) {
311
316
  if (input === null || typeof input !== "object")
312
317
  fail("input must be an object.");
313
318
  for (const key of Object.keys(input))
314
- if (!["width", "height", "bitDepth", "samples", "colourEncoding", "masteringDisplay", "contentLightLevel", "compression", "filter"].includes(key))
319
+ if (!["width", "height", "bitDepth", "samples", "colourEncoding", "masteringDisplay", "contentLightLevel", "compression", "filter", "maximumPixels"].includes(key))
315
320
  fail("unknown input field.");
316
321
  const { width, height, bitDepth, samples } = input;
317
- if (![width, height].every((v) => Number.isSafeInteger(v) && v >= 1 && v <= PNG_ENCODER_LIMITS.maximumDimension) || width * height > PNG_ENCODER_LIMITS.maximumPixels)
322
+ const maximumPixels = resolveRaisedLimit(input.maximumPixels, PNG_ENCODER_LIMITS.maximumPixels, PNG_ENCODER_LIMITS.ceilingPixels, "PNG encoder: maximumPixels must be an integer from 1 to " + PNG_ENCODER_LIMITS.ceilingPixels + ".");
323
+ if (![width, height].every((v) => Number.isSafeInteger(v) && v >= 1 && v <= PNG_ENCODER_LIMITS.maximumDimension) || width * height > maximumPixels)
318
324
  fail("dimensions are out of range.");
319
325
  if (bitDepth !== 8 && bitDepth !== 16)
320
326
  fail("bitDepth must be 8 or 16.");