Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
core/image compression: try to auto-determine JPEG quality for resized images
Adorian Doran5d0cb3fe9e2d
diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.tsindex 49a94e7906..fe459ffef2 100644--- a/apps/server/src/services/image_provider.spec.ts+++ b/apps/server/src/services/image_provider.spec.ts@@ -3,6 +3,7 @@ import { Jimp } from 'jimp';import { afterEach, beforeAll, describe, expect, it } from 'vitest';import { serverImageProvider } from './image_provider.js';+import { estimateJpegQuality } from './jpeg_quality.js';// is-svg / image-type / is-animated / jimp are all loaded by spec/setup.ts (which// imports serverImageProvider to initialise core), so they cannot be re-mocked@@ -25,6 +26,12 @@ let corruptPng: Uint8Array; // valid PNG signature but unreadable by jimplet transparentPng: Uint8Array; // 600x400 noisy, every pixel half-transparentlet noisyJpeg: Uint8Array; // 600x400 noisy jpeg stored at high qualitylet tinyJpeg: Uint8Array; // 8x8 jpeg that cannot get any smaller+/**+ * A photograph already saved cheaply, which is what most JPEGs in a note are. Re-encoding one of+ * these at a fixed high quality costs more bytes per pixel than a modest resize removes, so it is+ * the case that catches a "keep" path which does not honour the source's own quality.+ */+let lowQualityJpeg: Uint8Array;/*** A photograph's shape rather than a photograph: smooth, spatially correlated colour over* thousands of distinct values. PNG stores that poorly and JPEG stores it well, which is the@@ -93,6 +100,7 @@ beforeAll(async () => {}}photoPng = new Uint8Array(await photo.getBuffer('image/png'));+ lowQualityJpeg = new Uint8Array(await photo.getBuffer('image/jpeg', { quality: 40 }));}, 30000);afterEach(() => {@@ -419,6 +427,33 @@ describe('serverImageProvider.compressImage', () => {if (!compressed.compressed) throw new Error('expected it to compress');expect(atLow.buffer.byteLength).toBeGreaterThan(compressed.buffer.byteLength);});++ it('re-encodes a scaled "keep" JPEG at the quality it already had', async () => {+ const outcome = await serverImageProvider.compressImage(+ lowQualityJpeg, request({ jpegHandling: 'keep', maxWidthHeight: 400 }));++ if (!outcome.compressed) throw new Error('expected it to compress');++ // Read back off the result's own quantization table: "keep" means the image comes out+ // encoded as it went in, the scaling being the only thing given up.+ const estimate = estimateJpegQuality(outcome.buffer) ?? 0;+ expect(Math.abs(estimate - 40)).toBeLessThanOrEqual(8);+ });++ it('actually shrinks a modest resize of a cheaply saved JPEG', async () => {+ // The regression this is all for. Re-encoding at a fixed high quality costs more bytes+ // per pixel than a 16% reduction removes, so the result grows, the size guard rejects+ // it, and the resize the user asked for silently does not happen.+ const outcome = await serverImageProvider.compressImage(+ lowQualityJpeg, request({ jpegHandling: 'keep', maxWidthHeight: 550 }));++ expect(outcome.compressed).toBe(true);+ if (!outcome.compressed) return;+ expect(outcome.buffer.byteLength).toBeLessThan(lowQualityJpeg.byteLength);++ const decoded = await Jimp.read(Buffer.from(outcome.buffer));+ expect([ decoded.bitmap.width, decoded.bitmap.height ]).toEqual([ 550, 367 ]);+ });});it.each([diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex 1cfeba54c3..2690074789 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -11,6 +11,8 @@ import isSvg from "is-svg";import { Jimp } from "jimp";import * as UPNG from "upng-js";+import { estimateJpegQuality } from "./jpeg_quality.js";+const JPEG_FORMAT: ImageFormat = { ext: "jpg", mime: "image/jpeg" };const PNG_FORMAT: ImageFormat = { ext: "png", mime: "image/png" };@@ -194,7 +196,7 @@ export const serverImageProvider: ImageProvider = {// Reached either by conversion, which has already established there is no transparency// to lose, or by a JPEG source, which never had any to begin with.image.background = 0xffffffff;- result = await image.getBuffer("image/jpeg", { quality: jpegQualityFor(request, isLossless) });+ result = await image.getBuffer("image/jpeg", { quality: jpegQualityFor(request, isLossless, buffer) });} else if (quantize) {result = quantizePng(image, buffer.byteLength);} else {@@ -213,27 +215,34 @@ export const serverImageProvider: ImageProvider = {};/**- * Which of the two qualities a JPEG about to be written is owed. Converting a pristine original and- * recompressing an already-lossy one are different trades, so each has its own.+ * Which quality a JPEG about to be written is owed. Converting a pristine original and recompressing+ * an already-lossy one are different trades, so each has a setting of its own.*- * The third case has neither: a JPEG that is only being scaled, its handling left on `keep`. It has- * to be re-encoded all the same — there is no way to write scaled pixels without one — so it goes- * out at {@link RESIZE_QUALITY}, high enough that "keep" is not quietly made to mean "degrade".+ * The third case has neither: a JPEG only being scaled, its handling left on `keep`. It has to be+ * re-encoded all the same — there is no way to write scaled pixels without one — so it goes out at+ * whatever quality it was already stored at, read off its own quantization table. Anything fixed+ * would be wrong in both directions: below the source it degrades an image nobody asked to degrade,+ * and above it the bytes-per-pixel rise can outweigh the pixels removed, leaving a modest resize+ * *larger* than it started and rejected by the size guard — the resize silently undone.*/-function jpegQualityFor(request: ImageCompressionRequest, isLossless: boolean): number {+function jpegQualityFor(request: ImageCompressionRequest, isLossless: boolean, source: Uint8Array): number {if (isLossless) {return request.conversionQuality;}- return request.jpegHandling === "compress" ? request.quality : RESIZE_QUALITY;+ if (request.jpegHandling === "compress") {+ return request.quality;+ }++ return estimateJpegQuality(source) ?? FALLBACK_RESIZE_QUALITY;}/**- * What a JPEG is re-encoded at when nothing asked for it to be recompressed and only the scaling- * forced a rewrite. Near enough to lossless that the loss is not the point of the operation, while- * still far below the size a quality of 100 would produce for no visible return.+ * Stands in when a JPEG's own quality cannot be read — an unusual table, or an encoder that scales+ * the standard one its own way. High enough that "keep" is not quietly made to mean "degrade",+ * accepting that a mild resize of a heavily compressed original may then not pay for itself.*/-const RESIZE_QUALITY = 92;+const FALLBACK_RESIZE_QUALITY = 92;/*** Rewrites the image as a palette PNG, which is where a PNG's weight actually goes: the savingdiff --git a/apps/server/src/services/jpeg_quality.spec.ts b/apps/server/src/services/jpeg_quality.spec.tsnew file mode 100644index 0000000000..bcd7e9c44c--- /dev/null+++ b/apps/server/src/services/jpeg_quality.spec.ts@@ -0,0 +1,82 @@+import { Jimp } from "jimp";+import { beforeAll, describe, expect, it } from "vitest";++import { estimateJpegQuality } from "./jpeg_quality.js";++/**+ * Round-trips real JPEGs through the estimator: encode at a known quality, read it back off the+ * quantization table. Jimp's encoder scales the standard table the way libjpeg does, which is the+ * relationship the estimator inverts, so agreement here is the whole test.+ */+let photo: InstanceType<typeof Jimp>;++beforeAll(() => {+ photo = new Jimp({ width: 240, height: 160, color: 0x000000ff });+ for (let x = 0; x < 240; x++) {+ for (let y = 0; y < 160; y++) {+ const r = Math.round(128 + 127 * Math.sin(x / 20));+ const g = Math.round(128 + 127 * Math.sin(y / 15));+ const b = Math.round(128 + 127 * Math.sin((x + y) / 25));+ photo.setPixelColor((((r << 24) | (g << 16) | (b << 8) | 0xff) >>> 0), x, y);+ }+ }+});++async function encodedAt(quality: number): Promise<Uint8Array> {+ return new Uint8Array(await photo.getBuffer("image/jpeg", { quality }));+}++describe("estimateJpegQuality", () => {+ it.each([ 20, 40, 60, 75, 85, 95 ])("reads back a quality of %i within a few points", async (quality) => {+ const estimate = estimateJpegQuality(await encodedAt(quality));++ expect(estimate).not.toBeNull();+ expect(Math.abs((estimate ?? 0) - quality)).toBeLessThanOrEqual(5);+ });++ it("reads the top of the range as the top of the range", async () => {+ // Every coefficient is 1 there, which is the case the estimator has least to work with.+ const estimate = estimateJpegQuality(await encodedAt(100));++ expect(estimate).toBeGreaterThanOrEqual(95);+ expect(estimate).toBeLessThanOrEqual(100);+ });++ it("orders estimates as the qualities they came from are ordered", async () => {+ const estimates = await Promise.all([ 30, 50, 70, 90 ].map(async (quality) => (+ estimateJpegQuality(await encodedAt(quality)) ?? 0+ )));++ expect(estimates).toEqual([ ...estimates ].sort((a, b) => a - b));+ });++ it("finds the table behind an EXIF segment rather than giving up at the first marker", async () => {+ const jpeg = Buffer.from(await encodedAt(60));+ // A JPEG straight off a camera carries APP1 before its tables; walking the segments has to+ // step over it rather than assume the table comes first.+ const app1 = Buffer.concat([+ Buffer.from([ 0xff, 0xe1, 0x00, 0x10 ]),+ Buffer.from("Exif\0\0", "latin1"),+ Buffer.alloc(8)+ ]);+ const withExif = new Uint8Array(Buffer.concat([ jpeg.subarray(0, 2), app1, jpeg.subarray(2) ]));++ expect(Math.abs((estimateJpegQuality(withExif) ?? 0) - 60)).toBeLessThanOrEqual(5);+ });++ it.each([+ [ "a PNG", () => new Uint8Array([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4 ]) ],+ [ "an empty buffer", () => new Uint8Array() ],+ [ "a bare SOI with nothing after it", () => new Uint8Array([ 0xff, 0xd8 ]) ],+ [ "a JPEG whose segments do not line up", () => new Uint8Array([ 0xff, 0xd8, 0x12, 0x34, 0x56, 0x78 ]) ]+ ])("answers nothing for %s, leaving the caller its own fallback", (_label, build) => {+ expect(estimateJpegQuality(build())).toBeNull();+ });++ it("answers nothing for a JPEG truncated before its tables", async () => {+ const jpeg = await encodedAt(60);++ // Cut at the SOI: the scan reaches the end of the buffer without meeting a DQT.+ expect(estimateJpegQuality(jpeg.slice(0, 2))).toBeNull();+ });+});diff --git a/apps/server/src/services/jpeg_quality.ts b/apps/server/src/services/jpeg_quality.tsnew file mode 100644index 0000000000..cbea7e06e4--- /dev/null+++ b/apps/server/src/services/jpeg_quality.ts@@ -0,0 +1,184 @@+/**+ * Recovers the quality setting a JPEG was written at, by reading the quantization table it carries.+ *+ * Needed because re-encoding is unavoidable whenever an image is scaled: there is no way to write+ * new pixels without one. Choosing a fixed quality for that would be wrong in both directions — too+ * low quietly degrades an image nobody asked to degrade, and too high inflates bytes-per-pixel so+ * far that a modest resize produces a *larger* file than it started from, and gets rejected, leaving+ * the resize silently undone. Re-encoding at the quality the image already had avoids both.+ */++/**+ * The quality `buffer` appears to have been written at, 1 to 100, or `null` when that cannot be+ * read — a buffer that is not a JPEG, one carrying no luminance table, or one whose table says+ * nothing usable. Callers pick their own fallback.+ *+ * Approximate by nature: it inverts the scaling libjpeg applies to the standard table, so an+ * encoder that scales differently is estimated a few points out. That is harmless here, where the+ * figure only picks a re-encoding target rather than reproducing anything exactly.+ */+export function estimateJpegQuality(buffer: Uint8Array): number | null {+ const table = readLuminanceQuantizationTable(buffer);++ return table ? qualityFromTable(table) : null;+}++/**+ * Inverts libjpeg's scaling of the standard table. It writes each coefficient as+ * `(standard * scale + 50) / 100` clamped into a byte, so each one that did not hit that clamp+ * gives back an estimate of `scale`, and the median of those is robust against the few that did.+ */+function qualityFromTable(table: number[]): number | null {+ const scales: number[] = [];++ for (let index = 0; index < COEFFICIENT_COUNT; index++) {+ // A coefficient pinned at the top of the byte range was clamped rather than scaled, so it+ // carries no information about how far it was scaled. Ones pinned at the bottom are kept:+ // at high quality most of the table is 1s, and dropping them would leave nothing to read.+ if (table[index] >= MAX_COEFFICIENT) {+ continue;+ }++ scales.push((table[index] * 100 - 50) / STANDARD_LUMINANCE[ZIGZAG_TO_NATURAL[index]]);+ }++ if (scales.length === 0) {+ return null;+ }++ const scale = median(scales);+ // The other half of libjpeg's mapping, run backwards.+ const quality = scale < 100 ? (200 - scale) / 2 : 5000 / scale;++ return Math.min(Math.max(Math.round(quality), 1), 100);+}++/**+ * The 64 luminance coefficients, in the zig-zag order they are stored in, or `null` if the buffer+ * holds no such table.+ *+ * Walks the segment structure rather than searching for the marker bytes, since `FF DB` occurs+ * freely inside entropy-coded data and thumbnails.+ */+function readLuminanceQuantizationTable(buffer: Uint8Array): number[] | null {+ if (buffer.length < 4 || buffer[0] !== 0xff || buffer[1] !== MARKER_SOI) {+ return null;+ }++ let offset = 2;++ while (offset + 3 < buffer.length) {+ if (buffer[offset] !== 0xff) {+ // Out of step with the segments; nothing further can be read with any confidence.+ return null;+ }++ const marker = buffer[offset + 1];++ if (marker === 0xff) {+ // Fill bytes are allowed to pad ahead of a marker.+ offset++;+ continue;+ }++ if (marker === MARKER_SOI || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {+ // Standalone markers carry no length to skip by.+ offset += 2;+ continue;+ }++ if (marker === MARKER_SOS || marker === MARKER_EOI) {+ // Entropy-coded data begins here, and every table precedes it.+ return null;+ }++ const length = (buffer[offset + 2] << 8) | buffer[offset + 3];++ if (length < 2 || offset + 2 + length > buffer.length) {+ return null;+ }++ if (marker === MARKER_DQT) {+ const table = findLuminanceTable(buffer, offset + 4, offset + 2 + length);++ if (table) {+ return table;+ }+ }++ offset += 2 + length;+ }++ return null;+}++/** One DQT segment can hold several tables back to back; only the luminance one is wanted. */+function findLuminanceTable(buffer: Uint8Array, start: number, end: number): number[] | null {+ let offset = start;++ while (offset < end) {+ const precision = buffer[offset] >> 4;+ const identifier = buffer[offset] & 0x0f;+ const bytesPerCoefficient = precision === 0 ? 1 : 2;+ const size = COEFFICIENT_COUNT * bytesPerCoefficient;++ offset++;++ if (offset + size > end) {+ return null;+ }++ if (identifier === LUMINANCE_TABLE_ID) {+ return Array.from({ length: COEFFICIENT_COUNT }, (_unused, index) => (+ bytesPerCoefficient === 1+ ? buffer[offset + index]+ : (buffer[offset + index * 2] << 8) | buffer[offset + index * 2 + 1]+ ));+ }++ offset += size;+ }++ return null;+}++function median(values: number[]): number {+ const sorted = [ ...values ].sort((a, b) => a - b);+ const middle = Math.floor(sorted.length / 2);++ return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];+}++const MARKER_SOI = 0xd8;+const MARKER_DQT = 0xdb;+const MARKER_SOS = 0xda;+const MARKER_EOI = 0xd9;++/** Table 0 is the luminance one by convention, and the one whose scaling tracks the quality. */+const LUMINANCE_TABLE_ID = 0;+const COEFFICIENT_COUNT = 64;+const MAX_COEFFICIENT = 255;++/** The standard luminance quantization table (JPEG Annex K), in natural row-major order. */+const STANDARD_LUMINANCE = [+ 16, 11, 10, 16, 24, 40, 51, 61,+ 12, 12, 14, 19, 26, 58, 60, 55,+ 14, 13, 16, 24, 40, 57, 69, 56,+ 14, 17, 22, 29, 51, 87, 80, 62,+ 18, 22, 37, 56, 68, 109, 103, 77,+ 24, 35, 55, 64, 81, 104, 113, 92,+ 49, 64, 78, 87, 103, 121, 120, 101,+ 72, 92, 95, 98, 112, 100, 103, 99+];++/** Where each zig-zag position lands in the natural order above, tables being stored zig-zagged. */+const ZIGZAG_TO_NATURAL = [+ 0, 1, 8, 16, 9, 2, 3, 10,+ 17, 24, 32, 25, 18, 11, 4, 5,+ 12, 19, 26, 33, 40, 48, 41, 34,+ 27, 20, 13, 6, 7, 14, 21, 28,+ 35, 42, 49, 56, 57, 50, 43, 36,+ 29, 22, 15, 23, 30, 37, 44, 51,+ 58, 59, 52, 45, 38, 31, 39, 46,+ 53, 60, 61, 54, 47, 55, 62, 63+];