@photivra/engine 2.21.0 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +118 -1
  2. package/CITATION.cff +1 -1
  3. package/README.md +6 -6
  4. package/SECURITY.md +1 -1
  5. package/THIRD_PARTY.md +11 -0
  6. package/dist/capture/c2pa-embed.d.ts +116 -0
  7. package/dist/capture/c2pa-embed.js +493 -0
  8. package/dist/capture/c2pa-embed.js.map +1 -0
  9. package/dist/capture/dng-import.d.ts +73 -8
  10. package/dist/capture/dng-import.js +315 -80
  11. package/dist/capture/dng-import.js.map +1 -1
  12. package/dist/capture/dng-opcodes.d.ts +96 -0
  13. package/dist/capture/dng-opcodes.js +391 -0
  14. package/dist/capture/dng-opcodes.js.map +1 -0
  15. package/dist/capture/dng-profile-maps.d.ts +99 -0
  16. package/dist/capture/dng-profile-maps.js +381 -0
  17. package/dist/capture/dng-profile-maps.js.map +1 -0
  18. package/dist/capture/dng-stage-image.d.ts +23 -0
  19. package/dist/capture/dng-stage-image.js +65 -0
  20. package/dist/capture/dng-stage-image.js.map +1 -0
  21. package/dist/capture/jpeg-xl-tiles.d.ts +22 -0
  22. package/dist/capture/jpeg-xl-tiles.js +151 -0
  23. package/dist/capture/jpeg-xl-tiles.js.map +1 -0
  24. package/dist/capture/lossy-jpeg.d.ts +17 -0
  25. package/dist/capture/lossy-jpeg.js +369 -0
  26. package/dist/capture/lossy-jpeg.js.map +1 -0
  27. package/dist/capture/native-raw-development.d.ts +2 -1
  28. package/dist/capture/native-raw-development.js.map +1 -1
  29. package/dist/color/neighbor-highlight-reconstruction.d.ts +66 -0
  30. package/dist/color/neighbor-highlight-reconstruction.js +234 -0
  31. package/dist/color/neighbor-highlight-reconstruction.js.map +1 -0
  32. package/dist/color/sensor-color-development.d.ts +5 -0
  33. package/dist/color/sensor-color-development.js +7 -1
  34. package/dist/color/sensor-color-development.js.map +1 -1
  35. package/dist/color/spectral-spikiness.d.ts +11 -0
  36. package/dist/color/spectral-spikiness.js +23 -0
  37. package/dist/color/spectral-spikiness.js.map +1 -0
  38. package/dist/core/execution-error.d.ts +21 -0
  39. package/dist/core/execution-error.js +12 -0
  40. package/dist/core/execution-error.js.map +1 -0
  41. package/dist/core/version.d.ts +1 -1
  42. package/dist/core/version.js +1 -1
  43. package/dist/core/version.js.map +1 -1
  44. package/dist/facade/catalogue-lens-signal.d.ts +26 -1
  45. package/dist/facade/catalogue-lens-signal.js +25 -7
  46. package/dist/facade/catalogue-lens-signal.js.map +1 -1
  47. package/dist/facade/diffraction-provider.d.ts +1 -1
  48. package/dist/facade/diffraction-provider.js +4 -4
  49. package/dist/facade/diffraction-provider.js.map +1 -1
  50. package/dist/facade/display-view-gpu-session.js +38 -6
  51. package/dist/facade/display-view-gpu-session.js.map +1 -1
  52. package/dist/facade/display-view-gpu.d.ts +13 -5
  53. package/dist/facade/display-view-gpu.js.map +1 -1
  54. package/dist/facade/display-view-normal.d.ts +15 -0
  55. package/dist/facade/display-view-normal.js +44 -0
  56. package/dist/facade/display-view-normal.js.map +1 -0
  57. package/dist/facade/display-view-rendering.d.ts +97 -0
  58. package/dist/facade/display-view-rendering.js +598 -0
  59. package/dist/facade/display-view-rendering.js.map +1 -0
  60. package/dist/facade/display-view.d.ts +37 -65
  61. package/dist/facade/display-view.js +147 -476
  62. package/dist/facade/display-view.js.map +1 -1
  63. package/dist/facade/expected-signal-setup.js +2 -2
  64. package/dist/facade/expected-signal-setup.js.map +1 -1
  65. package/dist/facade/fast-methods.d.ts +1 -1
  66. package/dist/facade/fast-methods.js +37 -8
  67. package/dist/facade/fast-methods.js.map +1 -1
  68. package/dist/facade/generic-lens-capture.d.ts +1 -1
  69. package/dist/facade/generic-lens-capture.js +1 -1
  70. package/dist/facade/generic-lens-capture.js.map +1 -1
  71. package/dist/facade/image-plane.js +41 -10
  72. package/dist/facade/image-plane.js.map +1 -1
  73. package/dist/facade/on-demand-kits.d.ts +14 -0
  74. package/dist/facade/on-demand-kits.js +36 -0
  75. package/dist/facade/on-demand-kits.js.map +1 -0
  76. package/dist/facade/opt-in-kit.d.ts +9 -0
  77. package/dist/facade/opt-in-kit.js +11 -0
  78. package/dist/facade/opt-in-kit.js.map +1 -0
  79. package/dist/facade/quality-kit.d.ts +21 -0
  80. package/dist/facade/quality-kit.js +23 -0
  81. package/dist/facade/quality-kit.js.map +1 -0
  82. package/dist/facade/quality-paths.d.ts +22 -0
  83. package/dist/facade/quality-paths.js +44 -0
  84. package/dist/facade/quality-paths.js.map +1 -0
  85. package/dist/facade/scene-radiance.d.ts +18 -2
  86. package/dist/facade/scene-radiance.js +6 -4
  87. package/dist/facade/scene-radiance.js.map +1 -1
  88. package/dist/facade/simulate-capture.d.ts +32 -13
  89. package/dist/facade/simulate-capture.js +162 -69
  90. package/dist/facade/simulate-capture.js.map +1 -1
  91. package/dist/facade/simulate-display-view.d.ts +10 -12
  92. package/dist/facade/simulate-display-view.js +57 -48
  93. package/dist/facade/simulate-display-view.js.map +1 -1
  94. package/dist/gpu/display-view-gpu-renderer.d.ts +43 -0
  95. package/dist/gpu/display-view-gpu-renderer.js +134 -0
  96. package/dist/gpu/display-view-gpu-renderer.js.map +1 -0
  97. package/dist/gpu/display-view-image-material-module.d.ts +3 -2
  98. package/dist/gpu/display-view-image-material-module.js +25 -3
  99. package/dist/gpu/display-view-image-material-module.js.map +1 -1
  100. package/dist/gpu/display-view-image-quality.d.ts +43 -1
  101. package/dist/gpu/display-view-image-quality.js +256 -11
  102. package/dist/gpu/display-view-image-quality.js.map +1 -1
  103. package/dist/gpu/display-view-quality-gpu.d.ts +13 -64
  104. package/dist/gpu/display-view-quality-gpu.js +60 -249
  105. package/dist/gpu/display-view-quality-gpu.js.map +1 -1
  106. package/dist/gpu/display-view-speed-gpu.d.ts +16 -16
  107. package/dist/gpu/display-view-speed-gpu.js +50 -12
  108. package/dist/gpu/display-view-speed-gpu.js.map +1 -1
  109. package/dist/gpu/image-kernel-accelerator.js +3 -0
  110. package/dist/gpu/image-kernel-accelerator.js.map +1 -1
  111. package/dist/gpu/image-kernel-execution.d.ts +2 -13
  112. package/dist/gpu/image-kernel-execution.js +2 -10
  113. package/dist/gpu/image-kernel-execution.js.map +1 -1
  114. package/dist/gpu/wgsl-display-view-coupled-stub.d.ts +8 -0
  115. package/dist/gpu/wgsl-display-view-coupled-stub.js +21 -0
  116. package/dist/gpu/wgsl-display-view-coupled-stub.js.map +1 -0
  117. package/dist/gpu/wgsl-display-view-coupled.d.ts +88 -0
  118. package/dist/gpu/wgsl-display-view-coupled.js +353 -0
  119. package/dist/gpu/wgsl-display-view-coupled.js.map +1 -0
  120. package/dist/gpu/wgsl-display-view-quality-kernel.d.ts +4 -9
  121. package/dist/gpu/wgsl-display-view-quality-kernel.js +109 -111
  122. package/dist/gpu/wgsl-display-view-quality-kernel.js.map +1 -1
  123. package/dist/gpu/wgsl-display-view-speed-kernel.d.ts +1 -41
  124. package/dist/gpu/wgsl-display-view-speed-kernel.js +71 -8
  125. package/dist/gpu/wgsl-display-view-speed-kernel.js.map +1 -1
  126. package/dist/index.d.ts +11 -3
  127. package/dist/index.js +9 -1
  128. package/dist/index.js.map +1 -1
  129. package/dist/output/camera-channel-response.d.ts +50 -0
  130. package/dist/output/camera-channel-response.js +69 -0
  131. package/dist/output/camera-channel-response.js.map +1 -0
  132. package/dist/output/native-capture-sdr.js +5 -2
  133. package/dist/output/native-capture-sdr.js.map +1 -1
  134. package/dist/output/sdr-rendering.d.ts +18 -1
  135. package/dist/output/sdr-rendering.js +39 -2
  136. package/dist/output/sdr-rendering.js.map +1 -1
  137. package/dist/sensor/native-sensor-report.d.ts +10 -0
  138. package/dist/sensor/native-sensor-report.js +16 -0
  139. package/dist/sensor/native-sensor-report.js.map +1 -0
  140. package/dist/sensor/sensor-characteristics.d.ts +81 -13
  141. package/dist/sensor/sensor-characteristics.js +10 -6
  142. package/dist/sensor/sensor-characteristics.js.map +1 -1
  143. package/docs/API_REFERENCE.md +117 -4
  144. package/docs/QUICK_START.md +37 -8
  145. package/docs/USAGE.md +104 -22
  146. package/docs/api/capture-c2pa-embed.md +177 -0
  147. package/docs/api/capture-dng-import.md +86 -10
  148. package/docs/api/capture-dng-opcodes.md +93 -0
  149. package/docs/api/capture-dng-profile-maps.md +141 -0
  150. package/docs/api/capture-dng-stage-image.md +43 -0
  151. package/docs/api/capture-jpeg-xl-tiles.md +33 -0
  152. package/docs/api/capture-lossy-jpeg.md +41 -0
  153. package/docs/api/capture-native-raw-development.md +2 -1
  154. package/docs/api/core-execution-error.md +43 -0
  155. package/docs/api/core-version.md +1 -1
  156. package/docs/api/exports.json +255 -5
  157. package/docs/api/facade-display-view-gpu.md +5 -2
  158. package/docs/api/facade-display-view.md +11 -15
  159. package/docs/api/facade-fast-methods.md +38 -9
  160. package/docs/api/facade-quality-paths.md +24 -0
  161. package/docs/api/facade-scene-radiance.md +1 -1
  162. package/docs/api/facade-simulate-capture.md +24 -7
  163. package/docs/api/facade-simulate-display-view.md +10 -12
  164. package/docs/api/gpu-image-kernel-execution.md +0 -36
  165. package/docs/api/output-camera-channel-response.md +55 -0
  166. package/docs/api/output-sdr-rendering.md +6 -1
  167. package/docs/api/sensor-sensor-characteristics.md +54 -2
  168. package/llms.txt +1 -0
  169. package/package.json +6 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lossy-jpeg.js","sourceRoot":"","sources":["../../src/capture/lossy-jpeg.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAoBpD,SAAS,IAAI,CAAC,OAAe,IAAW,MAAM,IAAI,yBAAyB,CAAC,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAExG,MAAM,MAAM,GAAG,eAAe,CAAC,CAAC,GAAe,EAAE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AAC,CAAC,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Size-limited decoder for 8-bit sequential DCT JPEG (ITU-T T.81 | ISO/IEC 10918-1, processes 1 and 2: SOF0 baseline and SOF1\n * extended sequential with Huffman coding), the variant DNG uses for Compression = 34892 (\"lossy JPEG\", DNG 1.4.0.0) strips and\n * tiles. Written independently from the published standard, with no third-party decoder source. Browser-safe: plain typed arrays.\n *\n * Decoding follows T.81 Annex F (Huffman decoding F.2.2, DC prediction, run-length AC decoding, restart intervals F.2.2.5) and the\n * inverse DCT of A.3.3, evaluated directly in double precision with the correctly rounded cosine table `JPEG_DCT_COSINES`, then\n * rounded half away from zero, level-shifted by 128 and clamped to 0..255 (A.3.1). DCT decoders may differ by one code from each\n * other (T.81 leaves the IDCT accuracy to ITU-T T.83 compliance limits); this one is deterministic.\n *\n * Subsampled components are interpolated linearly to full size with centred sample siting (T.871, JFIF: chroma samples sit at the\n * centre of the luma samples they cover), so a 2:1 factor uses the weights 3/4 and 1/4. Three-component data is converted from\n * YCbCr to RGB with the T.871 equations unless the stream says it is RGB: an APP14 \"Adobe\" segment with transform 0, or, without\n * JFIF or APP14 segments, component identifiers \"R\", \"G\", \"B\" (the conventions ITU-T T.872 describes). Four components are\n * returned as stored.\n *\n * Supported: precision 8, 1..4 components with sampling factors 1..4, interleaved and non-interleaved sequential scans, DRI restart\n * intervals, 8- and 16-bit quantization tables, tables defined in a separate abbreviated stream (DNG JPEGTables). Rejected:\n * progressive, hierarchical, lossless and arithmetic-coded frames, 12-bit precision, truncated data.\n */\n\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { JPEG_DCT_COSINES } from \"./export-jpeg.js\";\n\n/** Decoded samples, interleaved by component within each line (line, x, component), 0..255. */\nexport interface LossyJpegImage {\n width: number;\n height: number;\n components: number;\n /** \"ycbcr-to-rgb\" when three YCbCr components were converted to RGB; \"none\" otherwise. */\n colorTransform: \"ycbcr-to-rgb\" | \"none\";\n samples: Uint8Array;\n}\nexport interface LossyJpegLimits {\n /** Largest width x height x components accepted, checked before any sample buffer is allocated. */\n maximumSamples: number;\n /** An abbreviated table-specification stream (SOI, DQT/DHT, EOI) read before `bytes`, as DNG's JPEGTables tag (347) supplies. */\n tables?: Uint8Array;\n}\n\ninterface Huffman { maxCode: Int32Array; valPtr: Int32Array; minCode: Int32Array; values: Uint8Array }\ninterface Component { id: number; h: number; v: number; tq: number; blocksWide: number; blocksHigh: number; plane: Uint8Array; previousDc: number; dc?: Huffman | undefined; ac?: Huffman | undefined }\nfunction fail(message: string): never { throw new InvalidConfigurationError(\"Lossy JPEG: \" + message); }\n\nconst ZIGZAG = /* @__PURE__ */ ((): Int32Array => {\n const z = new Int32Array(64);\n for (let d = 0, i = 0; d <= 14; d++) {\n const points: number[] = [];\n for (let y = 0; y < 8; y++) { const x = d - y; if (x >= 0 && x < 8) points.push(y * 8 + x); }\n for (const p of d % 2 === 0 ? points.reverse() : points) z[i++] = p;\n }\n return z;\n})();\n\n/** T.81 Annex C code generation and F.2.2.3 decoder tables. */\nfunction buildHuffman(counts: Uint8Array, values: Uint8Array): Huffman {\n const maxCode = new Int32Array(18).fill(-1), minCode = new Int32Array(17), valPtr = new Int32Array(17);\n let code = 0, k = 0;\n for (let length = 1; length <= 16; length++) {\n const n = counts[length - 1]!;\n if (n) { valPtr[length] = k; minCode[length] = code; code += n; k += n; maxCode[length] = code - 1; }\n if (code > (1 << length)) fail(\"over-subscribed Huffman table.\");\n code <<= 1;\n }\n maxCode[17] = 0x7fffffff;\n return { maxCode, minCode, valPtr, values };\n}\n\n/** Decodes one DCT JPEG stream (see the module notes). Every length, count and table index is checked against the buffer. */\nexport function parseLossyJpeg(bytes: Uint8Array, limits: LossyJpegLimits): LossyJpegImage {\n if (!(bytes instanceof Uint8Array)) fail(\"input must be a Uint8Array.\");\n if (limits === null || typeof limits !== \"object\" || !Number.isSafeInteger(limits.maximumSamples) || limits.maximumSamples < 1) fail(\"invalid sample limit.\");\n if (limits.tables !== undefined && !(limits.tables instanceof Uint8Array)) fail(\"tables must be a Uint8Array.\");\n const quant: (Float64Array | undefined)[] = [], dcTables: (Huffman | undefined)[] = [], acTables: (Huffman | undefined)[] = [];\n const state = { restart: 0, jfif: false, adobe: -1 };\n let scanned = false;\n let frame: { width: number; height: number; components: Component[]; hMax: number; vMax: number; mcusWide: number; mcusHigh: number } | undefined;\n\n const segments = (data: Uint8Array, tablesOnly: boolean): void => {\n const n = data.length;\n if (n < 4 || data[0] !== 0xff || data[1] !== 0xd8) fail(\"missing SOI marker.\");\n let p = 2;\n for (;;) {\n while (p < n && data[p] === 0xff && data[p + 1] === 0xff) p++;\n if (p + 2 > n || data[p] !== 0xff) fail(\"malformed marker segment.\");\n const marker = data[p + 1]!;\n if (marker === 0xd9) { if (tablesOnly || scanned) return; fail(\"no scan before EOI.\"); }\n if (p + 4 > n) fail(\"malformed marker segment.\");\n const size = data[p + 2]! * 256 + data[p + 3]!, start = p + 4, end = p + 2 + size;\n if (size < 2 || end > n) fail(\"segment exceeds the stream.\");\n if (marker === 0xdb) {\n for (let q = start; q < end;) {\n const pq = data[q]! >> 4, tq = data[q]! & 15, len = pq ? 128 : 64;\n if (pq > 1 || tq > 3 || q + 1 + len > end) fail(\"invalid quantization table.\");\n const table = new Float64Array(64);\n for (let i = 0; i < 64; i++) {\n const v = pq ? data[q + 1 + i * 2]! * 256 + data[q + 2 + i * 2]! : data[q + 1 + i]!;\n if (v === 0) fail(\"zero quantization value.\");\n table[ZIGZAG[i]!] = v;\n }\n quant[tq] = table; q += 1 + len;\n }\n } else if (marker === 0xc4) {\n for (let q = start; q < end;) {\n const tc = data[q]! >> 4, th = data[q]! & 15;\n if (tc > 1 || th > 3 || q + 17 > end) fail(\"invalid Huffman table.\");\n const counts = data.subarray(q + 1, q + 17);\n let total = 0; for (const c of counts) total += c;\n if (total > 256 || q + 17 + total > end) fail(\"Huffman table exceeds its segment.\");\n (tc ? acTables : dcTables)[th] = buildHuffman(counts, data.slice(q + 17, q + 17 + total));\n q += 17 + total;\n }\n } else if (marker === 0xdd) {\n if (size !== 4) fail(\"invalid restart interval.\");\n state.restart = data[start]! * 256 + data[start + 1]!;\n } else if (marker === 0xe0) {\n if (size >= 7 && data[start] === 0x4a && data[start + 1] === 0x46 && data[start + 2] === 0x49 && data[start + 3] === 0x46 && data[start + 4] === 0) state.jfif = true;\n } else if (marker === 0xee) {\n if (size >= 14 && String.fromCharCode(...data.subarray(start, start + 5)) === \"Adobe\") state.adobe = data[start + 11]!;\n } else if (marker === 0xc0 || marker === 0xc1) {\n if (tablesOnly || frame) fail(\"unexpected frame header.\");\n if (size < 8) fail(\"unsupported frame header.\");\n const precision = data[start]!, height = data[start + 1]! * 256 + data[start + 2]!, width = data[start + 3]! * 256 + data[start + 4]!, nf = data[start + 5]!;\n if (precision !== 8) fail(\"only 8-bit precision is supported.\");\n if (height < 1 || width < 1 || nf < 1 || nf > 4 || size !== 8 + 3 * nf) fail(\"unsupported frame header.\");\n if (width * height * nf > limits.maximumSamples) fail(\"frame exceeds the sample limit.\");\n const raw: { id: number; h: number; v: number; tq: number }[] = [];\n for (let i = 0; i < nf; i++) {\n const o = start + 6 + i * 3, h = data[o + 1]! >> 4, v = data[o + 1]! & 15, tq = data[o + 2]!;\n if (h < 1 || h > 4 || v < 1 || v > 4 || tq > 3) fail(\"invalid component sampling or table.\");\n if (raw.some((c) => c.id === data[o])) fail(\"duplicate component identifier.\");\n raw.push({ id: data[o]!, h, v, tq });\n }\n const hMax = Math.max(...raw.map((c) => c.h)), vMax = Math.max(...raw.map((c) => c.v));\n const mcusWide = Math.ceil(width / (8 * hMax)), mcusHigh = Math.ceil(height / (8 * vMax));\n const components = raw.map((c) => {\n const blocksWide = mcusWide * c.h, blocksHigh = mcusHigh * c.v;\n return { ...c, blocksWide, blocksHigh, plane: new Uint8Array(blocksWide * blocksHigh * 64), previousDc: 0 };\n });\n frame = { width, height, components, hMax, vMax, mcusWide, mcusHigh };\n } else if (marker === 0xda) {\n if (tablesOnly || !frame) fail(\"scan before frame header.\");\n const ns = data[start]!;\n if (ns < 1 || ns > 4 || size !== 6 + 2 * ns) fail(\"invalid scan header.\");\n const scan: Component[] = [];\n for (let i = 0; i < ns; i++) {\n const c = frame.components.find((x) => x.id === data[start + 1 + i * 2]);\n if (!c || scan.includes(c)) fail(\"scan references an unknown component.\");\n const td = data[start + 2 + i * 2]! >> 4, ta = data[start + 2 + i * 2]! & 15;\n c.dc = dcTables[td]; c.ac = acTables[ta];\n if (!c.dc || !c.ac) fail(\"scan references an undefined Huffman table.\");\n if (!quant[c.tq]) fail(\"component references an undefined quantization table.\");\n scan.push(c);\n }\n const ss = data[start + 1 + 2 * ns]!, se = data[start + 2 + 2 * ns]!, a = data[start + 3 + 2 * ns]!;\n if (ss !== 0 || se !== 63 || a !== 0) fail(\"only sequential scans are supported.\");\n if (scan.reduce((s, c) => s + (ns === 1 ? 1 : c.h * c.v), 0) > 10) fail(\"too many blocks per MCU.\");\n // Further scans may follow (non-interleaved sequential); EOI ends the image.\n p = decodeScan(data, end, frame, scan, quant, state.restart);\n scanned = true;\n continue;\n } else if ((marker >= 0xc2 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) || marker === 0xde) {\n fail(\"only sequential Huffman DCT frames (SOF0, SOF1) are supported.\");\n } else if (marker === 0xcc) {\n fail(\"arithmetic coding is not supported.\");\n } else if (marker < 0xc0 || marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {\n fail(\"unexpected marker.\");\n }\n p = end;\n }\n };\n if (limits.tables) segments(limits.tables, true);\n segments(bytes, false);\n if (!frame) fail(\"no image.\");\n if (frame.components.some((c) => !c.dc)) fail(\"a component has no scan.\");\n return assemble(frame, state);\n}\n\nfunction decodeScan(data: Uint8Array, start: number, frame: { width: number; height: number; hMax: number; vMax: number; mcusWide: number; mcusHigh: number },\n scan: Component[], quant: (Float64Array | undefined)[], restartInterval: number): number {\n let p = start, buffer = 0, bits = 0, padding = 0, marker = -1;\n const fill = (): void => {\n let byte = 0;\n if (marker < 0 && p < data.length && data[p] !== 0xff) byte = data[p++]!;\n else if (marker < 0 && p + 1 < data.length && data[p] === 0xff && data[p + 1] === 0x00) { byte = 0xff; p += 2; }\n else {\n if (marker < 0 && p + 1 < data.length) marker = data[p + 1]!;\n if (++padding > 8) fail(\"entropy-coded data is truncated.\");\n }\n buffer = ((buffer << 8) | byte) >>> 0; bits += 8;\n };\n const readBits = (count: number): number => {\n if (count === 0) return 0;\n while (bits < count) fill();\n bits -= count;\n return (buffer >>> bits) & ((1 << count) - 1);\n };\n const decode = (t: Huffman): number => {\n let code = readBits(1), len = 1;\n while (code > t.maxCode[len]!) {\n if (++len > 16) fail(\"invalid Huffman code.\");\n code = (code << 1) | readBits(1);\n }\n const v = t.values[t.valPtr[len]! + code - t.minCode[len]!];\n if (v === undefined) fail(\"invalid Huffman code.\");\n return v;\n };\n const extend = (v: number, s: number): number => v < (1 << (s - 1)) ? v - (1 << s) + 1 : v;\n const coefficients = new Float64Array(64), rows = new Float64Array(64), cos = JPEG_DCT_COSINES;\n const block = (c: Component, bx: number, by: number): void => {\n coefficients.fill(0);\n const t = decode(c.dc!);\n if (t > 11) fail(\"invalid DC difference category.\");\n c.previousDc += t ? extend(readBits(t), t) : 0;\n const q = quant[c.tq]!;\n coefficients[0] = c.previousDc * q[0]!;\n for (let k = 1; k < 64;) {\n const rs = decode(c.ac!), r = rs >> 4, s = rs & 15;\n if (s === 0) { if (r === 15) { k += 16; continue; } break; }\n k += r;\n if (k > 63 || s > 10) fail(\"invalid AC coefficient.\");\n const z = ZIGZAG[k]!;\n coefficients[z] = extend(readBits(s), s) * q[z]!;\n k++;\n }\n // A.3.3: s(y,x) = 1/4 Σ_u Σ_v C(u)C(v) S(v,u) cos((2x+1)uπ/16) cos((2y+1)vπ/16), rows (u) first, then columns (v).\n for (let v = 0; v < 8; v++) for (let x = 0; x < 8; x++) {\n let sum = 0;\n for (let u = 0; u < 8; u++) sum += (u === 0 ? Math.SQRT1_2 : 1) * coefficients[v * 8 + u]! * cos[u * 8 + x]!;\n rows[v * 8 + x] = sum;\n }\n const stride = c.blocksWide * 8, base = by * 8 * stride + bx * 8;\n for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) {\n let sum = 0;\n for (let v = 0; v < 8; v++) sum += (v === 0 ? Math.SQRT1_2 : 1) * rows[v * 8 + x]! * cos[v * 8 + y]!;\n const value = sum / 4, rounded = value < 0 ? -Math.round(-value) : Math.round(value);\n c.plane[base + y * stride + x] = Math.min(255, Math.max(0, rounded + 128));\n }\n };\n for (const c of scan) c.previousDc = 0;\n // A single-component scan is non-interleaved: one block per MCU over the component's own (unpadded-to-MCU) block grid.\n const single = scan.length === 1 ? scan[0]! : undefined;\n const unitsWide = single ? Math.ceil(Math.ceil(frame.width * single.h / frame.hMax) / 8) : frame.mcusWide;\n const unitsHigh = single ? Math.ceil(Math.ceil(frame.height * single.v / frame.vMax) / 8) : frame.mcusHigh;\n const total = unitsWide * unitsHigh;\n for (let m = 0, restarts = 0; m < total; m++) {\n if (restartInterval && m > 0 && m % restartInterval === 0) {\n bits = 0; buffer = 0; padding = 0; marker = -1;\n if (p + 1 >= data.length || data[p] !== 0xff || data[p + 1] !== (0xd0 | (restarts & 7))) fail(\"missing restart marker.\");\n p += 2; restarts++;\n for (const c of scan) c.previousDc = 0;\n }\n const mx = m % unitsWide, my = Math.floor(m / unitsWide);\n if (single) block(single, mx, my);\n else for (const c of scan) for (let v = 0; v < c.v; v++) for (let h = 0; h < c.h; h++) block(c, mx * c.h + h, my * c.v + v);\n }\n // Skip to the next marker: remaining fill bits are discarded (T.81 F.1.2.3 pads with 1-bits).\n while (p < data.length && !(data[p] === 0xff && data[p + 1] !== 0x00 && !(data[p + 1]! >= 0xd0 && data[p + 1]! <= 0xd7))) p++;\n if (p + 1 >= data.length) fail(\"missing EOI marker.\");\n return p;\n}\n\nfunction assemble(frame: { width: number; height: number; components: Component[]; hMax: number; vMax: number }, state: { jfif: boolean; adobe: number }): LossyJpegImage {\n const { width, height, components, hMax, vMax } = frame, nf = components.length, out = new Uint8Array(width * height * nf);\n components.forEach((c, ci) => {\n const stride = c.blocksWide * 8, cw = Math.ceil(width * c.h / hMax), ch = Math.ceil(height * c.v / vMax);\n if (c.h === hMax && c.v === vMax) {\n for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) out[(y * width + x) * nf + ci] = c.plane[y * stride + x]!;\n return;\n }\n // Centred linear interpolation: output sample x covers component position (x + 0.5)·h/hMax − 0.5, clamped to the samples.\n const sx = c.h / hMax, sy = c.v / vMax;\n for (let y = 0; y < height; y++) {\n const fy = Math.min(Math.max((y + 0.5) * sy - 0.5, 0), ch - 1), y0 = Math.floor(fy), y1 = Math.min(y0 + 1, ch - 1), wy = fy - y0;\n for (let x = 0; x < width; x++) {\n const fx = Math.min(Math.max((x + 0.5) * sx - 0.5, 0), cw - 1), x0 = Math.floor(fx), x1 = Math.min(x0 + 1, cw - 1), wx = fx - x0;\n const a = c.plane[y0 * stride + x0]!, b = c.plane[y0 * stride + x1]!, d = c.plane[y1 * stride + x0]!, e = c.plane[y1 * stride + x1]!;\n out[(y * width + x) * nf + ci] = Math.round((a * (1 - wx) + b * wx) * (1 - wy) + (d * (1 - wx) + e * wx) * wy);\n }\n }\n });\n const ids = components.map((c) => c.id), rgbIds = ids[0] === 0x52 && ids[1] === 0x47 && ids[2] === 0x42;\n const ycc = nf === 3 && (state.adobe >= 0 ? state.adobe !== 0 : state.jfif || !rgbIds);\n if (ycc) for (let i = 0; i < out.length; i += 3) {\n // T.871 §7: R = Y + 1.402 (Cr − 128), G = Y − 0.344136 (Cb − 128) − 0.714136 (Cr − 128), B = Y + 1.772 (Cb − 128).\n const y = out[i]!, cb = out[i + 1]! - 128, cr = out[i + 2]! - 128;\n out[i] = clamp8(y + 1.402 * cr); out[i + 1] = clamp8(y - 0.344136 * cb - 0.714136 * cr); out[i + 2] = clamp8(y + 1.772 * cb);\n }\n return { width, height, components: nf, colorTransform: ycc ? \"ycbcr-to-rgb\" : \"none\", samples: out };\n}\nfunction clamp8(v: number): number { return Math.min(255, Math.max(0, Math.round(v))); }\n"]}
@@ -44,7 +44,8 @@ export interface NativeRawDevelopmentInput {
44
44
  }
45
45
  /** RAW saturation handled before white balance. Counts are pixels or samples of the developed output. */
46
46
  export interface RawHighlightDiagnostics {
47
- mode: RawHighlightMode;
47
+ /** #602: "reconstruct-neighbors" from `simulateCapture`'s whole-image neighbor reconstruction. */
48
+ mode: RawHighlightMode | "reconstruct-neighbors";
48
49
  /** Output pixels with at least one contributing site at or above its white level, or flagged as saturated. */
49
50
  saturatedPixelCount: number;
50
51
  /** `clip`: WB-scaled samples clipped at the smallest gain. Always 0 for `reconstruct`. */
@@ -1 +1 @@
1
- {"version":3,"file":"native-raw-development.js","sourceRoot":"","sources":["../../src/capture/native-raw-development.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;GAIG;AACH,OAAO,EAAE,sBAAsB,EAAsE,MAAM,iBAAiB,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAA2C,MAAM,+BAA+B,CAAC;AAC7H,OAAO,EAAE,iCAAiC,EAAE,4BAA4B,EAAE,kCAAkC,EACpE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,6BAA6B,EAAiC,MAAM,0BAA0B,CAAC;AACxG,OAAO,EAAE,6BAA6B,EAAsD,MAAM,sCAAsC,CAAC;AACzI,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,mBAAmB,EAAqD,MAAM,4BAA4B,CAAC;AACrK,OAAO,EAAE,gBAAgB,EAAgD,MAAM,iCAAiC,CAAC;AACjH,OAAO,EAAE,oCAAoC,EAAE,MAAM,+BAA+B,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC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AK,EAAC,mBAAmB,EAAC,SAAS,EAAC;oBAC5L,cAAc,EAAC,iBAAiB,CAAC,OAAO,CAAC,EAAC,gBAAgB,EAAC,sCAAsC,EAAC,sBAAsB,EAAC,KAAK,EAAC,CAAC;gBAAA,KAAK,GAAC,WAAW,CAAC;YACtJ,CAAC;YAAA,OAAM,KAAK,EAAC,CAAC;gBAAA,OAAO,EAAE,CAAC;gBAAA,IAAG,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAC,CAAC;oBAAA,KAAK,GAAC,QAAQ,CAAC;oBAAA,KAAK,CAAC,KAAK,EAAE,CAAC;gBAAA,CAAC;gBAAA,MAAM,KAAK,CAAC;YAAA,CAAC;QAC/F,CAAC;QACD,MAAM,KAAQ,IAAG,KAAK,KAAG,OAAO,IAAE,KAAK,KAAG,SAAS,IAAE,KAAK,KAAG,WAAW,EAAC,CAAC;YAAA,KAAK,GAAC,WAAW,CAAC;YAAA,KAAK,CAAC,KAAK,EAAE,CAAC;YAAA,OAAO,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC;QACtH,OAAO,KAAQ,IAAG,KAAK,KAAG,aAAa,EAAC,CAAC;YAAA,KAAK,GAAC,UAAU,CAAC;YAAA,KAAK,CAAC,KAAK,EAAE,CAAC;YAAA,OAAO,EAAE,CAAC;QAAA,CAAC,CAAA,CAAC;QACpF,UAAU,KAA8B,IAAG,KAAK,KAAG,WAAW,IAAE,CAAC,MAAM;YAAC,MAAM,IAAI,yBAAyB,CAAC,iCAAiC,CAAC,CAAC,CAAA,MAAM,KAAK,GAAC,MAAM,CAAC,CAAA,MAAM,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,IAAI,CAAC,CAAA,KAAK,GAAC,aAAa,CAAC,CAAA,OAAO,KAAK,CAAC,CAAA,CAAC;KAC5N,CAAC;AACJ,CAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW development: turns packed RAW codes into an SDR image. It reconstructs full colour from\n * the CFA (colour filter array) mosaic exactly, then applies the shared colour, white-balance and SDR\n * steps, in bounded pixel tiles.\n */\nimport { calculateNativeRawPlan, type NativeRawInput, type NativeRawOutput, type NativeRawTaskState } from \"./native-raw.js\";\nimport { parseRawReconstructionPhaseProfiles, type RawFrameReconstructionPhaseProfile } from \"./raw-frame-reconstruction.js\";\nimport { calculateRawReconstructionChannel, rawReconstructionKernelReach, validateMirrorBorderCfaConsistency,\n type RawReconstructionBorderHandling } from \"../sensor/raw-reconstruction.js\";\nimport { equalWithinUlps } from \"../core/portable-math.js\";\nimport { resolveColorSamplingSite } from \"../sensor/color-sampling.js\";\nimport { parseExportSensorColorProfile, type ExportSensorColorProfile } from \"./photographic-export.js\";\nimport { prepareSensorColorDevelopment, type RawHighlightMode, type SensorColorDevelopment } from \"../color/sensor-color-development.js\";\nimport { calculateSdrRendering, parseSdrRenderingProfile, prepareSdrPixelTone, type SdrRenderingProfile, type SdrRenderingResult } from \"../output/sdr-rendering.js\";\nimport { renderSdrRunInto, type NativeTaskProgress, type SdrPixelCounts } from \"../output/native-capture-sdr.js\";\nimport { transformOrientedRasterPointToNative } from \"../output/capture-geometry.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence } from \"./host-yield-cadence.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { stringifyCanonicalJson } from \"../core/canonical-json.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { createRawDevelopmentCounts, createRawPixelDeveloper, normalizedRawSite, rawSiteSaturated,\n type RawDevelopmentCounts, type RawDevelopmentSource } from \"./raw-development-kernel.js\";\n\nexport interface NativeRawDevelopmentInput {\n /**\n * Packed RAW. Ownership passes to the task. On creation its five typed arrays are detached with\n * `ArrayBuffer.prototype.transfer` (no copy; the caller's arrays become length 0), or copied when\n * the runtime has no `transfer`. The developed output hands back the same RAW, now owned by the output.\n */\n raw: NativeRawOutput;\n phaseProfiles: readonly RawFrameReconstructionPhaseProfile[];\n colorProfile: ExportSensorColorProfile;\n whiteBalance: \"not-required\" | \"apply-resolved-sensor-gains\";\n rendering: SdrRenderingProfile;\n /** Highlight handling. `clip` (default): clipped highlights become neutral. `reconstruct`: the documented blend toward neutral. */\n highlightMode?: RawHighlightMode;\n /**\n * Frame-edge handling. `reject` (default): every reconstruction neighbourhood must lie inside the\n * native RAW frame. `mirror`: a site outside the frame is read from its mirror image (reflect-101,\n * edge not repeated). This is allowed only when the mirrored site has the same CFA colour, which is\n * always true for a 2×2 Bayer pattern. Interior pixels are unchanged.\n */\n borderHandling?: RawReconstructionBorderHandling;\n /**\n * Development exposure push in stops (#556), from {@link NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS} −2 to +5; default 0.\n * Each site's black-subtracted, white-normalized value is multiplied by 2^stops before demosaic, white balance, the\n * highlight mode, colour and the tone curve, like a raw editor's exposure slider. A site whose pushed value reaches the\n * white level is clipped there and counted as saturated (so `highlightMode: \"reconstruct\"` rolls it off); values below\n * black stay signed. The RAW codes are not changed. 0 (or omitted) develops exactly as before, byte for byte.\n */\n exposureCompensationStops?: number;\n /** Counts the kept packed RAW plus the integer output. It does not count caller buffers, process heap or GPU memory. */\n maximumRetainedPayloadBytes: number;\n}\n/** RAW saturation handled before white balance. Counts are pixels or samples of the developed output. */\nexport interface RawHighlightDiagnostics {\n mode: RawHighlightMode;\n /** Output pixels with at least one contributing site at or above its white level, or flagged as saturated. */\n saturatedPixelCount: number;\n /** `clip`: WB-scaled samples clipped at the smallest gain. Always 0 for `reconstruct`. */\n whiteBalanceClippedSampleCount: number;\n /** `reconstruct`: pixels blended toward neutral. Always 0 for `clip`. */\n reconstructedPixelCount: number;\n}\nexport interface NativeRawDevelopmentOutput {\n raw: NativeRawOutput;\n phaseProfiles: readonly RawFrameReconstructionPhaseProfile[];\n colorProfile: ExportSensorColorProfile;\n whiteBalance: NativeRawDevelopmentInput[\"whiteBalance\"];\n width: number;\n height: number;\n integerSamples: Uint8Array | Uint16Array;\n diagnostics: SdrRenderingResult[\"diagnostics\"];\n highlight: RawHighlightDiagnostics;\n borderHandling: RawReconstructionBorderHandling;\n outputEncoding: SdrRenderingResult[\"outputEncoding\"];\n rendering: SdrRenderingProfile;\n displayAdaptation: SdrRenderingResult[\"displayAdaptation\"];\n imageDataPairing: \"derived-from-exact-packed-native-raw\";\n producerOriginVerified: false;\n}\n/** Host callbacks, the same shape as the other native task providers but without a tile reader. */\nexport interface NativeRawDevelopmentProvider {\n /** Must yield to the host event loop, so cancellation and input events can run between tiles. */\n yieldControl(signal: AbortSignal): Promise<void>;\n /** Optional callback after each committed 256-pixel output tile. It cannot change the output. */\n onProgress?(progress: NativeTaskProgress): void;\n}\nexport interface NativeRawDevelopmentTask {\n readonly state: NativeRawTaskState;\n readonly completedTileCount: number;\n readonly totalTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n takeOutput(): NativeRawDevelopmentOutput;\n}\nconst TILE_WIDTH = 256;\n/** Accepted range of `NativeRawDevelopmentInput.exposureCompensationStops` and `simulateCapture`'s `output.exposureCompensationStops` (#556). */\nexport const NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS = /* @__PURE__ */ Object.freeze({ minimum: -2, maximum: 5 } as const);\n/** Sites checked per integrity chunk before checking whether it is time to yield. */\nconst INTEGRITY_CHUNK_SITES = 1 << 18;\nfunction canonical(value: unknown): string {\n return stringifyCanonicalJson(value,{undefinedObjectProperties:\"reject\",nonFiniteNumberMessage:\"Invalid RAW metadata.\",unsupportedValueMessage:\"Invalid RAW metadata.\"});\n}\n/** Validates packed RAW storage and recomputes its plan. Shared with the native DNG writer. Not exported from the package. */\nexport function validatePackedNativeRaw(raw: NativeRawOutput): NativeRawOutput[\"plan\"] {\n requireAllowlistedRecord(raw,[\"plan\",\"codes\",\"blackLevels\",\"digitalSaturationCodes\",\"saturationFlags\",\"effectiveSaturationCodes\"],\"Invalid packed RAW output.\");\n const p=raw.plan;\n if(!p?.exposure||!p.frame)throw new InvalidConfigurationError(\"Packed RAW requires complete exposure and frame metadata.\");\n const {engineApiVersion,resolvedGeometry,equivalentFocalLength35Mm,...exposure}=p.exposure;\n void engineApiVersion;void resolvedGeometry;\n const {capture,containerBitDepth,...frame}=p.frame;void containerBitDepth;\n const input: NativeRawInput={exposure,...frame,maximumOutputBytes:p.outputBytes,...(p.tileWidth===undefined?{}:{tileWidth:p.tileWidth}),...(p.maximumPixels===undefined?{}:{maximumPixels:p.maximumPixels}),...(p.exposureWindow?{exposureWindow:p.exposureWindow}:{})};\n const plan=calculateNativeRawPlan(input);\n // The recomputed 35 mm-equivalent focal length (also inside frame.capture, the same exposure record) may\n // differ by a few ULPs, so records parse in every JavaScript engine. Every other field must match exactly.\n const eq=plan.exposure.equivalentFocalLength35Mm,archivedFrameEq=(capture as unknown as Record<string,unknown>|undefined)?.equivalentFocalLength35Mm;\n if(typeof equivalentFocalLength35Mm!==\"number\"||!equalWithinUlps(equivalentFocalLength35Mm,eq,8)||typeof archivedFrameEq!==\"number\"||!equalWithinUlps(archivedFrameEq,eq,8)||\n canonical({...p,exposure:{...p.exposure,equivalentFocalLength35Mm:eq},frame:{...p.frame,capture:{...p.frame.capture,equivalentFocalLength35Mm:eq}}})!==canonical(plan))\n throw new InvalidConfigurationError(\"Packed RAW metadata is stale or inconsistent.\");\n const layout=plan.frame.colorSamplingProfile.layout,phaseCount=layout.kind===\"periodic-mosaic\"?layout.repeatWidthSites*layout.repeatHeightSites:0;\n const buffers=new Set<ArrayBufferLike>();\n for(const [a,type,length] of [[raw.codes,Uint16Array,plan.pixelCount],[raw.blackLevels,Uint16Array,plan.pixelCount],[raw.digitalSaturationCodes,Uint16Array,plan.pixelCount],\n [raw.saturationFlags,Uint8Array,plan.pixelCount],[raw.effectiveSaturationCodes,Uint16Array,phaseCount]] as const){\n if(!(a instanceof type)||!(a.buffer instanceof ArrayBuffer)||a.length!==length||a.buffer.byteLength!==a.byteLength||buffers.has(a.buffer))throw new InvalidConfigurationError(\"Packed RAW storage must be exact owned native arrays.\");\n buffers.add(a.buffer);\n }\n return plan;\n}\n/** Takes sole ownership: detaches without copying when the runtime supports ArrayBuffer transfer, otherwise copies. */\nfunction own<T extends Uint8Array<ArrayBuffer>|Uint16Array<ArrayBuffer>>(array: T, make: (buffer: ArrayBuffer)=>T): T {\n const buffer=array.buffer as ArrayBuffer&{transfer?:()=>ArrayBuffer};\n return typeof buffer.transfer===\"function\"?make(buffer.transfer()):make(buffer.slice(0));\n}\n/** Takes the validated packed RAW's arrays (without copying where supported). Not exported from the package. */\nexport function takeNativeRawOwnership(given: NativeRawOutput, plan: NativeRawOutput[\"plan\"]): NativeRawOutput {\n return {plan,codes:own(given.codes as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),blackLevels:own(given.blackLevels as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),\n digitalSaturationCodes:own(given.digitalSaturationCodes as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),saturationFlags:own(given.saturationFlags as Uint8Array<ArrayBuffer>,b=>new Uint8Array(b)),\n effectiveSaturationCodes:given.effectiveSaturationCodes.slice()};\n}\n/** Validated development metadata (internal; shared with the image-kernel accelerator). Not exported from the package. */\nexport interface PreparedDevelopment {\n plan: NativeRawOutput[\"plan\"]; phases: RawFrameReconstructionPhaseProfile[]; color: ExportSensorColorProfile; profile: SdrRenderingProfile;\n whiteBalance: NativeRawDevelopmentInput[\"whiteBalance\"]; highlightMode: RawHighlightMode; development: SensorColorDevelopment;\n crop: {x:number;y:number;width:number;height:number}; raster: {pixelWidth:number;pixelHeight:number};\n border: RawReconstructionBorderHandling; mirror: {nativeHeight:number;reach:number}|undefined;\n /** Development exposure gain 2^exposureCompensationStops; exactly 1 without a push. */\n exposureGain: number;\n}\n/**\n * Synchronous checks of metadata, kernel halo (the neighbourhood each pixel reads) and CFA, shared by the\n * task, the reference and the accelerator. No pixel loop. Not exported from the package.\n */\nexport function prepareNativeRawDevelopment(input: NativeRawDevelopmentInput): PreparedDevelopment {\n const r=requireAllowlistedRecord(input,[\"raw\",\"phaseProfiles\",\"colorProfile\",\"whiteBalance\",\"rendering\",\"highlightMode\",\"borderHandling\",\"exposureCompensationStops\",\"maximumRetainedPayloadBytes\"],\"Invalid native RAW development input.\");\n const plan=validatePackedNativeRaw(input.raw),g=plan.exposure.resolvedGeometry,native=plan.exposure.geometry.nativeRaster;\n const phases=freezeOwnedData(parseRawReconstructionPhaseProfiles(r.phaseProfiles,plan.frame.modeId,plan.frame.colorSamplingProfile));\n const color=freezeOwnedData(parseExportSensorColorProfile(r.colorProfile)),profile=freezeOwnedData(parseSdrRenderingProfile(r.rendering));\n const crop=g.output.cropRect,raster=g.output.raster,active=g.activeCapture.nativeRect,intent=plan.exposure.whiteBalanceIntent;\n const highlightMode=r.highlightMode===undefined?\"clip\":r.highlightMode;\n if(highlightMode!==\"clip\"&&highlightMode!==\"reconstruct\")throw new InvalidConfigurationError(\"Unsupported RAW highlight mode.\");\n const border=r.borderHandling===undefined?\"reject\":r.borderHandling;\n if(border!==\"reject\"&&border!==\"mirror\")throw new InvalidConfigurationError(\"Unsupported RAW border handling.\");\n const stops=r.exposureCompensationStops===undefined?0:r.exposureCompensationStops;\n if(typeof stops!==\"number\"||!Number.isFinite(stops)||stops<NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS.minimum||stops>NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS.maximum)\n throw new InvalidConfigurationError(\"RAW development exposureCompensationStops must be a finite number from -2 to +5.\");\n const exposureGain=stops===0?1:2**stops;\n if(color.colorSamplingProfileId!==plan.frame.colorSamplingProfile.profileId||phases.some(p=>canonical(p.profile.kernels.map(k=>k.outputChannelId))!==canonical(color.channelIds))||\n (r.whiteBalance!==\"not-required\"&&r.whiteBalance!==\"apply-resolved-sensor-gains\")||(intent!==null)!==(r.whiteBalance===\"apply-resolved-sensor-gains\")||\n raster.pixelWidth!==crop.width||raster.pixelHeight!==crop.height)throw new InvalidConfigurationError(\"Development requires bound sensor RGB, explicit one-time WB and 1:1 output crop.\");\n const bytes=plan.outputBytes+raster.pixelWidth*raster.pixelHeight*3*profile.bitDepth/8;\n if(typeof r.maximumRetainedPayloadBytes!==\"number\"||!Number.isSafeInteger(r.maximumRetainedPayloadBytes)||r.maximumRetainedPayloadBytes<bytes)throw new InvalidConfigurationError(\"Development exceeds retained output budget.\");\n const gains=intent?[intent.channelGains.red,intent.channelGains.green,intent.channelGains.blue]:null;\n const development=prepareSensorColorDevelopment(color.normalizedCameraChannelsToXyz,gains,highlightMode),layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Development requires periodic CFA.\");\n const nativeCorners=[{x:crop.x+.5,y:crop.y+.5},{x:crop.x+crop.width-.5,y:crop.y+crop.height-.5}].map(point=>{\n const p=transformOrientedRasterPointToNative({point,nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});return {x:Math.floor(p.x)+active.x,y:Math.floor(p.y)+active.y};\n });\n const minX=Math.min(...nativeCorners.map(p=>p.x)),maxX=Math.max(...nativeCorners.map(p=>p.x)),minY=Math.min(...nativeCorners.map(p=>p.y)),maxY=Math.max(...nativeCorners.map(p=>p.y));\n for(const phase of phases){\n const firstX=minX+(phase.phaseX-minX%layout.repeatWidthSites+layout.repeatWidthSites)%layout.repeatWidthSites;\n const firstY=minY+(phase.phaseY-minY%layout.repeatHeightSites+layout.repeatHeightSites)%layout.repeatHeightSites;\n if(firstX>maxX||firstY>maxY)continue;\n const lastX=maxX-(maxX-phase.phaseX+layout.repeatWidthSites)%layout.repeatWidthSites,lastY=maxY-(maxY-phase.phaseY+layout.repeatHeightSites)%layout.repeatHeightSites;\n for(const kernel of phase.profile.kernels)for(const c of kernel.contributions){\n if(firstX+c.offsetX<0||firstY+c.offsetY<0||lastX+c.offsetX>=native.pixelWidth||lastY+c.offsetY>=native.pixelHeight){\n if(border===\"reject\")throw new InvalidConfigurationError(\"Reconstruction halo leaves native RAW; no padding or renormalization.\");\n // Mirror: check the virtual site from the repeating pattern; validateMirrorBorderCfaConsistency proves mirrored reads agree with it.\n const vx=phase.phaseX+c.offsetX,vy=phase.phaseY+c.offsetY;\n if(layout.siteChannelIds[((vy%layout.repeatHeightSites)+layout.repeatHeightSites)%layout.repeatHeightSites*layout.repeatWidthSites+((vx%layout.repeatWidthSites)+layout.repeatWidthSites)%layout.repeatWidthSites]!==c.sourceChannelId)\n throw new InvalidConfigurationError(\"Reconstruction source channel disagrees with absolute CFA phase.\");\n continue;\n }\n const channel=resolveColorSamplingSite({profile:plan.frame.colorSamplingProfile,site:{x:firstX+c.offsetX,y:firstY+c.offsetY}}).mapping.channelId;\n if(channel!==c.sourceChannelId)throw new InvalidConfigurationError(\"Reconstruction source channel disagrees with absolute CFA phase.\");\n }\n }\n let mirror:PreparedDevelopment[\"mirror\"];\n if(border===\"mirror\"){\n const reach=rawReconstructionKernelReach(phases);\n validateMirrorBorderCfaConsistency(layout,native.pixelWidth,native.pixelHeight,reach);\n mirror={nativeHeight:native.pixelHeight,reach};\n }\n return {plan,phases,color,profile,whiteBalance:r.whiteBalance,highlightMode,development,crop,raster,border,mirror,exposureGain};\n}\n/** Checks the numbers in rows [y0,y1). Values below black stay signed; each white-minus-black span is positive. Not exported from the package. */\nexport function checkNativeRawIntegrity(raw: NativeRawOutput, nativeWidth: number, repeatWidth: number, repeatHeight: number, y0: number, y1: number): void {\n const codes=raw.codes,blacks=raw.blackLevels,digital=raw.digitalSaturationCodes,flags=raw.saturationFlags,white=raw.effectiveSaturationCodes;\n for(let y=y0;y<y1;y++){\n const row=(y%repeatHeight)*repeatWidth;\n for(let x=0,i=y*nativeWidth;x<nativeWidth;x++,i++){\n const d=digital[i]!,w=white[row+x%repeatWidth]!,b=blacks[i]!;\n if(b>=w||w>d||codes[i]!>d||flags[i]!>7)throw new InvalidConfigurationError(\"Invalid packed RAW code span, white level or saturation flags.\");\n }\n }\n}\nfunction source(raw: NativeRawOutput, plan: NativeRawOutput[\"plan\"], exposureGain: number): RawDevelopmentSource {\n const layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Development requires periodic CFA.\");\n return {nativeWidth:plan.exposure.geometry.nativeRaster.pixelWidth,repeatWidth:layout.repeatWidthSites,repeatHeight:layout.repeatHeightSites,\n codes:raw.codes,blackLevels:raw.blackLevels,saturationFlags:raw.saturationFlags,whiteByPhase:raw.effectiveSaturationCodes,...(exposureGain===1?{}:{exposureGain})};\n}\nfunction emptyDiagnostics(): SdrRenderingResult[\"diagnostics\"] {\n return {renderingNegativeSampleCount:0,renderingAboveReferenceSampleCount:0,toneChangedSampleCount:0,gamutClippedLowSampleCount:0,gamutClippedHighSampleCount:0,captureSaturation:\"consumed-in-raw-development\"};\n}\nfunction highlightOf(mode: RawHighlightMode, counts: RawDevelopmentCounts): RawHighlightDiagnostics {\n return {mode,saturatedPixelCount:counts.saturatedPixelCount,whiteBalanceClippedSampleCount:counts.whiteBalanceClippedSampleCount,reconstructedPixelCount:counts.reconstructedPixelCount};\n}\n/**\n * Internal, slow reference development using one object per step (not exported from the package). It is\n * kept to prove that the fast typed kernel gives byte-identical output.\n *\n * For each pixel it maps orientation with `transformOrientedRasterPointToNative`, gathers each channel\n * with `calculateRawReconstructionChannel`, develops with the shared colour operator, and renders\n * 256-pixel rows with the reference `calculateSdrRendering`. It does not take ownership of the RAW.\n */\nexport function developNativeRawReference(input: NativeRawDevelopmentInput): {integerSamples:number[];diagnostics:SdrRenderingResult[\"diagnostics\"];highlight:RawHighlightDiagnostics} {\n const v=prepareNativeRawDevelopment(input),plan=v.plan,g=plan.exposure.resolvedGeometry,active=g.activeCapture.nativeRect,src=source(input.raw,plan,v.exposureGain);\n checkNativeRawIntegrity(input.raw,src.nativeWidth,src.repeatWidth,src.repeatHeight,0,plan.exposure.geometry.nativeRaster.pixelHeight);\n const counts=createRawDevelopmentCounts(),diagnostics=emptyDiagnostics(),out:number[]=[];\n for(let y=0;y<v.raster.pixelHeight;y++)for(let x=0;x<v.raster.pixelWidth;x+=TILE_WIDTH){\n const width=Math.min(TILE_WIDTH,v.raster.pixelWidth-x),rgb:number[]=[];\n for(let j=0;j<width;j++){\n const q=transformOrientedRasterPointToNative({point:{x:v.crop.x+x+j+.5,y:v.crop.y+y+.5},nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});\n const point={x:Math.floor(q.x)+active.x,y:Math.floor(q.y)+active.y};\n const phase=v.phases[(point.y%src.repeatHeight)*src.repeatWidth+point.x%src.repeatWidth]!;\n let saturated=false;\n const values=phase.profile.kernels.map(kernel=>calculateRawReconstructionChannel(kernel,point,(sx,sy)=>{\n if(rawSiteSaturated(src,sx,sy))saturated=true;return normalizedRawSite(src,sx,sy);\n },v.mirror===undefined?undefined:{width:src.nativeWidth,height:v.mirror.nativeHeight}).linearBlackSubtractedNormalizedValue);\n if(saturated)counts.saturatedPixelCount++;\n const developed=[0,0,0];v.development.developInto(values[0]!,values[1]!,values[2]!,developed,0,counts);rgb.push(...developed);\n }\n const rendered=calculateSdrRendering({sourceImageStateId:plan.frame.frameId+\":developed\",inputImageState:\"color-transformed-linear-rgb\",inputColorSpace:\"linear-srgb-d65\",whiteBalanceHandling:plan.exposure.whiteBalanceIntent?\"already-applied-upstream\":\"not-required\",pixelWidth:width,pixelHeight:1,referenceWhiteValue:1,samples:rgb,profile:v.profile}).value;\n out.push(...rendered.integerSamples);\n for(const key of [\"renderingNegativeSampleCount\",\"renderingAboveReferenceSampleCount\",\"toneChangedSampleCount\",\"gamutClippedLowSampleCount\",\"gamutClippedHighSampleCount\"] as const)diagnostics[key]+=rendered.diagnostics[key];\n }\n return {integerSamples:out,diagnostics,highlight:highlightOf(v.highlightMode,counts)};\n}\nfunction sdrOutputEncoding(maximum: number): SdrRenderingResult[\"outputEncoding\"] {\n return {imageState:\"output-referred-sdr\",colorSpace:\"srgb\",primariesXy:{red:[.64,.33],green:[.30,.60],blue:[.15,.06]},whitePointXy:[.3127,.3290],referenceWhiteLuminanceCdM2:80,codeMinimum:0,codeMaximum:maximum};\n}\n/**\n * Creates a native RAW development task.\n *\n * It checks that every CFA phase has a reconstruction kernel and that every kernel neighbourhood is\n * available, takes ownership of the packed RAW (without copying where supported), and renders 256-pixel\n * output tiles with the fast typed kernel. Development scales each site to its CFA phase's effective white\n * level, clips flagged or white-level sites before white balance, and applies the selected highlight mode\n * (see `prepareSensorColorDevelopment`).\n *\n * The RAW numbers are checked in bounded chunks at the start of `run()`, with host yields, so creating the\n * task costs only as much as reading the metadata. The task yields to the host at chunk and tile boundaries\n * once about 8 ms of work has passed since the last yield, and after the final tile. Yield timing never\n * changes the output.\n *\n * `provider` is `{ yieldControl, onProgress? }`, the same shape as the other native task providers. A bare\n * yield function is still accepted in 2.x but is deprecated.\n *\n * The tile width used at capture is kept when rebuilding the exact packed plan. That width changes neither\n * CFA or noise-seed coordinates nor the developed pixels, and says nothing about transport or what a device\n * can handle.\n */\nexport function createNativeRawDevelopmentTask(input: NativeRawDevelopmentInput,\n provider: NativeRawDevelopmentProvider | ((signal:AbortSignal)=>Promise<void>)): NativeRawDevelopmentTask {\n return createNativeRawDevelopmentTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes output. Not exported from the package. */\nexport function createNativeRawDevelopmentTaskWithCadence(input: NativeRawDevelopmentInput,\n provider: NativeRawDevelopmentProvider | ((signal:AbortSignal)=>Promise<void>),cadence: HostYieldCadence): NativeRawDevelopmentTask {\n const hooks=typeof provider===\"function\"?{yieldControl:provider}:provider;\n if(!hooks||typeof hooks.yieldControl!==\"function\"||(hooks.onProgress!==undefined&&typeof hooks.onProgress!==\"function\"))throw new InvalidConfigurationError(\"Development requires a host event-loop yield.\");\n const yieldControl=hooks.yieldControl.bind(hooks),onProgress=hooks.onProgress?.bind(hooks);\n const v=prepareNativeRawDevelopment(input),plan=v.plan,g=plan.exposure.resolvedGeometry,active=g.activeCapture.nativeRect,raster=v.raster,crop=v.crop;\n const nativeHeight=plan.exposure.geometry.nativeRaster.pixelHeight;\n // Ownership is transferred only after every synchronous check has passed.\n const raw=takeNativeRawOwnership(input.raw,plan);\n const src=source(raw,plan,v.exposureGain),tilesPerRow=Math.ceil(raster.pixelWidth/TILE_WIDTH),totalTileCount=tilesPerRow*raster.pixelHeight;\n const abort=new AbortController();let state:NativeRawTaskState=\"ready\",output:NativeRawDevelopmentOutput|null=null,codes:Uint8Array|Uint16Array|null=null,completed=0;\n function release(): void {raw.codes.fill(0);raw.blackLevels.fill(0);raw.digitalSaturationCodes.fill(0);raw.saturationFlags.fill(0);raw.effectiveSaturationCodes.fill(0);codes?.fill(0);codes=null;output=null;}\n function check(): void {if(abort.signal.aborted)throw new InvalidConfigurationError(\"Native RAW development aborted.\");}\n /** Native coordinates of oriented output pixel (x, y) and the step to (x+1, y), both integer. */\n function rowMapping(x: number, y: number, width: number): {nx:number;ny:number;dx:number;dy:number} {\n const at=(j:number):{x:number;y:number}=>{const q=transformOrientedRasterPointToNative({point:{x:crop.x+x+j+.5,y:crop.y+y+.5},nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});return {x:Math.floor(q.x)+active.x,y:Math.floor(q.y)+active.y};};\n const first=at(0),second=width>1?at(1):first,dx=second.x-first.x,dy=second.y-first.y,last=at(width-1);\n if(Math.abs(dx)+Math.abs(dy)!==(width>1?1:0)||last.x!==first.x+dx*(width-1)||last.y!==first.y+dy*(width-1))throw new InvalidConfigurationError(\"Development orientation mapping is not a unit native step.\");\n return {nx:first.x,ny:first.y,dx,dy};\n }\n return {get state():NativeRawTaskState{return state;},get completedTileCount():number{return completed;},totalTileCount,\n async run():Promise<void>{\n if(state!==\"ready\")throw new InvalidConfigurationError(\"Development task is single-use.\");state=\"running\";\n try{\n const gate=createHostYieldGate(cadence);\n const rowsPerChunk=Math.max(1,Math.floor(INTEGRITY_CHUNK_SITES/src.nativeWidth));\n for(let y=0;y<nativeHeight;y+=rowsPerChunk){\n check();checkNativeRawIntegrity(raw,src.nativeWidth,src.repeatWidth,src.repeatHeight,y,Math.min(nativeHeight,y+rowsPerChunk));\n if(gate.due()){await yieldControl(abort.signal);check();gate.restart();}\n }\n codes=v.profile.bitDepth===8?new Uint8Array(raster.pixelWidth*raster.pixelHeight*3):new Uint16Array(raster.pixelWidth*raster.pixelHeight*3);\n const diagnostics=emptyDiagnostics(),developer=createRawPixelDeveloper(src,v.phases,v.development,v.mirror),tone=prepareSdrPixelTone(v.profile);\n const scale=2**v.profile.renderingExposureEv,maximum=2**v.profile.bitDepth-1,rgb=new Float64Array(TILE_WIDTH*3),scratch=new Float64Array(3);\n if(!Number.isFinite(scale)||scale<=0)throw new InvalidConfigurationError(\"Rendering scale is unrepresentable.\");\n for(let y=0;y<raster.pixelHeight;y++)for(let x=0;x<raster.pixelWidth;x+=TILE_WIDTH){\n check();const width=Math.min(TILE_WIDTH,raster.pixelWidth-x),map=rowMapping(x,y,width);\n const counts:SdrPixelCounts={negative:0,above:0,changed:0,low:0,high:0,outOfGamut:false};\n developer.developRun(map.nx,map.ny,map.dx,map.dy,width,rgb);\n renderSdrRunInto(rgb,0,width,v.profile,tone,scale,maximum,codes,(y*raster.pixelWidth+x)*3,scratch,counts);\n // Same 256-pixel granularity as the reference rows, so exposure errors come before gamut rejection.\n if(counts.outOfGamut)throw new InvalidConfigurationError(\"Tone output exceeds the declared SDR gamut range.\");\n diagnostics.renderingNegativeSampleCount+=counts.negative;diagnostics.renderingAboveReferenceSampleCount+=counts.above;diagnostics.toneChangedSampleCount+=counts.changed;\n diagnostics.gamutClippedLowSampleCount+=counts.low;diagnostics.gamutClippedHighSampleCount+=counts.high;\n completed++;onProgress?.({completedTileCount:completed,totalTileCount});\n if(gate.due()||(y===raster.pixelHeight-1&&x+TILE_WIDTH>=raster.pixelWidth)){await yieldControl(abort.signal);check();gate.restart();}\n }\n output={raw,phaseProfiles:v.phases,colorProfile:v.color,whiteBalance:v.whiteBalance,width:raster.pixelWidth,height:raster.pixelHeight,integerSamples:codes,diagnostics,\n highlight:highlightOf(v.highlightMode,developer.counts),borderHandling:v.border,rendering:v.profile,displayAdaptation:{kind:\"external-platform\",applied:false,displayCapabilities:\"unknown\"},\n outputEncoding:sdrOutputEncoding(maximum),imageDataPairing:\"derived-from-exact-packed-native-raw\",producerOriginVerified:false};state=\"completed\";\n }catch(error){release();if(!abort.signal.aborted){state=\"failed\";abort.abort();}throw error;}\n },\n cancel():void{if(state===\"ready\"||state===\"running\"||state===\"completed\"){state=\"cancelled\";abort.abort();release();}},\n dispose():void{if(state!==\"transferred\"){state=\"disposed\";abort.abort();release();}},\n takeOutput():NativeRawDevelopmentOutput{if(state!==\"completed\"||!output)throw new InvalidConfigurationError(\"Development output unavailable.\");const value=output;output=null;codes=null;state=\"transferred\";return value;}\n };\n}\n"]}
1
+ {"version":3,"file":"native-raw-development.js","sourceRoot":"","sources":["../../src/capture/native-raw-development.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC;;;;GAIG;AACH,OAAO,EAAE,sBAAsB,EAAsE,MAAM,iBAAiB,CAAC;AAC7H,OAAO,EAAE,mCAAmC,EAA2C,MAAM,+BAA+B,CAAC;AAC7H,OAAO,EAAE,iCAAiC,EAAE,4BAA4B,EAAE,kCAAkC,EACpE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,6BAA6B,EAAiC,MAAM,0BAA0B,CAAC;AACxG,OAAO,EAAE,6BAA6B,EAAsD,MAAM,sCAAsC,CAAC;AACzI,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,mBAAmB,EAAqD,MAAM,4BAA4B,CAAC;AACrK,OAAO,EAAE,gBAAgB,EAAgD,MAAM,iCAAiC,CAAC;AACjH,OAAO,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ourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Native RAW development: turns packed RAW codes into an SDR image. It reconstructs full colour from\n * the CFA (colour filter array) mosaic exactly, then applies the shared colour, white-balance and SDR\n * steps, in bounded pixel tiles.\n */\nimport { calculateNativeRawPlan, type NativeRawInput, type NativeRawOutput, type NativeRawTaskState } from \"./native-raw.js\";\nimport { parseRawReconstructionPhaseProfiles, type RawFrameReconstructionPhaseProfile } from \"./raw-frame-reconstruction.js\";\nimport { calculateRawReconstructionChannel, rawReconstructionKernelReach, validateMirrorBorderCfaConsistency,\n type RawReconstructionBorderHandling } from \"../sensor/raw-reconstruction.js\";\nimport { equalWithinUlps } from \"../core/portable-math.js\";\nimport { resolveColorSamplingSite } from \"../sensor/color-sampling.js\";\nimport { parseExportSensorColorProfile, type ExportSensorColorProfile } from \"./photographic-export.js\";\nimport { prepareSensorColorDevelopment, type RawHighlightMode, type SensorColorDevelopment } from \"../color/sensor-color-development.js\";\nimport { calculateSdrRendering, parseSdrRenderingProfile, prepareSdrPixelTone, type SdrRenderingProfile, type SdrRenderingResult } from \"../output/sdr-rendering.js\";\nimport { renderSdrRunInto, type NativeTaskProgress, type SdrPixelCounts } from \"../output/native-capture-sdr.js\";\nimport { transformOrientedRasterPointToNative } from \"../output/capture-geometry.js\";\nimport { InvalidConfigurationError } from \"../core/configuration-error.js\";\nimport { DEFAULT_HOST_YIELD_CADENCE, createHostYieldGate, type HostYieldCadence } from \"./host-yield-cadence.js\";\nimport { requireAllowlistedRecord } from \"../core/record-validation.js\";\nimport { stringifyCanonicalJson } from \"../core/canonical-json.js\";\nimport { freezeOwnedData } from \"../core/owned-data.js\";\nimport { createRawDevelopmentCounts, createRawPixelDeveloper, normalizedRawSite, rawSiteSaturated,\n type RawDevelopmentCounts, type RawDevelopmentSource } from \"./raw-development-kernel.js\";\n\nexport interface NativeRawDevelopmentInput {\n /**\n * Packed RAW. Ownership passes to the task. On creation its five typed arrays are detached with\n * `ArrayBuffer.prototype.transfer` (no copy; the caller's arrays become length 0), or copied when\n * the runtime has no `transfer`. The developed output hands back the same RAW, now owned by the output.\n */\n raw: NativeRawOutput;\n phaseProfiles: readonly RawFrameReconstructionPhaseProfile[];\n colorProfile: ExportSensorColorProfile;\n whiteBalance: \"not-required\" | \"apply-resolved-sensor-gains\";\n rendering: SdrRenderingProfile;\n /** Highlight handling. `clip` (default): clipped highlights become neutral. `reconstruct`: the documented blend toward neutral. */\n highlightMode?: RawHighlightMode;\n /**\n * Frame-edge handling. `reject` (default): every reconstruction neighbourhood must lie inside the\n * native RAW frame. `mirror`: a site outside the frame is read from its mirror image (reflect-101,\n * edge not repeated). This is allowed only when the mirrored site has the same CFA colour, which is\n * always true for a 2×2 Bayer pattern. Interior pixels are unchanged.\n */\n borderHandling?: RawReconstructionBorderHandling;\n /**\n * Development exposure push in stops (#556), from {@link NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS} −2 to +5; default 0.\n * Each site's black-subtracted, white-normalized value is multiplied by 2^stops before demosaic, white balance, the\n * highlight mode, colour and the tone curve, like a raw editor's exposure slider. A site whose pushed value reaches the\n * white level is clipped there and counted as saturated (so `highlightMode: \"reconstruct\"` rolls it off); values below\n * black stay signed. The RAW codes are not changed. 0 (or omitted) develops exactly as before, byte for byte.\n */\n exposureCompensationStops?: number;\n /** Counts the kept packed RAW plus the integer output. It does not count caller buffers, process heap or GPU memory. */\n maximumRetainedPayloadBytes: number;\n}\n/** RAW saturation handled before white balance. Counts are pixels or samples of the developed output. */\nexport interface RawHighlightDiagnostics {\n /** #602: \"reconstruct-neighbors\" from `simulateCapture`'s whole-image neighbor reconstruction. */\n mode: RawHighlightMode | \"reconstruct-neighbors\";\n /** Output pixels with at least one contributing site at or above its white level, or flagged as saturated. */\n saturatedPixelCount: number;\n /** `clip`: WB-scaled samples clipped at the smallest gain. Always 0 for `reconstruct`. */\n whiteBalanceClippedSampleCount: number;\n /** `reconstruct`: pixels blended toward neutral. Always 0 for `clip`. */\n reconstructedPixelCount: number;\n}\nexport interface NativeRawDevelopmentOutput {\n raw: NativeRawOutput;\n phaseProfiles: readonly RawFrameReconstructionPhaseProfile[];\n colorProfile: ExportSensorColorProfile;\n whiteBalance: NativeRawDevelopmentInput[\"whiteBalance\"];\n width: number;\n height: number;\n integerSamples: Uint8Array | Uint16Array;\n diagnostics: SdrRenderingResult[\"diagnostics\"];\n highlight: RawHighlightDiagnostics;\n borderHandling: RawReconstructionBorderHandling;\n outputEncoding: SdrRenderingResult[\"outputEncoding\"];\n rendering: SdrRenderingProfile;\n displayAdaptation: SdrRenderingResult[\"displayAdaptation\"];\n imageDataPairing: \"derived-from-exact-packed-native-raw\";\n producerOriginVerified: false;\n}\n/** Host callbacks, the same shape as the other native task providers but without a tile reader. */\nexport interface NativeRawDevelopmentProvider {\n /** Must yield to the host event loop, so cancellation and input events can run between tiles. */\n yieldControl(signal: AbortSignal): Promise<void>;\n /** Optional callback after each committed 256-pixel output tile. It cannot change the output. */\n onProgress?(progress: NativeTaskProgress): void;\n}\nexport interface NativeRawDevelopmentTask {\n readonly state: NativeRawTaskState;\n readonly completedTileCount: number;\n readonly totalTileCount: number;\n run(): Promise<void>;\n cancel(): void;\n dispose(): void;\n takeOutput(): NativeRawDevelopmentOutput;\n}\nconst TILE_WIDTH = 256;\n/** Accepted range of `NativeRawDevelopmentInput.exposureCompensationStops` and `simulateCapture`'s `output.exposureCompensationStops` (#556). */\nexport const NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS = /* @__PURE__ */ Object.freeze({ minimum: -2, maximum: 5 } as const);\n/** Sites checked per integrity chunk before checking whether it is time to yield. */\nconst INTEGRITY_CHUNK_SITES = 1 << 18;\nfunction canonical(value: unknown): string {\n return stringifyCanonicalJson(value,{undefinedObjectProperties:\"reject\",nonFiniteNumberMessage:\"Invalid RAW metadata.\",unsupportedValueMessage:\"Invalid RAW metadata.\"});\n}\n/** Validates packed RAW storage and recomputes its plan. Shared with the native DNG writer. Not exported from the package. */\nexport function validatePackedNativeRaw(raw: NativeRawOutput): NativeRawOutput[\"plan\"] {\n requireAllowlistedRecord(raw,[\"plan\",\"codes\",\"blackLevels\",\"digitalSaturationCodes\",\"saturationFlags\",\"effectiveSaturationCodes\"],\"Invalid packed RAW output.\");\n const p=raw.plan;\n if(!p?.exposure||!p.frame)throw new InvalidConfigurationError(\"Packed RAW requires complete exposure and frame metadata.\");\n const {engineApiVersion,resolvedGeometry,equivalentFocalLength35Mm,...exposure}=p.exposure;\n void engineApiVersion;void resolvedGeometry;\n const {capture,containerBitDepth,...frame}=p.frame;void containerBitDepth;\n const input: NativeRawInput={exposure,...frame,maximumOutputBytes:p.outputBytes,...(p.tileWidth===undefined?{}:{tileWidth:p.tileWidth}),...(p.maximumPixels===undefined?{}:{maximumPixels:p.maximumPixels}),...(p.exposureWindow?{exposureWindow:p.exposureWindow}:{})};\n const plan=calculateNativeRawPlan(input);\n // The recomputed 35 mm-equivalent focal length (also inside frame.capture, the same exposure record) may\n // differ by a few ULPs, so records parse in every JavaScript engine. Every other field must match exactly.\n const eq=plan.exposure.equivalentFocalLength35Mm,archivedFrameEq=(capture as unknown as Record<string,unknown>|undefined)?.equivalentFocalLength35Mm;\n if(typeof equivalentFocalLength35Mm!==\"number\"||!equalWithinUlps(equivalentFocalLength35Mm,eq,8)||typeof archivedFrameEq!==\"number\"||!equalWithinUlps(archivedFrameEq,eq,8)||\n canonical({...p,exposure:{...p.exposure,equivalentFocalLength35Mm:eq},frame:{...p.frame,capture:{...p.frame.capture,equivalentFocalLength35Mm:eq}}})!==canonical(plan))\n throw new InvalidConfigurationError(\"Packed RAW metadata is stale or inconsistent.\");\n const layout=plan.frame.colorSamplingProfile.layout,phaseCount=layout.kind===\"periodic-mosaic\"?layout.repeatWidthSites*layout.repeatHeightSites:0;\n const buffers=new Set<ArrayBufferLike>();\n for(const [a,type,length] of [[raw.codes,Uint16Array,plan.pixelCount],[raw.blackLevels,Uint16Array,plan.pixelCount],[raw.digitalSaturationCodes,Uint16Array,plan.pixelCount],\n [raw.saturationFlags,Uint8Array,plan.pixelCount],[raw.effectiveSaturationCodes,Uint16Array,phaseCount]] as const){\n if(!(a instanceof type)||!(a.buffer instanceof ArrayBuffer)||a.length!==length||a.buffer.byteLength!==a.byteLength||buffers.has(a.buffer))throw new InvalidConfigurationError(\"Packed RAW storage must be exact owned native arrays.\");\n buffers.add(a.buffer);\n }\n return plan;\n}\n/** Takes sole ownership: detaches without copying when the runtime supports ArrayBuffer transfer, otherwise copies. */\nfunction own<T extends Uint8Array<ArrayBuffer>|Uint16Array<ArrayBuffer>>(array: T, make: (buffer: ArrayBuffer)=>T): T {\n const buffer=array.buffer as ArrayBuffer&{transfer?:()=>ArrayBuffer};\n return typeof buffer.transfer===\"function\"?make(buffer.transfer()):make(buffer.slice(0));\n}\n/** Takes the validated packed RAW's arrays (without copying where supported). Not exported from the package. */\nexport function takeNativeRawOwnership(given: NativeRawOutput, plan: NativeRawOutput[\"plan\"]): NativeRawOutput {\n return {plan,codes:own(given.codes as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),blackLevels:own(given.blackLevels as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),\n digitalSaturationCodes:own(given.digitalSaturationCodes as Uint16Array<ArrayBuffer>,b=>new Uint16Array(b)),saturationFlags:own(given.saturationFlags as Uint8Array<ArrayBuffer>,b=>new Uint8Array(b)),\n effectiveSaturationCodes:given.effectiveSaturationCodes.slice()};\n}\n/** Validated development metadata (internal; shared with the image-kernel accelerator). Not exported from the package. */\nexport interface PreparedDevelopment {\n plan: NativeRawOutput[\"plan\"]; phases: RawFrameReconstructionPhaseProfile[]; color: ExportSensorColorProfile; profile: SdrRenderingProfile;\n whiteBalance: NativeRawDevelopmentInput[\"whiteBalance\"]; highlightMode: RawHighlightMode; development: SensorColorDevelopment;\n crop: {x:number;y:number;width:number;height:number}; raster: {pixelWidth:number;pixelHeight:number};\n border: RawReconstructionBorderHandling; mirror: {nativeHeight:number;reach:number}|undefined;\n /** Development exposure gain 2^exposureCompensationStops; exactly 1 without a push. */\n exposureGain: number;\n}\n/**\n * Synchronous checks of metadata, kernel halo (the neighbourhood each pixel reads) and CFA, shared by the\n * task, the reference and the accelerator. No pixel loop. Not exported from the package.\n */\nexport function prepareNativeRawDevelopment(input: NativeRawDevelopmentInput): PreparedDevelopment {\n const r=requireAllowlistedRecord(input,[\"raw\",\"phaseProfiles\",\"colorProfile\",\"whiteBalance\",\"rendering\",\"highlightMode\",\"borderHandling\",\"exposureCompensationStops\",\"maximumRetainedPayloadBytes\"],\"Invalid native RAW development input.\");\n const plan=validatePackedNativeRaw(input.raw),g=plan.exposure.resolvedGeometry,native=plan.exposure.geometry.nativeRaster;\n const phases=freezeOwnedData(parseRawReconstructionPhaseProfiles(r.phaseProfiles,plan.frame.modeId,plan.frame.colorSamplingProfile));\n const color=freezeOwnedData(parseExportSensorColorProfile(r.colorProfile)),profile=freezeOwnedData(parseSdrRenderingProfile(r.rendering));\n const crop=g.output.cropRect,raster=g.output.raster,active=g.activeCapture.nativeRect,intent=plan.exposure.whiteBalanceIntent;\n const highlightMode=r.highlightMode===undefined?\"clip\":r.highlightMode;\n if(highlightMode!==\"clip\"&&highlightMode!==\"reconstruct\")throw new InvalidConfigurationError(\"Unsupported RAW highlight mode.\");\n const border=r.borderHandling===undefined?\"reject\":r.borderHandling;\n if(border!==\"reject\"&&border!==\"mirror\")throw new InvalidConfigurationError(\"Unsupported RAW border handling.\");\n const stops=r.exposureCompensationStops===undefined?0:r.exposureCompensationStops;\n if(typeof stops!==\"number\"||!Number.isFinite(stops)||stops<NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS.minimum||stops>NATIVE_RAW_DEVELOPMENT_EXPOSURE_RANGE_STOPS.maximum)\n throw new InvalidConfigurationError(\"RAW development exposureCompensationStops must be a finite number from -2 to +5.\");\n const exposureGain=stops===0?1:2**stops;\n if(color.colorSamplingProfileId!==plan.frame.colorSamplingProfile.profileId||phases.some(p=>canonical(p.profile.kernels.map(k=>k.outputChannelId))!==canonical(color.channelIds))||\n (r.whiteBalance!==\"not-required\"&&r.whiteBalance!==\"apply-resolved-sensor-gains\")||(intent!==null)!==(r.whiteBalance===\"apply-resolved-sensor-gains\")||\n raster.pixelWidth!==crop.width||raster.pixelHeight!==crop.height)throw new InvalidConfigurationError(\"Development requires bound sensor RGB, explicit one-time WB and 1:1 output crop.\");\n const bytes=plan.outputBytes+raster.pixelWidth*raster.pixelHeight*3*profile.bitDepth/8;\n if(typeof r.maximumRetainedPayloadBytes!==\"number\"||!Number.isSafeInteger(r.maximumRetainedPayloadBytes)||r.maximumRetainedPayloadBytes<bytes)throw new InvalidConfigurationError(\"Development exceeds retained output budget.\");\n const gains=intent?[intent.channelGains.red,intent.channelGains.green,intent.channelGains.blue]:null;\n const development=prepareSensorColorDevelopment(color.normalizedCameraChannelsToXyz,gains,highlightMode),layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Development requires periodic CFA.\");\n const nativeCorners=[{x:crop.x+.5,y:crop.y+.5},{x:crop.x+crop.width-.5,y:crop.y+crop.height-.5}].map(point=>{\n const p=transformOrientedRasterPointToNative({point,nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});return {x:Math.floor(p.x)+active.x,y:Math.floor(p.y)+active.y};\n });\n const minX=Math.min(...nativeCorners.map(p=>p.x)),maxX=Math.max(...nativeCorners.map(p=>p.x)),minY=Math.min(...nativeCorners.map(p=>p.y)),maxY=Math.max(...nativeCorners.map(p=>p.y));\n for(const phase of phases){\n const firstX=minX+(phase.phaseX-minX%layout.repeatWidthSites+layout.repeatWidthSites)%layout.repeatWidthSites;\n const firstY=minY+(phase.phaseY-minY%layout.repeatHeightSites+layout.repeatHeightSites)%layout.repeatHeightSites;\n if(firstX>maxX||firstY>maxY)continue;\n const lastX=maxX-(maxX-phase.phaseX+layout.repeatWidthSites)%layout.repeatWidthSites,lastY=maxY-(maxY-phase.phaseY+layout.repeatHeightSites)%layout.repeatHeightSites;\n for(const kernel of phase.profile.kernels)for(const c of kernel.contributions){\n if(firstX+c.offsetX<0||firstY+c.offsetY<0||lastX+c.offsetX>=native.pixelWidth||lastY+c.offsetY>=native.pixelHeight){\n if(border===\"reject\")throw new InvalidConfigurationError(\"Reconstruction halo leaves native RAW; no padding or renormalization.\");\n // Mirror: check the virtual site from the repeating pattern; validateMirrorBorderCfaConsistency proves mirrored reads agree with it.\n const vx=phase.phaseX+c.offsetX,vy=phase.phaseY+c.offsetY;\n if(layout.siteChannelIds[((vy%layout.repeatHeightSites)+layout.repeatHeightSites)%layout.repeatHeightSites*layout.repeatWidthSites+((vx%layout.repeatWidthSites)+layout.repeatWidthSites)%layout.repeatWidthSites]!==c.sourceChannelId)\n throw new InvalidConfigurationError(\"Reconstruction source channel disagrees with absolute CFA phase.\");\n continue;\n }\n const channel=resolveColorSamplingSite({profile:plan.frame.colorSamplingProfile,site:{x:firstX+c.offsetX,y:firstY+c.offsetY}}).mapping.channelId;\n if(channel!==c.sourceChannelId)throw new InvalidConfigurationError(\"Reconstruction source channel disagrees with absolute CFA phase.\");\n }\n }\n let mirror:PreparedDevelopment[\"mirror\"];\n if(border===\"mirror\"){\n const reach=rawReconstructionKernelReach(phases);\n validateMirrorBorderCfaConsistency(layout,native.pixelWidth,native.pixelHeight,reach);\n mirror={nativeHeight:native.pixelHeight,reach};\n }\n return {plan,phases,color,profile,whiteBalance:r.whiteBalance,highlightMode,development,crop,raster,border,mirror,exposureGain};\n}\n/** Checks the numbers in rows [y0,y1). Values below black stay signed; each white-minus-black span is positive. Not exported from the package. */\nexport function checkNativeRawIntegrity(raw: NativeRawOutput, nativeWidth: number, repeatWidth: number, repeatHeight: number, y0: number, y1: number): void {\n const codes=raw.codes,blacks=raw.blackLevels,digital=raw.digitalSaturationCodes,flags=raw.saturationFlags,white=raw.effectiveSaturationCodes;\n for(let y=y0;y<y1;y++){\n const row=(y%repeatHeight)*repeatWidth;\n for(let x=0,i=y*nativeWidth;x<nativeWidth;x++,i++){\n const d=digital[i]!,w=white[row+x%repeatWidth]!,b=blacks[i]!;\n if(b>=w||w>d||codes[i]!>d||flags[i]!>7)throw new InvalidConfigurationError(\"Invalid packed RAW code span, white level or saturation flags.\");\n }\n }\n}\nfunction source(raw: NativeRawOutput, plan: NativeRawOutput[\"plan\"], exposureGain: number): RawDevelopmentSource {\n const layout=plan.frame.colorSamplingProfile.layout;\n if(layout.kind!==\"periodic-mosaic\")throw new InvalidConfigurationError(\"Development requires periodic CFA.\");\n return {nativeWidth:plan.exposure.geometry.nativeRaster.pixelWidth,repeatWidth:layout.repeatWidthSites,repeatHeight:layout.repeatHeightSites,\n codes:raw.codes,blackLevels:raw.blackLevels,saturationFlags:raw.saturationFlags,whiteByPhase:raw.effectiveSaturationCodes,...(exposureGain===1?{}:{exposureGain})};\n}\nfunction emptyDiagnostics(): SdrRenderingResult[\"diagnostics\"] {\n return {renderingNegativeSampleCount:0,renderingAboveReferenceSampleCount:0,toneChangedSampleCount:0,gamutClippedLowSampleCount:0,gamutClippedHighSampleCount:0,captureSaturation:\"consumed-in-raw-development\"};\n}\nfunction highlightOf(mode: RawHighlightMode, counts: RawDevelopmentCounts): RawHighlightDiagnostics {\n return {mode,saturatedPixelCount:counts.saturatedPixelCount,whiteBalanceClippedSampleCount:counts.whiteBalanceClippedSampleCount,reconstructedPixelCount:counts.reconstructedPixelCount};\n}\n/**\n * Internal, slow reference development using one object per step (not exported from the package). It is\n * kept to prove that the fast typed kernel gives byte-identical output.\n *\n * For each pixel it maps orientation with `transformOrientedRasterPointToNative`, gathers each channel\n * with `calculateRawReconstructionChannel`, develops with the shared colour operator, and renders\n * 256-pixel rows with the reference `calculateSdrRendering`. It does not take ownership of the RAW.\n */\nexport function developNativeRawReference(input: NativeRawDevelopmentInput): {integerSamples:number[];diagnostics:SdrRenderingResult[\"diagnostics\"];highlight:RawHighlightDiagnostics} {\n const v=prepareNativeRawDevelopment(input),plan=v.plan,g=plan.exposure.resolvedGeometry,active=g.activeCapture.nativeRect,src=source(input.raw,plan,v.exposureGain);\n checkNativeRawIntegrity(input.raw,src.nativeWidth,src.repeatWidth,src.repeatHeight,0,plan.exposure.geometry.nativeRaster.pixelHeight);\n const counts=createRawDevelopmentCounts(),diagnostics=emptyDiagnostics(),out:number[]=[];\n for(let y=0;y<v.raster.pixelHeight;y++)for(let x=0;x<v.raster.pixelWidth;x+=TILE_WIDTH){\n const width=Math.min(TILE_WIDTH,v.raster.pixelWidth-x),rgb:number[]=[];\n for(let j=0;j<width;j++){\n const q=transformOrientedRasterPointToNative({point:{x:v.crop.x+x+j+.5,y:v.crop.y+y+.5},nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});\n const point={x:Math.floor(q.x)+active.x,y:Math.floor(q.y)+active.y};\n const phase=v.phases[(point.y%src.repeatHeight)*src.repeatWidth+point.x%src.repeatWidth]!;\n let saturated=false;\n const values=phase.profile.kernels.map(kernel=>calculateRawReconstructionChannel(kernel,point,(sx,sy)=>{\n if(rawSiteSaturated(src,sx,sy))saturated=true;return normalizedRawSite(src,sx,sy);\n },v.mirror===undefined?undefined:{width:src.nativeWidth,height:v.mirror.nativeHeight}).linearBlackSubtractedNormalizedValue);\n if(saturated)counts.saturatedPixelCount++;\n const developed=[0,0,0];v.development.developInto(values[0]!,values[1]!,values[2]!,developed,0,counts);rgb.push(...developed);\n }\n const rendered=calculateSdrRendering({sourceImageStateId:plan.frame.frameId+\":developed\",inputImageState:\"color-transformed-linear-rgb\",inputColorSpace:\"linear-srgb-d65\",whiteBalanceHandling:plan.exposure.whiteBalanceIntent?\"already-applied-upstream\":\"not-required\",pixelWidth:width,pixelHeight:1,referenceWhiteValue:1,samples:rgb,profile:v.profile}).value;\n out.push(...rendered.integerSamples);\n for(const key of [\"renderingNegativeSampleCount\",\"renderingAboveReferenceSampleCount\",\"toneChangedSampleCount\",\"gamutClippedLowSampleCount\",\"gamutClippedHighSampleCount\"] as const)diagnostics[key]+=rendered.diagnostics[key];\n }\n return {integerSamples:out,diagnostics,highlight:highlightOf(v.highlightMode,counts)};\n}\nfunction sdrOutputEncoding(maximum: number): SdrRenderingResult[\"outputEncoding\"] {\n return {imageState:\"output-referred-sdr\",colorSpace:\"srgb\",primariesXy:{red:[.64,.33],green:[.30,.60],blue:[.15,.06]},whitePointXy:[.3127,.3290],referenceWhiteLuminanceCdM2:80,codeMinimum:0,codeMaximum:maximum};\n}\n/**\n * Creates a native RAW development task.\n *\n * It checks that every CFA phase has a reconstruction kernel and that every kernel neighbourhood is\n * available, takes ownership of the packed RAW (without copying where supported), and renders 256-pixel\n * output tiles with the fast typed kernel. Development scales each site to its CFA phase's effective white\n * level, clips flagged or white-level sites before white balance, and applies the selected highlight mode\n * (see `prepareSensorColorDevelopment`).\n *\n * The RAW numbers are checked in bounded chunks at the start of `run()`, with host yields, so creating the\n * task costs only as much as reading the metadata. The task yields to the host at chunk and tile boundaries\n * once about 8 ms of work has passed since the last yield, and after the final tile. Yield timing never\n * changes the output.\n *\n * `provider` is `{ yieldControl, onProgress? }`, the same shape as the other native task providers. A bare\n * yield function is still accepted in 2.x but is deprecated.\n *\n * The tile width used at capture is kept when rebuilding the exact packed plan. That width changes neither\n * CFA or noise-seed coordinates nor the developed pixels, and says nothing about transport or what a device\n * can handle.\n */\nexport function createNativeRawDevelopmentTask(input: NativeRawDevelopmentInput,\n provider: NativeRawDevelopmentProvider | ((signal:AbortSignal)=>Promise<void>)): NativeRawDevelopmentTask {\n return createNativeRawDevelopmentTaskWithCadence(input,provider,DEFAULT_HOST_YIELD_CADENCE);\n}\n/** Internal: the same task with an explicit host-yield timing. Timing never changes output. Not exported from the package. */\nexport function createNativeRawDevelopmentTaskWithCadence(input: NativeRawDevelopmentInput,\n provider: NativeRawDevelopmentProvider | ((signal:AbortSignal)=>Promise<void>),cadence: HostYieldCadence): NativeRawDevelopmentTask {\n const hooks=typeof provider===\"function\"?{yieldControl:provider}:provider;\n if(!hooks||typeof hooks.yieldControl!==\"function\"||(hooks.onProgress!==undefined&&typeof hooks.onProgress!==\"function\"))throw new InvalidConfigurationError(\"Development requires a host event-loop yield.\");\n const yieldControl=hooks.yieldControl.bind(hooks),onProgress=hooks.onProgress?.bind(hooks);\n const v=prepareNativeRawDevelopment(input),plan=v.plan,g=plan.exposure.resolvedGeometry,active=g.activeCapture.nativeRect,raster=v.raster,crop=v.crop;\n const nativeHeight=plan.exposure.geometry.nativeRaster.pixelHeight;\n // Ownership is transferred only after every synchronous check has passed.\n const raw=takeNativeRawOwnership(input.raw,plan);\n const src=source(raw,plan,v.exposureGain),tilesPerRow=Math.ceil(raster.pixelWidth/TILE_WIDTH),totalTileCount=tilesPerRow*raster.pixelHeight;\n const abort=new AbortController();let state:NativeRawTaskState=\"ready\",output:NativeRawDevelopmentOutput|null=null,codes:Uint8Array|Uint16Array|null=null,completed=0;\n function release(): void {raw.codes.fill(0);raw.blackLevels.fill(0);raw.digitalSaturationCodes.fill(0);raw.saturationFlags.fill(0);raw.effectiveSaturationCodes.fill(0);codes?.fill(0);codes=null;output=null;}\n function check(): void {if(abort.signal.aborted)throw new InvalidConfigurationError(\"Native RAW development aborted.\");}\n /** Native coordinates of oriented output pixel (x, y) and the step to (x+1, y), both integer. */\n function rowMapping(x: number, y: number, width: number): {nx:number;ny:number;dx:number;dy:number} {\n const at=(j:number):{x:number;y:number}=>{const q=transformOrientedRasterPointToNative({point:{x:crop.x+x+j+.5,y:crop.y+y+.5},nativeRaster:g.activeCapture.raster,orientation:plan.exposure.geometry.orientation});return {x:Math.floor(q.x)+active.x,y:Math.floor(q.y)+active.y};};\n const first=at(0),second=width>1?at(1):first,dx=second.x-first.x,dy=second.y-first.y,last=at(width-1);\n if(Math.abs(dx)+Math.abs(dy)!==(width>1?1:0)||last.x!==first.x+dx*(width-1)||last.y!==first.y+dy*(width-1))throw new InvalidConfigurationError(\"Development orientation mapping is not a unit native step.\");\n return {nx:first.x,ny:first.y,dx,dy};\n }\n return {get state():NativeRawTaskState{return state;},get completedTileCount():number{return completed;},totalTileCount,\n async run():Promise<void>{\n if(state!==\"ready\")throw new InvalidConfigurationError(\"Development task is single-use.\");state=\"running\";\n try{\n const gate=createHostYieldGate(cadence);\n const rowsPerChunk=Math.max(1,Math.floor(INTEGRITY_CHUNK_SITES/src.nativeWidth));\n for(let y=0;y<nativeHeight;y+=rowsPerChunk){\n check();checkNativeRawIntegrity(raw,src.nativeWidth,src.repeatWidth,src.repeatHeight,y,Math.min(nativeHeight,y+rowsPerChunk));\n if(gate.due()){await yieldControl(abort.signal);check();gate.restart();}\n }\n codes=v.profile.bitDepth===8?new Uint8Array(raster.pixelWidth*raster.pixelHeight*3):new Uint16Array(raster.pixelWidth*raster.pixelHeight*3);\n const diagnostics=emptyDiagnostics(),developer=createRawPixelDeveloper(src,v.phases,v.development,v.mirror),tone=prepareSdrPixelTone(v.profile);\n const scale=2**v.profile.renderingExposureEv,maximum=2**v.profile.bitDepth-1,rgb=new Float64Array(TILE_WIDTH*3),scratch=new Float64Array(3);\n if(!Number.isFinite(scale)||scale<=0)throw new InvalidConfigurationError(\"Rendering scale is unrepresentable.\");\n for(let y=0;y<raster.pixelHeight;y++)for(let x=0;x<raster.pixelWidth;x+=TILE_WIDTH){\n check();const width=Math.min(TILE_WIDTH,raster.pixelWidth-x),map=rowMapping(x,y,width);\n const counts:SdrPixelCounts={negative:0,above:0,changed:0,low:0,high:0,outOfGamut:false};\n developer.developRun(map.nx,map.ny,map.dx,map.dy,width,rgb);\n renderSdrRunInto(rgb,0,width,v.profile,tone,scale,maximum,codes,(y*raster.pixelWidth+x)*3,scratch,counts);\n // Same 256-pixel granularity as the reference rows, so exposure errors come before gamut rejection.\n if(counts.outOfGamut)throw new InvalidConfigurationError(\"Tone output exceeds the declared SDR gamut range.\");\n diagnostics.renderingNegativeSampleCount+=counts.negative;diagnostics.renderingAboveReferenceSampleCount+=counts.above;diagnostics.toneChangedSampleCount+=counts.changed;\n diagnostics.gamutClippedLowSampleCount+=counts.low;diagnostics.gamutClippedHighSampleCount+=counts.high;\n completed++;onProgress?.({completedTileCount:completed,totalTileCount});\n if(gate.due()||(y===raster.pixelHeight-1&&x+TILE_WIDTH>=raster.pixelWidth)){await yieldControl(abort.signal);check();gate.restart();}\n }\n output={raw,phaseProfiles:v.phases,colorProfile:v.color,whiteBalance:v.whiteBalance,width:raster.pixelWidth,height:raster.pixelHeight,integerSamples:codes,diagnostics,\n highlight:highlightOf(v.highlightMode,developer.counts),borderHandling:v.border,rendering:v.profile,displayAdaptation:{kind:\"external-platform\",applied:false,displayCapabilities:\"unknown\"},\n outputEncoding:sdrOutputEncoding(maximum),imageDataPairing:\"derived-from-exact-packed-native-raw\",producerOriginVerified:false};state=\"completed\";\n }catch(error){release();if(!abort.signal.aborted){state=\"failed\";abort.abort();}throw error;}\n },\n cancel():void{if(state===\"ready\"||state===\"running\"||state===\"completed\"){state=\"cancelled\";abort.abort();release();}},\n dispose():void{if(state!==\"transferred\"){state=\"disposed\";abort.abort();release();}},\n takeOutput():NativeRawDevelopmentOutput{if(state!==\"completed\"||!output)throw new InvalidConfigurationError(\"Development output unavailable.\");const value=output;output=null;codes=null;state=\"transferred\";return value;}\n };\n}\n"]}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * #602 (2.22.0): highlight reconstruction from neighboring pixels, `highlightMode: "reconstruct-neighbors"` (opt-in; an estimate,
3
+ * not a recovery of the clipped scene signal). The engine's own method, acting on the developed, white-balanced camera values
4
+ * u = g·c of the whole image at use (no tables):
5
+ *
6
+ * 1. A pixel is clipped when one of its normalized camera channels c_k reaches `NEIGHBOR_HIGHLIGHT_THRESHOLD` of white; clipped
7
+ * pixels form regions (8-connected).
8
+ * 2. Each unclipped pixel has the color ratios ρ = u/(u₀ + u₁ + u₂) (its chromaticity in white-balanced camera space). Pixels
9
+ * within `NEIGHBOR_HIGHLIGHT_MARGIN` pixels of a clipped one give no ratios: their demosaic reads clipped sites, which lowers
10
+ * the clipped channel (and noise selects them by the threshold); the regions below are the clipped pixels widened by it.
11
+ * 3. The clipped region takes its ratios from its unclipped boundary. **Fast:** the mean of ρ over the unclipped pixels within
12
+ * `NEIGHBOR_HIGHLIGHT_RING` pixels (Chebyshev distance) of the region. **Full:** the discrete harmonic (Laplace) interpolation
13
+ * of ρ inward: ρ at each clipped pixel is the mean of its 4-neighbors', with the unclipped neighbors' ratios as Dirichlet
14
+ * boundary values (pixels outside the image are left out), solved by successive over-relaxation from the fast values. A region
15
+ * with no unclipped neighbor keeps the neutral ratios.
16
+ * 4. A clipped pixel keeps its unclipped channels; its scale s = Σ_unclipped u_k / Σ_unclipped ρ_k, and each clipped channel
17
+ * becomes max(u_k, s·ρ_k) (never below what was recorded). Where every channel is clipped, s = max_k u_k/ρ_k.
18
+ * The result is not clipped at the white level: the tone curve and gamut handling then render it.
19
+ *
20
+ * Mathematics only, general and free: the discrete Laplace equation and its Dirichlet problem, and successive over-relaxation
21
+ * (e.g. G. Strang, MIT OpenCourseWare 18.086, "Mathematical Methods for Engineers II", finite differences for Laplace's equation
22
+ * and iterative solvers, free at https://ocw.mit.edu/courses/18-086-mathematical-methods-for-engineers-ii-spring-2006/).
23
+ */
24
+ /** Normalized channel level at which a channel counts as clipped. */
25
+ export declare const NEIGHBOR_HIGHLIGHT_THRESHOLD = 0.98;
26
+ /** Pixels this close (Chebyshev distance) to a clipped pixel give no ratios and are filled with the region. */
27
+ export declare const NEIGHBOR_HIGHLIGHT_MARGIN = 2;
28
+ /** The fast method's ring width in pixels around a (widened) clipped region. */
29
+ export declare const NEIGHBOR_HIGHLIGHT_RING = 2;
30
+ /** The full method's relaxation factor, tolerance and iteration cap. */
31
+ export declare const NEIGHBOR_HIGHLIGHT_SOR: Readonly<{
32
+ omega: 1.8;
33
+ tolerance: 1e-9;
34
+ maximumIterations: 20000;
35
+ }>;
36
+ export interface NeighborHighlightReport {
37
+ method: "ring-average" | "harmonic-interpolation";
38
+ /** Clipped pixels rebuilt, and the clipped regions. */
39
+ reconstructedPixelCount: number;
40
+ regionCount: number;
41
+ /** Full method: the largest number of relaxation sweeps a region needed, and whether every region met the tolerance. */
42
+ iterations: number;
43
+ converged: boolean;
44
+ }
45
+ /**
46
+ * The region ratios of an image: per pixel the ratios ρ its rebuild uses (`ratios`, 3 per pixel; for an unclipped pixel its own),
47
+ * and which pixels are clipped. `clippedAt(i)` tells whether pixel i is clipped; `valueAt(i, out)` writes pixel i's u.
48
+ * Pixels are i = y·width + x.
49
+ */
50
+ export declare function neighborHighlightRatios(width: number, height: number, clippedAt: (i: number) => boolean, valueAt: (i: number, out: Float64Array) => void, fast: boolean): {
51
+ clipped: Uint8Array;
52
+ ratios: Float64Array;
53
+ regionCount: number;
54
+ iterations: number;
55
+ converged: boolean;
56
+ };
57
+ /**
58
+ * The rebuild of one clipped pixel (step 4) into b, with its slopes ∂b/∂c (row-major 3 × 3, a.e.) when `slopes` is given.
59
+ * `c` are the normalized camera channels, `g` the white-balance gains, `rho` the pixel's ratios.
60
+ */
61
+ export declare function rebuildClippedPixel(c0: number, c1: number, c2: number, g: ArrayLike<number>, rho: ArrayLike<number>, b: Float64Array | number[], slopes?: Float64Array): void;
62
+ /**
63
+ * Rebuilds the clipped pixels of a white-balanced image u (3 per pixel, in place; becomes b), with the normalized channels
64
+ * c = u/g deciding which channels are clipped.
65
+ */
66
+ export declare function reconstructHighlightsFromNeighbors(u: Float64Array, width: number, height: number, gains: ArrayLike<number>, fast: boolean): NeighborHighlightReport;