Run the camera-to-sRGB pass on a worker thread

At four parallel imports the synchronous colour conversion was the widest
serial section left in the pipeline. The frame buffers now live on
SharedArrayBuffer, so a worker writes the same memory the encoder reads
and the main thread is free for the decoder pool and zlib.
This commit is contained in:
2026-12-02 04:02:33 +00:00
parent 7f0838156b
commit d24cbf26b8
3 changed files with 79 additions and 4 deletions
+54
View File
@@ -0,0 +1,54 @@
/**
* Runs the camera-to-sRGB conversion off the main thread when it can.
*
* The conversion is CPU-bound and synchronous, so at four parallel imports it
* was the widest serial section left in the pipeline: four 24 MP frames cost
* ~10 s of event-loop time on top of the demosaic. A worker takes that loop off
* the main thread while the decoder pool and zlib keep their own threads.
*
* The frame is shared rather than transferred: `toRgb` allocates both buffers
* on SharedArrayBuffer, so `postMessage` hands over views and the worker writes
* the same memory the encoder will read. A frame that is not shared (a caller
* outside the raw pipeline) stays on this thread instead of being copied.
*/
import { Worker } from 'node:worker_threads';
import { cameraToProxy } from './color.mjs';
function isShared(view) {
return view?.buffer instanceof SharedArrayBuffer;
}
function runInWorker(rgb16, rgb8, matrix) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./color-worker.mjs', import.meta.url), {
workerData: { rgb16, rgb8, matrix },
});
let settled = false;
const finish = (fn, value) => {
if (settled) return;
settled = true;
worker.terminate().catch(() => {});
fn(value);
};
worker.once('message', (message) => {
if (message?.error) finish(reject, new Error(message.error));
else finish(resolve, message?.gain);
});
worker.once('error', (error) => finish(reject, error));
worker.once('exit', (code) => {
// A clean exit arrives after the message; only a crash before it is an error.
if (code !== 0) finish(reject, new Error(`colour worker exited with code ${code}`));
});
});
}
/**
* Applies the camera matrix to the frame in place and resolves with the white
* point gain, exactly like `cameraToProxy`. A worker failure rejects rather
* than re-running the conversion here: the worker may have written part of the
* frame, and applying it again would double the white point.
*/
export async function cameraToProxyAsync(rgb16, rgb8, matrix) {
if (!isShared(rgb16) || !isShared(rgb8)) return cameraToProxy(rgb16, rgb8, matrix);
return runInWorker(rgb16, rgb8, matrix);
}
+17
View File
@@ -0,0 +1,17 @@
/**
* Off-main-thread camera-to-proxy conversion.
*
* `cameraToProxy` is a pixel loop over the whole frame: 2.4 s on a 24 MP decode
* here, and four parallel imports serialised on it. The buffers arrive as
* SharedArrayBuffer views, so the worker mutates the frame in place and nothing
* is copied across the thread boundary.
*/
import { parentPort, workerData } from 'node:worker_threads';
import { cameraToProxy } from './color.mjs';
try {
const gain = cameraToProxy(workerData.rgb16, workerData.rgb8, workerData.matrix);
parentPort.postMessage({ gain });
} catch (error) {
parentPort.postMessage({ error: error instanceof Error ? error.message : String(error) });
}
+8 -4
View File
@@ -1,5 +1,6 @@
import { RAW_16BIT, RAW_PREVIEW_EDGE, RAW_TIMEOUT_MS, RAW_XTRANS_QUALITY } from './config.mjs'; import { RAW_16BIT, RAW_PREVIEW_EDGE, RAW_TIMEOUT_MS, RAW_XTRANS_QUALITY } from './config.mjs';
import { cameraToProxy, readRgbCam } from './color.mjs'; import { readRgbCam } from './color.mjs';
import { cameraToProxyAsync } from './color-offload.mjs';
import { import {
encodePng16Async, encodePng16Async,
encodeRgb, encodeRgb,
@@ -144,11 +145,14 @@ function toRgb(img) {
); );
} }
const rgb = Buffer.alloc(pixelCount * 3); // Both outputs are shared memory: the camera-to-sRGB pass runs in a worker
// (color-offload.mjs) and writes these same bytes, so a 24 MP frame is not
// copied across the thread boundary.
const rgb = Buffer.from(new SharedArrayBuffer(pixelCount * 3));
let rgb16 = null; let rgb16 = null;
if (bits > 8) { if (bits > 8) {
const view = wide instanceof Uint16Array ? wide : src; const view = wide instanceof Uint16Array ? wide : src;
rgb16 = new Uint16Array(pixelCount * 3); rgb16 = new Uint16Array(new SharedArrayBuffer(pixelCount * 3 * 2));
for (let i = 0; i < pixelCount; i++) { for (let i = 0; i < pixelCount; i++) {
const s = i * colors; const s = i * colors;
const r = view[s]; const r = view[s];
@@ -313,7 +317,7 @@ export async function decodeRaw(buffer, { sidecar = RAW_16BIT } = {}) {
const { width, height, rgbCam } = frame; const { width, height, rgbCam } = frame;
// Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and // Both buffers are rewritten in place: `rgb` becomes the sRGB proxy and
// `rgb16` the camera-native sidecar, sharing one white point. // `rgb16` the camera-native sidecar, sharing one white point.
if (rgbCam && frame.rgb16) cameraToProxy(frame.rgb16, frame.rgb, rgbCam); if (rgbCam && frame.rgb16) await cameraToProxyAsync(frame.rgb16, frame.rgb, rgbCam);
const { rgb } = frame; const { rgb } = frame;
const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE); const encoded = await encodeRgb(rgb, width, height, 92, RAW_PREVIEW_EDGE);
// The sidecar must match the JPEG pixel for pixel: the editor swaps the // The sidecar must match the JPEG pixel for pixel: the editor swaps the