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:
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user