From b821790c9617801bb359aee615f1bfacbfb3b815 Mon Sep 17 00:00:00 2001 From: Mathis Mensing Date: Sat, 28 Nov 2026 21:16:28 +0000 Subject: [PATCH 1/4] add progressive JPEG encoding --- CHANGELOG.md | 6 + README.md | 2 +- THIRD_PARTY_NOTICES.md | 10 +- src/codecs/jpeg.ts | 282 ++++++++++++++++++++++++++++++- src/image.ts | 13 +- tests/jpeg-progressive-encode.js | 66 ++++++++ tests/option-checks.js | 4 + tests/util/progressive-images.js | 81 +++++++++ 8 files changed, 447 insertions(+), 17 deletions(-) create mode 100644 tests/jpeg-progressive-encode.js create mode 100644 tests/util/progressive-images.js diff --git a/CHANGELOG.md b/CHANGELOG.md index ca80c3da..4581eb92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 4.1.0 + +### New + +- `encodeJPEG({ progressive: true })` writes a progressive JPEG: browsers show the whole picture blurry first and sharpen it while the file loads, and the file is 2 to 4% smaller for photos with the same pixels (the scans are the ones mozjpeg uses, each with Huffman tables made for it). Encoding takes 1.1 to 1.6 times as long (a 2400x1600 photo at quality 80: 80 to 123 ms) + ## 4.0.1 ### Performance diff --git a/README.md b/README.md index 09573ff5..9cd34cb1 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ compares ImageScript's speed and file sizes with Jimp, sharp and other libraries ### Credits ImageScript builds on [fflate](https://github.com/101arrowz/fflate), libjpeg, [pdf.js](https://github.com/mozilla/pdf.js), -[font-rs](https://github.com/raphlinus/font-rs), [libwebp](https://chromium.googlesource.com/webm/libwebp), +[font-rs](https://github.com/raphlinus/font-rs), [mozjpeg](https://github.com/mozilla/mozjpeg), [libwebp](https://chromium.googlesource.com/webm/libwebp), [HarfBuzz](https://github.com/harfbuzz/harfbuzz), [dav1d](https://code.videolan.org/videolan/dav1d), [libavif](https://github.com/AOMediaCodec/libavif), libaom, [jxl-oxide](https://github.com/tirr-c/jxl-oxide) and [libjxl](https://github.com/libjxl/libjxl). The TrueType hinting follows [FreeType](https://freetype.org): portions of diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e9cfabf0..b1858f54 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -7,7 +7,8 @@ following projects, under their own licenses. Each derived file says so in its h |---|---|---| | [fflate](https://github.com/101arrowz/fflate) by Arjun Barrett | `src/codecs/zlib.ts` (deflate/inflate) | MIT | | [Fast CRC32 in JavaScript](https://gist.github.com/101arrowz/e58695f7ccfdf74f60ba22018093edea) by Arjun Barrett | `src/codecs/crc.ts` (slice-by-16 CRC-32) | MIT | -| [libjpeg](https://ijg.org/) / [libjpeg-turbo](https://libjpeg-turbo.org/) by the Independent JPEG Group | `src/codecs/jpeg.ts` (IDCT, FDCT, upsampling, color conversion, progressive refinement, optimal Huffman tables) | IJG | +| [libjpeg](https://ijg.org/) / [libjpeg-turbo](https://libjpeg-turbo.org/) by the Independent JPEG Group | `src/codecs/jpeg.ts` (IDCT, FDCT, upsampling, color conversion, progressive decoding and encoding, optimal Huffman tables) | IJG | +| [mozjpeg](https://github.com/mozilla/mozjpeg) by Mozilla | `src/codecs/jpeg.ts` (the scan script of progressive files) | IJG | | [pdf.js](https://github.com/mozilla/pdf.js) (forked from [jpgjs](https://github.com/notmasteryet/jpgjs) by notmasteryet) | `src/codecs/jpeg.ts` (structure of the scan decoder) | Apache-2.0 | | [font-rs](https://github.com/raphlinus/font-rs) by Raph Levien | `src/render/text.ts` (the `Rasterizer` class, also used for SVGs) | Apache-2.0 | | [RFC 9649](https://www.rfc-editor.org/rfc/rfc9649) (WebP Image Format) | `src/codecs/vp8l.ts` (lossless bitstream, short distance code table), `src/codecs/webp.ts` (container) | BSD-3-Clause (Revised BSD) | @@ -66,9 +67,10 @@ This software is based in part on the work of the Independent JPEG Group. The JPEG codec translates parts of libjpeg (as shipped by libjpeg-turbo) to TypeScript: the integer inverse DCT (`jidctint.c`), the floating point forward DCT (`jfdctflt.c`), fancy upsampling (`jdsample.c`), the YCbCr to RGB -tables (`jdcolor.c`), the progressive AC refinement (`jdphuff.c`) and the optimal Huffman table generation -(`jcphuff.c`/`jchuff.c`). The translations were rewritten for TypeScript's numbers and typed arrays; the rest of the -codec is ImageScript's own. libjpeg's README with its copyright and terms is included unaltered as +tables (`jdcolor.c`), the progressive AC refinement (`jdphuff.c`), the progressive encoder (`jcphuff.c`) and the +optimal Huffman table generation (`jchuff.c`). The scans of progressive files are the ones of mozjpeg's +`jpeg_simple_progression` (`jcparam.c`). The translations were rewritten for TypeScript's numbers and typed arrays; the +rest of the codec is ImageScript's own. libjpeg's README with its copyright and terms is included unaltered as [licenses/README.ijg](licenses/README.ijg). ## pdf.js, font-rs diff --git a/src/codecs/jpeg.ts b/src/codecs/jpeg.ts index 811d6ff4..0ab5600c 100644 --- a/src/codecs/jpeg.ts +++ b/src/codecs/jpeg.ts @@ -1,7 +1,8 @@ /*! * JPEG codec. This software is based in part on the work of the Independent JPEG Group: the IDCT, FDCT, upsampling, - * downsampling, color conversion, quantization, progressive refinement and optimal Huffman tables are translated from - * libjpeg/libjpeg-turbo (IJG license, see licenses/README.ijg). The scan decoder follows the structure of pdf.js' jpg.js + * downsampling, color conversion, quantization, progressive refinement and encoding and optimal Huffman tables are + * translated from libjpeg/libjpeg-turbo, and the progressive scan script is mozjpeg's (IJG license, see + * licenses/README.ijg). The scan decoder follows the structure of pdf.js' jpg.js * (Copyright 2014 Mozilla Foundation, Apache License 2.0). See THIRD_PARTY_NOTICES.md */ @@ -1544,6 +1545,8 @@ export interface EncodeMetadata { fullChroma?: boolean; /** the chroma subsampling, overriding the default by quality (4:2:0 up to 90, 4:4:4 above) */ subsampling?: '4:4:4' | '4:2:0'; + /** whether to write a progressive JPEG (mozjpeg's scans, each with Huffman tables made for it) */ + progressive?: boolean; /** * with it, `pixels` is the one row of scratch pixels (width * 4 bytes): `rows(y)` fills it with row y before the * row is read, so the pixels need not be in memory whole (the image composited onto a background, row by row) @@ -1551,7 +1554,7 @@ export interface EncodeMetadata { rows?: (y: number) => void; } -export function encode(pixels: Uint8Array, width: number, height: number, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, rows }: EncodeMetadata = {}): Uint8Array { +export function encode(pixels: Uint8Array, width: number, height: number, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, progressive = false, rows }: EncodeMetadata = {}): Uint8Array { if (!width || !height) throw new RangeError('JPEG: invalid dimensions'); checkFormatSize('JPEG', width, height, 0xffff); @@ -1678,11 +1681,11 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit const blocks = { coefficients, owners, ends, count }; - // pass 1: gather symbol statistics, pass 2: write with optimal tables + // (sequential: pass 1 gathers symbol statistics, pass 2 writes with optimal tables; progressive: both per scan) const frequencies = [new Int32Array(257), new Int32Array(257), new Int32Array(257), new Int32Array(257)]; - countSymbols(blocks, frequencies); + if (!progressive) countSymbols(blocks, frequencies); - const huffman = frequencies.slice(0, gray ? 2 : 4).map(buildOptimalTable); + const huffman = progressive ? [] : frequencies.slice(0, gray ? 2 : 4).map(buildOptimalTable); const writer = new BitWriter(width * height); writer.bytes(0xff, 0xd8); @@ -1704,13 +1707,22 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit for (let k = 0; k < 64; k++) writer.bytes(tables[t][ZIGZAG[k]]); } - // SOF0 - if (gray) writer.bytes(0xff, 0xc0, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0); + // SOF0, or SOF2 for progressive + const sof = progressive ? 0xc2 : 0xc0; + if (gray) writer.bytes(0xff, sof, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0); else { - writer.bytes(0xff, 0xc0, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03); + writer.bytes(0xff, sof, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03); writer.bytes(1, hmax << 4 | hmax, 0, 2, 0x11, 1, 3, 0x11, 1); } + if (progressive) { + // (the blocks of a component, by position, in MCU order: the MCU, then the block in it) + const layout = components.slice(0, componentCount).map((component, c) => ({ ...component, offset: c === 0 ? 0 : hmax * hmax + c - 1 })); + writeProgressive(writer, progressiveScans(componentCount), blocks, layout, mcusPerLine, blocksPerMcu); + writer.bytes(0xff, 0xd9); + return writer.finish(); + } + // DHT: luma DC, luma AC, chroma DC, chroma AC for (const [index, id] of ([[0, 0x00], [1, 0x10], [2, 0x01], [3, 0x11]] as Array<[number, number]>).slice(0, gray ? 2 : 4)) { const { bits, values } = huffman[index]; @@ -1730,6 +1742,258 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit return writer.finish(); } +// a progressive scan: the components (by index) and the band of coefficients (in zigzag order) it holds, and the bit +// of the coefficients it starts at (Al) and refines from (Ah, 0 for the first scan of a band) +interface Scan { + comps: number[]; + ss: number; + se: number; + ah: number; + al: number; +} + +// mozjpeg's script (jpeg_simple_progression of its jcparam.c, the max compression profile), which makes smaller files +// than libjpeg's ten scans (libjpeg-turbo's: DC at two bits, luma 1-5, chroma, luma 6-63 each at lower bits and refined +// later): the DC first, the luma's lowest frequencies and the rest of its AC at one bit less than full, that bit +// last, and each chroma component's AC in two bands +function progressiveScans(componentCount: number): Scan[] { + const dc: Scan = { comps: Array.from({ length: componentCount }, (_, c) => c), ss: 0, se: 0, ah: 0, al: 0 }; + const ac = (comp: number, ss: number, se: number, ah: number, al: number): Scan => ({ comps: [comp], ss, se, ah, al }); + + const luma = [ac(0, 1, 2, 0, 1), ac(0, 3, 63, 0, 1), ac(0, 1, 63, 1, 0)]; + if (componentCount === 1) return [dc, ...luma]; + return [dc, ...luma, ac(1, 1, 8, 0, 0), ac(1, 9, 63, 0, 0), ac(2, 1, 8, 0, 0), ac(2, 9, 63, 0, 0)]; +} + +// correction bits of refinement scans wait for the end-of-band run they belong to: at most this many (jcphuff.c) +const MAX_CORR_BITS = 1000; + +interface ProgressiveComponent { + h: number; + v: number; + blocksX: number; + blocksY: number; + offset: number; +} + +// jcphuff.c's encoders of one scan: counts the symbols of its Huffman tables (`counts`), or writes the scan with them +// (`tables`) +class ScanCoder { + private eobrun = 0; + // correction bits waiting for the end-of-band run, and how many + private readonly pending = new Uint8Array(MAX_CORR_BITS); + private waiting = 0; + private readonly magnitudes = new Int32Array(64); + + private readonly writer: BitWriter; + private readonly counts: Int32Array[] | null; + private readonly tables: OptimalTable[] | null; + + constructor(writer: BitWriter, counts: Int32Array[] | null, tables: OptimalTable[] | null) { + this.writer = writer; + this.counts = counts; + this.tables = tables; + } + + private symbol(table: number, symbol: number): void { + if (this.counts) this.counts[table][symbol]++; + else { + const { codes, sizes } = (this.tables as OptimalTable[])[table]; + this.writer.write(codes[symbol], sizes[symbol]); + } + } + + private bits(value: number, size: number): void { + if (!this.counts) this.writer.write(value, size); + } + + private buffered(start: number, count: number): void { + if (!this.counts) for (let i = 0; i < count; i++) this.writer.write(this.pending[start + i], 1); + } + + private emitEobrun(table: number): void { + if (this.eobrun === 0) return; + const nbits = 31 - Math.clz32(this.eobrun); + this.symbol(table, nbits << 4); + if (nbits) this.bits(this.eobrun, nbits); + this.eobrun = 0; + // (the correction bits that go with it) + this.buffered(0, this.waiting); + this.waiting = 0; + } + + /** the first scan of the DC coefficients (point transform Al): the differences of the shifted values */ + dcFirst(coefficients: Int16Array, owners: Uint8Array, count: number, last: number[], al: number): void { + for (let n = 0; n < count; n++) { + const component = owners[n], table = component === 0 ? 0 : 1; + const value = coefficients[n * 64] >> al, diff = value - last[component]; + last[component] = value; + const nbits = 32 - Math.clz32(Math.abs(diff)); + this.symbol(table, nbits); + if (nbits) this.bits(diff < 0 ? diff - 1 : diff, nbits); + } + } + + /** a refinement scan of the DC coefficients: their next bit */ + dcRefine(coefficients: Int16Array, count: number, al: number): void { + for (let n = 0; n < count; n++) this.bits(coefficients[n * 64] >> al, 1); + } + + /** the first scan of a band of AC coefficients of one block, whose last nonzero coefficient is `end` */ + acFirst(coefficients: Int16Array, o: number, end: number, table: number, ss: number, se: number, al: number): void { + // (the coefficients after the last nonzero one are zeros: a run) + const stop = Math.min(se, end); + let run = 0; + for (let k = ss; k <= stop; k++) { + let value = coefficients[o + k]; + if (value === 0) { + run++; + continue; + } + // (the point transform divides the magnitude, rounding toward zero) + let bits: number; + if (value < 0) { + value = -value >> al; + bits = ~value; + } else { + value >>= al; + bits = value; + } + if (value === 0) { + run++; + continue; + } + + this.emitEobrun(table); + for (; run > 15; run -= 16) this.symbol(table, 0xf0); + const nbits = 32 - Math.clz32(value); + this.symbol(table, run << 4 | nbits); + this.bits(bits, nbits); + run = 0; + } + + if (stop < se) run += se - Math.max(stop, ss - 1); + if (run > 0) { + this.eobrun++; + if (this.eobrun === 0x7fff) this.emitEobrun(table); + } + } + + /** a refinement scan of a band of AC coefficients of one block: the new nonzero ones and the next bit of the others */ + acRefine(coefficients: Int16Array, o: number, end: number, table: number, ss: number, se: number, al: number): void { + const magnitudes = this.magnitudes; + const stop = Math.min(se, end); + // (the last coefficient that becomes nonzero: zero runs after it fold into the end of the band) + let eob = 0; + for (let k = ss; k <= stop; k++) { + const value = Math.abs(coefficients[o + k]) >> al; + magnitudes[k] = value; + if (value === 1) eob = k; + } + + let run = 0, start = this.waiting, count = 0; + for (let k = ss; k <= stop; k++) { + const value = magnitudes[k]; + if (value === 0) { + run++; + continue; + } + + for (; run > 15 && k <= eob; run -= 16) { + this.emitEobrun(table); + this.symbol(table, 0xf0); + this.buffered(start, count); + start = 0; + count = 0; + } + + // already nonzero: only its next bit + if (value > 1) { + this.pending[start + count++] = value & 1; + continue; + } + + this.emitEobrun(table); + this.symbol(table, run << 4 | 1); + this.bits(coefficients[o + k] < 0 ? 0 : 1, 1); + this.buffered(start, count); + start = 0; + count = 0; + run = 0; + } + + if (stop < se) run += se - Math.max(stop, ss - 1); + if (run > 0 || count > 0) { + this.eobrun++; + this.waiting += count; + // (forced out before the run or the correction bits can overflow) + if (this.eobrun === 0x7fff || this.waiting > MAX_CORR_BITS - 63) this.emitEobrun(table); + } + } + + /** the end of the scan: the pending run */ + finish(table: number): void { + this.emitEobrun(table); + } +} + +// the scans of a progressive JPEG, each with Huffman tables made for its own symbols (libjpeg writes progressive files +// with optimized tables: jcphuff.c, jcmarker.c) +function writeProgressive(writer: BitWriter, scans: Scan[], { coefficients, owners, ends, count }: Blocks, layout: ProgressiveComponent[], mcusPerLine: number, blocksPerMcu: number): void { + // (the table of a component: luma 0, chroma 1) + const slot = (comp: number): number => comp === 0 ? 0 : 1; + + const run = (coder: ScanCoder, { comps, ss, se, ah, al }: Scan): void => { + if (ss === 0) { + if (ah === 0) coder.dcFirst(coefficients, owners, count, [0, 0, 0], al); + else coder.dcRefine(coefficients, count, al); + return; + } + + // (the blocks of the image only, a row after the other) + const comp = comps[0], { h, v, blocksX, blocksY, offset } = layout[comp]; + const table = slot(comp); + for (let by = 0; by < blocksY; by++) + for (let bx = 0; bx < blocksX; bx++) { + const n = ((by / v | 0) * mcusPerLine + (bx / h | 0)) * blocksPerMcu + offset + by % v * h + bx % h; + if (ah === 0) coder.acFirst(coefficients, n * 64, ends[n], table, ss, se, al); + else coder.acRefine(coefficients, n * 64, ends[n], table, ss, se, al); + } + coder.finish(table); + }; + + for (const scan of scans) { + const { comps, ss, se, ah, al } = scan; + const dcScan = ss === 0; + + // pass 1: the symbols' frequencies + const counts = [new Int32Array(257), new Int32Array(257)]; + run(new ScanCoder(writer, counts, null), scan); + + // (a table once per scan, none for a DC refinement: it holds bits only) + const used: number[] = []; + if (!(dcScan && ah !== 0)) for (const comp of comps) if (!used.includes(slot(comp))) used.push(slot(comp)); + const tables: OptimalTable[] = []; + for (const table of used) tables[table] = buildOptimalTable(counts[table]); + + for (const table of used) { + const { bits, values } = tables[table]; + writer.bytes(0xff, 0xc4, 19 + values.length >> 8, 19 + values.length & 0xff, table | (dcScan ? 0x00 : 0x10)); + for (let i = 1; i <= 16; i++) writer.bytes(bits[i]); + for (const value of values) writer.bytes(value); + } + + // SOS: the components and their tables (a DC scan names the DC one, an AC scan the AC one, a refinement of DC none) + writer.bytes(0xff, 0xda, 0x00, 2 * comps.length + 6, comps.length); + for (const comp of comps) writer.bytes(comp + 1, dcScan ? (ah === 0 ? slot(comp) << 4 : 0) : slot(comp)); + writer.bytes(ss, se, ah << 4 | al); + + // pass 2: the scan + run(new ScanCoder(writer, null, tables), scan); + writer.flush(); + } +} + // tables: 0 luma DC, 1 luma AC, 2 chroma DC, 3 chroma AC interface Blocks { coefficients: Int16Array; diff --git a/src/image.ts b/src/image.ts index 47e0bc20..9cfe88b6 100644 --- a/src/image.ts +++ b/src/image.ts @@ -408,6 +408,12 @@ export interface JPEGEncodeOptions extends EncodeOptions { * @defaultValue `'4:2:0'` up to quality 90, `'4:4:4'` above */ subsampling?: '4:4:4' | '4:2:0'; + /** + * Whether to write a progressive JPEG: the picture first appears blurry as a whole and sharpens while it loads, and + * the file is 2 to 4% smaller for photos. The pixels are the same, and encoding takes 1.1 to 1.6 times as long + * @defaultValue `false` + */ + progressive?: boolean; /** * The background color to combine with transparent pixels, since JPEG doesn't support transparency. Opaque images * are encoded as they are @@ -2678,9 +2684,10 @@ export class Image { encodeJPEG(options?: JPEGEncodeOptions): Promise>; async encodeJPEG(options: JPEGEncodeOptions = {}): Promise> { checkOptions(options, 'encodeJPEG({ quality: 80 })'); - const { quality: qualityOption = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options; + const { quality: qualityOption = 90, subsampling, progressive = false, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options; const quality = checkQuality(qualityOption); if (subsampling !== undefined) oneOf(subsampling, SUBSAMPLINGS, 'subsampling'); + boolean(progressive, 'progressive'); const backgroundColor = checkColor(background, 'background'); const embed = gainMapEmbed(gainMapOption); const m = resolveMetadata(metadata); @@ -2698,7 +2705,7 @@ export class Image { // them (no copy of the image: __flattened__'s copy of 4 bytes a pixel was the peak memory) if (!this.__gain_map__) { const flat = this.__flatRows__(backgroundColor); - const base = { exif, comment, subsampling }; + const base = { exif, comment, subsampling, progressive }; if (!flat) return jpeg.encode(this.__bytes__(), this.width, this.height, quality, { ...base, gray: this.__is_gray__() }); return jpeg.encode(flat.pixels, this.width, this.height, quality, { ...base, gray: flat.gray(), rows: flat.row }); } @@ -2707,7 +2714,7 @@ export class Image { const source = this.__flattened__(backgroundColor, embed !== null) ?? this; const gainMap = source.__gain_map__; // (an image whose pixels are all gray is written with one component, like cjpeg -grayscale: a third the data) - const base = { exif, comment, subsampling, gray: source.__is_gray__() }; + const base = { exif, comment, subsampling, progressive, gray: source.__is_gray__() }; if (!gainMap || !embed) return jpeg.encode(source.__bytes__(), source.width, source.height, quality, base); // the gain map's JPEG first: the primary's XMP holds its length diff --git a/tests/jpeg-progressive-encode.js b/tests/jpeg-progressive-encode.js new file mode 100644 index 00000000..2c943088 --- /dev/null +++ b/tests/jpeg-progressive-encode.js @@ -0,0 +1,66 @@ +const crypto = require('crypto'); +const {Image} = require('..'); +const cases = require('./util/progressive-images.js'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// sha256 of libjpeg-turbo 2.1.5's cjpeg -baseline -scans