Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 up to 1.3 times as long (a 2400x1600 photo at quality 80: 80 to 97 ms)

## 4.0.1

### Performance
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 6 additions & 4 deletions THIRD_PARTY_NOTICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down Expand Up @@ -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
Expand Down
455 changes: 442 additions & 13 deletions src/codecs/jpeg.ts

Large diffs are not rendered by default.

13 changes: 10 additions & 3 deletions src/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 up to 1.3 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
Expand Down Expand Up @@ -2678,9 +2684,10 @@ export class Image {
encodeJPEG(options?: JPEGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
async encodeJPEG(options: JPEGEncodeOptions = {}): Promise<Uint8Array<ArrayBuffer>> {
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);
Expand All @@ -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 });
}
Expand All @@ -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
Expand Down
66 changes: 66 additions & 0 deletions tests/jpeg-progressive-encode.js
Original file line number Diff line number Diff line change
@@ -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 <script> of the same pixels, with the script the encoder uses
// (cjpeg -progressive has libjpeg's own ten scans): the encoder writes the same bytes, but for its Exif segment. Every
// case is a different corner of the entropy coding: refinement bits waiting for the end-of-band run, runs of 16 zeros
// folded into it or written out before the last new nonzero coefficient, a run that fills up, blocks the image only
// pads, one block
const expected = {
'noise 97x61@75@4:2:0': 'bce4749c1514b4947fff8cbd7046a7224c5daee2e1b16d6397ab24e09ae032e7',
'noise 97x61@95@4:4:4': 'eb912751475c8fd4e3f1d7e1cb6c70626d353a4f781c69bcf28f76a8d41617ad',
'noise 97x61@50@4:4:4@gray': 'b794934bfff9f870ae3645a09d1fdf65b46edd3894082148c142a3cfede753c0',
'noise 97x61@100@4:4:4': '943065d01c831cd4d736025602ec54bccd16de34fbe524d1366c0787c8c79a05',
'noise 97x61@100@4:4:4@gray': '031a2848421f62b19add2bdbc605d9c6edc1c80848a118bff549228cc2c18a8f',
'dots 200x200@100@4:4:4': '801de51eafe9344d4fa23a2b6e5ec72f707e8fa1a903baf789d5a8f516001086',
'dots 200x200@100@4:4:4@gray': '4cf881db67d97993233658476e7c71dc8a0f539b62140f8bebc0d37fa00164e5',
'stripes 512x64@100@4:4:4@gray': 'deb41394c461d0dfb0d2f6a6fe619bb007c6a1a7e470ea2a556268f7efa4a90e',
'sparse 257x193@75@4:2:0': '9bbba325f0c4cf1b2173b3f9441173bb3985a97d92e9787f131f2aeaa391ac76',
'sparse 257x193@85@4:4:4@gray': 'd4b778ac09036f223adc2c03e402919c2a2a083912029be4efcfd8d08b037969',
'gradient 100x75@30@4:4:4': 'bc9e3d847506aa84fe2ab2f0b3653b11760b10531f64c8296712e4bee53aad22',
'gradient 100x75@90@4:2:0': '9c258afe1a4be29b5cc1805b07a8ff3e5103996a9fc78b4a7f819941f02085d2',
'gradient 33x17@75@4:2:0': 'c3f7d1e71496d346fa6ecef75936a47ede204dca2067c23f30a5889756b16290',
'noise 7x5@75@4:2:0': 'ac9d04e15ab41aa14f824b5e5a0c4eea2d824b938e6e93426a7ae68ac94cebe4',
'noise 1x1@75@4:2:0': '7f79b49b069af2b52b0ac5c91f6cfcdedd31ab2db915d3ac762b0e39375128d1',
'noise 16x16@10@4:2:0': 'cbe7732be9ccdf10528194853fa743b599314d59152845aeec3851991b77340d',
'flat 2200x1000@75@4:4:4@gray': 'e7f4992c874dc49b6bbf48d949f0fb93d98051e335f4c2867c1a9ea11c5ef7e3'
};

// removes the APP1 (Exif) segment following SOI and APP0
const withoutExif = data => {
if (data[20] !== 0xff || data[21] !== 0xe1) panic('no Exif segment after APP0');
return Buffer.concat([data.subarray(0, 20), data.subarray(22 + (data[22] << 8 | data[23]))]);
};

const sha = data => crypto.createHash('sha256').update(data).digest('hex');

(async () => {
for (const [name, make, quality, subsampling, gray] of cases) {
const key = `${name}@${quality}@${subsampling}${gray ? '@gray' : ''}`;
const image = make();
if (gray) image.saturation(0);

const progressive = Buffer.from(await image.encodeJPEG({quality, subsampling, progressive: true}));
if (sha(withoutExif(progressive)) !== expected[key]) panic(`${key}: encoded bytes don't match cjpeg's`);

// the same coefficients: the same pixels as the file of the default scan
const baseline = Buffer.from(await image.encodeJPEG({quality, subsampling}));
if (progressive.indexOf(Buffer.of(0xff, 0xc2)) < 0 || baseline.indexOf(Buffer.of(0xff, 0xc2)) >= 0) panic(`${key}: the progressive file isn't progressive (or the default is)`);
const a = await Image.decode(progressive), b = await Image.decode(baseline);
if (!Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap))) panic(`${key}: the progressive file decodes to other pixels`);
}

// pixels with transparency are put on the background row by row on the way to the encoder: the same for both
const translucent = new Image(70, 41).fill(0x40a0f0c0);
for (let x = 0; x < 70; x++) translucent.setPixelAt(x, x % 41, 0x00000000);
for (const options of [{}, {background: 0xffffffff}, {subsampling: '4:4:4', quality: 60}]) {
const a = await Image.decode(await translucent.encodeJPEG({...options, progressive: true})), b = await Image.decode(await translucent.encodeJPEG(options));
if (!Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap))) panic(`translucent ${JSON.stringify(options)}: the progressive file decodes to other pixels`);
}
})();
4 changes: 4 additions & 0 deletions tests/option-checks.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ const rejects = async (name, fn, Type) => {
await rejects(`encodeJPEG quality ${quality}`, () => image.encodeJPEG({quality}), RangeError);
}
for (const quality of [0, 1, 100]) await image.encodeJPEG({quality});
// (a progressive JPEG is true or false, not truthy)
for (const progressive of ['yes', 1, null, 'true', {}])
await rejects(`encodeJPEG progressive ${progressive}`, () => image.encodeJPEG({progressive}), TypeError);
for (const progressive of [true, false]) await image.encodeJPEG({progressive});
for (const quality of [-1, 101, NaN]) {
await rejects(`encodeAVIF quality ${quality}`, () => image.encodeAVIF({quality}), RangeError);
await rejects(`encodeAVIF alphaQuality ${quality}`, () => image.encodeAVIF({alphaQuality: quality}), RangeError);
Expand Down
81 changes: 81 additions & 0 deletions tests/util/progressive-images.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const {Image} = require('../..');

// the images of tests/jpeg-progressive-encode.js, made from numbers: noise (long runs of zeros and refinement bits in
// every band), noise of eight colors, stripes, a few dark dots on white (empty blocks between busy ones), a gradient, and a flat image of more blocks
// than an end-of-band run can hold
const noise = (width, height) => {
const image = new Image(width, height);
let x = 12345;
for (let i = 0; i < image.bitmap.length; i++) {
x = Math.imul(x, 1103515245) + 12345 >>> 0;
image.bitmap[i] = i % 4 === 3 ? 255 : x >>> 24;
}
return image;
};

// noise of eight colors, or of black and white: at the top quality, hundreds of coefficients wait for the end of a band
const dots = (width, height, mono = false) => {
const image = new Image(width, height);
let x = 777;
for (let i = 0; i < image.bitmap.length; i += 4) {
x = Math.imul(x, 1103515245) + 12345 >>> 0;
image.bitmap[i] = x >>> 31 ? 255 : 0;
image.bitmap[i + 1] = mono ? image.bitmap[i] : x >>> 30 & 1 ? 255 : 0;
image.bitmap[i + 2] = mono ? image.bitmap[i] : x >>> 29 & 1 ? 255 : 0;
image.bitmap[i + 3] = 255;
}
return image;
};

// a square wave of eight pixels: every block has the same four coefficients that wait for the end of a band
const stripes = (width, height) => {
const image = new Image(width, height);
for (let y = 0; y < height; y++)
for (let x = 0; x < width; x++) image.setPixelAt(x, y, x % 8 < 4 ? 0xa8a8a8ff : 0x585858ff);
return image;
};

const sparse = (width, height) => {
const image = new Image(width, height).fill(0xffffffff);
let x = 12345;
for (let i = 0; i < 400; i++) {
x = Math.imul(x, 1103515245) + 12345 >>> 0;
image.setPixelAt(x % width, (x >>> 9) % height, (x | 0xff) >>> 0);
}
return image;
};

const gradient = (width, height) => {
const image = new Image(width, height);
for (let y = 0; y < height; y++)
for (let x = 0; x < width; x++) image.setPixelAt(x, y, (x * 255 / width << 24 | y * 255 / height << 16 | (x + y & 255) << 8 | 255) >>> 0);
return image;
};

const flat = (width, height) => {
const image = new Image(width, height).fill(0x336699ff);
image.setPixelAt(5, 5, 0xff0000ff);
return image;
};

// [name, image, quality, subsampling, gray]
module.exports = [
['noise 97x61', () => noise(97, 61), 75, '4:2:0', false],
['noise 97x61', () => noise(97, 61), 95, '4:4:4', false],
['noise 97x61', () => noise(97, 61), 50, '4:4:4', true],
['noise 97x61', () => noise(97, 61), 100, '4:4:4', false],
['noise 97x61', () => noise(97, 61), 100, '4:4:4', true],
['dots 200x200', () => dots(200, 200), 100, '4:4:4', false],
['dots 200x200', () => dots(200, 200, true), 100, '4:4:4', true],
['stripes 512x64', () => stripes(512, 64), 100, '4:4:4', true],
['sparse 257x193', () => sparse(257, 193), 75, '4:2:0', false],
['sparse 257x193', () => sparse(257, 193), 85, '4:4:4', true],
['gradient 100x75', () => gradient(100, 75), 30, '4:4:4', false],
['gradient 100x75', () => gradient(100, 75), 90, '4:2:0', false],
['gradient 33x17', () => gradient(33, 17), 75, '4:2:0', false],
['noise 7x5', () => noise(7, 5), 75, '4:2:0', false],
['noise 1x1', () => noise(1, 1), 75, '4:2:0', false],
['noise 16x16', () => noise(16, 16), 10, '4:2:0', false],
// 34375 blocks: the end-of-band run is written out at 32767
['flat 2200x1000', () => flat(2200, 1000), 75, '4:4:4', true]
];
Loading