Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep image keying kernel sharp-free (#4654)

[._.]/ Adam Eivy2006689896d7
diff --git a/server/lib/borderKey.js b/server/lib/borderKey.js
index 33d7d5cc9c..4a66a64a01 100644
--- a/server/lib/borderKey.js
+++ b/server/lib/borderKey.js
@@ -13,27 +13,37 @@ export function median(values) {
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
-const borderBandOffsets = ({ width, height }) => {
+/**
+ * Return raw RGBA offsets for the shared border band.
+ *
+ * Callers that need a different sampling geometry can override `band` and
+ * `step`; the sprite lane uses the defaults, while a domain preserving a
+ * historical one-pixel ring can request `{ band: 1, step: 1 }` explicitly.
+ */
+export function getBorderBandOffsets(
+ { width, height },
+ { band, step } = {},
+) {
const minDim = Math.min(width, height);
- const band = Math.max(4, Math.floor(minDim / 120));
- const step = Math.max(1, Math.floor(minDim / 320));
+ const sampleBand = Math.max(1, band ?? Math.max(4, Math.floor(minDim / 120)));
+ const sampleStep = Math.max(1, step ?? Math.max(1, Math.floor(minDim / 320)));
const offsets = [];
const push = (x, y) => offsets.push((y * width + x) * 4);
- for (let x = 0; x < width; x += step) {
- for (let o = 0; o < band && o < height; o += 1) {
+ for (let x = 0; x < width; x += sampleStep) {
+ for (let o = 0; o < sampleBand && o < height; o += 1) {
push(x, o);
push(x, height - 1 - o);
}
}
- for (let y = 0; y < height; y += step) {
- for (let o = 0; o < band && o < width; o += 1) {
+ for (let y = 0; y < height; y += sampleStep) {
+ for (let o = 0; o < sampleBand && o < width; o += 1) {
push(o, y);
push(width - 1 - o, y);
}
}
return offsets;
-};
+}
const borderColor = (data, offsets) => (
[0, 1, 2].map((channel) => median(offsets.map((offset) => data[offset + channel])))
@@ -55,8 +65,8 @@ const rgbDistanceSq = (data, offset, [r, g, b]) => (
* @param {{data: Buffer|Uint8Array, width: number, height: number}} frame
* @returns {[number, number, number]}
*/
-export function sampleBorderKey({ data, width, height }) {
- const offsets = borderBandOffsets({ width, height });
+export function sampleBorderKey({ data, width, height }, options = {}) {
+ const offsets = getBorderBandOffsets({ width, height }, options);
return borderColor(data, offsets);
}
@@ -69,9 +79,14 @@ export function sampleBorderKey({ data, width, height }) {
*/
export function detectSolidBorderColor(
{ data, width, height },
- { tolerance = 30, minCoverage = 0.9 } = {},
+ {
+ tolerance = 30,
+ minCoverage = 0.9,
+ band,
+ step,
+ } = {},
) {
- const offsets = borderBandOffsets({ width, height });
+ const offsets = getBorderBandOffsets({ width, height }, { band, step });
if (!offsets.length) return null;
const color = borderColor(data, offsets);
const toleranceSq = tolerance ** 2;
@@ -83,13 +98,12 @@ export function detectSolidBorderColor(
}
/**
- * Whether an RGBA buffer contains alpha below the caller's meaningfulness
- * threshold. The default preserves image-to-3D's historical 250 cutoff; the
- * sprite lane passes 255 to preserve its previous "any alpha variation" test.
+ * Whether an RGBA buffer contains alpha below image-to-3D's historical 250
+ * meaningfulness cutoff.
*/
-export function hasMeaningfulAlpha(data, alphaThreshold = 250) {
+export function hasMeaningfulAlpha(data) {
for (let i = 3; i < data.length; i += 4) {
- if (data[i] < alphaThreshold) return true;
+ if (data[i] < 250) return true;
}
return false;
}
diff --git a/server/lib/borderKey.test.js b/server/lib/borderKey.test.js
index 388f8fd6d5..e0c881e48a 100644
--- a/server/lib/borderKey.test.js
+++ b/server/lib/borderKey.test.js
@@ -39,10 +39,9 @@ describe('borderKey', () => {
expect(detectSolidBorderColor(frame)).toEqual(GREEN);
});
- it('shares the alpha meaningfulness threshold with an explicit override', () => {
+ it('shares the image-to-3D alpha meaningfulness threshold', () => {
const almostOpaque = makeFrame(2, 1, (x) => [0, 0, 0, x ? 255 : 249]);
expect(hasMeaningfulAlpha(almostOpaque.data)).toBe(true);
- expect(hasMeaningfulAlpha(almostOpaque.data, 255)).toBe(true);
expect(hasMeaningfulAlpha(makeFrame(2, 1, () => [0, 0, 0, 255]).data)).toBe(false);
});
diff --git a/server/services/imageTo3d/sourceKeying.js b/server/services/imageTo3d/sourceKeying.js
index 935fe3e15c..1b2757dda1 100644
--- a/server/services/imageTo3d/sourceKeying.js
+++ b/server/services/imageTo3d/sourceKeying.js
@@ -39,23 +39,29 @@ import { stat } from 'node:fs/promises';
import { Worker } from 'node:worker_threads';
import sharp from 'sharp';
import {
- detectSolidBorderColor as detectSolidBorderColorShared,
hasMeaningfulAlpha as hasMeaningfulAlphaShared,
} from '../../lib/borderKey.js';
import { atomicWrite, readJSONFile, sha256File } from '../../lib/fileUtils.js';
import { decodeRgbaFrame, encodePng } from '../../lib/imageRgba.js';
+import {
+ KEY_TOLERANCE,
+ KEY_TIGHT_TOLERANCE,
+ KEY_MIN_BORDER_COVERAGE,
+ KEY_SOFT_BAND,
+ KEY_MIN_KEYED_RATIO,
+ KEY_MAX_KEYED_RATIO,
+} from './sourceKeyingKernel.js';
-/** Euclidean RGB distance for the border/flood match (0–441 scale). */
-export const KEY_TOLERANCE = 30;
-/** Tighter distance for enclosed pockets that can't be reached from the border. */
-export const KEY_TIGHT_TOLERANCE = 15;
-/** Minimum fraction of border pixels that must match for "solid background". */
-export const KEY_MIN_BORDER_COVERAGE = 0.9;
-/** Distance band past KEY_TOLERANCE that maps to partial alpha at the edge. */
-export const KEY_SOFT_BAND = 30;
-/** Keyed-area fraction outside (min, max) means the detection was wrong. */
-export const KEY_MIN_KEYED_RATIO = 0.05;
-export const KEY_MAX_KEYED_RATIO = 0.98;
+export {
+ detectSolidBorderColor,
+ keySolidBackground,
+ KEY_TOLERANCE,
+ KEY_TIGHT_TOLERANCE,
+ KEY_MIN_BORDER_COVERAGE,
+ KEY_SOFT_BAND,
+ KEY_MIN_KEYED_RATIO,
+ KEY_MAX_KEYED_RATIO,
+} from './sourceKeyingKernel.js';
/** Sources above this pixel count skip Node-side keying entirely: the raw
* decode plus the flood/queue/output buffers scale at ~20 bytes per pixel
@@ -78,104 +84,9 @@ export const KEYING_CACHE_VERSION = [
KEY_MAX_PIXELS,
].join(':');
-// Squared-distance comparisons throughout the hot loops — Math.sqrt only where a
-// real distance is needed (the feather ramp, edge pixels only).
-const KEY_TOLERANCE_SQ = KEY_TOLERANCE ** 2;
-const KEY_TIGHT_TOLERANCE_SQ = KEY_TIGHT_TOLERANCE ** 2;
-
-const distSq = (data, i, [r, g, b]) => (
- (data[i] - r) ** 2 + (data[i + 1] - g) ** 2 + (data[i + 2] - b) ** 2
-);
-
/** Whether an RGBA buffer already carries a meaningful (non-opaque) alpha channel. */
export const hasMeaningfulAlpha = hasMeaningfulAlphaShared;
-/**
- * Detect a solid border color in a raw RGBA buffer. Returns `[r, g, b]` when at
- * least `KEY_MIN_BORDER_COVERAGE` of the border pixels sit within `KEY_TOLERANCE`
- * of the border's median color, else null.
- * @param {{data: Buffer|Uint8Array, width: number, height: number}} image
- * @returns {[number, number, number]|null}
- */
-export function detectSolidBorderColor({ data, width, height }) {
- return detectSolidBorderColorShared(
- { data, width, height },
- { tolerance: KEY_TOLERANCE, minCoverage: KEY_MIN_BORDER_COVERAGE },
- );
-}
-
-/**
- * Key a solid background out of a raw RGBA buffer. Pure — returns a NEW buffer
- * plus stats, or null when the image has no detectable solid background (or the
- * detection failed its own sanity gates). See the module doc for the algorithm.
- * @param {{data: Buffer|Uint8Array, width: number, height: number}} image
- * @returns {{data: Uint8Array, background: [number, number, number], keyedRatio: number}|null}
- */
-export function keySolidBackground({ data, width, height }) {
- const background = detectSolidBorderColor({ data, width, height });
- if (!background) return null;
-
- const pixelCount = width * height;
- const keyed = new Uint8Array(pixelCount); // 1 = background
- const queue = new Int32Array(pixelCount);
- let queueLength = 0;
-
- const enqueue = (p) => {
- if (!keyed[p] && distSq(data, p * 4, background) <= KEY_TOLERANCE_SQ) {
- keyed[p] = 1;
- queue[queueLength] = p;
- queueLength += 1;
- }
- };
- for (let x = 0; x < width; x += 1) { enqueue(x); enqueue((height - 1) * width + x); }
- for (let y = 1; y < height - 1; y += 1) { enqueue(y * width); enqueue(y * width + width - 1); }
-
- for (let head = 0; head < queueLength; head += 1) {
- const p = queue[head];
- const x = p % width;
- if (x > 0) enqueue(p - 1);
- if (x < width - 1) enqueue(p + 1);
- if (p >= width) enqueue(p - width);
- if (p < pixelCount - width) enqueue(p + width);
- }
-
- // Enclosed pockets: background color trapped between limbs never touches the
- // border, so the flood can't reach it — key it only on the tight tolerance.
- // The flood already counted itself (queueLength); count pockets as they key.
- let keyedCount = queueLength;
- for (let p = 0; p < pixelCount; p += 1) {
- if (!keyed[p] && distSq(data, p * 4, background) <= KEY_TIGHT_TOLERANCE_SQ) {
- keyed[p] = 1;
- keyedCount += 1;
- }
- }
-
- const keyedRatio = keyedCount / pixelCount;
- if (keyedRatio < KEY_MIN_KEYED_RATIO || keyedRatio > KEY_MAX_KEYED_RATIO) return null;
-
- const out = new Uint8Array(data.length);
- out.set(data);
- for (let y = 0; y < height; y += 1) {
- for (let x = 0; x < width; x += 1) {
- const p = y * width + x;
- if (keyed[p]) { out[p * 4 + 3] = 0; continue; }
- // Feather only against pixels that actually border the keyed region — a
- // background-adjacent edge texel carrying spill gets partial alpha; interior
- // pixels that merely resemble the background stay fully opaque.
- const touchesKeyed = (x > 0 && keyed[p - 1]) || (x < width - 1 && keyed[p + 1])
- || (y > 0 && keyed[p - width]) || (y < height - 1 && keyed[p + width]);
- if (!touchesKeyed) continue;
- const d = Math.sqrt(distSq(data, p * 4, background));
- if (d < KEY_TOLERANCE + KEY_SOFT_BAND) {
- // Max(0): an enclosed pixel inside KEY_TOLERANCE (but above the tight
- // pocket threshold) lands here with a negative ramp value.
- out[p * 4 + 3] = Math.max(0, Math.round(((d - KEY_TOLERANCE) / KEY_SOFT_BAND) * 255));
- }
- }
- }
- return { data: out, background, keyedRatio };
-}
-
const runKeySolidBackground = (frame) => {
const source = frame.data instanceof Uint8Array ? frame.data : Uint8Array.from(frame.data);
// Always copy the exact view into a fresh ArrayBuffer. Native image decoders
@@ -260,6 +171,8 @@ export async function prepareSourceImage({ sourcePath, targetPath }) {
await atomicWrite(keyedCacheMetadataPath(targetPath), {
version: KEYING_CACHE_VERSION,
sourceSha256: await sha256File(sourcePath),
- }).catch(() => {});
+ }).catch((error) => {
+ console.error(`❌ Image-to-3D keying cache metadata failed for ${targetPath}: ${error.message}`);
+ });
return targetPath;
}
diff --git a/server/services/imageTo3d/sourceKeying.test.js b/server/services/imageTo3d/sourceKeying.test.js
index d94222379e..8dc97f288c 100644
--- a/server/services/imageTo3d/sourceKeying.test.js
+++ b/server/services/imageTo3d/sourceKeying.test.js
@@ -70,6 +70,17 @@ describe('keySolidBackground', () => {
expect(alphaAt(keyed, 6, 6)).toBe(255); // subject interior near the edge
});
+ it('floods through a dirty outer row using the shared border-band seeds', () => {
+ const dirtyEdge = makeImage(20, 20, (x, y) => (
+ y === 0 ? [255, 0, 0] : (x >= 5 && x < 15 && y >= 5 && y < 15 ? BROWN : GREEN)
+ ));
+ const result = keySolidBackground(dirtyEdge);
+ expect(result).not.toBeNull();
+ const keyed = { data: result.data, width: 20, height: 20 };
+ expect(alphaAt(keyed, 0, 1)).toBe(0);
+ expect(alphaAt(keyed, 0, 0)).toBe(255); // non-background edge artifact is preserved
+ });
+
it('keys enclosed background pockets the flood fill cannot reach', () => {
// A brown ring with a green hole in the middle — unreachable from the border.
const ring = makeImage(20, 20, (x, y) => {
diff --git a/server/services/imageTo3d/sourceKeyingKernel.js b/server/services/imageTo3d/sourceKeyingKernel.js
new file mode 100644
index 0000000000..3a21b95a17
--- /dev/null
+++ b/server/services/imageTo3d/sourceKeyingKernel.js
@@ -0,0 +1,109 @@
+/**
+ * Sharp-free image-to-3D background-keying kernel.
+ *
+ * The worker imports this leaf directly so a render does not load the
+ * sharp/file-I/O boundary in a fresh thread. `sourceKeying.js` re-exports the
+ * public kernel functions for the existing service/test import surface.
+ */
+
+import {
+ detectSolidBorderColor as detectSolidBorderColorShared,
+ getBorderBandOffsets,
+} from '../../lib/borderKey.js';
+
+/** Euclidean RGB distance for the border/flood match (0–441 scale). */
+export const KEY_TOLERANCE = 30;
+/** Tighter distance for enclosed pockets that can't be reached from the border. */
+export const KEY_TIGHT_TOLERANCE = 15;
+/** Minimum fraction of border pixels that must match for "solid background". */
+export const KEY_MIN_BORDER_COVERAGE = 0.9;
+/** Distance band past KEY_TOLERANCE that maps to partial alpha at the edge. */
+export const KEY_SOFT_BAND = 30;
+/** Keyed-area fraction outside (min, max) means the detection was wrong. */
+export const KEY_MIN_KEYED_RATIO = 0.05;
+export const KEY_MAX_KEYED_RATIO = 0.98;
+
+const KEY_TOLERANCE_SQ = KEY_TOLERANCE ** 2;
+const KEY_TIGHT_TOLERANCE_SQ = KEY_TIGHT_TOLERANCE ** 2;
+
+const distSq = (data, i, [r, g, b]) => (
+ (data[i] - r) ** 2 + (data[i + 1] - g) ** 2 + (data[i + 2] - b) ** 2
+);
+
+/**
+ * Detect the image-to-3D background with the shared band sampler. The
+ * image-to-3D lane intentionally adopts the sprite lane's robust band policy;
+ * its flood seeds use the same offsets so measurement and keying agree.
+ */
+export function detectSolidBorderColor({ data, width, height }) {
+ return detectSolidBorderColorShared(
+ { data, width, height },
+ { tolerance: KEY_TOLERANCE, minCoverage: KEY_MIN_BORDER_COVERAGE },
+ );
+}
+
+/**
+ * Key a solid background out of a raw RGBA buffer. Pure — returns a NEW buffer
+ * plus stats, or null when the image has no detectable solid background (or the
+ * detection failed its own sanity gates).
+ */
+export function keySolidBackground({ data, width, height }) {
+ const background = detectSolidBorderColor({ data, width, height });
+ if (!background) return null;
+
+ const pixelCount = width * height;
+ const keyed = new Uint8Array(pixelCount); // 1 = background
+ const queue = new Int32Array(pixelCount);
+ let queueLength = 0;
+
+ const enqueue = (p) => {
+ if (!keyed[p] && distSq(data, p * 4, background) <= KEY_TOLERANCE_SQ) {
+ keyed[p] = 1;
+ queue[queueLength] = p;
+ queueLength += 1;
+ }
+ };
+ for (const offset of getBorderBandOffsets({ width, height })) enqueue(offset / 4);
+
+ for (let head = 0; head < queueLength; head += 1) {
+ const p = queue[head];
+ const x = p % width;
+ if (x > 0) enqueue(p - 1);
+ if (x < width - 1) enqueue(p + 1);
+ if (p >= width) enqueue(p - width);
+ if (p < pixelCount - width) enqueue(p + width);
+ }
+
+ // Enclosed pockets: background color trapped between limbs never touches the
+ // border, so the flood can't reach it — key it only on the tight tolerance.
+ let keyedCount = queueLength;
+ for (let p = 0; p < pixelCount; p += 1) {
+ if (!keyed[p] && distSq(data, p * 4, background) <= KEY_TIGHT_TOLERANCE_SQ) {
+ keyed[p] = 1;
+ keyedCount += 1;
+ }
+ }
+
+ const keyedRatio = keyedCount / pixelCount;
+ if (keyedRatio < KEY_MIN_KEYED_RATIO || keyedRatio > KEY_MAX_KEYED_RATIO) return null;
+
+ const out = new Uint8Array(data.length);
+ out.set(data);
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ const p = y * width + x;
+ if (keyed[p]) { out[p * 4 + 3] = 0; continue; }
+ // Feather only against pixels that actually border the keyed region — a
+ // background-adjacent edge texel carrying spill gets partial alpha; interior
+ // pixels that merely resemble the background stay fully opaque.
+ const touchesKeyed = (x > 0 && keyed[p - 1]) || (x < width - 1 && keyed[p + 1])
+ || (y > 0 && keyed[p - width]) || (y < height - 1 && keyed[p + width]);
+ if (!touchesKeyed) continue;
+ const d = Math.sqrt(distSq(data, p * 4, background));
+ if (d < KEY_TOLERANCE + KEY_SOFT_BAND) {
+ out[p * 4 + 3] = Math.max(0, Math.round(((d - KEY_TOLERANCE) / KEY_SOFT_BAND) * 255));
+ }
+ }
+ }
+ return { data: out, background, keyedRatio };
+}
diff --git a/server/services/imageTo3d/sourceKeyingWorker.js b/server/services/imageTo3d/sourceKeyingWorker.js
index a9102b7baa..96de35af44 100644
--- a/server/services/imageTo3d/sourceKeyingWorker.js
+++ b/server/services/imageTo3d/sourceKeyingWorker.js
@@ -1,5 +1,5 @@
import { parentPort, workerData } from 'node:worker_threads';
-import { keySolidBackground } from './sourceKeying.js';
+import { keySolidBackground } from './sourceKeyingKernel.js';
const frame = {
data: new Uint8Array(workerData.data),
diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.js
index cbf574822c..40d82b909e 100644
--- a/server/services/sprites/walkPostprocess.js
+++ b/server/services/sprites/walkPostprocess.js
@@ -52,9 +52,9 @@ export {
walkPhaseLabels, clampFrameCount, clampFps,
} from './walkBounds.js';
-// Preserve the sprite lane's established deep-import surface while the
-// implementations live in the shared leaves.
-export { decodeRgbaFrame, median };
+// Preserve the sprite lane's established median deep-import surface while the
+// implementation lives in the shared leaf.
+export { median };
// Source pipeline constants (animation_postprocess.py) — values are part of
// the cross-install artifact contract (imported manifests carry them).