Skip to content

Build your personal knowledge base with Trilium Notes

core/image compression: performance improvements

Adorian Dorana8222cc53125
diff --git a/apps/server/src/services/image_codec.spec.ts b/apps/server/src/services/image_codec.spec.ts
new file mode 100644
index 0000000000..ae82d8859f
--- /dev/null
+++ b/apps/server/src/services/image_codec.spec.ts
@@ -0,0 +1,102 @@
+import { inspectImage } from "@triliumnext/core/src/services/image_inspect.js";
+import type { ImageCompressionRequest, ImageFormat } from "@triliumnext/core/src/services/image_provider.js";
+import { Jimp } from "jimp";
+import * as UPNG from "upng-js";
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { compressImageBytes, planFromBytes } from "./image_codec.js";
+
+/**
+ * The header-level planning on real encoder output: what an image's own bytes say about whether
+ * the work has already been done to it. The full pipeline around this is covered by
+ * `image_compression.spec.ts`; what is asserted here is the reasoning itself, on the exact
+ * artifacts the tool writes.
+ */
+const JPEG_FORMAT: ImageFormat = { ext: "jpg", mime: "image/jpeg" };
+const PNG_FORMAT: ImageFormat = { ext: "png", mime: "image/png" };
+
+function request(overrides: Partial<ImageCompressionRequest> = {}): ImageCompressionRequest {
+ return {
+ resize: true,
+ maxWidthHeight: 2000,
+ jpegHandling: "compress",
+ pngHandling: "optimize",
+ quality: 75,
+ conversionQuality: 85,
+ ...overrides
+ };
+}
+
+/** The same picture at two qualities, straddling the default target. */
+let jpegAt60: Uint8Array;
+let jpegAt95: Uint8Array;
+/** A palette PNG — what quantizing produces — and the truecolour original it came from. */
+let indexedPng: Uint8Array;
+let truecolorPng: Uint8Array;
+
+beforeAll(async () => {
+ // Smooth, spatially correlated colour, so the encoders behave as they do on real pictures.
+ const photo = new Jimp({ width: 200, height: 150 });
+ const { data, width } = photo.bitmap;
+
+ for (let index = 0; index < data.length; index += 4) {
+ const x = (index / 4) % width;
+ const y = Math.floor(index / 4 / width);
+
+ data[index] = x % 256;
+ data[index + 1] = y % 256;
+ data[index + 2] = (x + y) % 256;
+ data[index + 3] = 255;
+ }
+
+ jpegAt60 = new Uint8Array(await photo.getBuffer("image/jpeg", { quality: 60 }));
+ jpegAt95 = new Uint8Array(await photo.getBuffer("image/jpeg", { quality: 95 }));
+ truecolorPng = new Uint8Array(await photo.getBuffer("image/png"));
+
+ const rgba = new Uint8Array(64 * 64 * 4);
+
+ for (let index = 0; index < rgba.length; index += 4) {
+ rgba[index] = (index / 4) % 8 * 32;
+ rgba[index + 3] = 255;
+ }
+
+ indexedPng = new Uint8Array(UPNG.encode([ rgba.buffer ], 64, 64, 256));
+});
+
+describe("settling an already-compressed image from its header", () => {
+ it("leaves a JPEG stored at or below the target quality alone, and only such a JPEG", () => {
+ expect(planFromBytes(JPEG_FORMAT, jpegAt60, request())).toEqual({ verdict: "skip", reason: "no-gain" });
+ // Above the target, re-encoding still buys something.
+ expect(planFromBytes(JPEG_FORMAT, jpegAt95, request()).verdict).toBe("proceed");
+ // The same image is above a lower target.
+ expect(planFromBytes(JPEG_FORMAT, jpegAt60, request({ quality: 50 })).verdict).toBe("proceed");
+ // A resize still owed overrides the quality reading entirely.
+ expect(planFromBytes(JPEG_FORMAT, jpegAt60, request({ maxWidthHeight: 100 })).verdict).toBe("proceed");
+ });
+
+ it("leaves an already-palettized PNG alone, except where it could still become a JPEG", () => {
+ // The premise the fixture rests on, asserted so an encoder change cannot quietly void it.
+ expect(inspectImage(indexedPng).indexed).toBe(true);
+
+ expect(planFromBytes(PNG_FORMAT, indexedPng, request())).toEqual({ verdict: "skip", reason: "no-gain" });
+ // Conversion can still gain on an indexed source, and a resize still owed always proceeds.
+ expect(planFromBytes(PNG_FORMAT, indexedPng, request({ pngHandling: "jpeg" })).verdict).toBe("proceed");
+ expect(planFromBytes(PNG_FORMAT, indexedPng, request({ maxWidthHeight: 32 })).verdict).toBe("proceed");
+ // The truecolour original has its quantization still ahead of it.
+ expect(planFromBytes(PNG_FORMAT, truecolorPng, request()).verdict).toBe("proceed");
+ });
+
+ it("skips on a second pass exactly what the first pass wrote, making runs idempotent", async () => {
+ const reencodedJpeg = await compressImageBytes(jpegAt95, request());
+ const quantizedPng = await compressImageBytes(truecolorPng, request());
+
+ if (!reencodedJpeg.compressed || !quantizedPng.compressed) {
+ throw new Error("expected the first pass to compress both fixtures");
+ }
+
+ // Without this, every run re-encoded its own output: the result lands a few bytes
+ // smaller each time, so the size guard never stops it, and quality erodes run by run.
+ expect(planFromBytes(JPEG_FORMAT, reencodedJpeg.buffer, request())).toEqual({ verdict: "skip", reason: "no-gain" });
+ expect(planFromBytes(PNG_FORMAT, quantizedPng.buffer, request())).toEqual({ verdict: "skip", reason: "no-gain" });
+ });
+});
diff --git a/apps/server/src/services/image_codec.ts b/apps/server/src/services/image_codec.ts
index d2c7bc04a0..c825b8678d 100644
--- a/apps/server/src/services/image_codec.ts
+++ b/apps/server/src/services/image_codec.ts
@@ -122,6 +122,16 @@ export function planFromBytes(
return { verdict: "skip", reason: "no-gain" };
}
+ // What is left to do is a re-encoding, and a file can show that it has already had one.
+ // Settled from the header rather than proven by decoding, which is what makes a second run
+ // over the same tree cost a glance per image instead of a decode — and what stops those
+ // re-encodings from shaving a little more quality off the same pixels on every run: writing
+ // a JPEG back at the quality it already has usually saves a few bytes, so the size guard
+ // after the decode never stops it.
+ if (!mayNeedResize && alreadyReencoded(isLossless, bytes, declared, request)) {
+ return { verdict: "skip", reason: "no-gain" };
+ }
+
if (exceedsDecodeCeiling(declared)) {
log(`Image of ${declared.width}x${declared.height} is too large to decode; leaving it alone.`);
@@ -131,6 +141,35 @@ export function planFromBytes(
return { verdict: "proceed", isLossless, worthReencoding, declared };
}
+/**
+ * Whether the one step left to do — re-encoding — has visibly already happened to this image.
+ * Consulted only once resizing is off the table, so this is the whole of what remains.
+ *
+ * A JPEG carries the quality it was written at in its quantization table; at or below the target,
+ * re-encoding buys nothing and costs a little of the picture, every time it is done. A PNG that
+ * already stores a palette is what quantizing would produce. Conversion stays out of this: an
+ * indexed PNG asked to become a JPEG can still come out smaller, so it is still worth attempting.
+ *
+ * Read from whatever bytes the caller had, and erring toward doing the work: a quality that cannot
+ * be read — an unusual table, or one sitting past the end of a header prefix — answers false, and
+ * the image is decoded exactly as before. The few points the estimate can be out by are accepted
+ * the other way too: a re-encoding it forgoes was itself marginal.
+ */
+function alreadyReencoded(
+ isLossless: boolean,
+ bytes: Uint8Array,
+ declared: InspectedImage,
+ request: ImageCompressionRequest
+): boolean {
+ if (isLossless) {
+ return request.pngHandling === "optimize" && declared.indexed === true;
+ }
+
+ const quality = estimateJpegQuality(bytes);
+
+ return quality !== null && quality <= request.quality;
+}
+
/**
* Whether decoding this would want more than one decode is allowed.
*
diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.ts
index d428cd9479..b872c98d45 100644
--- a/apps/server/src/services/image_compression.spec.ts
+++ b/apps/server/src/services/image_compression.spec.ts
@@ -535,6 +535,28 @@ describe("compression parameters", () => {
// The bound is quoted and ignored: nothing was asked to be measured against it.
expect(await decodedSize(noteId)).toEqual([ 600, 400 ]);
});
+
+ it("settles a second run from headers alone, leaving what the first run wrote untouched", async () => {
+ const jpegNoteId = await createImageNote(noisyJpeg, "root", "image/jpeg");
+ const pngNoteId = await createImageNote(noisyPng);
+ const body = { resize: true, maxWidthHeight: 300, jpegHandling: "compress", pngHandling: "optimize", quality: 75 };
+
+ for (const noteId of [ jpegNoteId, pngNoteId ]) {
+ const first = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, { body });
+
+ expect(first.body.items[0].compressed).toBe(true);
+
+ const written = readNote(noteId).size;
+ // The second run finds a JPEG already at the target quality and a PNG already storing
+ // a palette, and reports both as no-gain without decoding — or rewriting — either.
+ // Without that reading, each run re-encoded the last run's output a few bytes smaller,
+ // eroding quality and churning the database every time.
+ const second = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, { body });
+
+ expect(second.body.items[0]).toMatchObject({ compressed: false, skipReason: "no-gain" });
+ expect(readNote(noteId).size).toBe(written);
+ }
+ });
});
describe("compress one attachment (POST /api/attachments/:attachmentId/compress-image)", () => {
diff --git a/apps/server/src/services/image_worker_pool.spec.ts b/apps/server/src/services/image_worker_pool.spec.ts
new file mode 100644
index 0000000000..2d8c1e5d95
--- /dev/null
+++ b/apps/server/src/services/image_worker_pool.spec.ts
@@ -0,0 +1,146 @@
+import type { ImageCompressionRequest } from "@triliumnext/core/src/services/image_provider.js";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * The pool's failure semantics, with the processes themselves faked out: what separates "this
+ * installation cannot run workers, stop trying" from "this one image killed its worker, fail it
+ * alone". Getting that line wrong in the second direction hands the poison image to the thread
+ * serving the application — the freeze the pool exists to prevent.
+ */
+const h = vi.hoisted(() => {
+ type Handler = (...args: unknown[]) => void;
+
+ class FakeChild {
+ pid: number;
+ sent: unknown[] = [];
+ killed = false;
+ channel = { unref() {} };
+ private handlers = new Map<string, Handler[]>();
+
+ constructor(pid: number) {
+ this.pid = pid;
+ }
+
+ on(event: string, handler: Handler) {
+ this.handlers.set(event, [ ...(this.handlers.get(event) ?? []), handler ]);
+
+ return this;
+ }
+
+ emit(event: string, ...args: unknown[]) {
+ (this.handlers.get(event) ?? []).forEach((handler) => handler(...args));
+ }
+
+ send(message: unknown, callback?: (error: Error | null) => void) {
+ this.sent.push(message);
+ callback?.(null);
+
+ return true;
+ }
+
+ kill() {
+ this.killed = true;
+
+ return true;
+ }
+
+ unref() {}
+ }
+
+ const forked: InstanceType<typeof FakeChild>[] = [];
+ const forkOptions: { serialization?: string; execArgv?: string[] }[] = [];
+
+ return {
+ forked,
+ forkOptions,
+ fork(file: string, options: { serialization?: string; execArgv?: string[] }) {
+ void file;
+ forkOptions.push(options);
+
+ const child = new FakeChild(4000 + forked.length);
+
+ forked.push(child);
+
+ return child;
+ }
+ };
+});
+
+vi.mock("node:child_process", () => ({ fork: h.fork }));
+vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info() {}, error() {} }) }));
+
+const REQUEST: ImageCompressionRequest = {
+ resize: true,
+ maxWidthHeight: 800,
+ jpegHandling: "compress",
+ pngHandling: "optimize",
+ quality: 75,
+ conversionQuality: 85
+};
+
+const BYTES = new Uint8Array([ 1, 2, 3 ]);
+
+/** Lets the pool's ready-gate promise chain and send callbacks run to completion. */
+async function flush() {
+ await new Promise((resolve) => setImmediate(resolve));
+ await new Promise((resolve) => setImmediate(resolve));
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ h.forked.length = 0;
+ h.forkOptions.length = 0;
+});
+
+describe("worker pool failure semantics", () => {
+ it("fails a poison image alone once any worker has announced, and replaces its worker", async () => {
+ const pool = await import("./image_worker_pool.js");
+ const first = pool.compressInWorker(BYTES, REQUEST, 1024);
+
+ await flush();
+
+ const child = h.forked[0];
+
+ expect(child).toBeDefined();
+ // The bytes only survive the channel under structured clone; JSON would mangle them.
+ expect(h.forkOptions[0]).toMatchObject({ serialization: "advanced" });
+
+ // The image goes out only once the child has provably attached its listener.
+ expect(child.sent).toHaveLength(0);
+ child.emit("message", { trace: "worker 4000: loaded and listening" });
+ await flush();
+ expect(child.sent).toHaveLength(1);
+
+ // The decode takes the worker down mid-image: the image fails, the pool does not.
+ child.emit("exit", 1, null);
+ await expect(first).rejects.toThrow("exited with code 1");
+ expect(child.killed).toBe(true);
+
+ const second = pool.compressInWorker(BYTES, REQUEST, 1024);
+
+ await flush();
+
+ const replacement = h.forked[1];
+
+ expect(replacement).toBeDefined();
+ replacement.emit("message", { trace: "worker 4001: loaded and listening" });
+ await flush();
+ replacement.emit("message", { id: (replacement.sent[0] as { id: number }).id, outcome: { compressed: false, reason: "no-gain" }, logs: [] });
+ await expect(second).resolves.toMatchObject({ compressed: false, reason: "no-gain" });
+ });
+
+ it("gives up on workers for good only when none has ever spoken", async () => {
+ const pool = await import("./image_worker_pool.js");
+ const first = pool.compressInWorker(BYTES, REQUEST, 1024);
+
+ await flush();
+ // Dead before its announce: nothing has proven workers can run here at all.
+ h.forked[0].emit("exit", 127, null);
+
+ await expect(first).resolves.toBeNull();
+
+ // Disabled: the next image is answered without so much as a spawn attempt.
+ await expect(pool.compressInWorker(BYTES, REQUEST, 1024)).resolves.toBeNull();
+ expect(h.forked).toHaveLength(1);
+ });
+});
diff --git a/apps/server/src/services/image_worker_pool.ts b/apps/server/src/services/image_worker_pool.ts
index dc359eda47..80338ebdcf 100644
--- a/apps/server/src/services/image_worker_pool.ts
+++ b/apps/server/src/services/image_worker_pool.ts
@@ -83,8 +83,6 @@ export async function compressInWorker(
try {
const response = await send(worker, buffer, request, budgetMb);
- everSucceeded = true;
-
// The worker's own logging, written here because here is where a logger exists.
response.logs.forEach((line) => getLog().info(line));
@@ -101,18 +99,22 @@ export async function compressInWorker(
// hanging rather than like one image having failed.
retire(worker);
- // Nothing has ever come back from a worker here, so this is not one process having died but
- // this installation being unable to run them — an environment whose loader cannot read the
- // entry point, say. Answered as "there are no workers", which is the truth of it: this image
- // and every one after it is compressed by the caller, exactly as before there were workers.
- if (!everSucceeded) {
+ // No worker has ever so much as announced itself, so this is not one process having died
+ // but this installation being unable to run them — an environment whose loader cannot read
+ // the entry point, say. Answered as "there are no workers", which is the truth of it: this
+ // image and every one after it is compressed by the caller, exactly as before there were
+ // workers.
+ if (!everSpoke) {
return disable(`they do not work here (${firstLine(e)})`);
}
- // Workers do work here, and one of them failed on this image. Raised rather than answered
- // with a fallback: doing it on the calling thread instead would stop the application for the
- // length of a decode, and doing that for each of several failing workers is how a run takes
- // the whole application down with it. The image is reported untouched and the run goes on.
+ // Workers run here — one announced itself, which took spawning, the loader and the channel
+ // all working — so this failure belongs to the image: a decode that blew through the heap,
+ // say, taking its worker with it. Raised rather than answered with a fallback, and
+ // emphatically not treated as the installation being broken: decoding this image on the
+ // calling thread would stop the application for the length of a decode — the very freeze
+ // the pool exists to prevent, handed to exactly the image that just proved too much for a
+ // worker. The image is reported untouched and the run goes on.
throw e;
}
}
@@ -175,7 +177,13 @@ const idle: PooledWorker[] = [];
const waiting: ((worker: PooledWorker | null) => void)[] = [];
let started = 0;
let disabled = false;
-let everSucceeded = false;
+/**
+ * Whether any worker has ever sent anything back — its startup announce being the first thing one
+ * says. That is proof the installation can run workers at all, which is the line between "give up
+ * on workers for good" and "this one image failed": everything a worker needs to exist — spawning,
+ * the loader, the channel home — has demonstrably worked once.
+ */
+let everSpoke = false;
async function acquire(): Promise<PooledWorker | null> {
if (disabled) {
@@ -291,6 +299,7 @@ function spawn(): PooledWorker | null {
() => getLog().info(`Image Compression Tool: worker ${pooled.pid} online in ${Date.now() - startedAt}ms`));
pooled.worker.on("message", (response: ImageWorkerResponse | ImageWorkerTrace) => {
+ everSpoke = true;
readiness.arrived?.();
// Traces arrive while the image is still being worked on, so they are written straight