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: do not retrieve the whole BLOB for reading the image size
Adorian Doran85679256adb2
diff --git a/apps/build-docs/src/build-docs.ts b/apps/build-docs/src/build-docs.tsindex a54bb50ca6..fcff3152ed 100644--- a/apps/build-docs/src/build-docs.ts+++ b/apps/build-docs/src/build-docs.ts@@ -41,7 +41,8 @@ const stubImageProvider: ImageProvider = {processImage: async () => {throw new Error("Image processing not supported in build-docs");},- compressImage: async () => ({ compressed: false, reason: "unsupported-platform" })+ compressImage: async () => ({ compressed: false, reason: "unsupported-platform" }),+ planCompression: async () => "unsupported-platform"};import { ZipArchive } from "archiver";import { execSync } from "child_process";diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex 5bc7488282..5058b5859e 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -1,5 +1,6 @@import type { ImageCompressionResponse } from "@triliumnext/commons";import { becca, cls, getSql, options } from "@triliumnext/core";+import { collectNoteTargets, HEADER_BYTES } from "@triliumnext/core/src/services/image_compression.js";import { getImageProvider, initImageProvider } from "@triliumnext/core/src/services/image_provider.js";import { createTextNote } from "@triliumnext/core/src/test/api_fixtures.js";import { CoreApiTester } from "@triliumnext/core/src/test/api_tester.js";@@ -370,6 +371,40 @@ describe("compression parameters", () => {expect(readAttachment(attachmentId).size).toBe(corruptPng.byteLength);});+ it("reads the front of an image and its weight, leaving the body of it in the database", async () => {+ const { noteId } = await createTextNote(api);+ const attachmentId = await addAttachment(noteId, "big.png", noisyPng);++ const peeked = cls.init(() => {+ const target = collectNoteTargets(becca.getNoteOrThrow(noteId), false)+ .find((candidate) => candidate.entityId === attachmentId);++ return target?.peek();+ });++ // The weight is the whole image's, counted by the database; the bytes are only its front.+ expect(peeked?.size).toBe(noisyPng.byteLength);+ expect(noisyPng.byteLength).toBeGreaterThan(HEADER_BYTES);+ expect(peeked?.header.byteLength).toBe(HEADER_BYTES);+ expect(Array.from(peeked?.header.slice(0, 8) ?? [])).toEqual(Array.from(noisyPng.slice(0, 8)));+ });++ it("still compresses a JPEG whose dimensions sit past the front of the file", async () => {+ const { noteId } = await createTextNote(api);+ // Metadata ahead of the frame header, as a camera's thumbnail or a colour profile leaves it:+ // nothing in the peeked bytes says how large the image is, so the run has to read it in full+ // rather than assume. Getting that wrong would silently stop resizing such photographs.+ const padded = withLeadingMetadata(noisyJpeg);+ const attachmentId = await addAttachment(noteId, "padded.jpg", padded, { mime: "image/jpeg" });++ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {+ body: { resize: true, maxWidthHeight: 200, jpegHandling: "keep", pngHandling: "keep" }+ });++ expect(res.body.items[0]).toMatchObject({ entityId: attachmentId, compressed: true });+ expect(readAttachment(attachmentId).size).toBeLessThan(padded.byteLength);+ });+it("refuses an image too large to decode rather than failing part-way through one", async () => {const { noteId } = await createTextNote(api);// 400 megapixels by its own header — well past what one decode is allowed. The bytes behind@@ -526,6 +561,29 @@ function paintPhoto(image: InstanceType<typeof Jimp>, alpha: number) {}}+/**+ * The same JPEG behind two segments of filler metadata, as a camera's thumbnail or an embedded+ * colour profile sits ahead of the frame header — enough of it that nothing in the bytes a run+ * peeks at says how large the picture is.+ */+function withLeadingMetadata(jpeg: Uint8Array): Uint8Array {+ // A JPEG segment's length field counts itself, and is two bytes, so this is the largest one.+ const payloadBytes = 65533;+ const segment = new Uint8Array(4 + payloadBytes);+ segment[0] = 0xff;+ segment[1] = 0xe1;+ new DataView(segment.buffer).setUint16(2, payloadBytes + 2);++ const padded = new Uint8Array(2 + segment.byteLength * 2 + jpeg.byteLength - 2);+ padded.set([ 0xff, 0xd8 ]);+ padded.set(segment, 2);+ padded.set(segment, 2 + segment.byteLength);+ // Everything after the original's own start-of-image marker, which is now carried above.+ padded.set(jpeg.subarray(2), 2 + segment.byteLength * 2);++ return padded;+}+/*** The same PNG, its IHDR rewritten to claim the given dimensions — width and height sit at fixed* offsets, and nothing on this path verifies the chunk's checksum. A header that lies about how@@ -603,6 +661,7 @@ async function whileCompressing<T>(interfere: () => void, request: () => PromiseinitImageProvider({getImageType: (buffer) => real.getImageType(buffer),processImage: (buffer, originalName, shrink) => real.processImage(buffer, originalName, shrink),+ planCompression: (header, compressionRequest) => real.planCompression(header, compressionRequest),compressImage: (buffer, compressionRequest) => {interfere();return real.compressImage(buffer, compressionRequest);diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex 128d4e69dc..1691c37dff 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -3,7 +3,7 @@* Uses JIMP for image processing with full compression support.*/-import { IMAGE_COMPRESSIBLE_FORMATS } from "@triliumnext/commons";+import { IMAGE_COMPRESSIBLE_FORMATS, type ImageCompressionSkipReason } from "@triliumnext/commons";import { estimateJpegQuality, getLog, type InspectedImage, inspectImage, options as optionService } from "@triliumnext/core";import type { ImageCompressionOutcome, ImageCompressionRequest, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core/src/services/image_provider.js";import imageType from "image-type";@@ -57,6 +57,67 @@ const DECODE_BYTES_PER_PIXEL = 16;*/const MAX_DECODE_PIXELS = Math.floor((DECODE_MEMORY_MB * 1024 * 1024) / DECODE_BYTES_PER_PIXEL);+type CompressionPlan =+ | { verdict: "skip"; reason: ImageCompressionSkipReason }+ | { verdict: "proceed"; isLossless: boolean; worthReencoding: boolean };++/**+ * What is to become of an image, decided from as much of it as the caller had.+ *+ * Every question here is answered from the header, which is what lets the same reasoning serve a+ * run deciding whether an image is worth reading at all and the compression that follows once it+ * has been. Given only the front of a file it errs one way: a dimension it cannot reach leaves the+ * image to be read in full, never leaves it skipped on a reading that was never taken.+ */+function planFromBytes(+ format: ImageFormat | null,+ bytes: Uint8Array,+ request: ImageCompressionRequest+): CompressionPlan {+ if (!format || !COMPRESSIBLE_EXTENSIONS.has(format.ext)) {+ return { verdict: "skip", reason: "unsupported-format" };+ }++ /* v8 ignore start -- the same rare defensive guard as in processImage above: spec-compliant+ animated images already fail the format gate (file-type reports animated PNG as "apng"+ and animated GIF/WebP as gif/webp). Only a pathological PNG with 512+ chunks before its+ acTL chunk reaches here, and recompressing it would keep the first frame alone. */+ if (isAnimated(Buffer.from(bytes))) {+ return { verdict: "skip", reason: "animated" };+ }+ /* v8 ignore stop */++ const isLossless = format.ext === "png";++ // Whether re-encoding alone is worth doing to *this* image, each kind answering for itself:+ // a lossy source when its handling asks for it, a lossless one when its handling asks for+ // anything at all — rewriting a PNG as the same PNG at its own size gains nothing.+ //+ // A PNG's transparency does not enter into it, though it decides *which* re-encoding happens:+ // an image `jpeg` cannot take is quantized instead, so either way there is one to do. That is+ // what lets this be answered before the image is decoded.+ const worthReencoding = isLossless ? request.pngHandling !== "keep" : request.jpegHandling === "compress";++ // Read off the header rather than from the pixels: deciding whether anything is going to happen+ // to an image should not cost more than doing it. Dimensions the header does not give up — past+ // the end of a prefix, or behind metadata — leave this open, and the decode settles it.+ const declared = inspectImage(bytes);+ const declaredEdge = Math.max(declared.width ?? 0, declared.height ?? 0);+ const mayNeedResize = request.resize && (declaredEdge === 0 || declaredEdge > request.maxWidthHeight);++ if (!mayNeedResize && !worthReencoding) {+ return { verdict: "skip", reason: "no-gain" };+ }++ if (exceedsDecodeCeiling(declared)) {+ getLog().info(`Image of ${declared.width}x${declared.height} is too large to decode; leaving it alone.`);++ return { verdict: "skip", reason: "too-large" };+ }++ return { verdict: "proceed", isLossless, worthReencoding };+}+/*** Whether the header claims more pixels than {@link MAX_DECODE_PIXELS} allows.*@@ -243,51 +304,23 @@ export const serverImageProvider: ImageProvider = {return { buffer: finalBuffer, format };},- async compressImage(buffer: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionOutcome> {- const format = await getImageTypeFromBuffer(buffer);-- if (!format || !COMPRESSIBLE_EXTENSIONS.has(format.ext)) {- return { compressed: false, reason: "unsupported-format" };- }-- /* v8 ignore start -- the same rare defensive guard as in processImage above: spec-compliant- animated images already fail the format gate (file-type reports animated PNG as "apng"- and animated GIF/WebP as gif/webp). Only a pathological PNG with 512+ chunks before its- acTL chunk reaches here, and recompressing it would keep the first frame alone. */- if (isAnimated(Buffer.from(buffer))) {- return { compressed: false, reason: "animated" };- }- /* v8 ignore stop */+ async planCompression(header: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionSkipReason | null> {+ const plan = planFromBytes(await getImageTypeFromBuffer(header), header, request);- const isLossless = format.ext === "png";-- // Whether re-encoding alone is worth doing to *this* image, each kind answering for itself:- // a lossy source when its handling asks for it, a lossless one when its handling asks for- // anything at all — rewriting a PNG as the same PNG at its own size gains nothing.- //- // A PNG's transparency does not enter into it, though it decides *which* re-encoding- // happens: an image `jpeg` cannot take is quantized instead, so either way there is one to- // do. That is what lets this be answered before the image is decoded.- const worthReencoding = isLossless ? request.pngHandling !== "keep" : request.jpegHandling === "compress";-- // Read off the header rather than from the pixels: deciding whether anything is going to- // happen to an image should not cost more than doing it. Dimensions the header does not- // give up leave this open, and the exact answer is taken from the decode below.- const declared = inspectImage(buffer);- const declaredEdge = Math.max(declared.width ?? 0, declared.height ?? 0);- const mayNeedResize = request.resize && (declaredEdge === 0 || declaredEdge > request.maxWidthHeight);-- if (!mayNeedResize && !worthReencoding) {- return { compressed: false, reason: "no-gain" };- }+ return plan.verdict === "skip" ? plan.reason : null;+ },- if (exceedsDecodeCeiling(declared)) {- getLog().info(- `Image of ${declared.width}x${declared.height} is too large to decode; leaving it alone.`);+ async compressImage(buffer: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionOutcome> {+ // Asked again of the whole image, whatever a header was already judged on: the caller may+ // have skipped that step entirely, and where it did not, this is the reading that had the+ // bytes the other one was missing.+ const plan = planFromBytes(await getImageTypeFromBuffer(buffer), buffer, request);- return { compressed: false, reason: "too-large" };+ if (plan.verdict === "skip") {+ return { compressed: false, reason: plan.reason };}+ const { isLossless, worthReencoding } = plan;const start = Date.now();const image = await decodeImage(buffer);const { width, height } = image.bitmap;diff --git a/apps/standalone/src/services/image_provider.ts b/apps/standalone/src/services/image_provider.tsindex dc13c6f1ec..61d052c40d 100644--- a/apps/standalone/src/services/image_provider.ts+++ b/apps/standalone/src/services/image_provider.ts@@ -4,6 +4,7 @@* Images are saved as-is without resizing.*/+import type { ImageCompressionSkipReason } from "@triliumnext/commons";import type { ImageCompressionOutcome, ImageFormat, ImageProvider, ProcessedImage } from "@triliumnext/core";import { inspectImage, UNKNOWN_FORMAT } from "@triliumnext/core/src/services/image_inspect.js";@@ -36,5 +37,11 @@ export const standaloneImageProvider: ImageProvider = {// No decoder here, so there is nothing to recompress with — the request is answered rather// than refused, and the caller reports the images as untouched along with the reason.return { compressed: false, reason: "unsupported-platform" };+ },++ async planCompression(): Promise<ImageCompressionSkipReason> {+ // Settled before an image is so much as weighed: nothing here is going to compress it+ // whatever its header says, so a run over a tree reads none of them.+ return "unsupported-platform";}};diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex b1d2a10698..678da69311 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -149,6 +149,23 @@ function defaultQuality(): number {* (a canvas addresses its images by the Excalidraw file id stored as the title), and download and* export filenames already derive their extension from the mime when the title disagrees.*/+/** What an image weighs, and enough of its front to say what it is. */+export interface TargetPeek {+ /** The stored image's size in bytes — the whole of it, not of {@link header}. */+ size: number;+ header: Uint8Array;+}++/**+ * How much of an image is read to identify it.+ *+ * A PNG states its dimensions within the first thirty-odd bytes, but a JPEG states them after+ * whatever metadata precedes them, and a camera's EXIF thumbnail or an embedded colour profile can+ * run to tens of kilobytes. This is picked to clear those: past it the reading simply comes back+ * without dimensions, and the image is read in full as it was before — slower, never wrong.+ */+export const HEADER_BYTES = 64 * 1024;+export interface CompressionTarget {entityType: "note" | "attachment";entityId: string;@@ -157,6 +174,17 @@ export interface CompressionTarget {/** Set when the target must be left alone for a reason known before reading its content. */skip?: ImageCompressionSkipReason;getContent(): Uint8Array;+ /**+ * The image's size and its opening bytes, taken from the database without loading the rest.+ *+ * What decides an image's fate is almost entirely in its header, and reading a whole photograph+ * to look at thirty bytes of it is most of what a run over a large tree spends its time on.+ *+ * Null where the bytes in the database are not the bytes of the image — protected content is+ * stored encrypted, and a header read off the ciphertext describes nothing. The caller falls+ * back to reading it in full, which is what decrypts it.+ */+ peek(): TargetPeek | null;/** Names the content {@link getContent} returns — a hash of those exact bytes. */blobId(): string | undefined;/**@@ -210,6 +238,7 @@ function noteTarget(note: BNote): CompressionTarget {mime: note.mime,skip: note.isContentAvailable() ? undefined : "protected",getContent: () => wrapStringOrBuffer(note.getContent()),+ peek: () => peekBlob(note.blobId, note.isProtected),blobId: () => note.blobId,save(buffer, mime, sourceBlobId) {const current = becca.getNote(note.noteId);@@ -237,6 +266,7 @@ function attachmentTarget(attachment: BAttachment): CompressionTarget {mime: attachment.mime,skip: resolveAttachmentSkip(attachment),getContent: () => wrapStringOrBuffer(attachment.getContent()),+ peek: () => peekBlob(attachment.blobId, attachment.isProtected),blobId: () => attachment.blobId,// Written through a freshly read attachment rather than the one collected at the start of// the run: that one is a detached copy of its row, and `forceSave` writes the whole row@@ -256,6 +286,31 @@ function attachmentTarget(attachment: BAttachment): CompressionTarget {};}+/**+ * Reads an image's weight and its opening bytes straight out of the blob, leaving the body of it in+ * the database. One statement answers both, so the saving is a smaller read rather than a second+ * round trip.+ *+ * `CAST` on both: a blob column can hold text for other kinds of content, where `LENGTH` would+ * count characters and `substr` would cut on them. Bytes are what an image header is measured in.+ */+function peekBlob(blobId: string | undefined, isProtected: boolean | undefined): TargetPeek | null {+ if (!blobId || isProtected) {+ return null;+ }++ const row = getSql().getRow<{ size: number | null; header: string | Uint8Array | null }>(/*sql*/`+ SELECT LENGTH(CAST(content AS BLOB)) AS size,+ substr(CAST(content AS BLOB), 1, ?) AS header+ FROM blobs WHERE blobId = ?`, [ HEADER_BYTES, blobId ]);++ if (!row || row.size === null || row.header === null) {+ return null;+ }++ return { size: row.size, header: wrapStringOrBuffer(row.header) };+}+/*** A canvas, mermaid, mind map or spreadsheet note carries its rendered picture in an attachment of* a fixed title. Those are regenerated whenever the note is saved, so compressing one buys nothing@@ -309,14 +364,26 @@ async function compressTarget(target: CompressionTarget, request: ImageCompressilet content: Uint8Array | undefined;try {- content = target.getContent();- // Read in the same turn as the content itself, so it names exactly the bytes just read.- const sourceBlobId = target.blobId();+ // The front of the image and what it weighs, without the body of it. Most images a run+ // visits are settled from this alone, and never read any further.+ const peeked = target.peek();if (target.skip) {- return skipped(content.byteLength, target.skip);+ return skipped(peeked?.size ?? target.getContent().byteLength, target.skip);+ }++ if (peeked) {+ const foreseen = await getImageProvider().planCompression(peeked.header, request);++ if (foreseen) {+ return skipped(peeked.size, foreseen);+ }}+ content = target.getContent();+ // Read in the same turn as the content itself, so it names exactly the bytes just read.+ const sourceBlobId = target.blobId();+const outcome = await getImageProvider().compressImage(content, request);if (!outcome.compressed) {diff --git a/packages/trilium-core/src/services/image_inventory.ts b/packages/trilium-core/src/services/image_inventory.tsindex ab9df7742f..9e58847c84 100644--- a/packages/trilium-core/src/services/image_inventory.ts+++ b/packages/trilium-core/src/services/image_inventory.ts@@ -23,6 +23,7 @@ import { NotFoundError } from "../errors.js";import {collectNoteImages,type CompressionTarget,+ type TargetPeek,resolveMaxWidthHeight,resolveRecursive} from "./image_compression.js";@@ -53,15 +54,15 @@ export function getNoteImageInventory(noteId: string, options: ImageInventoryOptlet unreadable = 0;for (const target of targets) {- const content = readContent(target);+ const read = readHeader(target);- if (!content) {+ if (!read) {unreadable++;continue;}- const { format, width, height } = inspectImage(content);- const size = content.byteLength;+ const { format, width, height } = inspectImage(read.header);+ const size = read.size;add(total, size);add(tallyFor(formats, format), size);@@ -99,17 +100,32 @@ export function getNoteImageInventory(noteId: string, options: ImageInventoryOpt}/**- * The image's bytes, or `null` where they cannot be had — protected content with no session open,- * and any read that fails for a reason this has no use for. Counting an image it could not measure- * would put a size of zero into the totals, which is worse than saying it went unread.+ * What the image weighs and enough of it to identify, or `null` where neither can be had —+ * protected content with no session open, and any read that fails for a reason this has no use for.+ * Counting an image it could not measure would put a size of zero into the totals, which is worse+ * than saying it went unread.+ *+ * Everything this reports — the format, the dimensions, the weight — is in the front of the file or+ * in the database's own accounting, so the pictures themselves are left where they are. A note+ * holding a gigabyte of photographs is tallied without a gigabyte being read to do it.*/-function readContent(target: CompressionTarget): Uint8Array | null {+function readHeader(target: CompressionTarget): TargetPeek | null {if (target.skip === "protected") {return null;}try {- return target.getContent();+ // Protected content with a session open has no peek to give — the stored bytes are+ // encrypted — so it falls back to the read that decrypts them.+ const peeked = target.peek();++ if (peeked) {+ return peeked;+ }++ const content = target.getContent();++ return { size: content.byteLength, header: content };} catch {return null;}diff --git a/packages/trilium-core/src/services/image_provider.spec.ts b/packages/trilium-core/src/services/image_provider.spec.tsindex 125c42aa1f..c8c6a3bd80 100644--- a/packages/trilium-core/src/services/image_provider.spec.ts+++ b/packages/trilium-core/src/services/image_provider.spec.ts@@ -20,7 +20,8 @@ describe("image provider (core)", () => {compressImage: vi.fn(async (): Promise<ImageCompressionOutcome> => ({compressed: false,reason: "no-gain"- }))+ })),+ planCompression: vi.fn(async () => null)};mod.initImageProvider(fake);expect(mod.getImageProvider()).toBe(fake);diff --git a/packages/trilium-core/src/services/image_provider.ts b/packages/trilium-core/src/services/image_provider.tsindex b9ae9ef6a1..1324a6d09f 100644--- a/packages/trilium-core/src/services/image_provider.ts+++ b/packages/trilium-core/src/services/image_provider.ts@@ -66,6 +66,24 @@ export interface ImageProvider {* @param request - Fully resolved compression parameters*/compressImage(buffer: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionOutcome>;++ /**+ * Why an image with this header would be left alone, decided without the rest of it.+ *+ * The point is to answer for images a run will not touch without paying to read them: an+ * unsupported format, one already within the bound with nothing asked of its encoding, one too+ * large to decode. Over a tree those are most of the images there are, and the difference is+ * between reading a database's worth of pictures and reading the front of each.+ *+ * Answers only what the header settles. Anything it leaves open — dimensions past the end of+ * the given bytes, a question that needs the pixels — comes back `null`, meaning the image has+ * to be read in full and put through {@link compressImage}, which decides for itself either+ * way. A reason given here is therefore always one that would be given there.+ *+ * @param header - The opening bytes of the image; may be the whole of it.+ * @param request - Fully resolved compression parameters+ */+ planCompression(header: Uint8Array, request: ImageCompressionRequest): Promise<ImageCompressionSkipReason | null>;}let imageProvider: ImageProvider | null = null;