diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 63d7e7b0..126c728a 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -1,8 +1,9 @@ name: coverage # measures the test coverage (npm run coverage) of every pushed branch and pull requests from forks, and how it -# changed: compared with the commit before the push on master, else with where the branch (or pull request) left -# master, measured in the same job. The job summary shows it; pushes to master get it as a commit comment, pushes to a +# changed, measured in the same job: compared with the commit before the push on master and on branches without a pull +# request (where the branch left master for a new branch or a force push), else with where the branch (or pull request) +# left master. The job summary shows it; pushes to master get it as a commit comment, pushes to a # branch with a pull request as a comment on it (one, updated by later pushes). Pull requests from forks have no # write access: only the job summary on: @@ -39,6 +40,8 @@ jobs: run: | if [ "$EVENT" = pull_request ]; then base=$(git merge-base "$PR_BASE" HEAD); name="the pull request's base" elif [ "$REF" = refs/heads/master ]; then base=$BEFORE; name="the previous commit on master" + elif [ -z "$(gh pr list --head "$BRANCH" --state open --json number --jq '.[0].number')" ] && git cat-file -e "$BEFORE^{commit}" 2>/dev/null; then + base=$BEFORE; name="the previous push" else base=$(git merge-base origin/master HEAD); name="master where the branch left it"; fi if [ -z "$base" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null || [ "$base" = "$(git rev-parse HEAD)" ]; then echo "no base to compare with"; exit 0 @@ -55,6 +58,8 @@ jobs: REF: ${{ github.ref }} BEFORE: ${{ github.event.before }} PR_BASE: ${{ github.event.pull_request.base.sha }} + BRANCH: ${{ github.ref_name }} + GH_TOKEN: ${{ github.token }} - if: steps.base.outputs.summary run: node scripts/coverage-report.js "$SUMMARY" "$ROOT" env: diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 7eb2b77e..2b5d450b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -34,7 +34,10 @@ jobs: run: node scripts/version.js "$VERSION" env: VERSION: ${{ inputs.version }} - - run: npm run docs + # (source links point at the released tag, not at master, which moves on) + - run: npm run docs -- ${VERSION:+--gitRevision "v$VERSION"} + env: + VERSION: ${{ inputs.version }} - uses: actions/configure-pages@v6 - uses: actions/upload-pages-artifact@v5 diff --git a/.github/workflows/node.yml b/.github/workflows/node.yml index 9986ba3b..d30eada3 100644 --- a/.github/workflows/node.yml +++ b/.github/workflows/node.yml @@ -13,6 +13,10 @@ concurrency: group: node-${{ github.event_name }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name != 'release' }} +# the jobs only install, build and test +permissions: + contents: read + jobs: build: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository @@ -94,7 +98,8 @@ jobs: node-version: 24.x - run: npm install - run: npm run build - - run: npm install --no-save esbuild@0.28.2 miniflare@4.20260730.0 edge-runtime@4.0.1 + # (esbuild's and workerd's postinstall scripts only check their binaries, which come with their platform packages) + - run: npm install --no-save --ignore-scripts esbuild@0.28.2 miniflare@4.20260730.0 edge-runtime@4.0.1 - run: node tests/edge/run.mjs browser: @@ -107,6 +112,8 @@ jobs: node-version: 24.x - run: npm install - run: npm run build - - run: npm install --no-save vite@6.4.5 playwright@1.64.1 esbuild@0.28.2 - - run: npx playwright install --with-deps chromium + - run: npm install --no-save --ignore-scripts vite@8.3.8 playwright@1.65.0 + # (the runner image has the libraries Chromium needs: --with-deps only added fonts through apt, which the tests + # don't use, and failed the job whenever the Ubuntu mirrors were unreachable) + - run: npx playwright install chromium - run: node tests/browser/run.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fa77663f..6e8c3821 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,6 +5,8 @@ name: release # the tag's version to npm (with provenance, through trusted publishing) and JSR (through GitHub OIDC, no tokens), # then the docs are deployed and, for regular releases, the version is committed to the default branch, the playground # is updated to it and the benchmark in bench/ is run against the release +# The package's README and changelog link to files on the default branch (the migration guide): merge what a release +# links to into it before publishing the release, or the pages on npm and JSR link to a 404 until the merge on: release: types: [published] diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e462c17..1d1f1924 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,199 @@ # Changelog +## 4.0.0 + +### Breaking changes + +Upgrading from 3.x? Upgrade to the latest 3.x release first, fix the deprecation hints, then switch: the [migration guide](https://github.com/imagescript/ImageScript/blob/master/guides/Migrating%20to%204.0.md) covers the 3.x-to-4.0 API changes and the eighteen behavior changes that don't show up as deprecations or compile errors. + +- **Methods that take options refuse anything else than an object**: a stray number, string, boolean, array or `null` as the options of `cropCircle()`, `Image.renderText()`, the encoders (`encodeWebP()`, `encodeAVIF()`, `encodeJXL()`, ...), `quantize()`, `transform()`, `dropShadow()`, `outline()`, the gradients, `Image.decode()`, the animation encoders, and `new GainMap()` throws a `TypeError` that names the working form (e.g. `cropCircle({ fit: 'cover' })`), so the 3.x calls that are gone like `cropCircle(true)` or `Image.renderText(font, 32, 'Hi')` fail instead of being ignored. Only the type of the argument is checked: a key that isn't an option is still ignored, so a typo like `{ maxWith: 300 }` isn't caught. + +- **The mode constants are removed, modes are plain strings**: `Image.RESIZE_*`, `Image.SVG_MODE_*`, `Frame.DISPOSAL_*` and the `ResizeModes`, `SVGScaleModes` and `FrameDisposalModes` classes are gone. Resize modes are `'nearest-neighbor'`, `'bilinear'`, `'bicubic'` and `'area'` (the `ResizeMode` type), disposal modes `'any'`, `'keep'`, `'previous'` and `'background'` (`FrameDisposalMode`), and the SVG modes became options of `renderSVG()` (below). `Image.RESIZE_AUTO`/`ResizeModes.AUTO` is `image.resize({ width: 256 })`. The old values are no longer accepted either: `'RESIZE_BILINEAR'`, the numbers 1-3 for SVG scale modes and the numeric disposal ids 0-3. + +- **`absolute` is removed from `opacity()`, `red()`, `green()`, `blue()`, `lightness()` and `saturation()`**: they only scale now, `image.red(0.5)` (and `AdjustOptions`, the type of their options, is removed). For a fixed color, use `image.recolor()`. In JavaScript a leftover `image.red(0.5, true)` scales the channel instead of setting it. + +- **`Image.encode()` is removed**: use `image.encodePNG()`, which takes the same arguments. + +- **`contain()` and `cover()` are removed** from `Image`, `Frame` and `Animation`: use `resize({ width, height, fit: 'contain' })` or `resize({ width, height, fit: 'cover' })`. `fit: 'contain'` also takes `background`; `ResizeFit` names the fit modes and `ContainOptions` is removed. 3.x's `contain()` maps to `'inside'`, and 3.x's padded `fit()` maps to `'contain'`. + +- **The color helpers of `Image` are removed**: `Image.rgbaToColor()`, `Image.rgbToColor()`, `Image.hslaToColor()`, `Image.hslToColor()`, `Image.rgbaToHSLA()`, `Image.colorToRGBA()`, `Image.colorToRGB()` and `Image.gradient()` are now `Colors.fromRGBA()`, `Colors.fromRGB()`, `Colors.fromHSLA()`, `Colors.fromHSL()`, `Colors.toHSLA()`, `Colors.toRGBA()`, `Colors.toRGB()` and `Colors.gradient()`. + +- **Iterating over an image, `iterateWithColors()` and `coordinates()` are removed**: `for (const [x, y] of image)`, `image.coordinates()` and `image.iterateWithColors()` are `image.pixels()`, which yields `[x, y, color]` for every pixel (`for (const [x, y] of image.pixels())`). + +- **`PNGMetadata` is removed**: use `Metadata`, which the encoders that write metadata take. The type is the same. + +- **The `max` argument of `cropCircle()` is removed**: `cropCircle(true, feathering)` and `cropCircle({ max: true })` are now `cropCircle({ fit: 'cover', feathering })`, and `cropCircle(false)` is `cropCircle()`, the default `fit: 'contain'`. The `size` option that 3.x added for it (and that 3.x's deprecation hint suggests) is `fit` too: `cropCircle({ size: 'cover' })` is `cropCircle({ fit: 'cover' })`, and `size` is ignored like any key that isn't an option. + +- **The positional forms of `Image.renderText()` are removed**: `Image.renderText(font, size, text, color?, layout?, style?)` and `Image.renderText(font, size, text, options?)` are now `Image.renderText(text, { font, size, color, ...layout, ...style })`. + +- **The deprecated animation encoder option types and `AnimationEncoder.frames` are removed**: `AnimationEncoderOptions`, `WebPAnimationEncoderOptions`, `GIFAnimationEncoderOptions` and `APNGAnimationEncoderOptions` are `AnimationEncodeOptions`, `WebPAnimationEncodeOptions`, `GIFAnimationEncodeOptions` and `APNGEncodeOptions`, each with `AnimationOptions` for the `loopCount`, and `encoder.frames` is `encoder.frameCount`. + +- **The positional mode of `scale()` and `resize()` is removed**, on `Image`, `Frame` and `Animation`: `image.resize(width, height, 'area')` and `image.resize(width, height, ResizeModes.AREA)` are now `image.resize(width, height, { mode: 'area' })`, and `image.scale(0.5, { mode })` takes the mode in the same way. Other values in the position throw a `TypeError`, and `fast` goes in the same object. + +- **The positional arguments of `composite()`, `rotate()`, `sharpen()`, `dominantColor()`, `roundCorners()`, `fisheye()`, `trim()` and `colorToAlpha()` are removed**: the values go in the options object, which is the only second argument now. `image.composite(logo, 10, 20, { opacity: 0.5 })` is `image.composite(logo, { x: 10, y: 20, opacity: 0.5 })`, `image.sharpen(2, 3)` is `image.sharpen({ amount: 2, radius: 3 })`, `image.rotate(45, false)` is `image.rotate(-45, { expand: false })` (see the clockwise rotation below), `image.dominantColor(true, true, 15)` is `image.dominantColor({ ignoreBlack: true, ignoreWhite: true, threshold: 15 })`, `image.roundCorners(8)` is `image.roundCorners({ radius: 8 })` and `image.fisheye(3)` is `image.fisheye({ strength: 3 })`. `trim(color, options)` and `colorToAlpha(color, options)` take the color as `color` in the options (`trim({ color, tolerance })`, `colorToAlpha({ color, transparencyThreshold })`), and `Frame.trim()` works the same way. A value in the old position throws a `TypeError`. + +- **The positional arguments of the encoders are removed**: `encodePNG(compression, metadata)` and `encodePNG(metadata)` are `encodePNG({ compression, metadata })`, `encodeJPEG(quality)` is `encodeJPEG({ quality })`, `Animation.encodeGIF(quality)` is `encodeGIF({ colors })` (see the GIF options below) and `Animation.encodeAPNG(compression)` is `encodeAPNG({ compression })`, and `GainMap.encode(quality)` is `encodeJPEG({ quality })`. For example, `image.encodePNG(1, { author })` is `image.encodePNG({ compression: 1, metadata: { author } })`; the metadata alone, `image.encodePNG({ author })`, is ignored now. + +- **The positional arguments of `Image.renderSVG()` are removed**: `Image.renderSVG(svg, 512, 'width')` is `Image.renderSVG(svg, { width: 512 })` (see below), next to the `fonts` and `images` options. + +- **The positional arguments of `new Frame()`, `Frame.from()` and `new Animation()` are removed, and `Animation.decode()` takes no flag**: `new Frame(width, height, duration, xOffset, yOffset, disposalMode)` is `new Frame(new Image(width, height), { duration, xOffset, yOffset, disposalMode })`, `Frame.from(image, duration, xOffset, yOffset, disposalMode)` is `new Frame(image.clone(), { duration, xOffset, yOffset, disposalMode })` (see the frames below), `new Animation(frames, loopCount)` is `new Animation(frames, { loopCount })`, and `Animation.decode(data, true)` is `Animation.decode(data)`, or `Image.decode(data)` for the first frame only. + +- **`Image.decode()` returns the first frame of an animation**: a GIF or an animated WebP, which threw in 3.x, is an `Image` of its first frame, composed onto the canvas as `Animation.decode()` composes it, and decoding stops after that frame, so it is fast on long animations. Animated JPEG XLs and AVIF sequences were already their first frame. An APNG is still its default image, what viewers without APNG support show. Use `Animation.decode()` for all the frames. + +- **`decode()` follows animation markers as well as frame count**: files with multiple frames or an explicit animation marker return an `Animation`, including one-frame APNGs and animated WebPs; a static image or an unmarked one-frame GIF returns an `Image`. A one-frame animation keeps its timing and loop metadata. `Image.decode()` still returns only an `Image` of the first frame. + +- **The `GIF` class is removed**: `new GIF(frames, loopCount)` is `new Animation(frames, { loopCount })`, `GIF.decode(data)` is `Animation.decode(data)` and `gif.encode(quality)` is `animation.encodeGIF({ colors })`. `Animation` decodes and encodes GIFs the same way it does APNGs and WebPs. + +- **`Animation` holds its frames instead of extending `Array`**: `animation.frames` is a frozen snapshot; the `Frame` objects remain mutable. To change the list, assign a new array (the setter copies it). `animation[0]`, `animation.push(frame)` and `animation.map(...)` become `animation.frames[0]`, `animation.frames = [...animation.frames, frame]` and `animation.frames.map(...)`. `animation.slice(start, end)` is `new Animation(animation.frames.slice(start, end), { loopCount: animation.loopCount })`. `for (const frame of animation)`, `animation.length` and the methods of `Animation` work as before, and `Array.isArray(animation)` is `false`. + +- **Loop counts are `Infinity` (forever, the default) or an integer from 0**: `loopCount: -1` is `loopCount: Infinity`, and the encoders and the decoded animations use `Infinity` where they used `-1`. `-1` now throws a `RangeError` like the other negative numbers, `NaN` and fractions do, and numeric strings, `null` and booleans throw a `TypeError`. The check applies to `new Animation(frames, { loopCount })`, `animation.loopCount = ...` (which leaves the count as it was when it throws) and the encoders (`Animation.gifEncoder()`, `webpEncoder()` and `apngEncoder()`). Finite counts are the same as before: `loopCount: 2` still plays three times. + +- **Text alignments only take the values of their own axis**: `horizontalAlign` takes `'left'`, `'center'` or `'right'` and `verticalAlign` takes `'top'`, `'middle'` or `'bottom'`. 3.x accepted the other axis' values in either field, which now throws a `TypeError`: `verticalAlign: 'right'` is `horizontalAlign: 'right'`. + +- **`decode()` takes options only**: `decode(data, true)` is `Image.decode(data)` for the first frame, and a boolean throws a `TypeError` that names the options form. + +- **`resize()` needs a height in the positional form**: `image.resize(100)` throws a `TypeError`; `resize({ width: 100 })` keeps the aspect ratio. The positional form takes both sides as finite numbers, `Image`, `Frame` and `Animation` alike. + +- **Loop counts a format can't store throw a `RangeError`**: a GIF stores up to 65535 loops, a WebP up to 65534 and an APNG up to 2147483646 (2^31 - 2). A larger count used to wrap around silently (65536 as a GIF was forever). The encoders and the streaming encoders refuse it before encoding; `Infinity` is always fine. + +- **Removed and narrowed exported types**: `TextOptions` is `RenderTextOptions`, `FrameDisposalModeId` is removed (`FrameDisposalMode` has the names), `AdjustOptions` is removed with `absolute`, `PNGMetadata` is `Metadata`, and `AnimationEncoderOptions`, `WebPAnimationEncoderOptions`, `GIFAnimationEncoderOptions` and `APNGAnimationEncoderOptions` are `AnimationEncodeOptions`, `WebPAnimationEncodeOptions`, `GIFAnimationEncodeOptions` and `APNGEncodeOptions`. `ResizeMode` is narrowed to the lower-case names (`'area'`, ...), `ContainOptions` is removed, and `SVGScaleMode` is removed. + +- **Fixed-length tuple types**: `Image`, `Frame` and `Animation.transform()` take `AffineTransform` (exactly six values); gain-map channel options and setters take a scalar or a three-value tuple (`GainMapChannelValues`), not an arbitrary `number[]`. + +- **Hues are in degrees**: `Colors.fromHSL()`, `Colors.fromHSLA()` and `Colors.toHSLA()` take and return the hue in degrees (0-360, like CSS' `hsl()` and `hueShift()`) instead of 0-1. + +- **`drawBox()` and `drawCircle()` are removed**: `image.composite(new Image(w, h).fill(color), { x, y })` draws a box, with `.cropCircle()` a circle. Compositing blends a translucent color over the image, where `drawBox()` replaced the pixels. + +- **`renderSVG()` takes `width`, `height` or `scale`**: `{ size: 512, mode: 'width' }` is `{ width: 512 }`, `{ size: 2 }` is `{ scale: 2 }`; `SVGScaleModes` and `SVGScaleMode` are removed. More than one of them throws a `TypeError`. + +- **`rotate()` turns clockwise**, like CSS' `rotate()` (3.x turned counterclockwise): negate the angle for the old result. Its `fast` option is removed (the bilinear sampling is always the 8-bit one that `fast: true` was, with the same pixels) and `mode` (`'nearest-neighbor'`, `'bilinear'` or `'bicubic'`) picks the sampling like `transform()`'s. + +- **`dominantColor()` counts colors in a histogram, and its `threshold` is in channel values**: the colors are counted in 16 levels per channel (like sharp's `dominant`) and the average of the fullest bin is returned, instead of the average of the largest of 8 median cut clusters, so the result is a color the image has and not a mix of two hues; it can differ from 3.x's. The `threshold` is 0-256 instead of steps of 4 (0-64): the default `60` is 3.x's `15`; multiply a threshold you give by 4. + +- **`renderText()` takes the image's `width` and `height`**: `maxWidth` and `maxHeight` are `width` and `height`, which also set the image's size: lines wrap to the width (inside the outline), lines that don't fit the height are left out, and `horizontalAlign` and `verticalAlign` place the text in that box. Without them, the image is as large as the text, as before. `wrapHardBreaks` is removed: remove the line breaks from the text instead. An old `maxWidth` is ignored, so the text doesn't wrap: search for it. `0` no longer means no limit (it throws). + +- **Right-to-left text is aligned to the right by default**: `horizontalAlign` defaults to the start of each paragraph's direction (like CSS' `text-align: start`), so Arabic, Hebrew and other right-to-left paragraphs are aligned to the right and left-to-right ones to the left, where 3.x aligned everything to the left. Pass `horizontalAlign: 'left'` for the old placement. + +- **The `fast` option of `resize()` and `scale()` is removed**, on `Image`, `Frame` and `Animation`: resizing always works like its default (`fast: true`); `{ fast: false }` is ignored. The precise path took 15-25% longer for opaque images, for results at most a step or two closer. + +- **`encodeJPEG()` composites transparent pixels onto a background**, black by default (`background` sets the color), instead of dropping the alpha and showing the stored color. Opaque images encode as before. + +- **`Frame` holds an image instead of extending `Image`**: `frame.image` is the image, `new Frame(image, options)` takes it (without a copy), and `Frame.from()` is removed. `resize()` (including its `'contain'` and `'cover'` fit modes), `scale()`, `crop()`, `trim()`, `rotate()`, `transform()`, `dropShadow()` and `outline()` stay on the frame and move its offsets so it stays in place; everything else is `frame.image.blur(2)` and the like. `frame.crop()` and `frame.rotate()` now move the offsets too (3.x kept them), and the offsets can become negative where 3.x stopped the growth at 0. + +- **GIF palettes take a color count**: the `quality` of `Animation.encodeGIF()` and `Animation.gifEncoder()` is `colors` (2-256, default 256, which `quality` 90 and above gave), with the new `dither` and `ditherStrength`. Their options type is `GIFAnimationEncodeOptions`; `GIFEncodeOptions` is now the options of `Image.encodeGIF()`. + +- **`quantize()` dithers by default**: Floyd-Steinberg at a strength of `0.85`, like the GIF encoders (3.x: no dithering, and a strength of `1` when dithering). `dither: 'none'` gives the old default. + +- **Removed**: `getRGBAAt()` (use `Colors.toRGBA(image.getPixelAt(x, y))`). + +- **Renamed types**: `FrameDisposalModeName` is `FrameDisposalMode`, `SVGOptions` is `RenderSVGOptions` (like `RenderTextOptions`) and `TextStyle` is `TextStyleOptions` (like `TextLayoutOptions`). They are types only, nothing changes at runtime. + +- **Renamed**: `greyscale()` is `grayscale()` (American spelling throughout), the `fonts` option of `renderSVG()` is `font` (like `renderText()`'s), `GainMap.encode()` is `GainMap.encodeJPEG()` (named for the format it writes), `region()` is `extract()`, the `resize` option of `rotate()` is `expand` (like `transform()`, `outline()` and `dropShadow()`), `GainMap`'s `gainMapMin` and `gainMapMax` (properties and options) are `min` and `max`, and the parameters of `setPixelAt()`, `lightness()`, `saturation()` and `opacity()` are `color` and `factor`. + +- **Fewer types and classes**: `TextLayout` isn't exported, `renderText()` takes the layout options with its other options (`{ font, size, width: 300 }`). `AnimationDecodeOptions` is `DecodeOptions`, which all decode functions take. `encodeTGA()` takes `TGAEncodeOptions`; `EncodeOptions` is the `metadata` that every encoder's options extend, and the `gainMap` option of the JPEG, AVIF and JPEG XL encoders is `boolean | GainMapEmbedOptions`. + +- **Values are checked when they are set**: `frame.duration`, `frame.xOffset`, `frame.yOffset` and the parameters of a `GainMap` throw for invalid values (instead of failing in a later encode) and keep their value. A gain map's parameters lie within ±(2^31 - 1) and its gamma is 2^-31 or more, what JPEG, AVIF and JPEG XL store: beyond that they were written wrapped or as 0, and decoders dropped the map. + +- **An animation has its own canvas size**: decoded animations keep the file's, `new Animation(frames, { width, height })` sets one (`AnimationCanvasOptions`), and `resize()` sets the new one. Without one it is the frames' extent, as before. Frames (or their parts) outside the canvas aren't encoded. + +- **Values that were wrapped, clamped or ignored throw**: colors have to be integers from -2^31 to 2^32 - 1, also the ones a `fill()` function returns (they wrapped to 32 bits; negative ones, which bitwise operators return, keep working); pixel coordinates are truncated without wrapping at 2^32; `compression` is an integer 0-9 like `effort` (it was clamped); `Colors.fromRGBA()` and `fromHSLA()` components outside of 0-255 (0-1 for saturation, lightness and alpha) throw, they were clamped; frame durations that GIF, APNG or WebP can't store throw a `RangeError` like loop counts (they were cut; unchanged frames merged by the encoders are split at the limit); `frame.xOffset` and `frame.yOffset` are truncated to integers when set; `image.bitmap = view` throws a `TypeError` for a view that doesn't start at a multiple of 4 bytes (it was copied, so changes to the view were lost); `Colors.gradient()` throws for a `NaN` position with any number of stops; `encodeGIF()` of an animation without frames throws like the other encoders; the `quality` of `encodeJPEG()` is checked like the other formats' (0-100, it was clamped); `composite()` throws a `TypeError` for a source that isn't an `Image`. + +- **Numbers have to be numbers**: a numeric string (`opacity('0.5')`, `quality: '50'`, `frame.duration = '40'`, `maxPixels: '100'`), `null` or a boolean where a number goes throws a `TypeError` naming the value. 3.x converted them in some methods and rejected them in others. `NaN` and the infinities are still a `RangeError`. +- **Values that did nothing useful throw**: `roundCorners({ radius })` below 0 (it was clamped to 0) and `fisheye({ strength })` of 0 or less (which left an empty image). +- **WebP at quality 100 is lossless**, like AVIF and JPEG XL: `encodeWebP({ quality: 100 })` wrote a lossy file in 3.x. Use `99` for the highest lossy quality +- **Gradients blend transparency premultiplied**, like CSS: `Colors.gradient()`, `Image.linearGradient()` and `radialGradient()` between a transparent and an opaque color no longer pass through a dark midpoint (transparent to red is `ff00007f` in the middle, was `7f00007f`). Gradients between opaque colors are unchanged. +- **Images use a copy of the gain map they are given**: `image.gainMap = map` copies it, so images that were given one map no longer change each other's by resizing or cropping. + +- **Invalid choices throw a `TypeError` naming the valid ones**: the resize `mode` (an `Error`, thrown once resizing started, so `resize({ fit: 'cover' })` could move a frame's offsets before failing), `composite()`'s `mode`, `flip()`, `disposalMode` and `wrapStyle` (`RangeError`s; an empty or `null` `wrapStyle` was the default). + +- **No creation time and no version in encoded files by default**: the encoders only write a creation time when `metadata.creationTime` is given, so the same image encodes to the same bytes on one runtime (PNG and APNG compress with the runtime's own zlib, whose output differs between Node.js, Deno, Bun and browsers), and the default software is `'ImageScript'` without the version. `creationTime: null` and `software: null` leave the field out. + +- **Drawing an SVG image that can't be drawn throws**: an `href` that isn't a data URI or one of the `images`, an image that can't be decoded (with the decoding error as its `cause`), an unsupported data URI type or an embedded SVG that can't be read throw once they are drawn (images in `` or hidden ones don't); they drew nothing before. A font in the `font` option that can't be read throws too, like in `renderText()` (it was left out); damaged fonts that the SVG embeds with `@font-face` are still left out, as in browsers. + +- **The encoders return `Promise>`** instead of `Promise`, so `new Blob()`, `new Response()` and `crypto.subtle` take the output without a cast, also with the stricter DOM types of TypeScript 5.9 and newer. The type needs TypeScript 5.7 or newer. + +### New + +- `renderSVG()`'s fixed limits of work throw a `LimitError` like its options' limits (an `Error` in 3.x): elements drawn through `` references, nested masks, clip paths, patterns, markers and filter images, and entity expansion. `LimitError` is a `RangeError`, so `catch` blocks that test for `Error` still catch them. +- `GainMap.decode(data, { maxPixels })` takes the limit of `Image.decode()`, and the `LimitError` that these limits throw is exported (with `name` `'LimitError'`). +- `rotate(angle, { expand: false })` keeps the image's size for quarter turns, too: the turned image is centered and what doesn't fit is cut off (they swapped width and height). +- `renderSVG()` throws for masks, clip paths, patterns, markers and filter images nested in each other so deeply that they would multiply (three per level took minutes at ten levels), and stops at 24 `feTurbulence` octaves, which are all that its output can hold. Shapes far outside the image no longer make rendering hang. +- `renderSVG({ maxLayerPixels })` limits the layers SVG rendering uses at once (groups with opacity, masks, filters, ...; 16 bytes per pixel each), so nested ones can't multiply the memory of a small SVG: default `4 * maxPixels`. `renderSVG({ maxImagePixels })` limits the raster images an SVG references together (default `maxPixels`; each was limited on its own before). +- `renderText({ maxPixels })`, default 16383², counting the outline, checked before anything is allocated. +- `Animation.clone()`, `Animation.crop()` and `Animation.flip()` (each frame mirrored, and its place on the canvas), and the `FlipDirection` type. +- `resize({ width, height, fit })` on images, frames and animations: `'inside'` fits without padding, `'contain'` pads, and `'cover'` crops while keeping the aspect ratio; `background` sets the bars for `'contain'`. +- `encodeJPEG()` accepts `subsampling: '4:4:4'` or `'4:2:0'`; the default stays 4:2:0 up to quality 90 and 4:4:4 above. +- `Colors.gradient()` takes an array of evenly spaced colors, like the `stops` of the gradient functions. +- `Animation.scale()`, `Animation.trim()`, `Animation.rotate()`, `Animation.transform()`, `Animation.dropShadow()` and `Animation.outline()`. `scale()` and `trim()` keep the frames; the others work on the composited animation (full canvas frames) and resize the canvas. +- `Frame.rotate()`, `Frame.transform()`, `Frame.dropShadow()` and `Frame.outline()`, which move the offsets like `Frame.resize()` and `Frame.crop()`. +- `Image.encodeGIF()` for single images, with `colors`, `dither` and `ditherStrength` (also on the animation encoders), and the `DitherMethod` and `DitherOptions` types that `quantize()` and the GIF encoders share. The option types of the animation encoders extend those of the format's still images (`APNGEncodeOptions` extends `PNGEncodeOptions`, `WebPAnimationEncodeOptions` extends `WebPEncodeOptions` without `threads`). `QuantizeOptions` is a union: TypeScript reports a call with both `colors` and `palette` (it throws at runtime). +- `RenderSVGOptions` is a union of the sizes (`width`, `height` or `scale`, TypeScript reports a call with more than one, which throws at runtime) and `SVGResourceOptions`, the limits, fonts and images. +- `renderSVG({ font })` takes a single font without an array, like `renderText()`. + +### Performance + +- Lossy JPEG XL encoding starts no worker threads below 1.5 megapixels when fewer than 4 threads are used (a machine with 2 or 3, or `threads: 2`): there the threads took 1.3-1.7x as long as one on images from 0.5 to 1 megapixel. With 4 threads or more, nothing changes (threads win from 0.5 megapixels). + +### Fixes + +- `renderSVG()` bounds the points paths are made of: an arc between far-apart ends is drawn with at most 64 curves a turn (a 139-byte path, `M 1e25 100 A 40 30 20 1 1 160 100`, stroked, ran the process out of memory), and the curves of arcs and the points of all paths, also of each copy drawn through ``, count against 2^25 points plus 4 per pixel of the output in one render and 2^21 in one path. Reading path data and placing text along a `` count, too, and SVGs embedded as images share the budget of the render they are in. More throw a `LimitError` (which a text's layout no longer takes for a damaged font). A path drawn through `` is read once a render instead of once a copy. +- SVG text: the glyph outlines of all texts count against the render's points before they are made, 16 points a command (20 texts of 1,000 characters of a complex font ran the process out of memory), so very long texts need a larger output; many ``s in one `` take linear time (10,000 took 20 s); a `` on a long path renders at a normal size; bitmap emoji (CBDT, sbix) are decoded once a render instead of once a draw (copies through `` took minutes), at most 2048x2048 pixels each (larger ones aren't drawn, also in `renderText()`: one that said 16383x16383 ran the process out of memory), and counted before they are decoded, also damaged ones. `renderText()` counts the work of decoding and scaling its bitmap glyphs against 2^28 pixels plus 64 per pixel of the image (more throw a `LimitError`), keeps at most 2^22 pixels of scaled glyphs in a render and none after it (they were kept with the font: 1 GB a size), keeps rasters of outline and color glyphs with the font only up to 256 KB each, 4 MB a font and 8 text colors a glyph (62 letters at size 6000 kept 774 MB, a new color each render grew without end), counts the glyphs it rasterizes against the same work budget as bitmap glyphs (2000 huge glyphs without advance took 260 s), frees a size's rasters when its sizes are evicted, and keeps at most 64 instances of a variable font in `renderText()` (a new weight each render ran out of memory after 8000; `renderSVG()` keeps the instances of one render), and doesn't draw a glyph scaled to more than 4 times the image (a strike at ppem 1 made a 32768x32768 copy for a 10x10 image). +- `renderText()` takes linear time for many combining marks and lines (400,000 lines took minutes). +- Very long text (50,000 characters in SVG, 200,000 combining marks or lines in `renderText()`) no longer overflows the call stack or says the font is damaged. +- Binary data and dates of other realms (iframes, `node:vm`, Jest) are accepted; objects that only claim to be one by `Symbol.toStringTag` aren't, and a detached buffer throws a `TypeError` that says so. +- `encodeJPEG()` and `encodeWebP()` check the image's size before going over its pixels; `metadata.creationTime` of another type than a `Date`, a number or a string throws a `TypeError` (`true` was 1970). +- `Colors.gradient()` has the later stop's color at every hard edge (two stops at one position), like CSS, also inside the gradient and with 2 stops. +- `encodeJPEG()` of an image with transparency composites it onto the background row by row instead of copying the image first: the peak memory of a 6000x6000 image is 378 MB instead of 485 MB, the same as without transparency, and the file is the same (images with a gain map still take the copy). +- `encodeWebP({ optimize: false })` makes the same file as `webpEncoder()` for animations with frames WebP can't store as they are (stored as the canvas from the first such frame on, not all of them), and `Colors.gradient()` with 3 or more stops has its first and last stops' exact colors before and after them (a transparent end stop gave `0x00000000`) and takes 200,000 stops without overflowing the call stack. +- `resize({ fit: 'inside' })` throws for a box side below 1 pixel, like the other fits, instead of making a 1x1 image; `pixels()` goes over the pixels the image has when it's called, also when it's resized before the first value is taken. +- `Image.renderText()` checks `strokeColor` without a `strokeWidth` too (a wrong color passed until a stroke was set), and an animation encoder whose `finish()` found no frame can still be given frames. +- A `creationTime` with a year outside 1000-9999 throws a `RangeError` instead of being written wrapped (TGA) or without 4 digits (Exif). +- An SVG with an element of more than about 100,000 children renders (or throws a `LimitError`) instead of a bare `RangeError` from the call stack. +- A damaged CFF font (a real number in a DICT without its end, which ran the process out of memory within seconds, through `renderText()` and an SVG's `@font-face` alike) throws an `Error`; a CID-keyed one whose FDSelect names a missing private dict throws an `Error` instead of an internal `TypeError`. +- **Cut-off JPEG and lossy WebP files throw** like the other formats: a JPEG without any scan data, or whose scan ends before its last block, and a WebP whose image data (any chunk of it) ends before its size says. They decoded without an error, as gray or smeared images. A JPEG that only lacks its end marker still decodes. +- `Image.pixels()` yields the pixels the image had when the iteration started, where resizing the image meanwhile threw an error from the inside or stopped early. +- `Animation.decode()` gives a still image (PNG, JPEG XL, WebP, JPEG, ...) a frame of 100 ms, the `Frame` default, not 0 ms. +- `JSON.stringify()` and `console.log()` of an `Image`, `Frame` or `Animation` show their size (and duration), not every pixel; `new Colors()` throws. +- `image.composite(image, { x, y })` onto itself (or an image sharing its pixels) read pixels it had already overwritten, and differed from compositing a copy. +- `dominantColor({ threshold })` outside 0-256, `GainMap.encodeJPEG({ quality: 0 })` and a `metadata` that is not an object throw instead of being clamped or ignored. +- `Animation.resize()` changes a frame once when the animation lists the same `Frame` (or two frames share one `Image`) more than once, as a hold or a ping-pong does; each listing resized or moved it again before (`new Animation([f, f, f]).resize(50, 50)` made 13x13 frames). +- The animation encoders (`Animation.webpEncoder()`, `gifEncoder()` and `apngEncoder()`) cut frames to the canvas like `Animation.encode*()` does when `optimize` is `false`: a frame reaching over the edge lost the part it covered (GIF, WebP) or threw (APNG). +- `AnimationEncoder.add()` rejects its promise for invalid frames instead of throwing synchronously, so `encoder.add(frame).catch()` sees them. +- `Image.linearGradient()` and `radialGradient()` work with fractional sizes (`width / 2`, ...) at the truncated size of the image; they threw a `RangeError` because they wrote past the pixels. +- `scale()` keeps each side at least one pixel like `resize()`, where `new Image(7, 1).scale(0.5)` threw. +- A damaged JPEG XL whose blend refers to a channel that doesn't exist throws the decoding error instead of a `TypeError` from inside the decoder. +- The gain map's `hdrCapacityMin` and `hdrCapacityMax` are checked against each other when they are set (the old value stays): `map.hdrCapacityMax = -0.5` was accepted, and `clone()`, `image.gainMap = map` and the encoders then threw. The check between `min` and `max` still applies when the map is cloned or encoded, and names the values. A one-element array for a channel value (`max: [2]`) throws like other lengths that aren't 3 (it was read as a scalar). +- The encoders' `gainMap: { quality, scale }` is checked also for images without a gain map, `quality` 1-100 (0 was accepted), and `gainMap: 'yes'` throws a `TypeError`; `encodeWebP()` checks `alphaQuality` for lossless images too (101 was accepted, like `effort` already was checked). +- Boolean options take `true` or `false` only: `optimize: 'yes'`, `applyOrientation: 'no'`, `hinting`, `ignoreBlack`, `ignoreWhite`, `sharpYuv` (also for lossless images) and `expand`, and the decoders' `gainMap` throw a `TypeError` (a string was read as `true`). +- A value that isn't a number where one goes is a `TypeError` everywhere: `transform('matrix(...)')`, `colorMatrix()` without an argument, `features: { liga: 'on' }`, `variations: { weight: 'bold' }` and a `metadata` text field that isn't a string (`title: 123` was written as `'123'`) threw a `RangeError` or were accepted; `Image.linearGradient(w, h)` without options names the missing `stops` instead of failing in a destructuring. The same for `renderText({ width: '300' })`, a string among the values of `transform()` and `colorMatrix()`, the canvas size of the streaming encoders (`Animation.gifEncoder('64', 64)`), `transform({ origin: null })` (a raw "Cannot read properties of null"), frames that aren't an array (`new Animation(5)` said "not iterable") and binary data that isn't one; `Image.linearGradient(w, h, {})` without `stops` names them too, and error messages name an object or an array as such instead of `[object Object]`. +- `software: null` without other metadata writes no Exif block to JPEG, WebP, AVIF and JPEG XL files (an empty 22-byte one was written). +- PNG chunks with a bad checksum are skipped when they hold color or text metadata (cICP, iCCP, tEXt, ...), like libpng and browsers do; a bad checksum on the image's own chunks (IHDR, PLTE, IDAT, IEND and the APNG frames) still throws. Such files (in the pngrs and Pillow test suites) were refused. +- A JPEG scan with restart markers carries on after corrupt entropy data: the rest of the damaged interval decodes to empty blocks and the next marker resyncs the decoder, like libjpeg; without restart markers, corrupt data still throws. A Pillow test photo with 1.2 KB of garbage in one interval was refused. +- `encodeBMP()` of a fully transparent image decodes to transparent pixels (3.x made them opaque): the decoder took an alpha channel that is zero everywhere for an unused one, which is right for the implicit alpha of 32-bit icons, not for the alpha mask the file declares. +- A wrapped right-to-left paragraph with `horizontalAlign: 'left'` or `'center'` places its lines by their ink: the space at a wrap point sits at the visual left of a right-to-left line, which pushed the lines right by its width. +- `encodeJPEG()` writes an image whose pixels are all gray as a grayscale JPEG (one component, like `cjpeg -grayscale`), a few percent smaller and quicker for readers; it was written with three components. +- `renderSVG()` of an SVG with a `viewBox` and only one of `width` and `height` sizes the other side by the viewBox's aspect ratio, like browsers (`` is 50x30; it was 50x60 with the content letterboxed). +- `Animation.resize()` resizes frames that share one `Image` at different offsets to the size their edges give (they got the first one's width, so a frame could reach past the canvas), and throws for a width or height below one pixel instead of returning 1x1. +- The GIF encoders throw a `RangeError` for a canvas wider or higher than 65535 pixels (it was stored modulo 65536: 70000 became 4464), and all encoders for an animation without a canvas (every frame outside it), which WebP wrote as 16777216x16777216. +- `Animation.decode()` of a JPEG XL animation counts the pixels of all frames against `maxPixels`, like the other formats; a frame was counted alone. +- `resize({ fit: 'cover' })` and `fill()` leave an image (and its gain map) as it was when they throw: a `cover` that couldn't allocate its result had already changed the gain map, and a `fill()` function that threw halfway had written half the pixels. +- Animations that are cut off keep the frames that arrived whole and nothing else, and throw without a whole one: a GIF (it decoded a blank image when cut before its first frame, and returned the half-decoded last frame otherwise), an APNG (it showed the first frame only), a lossy WebP animation and a lossy JPEG XL animation (both returned a damaged last frame, the JPEG XL one also for frames of a single section). +- Numeric arguments that accepted values silently refuse them like the rest: `scale('2')`, a `null` option value (`composite({ opacity: null })`, `roundCorners({ radius: null })`, `fisheye({ strength: null })`, a frame's `duration` and offsets in the encoders' `add()`), `blur('2')` and the gain map's setters with a non-number are a `TypeError`. `cropCircle({ feathering })` outside 0-1 throws instead of being clamped, and `renderText({ size: 0 })` throws like a negative size (it returned a 1x1 image). +- Damaged files with a frame header cut short (JPEG), a BitsPerSample tag outside of the file (TIFF) or sizes that don't match their pixels (GIF, TGA, TIFF) are decoding errors, where they read missing bytes (`JPEG: undefined-bit precision`) or threw a `RangeError` from making the image. +- `Colors.gradient()` with one color throws for a `NaN` position like the others. +- TIFF files that ask for far more memory than they are are refused before anything is allocated: YCbCr subsampling factors other than 1, 2 and 4 (65534x65535 took 4 GB and 5 s for a 32 KB file) and more than 32 samples per pixel (1 GB for 33 KB), and the memory of the YCbCr units counts against `maxPixels`. +- `Animation.decode()` of an APNG or WebP composites each frame as it is decoded, so its peak memory is 1.3 times the result instead of 2.2 (all decoded frames were held next to the composited ones); GIFs let go of each frame's color indices once it is composited (1.45 times, now 1.2). +- `renderSVG()` bounds the work of strokes with round joins: a join was a whole circle of up to 256 points at every vertex of a flattened curve, so a 17 KB path took 9 s and 1 GB and a 50 KB one 2.7 GB (now a wedge on the outer side, 1.6 s and 220 MB, and 0.3 s and 350 MB). Round joins differ from the circles by at most 5 of 255 on the edge pixels. Shapes whose edges cross the rows of the image more than 2^27 times (thousands of huge overlapping strokes took 38 s from 51 KB of SVG) throw a `LimitError`. +- Bundlers drop the parts of the library a page doesn't use: the build's `dist/package.json` declared only `"type": "module"`, which hid the `"sideEffects": false` of the package from them, so `import { Colors }` bundled the whole library (about 1.1 MB minified, now about 4 kB). +- `renderSVG()` rasterizes shapes with many edges in near linear time: the edges that start in a row were inserted one by one into the sorted active ones, so text of 20000 glyphs took 15 s (now 0.4 s) and 8000 random curves 18 s (now 2.3 s). +- `renderSVG()` keeps the memory of dashed strokes bounded: dashes beside the image are left out and the others are stroked a batch at a time, so a line of a million dashes (157 bytes of SVG) no longer takes 650 MB. The rasterizer also keeps one sub-scanline's crossings at a time instead of 16. +- AVIF 4:2:0 images of an odd width decode the last column like libavif: it took the chroma of the column to its left too (off by up to 51). +- `Animation.decode()` counts every frame as at least 1024 pixels of `maxPixels`, while the frames are decoded: a frame takes memory however small it is (a 4.6 MB GIF of 200000 frames of 1x1 took 720 MB, and 1000000 such frames 1.8 GB and 77 s), so the default limit allows about 262000 frames. +- `renderSVG()` bounds the pixels its shapes and layers paint: 2^28 plus 64 per pixel of the output in one render, more throws a `LimitError` (1000 `` copies of a full-canvas group, 16 KB of SVG, took 260 s at 4000x4000). +- `renderSVG()` bounds the work of markers: their elements count against the 100,000 elements of `` references, and one render draws at most 10,000 markers (120,000 vertices with `marker-mid` took 135 s). +- `renderSVG()` bounds the work of filters: their primitives may work on 2^25 pixels plus 16 per pixel of the output in one render (once per pass: an `feConvolveMatrix` per 9 taps of its kernel, an `feTurbulence` per octave, an `feMerge` per node), more throws a `LimitError`; a filter's region counts against `maxLayerPixels` like the other layers (one of more than 2^26 pixels was left out without a word) (600 blurs and morphologies over a megapixel, 37 KB of SVG, took more than 3 GB and minutes), and the results a filter keeps for `result=` references count against `maxLayerPixels`. +- `renderSVG()` parses `transform` lists in linear time: a long list of unclosed functions took 4.8 s at 280 KB. + ## 3.20.4 ### Deprecated @@ -70,7 +264,7 @@ there without an error: - `resize({ width })` and `resize({ height })` on images, frames and animations: the missing side keeps the aspect ratio, `resize({ width: 256, mode: 'bicubic' })`. - `image.coordinates()` yields `[x, y]` and `image.pixels()` yields `[x, y, color]` for every pixel, row by row. -- `cropCircle({ size: 'contain' | 'cover' })`: `'contain'` (the default, as before) keeps the circle inside the image. +- `cropCircle({ fit: 'contain' | 'cover' })`: `'contain'` (the default, as before) keeps the circle inside the image. - `Image.renderText(text, { font, size, color, layout, ...style })`: the text first, everything else in the options. `layout` is `TextLayoutOptions` or a `TextLayout`: `Image.renderText('Hi', { font, size: 32, layout: { maxWidth: 400 } })`. - `Infinity` as the loop count of animations that loop forever (`new Animation(frames, { loopCount: Infinity })`, @@ -94,7 +288,7 @@ there without an error: `APNGAnimationEncoderOptions`: they are the same as `AnimationEncodeOptions`, `WebPAnimationEncodeOptions`, `GIFEncodeOptions` and `APNGEncodeOptions` with `loopCount`, which are all the types there are in 4.0. - `encode()`: use `encodePNG()`, which takes the same arguments. Removed in 4.0. -- `cropCircle(max, feathering)` and the `max` option: use `cropCircle({ size: 'contain' | 'cover' })`. Removed in 4.0. +- `cropCircle(max, feathering)` and the `max` option: use `cropCircle({ fit: 'contain' | 'cover' })`. Removed in 4.0. ### Documentation diff --git a/LICENSE b/LICENSE index 3c1eb49a..19249d8c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,15 +1,19 @@ -This software is licensed under the following license(s): -- GNU AFFERO GENERAL PUBLIC LICENSE, Version 3 -- MIT License +Copyright (c) 2020-2026 Mathis Mensing -== SPDX-License-Identifier: AGPL-3.0-or-later OR MIT == +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -You may choose to comply with either one of the above -mentioned licenses, but a license must be chosen. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -The corresponding license files can be found in the projects -root directory, prefixed with LICENSE, suffixed with their -corresponding SPDX identifier. - -Parts of this software are derived from third party projects under their -own licenses (MIT, Apache-2.0 and the IJG license), see THIRD_PARTY_NOTICES.md. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/LICENSE.AGPL-3.0 b/LICENSE.AGPL-3.0 deleted file mode 100644 index ce0100f6..00000000 --- a/LICENSE.AGPL-3.0 +++ /dev/null @@ -1,619 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS diff --git a/LICENSE.MIT b/LICENSE.MIT deleted file mode 100644 index 8f0286a8..00000000 --- a/LICENSE.MIT +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2023 Mathis Mensing - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 15768387..b8faf659 100644 --- a/README.md +++ b/README.md @@ -13,21 +13,24 @@ --- -**ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, no -dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's Edge -Runtime, Deno Deploy), works with both `import` and `require()`, and ships with type definitions. Large images are -encoded and decoded on several threads wherever the runtime supports workers. +**ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, and no +runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's +Edge Runtime, Deno Deploy), works with `import` and, on supported Node.js versions, `require()`, and ships with type +definitions (TypeScript 5.7 or newer; CommonJS projects need `module: nodenext` and 5.8 or newer to `import` it (`module: node16` can't). With older versions and `skipLibCheck`, the encoders' return types become `any`). Large AVIF and JPEG XL operations, and lossless WebP encoding, can use multiple CPU cores when the runtime +supports it. ```sh npm install imagescript # Node.js, Bun and bundlers deno add jsr:@matmen/imagescript # Deno ``` +Upgrading from 3.x? Read [Migrating to 4.0](https://github.com/imagescript/ImageScript/blob/master/guides/Migrating%20to%204.0.md) first. + Without a bundler, import it from jsDelivr in the browser: ```html ``` +The codecs that can use worker threads (large AVIF and JPEG XL images, lossless WebP; the `threads` option) do so in +Node.js, Deno and Bun, and in browsers on cross-origin isolated pages. Where workers can't start, the work runs on the +calling thread: the output is the same, only slower, and nothing warns about it. Browsers refuse workers from another +origin, so the jsDelivr example above runs single-threaded; serve the package from your own origin (on a cross-origin +isolated page) to get threads. + +Bundlers that write one file (esbuild, Rollup, `bun build`) don't copy the worker's module: serve `dist/util/worker.js` next to the +bundle, or the same single-threaded fallback is used. webpack and Vite emit it. + --- ### Example @@ -45,7 +57,7 @@ import { Image } from 'imagescript'; import { readFile, writeFile } from 'node:fs/promises'; const image = await Image.decode(await readFile('input.jpg')); -image.resize({ width: 256 }).roundCorners(16); +image.resize({ width: 256 }).roundCorners({ radius: 16 }); await writeFile('output.png', await image.encodePNG()); ``` @@ -71,17 +83,27 @@ await writeFile('output.png', await image.encodePNG()); | GIF, APNG (animations) | ✓ | ✓ | | BMP, QOI, TGA, Netpbm | ✓ | ✓ | | TIFF, ICO/CUR, Radiance HDR | ✓ | | -| [HDR gain maps](https://imagescript.dev/classes/GainMap.html) (Ultra HDR and iPhone JPEGs, AVIF, JPEG XL) | ✓ | ✓, kept through edits | +| [HDR gain maps](https://imagescript.dev/classes/GainMap.html) (brighter highlights on HDR displays; JPEG, AVIF, JPEG XL) | ✓ | ✓ | [Animations](https://imagescript.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL, and encoded as GIF, APNG or WebP, all at once or -[frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Embedded color profiles (Display -P3, Adobe RGB, ...) are converted to sRGB when decoding, so images look the way browsers show them. +[frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Lossless encoding keeps every pixel +exactly; lossy encoding makes smaller files by approximating some image detail. `quality: 100` is lossless for WebP, +AVIF and JPEG XL (JPEG has no lossless mode). Without a `quality`, WebP and JPEG XL are lossless and AVIF is lossy. + +Not supported (decoding them throws an error): CCITT-compressed TIFF and arithmetic-coded JPEG. Lossless JPEG XL is +fast but not small: for small lossless files, PNG or WebP are the better choice. + +Embedded color profiles are converted to sRGB, the standard color format for most screens, where supported. CMYK and +lookup-table profiles are left unchanged. + +Supported image operations preserve gain maps; editing pixels directly with `image.bitmap` or `setPixelAt()` does not. -- [Text rendering](https://imagescript.dev/classes/Image.html#rendertext) with TrueType, OpenType and WOFF fonts: - all scripts, color emoji, variable fonts +- [Text rendering](https://imagescript.dev/classes/Image.html#rendertext) with TrueType, OpenType and WOFF fonts + (not WOFF2; some OpenType outline formats are unsupported): right-to-left text and scripts where letters connect or + combine, plus color emoji and variable TrueType fonts - [SVG rendering](https://imagescript.dev/classes/Image.html#rendersvg), including text (with fonts you pass - or fonts embedded in the SVG) + or fonts embedded in the SVG); no automatic fetching of external images or fonts - [Resizing](https://imagescript.dev/classes/Image.html#resize), [cropping](https://imagescript.dev/classes/Image.html#crop), [rotating](https://imagescript.dev/classes/Image.html#rotate), diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 657088dd..e9cfabf0 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -1,6 +1,6 @@ # Third party notices -ImageScript is licensed under AGPL-3.0-or-later OR MIT (see [LICENSE](LICENSE)). Parts of it are derived from the +ImageScript is licensed under MIT (see [LICENSE](LICENSE)). Parts of it are derived from the following projects, under their own licenses. Each derived file says so in its header. | Project | Used in | License | diff --git a/bench/README.md b/bench/README.md index f1624931..5f874359 100644 --- a/bench/README.md +++ b/bench/README.md @@ -1,9 +1,8 @@ # ImageScript benchmark -How [ImageScript](https://github.com/imagescript/ImageScript) compares to other image libraries for Node.js: speed, file -sizes and what installing each takes. ImageScript is plain JavaScript with no dependencies, so it runs wherever -JavaScript does, like Jimp, image-js and PureJsImage; sharp and @napi-rs/canvas wrap native libraries (libvips, Skia), -Photon is WebAssembly, and so is jsquash (Squoosh's libavif and libjxl, for AVIF and JPEG XL). +This benchmark compares processing speed, output-file size and install size. Lower times and smaller files are better, +but compare lossy files alongside their quality scores. Results depend on the machine, so compare libraries within a +single run. The Method section explains the test inputs and measurements. Time per operation of the libraries that run everywhere, colored by the distance to the fastest @@ -53,7 +52,8 @@ Time per operation (less is faster), measured 2026-11-18 with Node.js v26.13.1 o | render SVG | **119 ms** | – | – | – | – | 32 ms | – | 8.7 ms | | thumbnail, keeping HDR | **154 ms** | – | – | – | – | 125 ms | – | – | -Encoded sizes: +Encoded sizes. For lossy files, the dB score estimates how closely the decoded image matches the source; higher is +closer. | | **ImageScript** | **Jimp** | **image-js** | **PureJsImage** | **Photon** | **sharp** | **jsquash** | **@napi-rs/canvas** | |---|--:|--:|--:|--:|--:|--:|--:|--:| @@ -87,10 +87,11 @@ Encoded sizes: when the benchmark starts, PNG, lossy WebP, AVIF by sharp (libaom) and JPEG XL by jsquash (libjxl), at the qualities below), a 1434×1434 graphic with transparency (PNG), a 445×445 diagram with transparency placed on the photo (PNG), a 300×300 GIF with 101 frames (and made from it, an animated WebP by sharp at quality 80). -- Lossy WebP, AVIF and JPEG XL are encoded at the same nominal quality (80, 60 and 90); as the libraries' - scales differ, the file sizes come with their PSNR (of the color over black, decoded by libwebp, libavif and - libjxl). jsquash's libjxl runs at the effort ImageScript's default matches (cjxl's 5 lossy, 3 lossless; its own - default is 7). PureJsImage's AVIF +- Lossy WebP, AVIF and JPEG XL are encoded at the same nominal quality (80, 60 and 90). Because each library uses a + different quality scale, file sizes are shown with PSNR (peak signal-to-noise ratio), a measure of how closely the + decoded colors match the original; higher is closer. Colors are compared over black after decoding with libwebp, + libavif and libjxl. jsquash's JPEG XL encoder uses effort settings chosen to match ImageScript's defaults. + PureJsImage's AVIF encoder has no quality option, and its JPEG XL decoder doesn't support everything libjxl's files use, which shows as failing. jsquash only encodes and decodes AVIF and JPEG XL (it gets the other inputs as pixels); @napi-rs/canvas decodes both with Skia's codecs, but doesn't encode them. @@ -101,9 +102,10 @@ Encoded sizes: clone first, sharp runs a pipeline from raw pixels back to raw pixels, PureJsImage (which has no decoded images) one from a BMP back to a BMP, @napi-rs/canvas draws into a new canvas. PureJsImage has no blur, composite, rendering or animated GIFs. -- Where the library lets you choose, resizing is bilinear (or bicubic, in its own row), the thumbnail covers 400×400 - (cropping the sides), blurring is gaussian with a radius or sigma of 5, sharpening an unsharp mask of radius or - sigma 1 (Photon: its 3×3 sharpening kernel), rotating by 30° grows the image to fit, brightness and contrast go up +- Where the library lets you choose, resizing is bilinear (smooth) or bicubic (a sharper smoothing filter, in its own + row), the thumbnail covers 400×400 (cropping the sides), blurring is gaussian (softening) with a radius or sigma of + 5, sharpening uses an unsharp mask (edge enhancement) of radius or sigma 1 (Photon: its 3×3 sharpening kernel), + rotating by 30° grows the image to fit, brightness and contrast go up 20% (Jimp's and Photon's scales converted). image-js's and sharp's greyscale make one grey channel (and alpha). Each library uses its own defaults otherwise, e.g. its PNG compression level. - Threads: ImageScript uses worker threads where they pay off (the processors available, at most 8), and sharp gets @@ -111,7 +113,7 @@ Encoded sizes: libraries run on one thread (jsquash turns its threaded builds off in Node). - [tinybench](https://github.com/tinylibs/tinybench), at least 1.5 seconds and 3 runs per measurement, every library in its own process. -- The release workflow runs the benchmark for every release and commits the results, on a GitHub Actions runner; +- The release workflow runs the benchmark for every regular release and commits the results, on a GitHub Actions runner; runners vary, so compare libraries within one run rather than between runs. - Install sizes: `npm install ` in an empty project, the apparent size of `node_modules`. diff --git a/bench/libs.js b/bench/libs.js index 818b037a..b15015f4 100644 --- a/bench/libs.js +++ b/bench/libs.js @@ -64,9 +64,9 @@ const imageScript = IS => ({ jxl: image => image.encodeJXL({ quality: JXL_QUALITY }), jxlLossless: image => image.encodeJXL() }, - resize: image => image.clone().resize(...RESIZE, { mode: IS.ResizeModes.BILINEAR }), - resizeBicubic: image => image.clone().resize(...RESIZE, { mode: IS.ResizeModes.BICUBIC }), - cover: image => image.clone().cover(THUMB, THUMB, { mode: IS.ResizeModes.BILINEAR }), + resize: image => image.clone().resize(...RESIZE, { mode: 'bilinear' }), + resizeBicubic: image => image.clone().resize(...RESIZE, { mode: 'bicubic' }), + cover: image => image.clone().resize({ width: THUMB, height: THUMB, fit: 'cover', mode: 'bilinear' }), rotate: image => image.clone().rotate(ANGLE), rotate90: image => image.clone().rotate(90), flip: image => image.clone().flip('horizontal'), @@ -74,12 +74,12 @@ const imageScript = IS => ({ sharpen: image => image.clone().sharpen({ amount: 1, radius: 1 }), composite: (image, overlay) => image.clone().composite(overlay, { x: AT[0], y: AT[1] }), crop: image => image.clone().crop(...CROP), - greyscale: image => image.clone().greyscale(), + greyscale: image => image.clone().grayscale(), adjust: image => image.clone().brightness(ADJUST).contrast(ADJUST), // an Ultra HDR photo to a thumbnail that stays HDR: decoded, covered and encoded with its gain map - hdrThumbnail: async data => (await IS.Image.decode(data)).cover(THUMB, THUMB, { mode: IS.ResizeModes.BILINEAR }).encodeJPEG({ quality: 80 }), + hdrThumbnail: async data => (await IS.Image.decode(data)).resize({ width: THUMB, height: THUMB, fit: 'cover', mode: 'bilinear' }).encodeJPEG({ quality: 80 }), text: () => IS.Image.renderText(TEXT, { font, size: TEXT_SIZE }), - svg: () => IS.Image.renderSVG(svg, { size: SVG_WIDTH, mode: IS.SVGScaleModes.WIDTH }), + svg: () => IS.Image.renderSVG(svg, { width: SVG_WIDTH }), animation: { decode: data => IS.Animation.decode(data), encode: animation => animation.encodeGIF(), diff --git a/bench/package-lock.json b/bench/package-lock.json index 945b3a05..750b0fcb 100644 --- a/bench/package-lock.json +++ b/bench/package-lock.json @@ -8,14 +8,14 @@ "dependencies": { "@jsquash/avif": "2.1.1", "@jsquash/jxl": "1.3.0", - "@napi-rs/canvas": "1.0.11", + "@napi-rs/canvas": "1.1.0", "@silvia-odwyer/photon-node": "0.3.4", "image-js": "1.7.1", "imagescript": "3.20.4", "jimp": "1.6.1", "purejsimage": "0.17.0", "sharp": "0.35.5", - "tinybench": "6.2.2" + "tinybench": "6.2.3" } }, "node_modules/@borewit/text-codec": { @@ -987,9 +987,9 @@ } }, "node_modules/@napi-rs/canvas": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.0.11.tgz", - "integrity": "sha512-vt5tog1cr+QKadIddGe+3LrcX0EmjEd0izF717Uwf92mBmgYfq2XRmL2r4bZU40spB69exxhrBn9I91HYEr/7w==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.1.0.tgz", + "integrity": "sha512-k+ph/D8H9GS8ZZ48okvHrKeJynkqAA1kMUZRuzRWNlQUDHXngq7oRaWMZBdmSfd9ZhVy9bwNKei/7wMboI/uMg==", "license": "MIT", "workspaces": [ "e2e/*" @@ -1002,23 +1002,23 @@ "url": "https://github.com/sponsors/Brooooooklyn" }, "optionalDependencies": { - "@napi-rs/canvas-android-arm64": "1.0.11", - "@napi-rs/canvas-darwin-arm64": "1.0.11", - "@napi-rs/canvas-darwin-x64": "1.0.11", - "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.11", - "@napi-rs/canvas-linux-arm64-gnu": "1.0.11", - "@napi-rs/canvas-linux-arm64-musl": "1.0.11", - "@napi-rs/canvas-linux-riscv64-gnu": "1.0.11", - "@napi-rs/canvas-linux-x64-gnu": "1.0.11", - "@napi-rs/canvas-linux-x64-musl": "1.0.11", - "@napi-rs/canvas-win32-arm64-msvc": "1.0.11", - "@napi-rs/canvas-win32-x64-msvc": "1.0.11" + "@napi-rs/canvas-android-arm64": "1.1.0", + "@napi-rs/canvas-darwin-arm64": "1.1.0", + "@napi-rs/canvas-darwin-x64": "1.1.0", + "@napi-rs/canvas-linux-arm-gnueabihf": "1.1.0", + "@napi-rs/canvas-linux-arm64-gnu": "1.1.0", + "@napi-rs/canvas-linux-arm64-musl": "1.1.0", + "@napi-rs/canvas-linux-riscv64-gnu": "1.1.0", + "@napi-rs/canvas-linux-x64-gnu": "1.1.0", + "@napi-rs/canvas-linux-x64-musl": "1.1.0", + "@napi-rs/canvas-win32-arm64-msvc": "1.1.0", + "@napi-rs/canvas-win32-x64-msvc": "1.1.0" } }, "node_modules/@napi-rs/canvas-android-arm64": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.0.11.tgz", - "integrity": "sha512-dtJS4FQEfH9OwSYLtMrEnj7T8DzBbJc/97LI/OkiWOYpW/iW5t6R/gcxVrUXS8l45gCVpwMufgucRe/pe0ISqA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.1.0.tgz", + "integrity": "sha512-mKrSmRyhWK4q699Q1xthbZIZi7JBvLtsRNnOZAeFaLPOFT1yo8y82aRC2nNZbXTGJXU7fVDONgGQPr0vo3kerw==", "cpu": [ "arm64" ], @@ -1036,9 +1036,9 @@ } }, "node_modules/@napi-rs/canvas-darwin-arm64": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.0.11.tgz", - "integrity": "sha512-J/JylWoJTG8OQqZaiqly4IODyAxNofUlZo0wtSBJtHk6AdymbdIkPynAM1JvQaZpPaG5h+msk9QuK8y4i1ooqw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.1.0.tgz", + "integrity": "sha512-iqwST4g0oH+x8VCpBIYh+MYokv/mVvkM+v9oJGB0d9A3P2qBh42ogJlVyWq9SpPCrAjS7tplMb1D3OIfxl+utw==", "cpu": [ "arm64" ], @@ -1056,9 +1056,9 @@ } }, "node_modules/@napi-rs/canvas-darwin-x64": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.0.11.tgz", - "integrity": "sha512-nlecCk3xy06eAGC7krZtzNDm9UNTHKuHQYK8ZYegdjzgSL8anGt/eLJZm86OWaNgZkwQwvDqfSmG8Nqe6MPZNQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.1.0.tgz", + "integrity": "sha512-jkeA8eVTxDum03LTvc32YJ28F6KB1U0gYwnWMfOAUQZvWWEh/kvONby4iWGJx3+Tw45UqMGMXjtw2GKNVZDhVg==", "cpu": [ "x64" ], @@ -1076,9 +1076,9 @@ } }, "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.0.11.tgz", - "integrity": "sha512-DKImmG+sTPolE0kGPsYPBxTtOjb3INALp32O2lW2CfSr0bAzSEKKuu+GrQbtilClyoPOahUErS3OrznFDraoWA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.1.0.tgz", + "integrity": "sha512-Y4YkKG1ijoqkgUdTEEBNG4k+2BK5bR5jGL6S56YxCXYPwGfUd5nED8/74xyc7z+bpixPasCjSYoP3xYPOIGNxw==", "cpu": [ "arm" ], @@ -1096,9 +1096,9 @@ } }, "node_modules/@napi-rs/canvas-linux-arm64-gnu": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.0.11.tgz", - "integrity": "sha512-55sykACGENj5j1rhj+81AO8JbR9HYgGjRZ7/H+pNr4VE1DvINKYNMTcutk8ZmWxk276jAQvUKJ3+Kdj9GXU3lQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.1.0.tgz", + "integrity": "sha512-dE/XthqYkiWcBVtKFlZbUXwAYfDuQGqDWixznipJNmevLGpprNnTVQZyftm1RZJudkIOn2EkzYZDMMETM08Row==", "cpu": [ "arm64" ], @@ -1116,9 +1116,9 @@ } }, "node_modules/@napi-rs/canvas-linux-arm64-musl": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.0.11.tgz", - "integrity": "sha512-6Jz6jys17yXydO+WdJgu7JhoB4K7/w9sWHByzzTmLjQghUx3TDMWvLv+UcCdnWhg4oprET67EMymnrETdeGNAg==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.1.0.tgz", + "integrity": "sha512-DqZ/CMcHlhU56pPjv9AP0h3U7MFQ5LzC1HzMyRMotL+PFsJmZJA/ziApPYVyyz78DaVLhI8t3So3ztqtijbYpg==", "cpu": [ "arm64" ], @@ -1136,9 +1136,9 @@ } }, "node_modules/@napi-rs/canvas-linux-riscv64-gnu": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.0.11.tgz", - "integrity": "sha512-lf2XeEebWiUYVOVEjLXxF7dfXrBBSEOBn9AqBh39VYXrPt5cDqI+1t58IFSjn8npqkg5jIOs8TQbjKABbFW1gQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.1.0.tgz", + "integrity": "sha512-kJ7m5n2VffxWXM5QGa5lfq8ZN4LdOJEoz3aAJAmIqYvKiZw1gRdXqpucnRXsF6D9nLYiiIlevaAtAclR7c5ilg==", "cpu": [ "riscv64" ], @@ -1156,9 +1156,9 @@ } }, "node_modules/@napi-rs/canvas-linux-x64-gnu": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.0.11.tgz", - "integrity": "sha512-iDapw7nFSE5tsmQxcH2+KotJhyfVPmHd6vUOQN/Em+8WNbkZJwJ/rDowlJMFnMl0SYSDSfgKCNUGi6Sn5++Smg==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.1.0.tgz", + "integrity": "sha512-uQ9JuJlRhQdHyttcMWOiwLkfIqkqaB0YFUVe835LUe12THt2b51HXkTItq0fxWT1jdhUPX2ylWZ1walkJyD6GQ==", "cpu": [ "x64" ], @@ -1176,9 +1176,9 @@ } }, "node_modules/@napi-rs/canvas-linux-x64-musl": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.0.11.tgz", - "integrity": "sha512-26q26AyITo3CGZX4HWFIMgBMA1lu3YN07gxzBm4tW6Hglq/OVyTP50kDrmWuKybCX6dh3m8Ly+c7YhI+sqCgCQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.1.0.tgz", + "integrity": "sha512-has4CPPAkkCac/LZ13VAw5p+MJLdaKVoyrhumN/A7uJd6960xYkJNDZgUebyxiha82AFzXx6RV+QJg5qGG079g==", "cpu": [ "x64" ], @@ -1196,9 +1196,9 @@ } }, "node_modules/@napi-rs/canvas-win32-arm64-msvc": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.0.11.tgz", - "integrity": "sha512-cUO96IdsfvIj2S+2PNcDSkTcLhjPj8pIOEWRV1Kj70MOP4wnE9zSk7N4C1EKHlFGRcgdR5AkbnBZj0dfHK9nbQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.1.0.tgz", + "integrity": "sha512-MJnktLKNijmXqdjTughHDZ9TDLZ9uUm2hvFXqaOqn0+w7lphXFnft6bpSgQAc9U1exc20UGIBlzGu9+kiCj9Ag==", "cpu": [ "arm64" ], @@ -1216,9 +1216,9 @@ } }, "node_modules/@napi-rs/canvas-win32-x64-msvc": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.0.11.tgz", - "integrity": "sha512-DFYp/ZQRdKunI/LPc0UkRXG1vlNjJKOJf8O8Ctb8+wm2Nt2ELg9Eamc31D2VoakkfGo8L+z0Iejz6WtFbQwyGw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.1.0.tgz", + "integrity": "sha512-08575bFk7iiadxap4h+JxgGut9xDCHAGum6wh0eInN53zEMImkmEHi5MushX2FOmNO7qRNX7BPiDC5ZYBwHeEg==", "cpu": [ "x64" ], @@ -2041,9 +2041,9 @@ } }, "node_modules/tinybench": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", - "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", "license": "MIT", "engines": { "node": ">=20.0.0" diff --git a/bench/package.json b/bench/package.json index 149313d0..cd199bf0 100644 --- a/bench/package.json +++ b/bench/package.json @@ -9,13 +9,13 @@ "dependencies": { "@jsquash/avif": "2.1.1", "@jsquash/jxl": "1.3.0", - "@napi-rs/canvas": "1.0.11", + "@napi-rs/canvas": "1.1.0", "@silvia-odwyer/photon-node": "0.3.4", "image-js": "1.7.1", "imagescript": "3.20.4", "jimp": "1.6.1", "purejsimage": "0.17.0", "sharp": "0.35.5", - "tinybench": "6.2.2" + "tinybench": "6.2.3" } } diff --git a/bench/startup.js b/bench/startup.js index fb4ebe62..1c9beead 100644 --- a/bench/startup.js +++ b/bench/startup.js @@ -14,7 +14,7 @@ const [W, H] = [960, 540]; const LIBRARIES = { ImageScript: { load: () => import(process.env.IMAGESCRIPT === 'local' ? '../dist/index.js' : 'imagescript'), - job: async ({ Image }) => (await Image.decode(photo)).resize(W, H).encodeJPEG(80) + job: async ({ Image }) => (await Image.decode(photo)).resize(W, H).encodeJPEG({ quality: 80 }) }, Jimp: { load: () => import('jimp'), diff --git a/eslint.config.mjs b/eslint.config.mjs index 124d0081..9ae50059 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -22,6 +22,13 @@ export default tseslint.config( // ({ removed: _, ...rest }) leaves out a property '@typescript-eslint/no-unused-vars': ['error', { ignoreRestSiblings: true }], + // option checks live in util/options.ts, so one option is checked (and worded) the same everywhere: use a + // helper there, or add one (a check that only one place needs can say why with an eslint-disable) + 'no-restricted-syntax': ['error', { + selector: "ThrowStatement > NewExpression[callee.name=/^(Range|Type)Error$/] > :matches(TemplateLiteral, Literal)[quasis.0.value.raw=/must be/], ThrowStatement > NewExpression[callee.name=/^(Range|Type)Error$/] > Literal[value=/must be/]", + message: "Check options with the helpers of util/options.ts (oneOf, finite, pixelLimit, ...) instead of a hand-written 'must be' error." + }], + // SonarJS: code that does nothing or something else than it reads like 'sonarjs/array-callback-without-return': 'error', 'sonarjs/no-all-duplicated-branches': 'error', @@ -41,5 +48,16 @@ export default tseslint.config( // regular expressions that backtrack superlinearly (ReDoS) 'sonarjs/slow-regex': 'error' } + }, + { + // the dimension limits of a format aren't options (quantize.ts holds the dithering options, so it stays checked) + files: ['src/codecs/**/*.ts'], + ignores: ['src/codecs/quantize.ts'], + rules: { 'no-restricted-syntax': 'off' } + }, + { + // (where the helpers are) + files: ['src/util/options.ts'], + rules: { 'no-restricted-syntax': 'off' } } ); diff --git a/guides/Migrating to 4.0.md b/guides/Migrating to 4.0.md new file mode 100644 index 00000000..8c80168e --- /dev/null +++ b/guides/Migrating to 4.0.md @@ -0,0 +1,686 @@ +# Migrating to 4.0 + +ImageScript 4.0 removes everything 3.x deprecated, reshapes parts of the API, and changes eighteen behaviors. Most of the +removals are mechanical: the compiler points at them. The eighteen behavior changes are not deprecations, nothing warns +about them, and code keeps compiling while it does something else. Read the first section even if your build is clean. + +Node.js 22.13 or newer is required, as it was for 3.x (`engines` in `package.json`). + +The recommended path: + +1. Upgrade to the latest 3.x release. Everything still works. Editors show the deprecated APIs with a + strikethrough, and the deprecation text names the replacement. `tsc` doesn't fail on them, so use the editor's + problems list, or a lint rule for deprecated APIs (typescript-eslint has `no-deprecated`), to get the full list. +2. Fix every deprecation hint, using the tables below. +3. Switch to 4.0, fix what the compiler reports with the [renamed and reshaped APIs](#renamed-and-reshaped-apis), and go + through the eighteen behavior changes. The [checklist](#checklist) at the end has grep patterns + for finding the code they affect. + +## Behavior changes + +These change what code does without a compile error. + +### `decode()` uses animation markers as well as frame count + +In 3.x, `decode()` returned a `GIF` for every GIF, including a GIF with one frame, an `Animation` for an animated WebP, +and an `Image` for everything else. An APNG or a JPEG XL with several frames decoded to its first frame, as an `Image`. + +In 4.0, a file with several frames or an explicit animation marker decodes to an `Animation`. This includes one-frame +APNGs, animated WebPs, JPEG XL animations and GIFs with a loop extension; their timing and loop metadata are retained. +A file with one frame and no animation marker decodes to an `Image`, including a still image or a one-frame GIF without +a loop extension. + +```ts +// 3.x: a GIF was a GIF, which is an Animation with encode() +const gif = await decode(data); +const out = await gif.encode(90); + +// 4.0: check what you got +import { Animation, decode } from 'imagescript'; + +const decoded = await decode(data); +if (decoded instanceof Animation) { + const out = await decoded.encodeGIF(); +} +``` + +`Image.decode()` still returns only an `Image`: for an animated GIF or WebP it returns the first frame composed onto the +canvas like `Animation.decode()`, and decoding stops after it. Use `Animation.decode()` for all frames and their +metadata. An APNG still gives its default image, as before. + +```ts +const first = await Image.decode(data); // the first frame of an animated GIF or WebP +``` + +Search your code for: `decode(` where the result is used for `encode`, `.length`, indexing or `instanceof GIF`. + +### `Animation` holds its frames instead of extending `Array` + +In 3.x, an `Animation` was an array of its frames, so `animation[0]` and `animation.push()` worked, and `animation.map()` +returned a plain array. In 4.0 the frames are in `animation.frames`, and the animation is not an array. + +```ts +// 3.x +const first = animation[0]; +animation.push(frame); +const copy = animation.slice(0, 10); +const widths = animation.map(f => f.width); + +// 4.0 +const first = animation.frames[0]; +animation.frames = [...animation.frames, frame]; +const copy = new Animation(animation.frames.slice(0, 10), { loopCount: animation.loopCount }); +const widths = animation.frames.map(f => f.width); +``` + +These still work: `for (const frame of animation)`, `[...animation]`, `Array.from(animation)`, `animation.length` and +the methods of `Animation` itself (`resize()`, `encodeGIF()`, `width`, `duration`, ...). `Array.isArray(animation)` is +`false` now. `animation.frames` is a frozen snapshot, so array mutation methods and index assignment don't change it. +The `Frame` objects themselves remain mutable; replace the list by assigning a new array to `animation.frames`. + +`animation.length` is read-only, so `animation.length = 0` throws. Assigning `animation.frames = list` copies `list` +into a new array, so later changes to `list` don't reach the animation. + +Search your code for: `Array.isArray`, `.slice(`, `.map(`, `.filter(`, `.forEach(`, `.reduce(`, `.push(`, `.splice(`, `.length =` +and `[0]` on variables that hold an animation. + +### `JSON.stringify()` and `console.log()` show the size + +`JSON.stringify(image)` gives `{"width":64,"height":48}` (a `Frame` adds its duration, an `Animation` its duration and +frame count) and `console.log(image)` prints `Image<64x48>`, where 3.x serialized the internal fields, every pixel +included. Use `image.bitmap` for the pixels. + +### Loop counts + +In 3.x, `-1` meant "forever", and decoded animations reported `-1`. In 4.0, `Infinity` is forever, it is the default, +and decoded animations report `Infinity` (a GIF without a loop extension, which plays once, reports `0`). + +```ts +// 3.x +new Animation(frames, { loopCount: -1 }); // forever +animation.loopCount === -1; // true for a decoded animation that loops + +// 4.0 +new Animation(frames); // forever, the default +new Animation(frames, { loopCount: Infinity }); +animation.loopCount === Infinity; +``` + +The finite counts are the same: `0` plays once, `2` plays three times. The valid values are `Infinity` and integers +from 0 ([`AnimationOptions.loopCount`](https://imagescript.dev/interfaces/AnimationOptions.html#loopcount)). `-1` throws a `RangeError`, like other negative numbers, `NaN` and +fractions. Numeric strings, `null` and booleans throw a `TypeError`. The check applies to the constructor, to the setter `animation.loopCount = ...` (which keeps the +old count when it throws), and to the encoders `Animation.gifEncoder()`, `webpEncoder()` and `apngEncoder()`. + +The formats store a finite count in fixed-size fields: a GIF up to `65535`, a WebP up to `65534` and an APNG up to +`2147483646` (2^31 - 2). A larger count throws a `RangeError` before anything is encoded, from `encodeGIF()`, +`encodeWebP()`, `encodeAPNG()` and the streaming encoders. This limit is enforced since 3.x release 3.20.2; earlier releases silently wrapped a GIF count of `65536` to `0`, which means forever. `Infinity` is always +fine. + +Search your code for: `loopCount: -1`, `loopCount = -1`, `loopCount === -1` and `loopCount < 0`. + +### Resize fit modes + +`resize({ width, height, fit })` handles stretching, aspect-ratio fitting and cropping. It works on images, frames and +animations; frame offsets and animation canvases follow the resized pixels. + +| `fit` | Result | +| --- | --- | +| `'fill'` (default) | Stretches to the exact dimensions | +| `'inside'` | Keeps the aspect ratio and fits inside the box without padding | +| `'contain'` | Keeps the aspect ratio and pads to the exact box; `background` sets the bar color | +| `'cover'` | Keeps the aspect ratio and crops to the exact box | + +`contain` and `cover` require both dimensions. `background` is only valid with `fit: 'contain'`. `ResizeFit` is the +type of the `fit` option. + +| 3.x | 4.0 | +| --- | --- | +| `image.contain(800, 600)` (at most 800x600, no bars) | `image.resize({ width: 800, height: 600, fit: 'inside' })` | +| `image.fit(800, 600)` (exactly 800x600, transparent bars) | `image.resize({ width: 800, height: 600, fit: 'contain' })` | +| `image.cover(800, 600)` | `image.resize({ width: 800, height: 600, fit: 'cover' })` | + +### Hues are in degrees + +`Colors.fromHSL()`, `Colors.fromHSLA()` and `Colors.toHSLA()` take and return the hue in degrees (0-360, like CSS' +`hsl()` and like `hueShift()`), no longer as a fraction (0-1). Saturation, lightness and alpha stay 0-1. An old hue +still works without an error, but gives a different color: `Colors.fromHSL(0.5, 1, 0.5)` was cyan and is now red. + +| 3.x | 4.0 | +| --- | --- | +| `Colors.fromHSL(h, s, l)` with `h` in 0-1 | `Colors.fromHSL(h * 360, s, l)` | +| `Colors.toHSLA(color)[0]` in 0-1 | `Colors.toHSLA(color)[0] / 360` for the old value | + +### `rotate()` turns clockwise + +`image.rotate(angle)` turns the image clockwise, like CSS' `rotate()`. In 3.x it turned counterclockwise. Negate the +angle to keep the old result: + +| 3.x | 4.0 | +| --- | --- | +| `image.rotate(90)` | `image.rotate(-90)` (or `image.rotate(270)`) | +| `image.rotate(45, false)` | `image.rotate(-45, { expand: false })` | +| `image.rotate(90, false)` (swapped width and height anyway) | `image.rotate(-90)`: with `expand: false` quarter turns keep the size now, like every other angle, and cut off what doesn't fit | + +Search your code for: `.rotate(`. + +### JPEG composites transparent pixels onto black + +JPEG does not store transparency (also called an alpha channel). In 3.x, `encodeJPEG()` dropped the alpha and kept the +color, so a fully transparent pixel showed its stored red, green and blue values (often black, but not always). In +4.0, an image with transparent or translucent pixels is combined with a background first, black by default, the way +a viewer would show it on black. Pass `background` for another color: `image.encodeJPEG({ background: 0xffffffff })`. +Opaque images encode as before, byte for byte. +The new `subsampling` option controls how much color detail to keep: `'4:4:4'` keeps it all; `'4:2:0'` stores less +color detail to make a smaller file. Its default remains 4:2:0 up to quality 90 and 4:4:4 above. + +Search your code for: `encodeJPEG(` on images that can have transparency. + +### `quantize()` dithers by default + +`image.quantize()` reduces an image to a limited color palette. It now uses dithering by default: a pattern of small +color changes that helps smooth the result when colors are reduced. The default method is Floyd-Steinberg, with a +strength of `0.85`, like the GIF encoders. In 3.x it didn't dither unless you passed `dither`. For the old result, +pass `dither: 'none'`: + +| 3.x | 4.0 | +| --- | --- | +| `image.quantize({ colors: 16 })` | `image.quantize({ colors: 16, dither: 'none' })` | +| `image.quantize({ colors: 16, dither: 'floyd-steinberg' })` (strength 1) | `image.quantize({ colors: 16, dither: 'floyd-steinberg', ditherStrength: 1 })` | + +The second row matters for every dither method: the default strength is `0.85` now, so pass `ditherStrength: 1` to +keep 3.x's result. + +Search your code for: `.quantize(`. + +### Frames move their offsets when their size changes + +A frame's `crop()`, `resize({ fit: 'cover' })` and `rotate()` now move its offsets, so the frame's pixels stay where +they are in the animation. In 3.x, `crop()` and `rotate()` kept the offsets (the top left corner stayed in place), and +`cover()` only scaled them. Now: + +- `frame.crop(x, y, w, h)` adds `x` and `y` to the offsets, like `trim()` already did. +- `frame.rotate(angle)` keeps the frame's middle in place. +- `frame.resize({ width: w, height: h, fit: 'cover' })` scales the offsets and then moves them by the cropped amount. + +`transform()`, `dropShadow()` and `outline()` moved the offsets in 3.x too, but only as far as they allowed: a frame at +`xOffset: 0` couldn't grow to the left, so a shadow or outline was cut off on that side and a transform grew to the +right instead. Now the frame grows the same way an image does and the offsets can become negative; the part outside the +animation's canvas isn't encoded. + +To keep a frame's offsets as they are, call the method on its image: `frame.image.crop(x, y, w, h)`. See +[frames hold an image](#frames-hold-an-image) for the other frame changes. + +Search your code for: `.crop(`, `.resize(` with `fit: 'cover'`, and `.rotate(` on frames. + +### Values that were wrapped, clamped or ignored now throw + +Several values that 3.x quietly changed into something else now throw, naming the value: + +| Value | 3.x | 4.0 | +| --- | --- | --- | +| Colors (`setPixelAt()`, `fill()`, options like `background`, `Colors.toRGBA()`, ...) | any number, wrapped to 32 bits (`2 ** 32 + 5` was `0x00000005`, `1.5` was `1`) | an integer from `-2 ** 31` to `2 ** 32 - 1`, else a `RangeError`. Negative colors keep working: they're what bitwise operators return (`r << 24 \| g << 16 \| b << 8 \| a`) and read as the same unsigned color | +| Colors returned by a `fill()` function | anything, `undefined` was transparent black | checked like any color | +| Pixel coordinates (`getPixelAt()`, `setPixelAt()`, `crop()`, `extract()`, `composite()`'s `x` and `y`) | truncated to 32 bits, so `2 ** 32` was `0` | truncated (fractions dropped) without wrapping: a pixel or region entirely outside of the image throws as before, a region partly outside is clipped as before | +| `Image.rgbaToColor()`, `rgbToColor()` and `hslaToColor()`, now `Colors.fromRGBA()`, `fromRGB()` and `fromHSLA()`, with a component outside of its range (`256`, `-1`; saturation, lightness or alpha outside of 0-1) | clamped (`256` was `255`, `-1` was `0`) | a `RangeError` naming the component. Fractions are still rounded. Code that relied on clamping clamps itself: `Colors.fromRGBA(Math.min(r, 255), ...)` | +| `compression` of `encodePNG()`, `encodeAPNG()` and `apngEncoder()` | clamped to 0-9 and truncated | an integer from 0 to 9, like `effort`, else a `RangeError` | +| Frame durations over what the format stores (GIF and APNG 655350 ms, WebP 16777215 ms) | cut to the format's limit | a `RangeError`, like loop counts that don't fit. Unchanged frames that are merged are split at the limit instead | +| `frame.xOffset`, `frame.yOffset` (and encoder `add()` offsets) | stored as given, fractions included (`0.4`) | truncated to integers when set, like image sizes, so the offset you read is the one that is encoded | +| `image.bitmap = view` with a view that doesn't start at a multiple of 4 bytes | copied, so changes to the view no longer reached the image | a `TypeError`: pass an aligned view, or `view.slice()` for a copy | +| A number given as a string (`'0.5'`), `null` or a boolean where a number goes (`opacity('0.5')`, `quality: '50'`, `frame.duration = '40'`, `maxPixels: '100'`, `Colors.gradient()`'s positions) | converted by some methods (`'0.5'` was `0.5`, `null` was `0`), rejected by others | a `TypeError` naming the value, by all of them | +| A string where a boolean goes (`optimize: 'yes'`, `applyOrientation: 'no'`, `sharpYuv`, `hinting`, ...) | read as `true` (also `'no'` and `'false'`) | a `TypeError`: `true` or `false` only | +| `roundCorners({ radius })` below 0 | clamped to 0 | a `RangeError` | +| `fisheye({ strength })` of 0 or less | an empty image | a `RangeError` | +| `Colors.gradient()` at a `NaN` position | transparent black with two stops, a `RangeError` with more | a `RangeError` with any number of stops | +| `encodeGIF()` of an animation without frames | a GIF that doesn't decode | an `Error`, like `encodeAPNG()` and `encodeWebP()` | +| `quality` of `encodeJPEG()` | clamped to 1-100 | a number from 0 to 100 (0 is 1), else a `RangeError`, like the other lossy formats | +| JPEG and lossy WebP data that is cut off (a scan that ends before its last block, a WebP chunk shorter than its size) | decoded without an error, as a gray or smeared image | an `Error`, like the other formats. A JPEG that only lacks its end marker still decodes | +| The source of `composite()` when it isn't an `Image` | a `TypeError` from inside (`Cannot read properties of undefined`) or nothing | a `TypeError` naming the call | + +A value outside a fixed set of choices is a `TypeError` naming them all, like `resize mode must be 'nearest-neighbor', +'bilinear', 'bicubic' or 'area', not 'lanczos'`. This changes the error type of the resize `mode` (an `Error`, and only +thrown once resizing started), `composite()`'s `mode`, `flip()` and `disposalMode` (`RangeError`s), and `wrapStyle` +(a `RangeError`; `''` and `null` were the default, now they throw). + +Search your code for: `compression:`, `xOffset`, `yOffset`, `.bitmap =`, `duration:` above 655 seconds, and catch +blocks that check for `RangeError` around `resize()`, `composite()`, `flip()` and `disposalMode`. + +### Gradients blend transparency premultiplied + +`Colors.gradient()`, and so `Image.linearGradient()` and `radialGradient()`, blend colors with an alpha below 255 +premultiplied, like CSS does. 3.x blended the channels as they are, so a gradient from transparent black to red went +through a dark red (`7f00007f`) and one from red to transparent blue through purple; now the middle of the first is +`ff00007f` and what fades out leaves no color behind. Gradients between opaque colors are unchanged. + +### Images use a copy of the gain map they are given + +`image.gainMap = map` stores a copy. 3.x kept the object, so two images given one map changed it for both when either +was resized or cropped. Now every image has its own, and changes to `map` after assigning it don't reach the image. +`image.gainMap` returns the image's own map, which the image's methods keep up to date. + +### `dominantColor()` counts colors in a histogram, thresholds are channel values + +3.x grouped the colors into 8 clusters (median cut) and returned the average of the largest one, which can lie between +two hues when a cluster spans both. 4.0 counts the colors in 16 levels per channel (4096 bins, like sharp's `dominant`) +and returns the average of the pixels in the fullest bin: a color the image has. The result can differ from 3.x's for +images with many similar colors, and is the same for flat colors. + +The `threshold` is in channel values (0-256): colors whose channels are all below it count as black, all above 255 +minus it as white. In 3.x it counted in steps of 4 (0-64), so the default `15` meant 60. The default is the same; a +threshold you give has to be multiplied by 4: + +| 3.x | 4.0 | +| --- | --- | +| `image.dominantColor(true, true, 15)`, `dominantColor({ threshold: 15 })` | `image.dominantColor({ threshold: 60 })` | + +Search your code for: `dominantColor(`, and compare the colors it returns. + +### `renderText()` takes the image's size + +`maxWidth` and `maxHeight` are `width` and `height`, and they are the size of the image: the lines wrap to the width +(inside the outline of `strokeWidth`), the lines that don't fit the height are left out, and `horizontalAlign` and +`verticalAlign` place the text in that box. In 3.x the image was only as wide as the widest line and as high as the +lines, so the alignment only moved lines against each other. Without a `width` or `height` the image is as large as +the text, as before. `horizontalAlign` defaults to the start of each paragraph's direction: left for left-to-right text +and right for right-to-left text (Arabic, Hebrew, ...), where 3.x aligned everything to the left; pass +`horizontalAlign: 'left'` for the old placement. `wrapHardBreaks` is removed: + +| 3.x | 4.0 | +| --- | --- | +| `{ font, size, maxWidth: 300 }` (wrapped, as wide as the widest line) | `{ font, size, width: 300 }` (wrapped, 300 pixels wide); `trim()` the image for the old size | +| `{ font, size, maxHeight: 100, verticalAlign: 'bottom' }` | `{ font, size, height: 100, verticalAlign: 'bottom' }`: the last lines that fit, at the bottom of a 100 pixel high image | +| `{ font, size, maxWidth: 0 }` (no limit) | `{ font, size }`: `0` throws | +| `{ font, size, wrapHardBreaks: false }` | `Image.renderText(text.replace(/\r?\n/g, ''), { font, size })` | + +An old `maxWidth` or `maxHeight` is ignored, so the text isn't wrapped or cut off. Search your code for: `maxWidth`, +`maxHeight` and `wrapHardBreaks`. + +### Encoded files have no creation time and no version by default + +In 3.x, every encoder wrote the time of encoding as the creation time and `ImageScript vX.Y.Z` as the software, so the +same image never encoded to the same bytes twice, and every file told which release made it. In 4.0, the creation time +is only written when `metadata.creationTime` is given, and the default software is `'ImageScript'`, without a version +(`software: null` leaves it out): + +| 3.x | 4.0 | +| --- | --- | +| `image.encodePNG()` (with the time of encoding) | `image.encodePNG({ metadata: { creationTime: Date.now() } })` | + +Search your code for: code that reads `Creation Time`, Exif `DateTime` or the software version from encoded files. + +### WebP at quality 100 is lossless + +`encodeWebP({ quality: 100 })` and `animation.encodeWebP({ quality: 100 })` wrote a lossy file in 3.x, whose pixels +differ slightly from the image's. In 4.0, quality 100 is lossless, like it is for AVIF and JPEG XL: the file keeps every +pixel and is larger, and `effort` means what it does for lossless WebP. The highest lossy quality is 99. + +| 3.x | 4.0 | +| --- | --- | +| `image.encodeWebP({ quality: 100 })` (lossy) | `image.encodeWebP({ quality: 99 })` | + +Search your code for: `encodeWebP(` with a `quality` of 100. + +### SVG and text rendering limits, and images that can't be drawn + +`Image.renderSVG()` used to draw nothing for an `` it couldn't use. In 4.0, drawing one throws, so a rendered SVG +is the image it describes or nothing: + +- an `href` that isn't a data URI or a key of the `images` option (such as `href="logo.png"` or an `https:` URL, which + are never fetched): pass the image's bytes with `images: { 'logo.png': bytes }` +- an image that can't be decoded (the error says which, with the decoding error as its `cause`), a data URI of a type + that isn't supported, or an embedded SVG that can't be read +- images beyond the new `maxImagePixels` option: the pixels of all the raster images the SVG references, decoded + together (default: `maxPixels`; `Image` values in `images` don't count). In 3.x, each image was checked on its own, + so many images could take many times `maxPixels` + +Images that aren't drawn (in ``, `display="none"`, `visibility="hidden"`) don't throw. + +A font in the `font` option that can't be read throws too, like in `renderText()`; 3.x left it out. Damaged fonts that +the SVG embeds with `@font-face` are still left out, as in browsers. + +The new `maxLayerPixels` option limits the layers rendering uses at once, the output included: each group with opacity, +a mask, a filter or a blend mode is drawn in a layer of its own (16 bytes per pixel), so nested ones multiply the memory +of a small SVG. The default is `4 * maxPixels`; an SVG over it throws a `RangeError`. For untrusted SVGs, lower +`maxPixels` (it bounds the output, the layers and the images): the worst case is about 90 bytes per pixel of +`maxPixels` (64 for the layers, up to 20 for the images, 4 for the output), so `maxPixels: 4096 ** 2` keeps rendering +around 1.5 GB. + +Its fixed limits of work (elements drawn through `` references and markers, masks, clip paths, patterns and +filter images nested inside each other, entity expansion, filters) throw a `LimitError` too, where 3.x threw an +`Error`; code that tests for `Error` still catches them. + +`Image.renderText()` takes `maxPixels` too (default `16383 ** 2`), which counts the outline (`strokeWidth`), checked +before anything is allocated. + +Search your code for: `renderSVG(` with SVGs that reference files or URLs, or that may contain broken images, and with +fonts in its `font` option that may not load. + +## Removed APIs + +Each table maps a 3.x API to its 4.0 replacement. The deprecation hint in 3.x names a replacement too, but some of those +replacements were reshaped in 4.0 as well (for example `ResizeModes`, which became plain strings); the tables give the +4.0 form. The replacements are documented on their own pages: [`ResizeMode`](https://imagescript.dev/types/ResizeMode.html), [`FrameDisposalMode`](https://imagescript.dev/types/FrameDisposalMode.html), +[`Colors`](https://imagescript.dev/classes/Colors.html), [`Frame`](https://imagescript.dev/classes/Frame.html), [`Animation`](https://imagescript.dev/classes/Animation.html), [`AnimationEncoder`](https://imagescript.dev/classes/AnimationEncoder.html) and [`Metadata`](https://imagescript.dev/interfaces/Metadata.html). + +### Constants and modes + +| 3.x | 4.0 | +| --- | --- | +| `Image.RESIZE_NEAREST_NEIGHBOR`, `ResizeModes.NEAREST_NEIGHBOR` | `'nearest-neighbor'` | +| `Image.RESIZE_BILINEAR`, `ResizeModes.BILINEAR` | `'bilinear'` | +| `Image.RESIZE_BICUBIC`, `ResizeModes.BICUBIC` | `'bicubic'` | +| `Image.RESIZE_AREA`, `ResizeModes.AREA` | `'area'` | +| `Image.RESIZE_AUTO`, `ResizeModes.AUTO` | Pass only the width or the height: `image.resize({ width: 256 })` | +| The upper-case mode strings, `'RESIZE_BILINEAR'` and the others | The lower-case names, `'bilinear'` and the others | +| The `ResizeMode` type, with the upper-case strings or the numbers 1-3 | Narrowed to the lower-case names: `'nearest-neighbor'`, `'bilinear'`, `'bicubic'` or `'area'` | +| The `SVGScaleMode` type | Removed with the SVG modes, see [renamed APIs](#renamed-and-reshaped-apis) | +| `Image.SVG_MODE_SCALE` (or `1`) | `Image.renderSVG(svg, { scale: 2 })`, see [renamed APIs](#renamed-and-reshaped-apis) | +| `Image.SVG_MODE_WIDTH` (or `2`) | `Image.renderSVG(svg, { width: 512 })`, see [renamed APIs](#renamed-and-reshaped-apis) | +| `Image.SVG_MODE_HEIGHT` (or `3`) | `Image.renderSVG(svg, { height: 512 })`, see [renamed APIs](#renamed-and-reshaped-apis) | +| `Frame.DISPOSAL_ANY`, `Frame.DISPOSAL_KEEP`, `Frame.DISPOSAL_PREVIOUS`, `Frame.DISPOSAL_BACKGROUND`, and the same on `FrameDisposalModes` | `'any'`, `'keep'`, `'previous'`, `'background'` | +| Numeric disposal ids: `frame.disposalMode = 3`, `disposalMode: 3` in the frame options | The names: `frame.disposalMode = 'background'`, `disposalMode: 'background'`. `FrameDisposalModeId` is removed | + +The modes are plain strings in 4.0: the `ResizeModes` and `FrameDisposalModes` classes are removed, and the types +[`ResizeMode`](https://imagescript.dev/types/ResizeMode.html) and [`FrameDisposalMode`](https://imagescript.dev/types/FrameDisposalMode.html) list the names. The old string and number values are not accepted +any more, so `image.resize(256, 256, { mode: 'RESIZE_BICUBIC' })` throws. + +### Colors, pixels and encoding on `Image` + +| 3.x | 4.0 | +| --- | --- | +| `image.encode(options)` | `image.encodePNG(options)`. The positional forms are in the positional table below | +| `Image.rgbaToColor(r, g, b, a)` | `Colors.fromRGBA(r, g, b, a)` | +| `Image.rgbToColor(r, g, b)` | `Colors.fromRGB(r, g, b)` | +| `Image.hslaToColor(h, s, l, a)` | `Colors.fromHSLA(h, s, l, a)` | +| `Image.hslToColor(h, s, l)` | `Colors.fromHSL(h, s, l)` | +| `Image.rgbaToHSLA(r, g, b, a)` | `Colors.toHSLA(color)` | +| `Image.colorToRGBA(color)` | `Colors.toRGBA(color)` | +| `Image.colorToRGB(color)` | `Colors.toRGB(color)` | +| `Image.gradient(colors)` | `Colors.gradient(colors)` | +| `for (const [x, y] of image)`, `image.coordinates()` | `for (const [x, y] of image.pixels())`: `pixels()` yields `[x, y, color]` | +| `image.iterateWithColors()` | `image.pixels()`, which yields `[x, y, color]` | + +The moved color helpers keep their argument shapes and results, except for the hue-unit change described above. +`Colors.gradient()` also accepts an array of evenly spaced colors, in addition to the prior positions-to-colors object. +`Colors` is exported from the package. + +### Channel methods and `absolute` + +`opacity()`, `red()`, `green()`, `blue()`, `lightness()` and `saturation()` only scale now. The `absolute` argument is +removed, and so is the `AdjustOptions` type. + +| 3.x | 4.0 | +| --- | --- | +| `image.opacity(0.5)`, `image.red(0.5)` (scale) | Unchanged | +| `image.red(0.5, true)`, `image.opacity(0.5, true)`, `image.lightness(0.5, true)` | See below | +| `AdjustOptions` (type) | Removed with `absolute`: the channel methods take the factor only | +| `image.red(0.5, { absolute: true })` | See below | + +`tsc` reports a leftover call as `Expected 1 arguments, but got 2`. In JavaScript the extra argument is ignored, so +`image.red(0.5, true)` scales the channel instead of setting it (a pixel with red 0 stays 0, where 3.x's `absolute` set +it to 128): fix these while the 3.x deprecation hints still point at them. + +For a fixed color, use `image.recolor(color)`. It sets the RGB of every pixel and keeps each pixel's alpha. The 3.x +`absolute` calls set one channel of every pixel to a value, and `recolor()` has no equivalent for a single channel. Set +the bytes yourself when you need it, on an image without a gain map: + +```ts +// 3.x: every pixel's red channel to 128 +image.red(0.5, true); + +// 4.0 +for (let i = 0; i < image.bitmap.length; i += 4) image.bitmap[i] = 0.5 * 255; +``` + +`bitmap` stores four bytes per pixel: red, green, blue and transparency (alpha). Writing it directly skips the gain map +of a high-dynamic-range (HDR) image, so do not use it on images that have one. `absolute` on `lightness()` and +`saturation()` sets the value of every pixel and keeps its hue. +Do it per pixel: read the color with `Colors.toHSLA()`, set the lightness or saturation, and write the pixel back with +`Colors.fromHSLA()`. + +### Animations and GIF + +| 3.x | 4.0 | +| --- | --- | +| `new GIF(frames, loopCount)` | `new Animation(frames, { loopCount })` | +| `GIF.decode(data)` | `Animation.decode(data)`, which decodes APNGs and WebPs too | +| `gif.encode(quality)` | `animation.encodeGIF({ colors })`, see the [GIF options](#renamed-and-reshaped-apis) | +| `GIF` (the class, also in `instanceof`) | `Animation`. `GIF` is no longer exported | +| `animation.slice(start, end)` | `new Animation(animation.frames.slice(start, end), { loopCount: animation.loopCount })` | +| `animation[i]` and the array methods | `animation.frames[i]` and non-mutating array methods; assign a new array to change the frame list | +| `AnimationEncoder.frames` | `AnimationEncoder.frameCount` | +| `toString()` of a GIF, `GIF<64x64x1000ms>` | `Animation<64x64x1000ms>` | + +The option types of the streaming animation encoders are renamed, and each one takes `loopCount` through +`AnimationOptions` (`encodeGIF()`, `encodeAPNG()` and `encodeWebP()` use the animation's own `loopCount`): + +| 3.x | 4.0 | +| --- | --- | +| `AnimationEncoderOptions` | `AnimationEncodeOptions & AnimationOptions` | +| `WebPAnimationEncoderOptions` | `WebPAnimationEncodeOptions & AnimationOptions` | +| `GIFAnimationEncoderOptions` | `GIFAnimationEncodeOptions & AnimationOptions` | +| `APNGAnimationEncoderOptions` | `APNGEncodeOptions & AnimationOptions` | + +Each of them extends the options of the format's still images: `GIFAnimationEncodeOptions` extends +`GIFEncodeOptions`, `APNGEncodeOptions` extends `PNGEncodeOptions` and `WebPAnimationEncodeOptions` extends +`WebPEncodeOptions` (without `threads`: the frames are encoded one at a time). + +### Text, crop and metadata + +| 3.x | 4.0 | +| --- | --- | +| `Image.renderText(font, size, text)` | `Image.renderText(text, { font, size })` | +| `Image.renderText(font, size, text, color, layout, style)` | `Image.renderText(text, { font, size, color, ...layout, ...style })` | +| `Image.renderText(font, size, text, options)` | `Image.renderText(text, { font, size, ...options })` | +| `TextOptions` (type) | `RenderTextOptions` | +| `verticalAlign: 'right'`, `horizontalAlign: 'bottom'` (the other axis' values) | `horizontalAlign` takes `'left'`, `'center'` or `'right'`, `verticalAlign` takes `'top'`, `'middle'` or `'bottom'`. Other values throw a `TypeError` | +| `image.cropCircle(true)` | `image.cropCircle({ fit: 'cover' })` | +| `image.cropCircle(true, feathering)` | `image.cropCircle({ fit: 'cover', feathering })` | +| `image.cropCircle(false)` | `image.cropCircle()`, the default `fit: 'contain'` | +| `image.cropCircle({ max: true })` | `image.cropCircle({ fit: 'cover' })` | +| `image.cropCircle({ size: 'cover' })` (what 3.x's deprecation hint suggests) | `image.cropCircle({ fit: 'cover' })` | +| `PNGMetadata` (type) | `Metadata`, which the encoders that write metadata take | + +`renderText()` takes the text first. The font, the size, the color, the layout options ([`TextLayoutOptions`](https://imagescript.dev/interfaces/TextLayoutOptions.html)) and +the style are all in the one options object, documented in [`RenderTextOptions`](https://imagescript.dev/interfaces/RenderTextOptions.html). Crop options are in +[`CropCircleOptions`](https://imagescript.dev/interfaces/CropCircleOptions.html). A key that is not an option is ignored without an error, so +`cropCircle({ max: true })` and `cropCircle({ size: 'cover' })`, the form 3.x's deprecation hint suggests, quietly become +the default `contain`: change them to `fit: 'cover'`. + +### Positional arguments + +Methods that took options as their last positional arguments take the options object now. The values go into the +object under the names of their options. The options of each method are on its own page, for example +[`ResizeOptions`](https://imagescript.dev/interfaces/ResizeOptions.html), [`CompositeOptions`](https://imagescript.dev/interfaces/CompositeOptions.html), [`RotateOptions`](https://imagescript.dev/interfaces/RotateOptions.html), [`SharpenOptions`](https://imagescript.dev/interfaces/SharpenOptions.html), +[`DominantColorOptions`](https://imagescript.dev/interfaces/DominantColorOptions.html), [`RoundCornersOptions`](https://imagescript.dev/interfaces/RoundCornersOptions.html), [`FisheyeOptions`](https://imagescript.dev/interfaces/FisheyeOptions.html), [`TrimOptions`](https://imagescript.dev/interfaces/TrimOptions.html), +[`ColorToAlphaOptions`](https://imagescript.dev/interfaces/ColorToAlphaOptions.html), [`PNGEncodeOptions`](https://imagescript.dev/interfaces/PNGEncodeOptions.html), [`JPEGEncodeOptions`](https://imagescript.dev/interfaces/JPEGEncodeOptions.html), [`RenderSVGOptions`](https://imagescript.dev/types/RenderSVGOptions.html) and +[`FrameOptions`](https://imagescript.dev/interfaces/FrameOptions.html). The animation options are [`GIFAnimationEncodeOptions`](https://imagescript.dev/interfaces/GIFAnimationEncodeOptions.html), [`APNGEncodeOptions`](https://imagescript.dev/interfaces/APNGEncodeOptions.html), +[`DecodeOptions`](https://imagescript.dev/interfaces/DecodeOptions.html) and [`GainMapEncodeOptions`](https://imagescript.dev/interfaces/GainMapEncodeOptions.html) for `GainMap.encodeJPEG()`. + +| 3.x | 4.0 | +| --- | --- | +| `image.resize(256, 256, 'bicubic')`, `image.resize(256, 256, ResizeModes.AREA)` | `image.resize(256, 256, { mode: 'bicubic' })` | +| `image.scale(0.5, 'area')`, `image.scale(0.5, ResizeModes.AREA)` | `image.scale(0.5, { mode: 'area' })` | +| `image.resize(100)` (width only, the height left out) | `image.resize({ width: 100 })`, which keeps the aspect ratio. The positional form throws a `TypeError` without a height | +| `image.contain(w, h, mode)`, `image.fit(w, h, mode)`, `image.cover(w, h, mode)` | `image.resize({ width: w, height: h, fit: 'inside', mode })`, with `'contain'` or `'cover'` as needed; see [Resize fit modes](#resize-fit-modes) | +| `Frame` and `Animation`: `resize(w, h, mode)` | `resize(w, h, { mode })` | +| `image.composite(logo, 10, 20, { opacity: 0.5 })` | `image.composite(logo, { x: 10, y: 20, opacity: 0.5 })` | +| `image.rotate(45, false)` | `image.rotate(-45, { expand: false })`: the angle is negated because [`rotate()` turns clockwise](#rotate-turns-clockwise) now | +| `image.sharpen(2, 3)` | `image.sharpen({ amount: 2, radius: 3 })` | +| `image.dominantColor(true, true, 15)` | `image.dominantColor({ ignoreBlack: true, ignoreWhite: true, threshold: 60 })`: the threshold is in channel values now, see [below](#dominantcolor-counts-colors-in-a-histogram-thresholds-are-channel-values) | +| `image.roundCorners(8)` | `image.roundCorners({ radius: 8 })` | +| `image.fisheye(3)` | `image.fisheye({ strength: 3 })` | +| `image.trim(color, options)`, `frame.trim(color, options)` | `image.trim({ color, ...options })`, `frame.trim({ color, ...options })` | +| `image.colorToAlpha(color, options)` | `image.colorToAlpha({ color, ...options })` | +| `image.encodePNG(1, { author })` | `image.encodePNG({ compression: 1, metadata: { author } })` | +| `image.encodePNG({ author })` (metadata alone) | `image.encodePNG({ metadata: { author } })`. The old form is ignored, see below | +| `image.encodeJPEG(90)` | `image.encodeJPEG({ quality: 90 })` | +| `animation.encodeGIF(90)` | `animation.encodeGIF()`; a quality of 90 and above was the default 256 colors, see the [GIF options](#renamed-and-reshaped-apis) for lower ones | +| `animation.encodeAPNG(9)` | `animation.encodeAPNG({ compression: 9 })` | +| `gainMap.encode(90)`, `gainMap.encode({ quality: 90 })` | `gainMap.encodeJPEG({ quality: 90 })`: renamed for the format it writes, like `Image.encode()` became `encodePNG()` | +| `Image.renderSVG(svg, 512, 'width')` | `Image.renderSVG(svg, { width: 512 })` (and `{ height }`, `{ scale }`) | +| `new Frame(w, h, duration, x, y, disposal)` | `new Frame(new Image(w, h), { duration, xOffset, yOffset, disposalMode })`, see [frames](#frames-hold-an-image) | +| `Frame.from(image, duration, x, y, disposal)` | `new Frame(image.clone(), { duration, xOffset, yOffset, disposalMode })` | +| `new Animation(frames, loopCount)` | `new Animation(frames, { loopCount })` | +| `Animation.decode(data, true)` | `Image.decode(data)` for the first frame, `Animation.decode(data)` for all | +| `decode(data, true)` | `Image.decode(data)` | +| `decode(data, { onlyFirstFrame: true })` | `Image.decode(data)` | + +`decode()` and `Animation.decode()` take options only: a boolean throws a `TypeError` that names the options form. +`onlyFirstFrame` is not an option anymore, and options that don't exist are ignored without an error: `decode(data, { onlyFirstFrame: true })` +quietly returns an `Animation` for a file with several frames, so search for `onlyFirstFrame` too. + +In 3.x, `image.encodePNG({ author })` was read as metadata. In 4.0 the metadata goes in `metadata`, and an `author` key +at the top level is ignored like any other unknown key: TypeScript reports it for an inline object, JavaScript doesn't. + +## Renamed and reshaped APIs + +These changed in 4.0 without a deprecation in 3.x. Most are compile errors in TypeScript; in JavaScript, and for +options objects that aren't written inline, an old option key is ignored without an error (`rotate(45, { resize: +false })` grows the image again), so search for them too. + +### Methods and options + +| 3.x | 4.0 | +| --- | --- | +| `image.rotate(angle, { resize: false })` | `image.rotate(-angle, { expand: false })`, like `transform()`, `outline()` and `dropShadow()` (the angle negated, as [`rotate()` turns clockwise](#rotate-turns-clockwise)) | +| `image.rotate(angle, { fast: false })`, `{ fast: true }` | `image.rotate(-angle)`: the bilinear sampling is the `fast: true` one (the same pixels, `fast: false` is removed: it differed by a step at most). `mode` picks `'nearest-neighbor'`, `'bilinear'` or `'bicubic'`, like `transform()` | +| `resize(w, h, { fast: false })`, `scale(f, { fast: false })`, `{ fast: true }` | `resize(w, h)`, `scale(f)`: `fast` is removed, resizing always works like its default `fast: true` (8-bit rounding between the passes, at most a step or two off the precise result) | +| `ResizeModes.AREA` and the other `ResizeModes` | `'area'` and the other names, see [constants and modes](#constants-and-modes) | +| `FrameDisposalModes.BACKGROUND` and the other `FrameDisposalModes` | `'background'` and the other names | +| `Image.renderSVG(svg, { size: 512, mode: 'width' })`, `{ mode: 'height' }` | `Image.renderSVG(svg, { width: 512 })`, `{ height: 512 }` | +| `Image.renderSVG(svg, { size: 2 })`, `{ size: 2, mode: 'scale' }` | `Image.renderSVG(svg, { scale: 2 })` | +| `SVGScaleModes`, `SVGScaleMode` | Removed, see the two rows above | +| `image.drawBox(x, y, w, h, color)` | `image.composite(new Image(w, h).fill(color), { x, y })`. It blends a translucent color over the image; `drawBox()` replaced the pixels | +| `image.drawCircle(x, y, r, color)` | `image.composite(new Image(2 * r, 2 * r).fill(color).cropCircle(), { x: x - r, y: y - r })`: an approximation, the edge pixels differ (it blends instead of replacing, and `cropCircle()` has its own antialiasing) | +| `image.greyscale()` | `image.grayscale()` (the whole API spells American English) | +| `Image.renderText(text, { font, size, layout: { maxWidth: 300 } })`, `layout: new TextLayout(options)` | `Image.renderText(text, { font, size, width: 300 })`: the layout options ([`TextLayoutOptions`](https://imagescript.dev/interfaces/TextLayoutOptions.html)) are part of the options; `TextLayout` isn't exported | +| `image.getRGBAAt(x, y)` | `Colors.toRGBA(image.getPixelAt(x, y))`, an array (`getRGBAAt()` returned a view into the bitmap) | +| `image.region(x, y, w, h)` | `image.extract(x, y, w, h)` | +| `animation.encodeGIF({ quality })`, `Animation.gifEncoder(w, h, { quality })` | `{ colors }`: the palette size, 2-256. A quality of 90 and above is the default `256`; below, `colors: Math.round(8 * 32 ** (quality / 90))` gives the old palette size. `dither` (`'floyd-steinberg'` by default, `'atkinson'`, `'ordered'` or `'none'`) and `ditherStrength` are new | +| `FrameDisposalModeName` (type) | `FrameDisposalMode`: the `Name` suffix is gone, as `FrameDisposalModeId` is | +| `SVGOptions` (type) | `RenderSVGOptions`, like `RenderTextOptions` | +| `TextStyle` (type) | `TextStyleOptions`, like `TextLayoutOptions` | +| `GIFEncodeOptions` (the options of `Animation.encodeGIF()`) | `GIFAnimationEncodeOptions`. `GIFEncodeOptions` is now the options of the new `Image.encodeGIF()` | +| `AnimationDecodeOptions` (type) | `DecodeOptions`, which `Image.decode()`, `Animation.decode()` and `decode()` all take | +| `EncodeOptions` (type) as the options of `encodeTGA()` | `TGAEncodeOptions`. `EncodeOptions` is now the `metadata` that all encoder options extend | +| `new GainMap(image, { gainMapMin, gainMapMax })`, `map.gainMapMin`, `map.gainMapMax` | `new GainMap(image, { min, max })`, `map.min`, `map.max` | +| `Image.renderSVG(svg, { fonts })` | `Image.renderSVG(svg, { font })`, like `renderText()` (one font or an array). An old `fonts` is ignored, so text isn't drawn: search for it | +| `setPixelAt(x, y, pixelColor)`, `lightness(value)`, `saturation(value)`, `opacity(opacity)` (parameter names only) | `setPixelAt(x, y, color)`, `lightness(factor)`, `saturation(factor)`, `opacity(factor)` | + +### Fixed-length tuple types + +`transform()` on images, frames and animations takes an `AffineTransform` with exactly six values. Gain-map channel +parameters take a scalar or a three-value `[red, green, blue]` tuple (`GainMapChannelValues`); use a scalar for the +shared-channel form instead of a one-element array. The gain-map parameter properties (`min`, `max`, `gamma`, +`offsetSDR` and `offsetHDR`) return readonly copies: changing `map.min[0]` does not change the map (and TypeScript +rejects it). Assign a scalar or a full tuple instead, such as `map.min = [0, 1, 2]`. + +### Frames hold an image + +A `Frame` is no longer an `Image`: it holds one, `frame.image`, with the frame's duration, offsets and disposal mode. +`new Frame()` takes the image (which the frame uses as it is, without a copy), and `Frame.from()` is removed. + +| 3.x | 4.0 | +| --- | --- | +| `new Frame(width, height, options)` | `new Frame(new Image(width, height), options)` | +| `Frame.from(image, options)` | `new Frame(image.clone(), options)`, or `new Frame(image, options)` without the copy | +| `frame.blur(2)`, `frame.fill(color)`, `frame.bitmap`, `frame.gainMap`, ... | `frame.image.blur(2)`, `frame.image.fill(color)`, `frame.image.bitmap`, `frame.image.gainMap`, ... | +| `image.composite(frame)`, `frame.encodePNG()` | `image.composite(frame.image)`, `frame.image.encodePNG()` | +| `frame instanceof Image` | `false` now | + +The methods that change the size stay on the frame: `resize()` (including its `'contain'` and `'cover'` fit modes), +`scale()`, `crop()`, `trim()`, `rotate()`, `transform()`, `dropShadow()` and `outline()`. They move the offsets so the +frame stays in place in the animation (resizing scales the offsets, as if the whole animation was resized); see +[frames move their offsets](#frames-move-their-offsets-when-their-size-changes) for how that differs from 3.x. +`width`, `height`, `clone()` and `toString()` work as before. Everything else goes through `frame.image`. The image's +own methods don't know about the frame and leave the offsets alone: after `frame.image.rotate(90)`, the frame's top +left corner stays where it was, and the turned image hangs from it. + +### Checked values and the canvas + +Values that were only checked when they were used are now checked when they are set: `frame.duration`, +`frame.xOffset` and `frame.yOffset` (a finite number, truncated to an integer for the offsets; a duration from 0), and the parameters of a `GainMap` (finite, +a scalar or 3 values per channel, a gamma above 0, `hdrCapacityMin` from 0 and below `hdrCapacityMax`, +`useBaseColorSpace` a boolean). An invalid value throws a `RangeError` (a `TypeError` for `useBaseColorSpace`) and the +old value stays. + +An `Animation` now has a canvas size of its own: `animation.width` and `animation.height` are the decoded file's, the +one given as `new Animation(frames, { width, height })` (`AnimationCanvasOptions`), or the one `resize()` and `crop()` set. +Without one, they are the frames' right and bottom edge, as in 3.x. Frames, or the parts of them, outside the canvas +aren't encoded. + +The encoders return `Promise>`, so their output goes into `new Blob()`, `new Response()` and +`crypto.subtle` without a cast. This needs TypeScript 5.7 or newer. + +## Methods that take options refuse other arguments + +A method that takes options now throws a `TypeError` when its argument is anything other than an object (or left out). +That covers numbers, strings, booleans and `null`. The message names the form that works, for example: + +```text +TypeError: cropCircle() takes an options object, like cropCircle({ fit: 'cover' }), not boolean +``` + +This is how the positional calls you missed show up at runtime. It applies to every method that takes options, +including `cropCircle()`, `Image.renderText()`, `quantize()`, `transform()`, `dropShadow()`, `outline()`, the +gradients, `Image.decode()`, the encoders, `Animation.decode()` and `new GainMap()`. Only the type of the argument is +checked: a key that isn't an option is ignored, so a typo like `{ maxWith: 300 }` is not caught at runtime (TypeScript +reports it for an inline object). + +## Checklist + +Grep patterns for the affected code. They find candidates; read each hit, because some names are used by other code +(for example `.encode(` on a non-image object). + +```sh +# constants and modes +grep -rnE 'RESIZE_|SVG_MODE_|DISPOSAL_|ResizeModes|FrameDisposalModes' src + +# encode() on images, and the color helpers +grep -rnE '\.encode\(' src +grep -rnE 'rgbaToColor|rgbToColor|hslaToColor|hslToColor|rgbaToHSLA|colorToRGBA?|Image\.gradient' src + +# iteration over images +grep -rnE 'iterateWithColors|coordinates\(|for \(const \[[a-z]+, ?[a-z]+\] of' src + +# types and classes +grep -rnE 'PNGMetadata|AnimationEncoderOptions|AdjustOptions|TextOptions|FrameDisposalModeId|FrameDisposalModeName|SVGOptions|\bTextStyle\b|\bGIF\b' src + +# decode and animations +grep -rnE 'decode\(.*, *(true|false)\)|onlyFirstFrame' src +grep -rnE 'loopCount\s*(:|=|===)\s*-1|loopCount\s*<\s*0' src +grep -rnE 'Array\.isArray|\.slice\(|\.frames\b|\.length\s*=' src + +# frames and animations: constructors and positional arguments +grep -rnE 'new (Frame|Animation|GIF)\(|Frame\.from\(|Animation\.decode\(' src +grep -rnE '\.(encodeGIF|encodeAPNG|encodeJPEG|encodePNG)\(\s*[0-9]' src + +# options that were positional +grep -rnE "\.(resize|scale|contain|fit|cover)\([^)]*, *(['\"]|ResizeModes\.|SVGScaleModes\.)" src +grep -rnE '\.(composite|rotate|sharpen|dominantColor|roundCorners|fisheye|trim|colorToAlpha)\([^)]' src +grep -rnE 'renderSVG\(|renderText\(|cropCircle\(' src +grep -rnE '\.(red|green|blue|opacity|lightness|saturation)\([^)]*,' src + +# renamed and reshaped in 4.0 +grep -rnE '\.(contain|fit|cover)\(|greyscale|drawBox|drawCircle|SVGScaleMode|TextLayout|AnimationDecodeOptions|gainMapM(in|ax)' src +grep -rnE 'fromHSLA?\(|toHSLA\(|\.rotate\(|renderSVG\([^)]*(size|mode)|layout:|getRGBAAt|\.region\(' src +grep -rnE 'encodeGIF\(|gifEncoder\(|GIFEncodeOptions|encodeJPEG\(' src + +# frames: anything an Image does, on a frame, and the size changes that move the offsets now +grep -rnE 'new Frame\(|Frame\.from\(|frame\w*\.[a-zA-Z]+\(' src + +# behavior changes without a compile error +grep -rnE 'maxWidth|maxHeight|wrapHardBreaks|\.(rotate|quantize|contain|encodeJPEG|encodeWebP|dominantColor)\(|from(HSLA?)\(|toHSLA\(' src +grep -rnE 'compression:|[xy]Offset|\.bitmap =|renderSVG\(|Creation Time|DateTime' src + +# GainMap +grep -rnE 'gainMap\.encode\(|\.encode\(\s*[0-9]' src +``` + +Also search for the variables that hold animations, and for `[0]`, `.map(`, `.filter(` and `.forEach(` on them: the +search can't tell an animation from an array, so check the type of each receiver. + +Then compile with `tsc`, and run the tests that cover your decode and encode paths. The eighteen behavior changes need +runtime checks: a file with several frames, a one-frame GIF, any `loopCount: -1`, every resize fit mode, every HSL hue, +every `rotate()`, every `dominantColor()` threshold, all text rendered with a size, every JPEG made from an image with transparency, every `quantize()`, every `encodeWebP()` with a quality of 100, the size changes of frames, the +values that now throw (cut-off uploads among them), gradients with transparent stops, gain maps given to images, anything that reads the metadata of encoded files, and every SVG with images. diff --git a/jsr.json b/jsr.json index 934f4b70..d04815d7 100644 --- a/jsr.json +++ b/jsr.json @@ -8,8 +8,6 @@ "src", "README.md", "LICENSE", - "LICENSE.MIT", - "LICENSE.AGPL-3.0", "THIRD_PARTY_NOTICES.md", "licenses" ] diff --git a/media/docs.css b/media/docs.css index f6f12e46..5e40f12f 100644 --- a/media/docs.css +++ b/media/docs.css @@ -163,14 +163,6 @@ pre > button { height: var(--toolbar-height); } -.tsd-page-toolbar .table-cell { - line-height: var(--toolbar-height); -} - -.tsd-page-toolbar .tsd-toolbar-icon { - padding: calc((var(--toolbar-height) - 16px) / 2) 0; -} - .tsd-page-toolbar .tsd-widget { height: var(--toolbar-height); } @@ -211,7 +203,6 @@ pre > button { color: var(--color-text-aside); font-size: 0.9rem; font-weight: 500; - margin-left: 1.5rem; } #tsd-toolbar-links a:hover { @@ -219,31 +210,31 @@ pre > button { text-decoration: none; } -#tsd-search .field input { - font: inherit; +/* the search: a dialog the toolbar's button opens */ +#tsd-search { + border-radius: var(--radius); + box-shadow: 0 12px 32px rgb(0 0 0 / 0.16); } -#tsd-search .results { - border-radius: 0 0 var(--radius) var(--radius); - overflow: hidden; - box-shadow: 0 12px 32px rgb(0 0 0 / 0.16); +#tsd-search-input { + font: inherit; } -#tsd-search .results li { +#tsd-search-results > li { line-height: 1.4; } -#tsd-search .results li:nth-child(even) { +#tsd-search-results > li:nth-child(even) { background-color: var(--color-background); } -#tsd-search .results li:nth-child(odd) { +#tsd-search-results > li:nth-child(odd) { background-color: var(--color-background-secondary); } -#tsd-search .results li.current, -#tsd-search .results li:hover { +#tsd-search-results > li:is(:hover, [aria-selected="true"]) { background-color: var(--color-active-menu-item); + color: inherit; } /* ---------- layout ---------- */ @@ -341,11 +332,16 @@ pre > button { font-weight: 600; } -.tsd-navigation .tsd-accordion-summary svg, -.tsd-page-navigation .tsd-accordion-summary svg { - width: 0.75rem; - height: 0.75rem; - margin-right: 0.15rem; +/* typedoc's chevrons are 20px symbols in svgs without a viewBox: zoom scales them (a smaller width or height would only +cut them off). Their margins are zoomed too */ +.tsd-navigation .tsd-accordion-summary > svg { + zoom: 0.56; + margin-right: 0.27rem; + opacity: 0.6; +} + +/* (sized with the rest of the page menu's below) */ +.tsd-page-navigation .tsd-accordion-summary > svg { opacity: 0.6; } @@ -369,9 +365,8 @@ pre > button { } .page-menu .tsd-accordion-summary > svg { - width: 0.7rem; - height: 0.7rem; - margin-right: 0.3rem; + zoom: 0.72; + margin-right: 0.42rem; } .page-menu .tsd-page-navigation a { @@ -480,6 +475,10 @@ a.external[target="_blank"]:has(> img) { } .tsd-typography table { + /* a wide table scrolls inside its panel instead of running past the page edge on narrow screens */ + display: block; + max-width: 100%; + overflow-x: auto; border-collapse: collapse; font-size: 0.9rem; } @@ -521,12 +520,9 @@ a.external[target="_blank"]:has(> img) { margin: 0; } -.tsd-accordion-summary > h2 > svg, -.tsd-accordion-summary > h3 > svg, -.tsd-accordion-summary > h5 > svg, +/* (the size the headings' chevrons had at 0.8em of the headings) */ .tsd-accordion-summary > svg { - width: 0.8em; - height: 0.8em; + zoom: 1.59; opacity: 0.45; } diff --git a/package.json b/package.json index e31df0a3..0a803296 100644 --- a/package.json +++ b/package.json @@ -14,8 +14,6 @@ "files": [ "dist", "LICENSE", - "LICENSE.MIT", - "LICENSE.AGPL-3.0", "THIRD_PARTY_NOTICES.md", "licenses", "README.md" @@ -29,7 +27,7 @@ "test": "npm run build && node ./tests/run.js", "coverage": "node scripts/build.js --source-maps && c8 node ./tests/run.js && node scripts/coverage-report.js", "prepack": "npm run build", - "version": "node scripts/version.js && git add src/version.ts jsr.json" + "version": "node scripts/version.js && git add jsr.json" }, "repository": { "type": "git", @@ -79,14 +77,13 @@ "pbm", "pam", "pfm", - "hdr", "radiance", "animation", "text rendering", "font" ], "author": "Mathis Mensing ", - "license": "(AGPL-3.0-or-later OR MIT)", + "license": "MIT", "bugs": { "url": "https://github.com/imagescript/ImageScript/issues" }, @@ -95,12 +92,19 @@ "node": ">=22.13.0" }, "devDependencies": { - "@eslint/js": "9.39.5", + "@eslint/js": "10.0.1", "c8": "12.0.0", - "eslint": "9.39.5", + "eslint": "10.14.0", "eslint-plugin-sonarjs": "4.2.2", - "typedoc": "0.27.9", - "typescript": "5.7.3", - "typescript-eslint": "8.72.0" + "typedoc": "0.28.20", + "typescript": "6.0.3", + "typescript-eslint": "8.72.2" + }, + "overrides": { + "minimatch": "11.0.8", + "glob": "14.0.5", + "typedoc": { + "minimatch": "9.0.9" + } } } diff --git a/scripts/build.js b/scripts/build.js index 670fdcd7..9f5843d6 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -8,7 +8,7 @@ const root = path.join(__dirname, '..'); const tsc = require.resolve('typescript/bin/tsc'); const run = args => execFileSync(process.execPath, [tsc, ...args], { cwd: root, stdio: 'inherit' }); -// keep the version in PNG metadata and the one JSR publishes in sync with package.json +// keep the version JSR publishes in sync with package.json require('./version.js').setVersion(); fs.rmSync(path.join(root, 'dist'), { recursive: true, force: true }); @@ -52,5 +52,6 @@ const threadsCode = fs.readFileSync(threads, 'utf8'); if (!threadsCode.includes("new URL('./worker.ts', import.meta.url)")) throw new Error('build: the worker URL in threads.js not found'); fs.writeFileSync(threads, threadsCode.replace("new URL('./worker.ts', import.meta.url)", "new URL('./worker.js', import.meta.url)")); -// the package itself has no "type", so mark the build as ES modules -fs.writeFileSync(path.join(root, 'dist/package.json'), '{"type":"module"}\n'); +// the package itself has no "type", so mark the build as ES modules. Bundlers read "sideEffects" from the nearest +// package.json, which this one is for everything in dist/: without it they keep every module of the library +fs.writeFileSync(path.join(root, 'dist/package.json'), '{"type":"module","sideEffects":false}\n'); diff --git a/scripts/docs.js b/scripts/docs.js index 73186fbe..5a79cd58 100644 --- a/scripts/docs.js +++ b/scripts/docs.js @@ -11,7 +11,8 @@ const out = path.join(root, 'docs'); const typedoc = path.join(path.dirname(require.resolve('typedoc/package.json')), 'bin/typedoc'); fs.rmSync(out, { recursive: true, force: true }); -execFileSync(process.execPath, [typedoc], { cwd: root, stdio: 'inherit' }); +// (arguments are typedoc's: the docs workflow links the sources of the released tag with --gitRevision) +execFileSync(process.execPath, [typedoc, ...process.argv.slice(2)], { cwd: root, stdio: 'inherit' }); const site = 'https://imagescript.dev/'; const description = 'Pure TypeScript image processing that runs everywhere: Node.js, Deno, Bun, browsers and edge runtimes'; @@ -45,7 +46,7 @@ for (const page of pages) { html = html.replace(/()([^<]+?) - (v[^<]+)<\/a>/, '$1$2 $3'); html = html.replace(/(
[\s\S]*?

)(Class|Interface|Function|Type Alias|Variable|Enumeration|Namespace) /, '$1$2'); - // constants typed as their own literal (RESIZE_AREA: "RESIZE_AREA" = 'RESIZE_AREA') show the value once + // constants typed as their own literal (ResizeModes.AREA: "area" = 'area') show the value once html = html.replace(/((?:"([^&<]*)"|(-?[\d.]+))<\/span>) = (?:'([^&<]*)'|(-?[\d.]+))<\/span>/g, (all, type, typeString, typeNumber, valueString, valueNumber) => (typeString ?? typeNumber) === (valueString ?? valueNumber) ? type : all); @@ -63,8 +64,9 @@ for (const page of pages) { const redirects = { 'Image.html': ['classes/Image.html', true], 'Frame.html': ['classes/Frame.html', true], - 'GIF.html': ['classes/GIF.html', true], - 'TextLayout.html': ['classes/TextLayout.html', true], + 'GIF.html': ['classes/Animation.html', true], + // (TextLayout isn't exported any more: its options are renderText()'s) + 'TextLayout.html': ['interfaces/TextLayoutOptions.html', false], 'global.html': ['functions/decode.html', false] }; diff --git a/scripts/release-check.js b/scripts/release-check.js index 78924430..27d172fe 100644 --- a/scripts/release-check.js +++ b/scripts/release-check.js @@ -53,8 +53,10 @@ async function main() { : `the GitHub release is marked as prerelease, but ${version} has no prerelease suffix (like -beta.1)`); const changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); - if (!changelog.split('\n').some(line => /^##\s/.test(line) && line.replace(/^##\s+v?/, '').trim().split(/\s/)[0] === version)) - fail(`CHANGELOG.md has no "## ${version}" section`); + // (a prerelease may use the section of its release, so 4.0.0-alpha.1 and later prereleases share "## 4.0.0") + const release = version.replace(/-.*$/, ''); + if (!changelog.split('\n').some(line => /^##\s/.test(line) && [version, release].includes(line.replace(/^##\s+v?/, '').trim().split(/\s/)[0]))) + fail(`CHANGELOG.md has no "## ${version}" or "## ${release}" section`); // what JSR refuses when publishing, after npm has published (deno publish --dry-run doesn't check it): declaring // global types diff --git a/scripts/version.js b/scripts/version.js index 982e0a88..c4abdfc2 100644 --- a/scripts/version.js +++ b/scripts/version.js @@ -1,6 +1,6 @@ -// sets the package version and keeps its copies in sync: package.json, jsr.json and src/version.ts (reported in -// PNG metadata). The release workflow sets the version from the release tag, the build syncs the copies. -// usage: node scripts/version.js [version] (without a version only the copies are synced to package.json) +// sets the package version and keeps its copy in sync: package.json and jsr.json. The release workflow sets the +// version from the release tag, the build syncs the copy. +// usage: node scripts/version.js [version] (without a version only the copy is synced to package.json) const fs = require('fs'); const path = require('path'); @@ -15,10 +15,6 @@ function setVersion(version) { const jsr = readJSON('jsr.json'); if (jsr.version !== version) writeJSON('jsr.json', { ...jsr, version }); - - const file = path.join(root, 'src/version.ts'); - const source = `// kept in sync with package.json by scripts/version.js\nexport const VERSION = '${version}';\n`; - if (!fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== source) fs.writeFileSync(file, source); return version; } diff --git a/src/animation-encoder.ts b/src/animation-encoder.ts index bc67fcfc..804256b6 100644 --- a/src/animation-encoder.ts +++ b/src/animation-encoder.ts @@ -1,4 +1,5 @@ import * as gifCodec from './codecs/gif.ts'; +import { paletteOptions } from './codecs/quantize.ts'; import * as png from './codecs/png.ts'; import * as webp from './codecs/webp.ts'; import { Image } from './image.ts'; @@ -6,56 +7,41 @@ import { Frame, FrameOptions } from './frame.ts'; import { Optimizer, Compositor, InputFrame, OptimizeOptions, OptimizedFrame, coverCanvas, fillUnchanged } from './util/optimize.ts'; import { compressAsync, decompressAsync } from './codecs/zlib.ts'; import { resolveMetadata, pngText, exifData, gifComments } from './metadata.ts'; -import { finite, compressionLevel, fitLoops } from './util/options.ts'; -import type { AnimationOptions, AnimationEncodeOptions, WebPAnimationEncodeOptions, GIFEncodeOptions, APNGEncodeOptions } from './animation.ts'; - -// (ImageScript, like GIF, counts repetitions: -1 forever, 0 play once; APNG and WebP count plays, 0 forever) -const toPlays = (loopCount: number): number => loopCount < 0 || loopCount === Infinity ? 0 : loopCount + 1; - -/** - * The options all animation encoders of {@link Animation.webpEncoder} and the others have - * @deprecated {@link Animation.webpEncoder} and the others take the options of {@link Animation.encodeWebP} and the - * others ({@link AnimationEncodeOptions}) with the {@link AnimationOptions.loopCount}, this will be removed in 4.0 - * @group Deprecated - */ -export type AnimationEncoderOptions = AnimationEncodeOptions & AnimationOptions; - -/** - * Options of {@link Animation.webpEncoder} - * @deprecated Use {@link WebPAnimationEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed - * in 4.0 - * @group Deprecated - */ -export type WebPAnimationEncoderOptions = WebPAnimationEncodeOptions & AnimationOptions; - -/** - * Options of {@link Animation.gifEncoder} - * @deprecated Use {@link GIFEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed in 4.0 - * @group Deprecated - */ -export type GIFAnimationEncoderOptions = GIFEncodeOptions & AnimationOptions; - -/** - * Options of {@link Animation.apngEncoder} - * @deprecated Use {@link APNGEncodeOptions}, with {@link AnimationOptions.loopCount}: this will be removed in 4.0 - * @group Deprecated - */ -export type APNGAnimationEncoderOptions = APNGEncodeOptions & AnimationOptions; +import { instance, checkOptions, finite, nonNegative, canvasSize, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration, boolean } from './util/options.ts'; +import type { AnimationOptions, WebPAnimationEncodeOptions, GIFAnimationEncodeOptions, APNGEncodeOptions } from './animation.ts'; +import { checkFormatSize } from './util/limits.ts'; // a format's part: takes the frames in order once they can't change anymore, then makes the file interface Format { + readonly name: 'GIF' | 'APNG' | 'WebP'; readonly optimize: OptimizeOptions; frame(f: OptimizedFrame | InputFrame, optimized: boolean): Promise; - file(optimizer: Optimizer | null): Promise | Uint8Array; + file(optimizer: Optimizer | null): Promise> | Uint8Array; +} + +/** + * A frame cut to the canvas: as it is when it lies inside, else the part inside (a copy), or a transparent pixel when + * it lies entirely outside (it shows nothing, its duration counts), like {@link Animation}'s encoders do + */ +function clipToCanvas(frame: InputFrame & { disposal: number }, width: number, height: number): InputFrame & { disposal: number } { + const { x, y, width: w, height: h } = frame; + if (x >= 0 && y >= 0 && x + w <= width && y + h <= height) return frame; + const left = Math.max(0, x), top = Math.max(0, y), right = Math.min(width, x + w), bottom = Math.min(height, y + h); + if (right <= left || bottom <= top) return { ...frame, x: 0, y: 0, width: 1, height: 1, disposal: 1, dispose: 0, pixels: new Uint8Array(4) }; + const pixels = new Uint8Array((right - left) * (bottom - top) * 4); + for (let row = top; row < bottom; row++) + pixels.set(frame.pixels.subarray(((row - y) * w + left - x) * 4, ((row - y) * w + right - x) * 4), (row - top) * (right - left) * 4); + return { ...frame, x: left, y: top, width: right - left, height: bottom - top, pixels }; } /** * Encodes an animation a frame at a time, without keeping all frames in memory: see {@link Animation.webpEncoder}, - * {@link Animation.gifEncoder} and {@link Animation.apngEncoder}. The file is the one an {@link Animation} of the - * frames encodes to, but for unoptimized WebPs with frames WebP can't store as they are (disposed to the previous - * frame, or disposed with odd offsets): from the first of them on, the frames are the canvas they show (the same - * animation, blending rounds differently by 1 at most). APNGs keep their frames compressed until the end: their pixel - * format depends on all of them + * {@link Animation.gifEncoder} and {@link Animation.apngEncoder} + * @remarks + * The file is the one an {@link Animation} of the frames encodes to, but for unoptimized WebPs with frames WebP can't + * store as they are (disposed to the previous frame, or disposed with odd offsets): from the first of them on, the + * frames are the canvas they show (the same animation, blending rounds differently by 1 at most). APNGs keep their + * frames compressed until the end: their pixel format depends on all of them */ export class AnimationEncoder { private optimizer: Optimizer | null; @@ -68,8 +54,10 @@ export class AnimationEncoder { /** The canvas height */ readonly height: number; - /** @internal */ - constructor(width: number, height: number, private readonly format: Format, optimize: boolean) { + // (private: created by the factories of Animation, through the static methods below; a constructor marked for + // stripping would be left out of the declarations, which then show a public `new AnimationEncoder()` that fails) + private constructor(width: number, height: number, private readonly format: Format, optimize: boolean) { + if (!format) throw new TypeError('AnimationEncoder is created by Animation.gifEncoder(), apngEncoder() or webpEncoder()'); this.width = width; this.height = height; this.optimizer = optimize ? new Optimizer(width, height, format.optimize) : null; @@ -80,51 +68,57 @@ export class AnimationEncoder { return this.count; } - /** - * How many frames were added - * @deprecated Use {@link AnimationEncoder.frameCount}, `frames` will be removed in 4.0 - * @group Deprecated - */ - get frames(): number { - return this.count; - } - /** * Adds the next frame: a {@link Frame} (with its duration, offsets and disposal) or an image (a frame of 100 ms by * default). The options override the frame's. The pixels are copied right away, the image can change afterwards * @param frame The frame or image * @param options See {@link FrameOptions} + * @throws `TypeError` if the frame isn't a {@link Frame} or an {@link Image} + * @throws `RangeError` if the duration is negative or more than the format stores + * @throws `Error` if the encoder is finished */ - add(frame: Frame | Image, options: FrameOptions = {}): Promise { + async add(frame: Frame | Image, options: FrameOptions = {}): Promise { + checkOptions(options, 'encoder.add(frame, { duration: 40 })'); if (this.finished) throw new Error('The animation encoder is finished'); - if (!(frame instanceof Image)) throw new TypeError('Invalid frame passed'); + instance(frame, [Frame, Image], 'the frame of encoder.add()'); const own = frame instanceof Frame ? frame : null; - const duration = options.duration ?? own?.duration ?? 100; - const x = options.xOffset ?? own?.xOffset ?? 0, y = options.yOffset ?? own?.yOffset ?? 0; - if (finite(duration, 'frame duration') < 0) throw new RangeError('Invalid frame duration'); - finite(x, 'x offset'); - finite(y, 'y offset'); + const image = own ? own.image : frame as Image; + const duration = nonNegative(options.duration === undefined ? own?.duration ?? 100 : options.duration, 'frame duration'); + fitDuration(duration, this.format.name); + // (offsets are truncated to integers, like a frame's) + const x = Math.trunc(finite(options.xOffset === undefined ? own?.xOffset ?? 0 : options.xOffset, 'x offset')) || 0; + const y = Math.trunc(finite(options.yOffset === undefined ? own?.yOffset ?? 0 : options.yOffset, 'y offset')) || 0; const disposal = options.disposalMode !== undefined ? Frame.__convert_disposal_mode__(options.disposalMode) : own ? own.__disposal_id__ : 1; const input: InputFrame & { disposal: number } = { - x, y, width: frame.width, height: frame.height, duration, disposal, + x, y, width: image.width, height: image.height, duration, disposal, // (0 none, 1 background, 2 previous, like APNG) dispose: [0, 0, 2, 1][disposal], - pixels: new Uint8Array(frame.bitmap.buffer, frame.bitmap.byteOffset, frame.bitmap.byteLength).slice() + pixels: new Uint8Array(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength).slice() }; this.count++; + // (without the optimizer, which cuts frames to the canvas, a frame is cut here, like Animation does) + const given = this.optimizer ? input : clipToCanvas(input, this.width, this.height); return this.queue = this.queue.then(async () => { - if (!this.optimizer) return this.format.frame(input, false); + if (!this.optimizer) return this.format.frame(given, false); this.optimizer.push(input); for (const f of this.optimizer.take()) await this.format.frame(f, true); }); } - /** Encodes the rest and returns the file. The encoder can't be used afterwards */ - async finish(): Promise { + /** + * Encodes the rest and returns the file. The encoder can't be used afterwards + * @throws `RangeError` if no frame was added + * @throws `Error` if the encoder is finished already + */ + async finish(): Promise> { if (this.finished) throw new Error('The animation encoder is finished'); this.finished = true; await this.queue; - if (!this.count) throw new Error('An animation needs at least one frame'); + if (!this.count) { + // (nothing was encoded: the encoder isn't used up, frames can still be added) + this.finished = false; + throw new RangeError('An animation needs at least one frame, not 0'); + } if (this.optimizer) for (const f of this.optimizer.end()) await this.format.frame(f, true); const optimizer = this.optimizer; this.optimizer = null; @@ -132,10 +126,11 @@ export class AnimationEncoder { } /** @internal */ - static __webp__(width: number, height: number, { loopCount = -1, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }: WebPAnimationEncodeOptions & AnimationOptions): AnimationEncoder { - canvas(width, height, loopCount); - fitLoops(loopCount, 'WebP'); - if (width > 1 << 24 || height > 1 << 24) throw new RangeError('WebP: canvas too large'); + static __webp__(width: number, height: number, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }: WebPAnimationEncodeOptions & AnimationOptions): AnimationEncoder { + boolean(optimize, 'optimize'); + const loops = fitLoops(loopCount(count), 'WebP'); + [width, height] = canvas(width, height, 'WebP'); + checkFormatSize('WebP', width, height, 1 << 24); const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality); const resolved = resolveMetadata(metadata), chunks: Uint8Array[] = []; let alpha = false; @@ -148,7 +143,8 @@ export class AnimationEncoder { chunks.push(await webp.frameChunk(f, lossy, effort)); }; return new AnimationEncoder(width, height, { - optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined }, + name: 'WebP', + optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined, maxDuration: maxDuration('WebP') }, async frame(f, optimized) { if (optimized) return add(f as OptimizedFrame); const input = f as InputFrame & { disposal: number }; @@ -157,21 +153,24 @@ export class AnimationEncoder { if (full) return add({ x: 0, y: 0, width, height, duration: input.duration, dispose: true, blend: false, pixels: shown }); await add(webpFrame(input)); }, - file: () => webp.animationFile(chunks, width, height, toPlays(loopCount), alpha, exifData(resolved)) + file: () => webp.animationFile(chunks, width, height, toPlays(loops), alpha, exifData(resolved)) }, optimize); } /** @internal */ - static __gif__(width: number, height: number, { loopCount = -1, metadata = {}, optimize = true, quality: qualityOption = 95 }: GIFEncodeOptions & AnimationOptions): AnimationEncoder { - const quality = finite(qualityOption, 'quality'); - canvas(width, height, loopCount); - fitLoops(loopCount, 'GIF'); + static __gif__(width: number, height: number, { loopCount: count = Infinity, metadata = {}, optimize = true, colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85 }: GIFAnimationEncodeOptions & AnimationOptions): AnimationEncoder { + const checked = paletteOptions(colors, dither, ditherStrength); + const palette = { colors: checked.colors as number, dither: checked.dither, strength: checked.strength }; + boolean(optimize, 'optimize'); + const loops = fitLoops(loopCount(count), 'GIF'); + [width, height] = canvas(width, height, 'GIF'); const comments = gifComments(resolveMetadata(metadata)); // (the first frame is encoded last: it needs a transparent index if any frame restores the background) let first: gifCodec.GIFFrame | null = null, restores = false; const rest: Uint8Array[] = []; return new AnimationEncoder(width, height, { - optimize: { replace: false, even: false, alpha: 'frame', palette: 256, cover: true }, + name: 'GIF', + optimize: { replace: false, even: false, alpha: 'frame', palette: 256, cover: true, maxDuration: maxDuration('GIF') }, async frame(f, optimized) { if (!first && optimized) coverCanvas(f as OptimizedFrame, width, height); const gif: gifCodec.GIFFrame = { x: f.x, y: f.y, width: f.width, height: f.height, pixels: f.pixels, @@ -180,20 +179,21 @@ export class AnimationEncoder { delay: Math.round(f.duration / 10) }; restores ||= gif.dispose === 3; if (!first) first = gif; - else rest.push(gifCodec.encodeFrame(gif, quality, gif.dispose === 3)); + else rest.push(gifCodec.encodeFrame(gif, palette, gif.dispose === 3)); }, file() { const f = first as gifCodec.GIFFrame; - return concat([gifCodec.header(width, height, loopCount, comments), gifCodec.encodeFrame(f, quality, f.dispose === 3 || restores), ...rest, new Uint8Array([0x3b])]); + return concat([gifCodec.header(width, height, loops, comments), gifCodec.encodeFrame(f, palette, f.dispose === 3 || restores), ...rest, new Uint8Array([0x3b])]); } }, optimize); } /** @internal */ - static __apng__(width: number, height: number, { loopCount = -1, metadata = {}, optimize = true, compression: compressionOption = 4 }: APNGEncodeOptions & AnimationOptions): AnimationEncoder { + static __apng__(width: number, height: number, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4 }: APNGEncodeOptions & AnimationOptions): AnimationEncoder { const compression = compressionLevel(compressionOption); - canvas(width, height, loopCount); - fitLoops(loopCount, 'APNG'); + boolean(optimize, 'optimize'); + const loops = fitLoops(loopCount(count), 'APNG'); + [width, height] = canvas(width, height, 'APNG'); const text = pngText(resolveMetadata(metadata)); // the frames are kept compressed (quickly): the pixel format, and whether opaque animations are stored without // transparency, depend on all of them; then they are converted and compressed one at a time, like encodeAPNG @@ -201,7 +201,8 @@ export class AnimationEncoder { const cost = new png.AlphaCost(); let blended = false; return new AnimationEncoder(width, height, { - optimize: { replace: true, even: false, alpha: () => cost.cost() }, + name: 'APNG', + optimize: { replace: true, even: false, alpha: () => cost.cost(), maxDuration: maxDuration('APNG') }, async frame(f, optimized) { let frame: png.APNGEncodeFrame; if (optimized) { @@ -232,20 +233,23 @@ export class AnimationEncoder { for await (const f of frames()) scanner.add(f.pixels); const format = scanner.format(), encoded: png.EncodedAPNGFrame[] = []; for await (const { pixels, ...f } of frames()) encoded.push({ ...f, data: await png.frameData(pixels, f.width, f.height, format, compression) }); - return png.animationFile(encoded, width, height, toPlays(loopCount), format, text); + return png.animationFile(encoded, width, height, toPlays(loops), format, text); } }, optimize); } } -function canvas(width: number, height: number, loopCount: number): void { - if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw new RangeError(`Invalid canvas size: ${width}x${height}`); - if (loopCount !== Infinity && (!Number.isInteger(loopCount) || loopCount < -1)) throw new RangeError('Invalid loop count'); +function canvas(widthArgument: number, heightArgument: number, format: 'GIF' | 'APNG' | 'WebP'): [width: number, height: number] { + const [width, height] = canvasSize(widthArgument, heightArgument); + // (the GIF header stores the size in 16 bits, WebP in 24; larger ones would wrap) + if (format === 'GIF') checkFormatSize('GIF', width, height, 0xffff); + return [width, height]; } // a frame in the WebP codec's terms (odd offsets: one transparent pixel more on the left/top, blending makes it // invisible) -function webpFrame(f: InputFrame): webp.WebPEncodeFrame { +/** @internal a frame in the WebP codec's terms: odd offsets get one transparent pixel more on the left/top */ +export function webpFrame(f: InputFrame): webp.WebPEncodeFrame { let { x, y, width: w, height: h, pixels } = f; if (x & 1 || y & 1) { const dx = x & 1, dy = y & 1; @@ -257,7 +261,7 @@ function webpFrame(f: InputFrame): webp.WebPEncodeFrame { return { x, y, width: w, height: h, duration: f.duration, dispose: f.dispose === 1, pixels }; } -function concat(parts: Uint8Array[]): Uint8Array { +function concat(parts: Uint8Array[]): Uint8Array { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let offset = 0; for (const p of parts) { diff --git a/src/animation.ts b/src/animation.ts index 3200969c..269f6b66 100644 --- a/src/animation.ts +++ b/src/animation.ts @@ -6,314 +6,572 @@ import * as jxl from './codecs/jxl.ts'; import { availableThreads } from './util/threads.ts'; import { BinaryData, view } from './util/mem.ts'; import { GainMap } from './gainmap.ts'; -import type { ToneMapping } from './codecs/hdr.ts'; -import { Image, ResizeMode, ResizeModes, ResizeOptions, ResizeToOptions, resizeArguments } from './image.ts'; -import { Frame, FrameDisposalModes } from './frame.ts'; +import { Image, DecodeOptions, EncodeOptions, GIFEncodeOptions, ResizeOptions, ResizeToOptions, RotateOptions, TransformOptions, AffineTransform, ShadowOptions, OutlineOptions, TrimOptions, resizeArguments, insideSize, alignedPixels, PNGEncodeOptions, WebPEncodeOptions, FlipDirection, FLIP_DIRECTIONS, TONE_MAPPINGS } from './image.ts'; +import { Frame } from './frame.ts'; import { ImageType } from './image-type.ts'; -import { optimize, OptimizeOptions, OptimizedFrame } from './util/optimize.ts'; -import { Metadata, resolveMetadata, pngText, exifData, gifComments } from './metadata.ts'; -import { isOptions, finite, compressionLevel, fitLoops } from './util/options.ts'; -import { MAX_PIXELS, decoding } from './util/limits.ts'; -import { AnimationEncoder } from './animation-encoder.ts'; - -// loop counts: ImageScript (like GIF) counts repetitions (-1 forever, 0 play once), APNG and WebP count plays (0 forever) -const toPlays = (loopCount: number): number => loopCount < 0 || loopCount === Infinity ? 0 : loopCount + 1; -const fromPlays = (plays: number): number => plays === 0 ? -1 : plays - 1; +import { optimize, OptimizeOptions, OptimizedFrame, Compositor } from './util/optimize.ts'; +import { paletteOptions } from './codecs/quantize.ts'; +import { resolveMetadata, pngText, exifData, gifComments } from './metadata.ts'; +import { shown, scaleFactor, checkOptions, oneOf, pixelLimit, checkThreads, pixels, canvasSize, cropBounds, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, boolean, color as checkColor } from './util/options.ts'; +import { MAX_PIXELS, decoding, checkPixels, checkFormatSize } from './util/limits.ts'; +import { AnimationEncoder, webpFrame } from './animation-encoder.ts'; +import { describe } from './util/inspect.ts'; // frames decoded fully composited, as full canvas frames function canvasFrames(width: number, height: number, frames: Array<{ pixels: Uint8Array | Uint8ClampedArray, duration: number }>): Frame[] { return frames.map(({ pixels, duration }) => { - const frame = new Frame(width, height, duration, 0, 0, FrameDisposalModes.BACKGROUND); // the composited frames are copies already, the frame can keep them - frame.bitmap = pixels; - return frame; + const image = new Image(width, height); + image.bitmap = alignedPixels(pixels); + return new Frame(image, { duration, disposalMode: 'background' }); }); } /** Options of {@link Animation} */ export interface AnimationOptions { /** - * How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...). `-1` still - * means forever, it will be removed in 4.0. Default: forever + * How many times to repeat the animation: `Infinity` loops forever, 0 plays once, 1 plays twice, ... Anything else + * throws: a RangeError unless it is an integer from 0 or `Infinity`, a TypeError unless it is a number + * @defaultValue `Infinity` */ loopCount?: number; } -/** Options of {@link Animation.decode} */ -export interface AnimationDecodeOptions { - /** Whether to stop decoding after the first frame. Default: `false` */ - onlyFirstFrame?: boolean; - /** - * The most pixels to decode, of all frames together (every frame is a full canvas): larger animations throw a - * RangeError before anything that size is allocated, so small files declaring huge animations (decompression - * bombs) can't exhaust the memory. Default: `268402689` (16383², like sharp), `Infinity` for no limit - */ - maxPixels?: number; - /** Whether to convert the colors of frames with an embedded ICC profile (APNGs, WebPs) to sRGB, like `applyColorProfile` of {@link Image.decode}. Default: `true` */ - applyColorProfile?: boolean; - /** At most this many worker threads decode in parallel, like `threads` of {@link Image.decode}. Default: the processors available, at most 8 */ - threads?: number; +/** Options of {@link Animation}'s constructor: the canvas size and the loop count */ +export interface AnimationCanvasOptions extends AnimationOptions { /** - * Whether to rotate/mirror the frames as the orientation tag (Exif, JPEG XL's header, PNG's eXIf chunk or XMP) - * says, like `applyOrientation` of {@link Image.decode}: APNGs, animated WebPs and JPEG XLs. Default: `true` + * The canvas width in pixels (a fraction is truncated, like the size of an image): frames (or the parts of them) + * outside the canvas aren't encoded + * @defaultValue The frames' right edge (the largest `xOffset + width`), following the frames until a canvas size is + * set */ - applyOrientation?: boolean; + width?: number; /** - * How HDR (PQ or HLG) JPEG XL animations, whose light can be brighter than (SDR) white, become 8 bit sRGB, like - * `toneMapping` of {@link Image.decode}: `'reinhard'` compresses the brightest parts, `'clamp'` clamps everything - * brighter than white. Default: `'reinhard'` + * The canvas height in pixels, like `width` + * @defaultValue The frames' bottom edge (the largest `yOffset + height`) */ - toneMapping?: ToneMapping; - /** - * Whether to read the gain map (jhgm box) of JPEG XL animations into {@link Image.gainMap} of every frame, like - * `gainMap` of {@link Image.decode}. Default: `true` - */ - gainMap?: boolean; + height?: number; } /** The options all animation encoders have */ -export interface AnimationEncodeOptions { - /** Metadata to include, see {@link Metadata} */ - metadata?: Metadata; +export interface AnimationEncodeOptions extends EncodeOptions { /** * Whether to store each frame as the area that changed since the frame before and merge identical frames, which * usually makes files a lot smaller. The file shows the same animation either way, but only decodes to the same - * frames without it, which also encodes faster when little changes. Default: `true` + * frames without it, which also encodes faster when little changes. The exception is GIF, which has no partial + * transparency: without `optimize`, a semi-transparent pixel becomes opaque or transparent in its own frame, with + * it the frames are composited first + * @defaultValue `true` */ optimize?: boolean; } -/** Options of {@link Animation.encodeWebP} */ -export interface WebPAnimationEncodeOptions extends AnimationEncodeOptions { - /** - * Lossy frames (0-100, like libwebp's quality: 75 is its default), much smaller than lossless ones. Without it the - * frames are lossless. Optimized lossy frames, like libwebp's, leave out 8x8 blocks that only changed a little (by - * up to 3 per channel at quality 85, 1 at 100) - */ - quality?: number; - /** How much effort the frames take (0-6, lossy and lossless), see {@link WebPEncodeOptions.effort}. Default: `2` */ - effort?: number; - /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */ - sharpYuv?: boolean; - /** Lossy frames: the alpha planes' quality (0-100), see {@link WebPEncodeOptions.alphaQuality}. Default: `100` */ - alphaQuality?: number; -} +/** + * Options of {@link Animation.encodeWebP} and {@link Animation.webpEncoder}: those of {@link WebPEncodeOptions} for every + * frame (but `threads`: the frames are encoded one at a time), and the animation options. Without `quality` the frames + * are lossless + */ +export interface WebPAnimationEncodeOptions extends Omit, AnimationEncodeOptions {} -/** Options of {@link Animation.encodeGIF} */ -export interface GIFEncodeOptions extends AnimationEncodeOptions { - /** 1-100, scales the palette size from 8 colors (1) to 256 colors (90 and above). Default: `95` */ - quality?: number; -} +/** + * Options of {@link Animation.encodeGIF} and {@link Animation.gifEncoder}: those of {@link GIFEncodeOptions} for every + * frame, and the animation options + */ +export interface GIFAnimationEncodeOptions extends GIFEncodeOptions, AnimationEncodeOptions {} -/** Options of {@link Animation.encodeAPNG} */ -export interface APNGEncodeOptions extends AnimationEncodeOptions { - /** The zlib compression level (0-9), higher is smaller but slower. Default: `4` */ - compression?: number; -} +/** + * Options of {@link Animation.encodeAPNG} and {@link Animation.apngEncoder}: those of {@link PNGEncodeOptions}, and the + * animation options + */ +export interface APNGEncodeOptions extends PNGEncodeOptions, AnimationEncodeOptions {} /** - * An animation: frames ({@link Animation.frames}) that can be decoded from and encoded to GIF, APNG and WebP. - * - * The animation itself is an array of its frames too (`animation[0]`, `animation.map(...)`), which is deprecated: in 4.0 - * it won't extend `Array` anymore, use {@link Animation.frames} instead. Array methods like map and filter return - * plain arrays. + * An animation: frames ({@link Animation.frames}) that can be decoded from and encoded to GIF, APNG and WebP. It can be + * iterated (`for (const frame of animation)`), and its `length` is the number of frames. */ -export class Animation extends Array { - /** - * How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...). `-1` still - * means forever, it will be removed in 4.0, when `Infinity` is what animations that loop forever have (animations - * that loop forever have `-1` until then, also the decoded ones) - */ - loopCount: number; +export class Animation { + /** @internal @ignore */ + private __loopCount__ = Infinity; + + /** @internal @ignore */ + private __animationSignal__ = false; + + /** @internal @ignore */ + private __frames__: Frame[] = []; + + /** @internal @ignore */ + private __framesView__: readonly Frame[] | null = null; + + /** @internal @ignore the canvas size, once set (else the frames' extent) */ + private __canvas__: [width: number, height: number] | null = null; /** * Creates a new animation + * @example + * ```ts + * const animation = new Animation([ + * new Frame(new Image(64, 64).fill(0xff0000ff), { duration: 200 }), + * new Frame(new Image(64, 64).fill(0x0000ffff), { duration: 200 }) + * ], { loopCount: 2 }); + * const gif = await animation.encodeGIF(); + * ``` * @param frames The frames to create the animation from - * @param options See {@link AnimationOptions} - */ - constructor(frames: Frame[], options?: AnimationOptions); + * @param options The canvas size and the loop count, see {@link AnimationCanvasOptions} + */ + constructor(frames: Frame[], options?: AnimationCanvasOptions); + constructor(frames: Frame[], options: AnimationCanvasOptions = {}) { + checkOptions(options, 'new Animation(frames, { loopCount: 2 })'); + const { loopCount: count = Infinity, width, height } = options; + const loops = loopCount(count); + if ((width === undefined) !== (height === undefined)) throw new TypeError('Animation() takes both a canvas width and height, or neither'); + const canvas = width === undefined ? null : canvasSize(width, height as number); + this.frames = frames; + this.__loopCount__ = loops; + this.__canvas__ = canvas; + } + /** - * Creates a new animation - * @param frames The frames to create the animation from - * @param loopCount How many times to repeat the animation (`Infinity` = forever, 0 = play once, 1 = play twice, ...) - * @deprecated Pass {@link AnimationOptions} instead, the positional arguments will be removed in 4.0 + * How many times to repeat the animation: `Infinity` (the default) loops forever, 0 plays once, 1 plays twice, ... + * Other values throw, see {@link AnimationOptions.loopCount}, and the loop count stays as it was */ - constructor(frames: Frame[], loopCount?: number); - constructor(frames: Frame[], loopCountOrOptions: number | AnimationOptions = -1) { - super(); - const { loopCount = -1 } = isOptions(loopCountOrOptions) ? loopCountOrOptions : { loopCount: loopCountOrOptions }; - // push instead of super(...frames), so a single frame isn't taken as a length - for (const frame of frames) this.push(frame); - - for (let i = 0; i < this.length; i++) - if (!(this[i] instanceof Frame)) - throw new TypeError(`Frame ${i} is not an instance of Frame`); - - if (loopCount !== Infinity && (finite(loopCount, 'loop count') < -1 || !Number.isInteger(Number(loopCount)))) - throw new RangeError(`Invalid loop count: ${loopCount}`); - - this.loopCount = loopCount; + get loopCount(): number { + return this.__loopCount__; } /** - * @internal - * @ignore + * Replaces the loop count (see {@link Animation.loopCount}). Anything else than `Infinity` or an integer from 0 + * throws, and the count stays as it was + * @param value The new loop count */ - static override get [Symbol.species](): ArrayConstructor { - return Array; + set loopCount(value: number) { + this.__loopCount__ = loopCount(value); } /** - * The animation's frames: an array that changes the animation when it's changed (e.g. `push()`, `splice()`, or - * setting an index), and can be replaced as a whole + * The animation's frames as a frozen array. The frames themselves are mutable; assign a new array to replace the + * list */ - get frames(): Frame[] { - return this; + get frames(): readonly Frame[] { + return this.__framesView__ ??= Object.freeze([...this.__frames__]); } /** * Replaces the animation's frames - * @param frames The new frames (copied into the animation, the array itself isn't kept) - */ - set frames(frames: Frame[]) { - frames = Array.from(frames); - frames.forEach((frame, i) => { - if (!(frame instanceof Frame)) throw new TypeError(`Frame ${i} is not an instance of Frame`); - }); - this.length = 0; - for (const frame of frames) this.push(frame); + * @param frames The new frames (copied into the animation; the array itself isn't kept) + */ + set frames(frames: readonly Frame[]) { + if (frames === null || typeof frames !== 'object' || typeof (frames as Iterable)[Symbol.iterator] !== 'function') + throw new TypeError(`Animation() takes an array of Frame objects, not ${shown(frames)}`); + const copy: Frame[] = []; + for (const frame of frames) { + if (!(frame instanceof Frame)) throw new TypeError(`frames[${copy.length}] must be a Frame, not ${shown(frame)}`); + copy.push(frame); + } + this.__frames__ = copy; + this.__framesView__ = null; + } + + /** The number of frames */ + get length(): number { + return this.__frames__.length; + } + + /** Iterates over the frames, `for (const frame of animation)` */ + [Symbol.iterator](): IterableIterator { + return this.__frames__[Symbol.iterator](); } - /** The animation's width */ + /** + * The canvas width: the one given to the constructor, the decoded file's, or the one {@link Animation.resize} and + * {@link Animation.crop} set; else the frames' right edge + */ get width(): number { + if (this.__canvas__) return this.__canvas__[0]; let max = 0; - for (const frame of this) max = Math.max(max, frame.width + frame.xOffset); + for (const frame of this.frames) max = Math.max(max, frame.width + frame.xOffset); return max; } - /** The animation's height */ + /** The canvas height, like {@link Animation.width}; else the frames' bottom edge */ get height(): number { + if (this.__canvas__) return this.__canvas__[1]; let max = 0; - for (const frame of this) max = Math.max(max, frame.height + frame.yOffset); + for (const frame of this.frames) max = Math.max(max, frame.height + frame.yOffset); return max; } + /** Clones the animation: its frames (with their pixels), canvas size and loop count */ + clone(): Animation { + const copy = new Animation(this.frames.map(frame => frame.clone()), { loopCount: this.loopCount }); + copy.__canvas__ = this.__canvas__ && [...this.__canvas__]; + return copy; + } + /** The animation's duration (in ms) */ get duration(): number { let duration = 0; - for (const frame of this) duration += frame.duration; + for (const frame of this.frames) duration += frame.duration; return duration; } /** A short description for debugging, e.g. `Animation<64x64x1000ms>` */ - override toString(): string { + toString(): string { return `Animation<${this.width}x${this.height}x${this.duration}ms>`; } - /** - * Returns a new animation of the same class containing a range of this one's frames - * (same semantics as Array.prototype.slice) - * @param start The index of the first frame (negative counts from the end). Default: `0` - * @param end The index after the last frame (negative counts from the end). Default: the frame count - * @deprecated Use `new Animation(animation.frames.slice(start, end), animation.loopCount)`: in 4.0 animations - * aren't arrays anymore - * @group Deprecated - */ - override slice(start?: number, end?: number): this { - const Class = this.constructor as new (frames: Frame[], loopCount: number) => this; - return new Class(Array.prototype.slice.call(this, start, end) as Frame[], this.loopCount); - } - /** * Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally. * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio. + * @remarks + * With `fit: 'contain'` and a `background` that isn't transparent, the frames are composited onto it, so the animation + * has whole frames afterwards (the file shows the same, but it can't keep the frames' parts apart anymore) * @param width The new width * @param height The new height * @param options See {@link ResizeOptions} + * @throws `RangeError` if the width or height is less than 1 pixel, or the animation has no canvas */ resize(width: number, height: number, options?: ResizeOptions): this; - /** - * Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally. - * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio. - * @param width The new width - * @param height The new height - * @param mode The resizing mode to use. Default: {@link ResizeModes.BILINEAR} - * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0 - */ - resize(width: number, height: number, mode?: ResizeMode): this; /** * Resizes the animation, scaling every frame and its offsets proportionally: to the given width or height (the * other side keeps the aspect ratio), or to both * @param options The size and how to resize, see {@link ResizeToOptions} */ resize(options: ResizeToOptions): this; - resize(widthOrOptions: number | ResizeToOptions, heightArgument?: number, modeArgument?: ResizeMode | ResizeOptions): this { - // eslint-disable-next-line prefer-const - let [width, height, modeOrOptions] = resizeArguments(widthOrOptions, heightArgument, modeArgument); + resize(widthOrOptions: number | ResizeToOptions, heightArgument?: number, optionsArgument?: ResizeOptions): this { + const [givenWidth, givenHeight, options, fit] = resizeArguments(widthOrOptions, heightArgument, optionsArgument); + if (fit === 'contain' || fit === 'cover') { + if (givenWidth === undefined || givenHeight === undefined) throw new TypeError(`resize({ fit: '${fit}' }) needs both width and height`); + return fit === 'contain' + ? this.__contain__(givenWidth, givenHeight, options) + : this.__cover__(givenWidth, givenHeight, options); + } const originalWidth = this.width, originalHeight = this.height; - if (width === ResizeModes.AUTO && height === ResizeModes.AUTO) throw new Error('RESIZE_AUTO can only be used for either width or height, not for both'); - if (width === ResizeModes.AUTO) width = originalWidth / originalHeight * height; - if (height === ResizeModes.AUTO) height = originalHeight / originalWidth * width; + if (!originalWidth || !originalHeight) throw new RangeError('An animation without frames or canvas can\'t be resized'); + // (a side that is given has to be a pixel at least, like Image.resize() wants; one that follows the other can't be less) + if (givenWidth !== undefined) pixels(givenWidth, 'width'); + if (givenHeight !== undefined) pixels(givenHeight, 'height'); + // the size of the canvas as Image.resize() works it out: a side that is given is cut to whole pixels, one left + // out follows the other, keeping the aspect ratio + let width: number, height: number; + if (fit === 'inside' && givenWidth !== undefined && givenHeight !== undefined) [width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight).map(Math.floor); + else if (givenWidth === undefined) { + height = Math.floor(givenHeight as number); + width = Math.max(1, Math.round(originalWidth / originalHeight * height)); + } else if (givenHeight === undefined) { + width = Math.floor(givenWidth); + height = Math.max(1, Math.round(originalHeight / originalWidth * width)); + } else [width, height] = [Math.floor(givenWidth), Math.floor(givenHeight)]; + const canvas = canvasSize(Math.max(1, width), Math.max(1, height)); const sx = width / originalWidth, sy = height / originalHeight; - for (const frame of this) { + // (a frame listed twice, or two frames of one image, change once: the sizes and offsets are worked out before anything does) + const changes = this.__distinct__().map(frame => { // scale both edges so adjacent frames stay aligned const left = Math.round(frame.xOffset * sx), top = Math.round(frame.yOffset * sy); const right = Math.round((frame.xOffset + frame.width) * sx), bottom = Math.round((frame.yOffset + frame.height) * sy); - (Image.prototype.resize as (width: number, height: number, mode?: ResizeMode | ResizeOptions) => Image) - .call(frame, Math.max(1, right - left), Math.max(1, bottom - top), modeOrOptions); + return { frame, left, top, width: Math.max(1, right - left), height: Math.max(1, bottom - top) }; + }); + const shared = new Set(), seen = new Set(); + for (const { frame } of changes) (seen.has(frame.image) ? shared : seen).add(frame.image); + const originals = new Map(Array.from(shared, image => [image, image.clone()])); + const resized = new Map(); + for (const { frame, left, top, width, height } of changes) { + const size = `${width}x${height}`, done = resized.get(frame.image), original = originals.get(frame.image); + if (done === undefined) { + resized.set(frame.image, size); + frame.image.resize(width, height, options); + } else if (done !== size && original) { + // (the frame's image was resized already: the copy of the original is what the others start from) + frame.image = original.clone().resize(width, height, options); + } frame.xOffset = left; frame.yOffset = top; } + this.__canvas__ = canvas; + + return this; + } + /** + * Crops the canvas to the given region: the frames move with it and are cut to the new canvas (the same `Frame` + * objects, with new images where they are cut; a frame entirely outside becomes a transparent pixel). The region is + * clipped to the canvas, so the result can be smaller than the requested size + * @param x The x offset (0-based) + * @param y The y offset (0-based) + * @param width The new canvas width + * @param height The new canvas height + */ + crop(x: number, y: number, width: number, height: number): this { + // (the part of the region that lies on the canvas) + const [left, top, newWidth, newHeight] = cropBounds(this.width, this.height, x, y, width, height, 'canvas'); + // each frame is cut to the new canvas in place (the same objects, like resize() keeps them; an image frames + // share is replaced, not changed) + for (const frame of this.__distinct__()) { + const frameLeft = frame.xOffset - left, frameTop = frame.yOffset - top; + const cutLeft = Math.max(0, frameLeft), cutTop = Math.max(0, frameTop); + const cutRight = Math.min(newWidth, frameLeft + frame.width), cutBottom = Math.min(newHeight, frameTop + frame.height); + if (cutRight <= cutLeft || cutBottom <= cutTop) { + // (entirely outside: a transparent pixel, its duration counts) + frame.image = new Image(1, 1); + frame.xOffset = frame.yOffset = 0; + frame.disposalMode = 'keep'; + } else { + if (cutLeft !== frameLeft || cutTop !== frameTop || cutRight - cutLeft !== frame.width || cutBottom - cutTop !== frame.height) + frame.image = frame.image.extract(cutLeft - frameLeft, cutTop - frameTop, cutRight - cutLeft, cutBottom - cutTop); + frame.xOffset = cutLeft; + frame.yOffset = cutTop; + } + } + this.__canvas__ = [newWidth, newHeight]; return this; } /** + * Resizes and centers the animation in a box of exactly that size, with transparent or colored bars + * @internal + */ + private __contain__(width: number, height: number, options?: ResizeOptions & { background?: number }): this { + checkOptions(options, 'resize({ width, height, fit: \'contain\', background: 0x000000ff })'); + const { background = 0x00000000, ...resizeOpts } = options ?? {}; + const backgroundColor = checkColor(background, 'background'); + const [boxWidth, boxHeight] = canvasSize(width, height); + this.resize({ width: boxWidth, height: boxHeight, fit: 'inside', ...resizeOpts }); + const x = (boxWidth - this.width) / 2 | 0, y = (boxHeight - this.height) / 2 | 0; + for (const frame of this.__distinct__()) { + frame.xOffset += x; + frame.yOffset += y; + } + this.__canvas__ = [boxWidth, boxHeight]; + if (backgroundColor !== 0) { + this.frames = this.__flattened__().map(frame => { + frame.image = new Image(boxWidth, boxHeight).fill(backgroundColor).composite(frame.image); + return frame; + }); + } + return this; + } + + /** + * Resizes the animation to cover the box and crops the overflowing edges + * @internal + */ + private __cover__(width: number, height: number, options?: ResizeOptions): this { + checkOptions(options, 'resize({ width, height, fit: \'cover\' })'); + const [boxWidth, boxHeight] = canvasSize(width, height); + const scale = Math.max(boxWidth / this.width, boxHeight / this.height); + this.resize(Math.max(boxWidth, Math.round(this.width * scale)), Math.max(boxHeight, Math.round(this.height * scale)), options); + return this.crop((this.width - boxWidth) / 2, (this.height - boxHeight) / 2, boxWidth, boxHeight); + } + + /** + * Flips / mirrors the animation horizontally or vertically, like {@link Image.flip}: every frame is flipped and + * moved to the mirrored place on the canvas, which keeps its size + * @param direction The direction to flip, see {@link FlipDirection} + */ + flip(direction: FlipDirection): this { + oneOf(direction, FLIP_DIRECTIONS, 'flip direction'); + const width = this.width, height = this.height; + // (a frame listed twice, or two frames of one image, are flipped once) + const flipped = new Set(); + for (const frame of this.__distinct__()) { + if (!flipped.has(frame.image)) frame.image.flip(direction); + flipped.add(frame.image); + if (direction === 'horizontal') frame.xOffset = width - frame.xOffset - frame.width; + else frame.yOffset = height - frame.yOffset - frame.height; + } + // (the canvas stays: one that followed the frames would follow the mirrored ones elsewhere) + if (width && height) this.__canvas__ = [width, height]; + return this; + } + + /** + * Scales the animation by a factor: every frame and its offsets, and the canvas + * @param factor The factor + * @param options See {@link ResizeOptions} + */ + scale(factor: number, options?: ResizeOptions): this { + scaleFactor(factor, this.width, this.height); + // (a side doesn't shrink below one pixel, like Image.scale()) + return this.resize(Math.max(1, this.width * factor), Math.max(1, this.height * factor), options); + } + + /** + * Trims the canvas: removes the borders of one color around what any frame shows (in the composited animation), + * like {@link Image.trim}. The frames keep their pixels, the canvas is cropped like {@link Animation.crop} + * @param options The color (by default the top left pixel of the canvas as the first frame shows it) and the + * tolerance, see + * {@link TrimOptions} + */ + trim(options: TrimOptions = {}): this { + checkOptions(options, 'trim({ tolerance: 0.1 })'); + const frames = this.__flattened__(); + if (!frames.length) return this; + const { color = frames[0].image.getPixelAt(0, 0), ...rest } = options; + let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity; + for (const { image } of frames) { + const bounds = image.__trim_bounds__(color, rest); + if (!bounds) continue; + left = Math.min(left, bounds[0]); + top = Math.min(top, bounds[1]); + right = Math.max(right, bounds[0] + bounds[2]); + bottom = Math.max(bottom, bounds[1] + bounds[3]); + } + if (left === Infinity) return this; + return this.crop(left, top, right - left, bottom - top); + } + + /** + * Rotates the animation clockwise, like {@link Image.rotate}: the frames become full canvas frames of the + * composited animation (a partial frame turned by any angle wouldn't cover a rectangle anymore), each one rotated, + * and the canvas takes their size + * @param angle The angle in degrees, clockwise + * @param options See {@link RotateOptions} + */ + rotate(angle: number, options?: RotateOptions): this { + return this.__each__(image => image.rotate(angle, options)); + } + + /** + * Transforms the animation with an affine transform, like {@link Image.transform}: the frames become full canvas + * frames of the composited animation, each one transformed (by default around the canvas' middle), and the canvas + * takes their size + * @param matrix The six values [a, b, c, d, e, f] + * @param options See {@link TransformOptions} + */ + transform(matrix: AffineTransform, options?: TransformOptions): this { + return this.__each__(image => image.transform(matrix, options)); + } + + /** + * Adds a shadow behind what the animation shows, like {@link Image.dropShadow}: the frames become full canvas + * frames of the composited animation, each one with its shadow, and the canvas grows with them + * @param options See {@link ShadowOptions} + */ + dropShadow(options?: ShadowOptions): this { + return this.__each__(image => image.dropShadow(options)); + } + + /** + * Draws an outline around what the animation shows, like {@link Image.outline}: the frames become full canvas + * frames of the composited animation, each one outlined, and the canvas grows with them + * @param options See {@link OutlineOptions} + */ + outline(options?: OutlineOptions): this { + return this.__each__(image => image.outline(options)); + } + + /** + * The composited animation: one full canvas frame per frame, with its duration (gain maps are dropped) * @internal * @ignore */ - protected __validate__(): void { - for (const frame of this) - if (!(frame instanceof Frame)) throw new Error('Animation contains invalid frames'); + __flattened__(): Frame[] { + const { width, height } = this; + if (!this.length) return []; + return png.compositeAnimation({ width, height, frames: this.__apngFrames__() }).map(({ pixels, duration }) => { + const image = new Image(width, height); + image.bitmap = alignedPixels(pixels); + return new Frame(image, { duration, disposalMode: 'background' }); + }); } /** - * Encodes the animation as GIF. Like all encoders, it stores each frame as the area that changed since the frame - * before and merges identical frames (unless the `optimize` option is false), so the file decodes to what the - * animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent - * after the frames are composited - * @param options See {@link GIFEncodeOptions} + * Applies a change to every frame of the composited animation; the canvas takes the frames' new size. Nothing + * changes if the change throws + * @internal + * @ignore + */ + private __each__(change: (image: Image) => unknown): this { + const { width, height } = this; + if (!width || !height) throw new RangeError('An animation without frames or canvas can\'t be changed'); + const frames = this.__flattened__(); + const probe = frames[0]?.image ?? new Image(width, height); + for (const frame of frames.length ? frames : [new Frame(probe)]) change(frame.image); + this.frames = frames; + this.__canvas__ = [probe.width, probe.height]; + return this; + } + + /** + * The frames without repeats: a frame can be listed several times (to hold it, or in a ping-pong), and a change to + * it has to apply once + * @internal + * @ignore + */ + __distinct__(): Frame[] { + return [...new Set(this.__frames__)]; + } + + /** + * The frames cut to the canvas: frames that lie inside it as they are, the others cropped (copies), and frames + * entirely outside as a transparent pixel (they show nothing, their duration counts) + * @internal + * @ignore */ - encodeGIF(options?: GIFEncodeOptions): Promise; + __clipped_frames__(): Frame[] { + const width = this.width, height = this.height; + return this.frames.map(frame => { + const { xOffset: x, yOffset: y } = frame; + if (x >= 0 && y >= 0 && x + frame.width <= width && y + frame.height <= height) return frame; + const left = Math.max(0, x), top = Math.max(0, y); + const right = Math.min(width, x + frame.width), bottom = Math.min(height, y + frame.height); + const options = { duration: frame.duration, disposalMode: frame.disposalMode }; + if (right <= left || bottom <= top) return new Frame(new Image(1, 1), { ...options, disposalMode: 'keep' }); + const clipped = frame.image.extract(left - x, top - y, right - left, bottom - top); + clipped.gainMap = null; + return new Frame(clipped, { ...options, xOffset: left, yOffset: top }); + }); + } + + /** + * @internal + * @ignore + */ + protected __validate__(format: 'GIF' | 'APNG' | 'WebP'): void { + if (!this.length) throw new RangeError('An animation needs at least one frame, not 0'); + for (const frame of this.frames) { + if (!(frame instanceof Frame)) throw new Error('Animation contains invalid frames'); + fitDuration(frame.duration, format); + } + const { width, height } = this; + if (width < 1 || height < 1) throw new RangeError('The animation has no canvas: every frame lies outside of it'); + if (format === 'GIF') checkFormatSize('GIF', width, height, 0xffff); + if (format === 'WebP') checkFormatSize('WebP', width, height, 1 << 24); + } + /** * Encodes the animation as GIF. Like all encoders, it stores each frame as the area that changed since the frame * before and merges identical frames (unless the `optimize` option is false), so the file decodes to what the * animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent * after the frames are composited - * @param quality 1-100, scales the palette size from 8 colors (1) to 256 colors (90 and above) - * @deprecated Pass {@link GIFEncodeOptions} instead, the positional arguments will be removed in 4.0 - */ - encodeGIF(quality?: number): Promise; - async encodeGIF(qualityOrOptions: number | GIFEncodeOptions = 95): Promise { - const { quality = 95, metadata = {}, optimize = true } = isOptions(qualityOrOptions) ? qualityOrOptions : { quality: qualityOrOptions }; - fitLoops(this.loopCount, 'GIF'); - this.__validate__(); + * @param options See {@link GIFAnimationEncodeOptions}; the loop count is the animation's {@link loopCount} (the + * streaming {@link gifEncoder} takes it as an option) + * @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than GIF stores, or the canvas is wider or + * higher than 65535 pixels + */ + encodeGIF(options?: GIFAnimationEncodeOptions): Promise>; + async encodeGIF(options: GIFAnimationEncodeOptions = {}): Promise> { + checkOptions(options, 'encodeGIF({ colors: 64 })'); + const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {}, optimize = true } = options; + boolean(optimize, 'optimize'); + const palette = paletteOptions(colors, dither, ditherStrength); + const loops = fitLoops(this.loopCount, 'GIF'); + this.__validate__('GIF'); const frames = optimize - ? this.__optimized__({ replace: false, even: false, alpha: 'frame', palette: 256, cover: true }).map(f => ({ ...f, dispose: f.dispose ? 3 : 1 })) - : Array.from(this, frame => ({ + ? this.__optimized__({ replace: false, even: false, alpha: 'frame', palette: 256, cover: true, maxDuration: maxDuration('GIF') }).map(f => ({ ...f, dispose: f.dispose ? 3 : 1 })) + : Array.from(this.__clipped_frames__(), frame => ({ x: frame.xOffset, y: frame.yOffset, width: frame.width, height: frame.height, duration: frame.duration, dispose: frame.__disposal_id__, - pixels: new Uint8Array(frame.bitmap.buffer, frame.bitmap.byteOffset, frame.bitmap.byteLength) + pixels: new Uint8Array(frame.image.bitmap.buffer, frame.image.bitmap.byteOffset, frame.image.bitmap.byteLength) })); // gifs store centiseconds; rounding keeps e.g. 16 ms (60 fps) from becoming 10 ms const gifFrames = frames.map(({ duration, ...f }) => ({ ...f, delay: Math.round(duration / 10) })); - return gifCodec.encode({ width: this.width, height: this.height, loopCount: this.loopCount, frames: gifFrames }, finite(quality, 'quality'), gifComments(resolveMetadata(metadata))); + return gifCodec.encode({ width: this.width, height: this.height, loopCount: loops, frames: gifFrames }, { colors: palette.colors as number, dither: palette.dither, strength: palette.strength }, gifComments(resolveMetadata(metadata))); } /** @@ -321,45 +579,43 @@ export class Animation extends Array { * the first frame. Each frame is stored as the area that changed since the frame before, identical frames are * merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't * necessarily decode to the same frames - * @param options See {@link APNGEncodeOptions} - */ - encodeAPNG(options?: APNGEncodeOptions): Promise; - /** - * Encodes the animation as APNG (animated PNG, lossless and with full alpha). Viewers without APNG support show - * the first frame. Each frame is stored as the area that changed since the frame before, identical frames are - * merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't - * necessarily decode to the same frames - * @param compression The zlib compression level (0-9), higher is smaller but slower. Default: `4` - * @deprecated Pass {@link APNGEncodeOptions} instead, the positional arguments will be removed in 4.0 - */ - encodeAPNG(compression?: number): Promise; - async encodeAPNG(compressionOrOptions: number | APNGEncodeOptions = 4): Promise { - const { compression = 4, metadata = {}, optimize = true } = isOptions(compressionOrOptions) ? compressionOrOptions : { compression: compressionOrOptions }; - fitLoops(this.loopCount, 'APNG'); - this.__validate__(); - if (!this.length) throw new Error('An animation needs at least one frame'); + * @param options See {@link APNGEncodeOptions}; the loop count is the animation's {@link loopCount} (the streaming + * {@link apngEncoder} takes it as an option) + * @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than APNG stores + */ + encodeAPNG(options?: APNGEncodeOptions): Promise>; + async encodeAPNG(options: APNGEncodeOptions = {}): Promise> { + checkOptions(options, 'encodeAPNG({ compression: 9 })'); + const { compression = 4, metadata = {}, optimize = true } = options; + boolean(optimize, 'optimize'); + const loops = fitLoops(this.loopCount, 'APNG'); + this.__validate__('APNG'); const frames = optimize - ? this.__optimized__({ replace: true, even: false, alpha: frames => png.alphaCost(frames.map(f => f.pixels)) }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 })) + ? this.__optimized__({ replace: true, even: false, alpha: frames => png.alphaCost(frames.map(f => f.pixels)), maxDuration: maxDuration('APNG') }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 })) : this.__apngFrames__().map(({ blend: _, ...f }) => f); // blended, the encoder's default - return png.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), compressionLevel(compression), pngText(resolveMetadata(metadata))); + return png.encodeAnimation(frames, this.width, this.height, toPlays(loops), compressionLevel(compression), pngText(resolveMetadata(metadata))); } /** - * Encodes the animation as animated WebP, lossless or (with a quality) lossy. Each frame is stored as the area that + * Encodes the animation as animated WebP, lossless or (with a quality below 100) lossy. Each frame is stored as the area that * changed since the frame before, identical frames are merged (unless the `optimize` option is false): the file * shows the same animation, but doesn't necessarily decode to the same frames - * @param options See {@link WebPAnimationEncodeOptions} - */ - async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }: WebPAnimationEncodeOptions = {}): Promise { - fitLoops(this.loopCount, 'WebP'); - this.__validate__(); - if (!this.length) throw new Error('An animation needs at least one frame'); + * @param options See {@link WebPAnimationEncodeOptions}; the loop count is the animation's {@link loopCount} (the + * streaming {@link webpEncoder} takes it as an option) + * @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than WebP stores + */ + async encodeWebP(options: WebPAnimationEncodeOptions = {}): Promise> { + checkOptions(options, 'animation.encodeWebP({ quality: 80 })'); + const { metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = options; + boolean(optimize, 'optimize'); + const loops = fitLoops(this.loopCount, 'WebP'); + this.__validate__('WebP'); const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality); const tolerance = lossy ? webp.lossyTolerance(lossy.quality) : undefined; - const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance }) : this.__webpFrames__(); - return webp.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), exifData(resolveMetadata(metadata)), lossy, effort); + const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance, maxDuration: maxDuration('WebP') }) : this.__webpFrames__(); + return webp.encodeAnimation(frames, this.width, this.height, toPlays(loops), exifData(resolveMetadata(metadata)), lossy, effort); } /** @@ -368,24 +624,14 @@ export class Animation extends Array { */ __webpFrames__(): webp.WebPEncodeFrame[] { const width = this.width, height = this.height; - // WebP knows no "previous" disposal and stores offsets halved: such animations are stored as full frames - const fullFrames = this.some(f => f.disposalMode === 'previous' || (f.disposalMode === 'background' && (f.xOffset & 1 || f.yOffset & 1))); - if (fullFrames) - return png.compositeAnimation({ width, height, frames: this.__apngFrames__() }) - .map(c => ({ x: 0, y: 0, width, height, duration: c.duration, dispose: true, pixels: c.pixels })); - - return Array.from(this, frame => { - let { xOffset: x, yOffset: y, width: w, height: h } = frame; - let pixels = new Uint8Array(frame.bitmap.buffer, frame.bitmap.byteOffset, frame.bitmap.byteLength); - // odd offsets: one transparent pixel more on the left/top (blending makes it invisible) - if (x & 1 || y & 1) { - const dx = x & 1, dy = y & 1; - const padded = new Uint8Array((w + dx) * (h + dy) * 4); - for (let row = 0; row < h; row++) padded.set(pixels.subarray(row * w * 4, (row + 1) * w * 4), ((row + dy) * (w + dx) + dx) * 4); - pixels = padded; - x -= dx; y -= dy; w += dx; h += dy; - } - return { x, y, width: w, height: h, duration: frame.duration, dispose: frame.disposalMode === 'background', pixels }; + // WebP knows no "previous" disposal and stores offsets halved: from the first frame it can't store as it is, + // the frames are stored as the canvas they show, replacing it (like the streaming encoder, the same file) + const compositor = new Compositor(width, height); + let full = false; + return this.__apngFrames__().map(f => { + const shown = compositor.push(f); + full ||= f.dispose === 2 || (f.dispose === 1 && !!(f.x & 1 || f.y & 1)); + return full ? { x: 0, y: 0, width, height, duration: f.duration, dispose: true, blend: false, pixels: shown } : webpFrame(f); }); } @@ -405,7 +651,7 @@ export class Animation extends Array { */ __apngFrames__(): png.APNGFrame[] { const dispose = [0, 0, 2, 1]; - return Array.from(this, frame => ({ + return Array.from(this.__clipped_frames__(), frame => ({ x: frame.xOffset, y: frame.yOffset, width: frame.width, @@ -413,7 +659,7 @@ export class Animation extends Array { duration: frame.duration, dispose: dispose[frame.__disposal_id__], blend: 1, - pixels: new Uint8Array(frame.bitmap.buffer, frame.bitmap.byteOffset, frame.bitmap.byteLength) + pixels: new Uint8Array(frame.image.bitmap.buffer, frame.image.bitmap.byteOffset, frame.image.bitmap.byteLength) })); } @@ -421,22 +667,31 @@ export class Animation extends Array { * An encoder that makes an animated WebP a frame at a time, like {@link Animation.encodeWebP} (the same file), * without keeping the frames in memory: `await encoder.add(frame)` for each frame (a {@link Frame}, or an image * with `{ duration }`), then `await encoder.finish()` for the file - * @param width The canvas width - * @param height The canvas height + * @example + * ```ts + * const encoder = Animation.webpEncoder(64, 64, { quality: 80 }); + * for (const color of [0xff0000ff, 0x00ff00ff, 0x0000ffff]) + * await encoder.add(new Image(64, 64).fill(color), { duration: 200 }); + * const webp = await encoder.finish(); + * ``` + * @param width The canvas width in pixels (a fraction is truncated, like the size of an image) + * @param height The canvas height in pixels (a fraction is truncated) * @param options See {@link WebPAnimationEncodeOptions}, and {@link AnimationOptions.loopCount} */ static webpEncoder(width: number, height: number, options: WebPAnimationEncodeOptions & AnimationOptions = {}): AnimationEncoder { + checkOptions(options, 'Animation.webpEncoder(width, height, { quality: 80 })'); return AnimationEncoder.__webp__(width, height, options); } /** * An encoder that makes an animated GIF a frame at a time, like {@link Animation.encodeGIF} (the same file), * without keeping the frames in memory: `await encoder.add(frame)` for each frame, then `await encoder.finish()` - * @param width The canvas width - * @param height The canvas height - * @param options See {@link GIFEncodeOptions}, and {@link AnimationOptions.loopCount} + * @param width The canvas width in pixels (a fraction is truncated, like the size of an image) + * @param height The canvas height in pixels (a fraction is truncated) + * @param options See {@link GIFAnimationEncodeOptions}, and {@link AnimationOptions.loopCount} */ - static gifEncoder(width: number, height: number, options: GIFEncodeOptions & AnimationOptions = {}): AnimationEncoder { + static gifEncoder(width: number, height: number, options: GIFAnimationEncodeOptions & AnimationOptions = {}): AnimationEncoder { + checkOptions(options, 'Animation.gifEncoder(width, height, { colors: 64 })'); return AnimationEncoder.__gif__(width, height, options); } @@ -444,110 +699,140 @@ export class Animation extends Array { * An encoder that makes an APNG a frame at a time, like {@link Animation.encodeAPNG} (the same file), keeping the * frames only compressed (the pixel format depends on all of them): `await encoder.add(frame)` for each frame, * then `await encoder.finish()` - * @param width The canvas width - * @param height The canvas height + * @param width The canvas width in pixels (a fraction is truncated, like the size of an image) + * @param height The canvas height in pixels (a fraction is truncated) * @param options See {@link APNGEncodeOptions}, and {@link AnimationOptions.loopCount} */ static apngEncoder(width: number, height: number, options: APNGEncodeOptions & AnimationOptions = {}): AnimationEncoder { + checkOptions(options, 'Animation.apngEncoder(width, height, { compression: 9 })'); return AnimationEncoder.__apng__(width, height, options); } /** * Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame) + * @example + * ```ts + * const animation = await Animation.decode(gifBytes); + * const webp = await animation.resize({ width: 320 }).encodeWebP({ quality: 75 }); + * ``` + * @remarks A still image becomes one frame of 100 ms, the {@link Frame} default. An AVIF image sequence is decoded as + * its first frame only. A file that is cut off keeps the frames that arrived whole (like browsers show it) and + * throws when not even the first one did * @param input The binary data to decode - * @param options See {@link AnimationDecodeOptions} + * @param options See {@link DecodeOptions} + * @throws {@link LimitError} if the frames have more than `options.maxPixels` pixels together + * @throws `Error` if the data isn't a supported image, or is damaged or cut off before its first whole frame */ - static decode(input: BinaryData, options?: AnimationDecodeOptions): Promise; - /** - * Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame) - * @param input The binary data to decode - * @param onlyExtractFirstFrame Whether to stop decoding after the first frame - * @deprecated Pass {@link AnimationDecodeOptions} instead, the positional arguments will be removed in 4.0 - */ - static decode(input: BinaryData, onlyExtractFirstFrame?: boolean): Promise; - static async decode(input: BinaryData, onlyFirstFrameOrOptions: boolean | AnimationDecodeOptions = false): Promise { + static decode(input: BinaryData, options?: DecodeOptions): Promise; + static async decode(input: BinaryData, options: DecodeOptions = {}): Promise { // (checked outside of decoding(), which reports RangeErrors as damaged data) - if (isOptions(onlyFirstFrameOrOptions)) { - const { maxPixels = MAX_PIXELS, threads = 1 } = onlyFirstFrameOrOptions; - if (!Number.isInteger(threads) || threads < 1) throw new RangeError(`threads must be a positive integer, not ${threads}`); - if (!(Number(maxPixels) > 0)) throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`); - const { toneMapping = 'reinhard' } = onlyFirstFrameOrOptions; - if (toneMapping !== 'reinhard' && toneMapping !== 'clamp') throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`); - } - return decoding(() => Animation.__decode__(input, onlyFirstFrameOrOptions)); + checkOptions(options, 'Animation.decode(data, { maxPixels: 1e8 })'); + const { maxPixels = MAX_PIXELS, threads = 1 } = options; + checkThreads(threads); + pixelLimit(maxPixels); + const { toneMapping = 'reinhard' } = options; + oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping'); + return decoding(() => Animation.__decode__(input, options)); + } + + /** @internal @ignore */ + static __is_animated__(animation: Animation): boolean { + return animation.__animationSignal__; } /** * @internal * @ignore */ - private static async __decode__(input: BinaryData, onlyFirstFrameOrOptions: boolean | AnimationDecodeOptions): Promise { - const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS, applyColorProfile = true, threads = Math.max(1, Math.min(availableThreads(), 8)), applyOrientation = true, toneMapping = 'reinhard', gainMap = true } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions }; + private static async __decode__(input: BinaryData, options: DecodeOptions): Promise { + const { maxPixels = MAX_PIXELS, applyColorProfile = true, threads = Math.max(1, Math.min(availableThreads(), 8)), applyOrientation = true, toneMapping = 'reinhard', gainMap = true } = options; + boolean(applyOrientation, 'applyOrientation'); + boolean(applyColorProfile, 'applyColorProfile'); + boolean(gainMap, 'gainMap'); const orient = (frames: Frame[], orientation: number): Frame[] => { - if (applyOrientation && orientation > 1) for (const frame of frames) frame.__orient__(orientation); + if (applyOrientation && orientation > 1) for (const frame of frames) frame.image.__orient__(orientation); return frames; }; const profile = (frames: Frame[], icc: Uint8Array | undefined, space?: jxl.ColorSpace): Frame[] => { const transform = !applyColorProfile ? null : icc ? profileTransform(icc) : space ? colorSpaceTransform(space.xy, space.curve) : null; - if (transform) for (const frame of frames) transform(frame.bitmap); + if (transform) for (const frame of frames) transform(frame.image.bitmap); return frames; }; const data = view(input); const type = ImageType.getType(data); - if (type === 'gif') return Animation.__fromGIF__(data, onlyExtractFirstFrame, Animation, maxPixels); + if (type === 'gif') return Animation.__gifFrames__(data, maxPixels); if (type === 'webp') { - const decoded = webp.decodeAnimation(data, onlyExtractFirstFrame, maxPixels); + const animated = webp.isAnimated(data); + const decoded = webp.decodeAnimation(data, false, maxPixels); const frames = orient(profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc), decoded.orientation); - return new Animation(frames, fromPlays(decoded.loopCount)); + const animation = new Animation(frames, { loopCount: fromPlays(decoded.loopCount), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height }); + animation.__animationSignal__ = animated; + // (a still image has no duration: the frame's default) + if (!animated) for (const frame of frames) frame.duration = 100; + return animation; } // (still PNGs decode like images) if (type === 'png' && !png.isAnimated(data)) { const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile }); - return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 0 }]), -1); + return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 100 }]), { loopCount: Infinity, width: image.width, height: image.height }); } if (type === 'png') { - const decoded = await png.decodeAnimation(data, onlyExtractFirstFrame, maxPixels); - const frames = orient(profile(canvasFrames(decoded.width, decoded.height, png.compositeAnimation(decoded)), decoded.icc), decoded.orientation); - return new Animation(frames, decoded.frames.length > 1 ? fromPlays(decoded.plays) : -1); + const decoded = await png.decodeAnimation(data, false, maxPixels); + // (composited as they are decoded: the raw frames don't pile up) + const step = png.compositor(decoded.width, decoded.height), shown: Array<{ pixels: Uint8Array, duration: number }> = []; + for await (const frame of decoded.frames) shown.push({ pixels: step(frame), duration: frame.duration }); + const frames = orient(profile(canvasFrames(decoded.width, decoded.height, shown), decoded.icc), decoded.orientation); + const animation = new Animation(frames, { loopCount: fromPlays(decoded.plays), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height }); + animation.__animationSignal__ = true; + return animation; } if (type === 'jxl') { const frames: Frame[] = []; - let loopCount = -1, icc: Uint8Array | undefined, space: jxl.ColorSpace | undefined; + let loops = Infinity, animated = false, icc: Uint8Array | undefined, space: jxl.ColorSpace | undefined; let orientation = 1; for await (const decoded of jxl.frames(data, maxPixels, toneMapping, threads)) { - const frame = new Frame(decoded.width, decoded.height, decoded.duration, 0, 0, FrameDisposalModes.BACKGROUND); - frame.bitmap = decoded.pixels; - frames.push(frame); + const image = new Image(decoded.width, decoded.height); + image.bitmap = alignedPixels(decoded.pixels); + frames.push(new Frame(image, { duration: decoded.duration, disposalMode: 'background' })); + // (all frames count, like those of the other formats) + checkPixels(decoded.width, decoded.height, maxPixels, frames.length); orientation = decoded.orientation; - loopCount = fromPlays(decoded.loopCount); + loops = fromPlays(decoded.loopCount); + animated ||= decoded.animated; icc = decoded.icc; space = decoded.colorSpace; - if (onlyExtractFirstFrame) break; } // (a gain map that can't be read leaves the frames without one, it doesn't fail the decoding) const map = gainMap && data[0] !== 0xff ? await jxl.decodeGainMap(data, maxPixels).catch(() => undefined) : undefined; if (map) for (const frame of frames) { const image = new Image(map.width, map.height); image.bitmap = map.pixels.slice(); - frame.gainMap = GainMap.__from_pixels__(image, map.params); + frame.image.gainMap = GainMap.__from_pixels__(image, map.params); } for (const frame of orient(profile(frames, icc, space), orientation)) { - const mapOfFrame = frame.gainMap; + const mapOfFrame = frame.image.gainMap; if (!mapOfFrame || !applyOrientation || orientation <= 1) continue; try { mapOfFrame.image = mapOfFrame.image.__orient__(orientation); } catch { - frame.gainMap = null; + frame.image.gainMap = null; } } - return new Animation(frames, frames.length > 1 ? loopCount : -1); + const animation = new Animation(frames, { loopCount: animated ? loops : Infinity, ...(frames.length ? { width: frames[0].width, height: frames[0].height } : {}) }); + animation.__animationSignal__ = animated; + // (a still image has no duration: the frame's default) + if (!animated) for (const frame of frames) frame.duration = 100; + return animation; } - if (type) return new Animation([Frame.from(await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile, toneMapping, gainMap, threads }), 0)]); + if (type) { + const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile, toneMapping, gainMap, threads }); + return new Animation([new Frame(image)], { width: image.width, height: image.height }); + } throw new Error('Unsupported image type'); } @@ -555,17 +840,13 @@ export class Animation extends Array { * @internal * @ignore */ - static __fromGIF__(data: Uint8Array, onlyExtractFirstFrame: boolean, Class: new (frames: Frame[], loopCount: number) => T, maxPixels = MAX_PIXELS): Promise { - return decoding(() => Animation.__gifFrames__(data, onlyExtractFirstFrame, Class, maxPixels)); - } - - /** - * @internal - * @ignore - */ - private static __gifFrames__(data: Uint8Array, onlyExtractFirstFrame: boolean, Class: new (frames: Frame[], loopCount: number) => T, maxPixels: number): T { - const decoded = gifCodec.decode(data, onlyExtractFirstFrame, maxPixels); + private static __gifFrames__(data: Uint8Array, maxPixels: number): Animation { + const decoded = gifCodec.decode(data, false, maxPixels); const frames = gifCodec.composite(decoded).map(({ pixels, delay }) => ({ pixels, duration: 10 * delay })); - return new Class(canvasFrames(decoded.width, decoded.height, frames), decoded.loopCount); + const animation = new Animation(canvasFrames(decoded.width, decoded.height, frames), { loopCount: decoded.loopCount, width: decoded.width, height: decoded.height }); + animation.__animationSignal__ = decoded.hasLoopExtension; + return animation; } } + +describe(Animation, animation => ({ width: animation.width, height: animation.height, duration: animation.duration, frames: animation.frames.length })); diff --git a/src/codecs/av1/decode.ts b/src/codecs/av1/decode.ts index b7e9392c..198e885a 100644 --- a/src/codecs/av1/decode.ts +++ b/src/codecs/av1/decode.ts @@ -220,7 +220,7 @@ export class TileDecoder { private aPalSz: Uint8Array; private lPalSz = new Uint8Array(32); private aPalSzUv: Uint8Array; private lPalSzUv = new Uint8Array(32); private aPartition: Uint8Array; private lPartition = new Uint8Array(16); - // palettes of the neighbours: [position][plane][8] + // palettes of the neighbors: [position][plane][8] private aPal: Uint16Array; private lPal = new Uint16Array(32 * 24); private pal = new Uint16Array(24); @@ -600,7 +600,7 @@ export class TileDecoder { const segmentation = hdr.segmentation; let seg = null as null | typeof segmentation.data[0]; const readSegId = (): void => { - // predicted from the neighbours' segments + // predicted from the neighbors' segments const map = f.segMap, s = f.b4Stride, o = by * s + bx; let segCtx: number, pred: number; if (haveLeft && haveTop) { @@ -1433,7 +1433,7 @@ export class TileDecoder { const eobTok = m.symbol(cdf, eobCdf + ctx * 4, 2); let tok = eobTok + 1; let levelTok = tok * 0x41; - let mag = 0; + let mag: number; let scanTable: Uint16Array | null = null, stride: number, shift: number, shift2: number, mask: number, offsets = 0; if (txClass === TX_CLASS_2D) { diff --git a/src/codecs/av1/encode.ts b/src/codecs/av1/encode.ts index 4cbdb7e9..b85b3e16 100644 --- a/src/codecs/av1/encode.ts +++ b/src/codecs/av1/encode.ts @@ -762,7 +762,7 @@ class TileEncoder { return null; } - // the mode contexts of a block (the smooth modes of the neighbours change the edges' filters) + // the mode contexts of a block (the smooth modes of the neighbors change the edges' filters) private modeContexts(bs: number, b: Block): void { const bx4 = this.bx, by4 = this.by & 31, aw = 1 << bdim(bs, 2), lh = 1 << bdim(bs, 3); this.aMode.fill(b.yMode, bx4, bx4 + aw); @@ -1020,7 +1020,7 @@ class TileEncoder { const sx = plane ? this.ssx : 0, sy = plane ? this.ssy : 0; // (the visible part) const vw = Math.max(0, Math.min(w, (f.width + sx >> sx) - px)), vh = Math.max(0, Math.min(h, (f.height + sy >> sy) - py)); - let eob = -1; + let eob: number; if (!(this.w && b.skip)) { const res = this.res, coefs = this.coefs, q = this.q; let sse = 0; @@ -1286,7 +1286,7 @@ class TileEncoder { } } - // a plane's palette (Y or U): its size, the colors of the neighbours' palettes it uses, the others (increasing: + // a plane's palette (Y or U): its size, the colors of the neighbors' palettes it uses, the others (increasing: // the first one's bits, then the differences); like the decoder's readPalPlane private writePalPlane(b: Block, pl: number, szCtx: number, bx4: number, by4: number): void { const w = this.w as SymbolEncoder, palSz = b.palSz[pl]; diff --git a/src/codecs/av1/ipred.ts b/src/codecs/av1/ipred.ts index 3f3fcbdd..acb07efb 100644 --- a/src/codecs/av1/ipred.ts +++ b/src/codecs/av1/ipred.ts @@ -10,7 +10,7 @@ import { SM_WEIGHTS, DR_INTRA_DERIVATIVE, FILTER_INTRA_TAPS } from './tables.ts'; -/** Flags or'd into the angle: filter the edges, the edges are smooth (a neighbour uses smooth prediction) */ +/** Flags or'd into the angle: filter the edges, the edges are smooth (a neighbor uses smooth prediction) */ export const ANGLE_USE_EDGE_FILTER = 1024, ANGLE_SMOOTH_EDGE = 512; /** The edge buffer: the top left pixel at EDGE, the top (and top right) after it, the left (and bottom left) before */ diff --git a/src/codecs/av1/palette.ts b/src/codecs/av1/palette.ts index e9d5d9e0..9aafaf02 100644 --- a/src/codecs/av1/palette.ts +++ b/src/codecs/av1/palette.ts @@ -44,7 +44,7 @@ const ORDER = new Uint8Array(8); /** * Visits the color indices of a palette block (w x h of t, rows of stride) after the first, in the decoder's wavefront - * order: with the context and the index's rank in the order of its neighbours' colors (the symbol) + * order: with the context and the index's rank in the order of its neighbors' colors (the symbol) */ export function colorRanks(t: Uint8Array, stride: number, w: number, h: number, visit: (ctx: number, rank: number) => void): void { const order = ORDER; diff --git a/src/codecs/av1/tables.ts b/src/codecs/av1/tables.ts index f186a0eb..6af1aa6e 100644 --- a/src/codecs/av1/tables.ts +++ b/src/codecs/av1/tables.ts @@ -26,7 +26,7 @@ export const TX_4X4 = 0, TX_8X8 = 1, TX_16X16 = 2, TX_32X32 = 3, TX_64X64 = 4, R export const DCT_DCT = 0, IDTX = 9, WHT_WHT = 16; export const TX_CLASS_2D = 0, TX_CLASS_H = 1, TX_CLASS_V = 2; -// which neighbouring edges an intra predicted block can use +// which neighboring edges an intra predicted block can use export const EDGE_I444_TOP_HAS_RIGHT = 1, EDGE_I422_TOP_HAS_RIGHT = 2, EDGE_I420_TOP_HAS_RIGHT = 4, EDGE_I444_LEFT_HAS_BOTTOM = 8, EDGE_I422_LEFT_HAS_BOTTOM = 16, EDGE_I420_LEFT_HAS_BOTTOM = 32, EDGE_ALL_TOP_HAS_RIGHT = 7, EDGE_ALL_LEFT_HAS_BOTTOM = 56, EDGE_ALL_TR_AND_BL = 63; diff --git a/src/codecs/avif-enc.ts b/src/codecs/avif-enc.ts index e14512e4..2514d2b1 100644 --- a/src/codecs/avif-enc.ts +++ b/src/codecs/avif-enc.ts @@ -6,6 +6,7 @@ */ import { encodeAV1, encodeAV1Threaded, type AV1Image, type AV1Params } from './av1/encode.ts'; import { startThreads } from '../util/threads.ts'; +import { checkFormatSize } from '../util/limits.ts'; import { writeISO, type Params } from './gainmap.ts'; /** Options of the AVIF encoder */ @@ -22,7 +23,7 @@ export interface AVIFOptions { exif?: Uint8Array; /** at most this many worker threads (1: none) */ threads: number; - /** a gain map (RGBA, grey for one for all channels), written as a tone mapped derived item like libavif does */ + /** a gain map (RGBA, gray for one for all channels), written as a tone mapped derived item like libavif does */ gainMap?: { pixels: Uint8Array, width: number, height: number, params: Params, quality: number }; } @@ -118,7 +119,7 @@ function fillTransparent(rgba: Uint8Array, width: number, height: number): Uint8 } colors = next; } - // (the transparent pixels smoothed: a few passes of averaging with their neighbours) + // (the transparent pixels smoothed: a few passes of averaging with their neighbors) const unknown: number[] = []; for (let i = 0; i < width * height; i++) if (!rgba[4 * i + 3]) unknown.push(i); for (let pass = 0; pass < 4; pass++) { @@ -182,9 +183,9 @@ function seqMonochrome(d: Uint8Array, o: number): boolean { } /** Encodes RGBA pixels as an AVIF (with an alpha image if the image has transparency) */ -export async function encode(rgba: Uint8Array, width: number, height: number, { quality, alphaQuality, subsampling, effort, exif, threads: maxThreads, gainMap }: AVIFOptions): Promise { +export async function encode(rgba: Uint8Array, width: number, height: number, { quality, alphaQuality, subsampling, effort, exif, threads: maxThreads, gainMap }: AVIFOptions): Promise> { if (width < 1 || height < 1) throw new RangeError('AVIF: dimensions must be at least 1'); - if (width > 65536 || height > 65536) throw new RangeError('AVIF: dimensions must be at most 65536'); + checkFormatSize('AVIF', width, height, 65536); let opaque = true; for (let i = 3; i < rgba.length; i += 4) if (rgba[i] !== 255) { opaque = false; break; } // (lossy: the colors of transparent pixels don't matter, the cheapest are smooth ones) @@ -218,7 +219,7 @@ export async function encode(rgba: Uint8Array, width: number, height: number, { return encodeAV1(image, params); }; let color: Uint8Array, alpha: Uint8Array | null = null, map: Uint8Array | null = null; - // (the gain map: monochrome if grey, else 4:4:4, its values as they are, no transfer) + // (the gain map: monochrome if gray, else 4:4:4, its values as they are, no transfer) let mapGray = true; if (gainMap) for (let i = 0; i < gainMap.pixels.length; i += 4) if (gainMap.pixels[i] !== gainMap.pixels[i + 1] || gainMap.pixels[i] !== gainMap.pixels[i + 2]) { mapGray = false; break; } try { @@ -263,8 +264,9 @@ export async function encode(rgba: Uint8Array, width: number, height: number, { type: 'av01', name: 'GMap', hidden: true, data: [map], props: [property(fullBox('ispe', 0, 0, u32(gainMap.width), u32(gainMap.height))), property(av1C(map)) | 0x80, property(nclx(MAP_CICP)), property(pixi(mapGray ? 1 : 3))] }); - // (the HDR rendition's colors: the image's primaries with PQ's transfer, like avifenc assumes for JPEG gain maps) - tmapId = items.push({ type: 'tmap', name: 'TMap', data: [[0], writeISO(gainMap.params)], props: [ispe, property(nclx([cicp[0], 16, cicp[2]]))] }); + // (the HDR rendition's colors: those of the decoded file, else the image's primaries with PQ's transfer, like + // avifenc assumes for JPEG gain maps) + tmapId = items.push({ type: 'tmap', name: 'TMap', data: [[0], writeISO(gainMap.params)], props: [ispe, property(nclx(gainMap.params.alternate ?? [cicp[0], 16, cicp[2]]))] }); } const exifId = exif?.length ? items.push({ type: 'Exif', name: 'Exif', data: [u32(0), exif], props: [] }) : 0; const sizes = items.map(item => item.data.reduce((n, d) => n + d.length, 0)); diff --git a/src/codecs/avif.ts b/src/codecs/avif.ts index 95c4f67b..1e878daa 100644 --- a/src/codecs/avif.ts +++ b/src/codecs/avif.ts @@ -406,7 +406,7 @@ function convertRowSubsampled(c: Conversion, j: number): void { for (let i = 0, p = j * width * 4; i < width; i++, p += 4) { const lum = tableY[Y[yRow + i]]; // bilinear: the nearest chroma sample, the ones next to it in the row and column, the diagonal one - const o = uvRow + (i >> 1), adjCol = i === 0 || i === width - 1 && i % 2 ? 0 : i % 2 ? 1 : -1; + const o = uvRow + (i >> 1), adjCol = i === 0 || i === width - 1 ? 0 : i % 2 ? 1 : -1; const cb = f32(f32(f32(w9[U[o]] + w3[U[o + adjCol]]) + w3[U[o + adjRow]]) + w1[U[o + adjCol + adjRow]]); const cr = f32(f32(f32(w9[V[o]] + w3[V[o + adjCol]]) + w3[V[o + adjRow]]) + w1[V[o + adjCol + adjRow]]); out[p] = toByte(f32(lum + f32(cr2 * cr))); @@ -437,7 +437,7 @@ function convertRow(c: Conversion, j: number): void { cr = tableUV[V[o]]; } else { // bilinear: the nearest chroma sample, the ones next to it in the row and column, the diagonal one - const adjCol = i === 0 || i === width - 1 && i % 2 ? 0 : i % 2 ? 1 : -1; + const adjCol = i === 0 || i === width - 1 ? 0 : i % 2 ? 1 : -1; cb = f32(f32(f32(f32(tableUV[U[o]] * 0.5625) + f32(tableUV[U[o + adjCol]] * 0.1875)) + f32(tableUV[U[o + adjRow]] * 0.1875)) + f32(tableUV[U[o + adjCol + adjRow]] * 0.0625)); cr = f32(f32(f32(f32(tableUV[V[o]] * 0.5625) + f32(tableUV[V[o + adjCol]] * 0.1875)) + @@ -661,6 +661,12 @@ async function decodeGainMap(d: Uint8Array, primary: number, items: Map box.type === 'colr' && box.end - box.start >= 11 && fourcc(d, box.start) === 'nclx')) { + applyColr(d, tmap, colors); + params.alternate = [colors.primaries, colors.transfer, colors.matrix]; + } const yuv = await decodeItem(d, mapItem, items, idat, maxPixels, null); applyColr(d, mapItem, yuv); // (its values as they are: no transfer function to tone map) diff --git a/src/codecs/bmp.ts b/src/codecs/bmp.ts index f618c149..abc14700 100644 --- a/src/codecs/bmp.ts +++ b/src/codecs/bmp.ts @@ -201,8 +201,10 @@ export function decodeDIB(d: Uint8Array, o: number, pixelOffset: number | null, : (a << 24 | sample(cb, v) << 16 | sample(cg, v) << 8 | sample(cr, v)) >>> 0; } } - // an alpha channel that is zero everywhere is unused (writers that don't know about it leave it zero) - if (ca.max && !alphaSeen) for (let i = 0; i < out.length; i++) out[i] |= 0xff000000; + // an alpha channel that is zero everywhere is unused when the header doesn't declare it (writers that don't know + // about it leave it zero: the implicit alpha of 32-bit icons); a declared mask (bit fields, as encode() writes) is + // what it says + if (ca.max && !alphaSeen && !info.masks) for (let i = 0; i < out.length; i++) out[i] |= 0xff000000; if (ico && bits === 32 && alphaSeen) return { width, height, pixels }; } @@ -264,7 +266,7 @@ export function decode(d: Uint8Array, maxPixels = MAX_PIXELS): Decoded { * Encodes RGBA pixels into a BMP: a palette of 2, 16 or 256 colors if an opaque image has at most that many, else * 24 bit pixels, or 32 bit ones with an alpha mask (a version 4 header) if the image has transparency */ -export function encode(rgba: Uint8Array, width: number, height: number): Uint8Array { +export function encode(rgba: Uint8Array, width: number, height: number): Uint8Array { if (width < 1 || height < 1) throw new RangeError('BMP: dimensions must be at least 1'); const count = width * height; if (rgba.byteOffset % 4) rgba = rgba.slice(0, count * 4); diff --git a/src/codecs/gainmap.ts b/src/codecs/gainmap.ts index 645a0d6b..9dfbf05b 100644 --- a/src/codecs/gainmap.ts +++ b/src/codecs/gainmap.ts @@ -22,6 +22,8 @@ export interface Params { capacityMax: number; /** whether the gains apply in the base image's color space (else the HDR image's) */ useBaseColorSpace: boolean; + /** the HDR rendition's colors as AVIF's tone mapped item gives them (primaries, transfer, matrix), kept for its encode */ + alternate?: [number, number, number]; } const XMP_NAMESPACE = 'http://ns.adobe.com/xap/1.0/\0'; @@ -398,7 +400,7 @@ const segmentBytes = (marker: number, body: Uint8Array): Uint8Array => { out.set(body, 4); return out; }; -const join = (parts: Uint8Array[]): Uint8Array => { +const join = (parts: Uint8Array[]): Uint8Array => { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let o = 0; for (const p of parts) { @@ -424,14 +426,14 @@ export function stripMetadata(jpeg: Uint8Array): Uint8Array { } // inserts segments after a JPEG's APP0 (JFIF) segment if it starts with one, else after SOI -function insert(jpeg: Uint8Array, added: Uint8Array[]): Uint8Array { +function insert(jpeg: Uint8Array, added: Uint8Array[]): Uint8Array { let at = 2; if (jpeg[2] === 0xff && jpeg[3] === 0xe0) at = 4 + (jpeg[4] << 8 | jpeg[5]); return join([jpeg.subarray(0, at), ...added, jpeg.subarray(at)]); } /** A gain map JPEG with its metadata (hdrgm XMP and ISO 21496-1), from its compressed pixels */ -export function mapWithMetadata(body: Uint8Array, p: Params): Uint8Array { +export function mapWithMetadata(body: Uint8Array, p: Params): Uint8Array { const added = [segmentBytes(0xe1, join([ascii(XMP_NAMESPACE), ascii(writeMapXMP(p))])), segmentBytes(0xe2, join([ascii(ISO_NAMESPACE), writeISO(p)]))]; return insert(stripMetadata(body), added); } @@ -448,7 +450,7 @@ export function primarySegments(mapLength: number): Uint8Array[] { } /** Fills in the primary's MPF index (big endian like libultrahdr) and appends the gain map */ -export function finish(primary: Uint8Array, map: Uint8Array): Uint8Array { +export function finish(primary: Uint8Array, map: Uint8Array): Uint8Array { const mpf = segments(primary).find(({ marker, body }) => marker === 0xe2 && startsWith(body, 0, MPF_SIGNATURE)); if (!mpf) throw new Error('JPEG: missing MPF segment'); const tiff = mpf.start + 4 + 4; diff --git a/src/codecs/gif.ts b/src/codecs/gif.ts index 6b5e8424..a46657bf 100644 --- a/src/codecs/gif.ts +++ b/src/codecs/gif.ts @@ -1,6 +1,7 @@ import { ByteWriter } from '../util/bytes.ts'; +import type { DitherMethod } from '../image.ts'; import { quantize } from './quantize.ts'; -import { MAX_PIXELS, PixelBudget, checkPixels } from '../util/limits.ts'; +import { MAX_PIXELS, FRAME_PIXELS, PixelBudget, checkPixels } from '../util/limits.ts'; // ImageScript disposal modes (any, keep, previous, background) <-> GIF disposal methods (unspecified, none, background, previous) const DISPOSAL_TO_GIF = [0, 1, 3, 2]; @@ -8,6 +9,7 @@ const DISPOSAL_FROM_GIF = [0, 1, 3, 2, 0, 0, 0, 0]; const MAX_CODE = 4095; const UNEXPECTED_END = new Error('GIF: unexpected end of data'); +const EMPTY = new Uint8Array(0); export interface GIFFrame { x: number; @@ -25,7 +27,7 @@ export interface GIFFrame { export interface GIFData { width: number; height: number; - /** -1 loops forever, 0 plays once, n repeats n times */ + /** Infinity loops forever, 0 plays once, n repeats n times */ loopCount: number; frames: GIFFrame[]; } @@ -51,6 +53,7 @@ export interface DecodedGIF { width: number; height: number; loopCount: number; + hasLoopExtension: boolean; frames: DecodedGIFFrame[]; } @@ -60,22 +63,24 @@ interface GraphicControl { transparentIndex: number; } +/** The palette of every frame: its size (at most 256 colors, the transparent one included) and the dithering */ +export interface GIFPalette { + colors: number; + dither: DitherMethod; + strength: number; +} + /** - * Encodes frames into a GIF - * @param {{width: number, height: number, loopCount?: number, frames: GIFFrame[]}} gif loopCount -1 loops forever, 0 plays once, n repeats n times - * @param {number} [quality=95] 1-100, scales the palette size (1 = 8 colors, 50 = 55, 90 and above = 256) - * @return {Uint8Array} - */ -/** - * @param comments written as comment extensions + * Encodes frames into a GIF. `loopCount`: Infinity loops forever, 0 plays once (no loop extension), n repeats n times; + * `comments` are written as comment extensions */ -export function encode({ width, height, loopCount = -1, frames }: Omit & { loopCount?: number }, quality = 95, comments: Uint8Array[] = []): Uint8Array { +export function encode({ width, height, loopCount = Infinity, frames }: Omit & { loopCount?: number }, palette: GIFPalette, comments: Uint8Array[] = []): Uint8Array { // frames that restore the background have a transparent index: decoders like Pillow and ffmpeg restore to it // (browsers to transparent), otherwise to the background color. So does the first frame then: Pillow decides by it // whether the animation has transparency at all const restores = frames.some(frame => frame.dispose === 3); const parts = [header(width, height, loopCount, comments)]; - for (const [i, frame] of frames.entries()) parts.push(encodeFrame(frame, quality, frame.dispose === 3 || (i === 0 && restores))); + for (const [i, frame] of frames.entries()) parts.push(encodeFrame(frame, palette, frame.dispose === 3 || (i === 0 && restores))); parts.push(new Uint8Array([0x3b])); const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let offset = 0; @@ -99,7 +104,7 @@ export function header(width: number, height: number, loopCount: number, comment out.bytes(0x21, 0xff, 0x0b); out.string('NETSCAPE2.0'); out.bytes(0x03, 0x01); - out.u16(loopCount === -1 || loopCount === Infinity ? 0 : loopCount); + out.u16(loopCount === Infinity ? 0 : loopCount); out.bytes(0x00); } @@ -111,9 +116,9 @@ export function header(width: number, height: number, loopCount: number, comment } /** A frame (its graphic control extension, image descriptor, color table and pixels), with a transparent index if asked */ -export function encodeFrame(frame: GIFFrame, quality: number, transparent: boolean): Uint8Array { +export function encodeFrame(frame: GIFFrame, colors: GIFPalette, transparent: boolean): Uint8Array { const out = new GIFWriter(); - const { palette, indices, transparentIndex } = quantize(frame.pixels, frame.width, { quality, transparent }); + const { palette, indices, transparentIndex } = quantize(frame.pixels, frame.width, { maxColors: colors.colors, dither: colors.dither, ditherStrength: colors.strength, transparent }); const entries = palette.length / 3; const bits = Math.max(1, Math.ceil(Math.log2(entries))); @@ -219,10 +224,10 @@ function writeSubBlocks(out: GIFWriter, data: Uint8Array): void { /** * Decodes a GIF into its individual (uncomposited) frames, zero-sized images are skipped * @param {Uint8Array} data - * @param {boolean} [onlyFirstFrame=false] + * @param {boolean} [firstFrameOnly=false] * @return {{width: number, height: number, loopCount: number, frames: GIFFrame[]}} */ -export function decode(data: Uint8Array, onlyFirstFrame = false, maxPixels = MAX_PIXELS): DecodedGIF { +export function decode(data: Uint8Array, firstFrameOnly = false, maxPixels = MAX_PIXELS): DecodedGIF { const reader = new ByteReader(data); const signature = reader.string(6); @@ -237,25 +242,26 @@ export function decode(data: Uint8Array, onlyFirstFrame = false, maxPixels = MAX const frames: DecodedGIFFrame[] = []; let loopCount = 0; + let hasLoopExtension = false; let control: GraphicControl | null = null; // the frames' color indices, and later a canvas per frame - const budget = new PixelBudget(maxPixels); + const budget = new PixelBudget(maxPixels, firstFrameOnly ? 0 : FRAME_PIXELS); try { parse(); } catch (err) { - // truncated files keep every frame decoded so far, like browsers do - if (err !== UNEXPECTED_END) throw err; + // truncated files keep every frame decoded so far, like browsers do; one without a whole frame has no image + if (err !== UNEXPECTED_END || !frames.length) throw err; } checkPixels(width, height, maxPixels, Math.max(1, frames.length)); - return { width, height, loopCount, frames }; + return { width, height, loopCount, hasLoopExtension, frames }; function parse(): void { while (reader.offset < data.length) { const block = reader.u8(); - if (block === 0x3b) break; // trailer + if (block === 0x3b) return; // trailer if (block === 0x21) { const label = reader.u8(); @@ -275,12 +281,13 @@ export function decode(data: Uint8Array, onlyFirstFrame = false, maxPixels = MAX const id = reader.string(size); if (id === 'NETSCAPE2.0' || id === 'ANIMEXTS1.0') { + hasLoopExtension = true; // sub-block 1 holds the loop count for (let length; (length = reader.u8());) { const sub = reader.slice(length); if (sub[0] === 1 && length >= 3) { const count = sub[1] | sub[2] << 8; - loopCount = count === 0 ? -1 : count; + loopCount = count === 0 ? Infinity : count; } } } else skipSubBlocks(reader); @@ -291,7 +298,7 @@ export function decode(data: Uint8Array, onlyFirstFrame = false, maxPixels = MAX if (block !== 0x2c) { // unknown block, stop gracefully with whatever frames were decoded - if (frames.length) break; + if (frames.length) return; throw new Error(`GIF: unknown block type 0x${block.toString(16)}`); } @@ -329,8 +336,10 @@ export function decode(data: Uint8Array, onlyFirstFrame = false, maxPixels = MAX } frames.push({ x, y, width: fw, height: fh, delay, dispose, indices: ordered, colors, transparentIndex }); - if (onlyFirstFrame) break; + if (firstFrameOnly) return; } + // (no trailer: the data was cut off) + throw UNEXPECTED_END; } } @@ -362,6 +371,8 @@ export function composite({ width, height, frames }: DecodedGIF): Array<{ pixels } output.push({ pixels: new Uint8Array(canvas.slice().buffer), delay: frame.delay }); + // (its indices aren't needed anymore: let them go, so they don't add up with the composited frames) + frame.indices = EMPTY; if (frame.dispose === 3) { for (let y = y0; y < y1; y++) canvas.fill(0, y * width + x0, y * width + x1); @@ -454,11 +465,19 @@ function readSubBlocks(reader: ByteReader): Uint8Array { const blocks = []; let total = 0; - for (let length; reader.offset < reader.data.length && (length = reader.u8());) { + // (the terminating zero length block: without it the data was cut off, and the image data is incomplete) + let terminated = false; + while (reader.offset < reader.data.length) { + const length = reader.u8(); + if (!length) { + terminated = true; + break; + } const block = reader.slice(length); blocks.push(block); total += block.length; } + if (!terminated) throw UNEXPECTED_END; const out = new Uint8Array(total); let offset = 0; diff --git a/src/codecs/hdr.ts b/src/codecs/hdr.ts index f347eb8d..ef456344 100644 --- a/src/codecs/hdr.ts +++ b/src/codecs/hdr.ts @@ -16,7 +16,7 @@ function linearToSRGB(v: number): number { /** * Linear light RGB (3 values per pixel) as sRGB RGBA. Reinhard's extended operator ("Photographic Tone Reproduction - * for Digital Images", 2002, equation 4) without its automatic exposure, which makes dark scenes like nights grey: + * for Digital Images", 2002, equation 4) without its automatic exposure, which makes dark scenes like nights gray: * the luminance L becomes L (1 + L / Lw²) / (1 + L), the brightest pixel's (at least 1) Lw white, and the channels are * scaled by that, keeping their hue; images no brighter than white stay as they are */ diff --git a/src/codecs/jpeg.ts b/src/codecs/jpeg.ts index 303a3abd..9d094b77 100644 --- a/src/codecs/jpeg.ts +++ b/src/codecs/jpeg.ts @@ -6,7 +6,7 @@ */ import { ByteWriter } from '../util/bytes.ts'; -import { MAX_PIXELS, checkPixels } from '../util/limits.ts'; +import { MAX_PIXELS, checkPixels, checkFormatSize } from '../util/limits.ts'; import { orientation as exifOrientation } from './exif.ts'; import { concat } from '../util/mem.ts'; import { littleEndian } from '../util/alpha.ts'; @@ -19,7 +19,7 @@ const ZIGZAG = Int32Array.of( 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 ); -type Transform = 'grey' | 'rgb' | 'ycc' | 'ycck' | 'cmyk'; +type Transform = 'gray' | 'rgb' | 'ycc' | 'ycck' | 'cmyk'; interface HuffmanTable { /** (length << 8 | symbol) for codes up to 9 bits, 0 = slow path */ @@ -47,7 +47,7 @@ interface Component { * which the decoder turns into `plane` (the samples) as soon as the row is complete */ coefficients: Int16Array; - /** sequential: the sample plane, and which of its block rows are done (the others stay mid grey) */ + /** sequential: the sample plane, and which of its block rows are done (the others stay mid gray) */ plane?: Uint8Array; done?: Uint8Array; pred: number; @@ -85,7 +85,7 @@ function clamp8(v: number): number { /** * Decodes a JPEG into 8-bit RGBA pixel data * Supports baseline, extended and progressive huffman coded JPEGs with any - * sampling factors, restart intervals and greyscale, YCbCr, RGB, CMYK and YCCK color + * sampling factors, restart intervals and grayscale, YCbCr, RGB, CMYK and YCCK color * The output matches libjpeg's defaults (islow IDCT, fancy upsampling) * @param {Uint8Array} data * @param {{transform?: 'ycc'|'rgb'|'cmyk'}} [options] overrides the color transform detected from JFIF/Adobe markers (used by TIFF) @@ -104,6 +104,7 @@ export function decode(data: Uint8Array, { transform, maxPixels = MAX_PIXELS }: // the ICC profile's parts (APP2 ICC_PROFILE segments) by their sequence numbers const profile: Uint8Array[] = []; let restartInterval = 0; + let scans = 0; let pos = 2; const u16 = (offset: number): number => data[offset] << 8 | data[offset + 1]; @@ -173,9 +174,10 @@ export function decode(data: Uint8Array, { transform, maxPixels = MAX_PIXELS }: case 0xc0: case 0xc1: case 0xc2: { // SOF baseline, extended, progressive if (frame) throw new Error('JPEG: multiple frames are not supported'); + if (end - start < 6) throw new Error('JPEG: truncated frame header'); if (data[start] !== 8) throw new Error(`JPEG: ${data[start]}-bit precision is not supported`); checkPixels(u16(start + 3), u16(start + 1), maxPixels); - frame = createFrame(marker === 0xc2, u16(start + 1), u16(start + 3), data.subarray(start + 5, end)); + frame = createFrame(marker === 0xc2, u16(start + 1), u16(start + 3), data.subarray(start + 5, end), data.length - end); break; } @@ -233,6 +235,7 @@ export function decode(data: Uint8Array, { transform, maxPixels = MAX_PIXELS }: const successiveHigh = data[p + 2] >> 4; const successiveLow = data[p + 2] & 15; + scans++; pos = decodeScan(data, end, frame, components, restartInterval, spectralStart, spectralEnd, successiveHigh, successiveLow); continue; } @@ -242,12 +245,13 @@ export function decode(data: Uint8Array, { transform, maxPixels = MAX_PIXELS }: } if (!frame) throw new Error('JPEG: missing frame header'); + if (!scans) throw new Error('JPEG: no image data (the file is truncated)'); // (the profile only if no part is missing) const icc = profile.length && Array.from(profile).every(Boolean) ? concat(profile) : undefined; return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation, icc }; } -function createFrame(progressive: boolean, height: number, width: number, componentData: Uint8Array): Frame { +function createFrame(progressive: boolean, height: number, width: number, componentData: Uint8Array, available: number): Frame { const count = componentData[0]; const sampling: Array<{ id: number, h: number, v: number, tq: number }> = []; @@ -257,13 +261,21 @@ function createFrame(progressive: boolean, height: number, width: number, compon } if (!width || !sampling.length) throw new Error('JPEG: invalid dimensions'); - // (grey, YCbCr/RGB and CMYK have up to 4) + // (gray, YCbCr/RGB and CMYK have up to 4) if (sampling.length > 4) throw new Error(`JPEG: ${sampling.length} components are not supported`); const hmax = Math.max(...sampling.map(c => c.h)); const vmax = Math.max(...sampling.map(c => c.v)); const mcusPerLine = Math.ceil(width / (8 * hmax)); const mcusPerColumn = Math.ceil(height / (8 * vmax)); + // a sequential scan codes every block in 2 bits at least (a DC and an end-of-block code): a file with fewer bytes + // after the frame header than its blocks need is cut off, and is refused before the planes are allocated (a 19 KB + // file declaring 16383x16383 took 16 s and 1.1 GB to end the same way). Progressive scans can skip runs of blocks + if (!progressive) { + let blocks = 0; + for (const c of sampling) blocks += Math.ceil(Math.ceil(width * c.h / hmax) / 8) * Math.ceil(Math.ceil(height * c.v / vmax) / 8); + if (blocks * 2 > available * 8) throw new Error('JPEG: the scan data is truncated'); + } const components = sampling.map((c): Component => { const componentWidth = Math.ceil(width * c.h / hmax); @@ -320,18 +332,22 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: // bit reader state let pos = offset; let buffer = 0, bits = 0; + // the zero bytes fed after the scan's data ran out (the end of the file, or a marker): a scan that reads any of + // them is cut off + let padding = 0; const fill = (): void => { while (bits <= 24) { - let byte = 0; + let byte = 0, fed = false; if (pos < data.length) { byte = data[pos]; if (byte === 0xff) { const next = data[pos + 1]; if (next === 0x00) pos += 2; - else byte = 0; // marker reached, feed zeros + else fed = true; // marker reached, feed zeros } else pos++; - } + } else fed = true; + if (fed) { byte = 0; padding++; } buffer = buffer << 8 | byte; bits += 8; @@ -349,6 +365,9 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: return buffer >>> --bits & 1; }; + // corrupt entropy data (an invalid code): with restart markers, the rest of the interval is left empty and the next + // marker resyncs the decoder, like libjpeg does; without them, nothing can + let broken = false; const huffman = (table: HuffmanTable | undefined): number => { if (!table) throw new Error('JPEG: missing huffman table'); if (bits < 16) fill(); @@ -362,7 +381,11 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: let length = 10; let code = buffer >>> bits - 10 & 1023; while (code > table.maxCode[length]) { - if (++length > 16) throw new Error('JPEG: invalid huffman code'); + if (++length > 16) { + if (!restartInterval) throw new Error('JPEG: invalid huffman code'); + broken = true; + return 0; + } code = buffer >>> bits - length & (1 << length) - 1; } @@ -373,6 +396,11 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: const extend = (value: number, size: number): number => value < 1 << size - 1 ? value + (-1 << size) + 1 : value; const receiveExtend = (size: number): number => size ? extend(getBits(size), size) : 0; + // (the bits read are the real ones first, then the fed zeros: the ones still in the buffer are the last of those) + const checkComplete = (): void => { + if (padding * 8 > bits) throw new Error('JPEG: the scan data is truncated'); + }; + let eobrun = 0; const decodeBaseline = (component: Component, offset: number): void => { @@ -508,9 +536,9 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: const column = unit % component.blocksPerLine; if (sequential) { pending = row; - decodeBlock(component, column * 64); + if (!broken) decodeBlock(component, column * 64); if (column === component.blocksPerLine - 1) finish(); - } else decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64); + } else if (!broken) decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64); } else { const mcuRow = unit / frame.mcusPerLine | 0; const mcuColumn = unit % frame.mcusPerLine; @@ -521,7 +549,7 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: for (let h = 0; h < component.h; h++) { const row = sequential ? v : mcuRow * component.v + v; const column = mcuColumn * component.h + h; - decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64); + if (!broken) decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64); } if (sequential && mcuColumn === frame.mcusPerLine - 1) finish(); } @@ -529,12 +557,17 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: if (unit >= total) break; - // restart: discard remaining bits and expect an RSTn marker + // restart: discard remaining bits and expect an RSTn marker. An interval whose data ran out early (the zeros fed + // at the marker were read) is damage like a bad code when a marker follows, a cut-off scan when none does + const short = !broken && padding * 8 > bits; + broken = false; bits = 0; buffer = 0; + padding = 0; while (pos + 1 < data.length && !(data[pos] === 0xff && data[pos + 1] >= 0xd0 && data[pos + 1] <= 0xd7)) { // a different marker means the scan ended early if (data[pos] === 0xff && data[pos + 1] !== 0x00 && data[pos + 1] !== 0xff) { + if (short) throw new Error('JPEG: the scan data is truncated'); finish(); return pos; } @@ -542,6 +575,7 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: } if (pos + 1 >= data.length) { + if (short) throw new Error('JPEG: the scan data is truncated'); finish(); return pos; } @@ -550,6 +584,7 @@ function decodeScan(data: Uint8Array, offset: number, frame: Frame, components: for (const component of components) component.pred = 0; } + if (!broken) checkComplete(); finish(); return pos; } @@ -709,7 +744,7 @@ function idct(coefficients: Int16Array, offset: number, quantization: Int32Array // runs the IDCT over every block, producing the component's sample plane function buildPlane(component: Component): { plane: Uint8Array, stride: number } { const stride = component.blocksPerLineForMcu * 8; - // sequential: already rendered, the rows no scan reached are mid grey (what blocks without coefficients render to) + // sequential: already rendered, the rows no scan reached are mid gray (what blocks without coefficients render to) if (component.plane && component.done) { const { plane, done } = component; for (let row = 0; row < component.blocksPerColumn; row++) @@ -718,7 +753,7 @@ function buildPlane(component: Component): { plane: Uint8Array, stride: number } } const plane = new Uint8Array(stride * component.blocksPerColumnForMcu * 8); const workspace = new Int32Array(64); - // components without any scan data decode to mid grey + // components without any scan data decode to mid gray const quantization = component.quantization || new Int32Array(64); for (let row = 0; row < component.blocksPerColumn; row++) @@ -834,7 +869,7 @@ function output(frame: Frame, adobe: { transform: number } | null, jfif: boolean const count = components.length; let transform: Transform; - if (count === 1) transform = 'grey'; + if (count === 1) transform = 'gray'; else if (override && (count === 4) === (override === 'cmyk')) transform = override; else if (count === 3) { if (adobe) transform = adobe.transform === 0 ? 'rgb' : 'ycc'; @@ -846,15 +881,15 @@ function output(frame: Frame, adobe: { transform: number } | null, jfif: boolean const [p0, p1, p2, p3] = planes; // one loop per transform: deciding per pixel costs more than the conversion - if (transform === 'grey' || transform === 'rgb' || transform === 'ycc') { + if (transform === 'gray' || transform === 'rgb' || transform === 'ycc') { const s0 = p0.samples, s1 = (p1 ?? p0).samples, s2 = (p2 ?? p0).samples; - const grey = transform === 'grey', ycc = transform === 'ycc'; + const gray = transform === 'gray', ycc = transform === 'ycc'; // (YCbCr a pixel at a time as a 32-bit word, little endian) const words = littleEndian ? new Uint32Array(pixels.buffer) : null; for (let y = 0, o = 0; y < height; y++, o = y * width * 4) { for (const p of planes) p.fill?.(y); const r0 = y * p0.stride, r1 = p1 ? y * p1.stride : r0, r2 = p2 ? y * p2.stride : r0; - if (grey) for (let x = 0; x < width; x++, o += 4) { + if (gray) for (let x = 0; x < width; x++, o += 4) { pixels[o] = pixels[o + 1] = pixels[o + 2] = s0[r0 + x]; pixels[o + 3] = 0xff; } else if (ycc && words) for (let x = 0, w = o >> 2; x < width; x++, w++) { @@ -989,14 +1024,22 @@ export interface EncodeMetadata { comment?: Uint8Array; /** whole marker segments written after these (e.g. a gain map's XMP, ISO 21496-1 and MPF segments) */ segments?: Uint8Array[]; - /** a greyscale JPEG (one component, the luma of the pixels) */ - grey?: boolean; + /** a grayscale JPEG (one component, the luma of the pixels) */ + gray?: boolean; /** whether to keep the chroma at full resolution at any quality (else only above 90) */ 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'; + /** + * 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) + */ + rows?: (y: number) => void; } -export function encode(pixels: Uint8Array, width: number, height: number, quality = 90, { exif, comment, segments, grey = false, fullChroma = false }: EncodeMetadata = {}): Uint8Array { - if (!width || !height || width > 0xffff || height > 0xffff) throw new RangeError('JPEG: invalid dimensions'); +export function encode(pixels: Uint8Array, width: number, height: number, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, rows }: EncodeMetadata = {}): Uint8Array { + if (!width || !height) throw new RangeError('JPEG: invalid dimensions'); + checkFormatSize('JPEG', width, height, 0xffff); quality = Math.min(100, Math.max(1, Math.round(quality))); const scale = quality < 50 ? Math.floor(5000 / quality) : 200 - quality * 2; @@ -1006,8 +1049,8 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit // like libjpeg-turbo (cjpeg -optimize, -sample 1x1 above 90), byte for byte: its color conversion, downsampling, // integer DCT, quantization and padding - // (greyscale: like cjpeg -grayscale, one component, no subsampling) - const subsample = quality <= 90 && !grey && !fullChroma; + // (grayscale: like cjpeg -grayscale, one component, no subsampling) + const subsample = !gray && !fullChroma && (subsampling ? subsampling === '4:2:0' : quality <= 90); const hmax = subsample ? 2 : 1; const mcuSize = 8 * hmax; const mcusPerLine = Math.ceil(width / mcuSize); @@ -1024,10 +1067,12 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit const cbRows = subsample ? new Uint8Array(2 * rowWidth) : Cb, crRows = subsample ? new Uint8Array(2 * rowWidth) : Cr; // (pixels a 32-bit word at a time where they're aligned, little endian) - const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, width * height) : null; + const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, (rows ? width : width * height)) : null; for (let y = 0; y < height; y++) { + // (with `rows`, the pixels are the scratch row, filled first) + if (rows) rows(y); const row = subsample ? (y & 1) * rowWidth : y * CW; - let i = y * width * 4, o = y * W, c = row; + let i = rows ? 0 : y * width * 4, o = y * W, c = row; if (words) for (let x = 0, w = i >> 2; x < width; x++, w++, o++, c++) { const p = words[w], r = p & 255, g = p >> 8 & 255, b = p >> 16 & 255; @@ -1069,13 +1114,13 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit { plane: Cb, stride: CW, h: 1, v: 1, blocksX: chromaBlocksX, blocksY: chromaBlocksY, table: 1 }, { plane: Cr, stride: CW, h: 1, v: 1, blocksX: chromaBlocksX, blocksY: chromaBlocksY, table: 1 } ]; - const componentCount = grey ? 1 : 3; + const componentCount = gray ? 1 : 3; // quantized blocks in MCU order (Y blocks, then Cb, then Cr), their coefficients in zigzag order, with the index // of each block's last nonzero coefficient. MCUs reaching past a component's blocks get dummy blocks (jccoefct.c): // without AC coefficients, with the DC coefficient of the block before (below the image: of the MCU's block // before the row) - const blocksPerMcu = grey ? 1 : hmax * hmax + 2; + const blocksPerMcu = gray ? 1 : hmax * hmax + 2; const count = mcusPerLine * mcusPerColumn * blocksPerMcu; const coefficients = new Int16Array(count * 64); const owners = new Uint8Array(count), ends = new Uint8Array(count); @@ -1123,7 +1168,7 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit const frequencies = [new Int32Array(257), new Int32Array(257), new Int32Array(257), new Int32Array(257)]; countSymbols(blocks, frequencies); - const huffman = frequencies.slice(0, grey ? 2 : 4).map(buildOptimalTable); + const huffman = frequencies.slice(0, gray ? 2 : 4).map(buildOptimalTable); const writer = new BitWriter(width * height); writer.bytes(0xff, 0xd8); @@ -1140,20 +1185,20 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit if (segments) for (const bytes of segments) for (let i = 0; i < bytes.length; i++) writer.bytes(bytes[i]); // DQT, a segment per table like libjpeg - for (let t = 0; t < (grey ? 1 : 2); t++) { + for (let t = 0; t < (gray ? 1 : 2); t++) { writer.bytes(0xff, 0xdb, 0x00, 0x43, t); for (let k = 0; k < 64; k++) writer.bytes(tables[t][ZIGZAG[k]]); } // SOF0 - if (grey) writer.bytes(0xff, 0xc0, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0); + if (gray) writer.bytes(0xff, 0xc0, 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(1, hmax << 4 | hmax, 0, 2, 0x11, 1, 3, 0x11, 1); } // 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, grey ? 2 : 4)) { + 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]; const length = 19 + values.length; writer.bytes(0xff, 0xc4, length >> 8, length & 0xff, id); @@ -1162,7 +1207,7 @@ export function encode(pixels: Uint8Array, width: number, height: number, qualit } // SOS - if (grey) writer.bytes(0xff, 0xda, 0x00, 0x08, 0x01, 1, 0x00, 0x00, 0x3f, 0x00); + if (gray) writer.bytes(0xff, 0xda, 0x00, 0x08, 0x01, 1, 0x00, 0x00, 0x3f, 0x00); else writer.bytes(0xff, 0xda, 0x00, 0x0c, 0x03, 1, 0x00, 2, 0x11, 3, 0x11, 0x00, 0x3f, 0x00); writeBlocks(blocks, huffman, writer); diff --git a/src/codecs/jxl.ts b/src/codecs/jxl.ts index 9bd8e924..c2156b96 100644 --- a/src/codecs/jxl.ts +++ b/src/codecs/jxl.ts @@ -8,7 +8,7 @@ import { startThreads } from '../util/threads.ts'; import { MAX_PIXELS, checkPixels } from '../util/limits.ts'; import { BitReader } from './jxl/bits.ts'; import { - CS_GREY, CS_RGB, decodeICC, imageHeader, PRI_BT2100, PRI_CUSTOM, PRI_P3, readICC, TF_DCI, TF_HLG, TF_LINEAR, TF_PQ, + CS_GRAY, CS_RGB, decodeICC, imageHeader, PRI_BT2100, PRI_CUSTOM, PRI_P3, readICC, TF_DCI, TF_HLG, TF_LINEAR, TF_PQ, WP_CUSTOM, WP_DCI, WP_E, type ColourEncoding, type ImageHeader } from './jxl/headers.ts'; import { frameHeader, toc } from './jxl/frame-header.ts'; @@ -34,8 +34,8 @@ export function isJXL(d: Uint8Array): boolean { * Encodes RGBA pixels as a JPEG XL, lossless or lossy (with a Butteraugli distance above 0, and an effort 0-2): the * codestream, in the container if there is Exif data (a TIFF header and IFDs); lossy with up to threads worker threads */ -export async function encode(rgba: Uint8Array, width: number, height: number, exif?: Uint8Array, distance = 0, effort = 1, threads = 1, gainMap?: GainMapInput): Promise { - const codestreamOf = (pixels: Uint8Array, w: number, h: number, d: number): Promise | Uint8Array => d > 0 ? encodeVarDCT(pixels, w, h, { distance: d, effort, threads }) +export async function encode(rgba: Uint8Array, width: number, height: number, exif?: Uint8Array, distance = 0, effort = 1, threads = 1, gainMap?: GainMapInput): Promise> { + const codestreamOf = (pixels: Uint8Array, w: number, h: number, d: number): Promise> | Uint8Array => d > 0 ? encodeVarDCT(pixels, w, h, { distance: d, effort, threads }) : effort ? encodeModular(pixels, w, h, threads) : encodeRGBA(pixels, w, h); const stream = await codestreamOf(rgba, width, height, distance); if (!exif?.length && !gainMap) return stream; @@ -120,21 +120,21 @@ const PRIMARIES: Record = { */ export function colorSpace(image: ImageHeader): ColorSpace | undefined { const c: ColourEncoding = image.colour; - if (image.xybEncoded || c.wantICC || (c.colourSpace !== CS_RGB && c.colourSpace !== CS_GREY)) return; + if (image.xybEncoded || c.wantICC || (c.colourSpace !== CS_RGB && c.colourSpace !== CS_GRAY)) return; if (c.transfer === TF_PQ || c.transfer === TF_HLG) return; const curve: Curve | null = c.transfer === -1 ? (c.gamma > 0 ? v => v ** (1 / c.gamma) : null) : c.transfer === TF_LINEAR ? v => v : c.transfer === TF_DCI ? v => v ** 2.6 : null; const white = c.whitePoint === WP_CUSTOM ? c.white : c.whitePoint === WP_E ? [1 / 3, 1 / 3] : c.whitePoint === WP_DCI ? [0.314, 0.351] : null; - const primaries = c.colourSpace === CS_GREY ? null : c.primaries === PRI_CUSTOM + const primaries = c.colourSpace === CS_GRAY ? null : c.primaries === PRI_CUSTOM ? [0, 2, 4].map(i => c.primariesXY.slice(i, i + 2)) : PRIMARIES[c.primaries] ?? null; // (sRGB: nothing to convert; gray only by its curve) - if (c.colourSpace === CS_GREY) return curve ? { xy: null, curve } : undefined; + if (c.colourSpace === CS_GRAY) return curve ? { xy: null, curve } : undefined; if (!curve && !white && !primaries) return; return { xy: [...primaries ?? [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06]], white ?? WHITE_D65], curve: curve ?? srgbDecode }; } /** The frames shown (composited, as RGBA), their durations in milliseconds */ -export async function* frames(data: Uint8Array, maxPixels = MAX_PIXELS, toneMapping: ToneMapping = 'reinhard', threads = 1): AsyncGenerator<{ width: number, height: number, pixels: Uint8Array, duration: number, orientation: number, loopCount: number, icc?: Uint8Array, colorSpace?: ColorSpace }> { +export async function* frames(data: Uint8Array, maxPixels = MAX_PIXELS, toneMapping: ToneMapping = 'reinhard', threads = 1): AsyncGenerator<{ width: number, height: number, pixels: Uint8Array, duration: number, orientation: number, loopCount: number, animated: boolean, icc?: Uint8Array, colorSpace?: ColorSpace }> { const d = codestream(data); const r = new BitReader(d); const image = imageHeader(r); @@ -177,7 +177,7 @@ export async function* frames(data: Uint8Array, maxPixels = MAX_PIXELS, toneMapp shown++; yield { width: image.width, height: image.height, pixels: state.output.toRGBA(frame.canvas), duration: frame.header.duration * tick, - orientation: image.orientation, loopCount: a ? a.numLoops : 1, icc, colorSpace: space + orientation: image.orientation, loopCount: a ? a.numLoops : 1, animated: !!a, icc, colorSpace: space }; } if (frame.header.isLast) return; diff --git a/src/codecs/jxl/fast-lossless.ts b/src/codecs/jxl/fast-lossless.ts index d0b2e224..8e260c3c 100644 --- a/src/codecs/jxl/fast-lossless.ts +++ b/src/codecs/jxl/fast-lossless.ts @@ -511,7 +511,7 @@ function dcGlobalCommon(w: BitWriter, codes: PrefixCode[]): void { * Encodes RGBA pixels as a lossless JPEG XL codestream: grey if every pixel is, with alpha if one isn't opaque; byte for * byte what cjxl -e 1 writes on CPUs with AVX2 or NEON (libjxl's chunks of 16 pixels) */ -export function encodeRGBA(rgba: Uint8Array, width: number, height: number): Uint8Array { +export function encodeRGBA(rgba: Uint8Array, width: number, height: number): Uint8Array { if (width < 1 || height < 1) throw new RangeError('JPEG XL: dimensions must be at least 1'); const n = width * height; let grey = true, opaque = true; @@ -534,7 +534,7 @@ export function encodeRGBA(rgba: Uint8Array, width: number, height: number): Uin } /** Encodes 8-bit samples of 1-4 channels (grey, grey and alpha, RGB, RGBA) as a JPEG XL codestream */ -export function encode(px: Uint8Array, width: number, height: number, numChans: number, chunkSize = 16): Uint8Array { +export function encode(px: Uint8Array, width: number, height: number, numChans: number, chunkSize = 16): Uint8Array { const stride = width * numChans; // ---- a palette, if the colors (with black) are at most 512 and their hashes don't collide const palette = new Uint32Array(HASH_SIZE), lookup = new Int16Array(HASH_SIZE); diff --git a/src/codecs/jxl/frame-header.ts b/src/codecs/jxl/frame-header.ts index f72bd1a8..2361d931 100644 --- a/src/codecs/jxl/frame-header.ts +++ b/src/codecs/jxl/frame-header.ts @@ -81,11 +81,12 @@ const DEFAULT_EPF = (): EPF => ({ const DEFAULT_GAB = [0.115169525, 0.061248592, 0.115169525, 0.061248592, 0.115169525, 0.061248592]; -function blendingInfo(r: BitReader, haveExtra: boolean, resets: (mode: number) => boolean, mainMode = -1): BlendingInfo { +function blendingInfo(r: BitReader, numExtra: number, resets: (mode: number) => boolean, mainMode = -1): BlendingInfo { const mode = r.u32(0, 1, 2, [3, 2]); if (mode > 4) throw new Error('JPEG XL: invalid blend mode'); - const usesAlpha = haveExtra && (mode === BLEND_BLEND || mode === BLEND_MULADD); + const usesAlpha = numExtra > 0 && (mode === BLEND_BLEND || mode === BLEND_MULADD); const alphaChannel = usesAlpha ? r.u32(0, 1, 2, [3, 3]) : 0; + if (alphaChannel >= Math.max(1, numExtra)) throw new Error('JPEG XL: invalid blend alpha channel'); const clamp = usesAlpha || mode === BLEND_MUL ? r.bool() : false; const source = resets(mainMode >= 0 ? mainMode : mode) ? 0 : r.bits(2); return { mode, alphaChannel, clamp, source }; @@ -164,8 +165,8 @@ export function frameHeader(r: BitReader, image: ImageHeader): FrameHeader { let blending: BlendingInfo = { mode: BLEND_REPLACE, alphaChannel: 0, clamp: false, source: 0 }; const ecBlending: BlendingInfo[] = []; if (!allDefault && normal) { - blending = blendingInfo(r, numExtra > 0, resets); - for (let i = 0; i < numExtra; i++) ecBlending.push(blendingInfo(r, true, resets, blending.mode)); + blending = blendingInfo(r, numExtra, resets); + for (let i = 0; i < numExtra; i++) ecBlending.push(blendingInfo(r, numExtra, resets, blending.mode)); } else for (let i = 0; i < numExtra; i++) ecBlending.push({ ...blending }); let duration = 0, isLast = type === FRAME_REGULAR, saveAsReference = 0; if (!allDefault && normal) { diff --git a/src/codecs/jxl/frame.ts b/src/codecs/jxl/frame.ts index 5a00ff50..bacff156 100644 --- a/src/codecs/jxl/frame.ts +++ b/src/codecs/jxl/frame.ts @@ -56,7 +56,11 @@ class Sections { private single: BitReader | null = null; constructor(private readonly d: Uint8Array, private readonly t: TOC) { - if (t.offsets.length === 1) this.single = new BitReader(d, t.offsets[0], t.offsets[0] + t.sizes[0]); + if (t.offsets.length === 1) { + // (a frame of one section that the data ends in: its missing bytes would read as zeros) + if (t.offsets[0] + t.sizes[0] > d.length) throw new Error('JPEG XL: truncated data'); + this.single = new BitReader(d, t.offsets[0], t.offsets[0] + t.sizes[0]); + } } /** the reader of section i (LfGlobal, the LF groups, HfGlobal, then the pass groups) */ diff --git a/src/codecs/jxl/headers.ts b/src/codecs/jxl/headers.ts index f7d3bd80..6b1e12a7 100644 --- a/src/codecs/jxl/headers.ts +++ b/src/codecs/jxl/headers.ts @@ -24,7 +24,7 @@ export interface ExtraChannel { spot: number[]; } -export const CS_RGB = 0, CS_GREY = 1, CS_XYB = 2; +export const CS_RGB = 0, CS_GRAY = 1, CS_XYB = 2; export const WP_D65 = 1, WP_CUSTOM = 2, WP_E = 10, WP_DCI = 11; export const PRI_SRGB = 1, PRI_CUSTOM = 2, PRI_BT2100 = 9, PRI_P3 = 11; export const TF_BT709 = 1, TF_UNKNOWN = 2, TF_LINEAR = 8, TF_SRGB = 13, TF_PQ = 16, TF_DCI = 17, TF_HLG = 18; @@ -158,7 +158,7 @@ export function colourEncoding(r: BitReader): ColourEncoding { if (c.whitePoint === WP_CUSTOM) c.white = [customXY(r), customXY(r)]; else if (c.whitePoint !== WP_D65 && c.whitePoint !== WP_E && c.whitePoint !== WP_DCI) throw new Error('JPEG XL: invalid white point'); } - if (c.colourSpace !== CS_XYB && c.colourSpace !== CS_GREY) { + if (c.colourSpace !== CS_XYB && c.colourSpace !== CS_GRAY) { c.primaries = r.enum(); if (c.primaries === PRI_CUSTOM) for (let i = 0; i < 6; i++) c.primariesXY.push(customXY(r)); else if (c.primaries !== PRI_SRGB && c.primaries !== PRI_BT2100 && c.primaries !== PRI_P3) throw new Error('JPEG XL: invalid primaries'); @@ -273,7 +273,7 @@ const COMMON_DATA = ['XYZ ', 'desc', 'text', 'mluc', 'para', 'curv', 'sf32', 'gb /** The ICC profile an encoded ICC stream (see readICC) describes, null if the stream is invalid */ export function decodeICC(stream: Uint8Array): Uint8Array | null { - let at = 0; + let at: number; const fail = (): never => { throw new RangeError('invalid ICC stream'); }; diff --git a/src/codecs/jxl/modular-lossless.ts b/src/codecs/jxl/modular-lossless.ts index f9c9ba4e..b95207ae 100644 --- a/src/codecs/jxl/modular-lossless.ts +++ b/src/codecs/jxl/modular-lossless.ts @@ -216,7 +216,7 @@ const MIN_THREADED_PIXELS = 1 << 19, PIXELS_PER_THREAD = 1 << 17; * opaque; a palette of up to 1024 colors, else palettes of the channels using few of their values, YCoCg, the residuals * of the weighted predictor in the contexts of its error (groups in up to threads worker threads) */ -export async function encodeModular(rgba: Uint8Array, width: number, height: number, threads = 1): Promise { +export async function encodeModular(rgba: Uint8Array, width: number, height: number, threads = 1): Promise> { if (width < 1 || height < 1) throw new RangeError('JPEG XL: dimensions must be at least 1'); const n = width * height; let grey = true, opaque = true; diff --git a/src/codecs/jxl/patches-enc.ts b/src/codecs/jxl/patches-enc.ts index 926464c2..63ae87cc 100644 --- a/src/codecs/jxl/patches-enc.ts +++ b/src/codecs/jxl/patches-enc.ts @@ -283,7 +283,7 @@ export function findPatches(planes: Float32Array[], stride: number, width: numbe maxH = Math.max(maxH, p.h); } let refW = Math.max(maxW, Math.sqrt(total)), refH = Math.max(maxH, Math.sqrt(total)); - let spots: Array<[number, number]> = [], usedH = 0; + let spots: Array<[number, number]> = [], usedH: number; for (; ;) { refW = Math.floor(refW * 1.05 + 1); refH = Math.floor(refH * 1.05 + 1); diff --git a/src/codecs/jxl/vardct-enc.ts b/src/codecs/jxl/vardct-enc.ts index ffc5adee..8c798e14 100644 --- a/src/codecs/jxl/vardct-enc.ts +++ b/src/codecs/jxl/vardct-enc.ts @@ -316,12 +316,15 @@ export function hfTokenChunks({ types, hf, pw, bw, bh, groupsPerRow }: HFTokenTa } /** Encodes RGBA pixels as a lossy JPEG XL codestream, alpha (if the image has transparency) losslessly */ -export async function encodeVarDCT(rgba: Uint8Array, width: number, height: number, options: VarDCTOptions): Promise { +export async function encodeVarDCT(rgba: Uint8Array, width: number, height: number, options: VarDCTOptions): Promise> { if (width < 1 || height < 1) throw new RangeError('JPEG XL: dimensions must be at least 1'); // threads for the XYB planes, the quantization field, the varblock search, the coefficients and their tokens, if // they start (the same files). Started first, they load while the work begins here const n = Math.min(options.threads, Math.ceil(height / 64), Math.max(4, Math.floor(width * height / PIXELS_PER_THREAD[options.effort]))); - const pool = { threads: n > 1 && width * height >= MIN_THREADED_PIXELS[options.effort] ? startThreads(n) : null }; + // (fewer than 4 threads save less than their start costs on smaller images: on 2 cores, effort 1 took 1.3-1.7x as + // long with threads from 0.5 to 1 megapixel and broke even at 1.5, where 12 threads already win at 0.5) + const minimum = n < 4 ? Math.max(MIN_THREADED_PIXELS[options.effort], MIN_THREADED_PIXELS[0]) : MIN_THREADED_PIXELS[options.effort]; + const pool = { threads: n > 1 && width * height >= minimum ? startThreads(n) : null }; try { return await encode(rgba, width, height, options, pool); } finally { @@ -329,7 +332,7 @@ export async function encodeVarDCT(rgba: Uint8Array, width: number, height: numb } } -async function encode(rgba: Uint8Array, width: number, height: number, { distance, effort }: VarDCTOptions, pool: { threads: Thread[] | null }): Promise { +async function encode(rgba: Uint8Array, width: number, height: number, { distance, effort }: VarDCTOptions, pool: { threads: Thread[] | null }): Promise> { const bw = Math.ceil(width / 8), bh = Math.ceil(height / 8), pw = bw * 8; // (a stage in the threads; if they fail, like workers whose module can't be loaded, it and the rest run here) const parallel = async (run: (threads: Thread[] | null) => Promise): Promise => { diff --git a/src/codecs/netpbm.ts b/src/codecs/netpbm.ts index 75ba16b9..038b158e 100644 --- a/src/codecs/netpbm.ts +++ b/src/codecs/netpbm.ts @@ -126,7 +126,7 @@ export function decode(d: Uint8Array, maxPixels = MAX_PIXELS, toneMapping: ToneM for (let i = 0, o = header.data; i < samples.length; i++, o += wide ? 2 : 1) samples[i] = scale(wide ? d[o] << 8 | d[o + 1] : d[o]); } - // greyscale, greyscale and alpha, RGB, RGBA (by the depth; PAM's tuple types say the same) + // grayscale, grayscale and alpha, RGB, RGBA (by the depth; PAM's tuple types say the same) const pixels = new Uint8Array(count * 4); for (let i = 0; i < count; i++) { const s = i * depth, p = i * 4; @@ -165,32 +165,32 @@ function decodePFM(d: Uint8Array, channels: number, maxPixels: number, toneMappi } /** - * Encodes RGBA pixels into the smallest fitting Netpbm format: PBM for black and white images, PGM for greyscale - * ones, PPM, and PAM (greyscale or RGB with alpha) for images with transparency + * Encodes RGBA pixels into the smallest fitting Netpbm format: PBM for black and white images, PGM for grayscale + * ones, PPM, and PAM (grayscale or RGB with alpha) for images with transparency */ -export function encode(rgba: Uint8Array, width: number, height: number): Uint8Array { +export function encode(rgba: Uint8Array, width: number, height: number): Uint8Array { if (width < 1 || height < 1) throw new RangeError('Netpbm: dimensions must be at least 1'); const count = width * height; - let opaque = true, grey = true, bitmap = true; + let opaque = true, gray = true, bitmap = true; for (let p = 0; p < count * 4; p += 4) { const r = rgba[p], g = rgba[p + 1], b = rgba[p + 2], a = rgba[p + 3]; if (a !== 255) opaque = false; - if (r !== g || g !== b) grey = false; + if (r !== g || g !== b) gray = false; if (r !== 0 && r !== 255 || r !== g || g !== b) bitmap = false; - if (!opaque && !grey) break; + if (!opaque && !gray) break; } const ascii = (text: string): Uint8Array => Uint8Array.from(text, c => c.charCodeAt(0)); let header: Uint8Array, depth: number; if (!opaque) { - depth = grey ? 2 : 4; - header = ascii(`P7\nWIDTH ${width}\nHEIGHT ${height}\nDEPTH ${depth}\nMAXVAL 255\nTUPLTYPE ${grey ? 'GRAYSCALE_ALPHA' : 'RGB_ALPHA'}\nENDHDR\n`); + depth = gray ? 2 : 4; + header = ascii(`P7\nWIDTH ${width}\nHEIGHT ${height}\nDEPTH ${depth}\nMAXVAL 255\nTUPLTYPE ${gray ? 'GRAYSCALE_ALPHA' : 'RGB_ALPHA'}\nENDHDR\n`); } else if (bitmap) { depth = 0; header = ascii(`P4\n${width} ${height}\n`); } else { - depth = grey ? 1 : 3; - header = ascii(`P${grey ? 5 : 6}\n${width} ${height}\n255\n`); + depth = gray ? 1 : 3; + header = ascii(`P${gray ? 5 : 6}\n${width} ${height}\n255\n`); } const stride = depth ? width * depth : width + 7 >> 3; diff --git a/src/codecs/png.ts b/src/codecs/png.ts index 932a3913..5b1e75b5 100644 --- a/src/codecs/png.ts +++ b/src/codecs/png.ts @@ -38,7 +38,7 @@ export interface EncodeOptions { palette?: Uint8Array; /** alpha per palette entry */ transparency?: Uint8Array; - /** whether to paeth filter the rows (pays off for truecolor and greyscale images) */ + /** whether to paeth filter the rows (pays off for truecolor and grayscale images) */ filter?: boolean; } @@ -69,7 +69,7 @@ const ADAM7 = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, * Encodes raw pixel data into a PNG * @param data Raw pixel data, rows packed MSB first for depths below 8 */ -export async function encode(data: Uint8Array, { text, width, height, channels, depth = 8, level = 0, palette, transparency, filter: filterRows = false }: EncodeOptions): Promise { +export async function encode(data: Uint8Array, { text, width, height, channels, depth = 8, level = 0, palette, transparency, filter: filterRows = false }: EncodeOptions): Promise> { const header = new Uint8Array(13); const view = new DataView(header.buffer); view.setUint32(0, width); @@ -110,7 +110,7 @@ function filter(data: Uint8Array, rowBytes: number, y0: number, y1: number, bpp: const row = y * rowBytes, o = (y - y0) * (rowBytes + 1) + 1; out[o - 1] = 4; - // the first row has no row above, the first pixel of every row no left neighbour + // the first row has no row above, the first pixel of every row no left neighbor if (y === 0) { for (let i = 0; i < rowBytes; i++) out[o + i] = data[row + i] - (i >= bpp ? data[row + i - bpp] : 0); continue; @@ -183,11 +183,11 @@ export interface PixelFormat { /** * Picks the smallest lossless format that fits all the given RGBA images: a palette for up to 256 colors, - * otherwise greyscale or RGB, with alpha only if a pixel isn't opaque + * otherwise grayscale or RGB, with alpha only if a pixel isn't opaque */ /** * How much more an opaque image costs per pixel with transparent pixels than without them, given the pixel formats - * (palette, grey or truecolor) both get: e.g. 4/3 for RGBA instead of RGB, 4 for RGBA instead of a palette when the + * (palette, gray or truecolor) both get: e.g. 4/3 for RGBA instead of RGB, 4 for RGBA instead of a palette when the * transparent pixels are the 257th color, 2 for 8 instead of 4 bit palette indices when they're the 17th * @param images RGBA, only the transparent pixels aren't opaque */ @@ -199,7 +199,7 @@ export function alphaCost(images: Uint8Array[]): number { /** {@link alphaCost}, of images given one at a time */ export class AlphaCost { - private grey = true; + private gray = true; private colors = new Set(); private done = false; @@ -214,10 +214,10 @@ export class AlphaCost { previous = value; const o = i * 4; if (rgba[o + 3] === 0) continue; - if (rgba[o] !== rgba[o + 1] || rgba[o] !== rgba[o + 2]) this.grey = false; + if (rgba[o] !== rgba[o + 1] || rgba[o] !== rgba[o + 2]) this.gray = false; if (colors.size <= 256) colors.add(value); - // more than 256 colors and not grey: truecolor either way, nothing else can change - else if (!this.grey) { + // more than 256 colors and not gray: truecolor either way, nothing else can change + else if (!this.gray) { this.done = true; return; } @@ -225,11 +225,11 @@ export class AlphaCost { } cost(): number { - const { colors, grey } = this; - // bytes per pixel: palette 1/8 to 1 (by its bit depth), grey 1 (with alpha 2), truecolor 3 (with alpha 4) + const { colors, gray } = this; + // bytes per pixel: palette 1/8 to 1 (by its bit depth), gray 1 (with alpha 2), truecolor 3 (with alpha 4) const palette = (entries: number): number => (entries <= 2 ? 1 : entries <= 4 ? 2 : entries <= 16 ? 4 : 8) / 8; - const transparent = colors.size < 256 ? palette(colors.size + 1) : grey ? 2 : 4; - const opaque = colors.size <= 256 ? palette(colors.size) : grey ? 1 : 3; + const transparent = colors.size < 256 ? palette(colors.size + 1) : gray ? 2 : 4; + const opaque = colors.size <= 256 ? palette(colors.size) : gray ? 1 : 3; return transparent / opaque; } } @@ -243,7 +243,7 @@ function pixelFormat(images: Uint8Array[]): PixelFormat { /** {@link pixelFormat} of images given one at a time */ export class FormatScanner { private opaque = true; - private grey = true; + private gray = true; // up to 256 distinct colors, by their first appearance private colors: Map | null = new Map(); @@ -258,22 +258,22 @@ export class FormatScanner { const o = i * 4; if (rgba[o + 3] !== 255) this.opaque = false; - if (rgba[o] !== rgba[o + 1] || rgba[o] !== rgba[o + 2]) this.grey = false; + if (rgba[o] !== rgba[o + 1] || rgba[o] !== rgba[o + 2]) this.gray = false; if (this.colors && !this.colors.has(value)) { if (this.colors.size === 256) this.colors = null; else this.colors.set(value, this.colors.size); } // nothing left to find out: RGBA it is - if (!this.colors && !this.opaque && !this.grey) return; + if (!this.colors && !this.opaque && !this.gray) return; } } format(): PixelFormat { - return formatOf(this.colors, this.opaque, this.grey); + return formatOf(this.colors, this.opaque, this.gray); } } -function formatOf(colors: Map | null, opaque: boolean, grey: boolean): PixelFormat { +function formatOf(colors: Map | null, opaque: boolean, gray: boolean): PixelFormat { if (colors) { // opaque entries are moved to the end, so tRNS can be cut short const entries = [...colors.keys()].map(value => new Uint8Array(new Uint32Array([value]).buffer)); @@ -311,7 +311,7 @@ function formatOf(colors: Map | null, opaque: boolean, grey: boo }; } - const channels = (grey ? 1 : 3) + (opaque ? 0 : 1); + const channels = (gray ? 1 : 3) + (opaque ? 0 : 1); return { channels, depth: 8, convert(rgba, width, height) { @@ -343,7 +343,7 @@ const aligned = (rgba: Uint8Array): Uint8Array => rgba.byteOffset % 4 ? rgba.sli * Rows of non-palette images are paeth filtered where that compresses better (unless the data isn't compressed), * palette indices aren't filtered (like libpng recommends) */ -export async function encodeRGBA(rgba: Uint8Array, width: number, height: number, level: number, text?: EncodeOptions['text']): Promise { +export async function encodeRGBA(rgba: Uint8Array, width: number, height: number, level: number, text?: EncodeOptions['text']): Promise> { rgba = aligned(rgba.subarray(0, width * height * 4)); const format = pixelFormat([rgba]); const { channels, depth, palette, transparency } = format; @@ -372,8 +372,8 @@ export interface APNGEncodeFrame { * @param plays How often to play the animation, 0 = forever * @param text tEXt chunks, empty values are skipped */ -export async function encodeAnimation(frames: APNGEncodeFrame[], width: number, height: number, plays: number, level: number, text?: EncodeOptions['text']): Promise { - if (!frames.length) throw new Error('PNG: an animation needs at least one frame'); +export async function encodeAnimation(frames: APNGEncodeFrame[], width: number, height: number, plays: number, level: number, text?: EncodeOptions['text']): Promise> { + if (!frames.length) throw new RangeError('PNG: an animation needs at least one frame, not 0'); frames = [coverCanvas(frames[0], width, height), ...frames.slice(1)]; for (const f of frames) checkFrame(f, width, height); @@ -415,7 +415,7 @@ export function frameData(rgba: Uint8Array, width: number, height: number, forma } /** An APNG from its compressed frames, all in one pixel format */ -export function animationFile(frames: EncodedAPNGFrame[], width: number, height: number, plays: number, format: PixelFormat, text?: EncodeOptions['text']): Uint8Array { +export function animationFile(frames: EncodedAPNGFrame[], width: number, height: number, plays: number, format: PixelFormat, text?: EncodeOptions['text']): Uint8Array { const { channels, depth, palette, transparency } = format; const header = new Uint8Array(13); const hv = new DataView(header.buffer); @@ -498,6 +498,8 @@ interface Parsed { frames: Array<{ control: APNGFrameControl, data: Uint8Array[] }>; /** set if the animation is broken, which makes decoders fall back to the default image */ animationError: boolean; + /** set for an animation that ends before its IEND chunk: the frames that are there are what it has (the last one can be cut) */ + truncated: boolean; } function parse(array: Uint8Array): Parsed { @@ -518,6 +520,7 @@ function parse(array: Uint8Array): Parsed { let current: Parsed['frames'][number] | null = null; let sequence = 0; let animationError = false; + let ended = false, truncated = false; let offset = 8; while (offset + 8 <= array.length) { @@ -534,8 +537,13 @@ function parse(array: Uint8Array): Parsed { const chunk = array.subarray(start, end); - if (end + 4 <= array.length && crc32(array.subarray(offset + 4, end)) !== view.getUint32(end)) - throw new Error('PNG: chunk checksum mismatch'); + if (end + 4 <= array.length && crc32(array.subarray(offset + 4, end)) !== view.getUint32(end)) { + // a damaged chunk: the image's own (the critical ones and the animation's) are an error, color and text + // metadata is skipped, like libpng and browsers do + if (!(type & 0x20000000) || type === acTL || type === fcTL || type === fdAT) throw new Error('PNG: chunk checksum mismatch'); + offset = end + 4; + continue; + } if (type === IHDR) { if (length < 13) throw new Error('PNG: invalid IHDR'); @@ -585,7 +593,7 @@ function parse(array: Uint8Array): Parsed { else if (type === iCCP) iccp ??= chunk; else if (type === sRGB) srgb = true; else if (type === tEXt || type === zTXt || type === iTXt) text.push({ type, chunk }); - else if (type === IEND) break; + else if (type === IEND) { ended = true; break; } offset = end + 4; } @@ -603,9 +611,15 @@ function parse(array: Uint8Array): Parsed { // more frames than announced are ignored; fewer (or none) make the animation invalid if (animation) { if (frames.length > animation.frames) frames.length = animation.frames; - if (!frames.length || frames.length < animation.frames || frames.some(f => !f.data.length)) animationError = true; + // a file cut short keeps the frames that arrived (the last one may be cut: the decoder checks), like it does + // for GIF; one that ends properly with fewer frames than it announced is invalid + if (!ended) { + truncated = true; + while (frames.length && !frames[frames.length - 1].data.length) frames.pop(); + } + if (!frames.length || (frames.length < animation.frames && !truncated) || frames.some(f => !f.data.length)) animationError = true; } - return { header, palette, transparency, idat, exif, iccp: srgb ? null : iccp, text, animation, frames, animationError }; + return { header, palette, transparency, idat, exif, iccp: srgb ? null : iccp, text, animation, frames, animationError, truncated }; } // the interlace passes of an image ([x start, y start, x step, y step, width, height]) and its inflated size @@ -715,36 +729,51 @@ export function isAnimated(array: Uint8Array): boolean { /** * Decodes an APNG (https://wiki.mozilla.org/APNG_Specification) into its (uncomposited) frames; a plain PNG becomes - * a single frame + * a single frame. The frames are decoded one at a time as they are iterated (once), so compositing them doesn't hold + * all of them * @return plays: 0 = forever */ -export async function decodeAnimation(array: Uint8Array, onlyFirstFrame = false, maxPixels = MAX_PIXELS): Promise<{ width: number, height: number, plays: number, frames: APNGFrame[], icc?: Uint8Array, orientation: number }> { +export async function decodeAnimation(array: Uint8Array, firstFrameOnly = false, maxPixels = MAX_PIXELS): Promise<{ width: number, height: number, plays: number, frames: AsyncIterable, icc?: Uint8Array, orientation: number }> { const p = parse(array); const { width, height } = p.header; const orientation = p.exif ? exifOrientation(p.exif) : await textOrientation(p.text); // every frame is composited onto a canvas of its own - checkPixels(width, height, maxPixels, !p.animation || p.animationError || onlyFirstFrame ? 1 : Math.max(1, p.frames.length)); + checkPixels(width, height, maxPixels, !p.animation || p.animationError || firstFrameOnly ? 1 : Math.max(1, p.frames.length)); // broken animations show the default image, like browsers do if (!p.animation || p.animationError) { const pixels = await decodeImageData(p, p.idat, width, height); - return { width, height, plays: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels }], icc: await profile(p.iccp), orientation }; + const still = async function* (): AsyncGenerator { + yield { x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels }; + }; + return { width, height, plays: 0, frames: still(), icc: await profile(p.iccp), orientation }; } - const frames: APNGFrame[] = []; - for (const { control: c, data } of p.frames) { + for (const { control: c } of p.frames) if (!c.width || !c.height || c.x + c.width > width || c.y + c.height > height) throw new Error('PNG: invalid APNG frame region'); - frames.push({ - x: c.x, y: c.y, width: c.width, height: c.height, duration: c.delay, - // DISPOSE_OP_PREVIOUS on the first frame means background - dispose: !frames.length && c.dispose === 2 ? 1 : c.dispose, - blend: c.blend, - pixels: await decodeImageData(p, data, c.width, c.height) - }); - if (onlyFirstFrame) break; + async function* frames(): AsyncGenerator { + let count = 0; + for (const { control: c, data } of p.frames) { + let pixels: Uint8Array; + try { + pixels = await decodeImageData(p, data, c.width, c.height); + } catch (error) { + // (the last frame of a file that is cut off can be incomplete: the ones before it are what the file has) + if (p.truncated && count) return; + throw error; + } + yield { + x: c.x, y: c.y, width: c.width, height: c.height, duration: c.delay, + // DISPOSE_OP_PREVIOUS on the first frame means background + dispose: !count++ && c.dispose === 2 ? 1 : c.dispose, + blend: c.blend, + pixels + }; + if (firstFrameOnly) return; + } } - return { width, height, plays: p.animation.plays, frames, icc: await profile(p.iccp), orientation }; + return { width, height, plays: p.animation.plays, frames: frames(), icc: await profile(p.iccp), orientation }; } /** @@ -752,10 +781,15 @@ export async function decodeAnimation(array: Uint8Array, onlyFirstFrame = false, * blend_op section, https://wiki.mozilla.org/APNG_Specification) */ export function compositeAnimation({ width, height, frames }: { width: number, height: number, frames: APNGFrame[] }): Array<{ pixels: Uint8Array, duration: number }> { + const step = compositor(width, height); + return frames.map(f => ({ pixels: step(f), duration: f.duration })); +} + +/** {@link compositeAnimation} one frame at a time: each call composites the next frame and returns the canvas shown */ +export function compositor(width: number, height: number): (f: APNGFrame) => Uint8Array { const canvas = new Uint8Array(width * height * 4); - const output = []; - for (const f of frames) { + return f => { const previous = f.dispose === 2 ? canvas.slice() : null; for (let y = 0; y < f.height; y++) { @@ -782,14 +816,14 @@ export function compositeAnimation({ width, height, frames }: { width: number, h } } - output.push({ pixels: canvas.slice(), duration: f.duration }); + const shown = canvas.slice(); if (f.dispose === 1) for (let y = 0; y < f.height; y++) canvas.fill(0, ((f.y + y) * width + f.x) * 4, ((f.y + y) * width + f.x + f.width) * 4); else if (previous) canvas.set(previous); - } - return output; + return shown; + }; } const RAW_EXIF = /^Raw profile type (exif|APP1)$/; @@ -846,7 +880,7 @@ function unfilter(data: Uint8Array, offset: number, height: number, rowBytes: nu const out = inPlace ? data.subarray(offset, offset + height * rowBytes) : new Uint8Array(height * rowBytes); const first = Math.min(bpp, rowBytes); - // the first row and the first pixel of every row have zero neighbours, those are handled by separate loops + // the first row and the first pixel of every row have zero neighbors, those are handled by separate loops for (let y = 0; y < height; y++) { const filter = data[offset++]; const row = y * rowBytes; @@ -868,11 +902,11 @@ function unfilter(data: Uint8Array, offset: number, height: number, rowBytes: nu } } else if (filter === 4) { if (y === 0) { - // paeth with no row above picks the left neighbour + // paeth with no row above picks the left neighbor out.set(data.subarray(offset, offset + first), row); for (let i = row + bpp; i < row + rowBytes; i++) out[i] = data[src + i] + out[i - bpp]; } else { - // and with no left neighbour the one above + // and with no left neighbor the one above for (let i = row; i < row + first; i++) out[i] = data[src + i] + out[i - rowBytes]; if (bpp === 3 || bpp === 4) paethRow(data, src, out, row, rowBytes, bpp); else for (let i = row + bpp; i < row + rowBytes; i++) { @@ -891,7 +925,7 @@ function unfilter(data: Uint8Array, offset: number, height: number, rowBytes: nu return out; } -// the paeth filter on a row of 3 or 4 byte pixels, the left and upper left neighbours in variables: as above, with each +// the paeth filter on a row of 3 or 4 byte pixels, the left and upper left neighbors in variables: as above, with each // channel's predictor not waiting for the byte just stored function paethRow(data: Uint8Array, src: number, out: Uint8Array, row: number, rowBytes: number, bpp: number): void { const up = row - rowBytes, end = row + rowBytes; diff --git a/src/codecs/qoi.ts b/src/codecs/qoi.ts index e5cc922c..3f506ae9 100644 --- a/src/codecs/qoi.ts +++ b/src/codecs/qoi.ts @@ -62,7 +62,7 @@ export function decode(d: Uint8Array, maxPixels = MAX_PIXELS): { width: number, } /** Encodes RGBA pixels into a QOI (3 channels if the image is opaque), byte for byte like the reference encoder */ -export function encode(rgba: Uint8Array, width: number, height: number): Uint8Array { +export function encode(rgba: Uint8Array, width: number, height: number): Uint8Array { if (width < 1 || height < 1) throw new RangeError('QOI: dimensions must be at least 1'); const count = width * height; let opaque = true; diff --git a/src/codecs/quantize.ts b/src/codecs/quantize.ts index 2b0dfae1..9920f182 100644 --- a/src/codecs/quantize.ts +++ b/src/codecs/quantize.ts @@ -1,22 +1,43 @@ +import type { DitherMethod } from '../image.ts'; +import { oneOf, finite } from '../util/options.ts'; // perceptual channel weights for squared color distances const WR = 3, WG = 4, WB = 2; -/** - * Reduces RGBA pixel data to an indexed palette - * Pixels with alpha < 128 are mapped to a dedicated transparent index - * @param {Uint8Array} pixels RGBA pixel data - * @param {number} width Image width in pixels (needed for dithering) - * @param {{maxColors?: number, quality?: number}} [options] quality (1-100) scales the palette size exponentially (1 = 8 colors, 50 = 55, 90 and above = 256) - * @return {{palette: Uint8Array, indices: Uint8Array, transparentIndex: number}} palette is packed RGB, transparentIndex is -1 if unused - */ +/** Options of quantize(): the palette size and the dithering */ export interface QuantizeOptions { + /** the most palette entries, the transparent one included */ maxColors?: number; - quality?: number; + /** how the rounding error is spread (Floyd-Steinberg by default) */ + dither?: DitherMethod; + /** how strongly (0-1) */ + ditherStrength?: number; /** whether to have a transparent index even if no pixel is transparent */ transparent?: boolean; } +// every DitherMethod (a missing key is a type error) +const DITHER: Record = { 'none': true, 'floyd-steinberg': true, 'atkinson': true, 'ordered': true }; +export const DITHER_METHODS = Object.keys(DITHER) as DitherMethod[]; + +/** + * Checks palette options (`colors` from 2 to 256, a dither method, a strength 0-1) before anything changes, with the + * messages of Image.quantize() + */ +export function paletteOptions(colors: number | undefined, dither: unknown, ditherStrength: number): { colors: number | undefined, dither: DitherMethod, strength: number } { + let count: number | undefined; + if (colors !== undefined) { + count = finite(colors, 'colors'); + // eslint-disable-next-line no-restricted-syntax -- the palette size is only checked here + if (!Number.isInteger(count) || count < 2 || count > 256) throw new RangeError(`colors must be an integer from 2 to 256, not ${colors}`); + } + oneOf(dither, DITHER_METHODS, 'dither'); + const strength = finite(ditherStrength, 'ditherStrength'); + // eslint-disable-next-line no-restricted-syntax -- the dither strength is only checked here + if (strength < 0 || strength > 1) throw new RangeError(`ditherStrength must be 0-1, not ${ditherStrength}`); + return { colors: count, dither: dither as DitherMethod, strength }; +} + export interface Quantized { /** packed RGB */ palette: Uint8Array; @@ -33,16 +54,30 @@ interface Clusters { } /** - * Finds the color of the largest cluster among the opaque pixels that pass the filter - * @return packed RGB, or null if no pixel qualifies + * Finds the dominant color among the pixels that are at least half opaque and pass the filter: the colors are counted + * in a histogram of 16 levels per channel (4096 bins, like sharp's), and the average of the pixels in the fullest bin + * is the result, so it is a color the image has (a cluster's average can lie between two hues) + * @return RGB, or null if no pixel qualifies */ -export function dominantColor(pixels: Uint8Array, include: (r: number, g: number, b: number) => boolean, clusters = 8): [number, number, number] | null { - const { palette, weights } = medianCut(pixels, clusters, 4, include); - if (!weights.length) return null; +export function dominantColor(pixels: Uint8Array, include: (r: number, g: number, b: number) => boolean): [number, number, number] | null { + const counts = new Uint32Array(4096), sums = new Float64Array(4096 * 3); + let found = false; + for (let i = 0; i < pixels.length; i += 4) { + if (pixels[i + 3] < 128) continue; + const r = pixels[i], g = pixels[i + 1], b = pixels[i + 2]; + if (!include(r, g, b)) continue; + const bin = (r >> 4) << 8 | (g >> 4) << 4 | b >> 4; + counts[bin]++; + sums[bin * 3] += r; + sums[bin * 3 + 1] += g; + sums[bin * 3 + 2] += b; + found = true; + } + if (!found) return null; let best = 0; - for (let i = 1; i < weights.length; i++) if (weights[i] > weights[best]) best = i; - return [Math.round(palette[best * 3]), Math.round(palette[best * 3 + 1]), Math.round(palette[best * 3 + 2])]; + for (let bin = 1; bin < 4096; bin++) if (counts[bin] > counts[best]) best = bin; + return [Math.round(sums[best * 3] / counts[best]), Math.round(sums[best * 3 + 1] / counts[best]), Math.round(sums[best * 3 + 2] / counts[best])]; } interface Points { @@ -61,7 +96,11 @@ interface Box { error: number; } -export function quantize(pixels: Uint8Array, width: number, { maxColors = 256, quality = 95, transparent = false }: QuantizeOptions = {}): Quantized { +/** + * Reduces RGBA pixel data to an indexed palette (packed RGB). Pixels with alpha < 128 are mapped to a dedicated + * transparent index (-1 if unused) + */ +export function quantize(pixels: Uint8Array, width: number, { maxColors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, transparent = false }: QuantizeOptions = {}): Quantized { const length = pixels.length >> 2; let hasTransparency = transparent; for (let i = 3; i < pixels.length; i += 4) @@ -70,16 +109,14 @@ export function quantize(pixels: Uint8Array, width: number, { maxColors = 256, q break; } - quality = Math.min(100, Math.max(1, quality)); - const limit = Math.min(maxColors, Math.round(8 * 32 ** (Math.min(quality, 90) / 90))); - const colors = hasTransparency ? limit - 1 : limit; + const colors = hasTransparency ? maxColors - 1 : maxColors; const exact = exactPalette(pixels, colors); let palette: Uint8Array, indices: Uint8Array; if (exact) ({ palette, indices } = exact); else { - palette = Uint8Array.from(medianCut(pixels, colors, Math.ceil(quality / 25)).palette, Math.round); - indices = ditherMap(pixels, width, palette, palette.length / 3); + palette = Uint8Array.from(medianCut(pixels, colors, 4).palette, Math.round); + indices = dither === 'floyd-steinberg' ? ditherMap(pixels, width, palette, palette.length / 3, ditherStrength) : paletteIndices(pixels, width, palette, dither, ditherStrength); } let transparentIndex = -1; @@ -162,10 +199,10 @@ const ATKINSON = [[1, 0, 1 / 8], [2, 0, 1 / 8], [-1, 1, 1 / 8], [0, 1, 1 / 8], [ /** * Replaces the RGB of every pixel with an alpha above 0 by its nearest palette entry (packed RGB), in place. Pixels * with alpha 0 are left alone. Dithering: `'floyd-steinberg'` and `'atkinson'` spread each pixel's rounding error to - * the neighbours that come after it (serpentine: rows alternate direction), `'ordered'` offsets each pixel by a 4x4 + * the neighbors that come after it (serpentine: rows alternate direction), `'ordered'` offsets each pixel by a 4x4 * Bayer threshold. `strength` (0-1) scales the spread error and the threshold offset; 0 changes nothing but rounding */ -export function applyPalette(pixels: Uint8Array, width: number, height: number, palette: Uint8Array, dither: 'none' | 'floyd-steinberg' | 'atkinson' | 'ordered', strength: number): void { +export function applyPalette(pixels: Uint8Array, width: number, height: number, palette: Uint8Array, dither: DitherMethod, strength: number): void { const entries = palette.length / 3; if (!entries) return; const nearest = nearestSearch(palette, entries); @@ -444,15 +481,25 @@ function createLookup(palette: Uint8Array, entries: number): (r: number, g: numb }; } +// the palette indices of the pixels mapped by applyPalette() (no dithering, Atkinson or ordered) +function paletteIndices(pixels: Uint8Array, width: number, palette: Uint8Array, dither: DitherMethod, strength: number): Uint8Array { + const mapped = pixels.slice(); + applyPalette(mapped, width, (pixels.length >> 2) / width, palette, dither, strength); + const lookup = new Map(); + for (let i = palette.length / 3 - 1; i >= 0; i--) lookup.set(palette[i * 3] << 16 | palette[i * 3 + 1] << 8 | palette[i * 3 + 2], i); + const indices = new Uint8Array(pixels.length >> 2); + for (let p = 0; p < indices.length; p++) indices[p] = lookup.get(mapped[p * 4] << 16 | mapped[p * 4 + 1] << 8 | mapped[p * 4 + 2]) ?? 0; + return indices; +} + // serpentine floyd-steinberg error diffusion -function ditherMap(pixels: Uint8Array, width: number, palette: Uint8Array, entries: number): Uint8Array { +function ditherMap(pixels: Uint8Array, width: number, palette: Uint8Array, entries: number, strength: number): Uint8Array { const height = (pixels.length >> 2) / width; const lookup = createLookup(palette, entries); const indices = new Uint8Array(pixels.length >> 2); let current = new Float32Array((width + 2) * 3); let next = new Float32Array((width + 2) * 3); - const strength = 0.85; for (let y = 0; y < height; y++) { const reverse = y & 1; diff --git a/src/codecs/tga.ts b/src/codecs/tga.ts index 16462973..7a162219 100644 --- a/src/codecs/tga.ts +++ b/src/codecs/tga.ts @@ -1,7 +1,7 @@ import { encode as utf8 } from '../util/utf8.ts'; -import { MAX_PIXELS, checkPixels } from '../util/limits.ts'; +import { MAX_PIXELS, checkPixels, checkFormatSize } from '../util/limits.ts'; -// Truevision TGA: color mapped, truecolor and greyscale images, uncompressed or run length encoded +// Truevision TGA: color mapped, truecolor and grayscale images, uncompressed or run length encoded const SIGNATURE = 'TRUEVISION-XFILE.\0'; @@ -68,7 +68,7 @@ export function isTGA(d: Uint8Array): boolean { return h.imageType & 8 ? d.length > dataStart : d.length >= dataStart + pixelBytes; } -// reads a 15/16/24/32 bit color (BGR(A), 5 bits per channel for 15/16), or 8 bit grey (color maps) +// reads a 15/16/24/32 bit color (BGR(A), 5 bits per channel for 15/16), or 8 bit gray (color maps) function readColor(d: Uint8Array, o: number, bits: number, alphaBits: number, out: Uint8Array, p: number): void { if (bits === 8) { out[p] = out[p + 1] = out[p + 2] = d[o]; @@ -208,8 +208,9 @@ function extensionArea({ author, comment, time, software }: Extension, alpha: bo return area; } -export function encode(rgba: Uint8Array, width: number, height: number, extension?: Extension): Uint8Array { - if (width < 1 || height < 1 || width > 65535 || height > 65535) throw new RangeError('TGA: dimensions must be 1-65535'); +export function encode(rgba: Uint8Array, width: number, height: number, extension?: Extension): Uint8Array { + if (width < 1 || height < 1) throw new RangeError('TGA: dimensions must be at least 1'); + checkFormatSize('TGA', width, height, 65535); let opaque = true; for (let i = 3; i < rgba.length; i += 4) if (rgba[i] !== 255) { opaque = false; break; } diff --git a/src/codecs/tiff.ts b/src/codecs/tiff.ts index 825e05bf..5a7c3ff3 100644 --- a/src/codecs/tiff.ts +++ b/src/codecs/tiff.ts @@ -37,7 +37,7 @@ const COMPRESSION_NAMES: Record = { 2: 'CCITT RLE', 3: 'CCITT fa * Decodes the first image of a TIFF into 8-bit RGBA pixel data * Supports classic and BigTIFF in both byte orders, strips and tiles, chunky and planar data, * no/LZW/deflate/PackBits/JPEG compression, horizontal and floating point predictors, - * 1-32 bit integer and 32/64 bit float samples (auto-ranged), greyscale, palette, RGB, CMYK and YCbCr images with alpha + * 1-32 bit integer and 32/64 bit float samples (auto-ranged), grayscale, palette, RGB, CMYK and YCbCr images with alpha * @param {Uint8Array} data * @return {{width: number, height: number, pixels: Uint8Array}} */ @@ -142,6 +142,7 @@ export async function decode(data: Uint8Array, maxPixels = MAX_PIXELS): Promise< const samplesPerPixel = value(TAGS.SamplesPerPixel, 1); const bitsPerSample = values(TAGS.BitsPerSample, [1]); const bps = bitsPerSample[0]; + if (typeof bps !== 'number') throw new Error('TIFF: invalid BitsPerSample'); if (bitsPerSample.some(b => b !== bps)) throw new Error('TIFF: mixed bit depths are not supported'); const compression = value(TAGS.Compression, 1); @@ -155,7 +156,7 @@ export async function decode(data: Uint8Array, maxPixels = MAX_PIXELS): Promise< if (COMPRESSION_NAMES[compression]) throw new Error(`TIFF: ${COMPRESSION_NAMES[compression]} compression is not supported`); if (![1, 5, 7, 8, 32773, 32946].includes(compression)) throw new Error(`TIFF: compression ${compression} is not supported`); if (![0, 1, 2, 3, 5, 6].includes(photometric)) throw new Error(`TIFF: photometric interpretation ${photometric} is not supported`); - if (sampleFormat === 3 ? bps !== 32 && bps !== 64 : bps < 1 || bps > 32) throw new Error(`TIFF: ${bps}-bit samples are not supported`); + if (sampleFormat === 3 ? bps !== 32 && bps !== 64 : bps < 1 || bps > 32) throw new Error(`TIFF: ${bps}-bit ${sampleFormat === 3 ? 'floating-point ' : ''}samples are not supported`); const colorChannels = ({ 0: 1, 1: 1, 2: 3, 3: 1, 5: 4, 6: 3 } as Record)[photometric]; if (samplesPerPixel < colorChannels) throw new Error('TIFF: not enough samples per pixel'); @@ -187,6 +188,8 @@ export async function decode(data: Uint8Array, maxPixels = MAX_PIXELS): Promise< // memory than the pixels checkPixels(segmentWidth, segmentHeight, Math.max(4 * width * height, 1 << 20)); checkBytes(Math.ceil(width * samplesPerPixel * bps / 8) * height, maxPixels); + // (only the first four samples show: more are multispectral bands, whose count would only multiply the memory) + if (samplesPerPixel > 32) throw new Error('TIFF: unsupported number of samples per pixel'); const pixels = new Uint8Array(width * height * 4); // JPEG compressed segments decode straight to RGBA @@ -205,7 +208,7 @@ export async function decode(data: Uint8Array, maxPixels = MAX_PIXELS): Promise< stream = joined; } - const decoded = jpeg.decode(stream, { transform }); + const decoded = jpeg.decode(stream, { transform, maxPixels }); blitRGBA(decoded.pixels, decoded.width, decoded.height, pixels, width, height, (s % segmentsAcross) * segmentWidth, (s / segmentsAcross | 0) * segmentHeight); } @@ -221,8 +224,11 @@ export async function decode(data: Uint8Array, maxPixels = MAX_PIXELS): Promise< if (subsampled) { if (tiled || planar || bps !== 8) throw new Error('TIFF: subsampled YCbCr is only supported for 8-bit strips'); const [h, v] = subsampling; + // (the factors the specification allows: a bigger one would make the units larger than the image) + if (![1, 2, 4].includes(h) || ![1, 2, 4].includes(v)) throw new Error('TIFF: unsupported YCbCr subsampling'); const unitsPerRow = Math.ceil(width / h); const unitRowBytes = unitsPerRow * (h * v + 2); + checkBytes(Math.ceil(height / v) * unitRowBytes, maxPixels); const units = new Uint8Array(Math.ceil(height / v) * unitRowBytes); let written = 0; diff --git a/src/codecs/vp8.ts b/src/codecs/vp8.ts index 32e75f64..c1e8ae7f 100644 --- a/src/codecs/vp8.ts +++ b/src/codecs/vp8.ts @@ -357,7 +357,7 @@ export function decode(data: Uint8Array, maxPixels = MAX_PIXELS): { width: numbe } } - if (tokens.exhausted && d.exhausted) throw new Error('VP8: unexpected end of data'); + if (tokens.exhausted || d.exhausted) throw new Error('VP8: unexpected end of data'); } // a frame level of 0 disables the filter, whatever the segments say (RFC 6386 section 15) diff --git a/src/codecs/vp8l.ts b/src/codecs/vp8l.ts index ec31f22a..75acb095 100644 --- a/src/codecs/vp8l.ts +++ b/src/codecs/vp8l.ts @@ -7,7 +7,7 @@ */ import { ByteWriter } from '../util/bytes.ts'; -import { MAX_PIXELS, checkPixels } from '../util/limits.ts'; +import { MAX_PIXELS, checkPixels, checkFormatSize } from '../util/limits.ts'; import { runChunks, shared, type ChunkTask, type Thread } from '../util/threads.ts'; /** decoded VP8L image: ARGB pixels (0xAARRGGBB) */ @@ -570,7 +570,7 @@ class BitWriter extends ByteWriter { } } - override finish(): Uint8Array { + override finish(): Uint8Array { if (this.count > 0) this.write(0, 8 - this.count); return super.finish(); } @@ -1579,7 +1579,8 @@ export function predictorChunks({ p, src, modes, width, height, bits, candidates * predicting them compresses better (smooth gradients, like alpha) */ export async function encode(argb: Uint32Array, width: number, height: number, threads: Thread[] | null = null, effort = 2): Promise { - if (width < 1 || height < 1 || width > 16384 || height > 16384) throw new RangeError('VP8L: dimensions must be 1-16384'); + if (width < 1 || height < 1) throw new RangeError('WebP: dimensions must be at least 1'); + checkFormatSize('WebP', width, height, 16384); const tuning = TUNING[Math.min(2, effort)]; const colors = new Map(); for (let i = 0; i < argb.length && colors.size <= 256; i++) if (!colors.has(argb[i])) colors.set(argb[i], colors.size); diff --git a/src/codecs/webp.ts b/src/codecs/webp.ts index d7cdc9a1..34b4d793 100644 --- a/src/codecs/webp.ts +++ b/src/codecs/webp.ts @@ -9,8 +9,8 @@ import * as vp8 from './vp8.ts'; import { encodeVP8, encodeAlpha } from './vp8-enc.ts'; import { rgbaToYUV } from './vp8-enc-dsp.ts'; import { orientation as exifOrientation } from './exif.ts'; -import { MAX_PIXELS, checkPixels } from '../util/limits.ts'; -import { effort as checkEffort, quality as checkQuality } from '../util/options.ts'; +import { MAX_PIXELS, checkPixels, checkFormatSize } from '../util/limits.ts'; +import { effort as checkEffort, quality as checkQuality, boolean as checkBoolean } from '../util/options.ts'; import { startThreads } from '../util/threads.ts'; const fourCC = (s: string): number => s.charCodeAt(0) | s.charCodeAt(1) << 8 | s.charCodeAt(2) << 16 | s.charCodeAt(3) << 24; @@ -40,7 +40,8 @@ export interface WebPAnimation { loopCount: number; /** ARGB background color hint (decoders, like browsers, are free to ignore it) */ background: number; - frames: WebPFrame[]; + /** decoded one at a time as they are iterated (once), so compositing doesn't hold all of them */ + frames: Iterable; /** the embedded ICC profile */ icc?: Uint8Array; /** Exif orientation (1-8) */ @@ -50,6 +51,8 @@ export interface WebPAnimation { interface Chunk { type: number; data: Uint8Array; + /** the chunk is cut off: the data ends before its size says */ + cut?: boolean; } function chunks(data: Uint8Array, start: number, end: number): Chunk[] { @@ -61,7 +64,7 @@ function chunks(data: Uint8Array, start: number, end: number): Chunk[] { const size = view.getUint32(offset + 4, true); const dataStart = offset + 8; // tolerate a truncated last chunk, the bitstream decoders report missing data - out.push({ type, data: data.subarray(dataStart, Math.min(end, dataStart + size)) }); + out.push({ type, data: data.subarray(dataStart, Math.min(end, dataStart + size)), cut: dataStart + size > end }); offset = dataStart + size + (size & 1); } return out; @@ -83,6 +86,8 @@ const u24 = (d: Uint8Array, o: number): number => d[o] | d[o + 1] << 8 | d[o + 2 function decodeBitstream(list: Chunk[], maxPixels: number): { width: number, height: number, pixels: Uint8Array } { let alpha: Chunk | null = null; for (const chunk of list) { + // (the bitstream decoders read missing bytes as zeros, so a chunk that ends before its size says is cut off) + if ((chunk.type === ALPH || chunk.type === VP8L || chunk.type === VP8) && chunk.cut) throw new Error('WebP: the image data is truncated'); if (chunk.type === ALPH) alpha ??= chunk; else if (chunk.type === VP8L) { const { width, height, argb } = vp8l.decode(chunk.data, maxPixels); @@ -181,9 +186,10 @@ export function decode(data: Uint8Array, maxPixels = MAX_PIXELS): { width: numbe } /** - * Decodes an animated WebP into its frames (not composited); still WebPs become a single frame + * Decodes an animated WebP into its frames (not composited, decoded one at a time as they are iterated); still WebPs + * become a single frame */ -export function decodeAnimation(data: Uint8Array, onlyFirstFrame = false, maxPixels = MAX_PIXELS): WebPAnimation { +export function decodeAnimation(data: Uint8Array, firstFrameOnly = false, maxPixels = MAX_PIXELS): WebPAnimation { const list = container(data); const header = list[0]; if (!header || header.type !== VP8X || !list.some(c => c.type === ANMF)) { @@ -194,21 +200,24 @@ export function decodeAnimation(data: Uint8Array, onlyFirstFrame = false, maxPix if (header.data.length < 10) throw new Error('WebP: invalid VP8X chunk'); const width = u24(header.data, 4) + 1, height = u24(header.data, 7) + 1; // every frame is composited onto a canvas of its own - checkPixels(width, height, maxPixels, onlyFirstFrame ? 1 : list.filter(c => c.type === ANMF).length); + checkPixels(width, height, maxPixels, firstFrameOnly ? 1 : list.filter(c => c.type === ANMF).length); let loopCount = 0, background = 0; - const frames: WebPFrame[] = []; + const anim = list.find(c => c.type === ANIM && c.data.length >= 6); + if (anim) { + const d = anim.data; + // stored as BGRA + background = (d[3] << 24 | d[2] << 16 | d[1] << 8 | d[0]) >>> 0; + loopCount = d[4] | d[5] << 8; + } + // (a frame whose chunk is cut off is incomplete: the whole ones before it are the animation) + const anmf = list.filter(c => c.type === ANMF && !c.cut); + if (!anmf.length && list.some(c => c.type === ANMF)) throw new Error('WebP: unexpected end of data'); + for (const { data } of anmf) if (data.length < 16) throw new Error('WebP: invalid ANMF chunk'); - for (const chunk of list) { - if (chunk.type === ANIM && chunk.data.length >= 6) { - const d = chunk.data; - // stored as BGRA - background = (d[3] << 24 | d[2] << 16 | d[1] << 8 | d[0]) >>> 0; - loopCount = d[4] | d[5] << 8; - } else if (chunk.type === ANMF) { - const d = chunk.data; - if (d.length < 16) throw new Error('WebP: invalid ANMF chunk'); + function* frames(): Generator { + for (const { data: d } of anmf) { const frame = decodeBitstream(chunks(d, 16, d.length), maxPixels); - frames.push({ + yield { x: u24(d, 0) * 2, y: u24(d, 3) * 2, width: frame.width, @@ -217,13 +226,12 @@ export function decodeAnimation(data: Uint8Array, onlyFirstFrame = false, maxPix blend: (d[15] & 2) === 0, dispose: (d[15] & 1) === 1, pixels: frame.pixels - }); - if (onlyFirstFrame) break; + }; + if (firstFrameOnly) return; } } - if (!frames.length) throw new Error('WebP: animation without frames'); - return { width, height, loopCount, background, frames, icc: list.find(c => c.type === ICCP)?.data, orientation: orientationOf(list) }; + return { width, height, loopCount, background, frames: frames(), icc: list.find(c => c.type === ICCP)?.data, orientation: orientationOf(list) }; } // the Exif orientation of a WebP's chunks, 1 without one @@ -234,7 +242,7 @@ function orientationOf(list: Chunk[]): number { /** * Composites animation frames onto the canvas like browsers do (transparent background, the background color hint - * is ignored as the spec allows) + * is ignored as the spec allows). Each frame is let go once it is composited */ export function composite({ width, height, frames }: WebPAnimation): Array<{ pixels: Uint8Array, duration: number }> { const canvas = new Uint8Array(width * height * 4); @@ -302,7 +310,7 @@ function concat(parts: Uint8Array[]): Uint8Array { return out; } -function riff(chunks: Uint8Array[]): Uint8Array { +function riff(chunks: Uint8Array[]): Uint8Array { let size = 4; for (const c of chunks) size += c.length; const out = new Uint8Array(8 + size); @@ -340,7 +348,7 @@ const MIN_THREADED_PIXELS = 1536 << 10, PIXELS_PER_THREAD = 512 << 10; * @param exif Exif data (a TIFF header and IFDs), needs the extended format (VP8X) * @param effort 0 fast, 1 in between, 2 (and above) the most compression */ -export async function encode(rgba: Uint8Array, width: number, height: number, exif?: Uint8Array, threads = 1, effort = 2): Promise { +export async function encode(rgba: Uint8Array, width: number, height: number, exif?: Uint8Array, threads = 1, effort = 2): Promise> { const n = Math.min(threads, Math.floor(width * height / PIXELS_PER_THREAD)); const pool = n > 1 && width * height >= MIN_THREADED_PIXELS ? startThreads(n) : null; let stream: Uint8Array; @@ -377,14 +385,17 @@ export interface LossyOptions { /** * Checks the options of lossy images and frames (quality and alpha quality 0-100, effort 0-6) - * @returns undefined without a quality: lossless + * @returns undefined without a quality or with 100: lossless */ export function lossyOptions(quality: number | undefined, effort: number, sharp: boolean, alphaQuality: number): LossyOptions | undefined { - // (checked for lossless images too, which don't use it) + // (checked for lossless images too, which don't use them) checkEffort(effort, 6); + const a = checkQuality(alphaQuality, 'alphaQuality'); + checkBoolean(sharp, 'sharpYuv'); if (quality === undefined) return undefined; - const q = checkQuality(quality), a = checkQuality(alphaQuality, 'alphaQuality'); - return { quality: q, method: effort, sharp, alphaQuality: Math.round(a) }; + const q = checkQuality(quality); + // (100 is lossless, like for AVIF and JPEG XL) + return q === 100 ? undefined : { quality: q, method: effort, sharp, alphaQuality: Math.round(a) }; } /** @@ -392,7 +403,7 @@ export function lossyOptions(quality: number | undefined, effort: number, sharp: * isn't opaque) * @param exif Exif data (a TIFF header and IFDs), needs the extended format (VP8X) */ -export async function encodeLossy(rgba: Uint8Array, width: number, height: number, lossy: LossyOptions, exif?: Uint8Array): Promise { +export async function encodeLossy(rgba: Uint8Array, width: number, height: number, lossy: LossyOptions, exif?: Uint8Array): Promise> { const { alpha, chunks } = await lossyChunks(rgba, width, height, lossy); if (!alpha && !exif) return riff(chunks); @@ -405,7 +416,7 @@ export async function encodeLossy(rgba: Uint8Array, width: number, height: numbe // the ALPH (if not opaque) and VP8 chunks of a lossy image async function lossyChunks(rgba: Uint8Array, width: number, height: number, { quality, method, sharp, alphaQuality }: LossyOptions): Promise<{ alpha: boolean, chunks: Uint8Array[] }> { - if (width > 16383 || height > 16383) throw new RangeError('WebP: lossy images can be at most 16383 pixels wide and high'); + checkFormatSize('WebP', width, height, 16383); const picture = rgbaToYUV(rgba, width, height, sharp); const frame = encodeVP8(picture, quality, method); // (libwebp counts the padding byte in the chunk's size) @@ -449,9 +460,9 @@ export function lossyTolerance(quality: number): number { * @param lossy For lossy frames * @param effort For lossless frames: 0 fast, 1 in between, 2 (and above) the most compression */ -export async function encodeAnimation(frames: WebPEncodeFrame[], width: number, height: number, plays: number, exif?: Uint8Array, lossy?: LossyOptions, effort = 2): Promise { - if (!frames.length) throw new Error('WebP: an animation needs at least one frame'); - if (width > 1 << 24 || height > 1 << 24) throw new RangeError('WebP: canvas too large'); +export async function encodeAnimation(frames: WebPEncodeFrame[], width: number, height: number, plays: number, exif?: Uint8Array, lossy?: LossyOptions, effort = 2): Promise> { + if (!frames.length) throw new RangeError('WebP: an animation needs at least one frame, not 0'); + checkFormatSize('WebP', width, height, 1 << 24); let alpha = false; for (const [i, f] of frames.entries()) alpha ||= needsAlpha(f, i === 0, width, height); @@ -487,7 +498,7 @@ export async function frameChunk(f: WebPEncodeFrame, lossy?: LossyOptions, effor } /** An animation's file from its frames' ANMF chunks */ -export function animationFile(frames: Uint8Array[], width: number, height: number, plays: number, alpha: boolean, exif?: Uint8Array): Uint8Array { +export function animationFile(frames: Uint8Array[], width: number, height: number, plays: number, alpha: boolean, exif?: Uint8Array): Uint8Array { const vp8x = new Uint8Array(10); vp8x[0] = 2 | (alpha ? 16 : 0) | (exif ? 8 : 0); // animation, alpha, exif set24(vp8x, 4, width - 1); diff --git a/src/codecs/zlib.ts b/src/codecs/zlib.ts index b957e6b3..6e8b9fb2 100644 --- a/src/codecs/zlib.ts +++ b/src/codecs/zlib.ts @@ -107,7 +107,7 @@ function inflate(dat: Uint8Array, buf: Uint8Array): Uint8Array { if (!sl) return buf.subarray(0, 0); const tbts = sl * 8; - let final = 0, pos = 0, bt = 0; + let final: number, pos = 0, bt = 0; do { let lm: Uint16Array, dm: Uint16Array, lbt: number, dbt: number; diff --git a/src/colors.ts b/src/colors.ts index d6b29fca..d737f699 100644 --- a/src/colors.ts +++ b/src/colors.ts @@ -1,11 +1,6 @@ -import { finite, color as checkColor } from './util/options.ts'; +import { shown, finite, notNaN, byte, unitInterval, color as checkColor } from './util/options.ts'; import type { Color } from './image.ts'; -/** Clamps and rounds a channel value to 0..255 */ -export function channel(value: number): number { - return value > 255 ? 255 : value > 0 ? Math.round(value) : 0; -} - // wraps a hue into 0..1 (negative hues included), exactly like (h % 1 + 1) % 1 but without the slow float modulo export function wrapHue(h: number): number { const t = h - Math.trunc(h) + 1; @@ -62,21 +57,29 @@ export function rgbaToHSLA(r: number, g: number, b: number, a: number): [h: numb return [h, s, l, a / 255]; } +/** A position along a gradient: a number (the infinities are fine, they reach the ends), not NaN */ +function checkPosition(position: number): void { + notNaN(position, 'gradient position'); +} + function gradientBetween(startColor: Color, endColor: Color): (position: number) => Color { - const sr = startColor >>> 24; - const sg = startColor >> 16 & 0xff; - const sb = startColor >> 8 & 0xff; - const sa = startColor & 0xff; - const er = (endColor >>> 24) - sr; - const eg = (endColor >> 16 & 0xff) - sg; - const eb = (endColor >> 8 & 0xff) - sb; - const ea = (endColor & 0xff) - sa; + const sr = startColor >>> 24, sg = startColor >> 16 & 0xff, sb = startColor >> 8 & 0xff, sa = startColor & 0xff; + const er = (endColor >>> 24) - sr, eg = (endColor >> 16 & 0xff) - sg, eb = (endColor >> 8 & 0xff) - sb, ea = (endColor & 0xff) - sa; + // opaque colors blend directly + if (sa === 255 && ea === 0) return position => { + const r = sr + position * er, g = sg + position * eg, b = sb + position * eb; + return (((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | 0xff) >>> 0; + }; + + // with transparency the colors blend premultiplied (like CSS does), so a color doesn't leak from what is invisible + const pr = sr * sa / 255, pg = sg * sa / 255, pb = sb * sa / 255; + const dr = (er + sr) * (ea + sa) / 255 - pr, dg = (eg + sg) * (ea + sa) / 255 - pg, db = (eb + sb) * (ea + sa) / 255 - pb; return position => { - const r = sr + position * er; - const g = sg + position * eg; - const b = sb + position * eb; const a = sa + position * ea; + if (a <= 0) return 0; + const k = 255 / a; + const r = Math.min(255, (pr + position * dr) * k + 1e-9), g = Math.min(255, (pg + position * dg) * k + 1e-9), b = Math.min(255, (pb + position * db) * k + 1e-9); return (((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | (a & 0xff)) >>> 0; }; } @@ -86,10 +89,12 @@ function gradientBetween(startColor: Color, endColor: Color): (position: number) * and return, and gradients between colors */ export class Colors { - private constructor() {} + private constructor() { + throw new TypeError('Colors only has static methods, like Colors.fromRGBA()'); + } /** - * Converts RGBA components to an RGBA value, values are rounded and clamped to 0..255 + * Converts RGBA components to an RGBA value. Fractions are rounded, values outside of 0..255 throw a `RangeError` * @param r red (0..255) * @param g green (0..255) * @param b blue (0..255) @@ -97,11 +102,7 @@ export class Colors { * @returns RGBA value */ static fromRGBA(r: number, g: number, b: number, a: number): Color { - r = finite(r, 'red'); - g = finite(g, 'green'); - b = finite(b, 'blue'); - a = finite(a, 'alpha'); - return (channel(r) << 24 | channel(g) << 16 | channel(b) << 8 | channel(a)) >>> 0; + return (byte(r, 'red') << 24 | byte(g, 'green') << 16 | byte(b, 'blue') << 8 | byte(a, 'alpha')) >>> 0; } /** @@ -117,20 +118,17 @@ export class Colors { /** * Converts HSLA colors to RGBA colors - * @param h hue (0..1) - * @param s saturation (0..1) - * @param l lightness (0..1) - * @param a opacity (0..1) + * @param h hue in degrees (0..360, like CSS' `hsl()`: 0 red, 120 green, 240 blue; other values wrap around) + * @param s saturation (0..1, else a `RangeError`) + * @param l lightness (0..1, else a `RangeError`) + * @param a opacity (0..1, else a `RangeError`) * @returns color */ static fromHSLA(h: number, s: number, l: number, a: number): Color { - h = wrapHue(finite(h, 'hue')); - s = finite(s, 'saturation'); - l = finite(l, 'lightness'); - a = finite(a, 'alpha'); - s = Math.min(1, Math.max(0, s)); - l = Math.min(1, Math.max(0, l)); - a = Math.min(1, Math.max(0, a)); + h = wrapHue(finite(h, 'hue') / 360); + s = unitInterval(s, 'saturation'); + l = unitInterval(l, 'lightness'); + a = unitInterval(a, 'alpha'); let r: number, g: number, b: number; @@ -149,10 +147,10 @@ export class Colors { } /** - * Converts HSL colors to RGBA colors (assuming an opacity of 255) - * @param h hue (0..1) - * @param s saturation (0..1) - * @param l lightness (0..1) + * Converts HSL colors to RGBA colors (fully opaque) + * @param h hue in degrees (0..360, like CSS' `hsl()`; other values wrap around) + * @param s saturation (0..1, else a `RangeError`) + * @param l lightness (0..1, else a `RangeError`) * @returns color */ static fromHSL(h: number, s: number, l: number): Color { @@ -170,7 +168,7 @@ export class Colors { } /** - * Converts a color value to an array of RGB values (ignoring the colors alpha) + * Converts a color value to an array of RGB values (ignoring the color's alpha) * @param color The color value to convert * @returns The RGB values ([R, G, B]) */ @@ -182,38 +180,58 @@ export class Colors { /** * Converts a color to an array of HSLA values * @param color The color value to convert - * @returns The HSLA values ([H, S, L, A]), H and S and L and A in 0..1 + * @returns The HSLA values ([H, S, L, A]): H in degrees (0..360, like CSS' `hsl()`), S, L and A in 0..1 */ static toHSLA(color: Color): [h: number, s: number, l: number, a: number] { const [r, g, b, a] = Colors.toRGBA(color); - return rgbaToHSLA(r, g, b, a); + const [h, s, l, alpha] = rgbaToHSLA(r, g, b, a); + return [h * 360, s, l, alpha]; } /** * Creates a multi-point gradient generator - * @param colors The gradient points to use (e.g. `{0: 0xff0000ff, 1: 0x00ff00ff}`) + * @param stops The colors along the gradient: their positions (0..1) and colors (`{ 0: 0xff0000ff, 1: 0x00ff00ff }`), + * or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link GradientOptions.stops} + * @remarks A stop may lie outside 0..1 (`{ 0: red, 2: blue }`): it is where it says, so the part between 0 and 1 + * shows only part of the way between its colors. Before the first stop and after the last one, the gradient has + * their colors, and at a stop its color. Stops at the same position make a hard edge: the gradient jumps from + * the earlier stop's color to the later one's, which is the color at that position (like CSS) * @return The gradient generator. The function argument is the position in the gradient (0..1). */ - static gradient(colors: Record): (position: number) => Color { + static gradient(stops: Record | Color[]): (position: number) => Color { + if (typeof stops !== 'object' || stops === null) throw new TypeError(`Colors.gradient() takes an array of colors or an object of positions and colors, not ${shown(stops)}`); + let colors: Record; + if (Array.isArray(stops)) { + if (!stops.length) throw new RangeError('Colors.gradient() takes at least one color, not 0'); + // (one color is a gradient of two equal ones) + const list = stops.length === 1 ? [stops[0], stops[0]] : stops; + colors = Object.fromEntries(list.map((color, i) => [i / (list.length - 1), color])); + } else colors = stops; const entries = Object.entries(colors).sort((a, b) => Number(a[0]) - Number(b[0])); const positions = entries.map(e => finite(parseFloat(e[0]), 'gradient position')); const values = entries.map(e => checkColor(e[1])); - if (positions.length === 0) throw new RangeError('Invalid gradient point count'); + if (positions.length === 0) throw new RangeError('Colors.gradient() takes at least one color, not 0'); else if (positions.length === 1) { - return () => values[0]; + return position => { + checkPosition(position); + return values[0]; + }; } else if (positions.length === 2) { const gradient = gradientBetween(values[0], values[1]); return position => { - if (position <= positions[0]) return values[0]; + checkPosition(position); + // (at a stop the later stop's color when both are at one position, like CSS) if (position >= positions[1]) return values[1]; + if (position <= positions[0]) return values[0]; return gradient((position - positions[0]) / (positions[1] - positions[0])); }; } - const minDef = Math.min(...positions); - const maxDef = Math.max(...positions); + // (sorted: the first and the last; no spread, which overflows the call stack for many stops) + const minDef = positions[0]; + const maxDef = positions[positions.length - 1]; const gradients: Array<{ min: number, max: number, gradient: (position: number) => Color }> = []; for (let i = 0; i < positions.length; i++) { @@ -221,6 +239,8 @@ export class Colors { if (minPos === undefined) continue; const maxPos = positions[i]; + // (two stops at the same position: a hard edge, nothing in between) + if (maxPos === minPos) continue; let minVal = values[i - 1]; if (minVal === undefined) minVal = values[i]; @@ -231,14 +251,27 @@ export class Colors { gradients.push({min: minPos, max: maxPos, gradient}); } + // (every stop at the same position: a hard edge between the first and the last color) + if (!gradients.length) return position => { + checkPosition(position); + return position < minDef ? values[0] : values[values.length - 1]; + }; + + // the color at each stop's position: the last stop's there (a hard edge shows the later color, like CSS) + const atStop = new Map(positions.map((p, i) => [p, values[i]])); return position => { - if (position <= minDef) return gradients[0].gradient(0); - if (position >= maxDef) return gradients[gradients.length - 1].gradient(1); + checkPosition(position); + // (before and after the stops their colors, like with 2 stops: interpolating would lose the color of a + // transparent stop) + if (position < minDef) return values[0]; + if (position >= maxDef) return values[values.length - 1]; + const stop = atStop.get(position); + if (stop !== undefined) return stop; for (const gradient of gradients) - if (position >= gradient.min && position <= gradient.max) + if (position > gradient.min && position < gradient.max) return gradient.gradient((position - gradient.min) / (gradient.max - gradient.min)); - throw new RangeError(`Invalid gradient position: ${position}`); + throw new RangeError(`The gradient has no color at position ${position}`); }; } } diff --git a/src/frame.ts b/src/frame.ts index 37268a40..bc2df4c3 100644 --- a/src/frame.ts +++ b/src/frame.ts @@ -1,71 +1,63 @@ -import { Image, ResizeMode, ResizeOptions, ResizeToOptions, Color, TrimOptions, resizeArguments } from './image.ts'; -import { isOptions, finite } from './util/options.ts'; +import { Image, ResizeOptions, ResizeToOptions, TrimOptions, RotateOptions, TransformOptions, AffineTransform, ShadowOptions, OutlineOptions } from './image.ts'; +import { instance, checkOptions, finite, nonNegative, oneOf } from './util/options.ts'; +import { describe } from './util/inspect.ts'; -/** Names of the frame disposal modes, see {@link Frame.disposalMode} */ -export type FrameDisposalMode = 'any' | 'keep' | 'previous' | 'background'; -/** - * Names of the frame disposal modes, see {@link Frame.disposalMode} - * @deprecated Use {@link FrameDisposalMode}, its name in 4.0 - */ -export type FrameDisposalModeName = FrameDisposalMode; /** - * Ids of the frame disposal modes, as GIFs store them (0 any, 1 keep, 2 previous, 3 background) - * @deprecated Use the names ({@link FrameDisposalMode}: `'any'`, `'keep'`, `'previous'`, `'background'`), the ids will - * be removed in 4.0 + * What happens to a frame's area before the next frame is drawn, see {@link Frame.disposalMode}: + * - `'keep'` (the default): the frame stays, the next one is drawn over it + * - `'background'`: the frame's area is cleared to transparent + * - `'previous'`: the frame's area goes back to what it was before the frame + * - `'any'`: the decoder decides (in practice like `'keep'`) */ -export type FrameDisposalModeId = 0 | 1 | 2 | 3; +export type FrameDisposalMode = 'any' | 'keep' | 'previous' | 'background'; -// (the ids inside the library, without the deprecation shown to its own code) +// the ids the library stores the modes as (0 any, 1 keep, 2 previous, 3 background, like GIFs) type DisposalId = 0 | 1 | 2 | 3; -const DISPOSAL_MODES: readonly FrameDisposalModeName[] = ['any', 'keep', 'previous', 'background']; - -/** - * What happens to a frame's area before the next frame is drawn, see {@link Frame.disposalMode} - * @deprecated Use the names, `'background'` for `FrameDisposalModes.BACKGROUND`: `FrameDisposalModes` is removed in 4.0 - */ -export class FrameDisposalModes { - /** The decoder decides (in practice like {@link FrameDisposalModes.KEEP}) */ - static readonly ANY = 'any'; +const DISPOSAL_MODES: readonly FrameDisposalMode[] = ['any', 'keep', 'previous', 'background']; - /** The frame stays, the next one is drawn over it (the default) */ - static readonly KEEP = 'keep'; - - /** The frame's area goes back to what it was before the frame */ - static readonly PREVIOUS = 'previous'; - - /** The frame's area is cleared to transparent */ - static readonly BACKGROUND = 'background'; - - private constructor() {} -} - -/** Options of {@link Frame} and {@link Frame.from} */ +/** Options of {@link Frame} */ export interface FrameOptions { - /** The frame's duration in milliseconds. Default: `100` */ + /** + * The frame's duration in milliseconds + * @defaultValue `100` + */ duration?: number; - /** The frame's offset on the x-axis. Default: `0` */ + /** + * The frame's offset on the x-axis + * @defaultValue `0` + */ xOffset?: number; - /** The frame's offset on the y-axis. Default: `0` */ + /** + * The frame's offset on the y-axis + * @defaultValue `0` + */ yOffset?: number; - /** The frame's disposal mode, see {@link Frame.disposalMode}. Default: `'keep'` */ - disposalMode?: FrameDisposalModeName | FrameDisposalModeId; + /** + * The frame's disposal mode, see {@link Frame.disposalMode} + * @defaultValue `'keep'` + */ + disposalMode?: FrameDisposalMode; } /** - * Represents a frame of an {@link Animation}: an {@link Image} with a duration, offsets and a disposal mode, so every - * method of {@link Image} works on it too + * A frame of an {@link Animation}: an {@link Image} ({@link Frame.image}) with a duration, offsets and a disposal mode + * @remarks + * The frame has the methods that change the image's size (`resize()` including its `'contain'` and `'cover'` fit + * modes, `scale()`, `crop()`, `trim()`, `rotate()`, `transform()`, `dropShadow()` and `outline()`), which move the + * offsets along so the frame stays in place in the animation; every other change goes to the image + * (`frame.image.blur(2)`). The image's own size-changing methods leave the offsets as they are. Offsets can become + * negative: the parts of a frame outside the animation's canvas aren't encoded */ -export class Frame extends Image { - /** - * Milliseconds. GIFs store hundredths of a second, so this is rounded to 10 ms when encoding a GIF; - * note that browsers play frames shorter than 20 ms with 100 ms - */ - duration: number; - /** The frame's horizontal offset in the animation */ - xOffset: number; - /** The frame's vertical offset in the animation */ - yOffset: number; +export class Frame { + /** @internal @ignore */ + private __image__: Image; + /** @internal @ignore */ + private __duration__ = 100; + /** @internal @ignore */ + private __x__ = 0; + /** @internal @ignore */ + private __y__ = 0; /** * @internal * @ignore @@ -73,79 +65,104 @@ export class Frame extends Image { private __disposalMode__: DisposalId = 1; /** - * @deprecated Use the name `'any'`: `Frame.DISPOSAL_*` and `FrameDisposalModes` are removed in 4.0 - * @group Deprecated + * @internal + * @ignore */ - static readonly DISPOSAL_ANY: typeof FrameDisposalModes.ANY = FrameDisposalModes.ANY; + static __convert_disposal_mode__(mode: FrameDisposalMode): DisposalId { + return DISPOSAL_MODES.indexOf(oneOf(mode, DISPOSAL_MODES, 'disposal mode')) as DisposalId; + } /** - * @deprecated Use the name `'keep'`: `Frame.DISPOSAL_*` and `FrameDisposalModes` are removed in 4.0 - * @group Deprecated + * Creates a frame of an image. The frame uses the image as it is (it isn't copied): changes to it are the frame's + * @param image The frame's pixels + * @param options See {@link FrameOptions} */ - static readonly DISPOSAL_KEEP: typeof FrameDisposalModes.KEEP = FrameDisposalModes.KEEP; + constructor(image: Image, options?: FrameOptions); + constructor(image: Image, options: FrameOptions = {}) { + if (!(image instanceof Image)) throw new TypeError('A frame takes an Image, like new Frame(image, { duration: 100 })'); + checkOptions(options, 'new Frame(image, { duration: 100 })'); + const { duration = 100, xOffset: x = 0, yOffset: y = 0, disposalMode: disposal = 'keep' } = options; + this.__image__ = image; + this.duration = duration; + this.xOffset = x; + this.yOffset = y; + this.disposalMode = disposal; + } + + /** The frame's pixels. Changing the image changes the frame; the offsets stay as they are */ + get image(): Image { + return this.__image__; + } /** - * @deprecated Use the name `'previous'`: `Frame.DISPOSAL_*` and `FrameDisposalModes` are removed in 4.0 - * @group Deprecated + * Replaces the frame's pixels + * @param image The new image (used as it is, not copied) */ - static readonly DISPOSAL_PREVIOUS: typeof FrameDisposalModes.PREVIOUS = FrameDisposalModes.PREVIOUS; + set image(image: Image) { + instance(image, [Image], 'frame.image'); + this.__image__ = image; + } + + /** The frame's width (its image's) */ + get width(): number { + return this.__image__.width; + } + + /** The frame's height (its image's) */ + get height(): number { + return this.__image__.height; + } /** - * @deprecated Use the name `'background'`: `Frame.DISPOSAL_*` and `FrameDisposalModes` are removed in 4.0 - * @group Deprecated + * The frame's duration in milliseconds (a finite number from 0, else it throws a RangeError). It doesn't have to + * be a whole number: encoding rounds it, to whole milliseconds for APNG and WebP and, as GIFs store hundredths of + * a second, to 10 ms for GIF (1.5 ms becomes 0, 5 ms becomes 10). Browsers play GIF frames shorter than 20 ms with + * 100 ms */ - static readonly DISPOSAL_BACKGROUND: typeof FrameDisposalModes.BACKGROUND = FrameDisposalModes.BACKGROUND; + get duration(): number { + return this.__duration__; + } /** - * @internal - * @ignore + * Sets the duration + * @param duration Milliseconds, a finite number from 0 */ - static __convert_disposal_mode__(mode: FrameDisposalModeName | FrameDisposalModeId): DisposalId { - const id = typeof mode === 'string' ? DISPOSAL_MODES.indexOf(mode) : mode; - if (!(id >= 0 && id <= 3)) - throw new RangeError('Invalid disposal mode'); - - return id as DisposalId; + set duration(duration: number) { + this.__duration__ = nonNegative(duration, 'frame duration'); } /** - * Creates a new, blank frame - * @param width The width in pixels - * @param height The height in pixels - * @param options See {@link FrameOptions} + * The frame's horizontal offset in the animation: an integer, values with a fraction are truncated like image sizes + * (a value that isn't a finite number throws a RangeError) */ - constructor(width: number, height: number, options?: FrameOptions); + get xOffset(): number { + return this.__x__; + } + /** - * Creates a new, blank frame - * @param width The width in pixels - * @param height The height in pixels - * @param duration The frame's duration (in ms) - * @param xOffset The frame's offset on the x-axis - * @param yOffset The frame's offset on the y-axis - * @param disposalMode The frame's disposal mode - * @deprecated Pass {@link FrameOptions} instead, the positional arguments will be removed in 4.0 + * Sets the horizontal offset + * @param x The offset in pixels */ - constructor(width: number, height: number, duration?: number, xOffset?: number, yOffset?: number, disposalMode?: FrameDisposalModeName | FrameDisposalModeId); - constructor(width: number, height: number, durationOrOptions?: number | FrameOptions, xOffset?: number, yOffset?: number, disposalMode?: FrameDisposalModeName | FrameDisposalModeId) { - const { duration = 100, xOffset: x = 0, yOffset: y = 0, disposalMode: disposal = FrameDisposalModes.KEEP } = - isOptions(durationOrOptions) ? durationOrOptions : { duration: durationOrOptions, xOffset, yOffset, disposalMode }; - if (finite(duration, 'frame duration') < 0) - throw new RangeError('Invalid frame duration'); - finite(x, 'x offset'); - finite(y, 'y offset'); - - super(width, height); - this.duration = duration; - this.xOffset = x; - this.yOffset = y; - this.disposalMode = disposal; + set xOffset(x: number) { + // (|| 0: no negative zero) + this.__x__ = Math.trunc(finite(x, 'x offset')) || 0; + } + + /** The frame's vertical offset in the animation: an integer, like {@link Frame.xOffset} */ + get yOffset(): number { + return this.__y__; } /** - * The frame's disposal mode (`'any'`, `'keep'`, `'previous'` or `'background'`). Setting it by id (0-3) is deprecated, - * the ids will be removed in 4.0 + * Sets the vertical offset + * @param y The offset in pixels */ - get disposalMode(): FrameDisposalModeName { + set yOffset(y: number) { + this.__y__ = Math.trunc(finite(y, 'y offset')) || 0; + } + + /** The frame's disposal mode, see {@link FrameDisposalMode} */ + get disposalMode(): FrameDisposalMode { return DISPOSAL_MODES[this.__disposalMode__]; } @@ -160,131 +177,126 @@ export class Frame extends Image { /** * Sets the disposal mode - * @param disposalMode The mode's name (`'any'`, `'keep'`, `'previous'`, `'background'`) or, deprecated, its id (0-3) + * @param disposalMode The mode's name (`'any'`, `'keep'`, `'previous'`, `'background'`) */ - set disposalMode(disposalMode: FrameDisposalModeName | FrameDisposalModeId) { + set disposalMode(disposalMode: FrameDisposalMode) { this.__disposalMode__ = Frame.__convert_disposal_mode__(disposalMode); } /** A short description for debugging, e.g. `Frame<64x64x100ms>` */ - override toString(): string { + toString(): string { return `Frame<${this.width}x${this.height}x${this.duration}ms>`; } - /** - * Converts an Image instance to a Frame, cloning it in the process - * @param image The image to create the frame from - * @param options See {@link FrameOptions} - */ - static from(image: Image, options?: FrameOptions): Frame; - /** - * Converts an Image instance to a Frame, cloning it in the process - * @param image The image to create the frame from - * @param duration The frame's duration (in ms) - * @param xOffset The frame's offset on the x-axis - * @param yOffset The frame's offset on the y-axis - * @param disposalMode The frame's disposal mode - * @deprecated Pass {@link FrameOptions} instead, the positional arguments will be removed in 4.0 - */ - static from(image: Image, duration?: number, xOffset?: number, yOffset?: number, disposalMode?: FrameDisposalModeName | FrameDisposalModeId): Frame; - static from(image: Image, durationOrOptions?: number | FrameOptions, xOffset?: number, yOffset?: number, disposalMode?: FrameDisposalModeName | FrameDisposalModeId): Frame { - if (!(image instanceof Image)) - throw new TypeError('Invalid image passed'); - - const options = isOptions(durationOrOptions) ? durationOrOptions : { duration: durationOrOptions, xOffset, yOffset, disposalMode }; - const frame = new Frame(image.width, image.height, options); - frame.bitmap.set(image.bitmap); - - return frame; + /** Clones the frame: its image (with its pixels and gain map), duration, offsets and disposal mode */ + clone(): Frame { + return new Frame(this.__image__.clone(), { duration: this.duration, xOffset: this.xOffset, yOffset: this.yOffset, disposalMode: this.disposalMode }); } /** - * Clones the frame, including its duration, offsets and disposal mode + * Runs a change of the image, moving the offsets the way the image reports its pixels moved + * @internal + * @ignore */ - override clone(): Frame { - return Frame.from(this, { duration: this.duration, xOffset: this.xOffset, yOffset: this.yOffset, disposalMode: this.disposalMode }); + private __tracked__(change: (image: Image) => unknown): this { + const image = this.__image__; + image.__moved__ = (scaleX, scaleY, x, y) => { + this.xOffset = Math.round(this.xOffset * scaleX + x); + this.yOffset = Math.round(this.yOffset * scaleY + y); + }; + try { + change(image); + } finally { + delete image.__moved__; + } + return this; } /** - * @internal - * @ignore + * Resizes the frame, scaling its offsets along with it (as if the whole animation was resized by the same factor) + * @param width The new width + * @param height The new height + * @param options See {@link ResizeOptions} + */ + resize(width: number, height: number, options?: ResizeOptions): this; + /** + * Resizes the frame, scaling its offsets along with it: to the given width or height (the other side keeps the + * aspect ratio), or to both + * @param options The size and how to resize, see {@link ResizeToOptions} */ - protected override __room__(): { left: number, top: number } { - return { left: this.xOffset, top: this.yOffset }; + resize(options: ResizeToOptions): this; + resize(widthOrOptions: number | ResizeToOptions, heightArgument?: number, optionsArgument?: ResizeOptions): this { + return this.__tracked__(image => typeof widthOrOptions === 'number' + ? image.resize(widthOrOptions, heightArgument as number, optionsArgument) + : image.resize(widthOrOptions)); } /** - * @internal - * @ignore + * Scales the frame by a factor, and its offsets along with it + * @param factor The factor + * @param options See {@link ResizeOptions} */ - protected override __grown__(left: number, top: number): void { - this.xOffset -= left; - this.yOffset -= top; + scale(factor: number, options?: ResizeOptions): this { + return this.__tracked__(image => image.scale(factor, options)); } /** - * Removes borders of one color, moving the frame's offsets so the remaining pixels stay in place - * @param options See {@link TrimOptions} + * Crops the frame to a region of it, moving the offsets so the remaining pixels stay where they are in the + * animation. The region is clipped to the frame + * @param x The x offset in the frame (0-based) + * @param y The y offset in the frame (0-based) + * @param width The new width + * @param height The new height */ - override trim(options?: TrimOptions): this; + crop(x: number, y: number, width: number, height: number): this { + return this.__tracked__(image => image.crop(x, y, width, height)); + } + /** - * Removes borders of one color, moving the frame's offsets so the remaining pixels stay in place - * @param color The border color, by default the color of the top left pixel + * Removes borders of one color, moving the offsets so the remaining pixels stay where they are in the animation * @param options See {@link TrimOptions} - * @deprecated Pass {@link TrimOptions} instead, the positional arguments will be removed in 4.0 */ - override trim(color?: Color, options?: TrimOptions): this; - override trim(colorOrOptions?: Color | TrimOptions, optionsArgument: TrimOptions = {}): this { - const { color, ...options } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color }; - const bounds = this.__trim_bounds__(color, options); - if (!bounds) return this; - this.xOffset += bounds[0]; - this.yOffset += bounds[1]; - return this.__apply__(this.__crop__(...bounds)); + trim(options?: TrimOptions): this { + return this.__tracked__(image => image.trim(options)); } /** - * Resizes the frame, scaling its offsets along with it. - * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio. - * @param width The new width - * @param height The new height - * @param options See {@link ResizeOptions} + * Rotates the frame clockwise around its middle, like {@link Image.rotate}: when it grows (or shrinks), the + * offsets move so its middle stays where it is in the animation + * @param angle The angle in degrees, clockwise + * @param options See {@link RotateOptions} */ - override resize(width: number, height: number, options?: ResizeOptions): this; + rotate(angle: number, options?: RotateOptions): this { + return this.__tracked__(image => image.rotate(angle, options)); + } + /** - * Resizes the frame, scaling its offsets along with it. - * @param width The new width - * @param height The new height - * @param mode The resizing mode (default: {@link ResizeModes.BILINEAR}) - * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0 + * Transforms the frame with an affine transform, like {@link Image.transform}: when it grows, the offsets move + * so the transform's origin stays where it is in the animation + * @param matrix The six values [a, b, c, d, e, f] + * @param options See {@link TransformOptions} */ - override resize(width: number, height: number, mode?: ResizeMode): this; + transform(matrix: AffineTransform, options?: TransformOptions): this { + return this.__tracked__(image => image.transform(matrix, options)); + } + /** - * Resizes the frame, scaling its offsets along with it: to the given width or height (the other side keeps the - * aspect ratio), or to both - * @param options The size and how to resize, see {@link ResizeToOptions} + * Adds a shadow behind the frame's image, like {@link Image.dropShadow}: when it grows up or left, the offsets + * move so the image stays where it is in the animation + * @param options See {@link ShadowOptions} */ - override resize(options: ResizeToOptions): this; - override resize(widthOrOptions: number | ResizeToOptions, heightArgument?: number, modeArgument?: ResizeMode | ResizeOptions): this { - const [width, height, modeOrOptions] = resizeArguments(widthOrOptions, heightArgument, modeArgument); - const originalWidth = this.width; - const originalHeight = this.height; - - super.resize(width, height, modeOrOptions as ResizeMode); - - this.xOffset = Math.round(this.xOffset * this.width / originalWidth); - this.yOffset = Math.round(this.yOffset * this.height / originalHeight); - - return this; + dropShadow(options?: ShadowOptions): this { + return this.__tracked__(image => image.dropShadow(options)); } /** - * Scales the offsets like {@link Frame.resize} for a resize to the given size (that only produces a part of it) - * @internal - * @ignore + * Draws an outline around the frame's shape, like {@link Image.outline}: when it grows up or left, the offsets + * move so the image stays where it is in the animation + * @param options See {@link OutlineOptions} */ - protected override __rescaled__(width: number, height: number): void { - this.xOffset = Math.round(this.xOffset * width / this.width); - this.yOffset = Math.round(this.yOffset * height / this.height); + outline(options?: OutlineOptions): this { + return this.__tracked__(image => image.outline(options)); } } + +describe(Frame, frame => ({ width: frame.width, height: frame.height, duration: frame.duration })); diff --git a/src/gainmap.ts b/src/gainmap.ts index fc2b282f..4e134587 100644 --- a/src/gainmap.ts +++ b/src/gainmap.ts @@ -1,129 +1,218 @@ -import { Image } from './image.ts'; +import { Image, alignedPixels } from './image.ts'; +import type { DecodeOptions } from './image.ts'; +import { MAX_PIXELS, decoding } from './util/limits.ts'; import * as jpeg from './codecs/jpeg.ts'; import * as codec from './codecs/gainmap.ts'; import { BinaryData, view } from './util/mem.ts'; -import { finite, isOptions, quality as checkQuality } from './util/options.ts'; +import { shown, instance, nonNegative, finite, checkOptions, pixelLimit, boolean, quality as checkQuality } from './util/options.ts'; -/** Options of {@link GainMap.encode} */ +/** Options of {@link GainMap.encodeJPEG} */ export interface GainMapEncodeOptions { - /** The JPEG quality (1-100). Default: `90` */ + /** + * The JPEG quality (0-100, like {@link Image.encodeJPEG}'s: 0 is 1) + * @defaultValue `90` + */ quality?: number; } -/** Options of the {@link GainMap} constructor: per channel values can be one number for all three or [r, g, b] */ +/** A gain-map parameter shared across channels or specified as `[red, green, blue]` */ +export type GainMapChannelValues = number | readonly [red: number, green: number, blue: number]; + +/** Options of the {@link GainMap} constructor */ export interface GainMapOptions { - /** log2 of the boost of the map's value 0 (`-1`: half as bright). Default: `0` */ - min?: number | number[]; - /** log2 of the boost of the map's value 255 (`2`: 4 times as bright). Default: `2` */ - max?: number | number[]; /** - * Like {@link GainMapOptions.min} - * @deprecated Use `min`, its name in 4.0, which ignores `gainMapMin` + * Extra brightness at the map's darkest value (0); `-1` means half as bright + * @defaultValue `0` (no change) + */ + min?: GainMapChannelValues; + /** + * Extra brightness at the map's brightest value (255); `2` means four times as bright + * @defaultValue `2` + */ + max?: GainMapChannelValues; + /** + * How quickly the brightness changes between `min` and `max`; `1` changes it evenly + * @defaultValue `1` */ - gainMapMin?: number | number[]; + gamma?: GainMapChannelValues; /** - * Like {@link GainMapOptions.max} - * @deprecated Use `max`, its name in 4.0, which ignores `gainMapMax` + * Small brightness offset added before applying the boost, to keep black from being boosted indefinitely. + * @defaultValue `1/64` + */ + offsetSDR?: GainMapChannelValues; + /** + * Small brightness offset subtracted from the result + * @defaultValue `1/64` + */ + offsetHDR?: GainMapChannelValues; + /** + * How bright a display must be before the map starts to apply; `0` is standard-screen brightness + * @defaultValue `0` */ - gainMapMax?: number | number[]; - /** the gamma the map's values are stored with. Default: `1` */ - gamma?: number | number[]; - /** added to the SDR image's linear values before the boost (keeps black from being boosted forever). Default: `1/64` */ - offsetSDR?: number | number[]; - /** subtracted from the HDR result. Default: `1/64` */ - offsetHDR?: number | number[]; - /** log2 of the display headroom from which on the map starts to apply. Default: `0` */ hdrCapacityMin?: number; - /** log2 of the display headroom at which it applies fully. Default: `gainMapMax`'s largest value */ + /** + * How bright a display must be for the map to apply fully + * @defaultValue The largest value in `max` + */ hdrCapacityMax?: number; - /** whether the boost applies in the SDR image's color space (`false`: in the HDR image's). Default: `true` */ + /** + * Whether the boost uses the original image's colors (`false`: the brighter HDR colors) + * @defaultValue `true` + */ useBaseColorSpace?: boolean; } -const perChannel = (value: number | number[], name: string): number[] => { - const values = typeof value === 'number' ? [value, value, value] : Array.from(value); - if (values.length === 1) values.push(values[0], values[0]); - if (values.length !== 3) throw new RangeError(`${name} must be a number or an array of 3 numbers`); - return values.map(v => finite(v, name)); +// the largest magnitude of a parameter: what the ISO 21496-1 fractions of JPEG, AVIF and JPEG XL hold (an int32 +// numerator over 1); gamma and the capacities could go to 2^32 - 1 there, but one range is simpler +const LIMIT = 2 ** 31 - 1; +// the smallest gamma: 1 / 2^31, the smallest fraction above 0 there +const MIN_GAMMA = 2 ** -31; + +const bounded = (value: number, name: string): number => { + finite(value, name); + if (Math.abs(value) > LIMIT) throw new RangeError(`${name} must be from -${LIMIT} to ${LIMIT}, not ${value}`); + return value; +}; + +const perChannel = (value: GainMapChannelValues, name: string): number[] => { + const given: unknown = value; + if (typeof given !== 'number' && !Array.isArray(given)) throw new TypeError(`${name} must be a number or an array of 3 numbers, not ${shown(given)}`); + const values: number[] = typeof value === 'number' ? [value, value, value] : Array.from(value); + if (values.length !== 3) throw new RangeError(`${name} must be a number or an array of 3 numbers, not ${values.length}`); + return values.map(v => bounded(v, name)); }; /** - * A gain map: a small image saying how much brighter each part of an image gets on an HDR display, as Ultra HDR - * (JPEG-R) photos from phones carry it. HDR displays show the image boosted by it, the others the image as it is. + * A gain map is a small companion image that tells a high-dynamic-range (HDR) display how much brighter to show each + * part of a photo. Standard displays ignore it and show the regular-brightness image + * @remarks + * {@link Image.decode} reads gain maps from supported JPEG, AVIF and JPEG XL images into {@link Image.gainMap}; + * {@link Image.encodeJPEG}, {@link Image.encodeAVIF} and {@link Image.encodeJXL} can write them. The map covers the + * whole image, at any resolution. Each pixel's value (0-255) controls how much extra brightness to add at that + * location. For developers who need the exact calculation, the boost is + * `2^(min + (max - min) * (v / 255)^(1 / gamma))`, per color channel. * - * {@link Image.decode} reads the gain maps of JPEGs, AVIFs and JPEG XLs into {@link Image.gainMap}, - * {@link Image.encodeJPEG}, {@link Image.encodeAVIF} and {@link Image.encodeJXL} write them. The map covers the whole image, at any resolution (phones - * write a quarter of the width and height). Its value `v` (0-255, per channel or one for all) boosts the linear - * light of the image by `2^(gainMapMin + (gainMapMax - gainMapMin) * (v / 255)^(1 / gamma))` + * The parameters are checked when they are set: a value that isn't finite or lies beyond ±(2^31 - 1) (what the + * formats store), a gamma below 2^-31, or an array of other than 1 or 3 of them throws, and the map keeps its value */ export class GainMap { + /** @internal @ignore the parameters (the accessors check and copy them) */ + __min__!: number[]; + /** @internal @ignore */ + __max__!: number[]; + /** @internal @ignore */ + __gamma__!: number[]; + /** @internal @ignore */ + __offsetSDR__!: number[]; + /** @internal @ignore */ + __offsetHDR__!: number[]; + /** @internal @ignore */ + __capacityMin__!: number; + /** @internal @ignore */ + __capacityMax__!: number; + /** @internal @ignore */ + __useBaseColorSpace__!: boolean; + /** @internal @ignore the HDR rendition's colors of a decoded AVIF (written again by encodeAVIF) */ + __alternate__?: [number, number, number]; + + /** log2 of the boost of the map's value 0, per channel (red, green, blue; a copy: assign to change it) */ + get min(): readonly [red: number, green: number, blue: number] { return [this.__min__[0], this.__min__[1], this.__min__[2]]; } + /** + * Replaces the value (checked: an invalid one throws and the old one stays) + * @param value One number for all channels or [r, g, b] + */ + set min(value: GainMapChannelValues) { this.__min__ = perChannel(value, 'min'); } + /** log2 of the boost of the map's value 255, per channel (a copy: assign to change it) */ + get max(): readonly [red: number, green: number, blue: number] { return [this.__max__[0], this.__max__[1], this.__max__[2]]; } + /** + * Replaces the value (checked: an invalid one throws and the old one stays) + * @param value One number for all channels or [r, g, b] + */ + set max(value: GainMapChannelValues) { this.__max__ = perChannel(value, 'max'); } + /** The gamma the map's values are stored with, per channel (a copy: assign to change it) */ + get gamma(): readonly [red: number, green: number, blue: number] { return [this.__gamma__[0], this.__gamma__[1], this.__gamma__[2]]; } + /** + * Replaces the value (checked: an invalid one throws and the old one stays) + * @param value One number from 2^-31 for all channels or [r, g, b] + */ + set gamma(value: GainMapChannelValues) { + const gamma = perChannel(value, 'gamma'); + // eslint-disable-next-line no-restricted-syntax -- a rule of the gain map's values, not a shared option + if (gamma.some(g => g < MIN_GAMMA)) throw new RangeError(`The gain map's gamma must be 2^-31 or more, not ${gamma.find(g => g < MIN_GAMMA)}`); + this.__gamma__ = gamma; + } + /** Added to the SDR image's linear values before the boost, per channel (a copy: assign to change it) */ + get offsetSDR(): readonly [red: number, green: number, blue: number] { return [this.__offsetSDR__[0], this.__offsetSDR__[1], this.__offsetSDR__[2]]; } + /** + * Replaces the value (checked: an invalid one throws and the old one stays) + * @param value One number for all channels or [r, g, b] + */ + set offsetSDR(value: GainMapChannelValues) { this.__offsetSDR__ = perChannel(value, 'offsetSDR'); } + /** Subtracted from the HDR result, per channel (a copy: assign to change it) */ + get offsetHDR(): readonly [red: number, green: number, blue: number] { return [this.__offsetHDR__[0], this.__offsetHDR__[1], this.__offsetHDR__[2]]; } /** - * log2 of the boost of the map's value 0, per channel (red, green, blue) - * @deprecated Use {@link GainMap.min}, its name in 4.0 + * Replaces the value (checked: an invalid one throws and the old one stays) + * @param value One number for all channels or [r, g, b] */ - gainMapMin: number[]; + set offsetHDR(value: GainMapChannelValues) { this.__offsetHDR__ = perChannel(value, 'offsetHDR'); } + /** log2 of the display headroom from which on the map starts to apply (from 0) */ + get hdrCapacityMin(): number { return this.__capacityMin__; } /** - * log2 of the boost of the map's value 255, per channel - * @deprecated Use {@link GainMap.max}, its name in 4.0 + * Replaces the value (checked: an invalid one throws and the old one stays) + * @param value A finite number from 0, below `hdrCapacityMax` */ - gainMapMax: number[]; - /** the gamma the map's values are stored with, per channel */ - gamma: number[]; - /** added to the SDR image's linear values before the boost, per channel */ - offsetSDR: number[]; - /** subtracted from the HDR result, per channel */ - offsetHDR: number[]; - /** log2 of the display headroom from which on the map starts to apply */ - hdrCapacityMin: number; - /** log2 of the display headroom at which it applies fully */ - hdrCapacityMax: number; - /** whether the boost applies in the SDR image's color space (else in the HDR image's) */ - useBaseColorSpace: boolean; + set hdrCapacityMin(value: number) { + const capacity = bounded(nonNegative(value, 'hdrCapacityMin'), 'hdrCapacityMin'); + // (checked against the other one when both are set: the constructor sets min first) + if ((this.__capacityMax__ as number | undefined) !== undefined && !(capacity < this.__capacityMax__)) + // eslint-disable-next-line no-restricted-syntax -- a relation between two values of the gain map + throw new RangeError(`The gain map's hdrCapacityMin must be below its hdrCapacityMax (${capacity} >= ${this.__capacityMax__})`); + this.__capacityMin__ = capacity; + } + /** log2 of the display headroom at which it applies fully (above `hdrCapacityMin`) */ + get hdrCapacityMax(): number { return this.__capacityMax__; } + /** + * Replaces the value (checked: an invalid one throws and the old one stays) + * @param value A finite number above `hdrCapacityMin` + */ + set hdrCapacityMax(value: number) { + const capacity = bounded(value, 'hdrCapacityMax'); + if ((this.__capacityMin__ as number | undefined) !== undefined && !(capacity > this.__capacityMin__)) + // eslint-disable-next-line no-restricted-syntax -- a relation between two values of the gain map + throw new RangeError(`The gain map's hdrCapacityMax (by default the largest max) must be above its hdrCapacityMin (${capacity} <= ${this.__capacityMin__})`); + this.__capacityMax__ = capacity; + } + /** Whether the boost applies in the SDR image's color space (else in the HDR image's) */ + get useBaseColorSpace(): boolean { return this.__useBaseColorSpace__; } + /** + * Replaces the value (checked: an invalid one throws and the old one stays) + * @param value Whether the boost applies in the SDR image's color space + */ + set useBaseColorSpace(value: boolean) { + this.__useBaseColorSpace__ = boolean(value, 'useBaseColorSpace'); + } /** its pixels */ private __pixels__: Image | null = null; /** * Creates a gain map - * @param image The map's pixels: grey (red, green and blue the same) for one map for all channels. Its alpha is + * @param image The map's pixels: gray (red, green and blue the same) for one map for all channels. Its alpha is * ignored * @param options See {@link GainMapOptions} */ - /** log2 of the boost of the map's value 0, per channel (red, green, blue): {@link GainMap.gainMapMin}, by its name in 4.0 */ - get min(): number[] { - return this.gainMapMin; - } - - /** Sets {@link GainMap.gainMapMin} */ - set min(value: number[]) { - this.gainMapMin = value; - } - - /** log2 of the boost of the map's value 255, per channel: {@link GainMap.gainMapMax}, by its name in 4.0 */ - get max(): number[] { - return this.gainMapMax; - } - - /** Sets {@link GainMap.gainMapMax} */ - set max(value: number[]) { - this.gainMapMax = value; - } - constructor(image: Image, options: GainMapOptions = {}) { - if (!(image instanceof Image)) throw new TypeError('The gain map has to be an Image'); - if (options.min !== undefined && options.gainMapMin !== undefined) throw new TypeError('A gain map takes min, or the deprecated gainMapMin, not both'); - if (options.max !== undefined && options.gainMapMax !== undefined) throw new TypeError('A gain map takes max, or the deprecated gainMapMax, not both'); - const { gamma = 1, offsetSDR = 1 / 64, offsetHDR = 1 / 64, hdrCapacityMin = 0, useBaseColorSpace = true } = options; - // (min and max are the names of 4.0) - const gainMapMin = options.min ?? options.gainMapMin ?? 0, gainMapMax = options.max ?? options.gainMapMax ?? 2; - this.gainMapMin = perChannel(gainMapMin, 'gainMapMin'); - this.gainMapMax = perChannel(gainMapMax, 'gainMapMax'); - this.gamma = perChannel(gamma, 'gamma'); - this.offsetSDR = perChannel(offsetSDR, 'offsetSDR'); - this.offsetHDR = perChannel(offsetHDR, 'offsetHDR'); - this.hdrCapacityMin = finite(hdrCapacityMin, 'hdrCapacityMin'); - this.hdrCapacityMax = finite(options.hdrCapacityMax ?? Math.max(...this.gainMapMax), 'hdrCapacityMax'); - this.useBaseColorSpace = Boolean(useBaseColorSpace); + checkOptions(options, 'new GainMap(image, { max: 2 })'); + instance(image, [Image], 'the gain map image'); + const { min = 0, max = 2, gamma = 1, offsetSDR = 1 / 64, offsetHDR = 1 / 64, hdrCapacityMin = 0, useBaseColorSpace = true } = options; + this.min = min; + this.max = max; + this.gamma = gamma; + this.offsetSDR = offsetSDR; + this.offsetHDR = offsetHDR; + this.hdrCapacityMin = hdrCapacityMin; + this.hdrCapacityMax = options.hdrCapacityMax === undefined ? Math.max(...this.__max__) : options.hdrCapacityMax; + this.useBaseColorSpace = useBaseColorSpace; this.__pixels__ = image; this.__check__(); } @@ -132,10 +221,10 @@ export class GainMap { * @internal from a decoded file: the map's JPEG, decoded now (a damaged one throws here, not in a later * operation); `apple`: an Apple gain map's headroom, its values converted to the parameters' scale */ - static __from_jpeg__(map: Uint8Array, params: codec.Params, apple = 0): GainMap { - const { width, height, pixels } = jpeg.decode(map); + static __from_jpeg__(map: Uint8Array, params: codec.Params, apple = 0, maxPixels = MAX_PIXELS): GainMap { + const { width, height, pixels } = jpeg.decode(map, { maxPixels }); const image = new Image(width, height); - image.bitmap = pixels; + image.bitmap = alignedPixels(pixels); if (apple) { const table = new Uint8Array(256); for (let v = 0; v < 256; v++) table[v] = Math.round(255 * codec.appleValue(v / 255, apple)); @@ -149,12 +238,12 @@ export class GainMap { } /** - * @internal from decoded pixels (an AVIF's or JPEG XL's map); `grey`: a map whose channels differ by at most 2 - * levels anywhere is made grey (a grey map stored in color, like libjxl writes them: one channel when written) + * @internal from decoded pixels (an AVIF's or JPEG XL's map); `gray`: a map whose channels differ by at most 2 + * levels anywhere is made gray (a gray map stored in color, like libjxl writes them: one channel when written) */ - static __from_pixels__(image: Image, params: codec.Params, grey = true): GainMap { + static __from_pixels__(image: Image, params: codec.Params, gray = true): GainMap { const px = image.bitmap; - if (grey) { + if (gray) { let spread = 0; for (let i = 0; i < px.length && spread <= 2; i += 4) spread = Math.max(spread, Math.abs(px[i] - px[i + 1]), Math.abs(px[i] - px[i + 2])); if (spread > 0 && spread <= 2) for (let i = 0; i < px.length; i += 4) px[i] = px[i + 1] = px[i + 2] = Math.round((px[i] + px[i + 1] + px[i + 2]) / 3); @@ -166,36 +255,33 @@ export class GainMap { } private __set_params__(p: codec.Params): void { - this.gainMapMin = p.min.slice(); - this.gainMapMax = p.max.slice(); - this.gamma = p.gamma.slice(); - this.offsetSDR = p.offsetSDR.slice(); - this.offsetHDR = p.offsetHDR.slice(); - this.hdrCapacityMin = p.capacityMin; - this.hdrCapacityMax = p.capacityMax; - this.useBaseColorSpace = p.useBaseColorSpace; + this.__min__ = p.min.slice(); + this.__max__ = p.max.slice(); + this.__gamma__ = p.gamma.slice(); + this.__offsetSDR__ = p.offsetSDR.slice(); + this.__offsetHDR__ = p.offsetHDR.slice(); + this.__capacityMin__ = p.capacityMin; + this.__capacityMax__ = p.capacityMax; + this.__useBaseColorSpace__ = p.useBaseColorSpace; + this.__alternate__ = p.alternate?.slice() as [number, number, number] | undefined; } /** @internal the parameters, checked */ __params__(): codec.Params { this.__check__(); return { - min: this.gainMapMin.slice(), max: this.gainMapMax.slice(), gamma: this.gamma.slice(), offsetSDR: this.offsetSDR.slice(), - offsetHDR: this.offsetHDR.slice(), capacityMin: this.hdrCapacityMin, capacityMax: this.hdrCapacityMax, useBaseColorSpace: this.useBaseColorSpace + min: this.__min__.slice(), max: this.__max__.slice(), gamma: this.__gamma__.slice(), offsetSDR: this.__offsetSDR__.slice(), + offsetHDR: this.__offsetHDR__.slice(), capacityMin: this.__capacityMin__, capacityMax: this.__capacityMax__, useBaseColorSpace: this.__useBaseColorSpace__, + ...this.__alternate__ ? { alternate: this.__alternate__.slice() as [number, number, number] } : {} }; } private __check__(): void { - const p: codec.Params = { - min: perChannel(this.gainMapMin, 'gainMapMin'), max: perChannel(this.gainMapMax, 'gainMapMax'), gamma: perChannel(this.gamma, 'gamma'), - offsetSDR: perChannel(this.offsetSDR, 'offsetSDR'), offsetHDR: perChannel(this.offsetHDR, 'offsetHDR'), - capacityMin: finite(this.hdrCapacityMin, 'hdrCapacityMin'), capacityMax: finite(this.hdrCapacityMax, 'hdrCapacityMax'), useBaseColorSpace: this.useBaseColorSpace - }; - for (let c = 0; c < 3; c++) { - if (p.gamma[c] <= 0) throw new RangeError('The gain map\'s gamma must be above 0'); - if (p.max[c] < p.min[c]) throw new RangeError('The gain map\'s gainMapMax must be at least its gainMapMin'); - } - if (p.capacityMin < 0 || p.capacityMax <= p.capacityMin) throw new RangeError('The gain map\'s hdrCapacityMax must be above its hdrCapacityMin, which can\'t be negative'); + // (each value is checked when it is set; these are the checks between them) + for (let c = 0; c < 3; c++) + // eslint-disable-next-line no-restricted-syntax -- a relation between two values of the gain map + if (this.__max__[c] < this.__min__[c]) throw new RangeError(`The gain map's max must be at least its min (${this.__max__[c]} < ${this.__min__[c]}; the values are checked together when the map is cloned or encoded)`); + // (the capacities are checked against each other by their setters) } /** The map's pixels. Changes to them are written when the image is encoded */ @@ -208,7 +294,7 @@ export class GainMap { * @param image The new map, at any resolution: it covers the whole image */ set image(image: Image) { - if (!(image instanceof Image)) throw new TypeError('The gain map has to be an Image'); + instance(image, [Image], 'gainMap.image'); this.__pixels__ = image; } @@ -222,7 +308,7 @@ export class GainMap { return (this.__pixels__ as Image).height; } - /** `1` for a grey map (one boost for red, green and blue), `3` for one per channel */ + /** `1` for a gray map (one boost for red, green and blue), `3` for one per channel */ get channels(): 1 | 3 { const bitmap = (this.__pixels__ as Image).bitmap; for (let i = 0; i < bitmap.length; i += 4) if (bitmap[i] !== bitmap[i + 1] || bitmap[i] !== bitmap[i + 2]) return 3; @@ -246,16 +332,16 @@ export class GainMap { const bitmap = image.bitmap; const pixels = new Uint8Array(bitmap.buffer, bitmap.byteOffset, bitmap.byteLength); // (3 channels: their differences are the point, so the chroma keeps its resolution) - const grey = this.channels === 1; - return jpeg.encode(pixels, image.width, image.height, quality ?? 90, { grey, fullChroma: !grey }); + const gray = this.channels === 1; + return jpeg.encode(pixels, image.width, image.height, quality ?? 90, { gray, fullChroma: !gray }); } /** @internal the stored values (0-255, per channel) that boost by nothing (log2 gain 0), clamped to the range */ __neutral__(): number[] { return [0, 1, 2].map(c => { - const min = this.gainMapMin[c], max = this.gainMapMax[c]; + const min = this.__min__[c], max = this.__max__[c]; const t = max > min ? Math.min(1, Math.max(0, -min / (max - min))) : 0; - return Math.round(255 * t ** this.gamma[c]); + return Math.round(255 * t ** this.__gamma__[c]); }); } @@ -308,18 +394,13 @@ export class GainMap { * Encodes the gain map alone: a JPEG with its parameters (hdrgm XMP and ISO 21496-1), like the second image in an * Ultra HDR JPEG * @param options See {@link GainMapEncodeOptions} + * @see {@link Image.encodeJPEG} for the image with its gain map embedded */ - encode(options?: GainMapEncodeOptions): Promise; - /** - * Encodes the gain map alone: a JPEG with its parameters (hdrgm XMP and ISO 21496-1), like the second image in an - * Ultra HDR JPEG - * @param quality The JPEG quality (1-100). Default: `90` - * @deprecated Pass {@link GainMapEncodeOptions} instead, the positional arguments will be removed in 4.0 - */ - encode(quality?: number): Promise; - async encode(qualityOrOptions?: number | GainMapEncodeOptions): Promise { - let quality = isOptions(qualityOrOptions) ? qualityOrOptions.quality : qualityOrOptions; - if (quality !== undefined) quality = Math.max(1, checkQuality(quality)); + encodeJPEG(options?: GainMapEncodeOptions): Promise>; + async encodeJPEG(options?: GainMapEncodeOptions): Promise> { + checkOptions(options, 'gainMap.encodeJPEG({ quality: 80 })'); + const quality = options?.quality; + if (quality !== undefined) checkQuality(quality); return codec.mapWithMetadata(this.__body__(quality), this.__params__()); } @@ -327,13 +408,21 @@ export class GainMap { * Decodes a gain map JPEG with its parameters (hdrgm XMP or ISO 21496-1), like the second image in an Ultra HDR * JPEG, or the gain map of an Ultra HDR JPEG (or an iPhone's JPEG: its values converted to these parameters) * @param data The JPEG + * @param options The `maxPixels` limit, like {@link DecodeOptions.maxPixels} + * @throws {@link LimitError} if the map has more than `options.maxPixels` pixels + * @throws `Error` if the data has no gain map (or no parameters for it), or is damaged */ - static async decode(data: BinaryData): Promise { + static async decode(data: BinaryData, options: Pick = {}): Promise { + checkOptions(options, 'GainMap.decode(data, { maxPixels: 1e8 })'); + const { maxPixels = MAX_PIXELS } = options; + pixelLimit(maxPixels); const bytes = view(data); - const found = codec.find(bytes); - if (found) return GainMap.__from_jpeg__(found.map, found.params, found.apple); - const params = codec.readParams(bytes); - if (!params) throw new Error('No gain map (or no gain map parameters) found'); - return GainMap.__from_jpeg__(bytes, params); + return decoding(() => { + const found = codec.find(bytes); + if (found) return GainMap.__from_jpeg__(found.map, found.params, found.apple, maxPixels); + const params = codec.readParams(bytes); + if (!params) throw new Error('No gain map (or no gain map parameters) found'); + return GainMap.__from_jpeg__(bytes, params, 0, maxPixels); + }); } } diff --git a/src/gif.ts b/src/gif.ts deleted file mode 100644 index 5eaeaab7..00000000 --- a/src/gif.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { BinaryData, view } from './util/mem.ts'; -import { Frame } from './frame.ts'; -import { ImageType } from './image-type.ts'; -import { Animation, AnimationDecodeOptions, AnimationOptions, GIFEncodeOptions } from './animation.ts'; -import { isOptions } from './util/options.ts'; - -/** - * Represents a GIF image as an array of frames, an {@link Animation} whose `encode()` and `decode()` work with GIFs. - * Array methods like map and filter return plain arrays. - * @deprecated Use {@link Animation}, which works the same and also handles APNG: `new Animation(frames, loopCount)`, - * {@link Animation.decode} and {@link Animation.encodeGIF}. `GIF` will be removed in 4.0 - * @group Deprecated - */ -export class GIF extends Animation { - /** - * Creates a new GIF image - * @param frames The frames to create the GIF from - * @param loopCountOrOptions How many times to repeat the GIF (`Infinity` = forever, 0 = play once), or see - * {@link AnimationOptions} - */ - constructor(frames: Frame[], loopCountOrOptions?: number | AnimationOptions) { - super(frames, loopCountOrOptions as number); - } - - /** A short description for debugging, e.g. `GIF<64x64x1000ms>` */ - override toString(): string { - return `GIF<${this.width}x${this.height}x${this.duration}ms>`; - } - - /** - * Encodes the GIF - * @param qualityOrOptions 1-100, scales the palette size from 8 colors (1) to 256 colors (90 and above), or - * see {@link GIFEncodeOptions} - * @deprecated Use {@link Animation.encodeGIF} - */ - async encode(qualityOrOptions?: number | GIFEncodeOptions): Promise { - return this.encodeGIF(qualityOrOptions as number); - } - - /** - * Decodes a GIF into fully composited frames - * @param input The binary data to decode - * @param onlyFirstFrameOrOptions Whether to end GIF decoding after the first frame, or see - * {@link AnimationDecodeOptions} - * @deprecated Use {@link Animation.decode}, which decodes APNGs too - */ - static override async decode(input: BinaryData, onlyFirstFrameOrOptions: boolean | AnimationDecodeOptions = false): Promise { - const { onlyFirstFrame = false, maxPixels } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions }; - const data = view(input); - if (!ImageType.isGIF(new DataView(data.buffer, data.byteOffset, data.byteLength))) throw new Error('Unsupported image type'); - return Animation.__fromGIF__(data, onlyFirstFrame, GIF, maxPixels); - } -} diff --git a/src/image-type.ts b/src/image-type.ts index 7574b7a1..23467945 100644 --- a/src/image-type.ts +++ b/src/image-type.ts @@ -135,11 +135,19 @@ export class ImageType { } /** - * Whether the data is a Windows icon or cursor (ICO or CUR) + * Whether the data is a Windows icon (ICO) * @param data The file's data */ static isICO(data: BinaryData): boolean { - return iconType(u8(dataView(data))) !== null; + return iconType(u8(dataView(data))) === 'ico'; + } + + /** + * Whether the data is a Windows cursor (CUR) + * @param data The file's data + */ + static isCUR(data: BinaryData): boolean { + return iconType(u8(dataView(data))) === 'cur'; } /** diff --git a/src/image.ts b/src/image.ts index 413260e7..ff6ecc5e 100644 --- a/src/image.ts +++ b/src/image.ts @@ -15,31 +15,29 @@ import { availableThreads } from './util/threads.ts'; // (worker threads: the processors available, at most 8) const defaultThreads = (): number => Math.max(1, Math.min(availableThreads(), 8)); -const checkThreads = (threads: number): void => { - if (!Number.isInteger(threads) || threads < 1) throw new RangeError(`threads must be a positive integer, not ${threads}`); -}; import * as jxl from './codecs/jxl.ts'; import type { ToneMapping } from './codecs/hdr.ts'; import * as quantize from './codecs/quantize.ts'; import * as textRenderer from './render/text.ts'; import * as svgRenderer from './render/svg.ts'; -import { BinaryData, view } from './util/mem.ts'; +import { BinaryData, view, isBinaryData } from './util/mem.ts'; import { cicpTransform, colorSpaceTransform, profileTransform } from './util/icc.ts'; import { ImageType } from './image-type.ts'; -import { TextLayout, TextLayoutOptions } from './text-layout.ts'; -import { Metadata, resolveMetadata, pngText, exifData } from './metadata.ts'; +import { textLayout, TextLayoutOptions } from './text-layout.ts'; +import { Metadata, resolveMetadata, pngText, exifData, gifComments } from './metadata.ts'; import { encode as utf8 } from './util/utf8.ts'; import { resample, BOX, TRIANGLE, CUBIC, type Region } from './util/resample.ts'; -import { rotateBilinear } from './util/rotate.ts'; import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from './util/blur.ts'; -import { Colors, wrapHue, hue2rgb, rgbaToHSLA } from './colors.ts'; -import { isOptions, finite, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from './util/options.ts'; -import { MAX_PIXELS, decoding } from './util/limits.ts'; +import { Colors, wrapHue, hue2rgb } from './colors.ts'; +import { allocate, scaleFactor, instance, shown, isOptions, checkOptions, finite, nonNegative, atLeast, positive, pixels, coordinate, cropBounds, unitInterval, oneOf, pixelLimit, checkThreads, gainMapEmbed, boolean, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from './util/options.ts'; +import { MAX_PIXELS, LimitError, decoding, checkGrowth, checkFormatSize } from './util/limits.ts'; import { GainMap } from './gainmap.ts'; import * as gain from './util/gain.ts'; import { multiply, invert } from './util/matrix.ts'; import { sampleAffine } from './util/affine.ts'; +import { rotateBilinear } from './util/rotate.ts'; import * as gainMapCodec from './codecs/gainmap.ts'; +import { describe } from './util/inspect.ts'; /** A color as a 32-bit RGBA integer (`0xRRGGBBAA`) */ export type Color = number; @@ -48,74 +46,16 @@ export type Color = number; export type ColorFunction = (x: number, y: number) => Color; /** - * Resampling filters for {@link Image.resize} and the other scaling functions, see {@link ResizeModes}. - * The upper case names (`'RESIZE_BILINEAR'`, the values of the deprecated `Image.RESIZE_*`) still work, they are - * removed in 4.0 - */ -export type ResizeMode = 'nearest-neighbor' | 'bilinear' | 'bicubic' | 'area' - | 'RESIZE_NEAREST_NEIGHBOR' | 'RESIZE_BILINEAR' | 'RESIZE_BICUBIC' | 'RESIZE_AREA'; - -/** - * How {@link Image.renderSVG} scales, see {@link SVGScaleModes}. The numbers 1-3 (the values of the deprecated - * `Image.SVG_MODE_*`) still work, they are removed in 4.0 - * @deprecated Use `renderSVG(svg, { width })`, `{ height }` or `{ scale }`: the `mode` option is removed in 4.0 - */ -export type SVGScaleMode = 'scale' | 'width' | 'height' | 1 | 2 | 3; - -/** - * The resampling filters of {@link Image.resize} and the other scaling functions: - * `image.resize({ width: 256, mode: ResizeModes.BICUBIC })` - * @deprecated Use the names, `image.resize({ width: 256, mode: 'bicubic' })`: `ResizeModes` is removed in 4.0 - */ -export class ResizeModes { - /** - * Use {@link https://en.wikipedia.org/wiki/Image_scaling#Nearest-neighbor_interpolation Nearest-neighbor} resizing - */ - static readonly NEAREST_NEIGHBOR = 'nearest-neighbor'; - - /** - * Bilinear resizing (the default). When shrinking, the filter widens with the scale factor, so every source pixel - * contributes - */ - static readonly BILINEAR = 'bilinear'; - - /** Bicubic (Catmull-Rom) resizing, sharper than bilinear, especially when enlarging */ - static readonly BICUBIC = 'bicubic'; - - /** - * Area averaging (box filter): every output pixel is the average of the source pixels it covers. Meant for - * shrinking - */ - static readonly AREA = 'area'; - - /** - * Not a filter: passed as the width or the height, that side follows from the other one, keeping the image's - * aspect ratio - * @deprecated Pass only the width or the height instead, `image.resize({ width: 256 })`. `AUTO` is removed in 4.0 - * @group Deprecated - */ - static readonly AUTO = -1; - - private constructor() {} -} - -/** - * How {@link Image.renderSVG} scales the SVG to the given size - * @deprecated Use `renderSVG(svg, { width })`, `{ height }` or `{ scale }`: `SVGScaleModes` and the `mode` option are - * removed in 4.0 + * The resampling filters of {@link Image.resize} and the other scaling functions (`image.resize({ width: 256, mode: + * 'bicubic' })`): + * - `'nearest-neighbor'`: each output pixel takes the nearest source pixel (hard pixels, for pixel art) + * - `'bilinear'` (the default): when shrinking, the filter widens with the scale factor, so every source pixel + * contributes + * - `'bicubic'`: Catmull-Rom, sharper than bilinear, especially when enlarging + * - `'area'`: area averaging (box filter), every output pixel is the average of the source pixels it covers. Meant for + * shrinking */ -export class SVGScaleModes { - /** The size is a factor of the SVG's own size */ - static readonly SCALE = 'scale'; - - /** The size is the width in pixels, the height follows the SVG's aspect ratio */ - static readonly WIDTH = 'width'; - - /** The size is the height in pixels, the width follows the SVG's aspect ratio */ - static readonly HEIGHT = 'height'; - - private constructor() {} -} +export type ResizeMode = 'nearest-neighbor' | 'bilinear' | 'bicubic' | 'area'; /** Blend modes of {@link Image.composite}, named like CSS' mix-blend-mode values */ export type BlendMode = 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' @@ -123,154 +63,248 @@ export type BlendMode = 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' /** Options of {@link Image.composite} */ export interface CompositeOptions { - /** The x position to place the source at, if the options are the second argument. Default: `0` */ + /** + * The x position to place the source at + * @defaultValue `0` + */ x?: number; - /** The y position to place the source at, if the options are the second argument. Default: `0` */ + /** + * The y position to place the source at + * @defaultValue `0` + */ y?: number; - /** Opacity of the source (0..1). Default: `1` */ + /** + * Opacity of the source (0..1) + * @defaultValue `1` + */ opacity?: number; - /** How the colors are mixed. Default: `'normal'` */ + /** + * How the colors are mixed + * @defaultValue `'normal'` + */ mode?: BlendMode; } +/** How {@link Image.resize}, {@link Frame.resize} and {@link Animation.resize} fit an image into a box */ +export type ResizeFit = 'fill' | 'inside' | 'contain' | 'cover'; + /** * The size for {@link Image.resize}, {@link Frame.resize} and {@link Animation.resize}, and how to resize: a side * that is missing follows from the other one, keeping the aspect ratio */ -export interface ResizeToOptions extends ResizeOptions { - /** The new width. Without it, it follows from the height */ - width?: number; - /** The new height. Without it, it follows from the width */ - height?: number; -} - -/** Options of {@link Image.scale}, {@link Image.resize}, {@link Image.contain}, {@link Image.fit} and {@link Image.cover} */ +export type ResizeToOptions = ResizeOptions & ( + | { + /** The new width. Without it, it follows from the height */ + width?: number; + /** The new height. Without it, it follows from the width */ + height?: number; + /** + * `'fill'` stretches to the exact size; `'inside'` keeps the aspect ratio and makes the image as large as fits + * inside it, so one side can be smaller + * @defaultValue `'fill'` + */ + fit?: 'fill' | 'inside'; + /** Only with `fit: 'contain'` */ + background?: never; + } + | { + /** The exact width of the box */ + width: number; + /** The exact height of the box */ + height: number; + /** Keeps the aspect ratio and pads to the exact box */ + fit: 'contain'; + /** + * For `'contain'`, the color of the bars + * @defaultValue `0x00000000` (transparent) + */ + background?: Color; + } + | { + /** The exact width of the box */ + width: number; + /** The exact height of the box */ + height: number; + /** Keeps the aspect ratio and crops to the exact box */ + fit: 'cover'; + /** Only with `fit: 'contain'` */ + background?: never; + } +); + +type ResizeRuntimeOptions = ResizeOptions & { background?: Color }; + +/** Options of {@link Image.scale} and {@link Image.resize} */ export interface ResizeOptions { - /** The resizing mode. Default: {@link ResizeModes.BILINEAR} */ - mode?: ResizeMode; - /** - * Whether to round to 8 bits between the two passes, so two channels share the multiplications of both: about - * 15-25% faster for opaque images, with 10-25% of the channel values a step off the precise result (instead of - * about 1%, never more than 1). Transparent images are premultiplied to 8 bits like browsers do, which makes them - * about twice as fast: what shows once they're composited differs by up to about 2 steps, pixels that are almost - * transparent keep less of their color. Only affects {@link ResizeModes.BILINEAR} and {@link ResizeModes.AREA}, - * down to about a third of the size. Default: `true` - */ - fast?: boolean; -} - -/** - * Options of {@link Image.opacity}, {@link Image.red}, {@link Image.green}, {@link Image.blue}, {@link Image.lightness} - * and {@link Image.saturation} - */ -export interface AdjustOptions { /** - * Whether to set the value (true) or scale the current one (false). Default: `false` - * @deprecated Removed in 4.0: scale with a factor, or use {@link Image.recolor} for a fixed color + * The resizing mode + * @defaultValue `'bilinear'` */ - absolute?: boolean; + mode?: ResizeMode; } /** Options of {@link Image.sharpen} */ export interface SharpenOptions { - /** How strongly to sharpen (0 does nothing). Default: `1` */ + /** + * How strongly to sharpen (0 does nothing) + * @defaultValue `1` + */ amount?: number; - /** The radius of the blur the image is compared with (larger values sharpen coarser details). Default: `1` */ + /** + * The radius of the blur the image is compared with (larger values sharpen coarser details) + * @defaultValue `1` + */ radius?: number; } -// the dithering methods of Image.quantize() -const DITHER_METHODS = ['none', 'floyd-steinberg', 'atkinson', 'ordered'] as const; +/** + * How to reduce visible banding when an image is limited to a smaller set of colors ({@link Image.quantize}, + * {@link Image.encodeGIF}): `'none'` uses the nearest color; `'floyd-steinberg'` and `'atkinson'` spread small color + * errors to nearby pixels; `'ordered'` uses a repeating pattern. Atkinson tends to give a higher-contrast result. + */ +export type DitherMethod = 'none' | 'floyd-steinberg' | 'atkinson' | 'ordered'; -/** Options of {@link Image.quantize}: either `colors` or `palette`, and the dithering */ -export interface QuantizeOptions { +/** How colors are dithered when they are reduced to a palette: options of {@link Image.quantize} and the GIF encoders */ +export interface DitherOptions { /** - * The number of colors to reduce the image to, an integer from 2 to 256. The palette is the image's own colors when - * it has no more distinct ones than this, else colors chosen by median cut (the common colors get their own). Those - * are averages of groups of similar colors, so e.g. pure black and white are only in it if the image has them in - * quantity: give `palette` for exact colors. Default: `256`. Give `colors` or `palette`, not both + * How to spread small color changes across nearby pixels to make gradients look smoother with few colors, see + * {@link DitherMethod} + * @defaultValue `'floyd-steinberg'` */ - colors?: number; + dither?: DitherMethod; /** - * A fixed palette (1 to 256 colors, e.g. a Game Boy's four greens) that every pixel is mapped to, the nearest color - * by its RGB. The alpha of the palette's colors is ignored. Give `palette` or `colors`, not both + * How strongly to apply dithering: `0` disables it (like `'none'`); `1` applies it fully + * @defaultValue `0.85` */ - palette?: Color[]; + ditherStrength?: number; +} + +/** + * Options of {@link Image.quantize}: either `colors` or `palette` (TypeScript reports a call with both), and the + * dithering + */ +export type QuantizeOptions = DitherOptions & ({ /** - * How the rounding error of each pixel is handled, which makes gradients look smooth with few colors: - * `'none'` (each pixel takes its nearest color), `'floyd-steinberg'` (the error goes to the next pixels, 7/16, 3/16, - * 5/16 and 1/16), `'atkinson'` (the error goes to six neighbours, 1/8 each: lighter, more contrast), `'ordered'` (a - * regular 4x4 pattern of thresholds, no error spreading). Rows alternate direction for the error diffusions. - * Default: `'none'` + * The maximum number of colors to keep (2-256). Images with fewer distinct colors keep them exactly; otherwise + * ImageScript chooses a smaller set of representative colors. Give `palette` instead to choose exact colors. + * @defaultValue `256` */ - dither?: 'none' | 'floyd-steinberg' | 'atkinson' | 'ordered'; + colors?: number; + /** Not with `colors`: give one of them */ + palette?: never; +} | { /** - * How strongly to dither, from `0` (no spreading or threshold, the same as `'none'`) to `1` (the full error or - * threshold). Default: `1` + * A fixed palette (1-256 colors, e.g. a Game Boy's four greens). Every pixel is changed to the nearest palette + * color by its red, green and blue values; transparency in palette colors is ignored */ - ditherStrength?: number; -} + palette: Color[]; + /** Not with `palette`: give one of them */ + colors?: never; +}); -/** How {@link Image.transform} samples the pixels between the source's */ +/** The directions of {@link Image.flip} and {@link Animation.flip}: `'horizontal'` mirrors left and right, `'vertical'` top and bottom */ +export type FlipDirection = 'horizontal' | 'vertical'; + +/** How {@link Image.transform} and {@link Image.rotate} sample the pixels between the source's */ export type TransformMode = 'nearest-neighbor' | 'bilinear' | 'bicubic'; +/** The six values `[a, b, c, d, e, f]` of an affine transform */ +export type AffineTransform = readonly [a: number, b: number, c: number, d: number, e: number, f: number]; + // the sampling modes of Image.transform() -const TRANSFORM_MODES: readonly string[] = ['nearest-neighbor', 'bilinear', 'bicubic']; +const TRANSFORM_MODES: readonly TransformMode[] = ['nearest-neighbor', 'bilinear', 'bicubic']; +const RESIZE_FITS: readonly ResizeFit[] = ['fill', 'inside', 'contain', 'cover']; +const CIRCLE_FITS: readonly NonNullable[] = ['contain', 'cover']; +const SUBSAMPLINGS: readonly string[] = ['4:4:4', '4:2:0']; +/** @internal */ +export const TONE_MAPPINGS: readonly ToneMapping[] = ['reinhard', 'clamp']; +/** @internal */ +export const FLIP_DIRECTIONS: readonly FlipDirection[] = ['horizontal', 'vertical']; /** Options of {@link Image.transform} */ export interface TransformOptions { /** * The point the transform is applied around, in pixels: a rotation turns around it, a scale grows from it. - * Default: the middle of the image. It only decides where the result lies on a canvas that stays as large as the - * image (`expand: false`) + * It only decides where the result lies on a canvas that stays as large as the image (`expand: false`) + * @defaultValue The middle of the image */ origin?: { - /** The x position of the point in pixels. Default: half the width */ + /** + * The x position of the point in pixels + * @defaultValue Half the width + */ x?: number; - /** The y position of the point in pixels. Default: half the height */ + /** + * The y position of the point in pixels + * @defaultValue Half the height + */ y?: number; }; /** * Whether to make the image as large as the transformed one, which then fills it (a rotated image grows to fit its - * corners, a skewed one gets wider). Without it, the image keeps its size and the parts outside are lost. Frames - * only grow up and left as far as their offset allows. Default: `true` + * corners, a skewed one gets wider). Without it, the image keeps its size and the parts outside are lost. + * @defaultValue `true` */ expand?: boolean; /** * How the pixels between the source's are sampled: `'nearest-neighbor'` (hard pixels, no smoothing, for pixel art), - * `'bilinear'` (smooth), `'bicubic'` (sharper, slower, can overshoot a little at hard edges). Default: `'bilinear'` + * `'bilinear'` (smooth), `'bicubic'` (sharper, slower, can overshoot a little at hard edges) + * @defaultValue `'bilinear'` */ mode?: TransformMode; } /** Options of {@link Image.dropShadow} */ export interface ShadowOptions { - /** How far to move the shadow to the right (negative values: to the left), in pixels. Default: `0` */ + /** + * How far to move the shadow to the right (negative values: to the left), in pixels + * @defaultValue `0` + */ x?: number; - /** How far to move the shadow down (negative values: up), in pixels. Default: `0` */ + /** + * How far to move the shadow down (negative values: up), in pixels + * @defaultValue `0` + */ y?: number; - /** How soft the shadow's edge is: the standard deviation of a gaussian blur in pixels, like {@link Image.blur}. Default: `0` */ + /** + * How soft the shadow's edge is: the standard deviation of a gaussian blur in pixels, like {@link Image.blur} + * @defaultValue `0` + */ blur?: number; - /** How far to grow the shadow's shape before blurring it, in pixels. Default: `0` */ + /** + * How far to grow the shadow's shape before blurring it, in pixels + * @defaultValue `0` + */ spread?: number; - /** The shadow's color, its alpha is the shadow's opacity. Default: `0x00000080` (50% black) */ + /** + * The shadow's color, its alpha is the shadow's opacity + * @defaultValue `0x00000080` (50% black) + */ color?: Color; /** * Whether to make the image larger so the shadow isn't cut off. Without it, the image keeps its size and the part - * of the shadow outside is lost. Default: `true` + * of the shadow outside is lost + * @defaultValue `true` */ expand?: boolean; } /** Options of {@link Image.outline} */ export interface OutlineOptions { - /** The outline's width in pixels. Default: `1` */ + /** + * The outline's width in pixels + * @defaultValue `1` + */ width?: number; - /** The outline's color. Default: `0x000000ff` */ + /** + * The outline's color + * @defaultValue `0x000000ff` + */ color?: Color; /** * Whether to make the image larger so the outline isn't cut off. Without it, the image keeps its size and the - * outline is cut where the image ends. Default: `true` + * outline is cut where the image ends + * @defaultValue `true` */ expand?: boolean; } @@ -278,9 +312,9 @@ export interface OutlineOptions { /** The colors of a gradient, see {@link Image.linearGradient} */ export interface GradientOptions { /** - * The colors along the gradient: their positions (0..1) and colors, like {@link Colors.gradient} takes them - * (`{ 0: 0xff0000ff, 0.5: 0xffff00ff, 1: 0x00ff00ff }`), or just the colors, evenly spaced - * (`[0xff0000ff, 0x00ff00ff]`) + * The colors along the gradient: their positions (0..1) and colors (`{ 0: 0xff0000ff, 0.5: 0xffff00ff, 1: 0x00ff00ff }`), + * or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link Colors.gradient} takes them. A + * position outside 0..1 is allowed, see {@link Colors.gradient} */ stops: Record | Color[]; } @@ -290,302 +324,435 @@ export interface LinearGradientOptions extends GradientOptions { /** * The direction of the gradient in degrees, like CSS' `linear-gradient()`: `0` goes up, `90` to the right, `180` * down, `270` to the left. The first stop is at the start of the line through the center that touches the - * corners. Default: `180` + * corners + * @defaultValue `180` */ angle?: number; } /** Options of {@link Image.radialGradient} */ export interface RadialGradientOptions extends GradientOptions { - /** The x position of the center in pixels. Default: the middle of the image */ + /** + * The x position of the center in pixels + * @defaultValue The middle of the image + */ x?: number; - /** The y position of the center in pixels. Default: the middle of the image */ + /** + * The y position of the center in pixels + * @defaultValue The middle of the image + */ y?: number; - /** The radius of the last stop in pixels. Default: the distance to the farthest corner */ + /** + * The radius of the last stop in pixels + * @defaultValue The distance to the farthest corner + */ radius?: number; } -/** Options of {@link Image.encode} */ -export interface PNGEncodeOptions { - /** The compression level (0-9), higher is smaller but slower. Default: `4` */ - compression?: number; +/** The options every encoder that writes metadata has */ +export interface EncodeOptions { /** Metadata to include, see {@link Metadata} */ metadata?: Metadata; } +/** + * How the encoders that can carry a gain map (JPEG, AVIF, JPEG XL) write {@link Image.gainMap}, see their `gainMap` + * option + */ +export interface GainMapEmbedOptions { + /** + * The map's quality (0-100, like the format's `quality`; for JPEG XL 100 is lossless) + * @defaultValue `90` + */ + quality?: number; + /** + * The map's size as a factor of the image's (0-1) + * @defaultValue The map's own size + */ + scale?: number; +} + +/** Options of {@link Image.encodePNG} */ +export interface PNGEncodeOptions extends EncodeOptions { + /** + * The compression level (0-9), higher is smaller but slower + * @defaultValue `4` + */ + compression?: number; +} + +/** Options of {@link Image.encodeTGA}: the metadata, which TGA keeps in its extension area */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface TGAEncodeOptions extends EncodeOptions {} + +/** Options of {@link Image.encodeGIF}, and of {@link Animation.encodeGIF} with {@link GIFAnimationEncodeOptions} */ +export interface GIFEncodeOptions extends EncodeOptions, DitherOptions { + /** + * The maximum colors in each frame's palette (2-256, including transparency). Frames with fewer colors keep them + * exactly; otherwise ImageScript chooses representative colors + * @defaultValue `256` + */ + colors?: number; +} + /** Options of {@link Image.encodeJPEG} */ -export interface JPEGEncodeOptions { - /** The JPEG quality (1-100), chroma subsampling is disabled above 90. Default: `90` */ +export interface JPEGEncodeOptions extends EncodeOptions { + /** + * The JPEG quality (0-100, 0 is the same as 1) + * @defaultValue `90` + */ quality?: number; - /** Metadata to include, see {@link Metadata} */ - metadata?: Metadata; + /** + * How much color detail to keep: `'4:4:4'` keeps it all; `'4:2:0'` stores less color detail to make a smaller + * file (often hard to notice in photos, but more visible around colored edges) + * @defaultValue `'4:2:0'` up to quality 90, `'4:4:4'` above + */ + subsampling?: '4:4:4' | '4:2:0'; + /** + * The background color to combine with transparent pixels, since JPEG doesn't support transparency. Opaque images + * are encoded as they are + * @defaultValue `0x000000ff` (black) + */ + background?: Color; /** * Whether to write the image's {@link Image.gainMap} (an Ultra HDR JPEG, brighter on HDR displays), or how. - * Default: `true` (written if there is one) + * @defaultValue `true` (written if there is one) */ - gainMap?: boolean | { - /** The map's JPEG quality (1-100). Default: `90` */ - quality?: number, - /** The map's size as a factor of the image's (0-1). Default: the map's own size */ - scale?: number - }; + gainMap?: boolean | GainMapEmbedOptions; } /** Options of {@link Image.encodeWebP} */ -export interface WebPEncodeOptions { +export interface WebPEncodeOptions extends EncodeOptions { /** - * Lossy compression (0-100, like libwebp's quality: 75 is its default): the image is encoded like cwebp encodes it - * (with `-m` set to the effort), much smaller than lossless. Without it the image is encoded losslessly + * Lossy compression (0-100): higher values usually preserve more detail but make larger files. `100`, like no + * quality, encodes losslessly and keeps every pixel exact (`99` is the highest lossy quality) */ quality?: number; /** - * How much effort compression takes (0-6): higher is smaller but slower. Lossy (libwebp's method): 0-2 pick the - * predictions by how close they are, 3 and up also by how many bits they take, 5 and 6 also optimize the - * quantized values; the default `2` takes about a quarter of the time of 4 (cwebp's default) for files about 5% - * larger. Lossless: 0 is a fast mode (photos in about a fifth of the time, graphics in about a third, files about - * 6-8% larger), 1 takes about two thirds of the time for files up to 2% larger, 2 and up compress the most. - * Default: `2` + * Compression effort (0-6): higher values usually take longer but may make smaller files. For lossless images, + * `0` prioritizes speed; `2` and above spend more time reducing file size (lossless images are encoded the same at + * `2` and above) + * @defaultValue `2` */ effort?: number; /** - * For lossy compression: convert to YUV like libwebp's sharp conversion (cwebp's `-sharp_yuv`, the same file), - * which picks the color planes so that colored edges (red text on blue, thin colored lines) stay sharp instead of - * bleeding. It takes about twice the time at the default effort; photos get about as large, images with many - * hard color edges a lot larger (1200x800 red and blue squares: 2.7 times). Default: `false` + * For lossy compression: improve color detail around sharp edges (for example, red text on a blue background). + * This can take longer and make graphics larger + * @defaultValue `false` */ sharpYuv?: boolean; /** - * For lossy compression, the alpha plane's quality (0-100, like cwebp's `-alpha_q`): below 100 its levels are - * reduced (to 2-16 up to 70, 16-256 above), which makes it compress better; the alpha plane is lossless otherwise. - * Default: `100` + * For lossy compression, the transparency (alpha) channel's quality (0-100). Lower values may make the image + * smaller but can make transparency look less smooth + * @defaultValue `100` (full quality) */ alphaQuality?: number; /** - * For lossless compression, at most this many worker threads search the predictors and prefix codes in parallel - * (the same file, faster), `1` for none. Images under about 1.5 megapixels, and runtimes whose workers can't share - * memory (browsers without cross-origin isolation), encode without them. Default: the processors available, at - * most 8 + * For lossless compression, the maximum worker threads to use. Small images or runtimes that cannot share memory + * between workers use one thread + * @remarks + * Where workers can't start, the work runs on the calling thread with the same output. That includes browser pages + * that aren't cross-origin isolated and ones that load the package from another origin (a CDN such as jsDelivr), + * which browsers don't allow to start workers + * @defaultValue The available processors, up to 8 */ threads?: number; - /** Metadata to include, see {@link Metadata} */ - metadata?: Metadata; -} - -/** Options of {@link Image.encodeTGA} */ -export interface EncodeOptions { - /** Metadata to include, see {@link Metadata} */ - metadata?: Metadata; } /** Options of {@link Image.roundCorners} */ export interface RoundCornersOptions { - /** The radius of the corners. Default: a quarter of the smaller side */ + /** + * The radius of the corners, 0 or more; one above half the smaller side is cut to that + * @defaultValue A quarter of the smaller side + */ radius?: number; } /** Options of {@link Image.fisheye} */ export interface FisheyeOptions { - /** The distortion strength (exponent of the radial mapping), higher values bulge the center more. Default: `2` */ + /** + * The distortion strength (exponent of the radial mapping), above 0: higher values bulge the center more. At 1 and + * below, the picture shrinks into the middle of the image, and 0 or less would leave nothing of it (it throws) + * @defaultValue `2` + */ strength?: number; } -/** Options of {@link Image.renderSVG}: {@link SVGOptions}, by its name in 4.0 */ -export type RenderSVGOptions = SVGOptions; - -/** Options of {@link Image.renderSVG} */ -export interface SVGOptions { - /** The width in pixels, the height follows the SVG's aspect ratio. Only one of `width`, `height` and `scale` */ - width?: number; - /** The height in pixels, the width follows the SVG's aspect ratio. Only one of `width`, `height` and `scale` */ - height?: number; - /** A factor of the SVG's own size. Only one of `width`, `height` and `scale`. Default: `1` */ - scale?: number; - /** - * The scale, or the width or height in pixels, see `mode`. Default: `1` - * @deprecated Use `width`, `height` or `scale`, their names in 4.0, which ignores `size` and `mode`: - * `renderSVG(svg, { width: 512 })` - */ - size?: number; - /** - * What `size` is: one of {@link SVGScaleModes.SCALE}, {@link SVGScaleModes.WIDTH}, {@link SVGScaleModes.HEIGHT}. - * Default: {@link SVGScaleModes.SCALE} - * @deprecated Use `width`, `height` or `scale`, their names in 4.0, which ignores `size` and `mode`: - * `renderSVG(svg, { width: 512 })` - */ - mode?: SVGScaleMode; +/** The limits, fonts and images of {@link Image.renderSVG}, part of {@link RenderSVGOptions} */ +export interface SVGResourceOptions { /** - * Fonts for ``, like {@link SVGOptions.fonts}: one font, or several + * Maximum total pixels in the rendered output. Output over the limit throws a {@link LimitError} (a RangeError) before anything is + * rendered. It's also the default of {@link SVGResourceOptions.maxLayerPixels} and + * {@link SVGResourceOptions.maxImagePixels}. The work limits of rendering grow with it: see + * {@link SVGResourceOptions.maxLayerPixels} + * @defaultValue `268402689` (16383²); `Infinity` disables the limit */ - font?: BinaryData | BinaryData[]; + maxPixels?: number; /** - * Fonts for `` (TrueType, OpenType): each text gets the face its `font-family`, `font-weight`, `font-style` + * Maximum pixels of the layers rendering uses at once, the output's included. Groups with opacity, masks, clip + * paths of nested viewports, filters and blend modes are each rendered into a layer of their own (up to the + * output's size, 16 bytes per pixel) while their content is drawn, so deeply nested ones multiply the memory a + * small SVG takes. Exceeding it throws a {@link LimitError} (a RangeError). With the defaults, rendering can take + * about 90 bytes per pixel of `maxPixels` (64 for the layers, up to 20 for the images, 4 for the output): lower + * `maxPixels` to bound it for untrusted SVGs. + * + * Three limits on the work of a render don't depend on these options, and grow with the size of the output (so + * lowering `maxPixels` is what bounds them too). Each throws a {@link LimitError} when exceeded: + * - Painting: shapes and layers may paint 2²⁸ pixels plus 64 per pixel of the output + * - Paths: all paths together may be made of 2²⁵ points plus 4 per pixel of the output (curves flattened, each + * copy drawn through `` counted, a command of a glyph outline 16), one path of 2²¹ (texts excepted) + * - Filters: all the filters' primitives together may work on 2²⁵ pixels plus 16 per pixel of the output (a + * primitive counts its region's pixels once per pass: an `feConvolveMatrix` per 9 taps of its kernel, an + * `feTurbulence` per octave, an `feMerge` per node) + * @defaultValue `4 * maxPixels`; `Infinity` disables the limit + */ + maxLayerPixels?: number; + /** + * Maximum total pixels of the raster images the SVG references (data URIs and {@link SVGResourceOptions.images}), + * decoded together; already-decoded {@link Image} values are used as supplied and don't count. Drawing an image + * beyond the limit throws a {@link LimitError} (a RangeError) + * @defaultValue `maxPixels`; `Infinity` disables the limit + */ + maxImagePixels?: number; + /** + * Fonts for `` (TrueType, OpenType or WOFF; not WOFF2 or some newer OpenType outline formats such as CFF2): + * each text gets the face its `font-family`, `font-weight`, `font-style` * and `font-stretch` match best among them, by the names, weights and styles in the fonts (like browsers match * installed fonts). Generic families (`serif`, `sans-serif`, `monospace`, ...) are the first font that fits them, * other families and text without one get the first font's family; characters a face doesn't have come from the * other fonts (TrueType, OpenType or WOFF). Fonts the SVG embeds with `@font-face` (in data: URIs) are used too, - * before these for their family names. Without any fonts text isn't rendered. Default: `[]` - * @deprecated Use `font`, its name in 4.0, which ignores `fonts` (one font, or several in an array) + * before these for their family names. Without any fonts text isn't rendered (an empty array is the same as no + * option here; {@link Image.renderText} needs a font and throws for it). One font can be given without an + * array. A font here that can't be read throws an Error, like in {@link Image.renderText}; a damaged font that the + * SVG embeds is left out + * @defaultValue `[]` */ - fonts?: BinaryData[]; + font?: BinaryData | BinaryData[]; /** * Images for the `` elements (and `feImage`) by their `href`, the same string the SVG uses: with * `images: { 'logo.png': bytes }`, `` draws the image. Values are encoded images (PNG, * JPEG, WebP, GIF's first frame, ...) or {@link Image}s, decoded like data URI images are, and only for the hrefs - * the SVG references. Nothing else is read: no files and no URLs, so an href that isn't given (and isn't a data URI) - * draws nothing. SVG documents can't be given this way, use a data URI for them. Default: `{}` + * the SVG references. Nothing else is read: no files and no URLs, so drawing an image whose href isn't given (and + * isn't a data URI) throws, as does drawing one that can't be decoded. SVG documents can't be given this way, use a + * data URI for them + * @defaultValue `{}` */ images?: Record; } -/** Options of {@link Image.renderText}: the text color and layout, and its style (see {@link TextStyle}) */ -export interface TextOptions extends TextStyle { - /** The text color. Default: `0xffffffff` */ - color?: Color; - /** The text layout. Default: `new TextLayout()` */ - layout?: TextLayout; -} +/** + * Options of {@link Image.renderSVG}: the size (one of `width`, `height` and `scale`, TypeScript reports a call with + * more; by default the SVG's own size), and the limits, fonts and images (see {@link SVGResourceOptions}) + */ +export type RenderSVGOptions = SVGResourceOptions & ({ + /** + * The width in pixels, the height follows the SVG's aspect ratio + * @defaultValue The SVG's own width + */ + width?: number; + /** Not with `width`: give one of `width`, `height` and `scale` */ + height?: never; + /** Not with `width`: give one of `width`, `height` and `scale` */ + scale?: never; +} | { + /** Not with `height`: give one of `width`, `height` and `scale` */ + width?: never; + /** The height in pixels, the width follows the SVG's aspect ratio */ + height: number; + /** Not with `height`: give one of `width`, `height` and `scale` */ + scale?: never; +} | { + /** Not with `scale`: give one of `width`, `height` and `scale` */ + width?: never; + /** Not with `scale`: give one of `width`, `height` and `scale` */ + height?: never; + /** + * A factor of the SVG's own size (`2` renders it twice as large) + * @defaultValue `1` + */ + scale: number; +}); -/** Options of {@link Image.renderText}: the font and size, the text color and layout, and its style (see {@link TextStyle}) */ -export interface RenderTextOptions extends TextStyle { +/** + * Options of {@link Image.renderText}: the font and size, the text color, the layout (wrapping, cutting off and alignment, + * see {@link TextLayoutOptions}) and the style (see {@link TextStyleOptions}) + */ +export interface RenderTextOptions extends TextStyleOptions, TextLayoutOptions { /** - * TrueType (ttf/ttc), OpenType (otf) or WOFF font buffer to use, or several by priority: every character comes + * TrueType (ttf/ttc), OpenType (otf) or WOFF font buffer to use (not WOFF2 or some newer OpenType outline formats + * such as CFF2), or several by priority: every character comes * from the first font that has it (e.g. `[text, emoji]`), the first one sets the line height. Color glyphs (COLR - * layers and paints, CBDT and sbix bitmaps, as in emoji fonts) keep their colors. Text in any script is shaped - * like browsers do (right to left and bidirectional text, Arabic joining, Indic conjuncts, marks) + * layers and paints, CBDT and sbix bitmaps, as in emoji fonts) keep their colors. Shaping includes bidirectional + * layout, Arabic joining, and script-specific OpenType shapers for Indic scripts, Hebrew, Thai/Lao, Hangul, Khmer, + * Myanmar and other Universal Shaping Engine scripts; other scripts use default OpenType shaping. */ font: BinaryData | BinaryData[]; /** Font size in pixels (per em) */ size: number; - /** The text color. Default: `0xffffffff` */ + /** + * The text color + * @defaultValue `0xffffffff` + */ color?: Color; - /** The text layout, as {@link TextLayoutOptions} or a {@link TextLayout}. Default: the defaults of `TextLayout` */ - layout?: TextLayoutOptions | TextLayout; + /** + * Maximum total pixels of the rendered image (the outline included): larger text throws a {@link LimitError} (a RangeError) before its + * pixels are allocated + * @defaultValue `268402689` (16383²); `Infinity` disables the limit + */ + maxPixels?: number; } -/** Options of {@link Image.decode} */ +/** Options of {@link Image.decode}, {@link Animation.decode} and {@link decode} */ export interface DecodeOptions { - /** Whether to rotate/mirror JPEGs, TIFFs, PNGs and WebPs as their orientation tag (Exif or XMP) says. Default: `true` */ + /** + * Whether to rotate or mirror the image according to its saved orientation information, so photos taken with a + * rotated camera display upright. This applies to every animation frame too. AVIF's rotation and mirroring + * (`irot`, `imir`) are part of the image in that format and always applied, like other AVIF decoders do + * @defaultValue `true` + */ applyOrientation?: boolean; /** - * Whether to convert the colors of images with an embedded ICC profile (PNG, JPEG, WebP, AVIF, JPEG XL, TIFF), and - * of AVIFs with other color primaries than sRGB's (Display P3, BT.2020), to sRGB, like browsers show them: wide - * gamut photos (Display P3 from phones, Adobe RGB, ProPhoto) look as intended instead of washed out. Matrix/TRC - * profiles (RGB and gray) are applied, relative colorimetric (colors outside sRGB are clipped); profiles with only - * lookup tables, CMYK ones and ones that are sRGB anyway leave the pixels as they are. Default: `true` + * Whether to use the image's embedded color profile (color information describing its pixels) to convert its + * colors to sRGB, the standard used by most screens and browsers. Common RGB and gray profiles described by a + * color matrix and tone curves are converted, as are AVIFs using other color ranges (such as Display P3 or BT.2020). + * Colors outside sRGB are clipped. Profiles that rely on lookup tables, CMYK profiles and profiles already in + * sRGB are left unchanged + * @defaultValue `true` */ applyColorProfile?: boolean; /** - * The most pixels to decode: larger images throw a RangeError before anything that size is allocated, so small - * files declaring huge images (decompression bombs) can't exhaust the memory. Default: `268402689` (16383², like - * sharp), `Infinity` for no limit + * The maximum total pixels to decode. An image declaring more pixels throws a {@link LimitError} (a RangeError) before its pixel buffer + * is allocated, helping prevent a small or untrusted file from requesting an enormous amount of memory. + * {@link Animation.decode} counts all frames together because each frame uses a full canvas (and at least 1024 + * pixels, for the memory a frame takes however small it is). The decoded image + * takes 4 bytes per pixel (about 1 GiB at the default), and decoding needs more while it runs: for 8-bit images, + * about 4-7 bytes per pixel for PNG, JPEG, WebP, GIF and the simpler formats, about 14 for AVIF and about 60 for + * lossy JPEG XL on one thread, about 110 with worker threads (more with high bit depths). Lower it to bound the + * memory of servers decoding untrusted files + * @defaultValue `268402689` (16383²); `Infinity` disables the limit */ maxPixels?: number; /** - * How Radiance HDRs, PFMs and HDR (PQ or HLG) AVIFs and JPEG XLs, whose light can be brighter than (SDR) white, - * become 8 bit sRGB: `'reinhard'` compresses the brightest parts like Reinhard's tone mapping operator does (the - * brightest pixel becomes white, images no brighter than white stay as they are), `'clamp'` clamps everything - * brighter than white. Default: `'reinhard'` + * How high-dynamic-range images (which can be brighter than a standard screen's white) become 8-bit sRGB. + * `'reinhard'` gently compresses bright highlights so the brightest pixel becomes white; images that are not HDR + * stay unchanged. `'clamp'` clips anything brighter than white + * @defaultValue `'reinhard'` */ toneMapping?: ToneMapping; /** - * Whether to read the gain maps of JPEGs (Ultra HDR, JPEG-R, ISO 21496-1, Apple's), AVIFs (tone mapped items) and - * JPEG XLs (jhgm boxes) into {@link Image.gainMap}. Default: `true` + * Whether to read extra HDR brightness data (a gain map) from supported JPEG, AVIF and JPEG XL images into + * {@link Image.gainMap}. For animations, this also reads maps from supported JPEG XL frames + * @defaultValue `true` */ gainMap?: boolean; /** - * At most this many worker threads decode in parallel (lossy JPEG XLs from 4 megapixels on, one per 2 megapixels - * at most, lossless ones from 1.5 megapixels and 512 KiB on; AVIFs from 4 megapixels on: the conversion to RGB, - * one per megapixel, and the tiles of grids), `1` for none. Default: the processors available, at most 8 (1 where - * workers can't share memory) + * Maximum worker threads for formats and image sizes that can be decoded in parallel. Small images may use one + * thread because starting workers can take longer than decoding them + * @remarks + * Where workers can't start, the work runs on the calling thread with the same output. That includes browser pages + * that aren't cross-origin isolated and ones that load the package from another origin (a CDN such as jsDelivr), + * which browsers don't allow to start workers + * @defaultValue The available processors, up to 8 (one in runtimes that cannot share memory between workers) */ threads?: number; } /** Options of {@link Image.encodeJXL} */ -export interface JXLEncodeOptions { +export interface JXLEncodeOptions extends EncodeOptions { /** - * Lossy compression (0-100, like cjxl's `-q`: 90 is visually lossless, 100 lossless): higher is better and larger. - * Without it the image is encoded losslessly + * Lossy compression (0-100): higher values usually preserve more detail but make larger files; `100` is + * lossless. Without this option, the image is encoded losslessly */ quality?: number; /** - * How hard compression works: 0-2, faster to smaller. Lossy: 0 uses 8x8 DCTs only (like `cjxl -e 3`), 1 and 2 - * search their sizes like `cjxl -e 5` (2 tries more of the small ones), and 2 also stores text-like features that - * repeat (the glyphs of screenshots) once, as patches like `cjxl -e 7`. Lossless: 0 is `cjxl -e 1`'s fast mode - * (byte for byte), 1 and 2 like `cjxl -e 3` (about 15% smaller for photos, 13% for graphics; a few times slower). - * Default: `1` + * Compression effort (0-2): higher values usually take longer but may make smaller files. `0` prioritizes speed; + * `2` spends the most time compressing (lossy images only: lossless images are encoded the same at `1` and `2`) + * @defaultValue `1` */ effort?: number; /** - * At most this many worker threads compress in parallel (the same file, faster: lossy 2.3 times with 8 on a - * 1920x1080 photo at effort 1, 3.8 times on 3840x2160; lossless 2.8 and 4.3 times), `1` for none. Small images - * (lossy under about 1.5 megapixels at effort 0, 512x512 pixels at 1, 384x384 at 2; lossless under 724x724 and - * always at effort 0), and runtimes whose workers can't share memory (browsers without cross-origin isolation) - * encode without them. - * Default: the processors available, at most 8 + * Maximum worker threads for compression. Small images or runtimes that cannot share memory between workers use + * one thread + * @remarks + * Where workers can't start, the work runs on the calling thread with the same output. That includes browser pages + * that aren't cross-origin isolated and ones that load the package from another origin (a CDN such as jsDelivr), + * which browsers don't allow to start workers + * @defaultValue The available processors, up to 8 */ threads?: number; - /** Metadata to include, see {@link Metadata} */ - metadata?: Metadata; /** - * Whether to write the image's {@link Image.gainMap} (brighter on HDR displays: a jhgm box, like libjxl's), or how. - * Default: `true` (written if there is one) + * Whether to write the image's {@link Image.gainMap}, the extra data used to show brighter highlights on HDR + * displays + * @defaultValue `true` (written if there is one) */ - gainMap?: boolean | { - /** The map's quality (1-100 like `quality`, 100 lossless). Default: `90` */ - quality?: number, - /** The map's size as a factor of the image's (0-1). Default: the map's own size */ - scale?: number - }; + gainMap?: boolean | GainMapEmbedOptions; } /** Options of {@link Image.encodeAVIF} */ -export interface AVIFEncodeOptions { - /** 0-100, like avifenc's: higher is better and larger, 100 is lossless. Default: `60` */ +export interface AVIFEncodeOptions extends EncodeOptions { + /** + * 0-100, like avifenc's: higher is better and larger, 100 is lossless + * @defaultValue `60` + */ quality?: number; - /** The quality of the alpha channel (if the image has transparency), like avifenc's. Default: `100` (lossless) */ + /** + * The quality of the transparency channel, if the image has transparency + * @defaultValue `100` (lossless) + */ alphaQuality?: number; - /** Chroma subsampling: `'4:4:4'` keeps the full color resolution, `'4:2:0'` halves it (smaller). Default: `'4:4:4'` */ + /** + * How much color detail to keep: `'4:4:4'` keeps it all; `'4:2:0'` stores less color detail to make a smaller + * file + * @defaultValue `'4:4:4'` + */ subsampling?: '4:4:4' | '4:2:0'; - /** How hard the encoder searches for the best modes: 0-2, faster to smaller. Default: `1` */ + /** + * How hard the encoder searches for the best modes: 0-2, faster to smaller + * @defaultValue `1` + */ effort?: number; /** - * At most this many worker threads encode in parallel (the same file, faster: 2.9 times with 8 on a 1920x1080 - * photo at effort 1), `1` for none. Small images (under about 640x640 pixels at effort 0, 448x448 at 1, 320x320 - * at 2), and runtimes whose workers can't share memory (browsers without cross-origin isolation), encode without - * them. Default: the processors available, at most 8 + * Maximum worker threads for compression. Small images or runtimes that cannot share memory between workers use + * one thread + * @remarks + * Where workers can't start, the work runs on the calling thread with the same output. That includes browser pages + * that aren't cross-origin isolated and ones that load the package from another origin (a CDN such as jsDelivr), + * which browsers don't allow to start workers + * @defaultValue The available processors, up to 8 */ threads?: number; - /** Metadata to include, see {@link Metadata} */ - metadata?: Metadata; /** - * Whether to write the image's {@link Image.gainMap} (brighter on HDR displays: a tone mapped item, like libavif - * writes), or how. Default: `true` (written if there is one) + * Whether to write the image's {@link Image.gainMap}, the extra data used to show brighter highlights on HDR + * displays + * @defaultValue `true` (written if there is one) */ - gainMap?: boolean | { - /** The map's quality (1-100). Default: `90` */ - quality?: number, - /** The map's size as a factor of the image's (0-1). Default: the map's own size */ - scale?: number - }; + gainMap?: boolean | GainMapEmbedOptions; } /** Text style options of {@link Image.renderText} */ -export interface TextStyle { - /** Width of an outline around the glyphs in pixels. Default: `0` */ +export interface TextStyleOptions { + /** + * Width of an outline around the glyphs in pixels + * @defaultValue `0` + */ strokeWidth?: number; - /** Color of the outline. Default: `0x000000ff` */ + /** + * Color of the outline + * @defaultValue `0x000000ff` + */ strokeColor?: Color; /** * Whether to run the hinting instructions of TrueType fonts, which align stems and edges with the pixel grid for * crisper text at small sizes (like Windows renders text); the glyphs of hinted fonts are then placed on whole - * pixels. Fonts without instructions (and CFF/OpenType outlines) aren't affected. Default: `true` + * pixels. Fonts without instructions (and CFF/OpenType outlines) aren't affected + * @defaultValue `true` */ hinting?: boolean; /** * OpenType features by their tags, for the whole text: `true` turns one on (like `tnum` for tabular numbers, * `smcp` for small caps, `ss01` for a stylistic set), `false` off (also the ones on by default, like `liga` or - * `kern`), a number picks an alternate (`salt: 2`). Fonts without a feature ignore it. Default: `{}` + * `kern`), a number picks an alternate (`salt: 2`). Fonts without a feature ignore it + * @defaultValue `{}` */ features?: Record; /** @@ -594,7 +761,8 @@ export interface TextStyle { * right), `italic` (`true`/`false`), `opticalSize` (the size the glyphs are designed for, in pixels; default: the * font size, like browsers' `font-optical-sizing: auto`), and other axes by their 4-character tag (like Roboto * Flex's `GRAD: 50`). Values outside an axis's range are clamped, axes a font doesn't have are ignored, fonts - * without axes aren't affected. Default: `{}` (the fonts' default instances) + * without axes aren't affected + * @defaultValue `{}` (the fonts' default instances) */ variations?: Record; } @@ -602,46 +770,53 @@ export interface TextStyle { /** Options of {@link Image.cropCircle} */ export interface CropCircleOptions { /** - * The circle's size: `'contain'` fits it inside the image (the smaller dimension is its diameter, no hard edges), + * How the circle fits the image: `'contain'` fits it inside the image (the smaller dimension is its diameter, no hard edges), * `'cover'` covers the image (the larger dimension is its diameter, the corners of a rectangular image stay - * transparent on the shorter side). Default: `'contain'` + * transparent on the shorter side) + * @defaultValue `'contain'` */ fit?: 'contain' | 'cover'; /** - * The circle's size, like {@link CropCircleOptions.fit} - * @deprecated Use `fit`, its name in 4.0, which ignores `size`: `cropCircle({ fit: 'cover' })` + * Share of the radius (0 to 1, a value outside of it throws) over which the edge fades out + * @defaultValue `0` */ - size?: 'contain' | 'cover'; - /** - * Whether to use the larger dimension for the size. Default: `false` - * @deprecated Use `fit: 'cover'` (`true`) or `fit: 'contain'` (`false`), `max` will be removed in 4.0 - */ - max?: boolean; - /** Share of the radius (0..1) over which the edge fades out. Default: `0` */ feathering?: number; } /** Options of {@link Image.dominantColor} */ export interface DominantColorOptions { - /** Whether to ignore dark colors (all channels below the threshold). Default: `true` */ + /** + * Whether to ignore dark colors (all channels below `threshold`) + * @defaultValue `true` + */ ignoreBlack?: boolean; - /** Whether to ignore light colors (all channels above 255 minus the threshold). Default: `true` */ + /** + * Whether to ignore light colors (all channels above 255 minus `threshold`) + * @defaultValue `true` + */ ignoreWhite?: boolean; - /** The black/white threshold (0-64, in steps of 4 channel values). Default: `15` */ + /** + * How close (in channel values, 0-256) to black or white a color has to be to be ignored + * @defaultValue `60` + */ threshold?: number; } /** Options of {@link Image.rotate} */ export interface RotateOptions { - /** Whether to resize the image so it fits all pixels or just ignore outlying pixels. Default: `true` */ - resize?: boolean; /** - * Whether to sample with 8-bit weights on 8-bit premultiplied pixels (like {@link ResizeOptions.fast}), about twice - * as fast: opaque pixels stay within a step of the precise result, what shows of translucent ones (also the - * faded edges) within about 2.5 steps (pixels that are almost transparent keep less of their color). Only affects - * angles that aren't multiples of 90°. Default: `true` + * Whether to make the image larger so the rotated corners aren't cut off. Without it, the image keeps its size and + * the parts outside are lost + * @defaultValue `true` */ - fast?: boolean; + expand?: boolean; + /** + * How the pixels between the source's are sampled for angles that aren't multiples of 90° (those move whole + * pixels): `'nearest-neighbor'` (hard pixels, for pixel art), `'bilinear'` (smooth) or `'bicubic'` (sharper, can + * overshoot a little at hard edges), like {@link TransformOptions.mode} + * @defaultValue `'bilinear'` + */ + mode?: TransformMode; } /** Options of {@link Image.trim} */ @@ -653,7 +828,8 @@ export interface TrimOptions { color?: Color; /** * How far (0-1) a pixel's channels may be from the color for it to be trimmed, e.g. for JPEG artifacts or - * antialiasing. Default: `0` + * antialiasing + * @defaultValue `0` */ tolerance?: number; } @@ -662,26 +838,28 @@ export interface TrimOptions { export interface ColorToAlphaOptions { /** The color to remove, by default the color of the top left pixel (e.g. a background) */ color?: Color; - /** Pixels at most this far from the color (0-1) become fully transparent. Default: 0 */ + /** + * Pixels at most this far from the color (0-1) become fully transparent + * @defaultValue 0 + */ transparencyThreshold?: number; - /** Pixels at least this far from the color (0-1) stay fully opaque. Default: 1 */ + /** + * Pixels at least this far from the color (0-1) stay fully opaque + * @defaultValue 1 + */ opacityThreshold?: number; } -/** - * Text metadata written into PNGs - * @deprecated Use {@link Metadata}, which all encoders take - * @group Deprecated - */ -export type PNGMetadata = Metadata; - // OpenType features as tags and values (tags are 4 printable ASCII characters) function featureList(features: Record): Array<[string, number]> { - if (typeof features !== 'object' || features === null) throw new TypeError('Features must be an object'); + // eslint-disable-next-line no-restricted-syntax -- the OpenType features are only used by the text functions + if (typeof features !== 'object' || features === null) throw new TypeError(`features must be an object, like { liga: false }, not ${shown(features)}`); return Object.entries(features).map(([tag, value]) => { - if (!/^[\x20-\x7e]{4}$/.test(tag)) throw new RangeError(`Invalid OpenType feature tag: ${JSON.stringify(tag)}`); + // eslint-disable-next-line no-restricted-syntax -- the OpenType features are only used by the text functions + if (!/^[\x20-\x7e]{4}$/.test(tag)) throw new RangeError(`An OpenType feature tag must be 4 printable ASCII characters, not ${JSON.stringify(tag)}`); if (typeof value === 'boolean') return [tag, value ? 1 : 0]; - if (!Number.isInteger(value) || value < 0 || value > 255) throw new RangeError(`Invalid value of the OpenType feature ${tag}: ${value}`); + if (typeof value !== 'number') throw new TypeError(`The value of the OpenType feature ${tag} must be a boolean or a number, not ${shown(value)}`); + if (!Number.isInteger(value) || value < 0 || value > 255) throw new RangeError(`The value of the OpenType feature ${tag} must be a whole number from 0 to 255, not ${value}`); return [tag, value]; }); } @@ -689,6 +867,12 @@ function featureList(features: Record): Array<[string, /** * An RGBA image; provides the codecs and the manipulation functions. Methods that change the image modify it in place * and return it, so calls can be chained + * + * @remarks Subclassing is not supported: the methods that make an image ({@link Image.clone}, {@link Image.extract}, + * {@link Image.decode}, ...) return plain `Image`s, without calling a subclass' constructor. + * + * The `maxPixels` limits guard what comes from outside: decoding and rendering. `new Image()`, `resize()` and + * `scale()` make the size they are asked for, so check sizes that come from users before you pass them on */ export class Image { /** @@ -724,26 +908,25 @@ export class Image { /** * Creates a new image with the given dimensions, all pixels transparent black - * @param width The width in pixels - * @param height The height in pixels + * @param width The width in pixels (a fraction is truncated) + * @param height The height in pixels (a fraction is truncated) + * @throws `TypeError` if the width or height is not a number + * @throws `RangeError` if the width or height is less than 1, or the image is too large to allocate */ constructor(width: number, height: number) { - width = ~~width; - height = ~~height; - - if (width < 1) - throw new RangeError('Image has to be at least 1 pixel wide'); - if (height < 1) - throw new RangeError('Image has to be at least 1 pixel high'); + width = pixels(width, 'width'); + height = pixels(height, 'height'); this.__width__ = width; this.__height__ = height; - this.__set_bitmap__(new Uint8ClampedArray(width * height * 4)); + this.__set_bitmap__(allocate(width, height, () => new Uint8ClampedArray(width * height * 4))); } /** - * The image's gain map, if it has one (JPEGs from phones, Ultra HDR): how much brighter each part gets on HDR - * displays. {@link Image.encodeJPEG} writes it. `null` removes it + * Extra image data that lets high-dynamic-range (HDR) screens show brighter highlights. Standard screens show the + * image without the extra brightness. {@link Image.encodeJPEG}, {@link Image.encodeAVIF} and + * {@link Image.encodeJXL} can write it. `null` means there is no gain map. This is the image's own map, not a + * copy: changing it (`image.gainMap.max = 3`) changes the image's */ get gainMap(): GainMap | null { return this.__gain_map__; @@ -751,16 +934,22 @@ export class Image { /** * Replaces the gain map + * @remarks + * The image uses a copy of the map: changing the image (resizing it, say) changes its own map only, also when the + * same map was given to other images, and later changes to the map you gave don't reach the image * @param gainMap The new gain map, or `null` to remove it + * @throws `TypeError` if it isn't a {@link GainMap} or `null` */ set gainMap(gainMap: GainMap | null) { - if (gainMap !== null && !(gainMap instanceof GainMap)) throw new TypeError('The gain map has to be a GainMap or null'); - this.__gain_map__ = gainMap; + // eslint-disable-next-line no-restricted-syntax -- the one property that takes a GainMap + if (gainMap !== null && !(gainMap instanceof GainMap)) throw new TypeError(`gainMap must be a GainMap or null, not ${shown(gainMap)}`); + this.__gain_map__ = gainMap?.clone() ?? null; } /** - * The image's RGBA pixel data. It can be replaced by any 8-bit array with width * height * 4 bytes - * (it is used as is, without copying) + * The image's RGBA pixel data (red, green, blue and transparency, four bytes per pixel). It can be replaced by any + * 8-bit array with width * height * 4 bytes starting at a byte offset divisible by 4 (it is used as is, without + * copying). Direct changes to this array or {@link Image.setPixelAt} don't update the image's gain map. */ get bitmap(): Uint8ClampedArray { return this.__bitmap__; @@ -768,13 +957,16 @@ export class Image { /** * Replaces the pixel data - * @param bitmap The new RGBA data, width * height * 4 bytes (used as is, without copying) + * @param bitmap The new RGBA data, width * height * 4 bytes (used as is, without copying, so its byte offset has to be + * divisible by 4: the image reads it as 32-bit pixels too) */ set bitmap(bitmap: Uint8ClampedArray | Uint8Array) { - if (!(bitmap instanceof Uint8ClampedArray || bitmap instanceof Uint8Array)) - throw new TypeError('The bitmap has to be a Uint8ClampedArray or Uint8Array'); + instance(bitmap, [Uint8ClampedArray, Uint8Array], 'bitmap'); if (bitmap.length !== this.width * this.height * 4) - throw new RangeError(`The bitmap has to have ${this.width * this.height * 4} bytes (width * height * 4), got ${bitmap.length}`); + throw new RangeError(`bitmap must have ${this.width * this.height * 4} bytes (width * height * 4), not ${bitmap.length}`); + // (a copy would no longer be the array the caller has) + if (bitmap.byteOffset % 4) + throw new TypeError(`The bitmap has to start at a byte offset divisible by 4 to be used without copying, not ${bitmap.byteOffset} (pass bitmap.slice() for a copy)`); this.__set_bitmap__(bitmap instanceof Uint8ClampedArray ? bitmap : new Uint8ClampedArray(bitmap.buffer, bitmap.byteOffset, bitmap.length)); } @@ -785,11 +977,11 @@ export class Image { * @ignore */ protected __set_bitmap__(bitmap: Uint8ClampedArray): void { - // 32-bit views need an aligned offset + // 32-bit views need an aligned offset (the bitmap setter only takes aligned ones, internal pixels get copied) if (bitmap.byteOffset % 4) bitmap = bitmap.slice(); this.__bitmap__ = bitmap; this.__view__ = new DataView(bitmap.buffer, bitmap.byteOffset, bitmap.byteLength); - this.__u32__ = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >> 2); + this.__u32__ = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >>> 2); } /** A short description for debugging, e.g. `Image<64x64>` */ @@ -798,144 +990,36 @@ export class Image { } /** - * The images width + * The image's width */ get width(): number { return this.__width__; } /** - * The images height + * The image's height */ get height(): number { return this.__height__; } /** - * Yields an [x, y] array for every pixel in the image (0-based), row by row - * @yields The coordinates of the pixel ([x, y]) - * @deprecated Use {@link Image.pixels}, which yields `[x, y, color]`: `coordinates()` will be removed in 4.0 - * @group Deprecated - */ - *coordinates(): Generator<[x: number, y: number], void, undefined> { - for (let y = 0; y < this.height; y++) - for (let x = 0; x < this.width; x++) - yield [x, y]; - } - - /** - * Yields an [x, y, color] array for every pixel in the image (0-based), row by row + * Yields an [x, y, color] array for every pixel in the image (0-based), row by row. Resizing the image meanwhile + * doesn't affect the iteration (it goes on over the pixels the image had when `pixels()` was called), but other changes to the pixels, like + * `setPixelAt()`, are seen by the pixels not yet yielded * @yields The coordinates and color of the pixel ([x, y, color]) */ - *pixels(): Generator<[x: number, y: number, color: Color], void, undefined> { + pixels(): Generator<[x: number, y: number, color: Color], void, undefined> { + // (the pixels and the size as they are when this is called, not when the first value is taken: a generator's + // body only runs then, so this isn't one) const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength); - let offset = 0; - for (let y = 0; y < this.height; y++) - for (let x = 0; x < this.width; x++, offset += 4) - yield [x, y, view.getUint32(offset, false)]; - } - - /** - * Yields an [x, y] array for every pixel in the image (0-based) - * @yields The coordinates of the pixel ([x, y]) - * @deprecated Use {@link Image.pixels}, which yields `[x, y, color]`: iterating over the image will be removed in 4.0 - * @group Deprecated - */ - *[Symbol.iterator](): Generator<[x: number, y: number], void, undefined> { - yield* this.coordinates(); - } - - /** - * Yields an [x, y, color] array for every pixel in the image (0-based) - * @yields The coordinates and color of the pixel ([x, y, color]) - * @deprecated Use {@link Image.pixels}, `iterateWithColors()` will be removed in 4.0 - * @group Deprecated - */ - *iterateWithColors(): Generator<[x: number, y: number, color: Color], void, undefined> { - yield* this.pixels(); - } - - /** - * Converts RGBA components to an RGBA value, values are rounded and clamped to 0..255 - * @param r red (0..255) - * @param g green (0..255) - * @param b blue (0..255) - * @param a alpha (0..255) - * @deprecated Use {@link Colors.fromRGBA}, `Image.rgbaToColor` will be removed in 4.0 - * @group Deprecated - */ - static rgbaToColor(r: number, g: number, b: number, a: number): Color { - return Colors.fromRGBA(r, g, b, a); - } - - /** - * Converts RGB components to an RGBA value (assuming alpha = 255) - * @param r red (0..255) - * @param g green (0..255) - * @param b blue (0..255) - * @deprecated Use {@link Colors.fromRGB}, `Image.rgbToColor` will be removed in 4.0 - * @group Deprecated - */ - static rgbToColor(r: number, g: number, b: number): Color { - return Colors.fromRGB(r, g, b); - } - - /** - * Converts HSLA colors to RGBA colors - * @param h hue (0..1) - * @param s saturation (0..1) - * @param l lightness (0..1) - * @param a opacity (0..1) - * @deprecated Use {@link Colors.fromHSLA}, `Image.hslaToColor` will be removed in 4.0 - * @group Deprecated - */ - static hslaToColor(h: number, s: number, l: number, a: number): Color { - return Colors.fromHSLA(h, s, l, a); - } - - /** - * Converts HSL colors to RGBA colors (assuming an opacity of 255) - * @param h hue (0..1) - * @param s saturation (0..1) - * @param l lightness (0..1) - * @deprecated Use {@link Colors.fromHSL}, `Image.hslToColor` will be removed in 4.0 - * @group Deprecated - */ - static hslToColor(h: number, s: number, l: number): Color { - return Colors.fromHSL(h, s, l); - } - - /** - * Converts an RGBA value to an array of HSLA values - * @param r red (0..255) - * @param g green (0..255) - * @param b blue (0..255) - * @param a alpha (0..255) - * @deprecated Use {@link Colors.toHSLA}, `Image.rgbaToHSLA` will be removed in 4.0 - * @group Deprecated - */ - static rgbaToHSLA(r: number, g: number, b: number, a: number): [h: number, s: number, l: number, a: number] { - return rgbaToHSLA(r, g, b, a); - } - - /** - * Converts a color value to an array of RGBA values - * @param color The color value to convert - * @deprecated Use {@link Colors.toRGBA}, `Image.colorToRGBA` will be removed in 4.0 - * @group Deprecated - */ - static colorToRGBA(color: Color): [r: number, g: number, b: number, a: number] { - return Colors.toRGBA(color); - } - - /** - * Converts a color value to an array of RGB values (ignoring the colors alpha) - * @param color The color value to convert - * @deprecated Use {@link Colors.toRGB}, `Image.colorToRGB` will be removed in 4.0 - * @group Deprecated - */ - static colorToRGB(color: Color): [r: number, g: number, b: number] { - return Colors.toRGB(color); + const width = this.width, height = this.height; + return (function* () { + let offset = 0; + for (let y = 0; y < height; y++) + for (let x = 0; x < width; x++, offset += 4) + yield [x, y, view.getUint32(offset, false)] as [x: number, y: number, color: Color]; + })(); } /** @@ -946,10 +1030,14 @@ export class Image { * @returns The new image */ static linearGradient(width: number, height: number, options: LinearGradientOptions): Image { + checkOptions(options, 'Image.linearGradient(100, 50, { stops, angle: 90 })'); + if (options === undefined || options.stops === undefined) throw new TypeError('Image.linearGradient(width, height, { stops }) needs the stops in the options'); const { stops, angle = 180 } = options; const color = gradientFunction(stops); finite(angle, 'angle'); const image = new Image(width, height); + // (sizes with a fraction are truncated by the image: the pixels are written to that size) + ({ width, height } = image); const radians = angle * Math.PI / 180; // the direction (y points down, 0 degrees up), and the length of the line through the center to the corners const dx = Math.sin(radians), dy = -Math.cos(radians); @@ -969,11 +1057,17 @@ export class Image { * @returns The new image */ static radialGradient(width: number, height: number, options: RadialGradientOptions): Image { + checkOptions(options, 'Image.radialGradient(100, 50, { stops })'); + // (sizes with a fraction are truncated like the image's: the pixels are written to that size; the options are + // checked before the image is allocated) + width = pixels(width, 'width'); + height = pixels(height, 'height'); + if (options === undefined || options.stops === undefined) throw new TypeError('Image.radialGradient(width, height, { stops }) needs the stops in the options'); const { stops, x: cx = width / 2, y: cy = height / 2, radius = Math.hypot(Math.max(cx, width - cx), Math.max(cy, height - cy)) } = options; const color = gradientFunction(stops); finite(cx, 'x'); finite(cy, 'y'); - if (!(finite(radius, 'radius') > 0)) throw new RangeError('Invalid radius'); + positive(radius, 'radius'); const image = new Image(width, height); const bitmap = new DataView(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength); for (let y = 0, i = 0; y < height; y++) @@ -983,53 +1077,32 @@ export class Image { } /** - * Creates a multi-point gradient generator - * @param colors The gradient points to use (e.g. `{0: 0xff0000ff, 1: 0x00ff00ff}`) - * @deprecated Use {@link Colors.gradient}, `Image.gradient` will be removed in 4.0 - * @group Deprecated - */ - static gradient(colors: Record): (position: number) => Color { - return Colors.gradient(colors); - } - - /** - * Gets the pixel color at the specified position (0-based) - * @param x The x coordinate - * @param y The y coordinate + * Gets the pixel color at the specified position (0-based). {@link Colors.toRGBA} splits it into its channels + * @param x The x coordinate (a fraction is dropped: 1.9 is the pixel 1) + * @param y The y coordinate (likewise) * @returns The color value (`0xRRGGBBAA`) + * @throws `RangeError` if the position isn't inside the image + * @see {@link Image.pixels} to go over every pixel */ getPixelAt(x: number, y: number): Color { - x = ~~finite(x, 'x'); - y = ~~finite(y, 'y'); + x = Math.trunc(finite(x, 'x')); + y = Math.trunc(finite(y, 'y')); this.__check_boundaries__(x, y); return this.__view__.getUint32((y * this.width + x) * 4, false); } - /** - * Gets a view of the RGBA components of the pixel at the specified position (0-based) - * @param x The x coordinate - * @param y The y coordinate - * @returns The pixel's 4 bytes in {@link Image.bitmap}: writing to them changes the pixel - */ - getRGBAAt(x: number, y: number): Uint8ClampedArray { - x = ~~finite(x, 'x'); - y = ~~finite(y, 'y'); - this.__check_boundaries__(x, y); - const idx = (y * this.width + x) * 4; - return this.bitmap.subarray(idx, idx + 4); - } - /** * Sets the pixel color for the specified position (0-based) * @param x The x coordinate * @param y The y coordinate - * @param pixelColor The new color (`0xRRGGBBAA`) + * @param color The new color (`0xRRGGBBAA`) + * @throws `RangeError` if the position isn't inside the image */ - setPixelAt(x: number, y: number, pixelColor: Color): this { - x = ~~finite(x, 'x'); - y = ~~finite(y, 'y'); + setPixelAt(x: number, y: number, color: Color): this { + x = Math.trunc(finite(x, 'x')); + y = Math.trunc(finite(y, 'y')); this.__check_boundaries__(x, y); - this.__set_pixel__(x, y, checkColor(pixelColor)); + this.__set_pixel__(x, y, checkColor(color)); return this; } @@ -1046,50 +1119,35 @@ export class Image { * @ignore */ protected __check_boundaries__(x: number, y: number): void { - if (isNaN(x)) throw new TypeError(`Invalid pixel coordinates (x=${x})`); - if (isNaN(y)) throw new TypeError(`Invalid pixel coordinates (y=${y})`); - if (x < 0) - throw new RangeError(`${Image.__out_of_bounds__} (x=${x})<0`); - if (x >= this.width) - throw new RangeError(`${Image.__out_of_bounds__} (x=${x})>=(width=${this.width})`); - if (y < 0) - throw new RangeError(`${Image.__out_of_bounds__} (y=${y})<0`); - if (y >= this.height) - throw new RangeError(`${Image.__out_of_bounds__} (y=${y})>=(height=${this.height})`); - } - - /** - * @private - */ - /** - * @internal - * @ignore - */ - protected static get __out_of_bounds__(): string { - return 'Tried referencing a pixel outside of the images boundaries:'; + coordinate(x, this.width - 1, 'x'); + coordinate(y, this.height - 1, 'y'); } /** - * Fills the image data with the supplied color - * @param color The color, or a function returning the color of each pixel + * Fills the image data with the supplied color. The image's gain map, if it has one, is made neutral (no boost + * anywhere): the new pixels have no HDR light beyond their own + * @param color The color, or a function returning the color of each pixel (checked like any color: a result that + * isn't a number throws a TypeError, a number that isn't a color a RangeError) */ fill(color: Color | ColorFunction): this { const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength); if (typeof color !== 'function') color = checkColor(color); - // (the new pixels have no HDR light beyond their own: no boost anywhere) - if (this.__gain_map__) this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height); if (typeof color === 'function') { + // (written to a copy first: a function that throws leaves the image as it was) + const pixels = new Uint8ClampedArray(this.bitmap.length), out = new DataView(pixels.buffer); let offset = 0; for (let y = 0; y < this.height; y++) for (let x = 0; x < this.width; x++, offset += 4) - view.setUint32(offset, color(x, y), false); + out.setUint32(offset, checkColor(color(x, y)), false); + this.bitmap.set(pixels); } else { - if (!this.bitmap.length) return this; view.setUint32(0, color, false); const u32 = new Uint32Array(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength / 4); u32.fill(u32[0]); } + // (the new pixels have no HDR light beyond their own: no boost anywhere) + if (this.__gain_map__) this.__gain_map__ = gain.neutralMap(this.__gain_map__, this.width, this.width, this.height); return this; } @@ -1108,53 +1166,28 @@ export class Image { } /** - * @deprecated Use the name `'nearest-neighbor'`: `Image.RESIZE_*` and `ResizeModes` are removed in 4.0 - * @group Deprecated - */ - static readonly RESIZE_NEAREST_NEIGHBOR = 'RESIZE_NEAREST_NEIGHBOR'; - - /** - * @deprecated Use the name `'bilinear'`: `Image.RESIZE_*` and `ResizeModes` are removed in 4.0 - * @group Deprecated - */ - static readonly RESIZE_BILINEAR = 'RESIZE_BILINEAR'; - - /** - * @deprecated Use the name `'bicubic'`: `Image.RESIZE_*` and `ResizeModes` are removed in 4.0 - * @group Deprecated - */ - static readonly RESIZE_BICUBIC = 'RESIZE_BICUBIC'; - - /** - * @deprecated Use the name `'area'`: `Image.RESIZE_*` and `ResizeModes` are removed in 4.0 - * @group Deprecated - */ - static readonly RESIZE_AREA = 'RESIZE_AREA'; - - /** - * @deprecated Pass only the width or the height instead, `image.resize({ width: 256 })`. `Image.RESIZE_*` will - * be removed in 4.0 - * @group Deprecated + * Set by {@link Frame} while one of its methods runs: the methods that change the image's size call it with where + * the pixels went, so the frame can move its offsets. The new image's top left corner is where the point (x, y) + * of the old image was, after the old image was scaled by (scaleX, scaleY) + * @internal + * @ignore */ - static readonly RESIZE_AUTO: typeof ResizeModes.AUTO = ResizeModes.AUTO; + declare __moved__?: (scaleX: number, scaleY: number, x: number, y: number) => void; /** - * Resizes the image by the given factor + * Resizes the image by the given factor: a side of 7 pixels scaled by 0.5 is 3 (fractions are dropped, a side + * doesn't go below 1 pixel) * @param factor The factor to resize the image with * @param options See {@link ResizeOptions} */ scale(factor: number, options?: ResizeOptions): this; - /** - * Resizes the image by the given factor - * @param factor The factor to resize the image with - * @param [mode=ResizeModes.BILINEAR] The resizing mode to use - * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0 - */ - scale(factor: number, mode?: ResizeMode): this; - scale(factor: number, modeOrOptions?: ResizeMode | ResizeOptions): this { - const { mode, fast } = resizeOptions(modeOrOptions); - const image = this.__scale__(factor, mode, fast); + scale(factor: number, options?: ResizeOptions): this { + checkOptions(options, 'scale(factor, { mode: \'area\' })'); + const { mode } = resizeOptions(options); + scaleFactor(factor, this.width, this.height); + const image = this.__scale__(factor, mode); this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height); + this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0); return this.__apply__(image); } @@ -1163,9 +1196,11 @@ export class Image { * @internal * @ignore */ - protected __scale__(factor: number, mode: ResizeMode = ResizeModes.BILINEAR, fast = true): Image { + protected __scale__(factor: number, mode: ResizeMode = 'bilinear'): Image { if (factor === 1) return this; - return this.__resize__(this.width * factor, this.height * factor, mode, fast); + // (a side doesn't shrink below one pixel, like resize({ width }) keeping the aspect ratio) + const size = (side: number): number => factor > 0 ? Math.max(1, side * factor) : side * factor; + return this.__resize__(size(this.width), size(this.height), mode); } /** @@ -1177,126 +1212,75 @@ export class Image { * @returns The resized image */ resize(width: number, height: number, options?: ResizeOptions): this; - /** - * Resizes the image to the given dimensions. - * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio. - * @param width The new width - * @param height The new height - * @param [mode=ResizeModes.BILINEAR] The resizing mode to use - * @returns The resized image - * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0 - */ - resize(width: number, height: number, mode?: ResizeMode): this; /** * Resizes the image: to the given width or height (the other side keeps the aspect ratio), or to both + * @example + * ```ts + * image.resize({ width: 300, height: 200, fit: 'cover' }); // fills 300x200, cropping what doesn't fit + * image.resize({ width: 150 }); // 150 wide, the height keeps the aspect ratio + * ``` * @param options The size and how to resize, see {@link ResizeToOptions} * @returns The resized image */ resize(options: ResizeToOptions): this; - resize(widthOrOptions: number | ResizeToOptions, heightArgument?: number, modeArgument?: ResizeMode | ResizeOptions): this { - const [width, height, modeOrOptions] = resizeArguments(widthOrOptions, heightArgument, modeArgument); - const { mode, fast } = resizeOptions(modeOrOptions); - const image = this.__resize__(width, height, mode, fast); + resize(widthOrOptions: number | ResizeToOptions, heightArgument?: number, optionsArgument?: ResizeOptions): this { + const [width, height, options, fit] = resizeArguments(widthOrOptions, heightArgument, optionsArgument); + if (fit === 'contain' || fit === 'cover') { + if (width === undefined || height === undefined) throw new TypeError(`resize({ fit: '${fit}' }) needs both width and height`); + return fit === 'contain' + ? this.__contain__(width, height, options) + : this.__cover__(width, height, options); + } + const { mode } = resizeOptions(options); + const image = this.__resize__(...this.__resized_size__(width, height, fit), mode); this.__gain_map__?.__rescale__(this.width, this.height, image.width, image.height); + this.__moved__?.(image.width / this.width, image.height / this.height, 0, 0); return this.__apply__(image); } /** - * Resizes the image so it is contained in the given bounding box. - * Can return an image with one axis smaller than the given bounding box. - * @param width The width of the bounding box - * @param height The height of the bounding box - * @param options See {@link ResizeOptions} - * @returns The resized image - */ - contain(width: number, height: number, options?: ResizeOptions): this; - /** - * Resizes the image so it is contained in the given bounding box. - * Can return an image with one axis smaller than the given bounding box. - * @param width The width of the bounding box - * @param height The height of the bounding box - * @param [mode=ResizeModes.BILINEAR] The resizing mode to use - * @returns The resized image - * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0 - */ - contain(width: number, height: number, mode?: ResizeMode): this; - contain(width: number, height: number, modeOrOptions?: ResizeMode | ResizeOptions): this { - const options = resizeOptions(modeOrOptions); - width = Math.floor(finite(width, 'width')); - height = Math.floor(finite(height, 'height')); - // round instead of flooring the scaled size, so the limiting axis matches the box exactly - const scale = Math.min(width / this.width, height / this.height); - return this.resize(Math.max(1, Math.min(width, Math.round(this.width * scale))), Math.max(1, Math.min(height, Math.round(this.height * scale))), options); - } - - /** - * Resizes the image so it is contained in the given bounding box, placing it in the center of the given bounding box. - * Always returns the exact dimensions of the bounding box. - * @param width The width of the bounding box - * @param height The height of the bounding box - * @param options See {@link ResizeOptions} - * @returns The resized image - */ - fit(width: number, height: number, options?: ResizeOptions): this; - /** - * Resizes the image so it is contained in the given bounding box, placing it in the center of the given bounding box. - * Always returns the exact dimensions of the bounding box. - * @param width The width of the bounding box - * @param height The height of the bounding box - * @param [mode=ResizeModes.BILINEAR] The resizing mode to use - * @returns The resized image - * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0 + * Resizes and centers the image in a box of exactly that size, with transparent or colored bars + * @internal */ - fit(width: number, height: number, mode?: ResizeMode): this; - fit(width: number, height: number, modeOrOptions?: ResizeMode | ResizeOptions): this { - const options = resizeOptions(modeOrOptions); + private __contain__(width: number, height: number, options?: ResizeRuntimeOptions): this { + const { background = 0x00000000, ...resizeOpts } = options ?? {}; + const backgroundColor = checkColor(background, 'background'); + resizeOptions(resizeOpts); + // (checked before anything changes) + width = pixels(width, 'width'); + height = pixels(height, 'height'); const result = new Image(width, height); - this.contain(width, height, options); + if (backgroundColor !== 0) result.fill(backgroundColor); + this.resize(...insideSize(this.width, this.height, width, height), resizeOpts); const x = (width - this.width) / 2 | 0, y = (height - this.height) / 2 | 0; - result.composite(this, x, y); + result.composite(this, { x, y }); this.__gain_map__?.__transform__(this.width, this.height, result.width, result.height, (X, Y) => [X - x, Y - y]); + this.__moved__?.(1, 1, -x, -y); return this.__apply__(result); - } - - /** - * Resizes the image so it covers the given bounding box, cropping the overflowing edges. - * Always returns the exact dimensions of the bounding box. - * @param width The width of the bounding box - * @param height The height of the bounding box - * @param options See {@link ResizeOptions} - * @returns The resized image - */ - cover(width: number, height: number, options?: ResizeOptions): this; + } + /** - * Resizes the image so it covers the given bounding box, cropping the overflowing edges. - * Always returns the exact dimensions of the bounding box. - * @param width The width of the bounding box - * @param height The height of the bounding box - * @param [mode=ResizeModes.BILINEAR] The resizing mode to use - * @returns The resized image - * @deprecated Pass {@link ResizeOptions} with `mode` instead, the positional mode will be removed in 4.0 + * Resizes the image to cover the box, cropping the overflowing edges + * @internal */ - cover(width: number, height: number, mode?: ResizeMode): this; - cover(width: number, height: number, modeOrOptions?: ResizeMode | ResizeOptions): this { - const options = resizeOptions(modeOrOptions); - width = Math.floor(width); - height = Math.floor(height); + private __cover__(width: number, height: number, options?: ResizeOptions): this { + const resizeOpts = resizeOptions(options); // (checked before anything changes: a box below a pixel used to resize the image, then fail to crop it) - if (!(width >= 1 && Number.isFinite(width))) - throw new RangeError('Image has to be at least 1 pixel wide'); - if (!(height >= 1 && Number.isFinite(height))) - throw new RangeError('Image has to be at least 1 pixel high'); + width = pixels(width, 'width'); + height = pixels(height, 'height'); const scale = Math.max(width / this.width, height / this.height); const resizedWidth = Math.max(width, Math.round(this.width * scale)), resizedHeight = Math.max(height, Math.round(this.height * scale)); // only the part the crop keeps is resampled (the same pixels as resizing the whole image, then cropping) - if (options.mode !== ResizeModes.NEAREST_NEIGHBOR && width >= 1 && height >= 1) { + if (resizeOpts.mode !== 'nearest-neighbor' && width >= 1 && height >= 1) { const region = { x: ~~((resizedWidth - width) / 2), y: ~~((resizedHeight - height) / 2), width, height }; - this.__rescaled__?.(resizedWidth, resizedHeight); const fx = resizedWidth / this.width, fy = resizedHeight / this.height; + // (resampled first: this can fail to allocate, and the gain map has to stay as it was then) + const resized = this.__resize__(resizedWidth, resizedHeight, resizeOpts.mode, region); this.__gain_map__?.__transform__(this.width, this.height, width, height, (X, Y) => [(X + region.x) / fx, (Y + region.y) / fy], Math.min(fx, fy)); - return this.__apply__(this.__resize__(resizedWidth, resizedHeight, options.mode, options.fast, region)); + this.__moved__?.(fx, fy, region.x, region.y); + return this.__apply__(resized); } - this.resize(resizedWidth, resizedHeight, options); + this.resize(resizedWidth, resizedHeight, resizeOpts); return this.crop((this.width - width) / 2, (this.height - height) / 2, width, height); } @@ -1305,25 +1289,33 @@ export class Image { * @internal * @ignore */ - protected __resize__(width: number, height: number, mode: ResizeMode = ResizeModes.BILINEAR, fast = true, region?: Region): Image { - if (width === ResizeModes.AUTO && height === ResizeModes.AUTO) throw new Error('RESIZE_AUTO can only be used for either width or height, not for both'); - else if (width === ResizeModes.AUTO) width = Math.max(1, Math.round(this.width / this.height * Math.floor(height))); - else if (height === ResizeModes.AUTO) height = Math.max(1, Math.round(this.height / this.width * Math.floor(width))); + protected __resized_size__(width: number | undefined, height: number | undefined, fit: 'fill' | 'inside' = 'fill'): [width: number, height: number] { + // (the box is checked like a size: a side below 1 pixel throws, like with the other fits) + if (fit === 'inside' && width !== undefined && height !== undefined) return insideSize(this.width, this.height, pixels(width, 'width'), pixels(height, 'height')); + // a side left out follows the other one, keeping the aspect ratio + if (width === undefined) return [Math.max(1, Math.round(this.width / this.height * Math.floor(height as number))), height as number]; + if (height === undefined) return [width, Math.max(1, Math.round(this.height / this.width * Math.floor(width)))]; + return [width, height]; + } - width = Math.floor(width); - height = Math.floor(height); - if (width < 1) - throw new RangeError('Image has to be at least 1 pixel wide'); - if (height < 1) - throw new RangeError('Image has to be at least 1 pixel high'); + /** @private */ + /** + * @internal + * @ignore + */ + protected __resize__(width: number, height: number, mode: ResizeMode = 'bilinear', region?: Region): Image { + width = pixels(width, 'width'); + height = pixels(height, 'height'); - if (mode === ResizeModes.NEAREST_NEIGHBOR) return this.__resize_nearest_neighbor__(width, height); + oneOf(mode, RESIZE_MODES, 'resize mode'); + if (mode === 'nearest-neighbor') return this.__resize_nearest_neighbor__(width, height); - const filter = mode === ResizeModes.BILINEAR ? TRIANGLE : mode === ResizeModes.BICUBIC ? CUBIC : mode === ResizeModes.AREA ? BOX : null; - if (!filter) throw new Error('Invalid resize mode'); + const filter = mode === 'bilinear' ? TRIANGLE : mode === 'bicubic' ? CUBIC : BOX; const image = new Image(region?.width ?? width, region?.height ?? height); - resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, fast, region); + // (8-bit rounding between the passes and for transparent images, like browsers: what shows differs from the precise + // result by a step or two at most, see tests/resize.js) + resample(this.bitmap, this.width, this.height, width, height, filter, image.bitmap, true, region); return image; } @@ -1356,12 +1348,13 @@ export class Image { * The region is clipped to the image, so the result can be smaller than the requested size * @param x The x offset (0-based) * @param y The y offset (0-based) - * @param width The new images width - * @param height The new images height + * @param width The new width + * @param height The new height */ crop(x: number, y: number, width: number, height: number): this { const bounds = this.__crop_bounds__(x, y, width, height); this.__crop_gain_map__(this, ...bounds); + this.__moved__?.(1, 1, bounds[0], bounds[1]); return this.__apply__(this.__crop__(...bounds)); } @@ -1379,7 +1372,7 @@ export class Image { } /** - * Copies a region of the image into a new image, this one stays unchanged (like {@link Image.crop} on a clone, + * Copies a region of the image into a new image and leaves the image unchanged (like {@link Image.crop} on a clone, * without copying the whole image). The region is clipped to the image, so the result can be smaller than the * requested size * @param x The x offset (0-based) @@ -1387,7 +1380,7 @@ export class Image { * @param width The region's width * @param height The region's height */ - region(x: number, y: number, width: number, height: number): Image { + extract(x: number, y: number, width: number, height: number): Image { const bounds = this.__crop_bounds__(x, y, width, height); const image = this.__crop__(...bounds); this.__crop_gain_map__(image, ...bounds); @@ -1400,41 +1393,22 @@ export class Image { * @ignore */ protected __crop_bounds__(x: number, y: number, width: number, height: number): [number, number, number, number] { - x = ~~finite(x, 'x'); - y = ~~finite(y, 'y'); - width = ~~finite(width, 'width'); - height = ~~finite(height, 'height'); - - const left = Math.max(0, x), top = Math.max(0, y); - const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height); - if (right <= left || bottom <= top) - throw new RangeError('Crop region does not overlap the image'); - - return [left, top, right - left, bottom - top]; + return cropBounds(this.width, this.height, x, y, width, height, 'image'); } /** * Removes borders of one color, e.g. the empty space around rendered text or around a logo on a solid background. - * Frames keep their position: their offsets move by the trimmed amount. An image that only has the color stays - * unchanged + * An image that only has the color stays unchanged ({@link Frame.trim} also moves the frame's offsets) * @param options See {@link TrimOptions} */ trim(options?: TrimOptions): this; - /** - * Removes borders of one color, e.g. the empty space around rendered text or around a logo on a solid background. - * Frames keep their position: their offsets move by the trimmed amount. An image that only has the color stays - * unchanged - * @param color The border color, by default the color of the top left pixel. Fully transparent pixels count as the - * same color whatever their RGB values - * @param options See {@link TrimOptions} - * @deprecated Pass {@link TrimOptions} instead, the positional arguments will be removed in 4.0 - */ - trim(color?: Color, options?: TrimOptions): this; - trim(colorOrOptions?: Color | TrimOptions, optionsArgument: TrimOptions = {}): this { - const { color, ...options } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color }; - const bounds = this.__trim_bounds__(color, options); + trim(options: TrimOptions = {}): this { + checkOptions(options, 'trim({ tolerance: 0.1 })'); + const { color, ...rest } = options; + const bounds = this.__trim_bounds__(color, rest); if (!bounds) return this; this.__crop_gain_map__(this, ...bounds); + this.__moved__?.(1, 1, bounds[0], bounds[1]); return this.__apply__(this.__crop__(...bounds)); } @@ -1443,8 +1417,8 @@ export class Image { * @internal * @ignore */ - protected __trim_bounds__(color: Color | undefined, { tolerance = 0 }: TrimOptions): [number, number, number, number] | null { - if (!(tolerance >= 0 && tolerance <= 1)) throw new RangeError('Invalid tolerance, it has to be between 0 and 1'); + __trim_bounds__(color: Color | undefined, { tolerance = 0 }: TrimOptions): [number, number, number, number] | null { + unitInterval(tolerance, 'tolerance'); const bitmap = this.bitmap; const { width, height } = this; @@ -1495,133 +1469,17 @@ export class Image { return image; } - /** - * Draws a box at the specified coordinates (0-based), clipped to the image - * @param x The x offset - * @param y The y offset - * @param width The box width - * @param height The box height - * @param color The color to fill the box in with, a function gets coordinates relative to the box - */ - drawBox(x: number, y: number, width: number, height: number, color: Color | ColorFunction): this { - x = ~~finite(x, 'x'); - y = ~~finite(y, 'y'); - width = ~~finite(width, 'width'); - height = ~~finite(height, 'height'); - - if (typeof color !== 'function') this.__fast_box__(x, y, width, height, checkColor(color)); - else for (let tY = Math.max(0, -y); tY < height && tY + y < this.height; tY++) - for (let tX = Math.max(0, -x); tX < width && tX + x < this.width; tX++) - this.__set_pixel__(tX + x, tY + y, color(tX, tY)); - - // (the box's pixels have no HDR light beyond their own) - if (this.__gain_map__) gain.redraw(this, this.__gain_map__, Math.max(0, x), Math.max(0, y), Math.min(this.width, x + width), Math.min(this.height, y + height), (_x, _y, S, _boost, out) => { - out[0] = S[0]; - out[1] = S[1]; - out[2] = S[2]; - }); - return this; - } - - /** - * @internal - * @ignore - */ - protected __fast_box__(x: number, y: number, width: number, height: number, color: Color): this { - const left = Math.max(0, x), top = Math.max(0, y); - const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height); - if (right <= left || bottom <= top) return this; - - // fill the first row, then copy it to the others - for (let xPos = left; xPos < right; xPos++) - this.__view__.setUint32(4 * (xPos + top * this.width), color); - - const start = 4 * (left + top * this.width); - const end = 4 * (right + top * this.width); - for (let row = top + 1; row < bottom; row++) - this.bitmap.copyWithin(4 * (left + row * this.width), start, end); - - return this; - } - - /** - * Draws an antialiased circle around the center of the specified pixel (0-based) - * @param x The center x position - * @param y The center y position - * @param radius The circles radius in pixels - * @param color The color, a function gets coordinates relative to the circle's bounding box - */ - drawCircle(x: number, y: number, radius: number, color: Color | ColorFunction): this { - x = ~~finite(x, 'x'); - y = ~~finite(y, 'y'); - radius = finite(radius, 'radius'); - if (typeof color !== 'function') color = checkColor(color); - // the circle is centered on the pixel's center, its edge is antialiased - const cx = x + 0.5, cy = y + 0.5; - - for (let py = Math.max(0, Math.floor(cy - radius)); py < Math.min(this.height, Math.ceil(cy + radius)); py++) { - for (let px = Math.max(0, Math.floor(cx - radius)); px < Math.min(this.width, Math.ceil(cx + radius)); px++) { - const coverage = circleCoverage(px, py, cx, cy, radius); - if (coverage <= 0) continue; - - const value = typeof color === 'function' ? color(px - x + radius, py - y + radius) : color; - if (coverage >= 1) this.__set_pixel__(px, py, value); - else this.__blend_pixel__(px, py, value, coverage); - } - } - - // (the circle's pixels have no HDR light beyond their own; at the antialiased edge in part, by the coverage) - const map = this.__gain_map__; - if (map) { - const oS = map.offsetSDR, oH = map.offsetHDR; - gain.redraw(this, map, Math.max(0, Math.floor(cx - radius)), Math.max(0, Math.floor(cy - radius)), Math.min(this.width, Math.ceil(cx + radius)), Math.min(this.height, Math.ceil(cy + radius)), (px, py, S, boost, out) => { - const coverage = Math.min(1, Math.max(0, circleCoverage(px, py, cx, cy, radius))); - for (let c = 0; c < 3; c++) out[c] = coverage * S[c] + (1 - coverage) * ((S[c] + oS[c]) * boost[c] - oH[c]); - }); - } - return this; - } - - /** - * Moves a pixel towards a color by the given amount (with premultiplied alpha) - * @internal - * @ignore - */ - protected __blend_pixel__(x: number, y: number, color: Color, amount: number): void { - const i = (y * this.width + x) * 4, b = this.bitmap; - const sa = (color & 0xff) / 255 * amount, da = b[i + 3] / 255 * (1 - amount); - const a = sa + da; - if (a <= 0) { - b[i] = b[i + 1] = b[i + 2] = b[i + 3] = 0; - return; - } - - b[i] = ((color >>> 24) * sa + b[i] * da) / a; - b[i + 1] = ((color >> 16 & 0xff) * sa + b[i + 1] * da) / a; - b[i + 2] = ((color >> 8 & 0xff) * sa + b[i + 2] * da) / a; - b[i + 3] = a * 255; - } - /** * Crops the image into a circle with an antialiased edge * @param options See {@link CropCircleOptions} - */ - cropCircle(options?: CropCircleOptions): this; - /** - * Crops the image into a circle with an antialiased edge - * @param max Whether to use the larger dimension for the size. Default: `false` - * @param feathering Share of the radius (0..1) over which the edge fades out. Default: `0` - * @deprecated Pass {@link CropCircleOptions} instead, `cropCircle({ fit: 'cover' })`. The arguments will be - * removed in 4.0 - */ - cropCircle(max?: boolean, feathering?: number): this; - cropCircle(maxOrOptions: boolean | CropCircleOptions = false, featheringArgument = 0): this { - const { max = false, fit, size: givenSize, feathering = 0 } = typeof maxOrOptions === 'object' && maxOrOptions !== null - ? maxOrOptions : { max: maxOrOptions, feathering: featheringArgument } as CropCircleOptions; - const size = fit ?? givenSize ?? (max ? 'cover' : 'contain'); - finite(feathering, 'feathering'); - if (size !== 'contain' && size !== 'cover') throw new TypeError(`Invalid circle size: ${String(size)}`); - const radius = (size === 'cover' ? Math.max : Math.min)(this.width, this.height) / 2; + * @see {@link Image.roundCorners} for rounded corners + */ + cropCircle(options: CropCircleOptions = {}): this { + checkOptions(options, 'cropCircle({ fit: \'cover\' })'); + const { fit = 'contain', feathering = 0 } = options; + unitInterval(feathering, 'feathering'); + oneOf(fit, CIRCLE_FITS, 'fit'); + const radius = (fit === 'cover' ? Math.max : Math.min)(this.width, this.height) / 2; const cx = this.width / 2, cy = this.height / 2; // width of the soft edge, at least the one pixel of antialiasing const band = Math.min(1, Math.max(0, feathering)) * radius; @@ -1685,24 +1543,12 @@ export class Image { /** * Scales the opacity of the image - * @param opacity The factor to multiply the opacity with (0..1 lowers it, >1 raises it, results are clamped) - * @param options See {@link AdjustOptions} - */ - opacity(opacity: number, options?: AdjustOptions): this; - /** - * Scales the opacity of the image - * @param opacity The factor to multiply the opacity with (0..1 lowers it, >1 raises it, results are clamped) - * @param absolute Whether to set the opacity (true) instead of scaling it (false) - * @deprecated Use {@link Image.opacity} to scale; for a fixed alpha, `absolute` is removed in 4.0 + * @param factor The factor to multiply the opacity with (0..1 lowers it, >1 raises it, results are clamped) */ - opacity(opacity: number, absolute?: boolean): this; - opacity(opacity: number, absoluteOrOptions: boolean | AdjustOptions = false): this { - const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions; - opacity = finite(opacity, 'opacity value'); - if (opacity < 0) - throw new RangeError('Invalid opacity value'); + opacity(factor: number): this { + factor = nonNegative(factor, 'opacity factor'); - this.__set_channel_value__(opacity, absolute, 3); + this.__set_channel_value__(factor, 3); return this; } @@ -1710,24 +1556,12 @@ export class Image { /** * Scales the red channel * @param factor The factor to multiply the channel with (>= 0, results are clamped) - * @param options See {@link AdjustOptions} - */ - red(factor: number, options?: AdjustOptions): this; - /** - * Scales the red channel - * @param factor The factor to multiply the channel with (>= 0, results are clamped) - * @param absolute Whether to set every pixel's red channel to `factor` * 255 (true) instead of scaling it (false) - * @deprecated Use {@link Image.recolor} to set a fixed color; `absolute` is removed in 4.0 */ - red(factor: number, absolute?: boolean): this; - red(factor: number, absoluteOrOptions: boolean | AdjustOptions = false): this { - if (this.__gain_map__) return this.__recolor__(image => image.red(factor, absoluteOrOptions as boolean)); - const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions; - factor = finite(factor, 'red factor'); - if (factor < 0) - throw new RangeError('Invalid red factor'); + red(factor: number): this { + if (this.__gain_map__) return this.__recolor__(image => image.red(factor)); + factor = nonNegative(factor, 'red factor'); - this.__set_channel_value__(factor, absolute, 0); + this.__set_channel_value__(factor, 0); return this; } @@ -1735,24 +1569,12 @@ export class Image { /** * Scales the green channel * @param factor The factor to multiply the channel with (>= 0, results are clamped) - * @param options See {@link AdjustOptions} */ - green(factor: number, options?: AdjustOptions): this; - /** - * Scales the green channel - * @param factor The factor to multiply the channel with (>= 0, results are clamped) - * @param absolute Whether to set every pixel's green channel to `factor` * 255 (true) instead of scaling it (false) - * @deprecated Use {@link Image.recolor} to set a fixed color; `absolute` is removed in 4.0 - */ - green(factor: number, absolute?: boolean): this; - green(factor: number, absoluteOrOptions: boolean | AdjustOptions = false): this { - if (this.__gain_map__) return this.__recolor__(image => image.green(factor, absoluteOrOptions as boolean)); - const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions; - factor = finite(factor, 'green factor'); - if (factor < 0) - throw new RangeError('Invalid green factor'); + green(factor: number): this { + if (this.__gain_map__) return this.__recolor__(image => image.green(factor)); + factor = nonNegative(factor, 'green factor'); - this.__set_channel_value__(factor, absolute, 1); + this.__set_channel_value__(factor, 1); return this; } @@ -1760,24 +1582,12 @@ export class Image { /** * Scales the blue channel * @param factor The factor to multiply the channel with (>= 0, results are clamped) - * @param options See {@link AdjustOptions} - */ - blue(factor: number, options?: AdjustOptions): this; - /** - * Scales the blue channel - * @param factor The factor to multiply the channel with (>= 0, results are clamped) - * @param absolute Whether to set every pixel's blue channel to `factor` * 255 (true) instead of scaling it (false) - * @deprecated Use {@link Image.recolor} to set a fixed color; `absolute` is removed in 4.0 */ - blue(factor: number, absolute?: boolean): this; - blue(factor: number, absoluteOrOptions: boolean | AdjustOptions = false): this { - if (this.__gain_map__) return this.__recolor__(image => image.blue(factor, absoluteOrOptions as boolean)); - const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions; - factor = finite(factor, 'blue factor'); - if (factor < 0) - throw new RangeError('Invalid blue factor'); + blue(factor: number): this { + if (this.__gain_map__) return this.__recolor__(image => image.blue(factor)); + factor = nonNegative(factor, 'blue factor'); - this.__set_channel_value__(factor, absolute, 2); + this.__set_channel_value__(factor, 2); return this; } @@ -1786,84 +1596,51 @@ export class Image { * @internal * @ignore */ - protected __set_channel_value__(value: number, absolute: boolean, offset: number): void { + protected __set_channel_value__(value: number, offset: number): void { for (let i = offset; i < this.bitmap.length; i += 4) - this.bitmap[i] = value * (absolute ? 255 : this.bitmap[i]); + this.bitmap[i] = value * this.bitmap[i]; } /** * Scales the lightness of the image (HSL), keeping its hue and saturation - * @param value The factor to multiply the lightness with (>= 0, results are clamped) - * @param options See {@link AdjustOptions} + * @param factor The factor to multiply the lightness with (>= 0, results are clamped) */ - lightness(value: number, options?: AdjustOptions): this; - /** - * Scales the lightness of the image (HSL), keeping its hue and saturation - * @param value The factor to multiply the lightness with (>= 0, results are clamped) - * @param absolute Whether to set the lightness (true) instead of scaling it (false) - * @deprecated `absolute` is removed in 4.0: scale with a factor, or use {@link Image.recolor} for a fixed color - */ - lightness(value: number, absolute?: boolean): this; - lightness(value: number, absoluteOrOptions: boolean | AdjustOptions = false): this { - if (this.__gain_map__) return this.__recolor__(image => image.lightness(value, absoluteOrOptions as boolean)); - const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions; - value = finite(value, 'lightness value'); - if (value < 0) - throw new RangeError('Invalid lightness value'); + lightness(factor: number): this { + if (this.__gain_map__) return this.__recolor__(image => image.lightness(factor)); + factor = nonNegative(factor, 'lightness factor'); - return this.__map_hsla__(c => { c.l = value * (absolute ? 1 : c.l); }); + return this.__map_hsla__(c => { c.l = factor * c.l; }); } /** - * Scales the saturation of the image (HSL), keeping its hue and lightness. 0 makes it greyscale - * @param value The factor to multiply the saturation with (>= 0, results are clamped) - * @param options See {@link AdjustOptions} - */ - saturation(value: number, options?: AdjustOptions): this; - /** - * Scales the saturation of the image (HSL), keeping its hue and lightness. 0 makes it greyscale - * @param value The factor to multiply the saturation with (>= 0, results are clamped) - * @param absolute Whether to set the saturation (true) instead of scaling it (false) - * @deprecated `absolute` is removed in 4.0: scale with a factor, or use {@link Image.recolor} for a fixed color + * Scales the saturation of the image (HSL), keeping its hue and lightness. 0 makes it grayscale + * @param factor The factor to multiply the saturation with (>= 0, results are clamped) */ - saturation(value: number, absolute?: boolean): this; - saturation(value: number, absoluteOrOptions: boolean | AdjustOptions = false): this { - if (this.__gain_map__) return this.__recolor__(image => image.saturation(value, absoluteOrOptions as boolean), true); - const absolute = isOptions(absoluteOrOptions) ? absoluteOrOptions.absolute ?? false : absoluteOrOptions; - value = finite(value, 'saturation value'); - if (value < 0) - throw new RangeError('Invalid saturation value'); + saturation(factor: number): this { + if (this.__gain_map__) return this.__recolor__(image => image.saturation(factor), true); + factor = nonNegative(factor, 'saturation factor'); - return this.__map_hsla__(c => { c.s = value * (absolute ? 1 : c.s); }); + return this.__map_hsla__(c => { c.s = factor * c.s; }); } /** * Composites (overlays) the source onto this image + * @example + * ```ts + * image.composite(overlay, { x: 10, y: 10, opacity: 0.5, mode: 'multiply' }); + * ``` * @param source The image to place * @param options Position, opacity and blend mode, see {@link CompositeOptions} + * @throws `TypeError` if the source isn't an {@link Image} */ composite(source: Image, options?: CompositeOptions): this; - /** - * Composites (overlays) the source onto this image at the specified coordinates - * @param source The image to place - * @param [x=0] The x position to place the image at - * @param [y=0] The y position to place the image at - * @param options Opacity and blend mode, see {@link CompositeOptions} - * @deprecated Pass {@link CompositeOptions} instead, the positional arguments will be removed in 4.0 - */ - composite(source: Image, x?: number, y?: number, options?: CompositeOptions): this; - composite(source: Image, xOrOptions: number | CompositeOptions = 0, yArgument = 0, optionsArgument: CompositeOptions = {}): this { - const options = isOptions(xOrOptions) ? xOrOptions : optionsArgument; - const { opacity = 1, mode = 'normal' } = options; - let x = isOptions(xOrOptions) ? xOrOptions.x ?? 0 : xOrOptions, y = isOptions(xOrOptions) ? xOrOptions.y ?? 0 : yArgument; - x = finite(x, 'x') | 0; - y = finite(y, 'y') | 0; - - if (isNaN(opacity) || opacity < 0 || opacity > 1) - throw new RangeError('Invalid composite opacity'); - const blend = BLEND_MODES[mode]; - if (!blend || !Object.prototype.hasOwnProperty.call(BLEND_MODES, mode)) - throw new RangeError(`Invalid blend mode: ${mode}`); + composite(source: Image, options: CompositeOptions = {}): this { + checkOptions(options, 'composite(source, { x: 10, y: 20 })'); + if (!(source instanceof Image)) throw new TypeError('composite() takes an Image as its source, like image.composite(logo, { x: 10, y: 20 })'); + const { opacity = 1, mode = 'normal', x: givenX = 0, y: givenY = 0 } = options; + const x = Math.trunc(finite(givenX, 'x')), y = Math.trunc(finite(givenY, 'y')); + unitInterval(opacity, 'opacity'); + const blend = BLEND_MODES[oneOf(mode, Object.keys(BLEND_MODES) as BlendMode[], 'blend mode')]; if (opacity === 0) return this; if (this.__gain_map__ || source.__gain_map__) return this.__composite_gain__(source, x, y, opacity, mode); if (mode !== 'normal') return this.__blend__(source, x, y, opacity, blend); @@ -1871,7 +1648,9 @@ export class Image { // (the loop stays inline here: as a method of its own it ran about 20% slower) const left = Math.max(0, x), top = Math.max(0, y); const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height); - const dst = this.bitmap, src = source.bitmap; + const dst = this.bitmap; + // (a source sharing the destination's memory, itself or through the bitmap setter, is read before it is written) + const src = source.bitmap.buffer === dst.buffer ? source.bitmap.slice() : source.bitmap; for (let row = top; row < bottom; row++) { for (let column = left, s = 4 * ((row - y) * source.width + left - x), d = 4 * (row * this.width + left); column < right; column++, s += 4, d += 4) { @@ -1916,7 +1695,7 @@ export class Image { const ownMap = this.__gain_map__, sourceMap = source.__gain_map__; this.__gain_map__ = source.__gain_map__ = null; try { - this.composite(source, x, y, { opacity, mode }); + this.composite(source, { x, y, opacity, mode }); } finally { this.__gain_map__ = ownMap; source.__gain_map__ = sourceMap; @@ -1970,7 +1749,7 @@ export class Image { } out[c] = share * Hs + (1 - share) * Hd; } - }, map.channels === 1 && (!sourceMap || sourceMap.channels === 1), Math.max(0, ...(sourceMap?.gainMapMax ?? [0]))); + }, map.channels === 1 && (!sourceMap || sourceMap.channels === 1), Math.max(0, ...(sourceMap?.__max__ ?? [0]))); return this; } @@ -1982,7 +1761,9 @@ export class Image { protected __blend__(source: Image, x: number, y: number, opacity: number, blend: (backdrop: number, source: number) => number): this { const left = Math.max(0, x), top = Math.max(0, y); const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height); - const dst = this.bitmap, src = source.bitmap; + const dst = this.bitmap; + // (a source sharing the destination's memory, itself or through the bitmap setter, is read before it is written) + const src = source.bitmap.buffer === dst.buffer ? source.bitmap.slice() : source.bitmap; for (let row = top; row < bottom; row++) { for (let column = left; column < right; column++) { @@ -2009,7 +1790,7 @@ export class Image { } /** - * Inverts the images colors + * Inverts the image's colors */ invert(): this { if (this.__gain_map__) return this.__unboost__(image => image.invert()); @@ -2024,7 +1805,7 @@ export class Image { } /** - * Inverts the images lightness (HSL), keeping hue and saturation: dark colors become light and vice versa + * Inverts the image's lightness (HSL), keeping hue and saturation: dark colors become light and vice versa */ invertLightness(): this { if (this.__gain_map__) return this.__unboost__(image => image.invertLightness()); @@ -2032,7 +1813,7 @@ export class Image { } /** - * Inverts the images value (HSV), keeping hue and saturation: the brightest channel `v` becomes `255 - v` + * Inverts the image's value (HSV), keeping hue and saturation: the brightest channel `v` becomes `255 - v` * and the others scale along, black becomes white */ invertValue(): this { @@ -2056,7 +1837,7 @@ export class Image { } /** - * Shifts the images hue + * Shifts the image's hue * @param degrees How many degrees to shift the hue by */ hueShift(degrees: number): this { @@ -2074,17 +1855,17 @@ export class Image { protected __map_hsla__(map: (hsla: HSLA) => void): this { const bitmap = this.bitmap; const hsla: HSLA = { h: 0, s: 0, l: 0, a: 0 }; - const pixels = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >> 2); + const pixels = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >>> 2); // results of recently seen colors (direct mapped by a hash of the color), images often repeat colors const keys = new Uint32Array(4096), values = new Uint32Array(4096); keys[0] = 1; // so the empty slot 0 can't match the color 0 for (let i = 0; i < bitmap.length; i += 4) { - const color = pixels[i >> 2]; + const color = pixels[i >>> 2]; const slot = Math.imul(color, 0x9e3779b1) >>> 20; if (keys[slot] === color) { - pixels[i >> 2] = values[slot]; + pixels[i >>> 2] = values[slot]; continue; } @@ -2108,7 +1889,7 @@ export class Image { hsla.a = bitmap[i + 3] / 255; map(hsla); - // see hslaToColor + // see Colors.fromHSLA const nh = wrapHue(hsla.h); const ns = Math.min(1, Math.max(0, hsla.s)); const nl = Math.min(1, Math.max(0, hsla.l)); @@ -2125,7 +1906,7 @@ export class Image { bitmap[i + 3] = Math.round(na * 255); keys[slot] = color; - values[slot] = pixels[i >> 2]; + values[slot] = pixels[i >>> 2]; } return this; @@ -2136,8 +1917,7 @@ export class Image { * @param radius The blur radius: the gaussian's standard deviation in pixels, like CSS' blur() */ blur(radius: number): this { - if (!Number.isFinite(radius) || radius < 0) - throw new RangeError('Invalid blur radius'); + nonNegative(radius, 'blur radius'); // (the gain map blurred alike, at its resolution) const map = this.__gain_map__; if (map && radius * map.width / this.width >= 0.5) map.image = map.image.clone().blur(radius * map.width / this.width); @@ -2150,40 +1930,42 @@ export class Image { } /** - * Reduces the image to a palette of at most 256 colors (or a fixed one), in place, optionally dithered, e.g. - * `image.quantize({ colors: 16, dither: 'floyd-steinberg' })` or `image.quantize({ palette: [0x0f380fff, 0x306230ff, - * 0x8bac0fff, 0x9bbc0fff] })` for a Game Boy look. Transparent pixels (alpha 0) keep their color and don't count - * towards the palette; the other pixels keep their alpha and only their RGB is reduced. The result is deterministic. - * With a gain map (an HDR image), the HDR highlights are dropped, like {@link Image.invert} does: the map is neutral - * afterwards. Frames quantize their own pixels + * Reduces the image to a palette of at most 256 colors (or a fixed one), in place, optionally dithered + * @remarks + * Transparent pixels (alpha 0) keep their color and don't count towards the palette; the other pixels keep their alpha + * and only their RGB is reduced. The result is deterministic. With a gain map (an HDR image), the HDR highlights are + * dropped, like {@link Image.invert} does: the map is neutral afterwards + * @example + * ```ts + * image.quantize({ colors: 16, dither: 'floyd-steinberg' }); + * image.quantize({ palette: [0x0f380fff, 0x306230ff, 0x8bac0fff, 0x9bbc0fff] }); // a Game Boy look + * ``` * @param options See {@link QuantizeOptions} */ quantize(options: QuantizeOptions = {}): this { - if (typeof options !== 'object' || options === null) throw new TypeError('quantize takes an options object'); - const { colors, palette, dither = 'none', ditherStrength = 1 } = options; + checkOptions(options, 'image.quantize({ colors: 16 })'); + // (JavaScript callers can give both: checked below) + const { colors, palette, dither = 'floyd-steinberg', ditherStrength = 0.85 } = options as DitherOptions & { colors?: number, palette?: Color[] }; // everything is checked before the image changes if (colors !== undefined && palette !== undefined) throw new TypeError('quantize takes colors or palette, not both'); let fixed: Uint8Array | null = null, count = 256; if (palette !== undefined) { - if (!Array.isArray(palette)) throw new TypeError('palette has to be an array of colors'); - if (palette.length < 1 || palette.length > 256) throw new RangeError(`palette needs 1 to 256 colors, not ${palette.length}`); + // eslint-disable-next-line no-restricted-syntax -- the one palette option + if (!Array.isArray(palette)) throw new TypeError(`palette must be an array of colors, not ${shown(palette)}`); + if (palette.length < 1 || palette.length > 256) throw new RangeError(`palette must have 1-256 colors, not ${palette.length}`); const packed = new Uint8Array(palette.length * 3); palette.forEach((color, i) => { const value = checkColor(color, 'palette color'); - if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) throw new RangeError(`Invalid palette color: ${color}`); packed[i * 3] = value >>> 24; packed[i * 3 + 1] = value >>> 16 & 255; packed[i * 3 + 2] = value >>> 8 & 255; }); fixed = packed; - } else if (colors !== undefined) { - count = finite(colors, 'colors'); - if (!Number.isInteger(count) || count < 2 || count > 256) throw new RangeError(`colors must be an integer from 2 to 256, not ${colors}`); } - if (!(DITHER_METHODS as readonly unknown[]).includes(dither)) throw new TypeError(`dither must be one of ${DITHER_METHODS.map(name => `'${name}'`).join(', ')}, not ${String(dither)}`); - const strength = finite(ditherStrength, 'ditherStrength'); - if (strength < 0 || strength > 1) throw new RangeError(`ditherStrength must be 0-1, not ${ditherStrength}`); + const checked = quantize.paletteOptions(palette === undefined ? colors : undefined, dither, ditherStrength); + if (checked.colors !== undefined) count = checked.colors; + const strength = checked.strength; const reduce = (image: Image): void => { const bytes = image.__bytes__(); @@ -2197,23 +1979,27 @@ export class Image { /** * Mixes the colors of every pixel with a color matrix, like SVG's `feColorMatrix`: the new red, green, blue and alpha - * are each a sum of the old red, green, blue and alpha times a factor, plus an offset. Greyscale, sepia, tints, - * swapped channels, color blindness simulation or a mix of those in one pass. - * + * are each a sum of the old red, green, blue and alpha times a factor, plus an offset. Grayscale, sepia, tints, + * swapped channels, color blindness simulation or a mix of those in one pass + * @remarks * The values are 20 numbers, four rows of `[red, green, blue, alpha, offset]` for the new red, green, blue and alpha, * with the colors and the offsets as 0 to 1 (like CSS and SVG): `[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, * 0, 0, 0, 1, 0]` changes nothing, `[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]` swaps red and * blue. Nine numbers are the first three rows without the alpha and the offsets (the alpha stays as it is). The * colors are the sRGB values, not premultiplied, and the results are clamped. With a gain map (an HDR image), the * HDR highlights follow the change as they do for other color changes + * @example + * ```ts + * image.colorMatrix([0.393, 0.769, 0.189, 0.349, 0.686, 0.168, 0.272, 0.534, 0.131]); // sepia + * ``` * @param matrix The 9 or 20 values */ colorMatrix(matrix: ArrayLike): this { - if (matrix === null || typeof matrix !== 'object' || (matrix.length !== 9 && matrix.length !== 20)) - throw new RangeError('A color matrix has 9 or 20 values'); + if (matrix === null || typeof matrix !== 'object') throw new TypeError(`colorMatrix() takes an array of 9 or 20 values, not ${shown(matrix)}`); + if (matrix.length !== 9 && matrix.length !== 20) throw new RangeError(`a color matrix must have 9 or 20 values, not ${matrix.length}`); const m = new Float64Array(20); // (numbers only: a string is a mistake in data like this) - const value = (v: unknown): number => finite(typeof v === 'number' ? v : NaN, 'color matrix value'); + const value = (v: unknown): number => finite(v as number, 'color matrix value'); if (matrix.length === 20) for (let i = 0; i < 20; i++) m[i] = value(matrix[i]); else for (let row = 0; row < 3; row++) for (let column = 0; column < 3; column++) m[row * 5 + column] = value(matrix[row * 3 + column]); // (nine values leave the alpha as it is) @@ -2234,8 +2020,13 @@ export class Image { /** * Moves every point of the image with an affine transform, in one resampling: rotation, scaling, skew, flips and - * shifts in any mix and around any point. The six numbers are SVG's `matrix(a b c d e f)`: a point (x, y) of the - * image ends up at (a x + c y + e, b x + d y + f), with y pointing down. + * shifts in any mix and around any point + * @remarks + * The six numbers are SVG's `matrix(a b c d e f)`: a point (x, y) of the image ends up at (a x + c y + e, + * b x + d y + f), with y pointing down. The image grows to hold the result (`expand: false` keeps its size), so a shift + * only shows with `expand: false`. The edges fade, like the pixels outside were transparent. A transform that flattens + * the image (a factor of 0) is refused. With a gain map (an HDR image), the map moves with the image + * @example * ```ts * image.transform([1, 0, Math.tan(-0.3), 1, 0, 0]); // slanted like italics, around the middle * image.transform([0.5, 0, 0, 0.5, 0, 0], { origin: { x: 0, y: 0 } }); // half the size @@ -2243,19 +2034,20 @@ export class Image { * const a = Math.PI / 6; * image.transform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); // turned 30° clockwise * ``` - * The image grows to hold the result (`expand: false` keeps its size), so a shift only shows with `expand: false`. - * The edges fade, like the pixels outside were transparent. A transform that flattens the image (a factor of 0) is - * refused. With a gain map (an HDR image), the map moves with the image * @param matrix The six values [a, b, c, d, e, f] * @param options See {@link TransformOptions} + * @see {@link Image.rotate} for turning by an angle */ - transform(matrix: ArrayLike, options: TransformOptions = {}): this { - if (matrix === null || typeof matrix !== 'object' || matrix.length !== 6) throw new RangeError('A transform has 6 values: [a, b, c, d, e, f]'); + transform(matrix: AffineTransform, options: TransformOptions = {}): this { + checkOptions(options, 'image.transform([1, 0, 0, 1, 0, 0], { expand: false })'); + if (matrix === null || typeof matrix !== 'object') throw new TypeError(`transform() takes an array of 6 values, like transform([1, 0, 0, 1, 0, 0]), not ${shown(matrix)}`); + if (matrix.length !== 6) throw new RangeError(`a transform must have 6 values, [a, b, c, d, e, f], not ${(matrix as ArrayLike).length}`); // (numbers only: a string is a mistake in data like this) - const values = Array.from({ length: 6 }, (_, i) => finite(typeof matrix[i] === 'number' ? matrix[i] : NaN, 'transform value')); - if (typeof options !== 'object' || options === null) throw new TypeError('transform takes an options object'); + const values = Array.from({ length: 6 }, (_, i) => finite(matrix[i], 'transform value')); const { origin = {}, expand = true, mode = 'bilinear' } = options; - if (!TRANSFORM_MODES.includes(mode)) throw new TypeError(`transform mode must be one of ${TRANSFORM_MODES.map(name => `'${name}'`).join(', ')}, not ${String(mode)}`); + if (typeof origin !== 'object' || origin === null) throw new TypeError(`transform() takes an origin object like { x: 10, y: 20 }, not ${shown(origin)}`); + oneOf(mode, TRANSFORM_MODES, 'transform mode'); + boolean(expand, 'expand'); const { x: pivotX = this.width / 2, y: pivotY = this.height / 2 } = origin; finite(pivotX, 'origin x'); finite(pivotY, 'origin y'); @@ -2281,17 +2073,7 @@ export class Image { outHeight = Math.max(1, Math.round(maxY - minY)); left = minX - (outWidth - (maxX - minX)) / 2; top = minY - (outHeight - (maxY - minY)) / 2; - // frames only grow as far up and left as their offset allows - const room = this.__room__(); - if (left < -room.left) { - left = -room.left; - outWidth = Math.max(1, Math.round(maxX - left)); - } - if (top < -room.top) { - top = -room.top; - outHeight = Math.max(1, Math.round(maxY - top)); - } - if (outWidth * outHeight > MAX_PIXELS) throw new RangeError(`The transformed image would have ${outWidth}x${outHeight} pixels, more than the ${MAX_PIXELS} allowed`); + checkGrowth(outWidth, outHeight, 'The transform'); } const out = new Image(outWidth, outHeight); @@ -2301,25 +2083,25 @@ export class Image { const x = X + left, y = Y + top; return [inverse[0] * x + inverse[2] * y + inverse[4], inverse[1] * x + inverse[3] * y + inverse[5]]; }, scale); - this.__apply__(out); - // (a frame's offsets are whole pixels) - if (left || top) this.__grown__(-Math.round(left), -Math.round(top)); - return this; + this.__moved__?.(1, 1, left, top); + return this.__apply__(out); } /** * Adds a shadow behind the image, shaped by its alpha: a drop shadow with an offset, or a glow without one * (`image.dropShadow({ blur: 8, color: 0xff2fb9ff })`, with `spread` to make it stronger). The image grows to fit - * the shadow, unless `expand` is `false`. Frames stay where they are (their offsets move with the growth), they only - * grow up and left as far as their offset allows + * the shadow, unless `expand` is `false` * @param options See {@link ShadowOptions} + * @throws {@link LimitError} if the size or offset of the shadow would make the image larger than an image can be */ dropShadow(options: ShadowOptions = {}): this { + checkOptions(options, 'image.dropShadow({ blur: 8 })'); const { x = 0, y = 0, blur = 0, spread = 0, color = 0x00000080, expand = true } = options; + boolean(expand, 'expand'); finite(x, 'x'); finite(y, 'y'); - if (finite(blur, 'blur') < 0) throw new RangeError('Invalid blur radius'); - if (finite(spread, 'spread') < 0) throw new RangeError('Invalid spread'); + nonNegative(blur, 'blur'); + nonNegative(spread, 'spread'); const [r, g, b, a] = Colors.toRGBA(checkColor(color)); // the shadow's room: the spread and what the blur reaches (3 standard deviations), and a border for the outline @@ -2347,10 +2129,9 @@ export class Image { } } - const room = this.__room__(); return this.__under__(layer, x - margin, y - margin, expand ? { - left: Math.min(room.left, Math.max(0, Math.ceil(reach - x))), - top: Math.min(room.top, Math.max(0, Math.ceil(reach - y))), + left: Math.max(0, Math.ceil(reach - x)), + top: Math.max(0, Math.ceil(reach - y)), right: Math.max(0, Math.ceil(reach + x)), bottom: Math.max(0, Math.ceil(reach + y)) } : { left: 0, top: 0, right: 0, bottom: 0 }); @@ -2358,13 +2139,15 @@ export class Image { /** * Draws an outline around the image's shape (its alpha): the sticker effect for cut-out images, or an outline for - * text. The image grows to fit it, unless `expand` is `false`. Frames stay where they are (their offsets move with - * the growth), they only grow up and left as far as their offset allows + * text. The image grows to fit it, unless `expand` is `false` * @param options See {@link OutlineOptions} + * @throws {@link LimitError} if the width would make the image larger than an image can be */ outline(options: OutlineOptions = {}): this { + checkOptions(options, 'image.outline({ width: 4 })'); const { width = 1, color = 0x000000ff, expand = true } = options; - if (finite(width, 'outline width') < 0) throw new RangeError('Invalid outline width'); + boolean(expand, 'expand'); + nonNegative(width, 'outline width'); const [r, g, b, a] = Colors.toRGBA(checkColor(color)); if (width === 0) return this; @@ -2382,9 +2165,9 @@ export class Image { bitmap[i * 4 + 3] = stroke[i] * (1 - coverage[i] / 255) * a; } - const room = this.__room__(), grow = Math.ceil(width); + const grow = Math.ceil(width); return this.__under__(layer, -margin, -margin, expand - ? { left: Math.min(room.left, grow), top: Math.min(room.top, grow), right: grow, bottom: grow } + ? { left: grow, top: grow, right: grow, bottom: grow } : { left: 0, top: 0, right: 0, bottom: 0 }); } @@ -2394,6 +2177,7 @@ export class Image { * @ignore */ protected __shape_layer__(margin: number): Image { + checkGrowth(this.width + 2 * margin, this.height + 2 * margin, 'The shadow or outline'); const layer = new Image(this.width + 2 * margin, this.height + 2 * margin); for (let y = 0; y < this.height; y++) for (let x = 0; x < this.width; x++) @@ -2410,6 +2194,7 @@ export class Image { protected __under__(layer: Image, layerX: number, layerY: number, grow: { left: number, top: number, right: number, bottom: number }): this { const { left, top, right, bottom } = grow; const width = this.width + left + right, height = this.height + top + bottom; + checkGrowth(width, height, 'The shadow or outline'); const result = new Image(width, height); result.composite(layer, { x: layerX + left, y: layerY + top }); const map = this.__gain_map__; @@ -2420,28 +2205,8 @@ export class Image { this.__gain_map__ = map; } map?.__transform__(this.width, this.height, width, height, (X, Y) => [X - left, Y - top]); - this.__apply__(result); - if (left || top) this.__grown__(left, top); - return this; - } - - /** - * How far the image may grow up and left - * @internal - * @ignore - */ - protected __room__(): { left: number, top: number } { - return { left: Infinity, top: Infinity }; - } - - /** - * Called when the image has grown up and left - * @internal - * @ignore - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - protected __grown__(_left: number, _top: number): void { - // (frames move their offsets) + this.__moved__?.(1, 1, -left, -top); + return this.__apply__(result); } /** @@ -2449,19 +2214,10 @@ export class Image { * @param options See {@link SharpenOptions} */ sharpen(options?: SharpenOptions): this; - /** - * Sharpens the image with an unsharp mask: the difference to a blurred copy is amplified - * @param [amount=1] How strongly to sharpen (0 does nothing) - * @param [radius=1] The radius of the blur the image is compared with (larger values sharpen coarser details) - * @deprecated Pass {@link SharpenOptions} instead, the positional arguments will be removed in 4.0 - */ - sharpen(amount?: number, radius?: number): this; - sharpen(amountOrOptions: number | SharpenOptions = 1, radiusArgument = 1): this { - const { amount = 1, radius = 1 } = isOptions(amountOrOptions) ? amountOrOptions : { amount: amountOrOptions, radius: radiusArgument }; - if (!Number.isFinite(amount) || amount < 0) - throw new RangeError('Invalid sharpen amount'); - if (!Number.isFinite(radius) || radius <= 0) - throw new RangeError('Invalid sharpen radius'); + sharpen(options: SharpenOptions = {}): this { + checkOptions(options, 'sharpen({ amount: 0.5 })'); + const { amount: givenAmount = 1, radius: givenRadius = 1 } = options; + const amount = nonNegative(givenAmount, 'sharpen amount'), radius = positive(givenRadius, 'sharpen radius'); const blurred = premultiply(this.bitmap); gaussianBlur(blurred, this.width, this.height, radius); @@ -2487,21 +2243,17 @@ export class Image { */ brightness(factor: number): this { if (this.__gain_map__) return this.__recolor__(image => image.brightness(factor), false, v => v * factor); - factor = finite(factor, 'brightness factor'); - if (factor < 0) - throw new RangeError('Invalid brightness factor'); + factor = nonNegative(factor, 'brightness factor'); return this.__map_channels__(v => v * factor); } /** - * Scales the color channels' distance from mid grey, e.g. 1.5 increases the contrast, 0.5 reduces it - * @param factor The factor (>= 0, 1 keeps the image, 0 makes it grey) + * Scales the color channels' distance from mid gray, e.g. 1.5 increases the contrast, 0.5 reduces it + * @param factor The factor (>= 0, 1 keeps the image, 0 makes it gray) */ contrast(factor: number): this { if (this.__gain_map__) return this.__recolor__(image => image.contrast(factor), false, v => (v - 0.5) * factor + 0.5); - factor = finite(factor, 'contrast factor'); - if (factor < 0) - throw new RangeError('Invalid contrast factor'); + factor = nonNegative(factor, 'contrast factor'); return this.__map_channels__(v => (v - 127.5) * factor + 127.5); } @@ -2511,17 +2263,15 @@ export class Image { */ gamma(gamma: number): this { if (this.__gain_map__) return this.__recolor__(image => image.gamma(gamma), false, v => Math.max(0, v) ** (1 / gamma)); - gamma = finite(gamma, 'gamma'); - if (gamma <= 0) - throw new RangeError('Invalid gamma'); + gamma = positive(gamma, 'gamma'); return this.__map_channels__(v => 255 * (v / 255) ** (1 / gamma)); } /** - * Converts the image to greyscale by its luma (ITU-R 601, like Pillow), keeping the alpha + * Converts the image to grayscale by its luma (ITU-R 601, like Pillow), keeping the alpha */ - greyscale(): this { - if (this.__gain_map__) return this.__recolor__(image => image.greyscale(), true); + grayscale(): this { + if (this.__gain_map__) return this.__recolor__(image => image.grayscale(), true); const bitmap = this.bitmap; for (let i = 0; i < bitmap.length; i += 4) bitmap[i] = bitmap[i + 1] = bitmap[i + 2] = bitmap[i] * 19595 + bitmap[i + 1] * 38470 + bitmap[i + 2] * 7471 + 0x8000 >> 16; @@ -2552,22 +2302,15 @@ export class Image { * @param options See {@link ColorToAlphaOptions} */ colorToAlpha(options?: ColorToAlphaOptions): this; - /** - * Makes a color transparent, like GIMP's "Color to Alpha": the color is removed from every pixel and replaced by - * transparency, so pixels that are partly the color (e.g. antialiased edges against a background) become - * semi-transparent instead of keeping a fringe of it. - * The color is removed everywhere in the image, not only from a connected background: removing a white - * background also makes white areas inside the subject (e.g. eyes in a logo) transparent - * @param color The color to remove, by default the color of the top left pixel (e.g. a background) - * @param options See {@link ColorToAlphaOptions} - * @deprecated Pass {@link ColorToAlphaOptions} instead, the positional arguments will be removed in 4.0 - */ - colorToAlpha(color?: Color, options?: ColorToAlphaOptions): this; - colorToAlpha(colorOrOptions?: Color | ColorToAlphaOptions, optionsArgument: ColorToAlphaOptions = {}): this { - const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = isOptions(colorOrOptions) ? colorOrOptions : { ...optionsArgument, color: colorOrOptions ?? optionsArgument.color }; + colorToAlpha(options: ColorToAlphaOptions = {}): this { + checkOptions(options, 'colorToAlpha({ color: 0xffffffff })'); + const { color: colorOption, transparencyThreshold = 0, opacityThreshold = 1 } = options; let color = colorOption; + finite(transparencyThreshold, 'transparencyThreshold'); + finite(opacityThreshold, 'opacityThreshold'); if (!(transparencyThreshold >= 0 && opacityThreshold <= 1 && transparencyThreshold < opacityThreshold)) - throw new RangeError('Invalid thresholds, they have to satisfy 0 <= transparencyThreshold < opacityThreshold <= 1'); + // eslint-disable-next-line no-restricted-syntax -- two values that have to fit each other + throw new RangeError(`transparencyThreshold must be 0 or more and below opacityThreshold, which must be 1 or less, not ${transparencyThreshold} and ${opacityThreshold}`); const bitmap = this.bitmap; if (color !== undefined) color = checkColor(color); @@ -2615,6 +2358,7 @@ export class Image { /** * Gets the average color of the image, weighting each pixel by its opacity * @returns The average color (fully opaque), black for fully transparent images + * @see {@link Image.dominantColor} for the color that most of the image has */ averageColor(): Color { let r = 0, g = 0, b = 0, weight = 0; @@ -2631,26 +2375,22 @@ export class Image { } /** - * Gets the image's dominant color: the colors are grouped into a few clusters (median cut and k-means), - * the average color of the largest one is returned + * Gets the image's dominant color: the colors are counted in a histogram of 16 levels per channel, and the average + * of the pixels in the fullest bin is returned (so it is a color the image has, not a mix of two hues) * @param options Which colors to ignore, see {@link DominantColorOptions} * @return The image's dominant color (fully opaque); mostly transparent pixels are ignored. * If every pixel is ignored as black or white, the filter is dropped + * @see {@link Image.averageColor} for the mix of all colors */ dominantColor(options?: DominantColorOptions): Color; - /** - * Gets the image's dominant color, see {@link Image.dominantColor | the variant with options} - * @param ignoreBlack Whether to ignore dark colors (all channels below the threshold). Default: `true` - * @param ignoreWhite Whether to ignore light colors (all channels above 255 minus the threshold). Default: `true` - * @param bwThreshold The black/white threshold (0-64, in steps of 4 channel values). Default: `15` - * @return The image's dominant color (fully opaque) - * @deprecated Pass {@link DominantColorOptions} instead, the positional arguments will be removed in 4.0 - */ - dominantColor(ignoreBlack?: boolean, ignoreWhite?: boolean, bwThreshold?: number): Color; - dominantColor(ignoreBlackOrOptions: boolean | DominantColorOptions = true, ignoreWhiteArgument = true, thresholdArgument = 0xf): Color { - const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 0xf } = typeof ignoreBlackOrOptions === 'object' && ignoreBlackOrOptions !== null - ? ignoreBlackOrOptions : { ignoreBlack: ignoreBlackOrOptions, ignoreWhite: ignoreWhiteArgument, threshold: thresholdArgument }; - const threshold = Math.min(64, Math.max(0, finite(bwThreshold, 'threshold'))) * 4; + dominantColor(options: DominantColorOptions = {}): Color { + checkOptions(options, 'dominantColor({ ignoreBlack: false })'); + const { ignoreBlack = true, ignoreWhite = true, threshold: bwThreshold = 60 } = options; + boolean(ignoreBlack, 'ignoreBlack'); + boolean(ignoreWhite, 'ignoreWhite'); + const threshold = finite(bwThreshold, 'threshold'); + // eslint-disable-next-line no-restricted-syntax -- the one threshold that goes to 256 + if (threshold < 0 || threshold > 256) throw new RangeError(`threshold must be 0-256, not ${threshold}`); const pixels = this.__bytes__(); const color = quantize.dominantColor(pixels, (r, g, b) => @@ -2661,21 +2401,27 @@ export class Image { } /** - * Rotates the image counterclockwise by the given amount of degrees - * @param angle The angle to rotate the image for (in degrees) + * Rotates the image clockwise by the given angle in degrees (like CSS' `rotate()`; negative angles turn it + * counterclockwise). Multiples of 90° move whole pixels; other angles resample the image (see + * {@link RotateOptions.mode}). By default the image grows so the corners fit (a quarter turn swaps width and + * height); with `expand: false` it keeps its size, also for quarter turns, and what doesn't fit is cut off + * @example + * ```ts + * image.rotate(90); // a quarter turn clockwise: width and height swap + * image.rotate(-15, { expand: false }); // 15° counterclockwise, the size stays and the corners are cut off + * ``` + * @param angle The angle in degrees, clockwise * @param options See {@link RotateOptions} + * @see {@link Image.transform} for skews, flips and shifts */ rotate(angle: number, options?: RotateOptions): this; - /** - * Rotates the image counterclockwise by the given amount of degrees - * @param angle The angle to rotate the image for (in degrees) - * @param resize Whether to resize the image so it fits all pixels or just ignore outlying pixels. Default: `true` - * @deprecated Pass {@link RotateOptions} instead, the positional arguments will be removed in 4.0 - */ - rotate(angle: number, resize?: boolean): this; - rotate(angle: number, resizeOrOptions: boolean | RotateOptions = true): this { - const { resize = true, fast = true } = typeof resizeOrOptions === 'object' && resizeOrOptions !== null ? resizeOrOptions : { resize: resizeOrOptions }; - angle = ((finite(angle, 'angle') % 360) + 360) % 360; + rotate(angle: number, options: RotateOptions = {}): this { + checkOptions(options, 'rotate(angle, { expand: false })'); + const { expand = true, mode = 'bilinear' } = options; + oneOf(mode, TRANSFORM_MODES, 'rotate mode'); + boolean(expand, 'expand'); + // (counterclockwise from here on: the image's y axis points down, so this turns it clockwise on screen) + angle = ((-finite(angle, 'angle') % 360) + 360) % 360; if (angle === 0) return this; const {width, height} = this; @@ -2703,95 +2449,59 @@ export class Image { else dst[x * height + height - 1 - y] = i; } + if (!expand && out.width !== width) { + // (without `expand` the image keeps its size: the turned image is centered in it, what doesn't fit is cut off) + const canvas = new Image(width, height), target = canvas.__u32__, turned = out.__u32__; + const left = Math.floor((width - out.width) / 2), top = Math.floor((height - out.height) / 2); + for (let y = Math.max(0, top); y < Math.min(height, top + out.height); y++) + for (let x = Math.max(0, left); x < Math.min(width, left + out.width); x++) + target[y * width + x] = turned[(y - top) * out.width + x - left]; + rotateGainMap(width, height); + this.__moved__?.(1, 1, 0, 0); + return this.__apply__(canvas); + } rotateGainMap(out.width, out.height); + this.__moved__?.(1, 1, (width - out.width) / 2, (height - out.height) / 2); return this.__apply__(out); } const rad = angle * Math.PI / 180; const sin = Math.sin(rad), cos = Math.cos(rad); - const outWidth = resize ? Math.round(Math.abs(width * cos) + Math.abs(height * sin)) : width; - const outHeight = resize ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height; + const outWidth = expand ? Math.round(Math.abs(width * cos) + Math.abs(height * sin)) : width; + const outHeight = expand ? Math.round(Math.abs(width * sin) + Math.abs(height * cos)) : height; const out = new Image(outWidth, outHeight); rotateGainMap(outWidth, outHeight); - if (fast && rotateBilinear(this.bitmap, width, height, out.bitmap, outWidth, outHeight, sin, cos)) return this.__apply__(out); - const s8 = this.bitmap, d8 = out.bitmap; - - // bilinear sampling of the counterclockwise rotated source, with premultiplied alpha - for (let oy = 0; oy < outHeight; oy++) { - for (let ox = 0; ox < outWidth; ox++) { - const dx = ox + 0.5 - outWidth / 2, dy = oy + 0.5 - outHeight / 2; - const sx = dx * cos - dy * sin + width / 2 - 0.5; - const sy = dx * sin + dy * cos + height / 2 - 0.5; - const x0 = Math.floor(sx), y0 = Math.floor(sy); - if (x0 < -1 || y0 < -1 || x0 >= width || y0 >= height) continue; - - const fx = sx - x0, fy = sy - y0; - const w00 = (1 - fx) * (1 - fy), w10 = fx * (1 - fy), w01 = (1 - fx) * fy, w11 = fx * fy; - let r = 0, g = 0, b = 0, a = 0; - - // taps outside the source are skipped (zero weight taps add nothing either way) - const left = x0 >= 0, right = x0 + 1 < width, top = y0 >= 0, bottom = y0 + 1 < height; - let i = 4 * (y0 * width + x0); - if (top && left) { - const wa = w00 * s8[i + 3]; - r += wa * s8[i]; - g += wa * s8[i + 1]; - b += wa * s8[i + 2]; - a += wa; - } - if (top && right) { - const wa = w10 * s8[i + 7]; - r += wa * s8[i + 4]; - g += wa * s8[i + 5]; - b += wa * s8[i + 6]; - a += wa; - } - i += 4 * width; - if (bottom && left) { - const wa = w01 * s8[i + 3]; - r += wa * s8[i]; - g += wa * s8[i + 1]; - b += wa * s8[i + 2]; - a += wa; - } - if (bottom && right) { - const wa = w11 * s8[i + 7]; - r += wa * s8[i + 4]; - g += wa * s8[i + 5]; - b += wa * s8[i + 6]; - a += wa; - } - - if (a <= 0) continue; - // the clamped bitmap rounds on assignment - const o = 4 * (oy * outWidth + ox); - d8[o] = r / a; - d8[o + 1] = g / a; - d8[o + 2] = b / a; - d8[o + 3] = a; - } + // bilinear: 8-bit sampling, about twice as fast, within a step of the precise sampling below (tests/rotate.js) + if (mode === 'bilinear' && rotateBilinear(this.bitmap, width, height, out.bitmap, outWidth, outHeight, sin, cos)) { + this.__moved__?.(1, 1, (width - outWidth) / 2, (height - outHeight) / 2); + return this.__apply__(out); } - + // the source position of each output position (pixel centers), around the middles of both images + const inverse: [number, number, number, number, number, number] = [cos, sin, -sin, cos, + width / 2 - cos * outWidth / 2 + sin * outHeight / 2, height / 2 - sin * outWidth / 2 - cos * outHeight / 2]; + sampleAffine(this.bitmap, width, height, out.bitmap, outWidth, outHeight, inverse, 0, 0, mode); + this.__moved__?.(1, 1, (width - outWidth) / 2, (height - outHeight) / 2); return this.__apply__(out); } /** * Flips / mirrors the image horizontally or vertically - * @param direction The direction to flip + * @param direction The direction to flip, see {@link FlipDirection} */ - flip(direction: 'horizontal' | 'vertical'): this { + flip(direction: FlipDirection): this { + oneOf(direction, FLIP_DIRECTIONS, 'flip direction'); const u32 = this.__u32__; const {width, height} = this; if (direction === 'horizontal') { for (let y = 0; y < height; y++) u32.subarray(y * width, (y + 1) * width).reverse(); - } else if (direction === 'vertical') { + } else { for (let y = 0; y < height >> 1; y++) { const top = u32.slice(y * width, (y + 1) * width); u32.copyWithin(y * width, (height - 1 - y) * width, (height - y) * width); u32.set(top, (height - 1 - y) * width); } - } else throw new RangeError('Invalid flip direction'); + } this.__gain_map__?.__transform__(width, height, width, height, direction === 'horizontal' ? (X, Y) => [width - X, Y] : (X, Y) => [X, height - Y]); return this; @@ -2846,12 +2556,6 @@ export class Image { } } - /** - * For a resize to the given size that only produces a part of it (frames scale their offsets) - * @internal - * @ignore - */ - protected __rescaled__?(width: number, height: number): void; /** * @internal @@ -2868,20 +2572,16 @@ export class Image { } /** - * Rounds the images corners, with antialiased edges + * Rounds the image's corners, with antialiased edges * @param options See {@link RoundCornersOptions} + * @see {@link Image.cropCircle} for a circle */ roundCorners(options?: RoundCornersOptions): this; - /** - * Rounds the images corners, with antialiased edges - * @param [radius=min(width,height)/4] The radius of the corners - * @deprecated Pass {@link RoundCornersOptions} instead, the positional arguments will be removed in 4.0 - */ - roundCorners(radius?: number): this; - roundCorners(radiusOrOptions?: number | RoundCornersOptions): this { - let radius = (isOptions(radiusOrOptions) ? radiusOrOptions.radius : radiusOrOptions) ?? Math.min(this.width, this.height) / 4; - radius = finite(radius, 'radius'); - radius = Math.max(0, Math.min(radius, this.width / 2, this.height / 2)); + roundCorners(options: RoundCornersOptions = {}): this { + checkOptions(options, 'roundCorners({ radius: 10 })'); + const { radius: givenRadius = Math.min(this.width, this.height) / 4 } = options; + let radius = nonNegative(givenRadius, 'radius'); + radius = Math.min(radius, this.width / 2, this.height / 2); const size = Math.ceil(radius); // coverage of the top left corner, mirrored onto the others @@ -2902,16 +2602,12 @@ export class Image { /** * Applies a fisheye (barrel distortion) effect * @param options See {@link FisheyeOptions} + * @throws `RangeError` if the strength is 0 or less */ fisheye(options?: FisheyeOptions): this; - /** - * Applies a fisheye (barrel distortion) effect - * @param [strength=2] The distortion strength (exponent of the radial mapping), higher values bulge the center more - * @deprecated Pass {@link FisheyeOptions} instead, the positional arguments will be removed in 4.0 - */ - fisheye(strength?: number): this; - fisheye(strengthOrOptions?: number | FisheyeOptions): this { - const strength = finite((isOptions(strengthOrOptions) ? strengthOrOptions.strength : strengthOrOptions) ?? 2, 'strength'); + fisheye(options: FisheyeOptions = {}): this { + checkOptions(options, 'fisheye({ strength: 3 })'); + const strength = positive(options.strength === undefined ? 2 : options.strength, 'strength'); const r = new Image(this.width, this.height); const w = this.width; @@ -2951,144 +2647,219 @@ export class Image { /** * Encodes the image into a PNG, with the smallest lossless color type (a palette for up to 256 colors, - * greyscale or RGB, alpha only if needed). Uses the runtime's native zlib when available + * grayscale or RGB, alpha only if needed). Uses the runtime's native zlib when available, so the compressed + * bytes can differ between runtimes and browsers; the pixels are the same * @param options See {@link PNGEncodeOptions} * @return The encoded data */ - encodePNG(options?: PNGEncodeOptions): Promise; - /** - * Encodes the image into a PNG - * @param compression The compression level (0-9). Default: `4` - * @param metadata Metadata to include, see {@link Metadata} - * @return The encoded data - * @deprecated Pass {@link PNGEncodeOptions} instead, the positional arguments will be removed in 4.0 - */ - encodePNG(compression?: number, metadata?: Metadata): Promise; - /** - * Encodes the image into a PNG with compression level 4 - * @param metadata Metadata to include, see {@link Metadata} - * @return The encoded data - * @deprecated Pass {@link PNGEncodeOptions} instead, the positional arguments will be removed in 4.0 - */ - encodePNG(metadata?: Metadata): Promise; - async encodePNG(compressionOrOptions: number | PNGEncodeOptions | Metadata = 4, metadataArgument: Metadata = {}): Promise { - let compression = 4, metadata = metadataArgument; - if (!isOptions(compressionOrOptions)) compression = compressionOrOptions; - // the options and the metadata have no key in common: an object with neither is empty, the same either way - else if ('compression' in compressionOrOptions || 'metadata' in compressionOrOptions) - ({ compression = 4, metadata = {} } = compressionOrOptions); - else metadata = compressionOrOptions as Metadata; + encodePNG(options?: PNGEncodeOptions): Promise>; + async encodePNG(options: PNGEncodeOptions = {}): Promise> { + checkOptions(options, 'encodePNG({ compression: 9, metadata: { author: \'me\' } })'); + const { compression = 4, metadata = {} } = options; return png.encodeRGBA(this.__bytes__(), this.width, this.height, compressionLevel(compression), pngText(resolveMetadata(metadata))); } /** - * Encodes the image into a PNG - * @param options See {@link PNGEncodeOptions} - * @return The encoded data - * @deprecated Use {@link Image.encodePNG}, `encode()` will be removed in 4.0 - * @group Deprecated - */ - encode(options?: PNGEncodeOptions): Promise; - /** - * Encodes the image into a PNG - * @param compression The compression level (0-9). Default: `4` - * @param metadata Metadata to include, see {@link Metadata} - * @return The encoded data - * @deprecated Use {@link Image.encodePNG}, `encode()` will be removed in 4.0 - * @group Deprecated - */ - encode(compression?: number, metadata?: Metadata): Promise; - /** - * Encodes the image into a PNG with compression level 4 - * @param metadata Metadata to include, see {@link Metadata} - * @return The encoded data - * @deprecated Use {@link Image.encodePNG}, `encode()` will be removed in 4.0 - * @group Deprecated - */ - encode(metadata?: Metadata): Promise; - encode(compressionOrOptions?: number | PNGEncodeOptions | Metadata, metadata?: Metadata): Promise { - return this.encodePNG(compressionOrOptions as number, metadata); - } - - /** - * Encodes the image into a JPEG + * Encodes the image into a JPEG. JPEG has no transparency: an image with transparent or translucent pixels is + * composited onto the `background` color (black by default) first, the image itself stays unchanged. An image whose + * pixels are all gray is written as a grayscale JPEG (one component) * @param options See {@link JPEGEncodeOptions} - */ - encodeJPEG(options?: JPEGEncodeOptions): Promise; - /** - * Encodes the image into a JPEG - * @param [quality=90] The JPEG quality to use (1-100), chroma subsampling is disabled above 90 - * @deprecated Pass {@link JPEGEncodeOptions} instead, the positional arguments will be removed in 4.0 - */ - encodeJPEG(quality?: number): Promise; - async encodeJPEG(qualityOrOptions: number | JPEGEncodeOptions = 90): Promise { - const { quality = 90, metadata = {}, gainMap: gainMapOption = true } = isOptions(qualityOrOptions) ? qualityOrOptions : { quality: qualityOrOptions }; + * @throws `RangeError` if the image is wider or higher than 65535 pixels, or the comment or the Exif fields of the metadata are longer than 65533 bytes + */ + 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 = checkQuality(qualityOption); + if (subsampling !== undefined) oneOf(subsampling, SUBSAMPLINGS, 'subsampling'); + const backgroundColor = checkColor(background, 'background'); + const embed = gainMapEmbed(gainMapOption); const m = resolveMetadata(metadata); - const base = { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined }; - const gainMap = this.__gain_map__; - if (!gainMap || gainMapOption === false) return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), base); + // (checked before the work: a JPEG segment holds 65533 bytes, the Exif one 6 of them for its header) + const exif = exifData(m), comment = m.comment ? utf8(m.comment) : undefined; + // eslint-disable-next-line no-restricted-syntax -- a limit of the format, not a range of the option + if (comment && comment.length > 65533) throw new RangeError(`JPEG: the metadata's comment must be at most 65533 bytes in UTF-8, not ${comment.length}`); + // eslint-disable-next-line no-restricted-syntax -- a limit of the format, not a range of the option + if (exif && exif.length > 65527) throw new RangeError(`JPEG: the metadata's description, author, copyright, software and creation time must be at most 65533 bytes together in Exif, not ${exif.length + 6}`); + + // (before any pass over the pixels: one over an image the format can't store took seconds) + checkFormatSize('JPEG', this.width, this.height, 0xffff); + + // without a gain map: the transparent pixels are composited onto the background row by row as the encoder reads + // 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 }; + 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 }); + } + + // transparent pixels: composited onto the opaque background (with the gain map, so the HDR light dims alike) + 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__() }; + 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 - const { quality: mapQuality, scale } = typeof gainMapOption === 'object' && gainMapOption !== null ? gainMapOption : {} as { quality?: number, scale?: number }; + const { quality: mapQuality, scale } = embed; let width: number | undefined, height: number | undefined; if (scale !== undefined) { - const s = finite(scale, 'gain map scale'); - if (!(s > 0 && s <= 1)) throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`); - width = Math.max(1, Math.round(this.width * s)); - height = Math.max(1, Math.round(this.height * s)); + width = Math.max(1, Math.round(this.width * scale)); + height = Math.max(1, Math.round(this.height * scale)); } const params = gainMap.__params__(); - const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality === undefined ? undefined : Math.max(1, checkQuality(mapQuality, 'gain map quality')), width, height), params); - const primary = jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { ...base, segments: gainMapCodec.primarySegments(map.length) }); + const map = gainMapCodec.mapWithMetadata(gainMap.__body__(mapQuality, width, height), params); + const primary = jpeg.encode(source.__bytes__(), source.width, source.height, quality, { ...base, segments: gainMapCodec.primarySegments(map.length) }); return gainMapCodec.finish(primary, map); } + /** + * Whether every pixel has the same red, green and blue (a grayscale image) + * @internal + * @ignore + */ + protected __is_gray__(): boolean { + const px = this.bitmap; + for (let i = 0; i < px.length; i += 4) if (px[i] !== px[i + 1] || px[i] !== px[i + 2]) return false; + return true; + } + + /** + * The image composited onto an opaque color, one row at a time, as `__flattened__` does (the same arithmetic, so the + * same pixels), or null if it is opaque already. `pixels` is the scratch row that `row(y)` fills; `gray()` says + * whether every composited pixel is gray (streamed, stops at the first colored one) + * @internal + * @ignore + */ + protected __flatRows__(background: Color): { pixels: Uint8Array, row: (y: number) => void, gray: () => boolean } | null { + const src = this.bitmap; + let opaque = true; + for (let i = 3; i < src.length && opaque; i += 4) opaque = src[i] === 255; + if (opaque) return null; + const width = this.width, bgR = background >>> 24, bgG = background >>> 16 & 255, bgB = background >>> 8 & 255; + const scratch = new Uint8ClampedArray(width * 4); + const row = (y: number): void => { + // (source over an opaque background, the arithmetic of composite(): a clamped byte per channel) + for (let x = 0, s = 4 * y * width, d = 0; x < width; x++, s += 4, d += 4) { + const sa = src[s + 3]; + if (sa === 0) { + scratch[d] = bgR; + scratch[d + 1] = bgG; + scratch[d + 2] = bgB; + continue; + } + if (sa === 255) { + scratch[d] = src[s]; + scratch[d + 1] = src[s + 1]; + scratch[d + 2] = src[s + 2]; + continue; + } + const fa = sa / 255, ba = 1 - fa, a = fa + ba; + scratch[d] = (src[s] * fa + bgR * ba) / a; + scratch[d + 1] = (src[s + 1] * fa + bgG * ba) / a; + scratch[d + 2] = (src[s + 2] * fa + bgB * ba) / a; + } + }; + const gray = (): boolean => { + for (let y = 0; y < this.height; y++) { + row(y); + for (let d = 0; d < scratch.length; d += 4) if (scratch[d] !== scratch[d + 1] || scratch[d] !== scratch[d + 2]) return false; + } + return true; + }; + return { pixels: new Uint8Array(scratch.buffer), row, gray }; + } + + /** + * The image composited onto an opaque color, or null if it is opaque already (formats without alpha) + * @internal + * @ignore + */ + protected __flattened__(background: Color, withGainMap: boolean): Image | null { + const pixels = this.bitmap; + let opaque = true; + for (let i = 3; i < pixels.length && opaque; i += 4) opaque = pixels[i] === 255; + if (opaque) return null; + const flat = new Image(this.width, this.height).fill((background | 0xff) >>> 0); + if (withGainMap || !this.__gain_map__) return flat.composite(this); + const withoutMap = this.clone(); + withoutMap.gainMap = null; + return flat.composite(withoutMap); + } + /** * Encodes the image as WebP: lossless (usually 20-30% smaller than PNG, but slower to encode), or lossy with a - * quality + * quality below 100 * @param options See {@link WebPEncodeOptions} + * @throws `RangeError` if the image is wider or higher than 16383 pixels (lossy) or 16384 (lossless): the limits of the two codecs */ - async encodeWebP({ quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = defaultThreads(), metadata = {} }: WebPEncodeOptions = {}): Promise { + async encodeWebP(options: WebPEncodeOptions = {}): Promise> { + checkOptions(options, 'image.encodeWebP({ quality: 80 })'); + const { quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = defaultThreads(), metadata = {} } = options; checkThreads(threads); const exif = exifData(resolveMetadata(metadata)); const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality); + // (before the conversion of the pixels: the limits of the two codecs) + checkFormatSize('WebP', this.width, this.height, lossy ? 16383 : 16384); if (!lossy) return webp.encode(this.__bytes__(), this.width, this.height, exif, threads, effort); return webp.encodeLossy(this.__bytes__(), this.width, this.height, lossy, exif); } /** * Encodes the image as run length encoded TGA (32 bit, or 24 bit if the image is opaque) - * @param options See {@link EncodeOptions} + * @param options See {@link TGAEncodeOptions} + * @throws `RangeError` if the image is wider or higher than 65535 pixels */ - async encodeTGA({ metadata = {} }: EncodeOptions = {}): Promise { + async encodeTGA(options: TGAEncodeOptions = {}): Promise> { + checkOptions(options, 'image.encodeTGA({ metadata })'); + const { metadata = {} } = options; const { author, comment, creationTime: time, software } = resolveMetadata(metadata); return tga.encode(this.__bytes__(), this.width, this.height, { author, comment, time, software }); } + /** + * Encodes the image as a GIF (one frame): at most 256 colors, transparency only on or off (pixels with an alpha below + * 128 become transparent). For animations, see {@link Animation.encodeGIF} + * @param options The palette size, the dithering and the metadata, see {@link GIFEncodeOptions} + * @throws `RangeError` if the image is wider or higher than 65535 pixels + */ + async encodeGIF(options: GIFEncodeOptions = {}): Promise> { + checkOptions(options, 'image.encodeGIF({ colors: 64 })'); + const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {} } = options; + const palette = quantize.paletteOptions(colors, dither, ditherStrength); + checkFormatSize('GIF', this.width, this.height, 0xffff); + const frame = { x: 0, y: 0, width: this.width, height: this.height, delay: 0, dispose: 1, pixels: this.__bytes__() }; + return gif.encode({ width: this.width, height: this.height, loopCount: 0, frames: [frame] }, { colors: palette.colors as number, dither: palette.dither, strength: palette.strength }, gifComments(resolveMetadata(metadata))); + } + /** * Encodes the image as BMP: with a palette if it is opaque and has at most 256 colors, else with 24 bit pixels, or * 32 bit ones if it has transparency */ - async encodeBMP(): Promise { + async encodeBMP(): Promise> { return bmp.encode(this.__bytes__(), this.width, this.height); } /** * Encodes the image as QOI (3 channels if the image is opaque) */ - async encodeQOI(): Promise { + async encodeQOI(): Promise> { return qoi.encode(this.__bytes__(), this.width, this.height); } /** * Encodes the image as AVIF (AV1, with an alpha image if the image has transparency) * @param options See {@link AVIFEncodeOptions} + * @throws `RangeError` if the image is wider or higher than 65536 pixels */ - async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true }: AVIFEncodeOptions = {}): Promise { + async encodeAVIF(options: AVIFEncodeOptions = {}): Promise> { + checkOptions(options, 'image.encodeAVIF({ quality: 60 })'); + const { quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options; checkEffort(effort, 2); checkThreads(threads); - if (subsampling !== '4:4:4' && subsampling !== '4:2:0') throw new TypeError(`subsampling must be '4:4:4' or '4:2:0', not ${String(subsampling)}`); + oneOf(subsampling, SUBSAMPLINGS, 'subsampling'); const exif = exifData(resolveMetadata(metadata)); return avifEnc.encode(this.__bytes__(), this.width, this.height, { quality: checkQuality(quality), alphaQuality: checkQuality(alphaQuality, 'alphaQuality'), subsampling, effort, exif, threads, gainMap: this.__gain_map_pixels__(gainMap) @@ -3102,31 +2873,32 @@ export class Image { * @ignore */ protected __gain_map_pixels__(option: boolean | { quality?: number, scale?: number }): { pixels: Uint8Array, width: number, height: number, params: gainMapCodec.Params, quality: number } | undefined { + const embed = gainMapEmbed(option); const gainMap = this.__gain_map__; - if (!gainMap || option === false) return undefined; - const { quality = 90, scale } = typeof option === 'object' && option !== null ? option : {} as { quality?: number, scale?: number }; - const mapQuality = Math.max(1, checkQuality(quality, 'gain map quality')); + if (!gainMap || !embed) return undefined; + const { quality: mapQuality = 90, scale } = embed; let map = gainMap.image; if (scale !== undefined) { - const s = finite(scale, 'gain map scale'); - if (!(s > 0 && s <= 1)) throw new RangeError(`The gain map scale must be above 0 and at most 1, not ${s}`); - const width = Math.max(1, Math.round(this.width * s)), height = Math.max(1, Math.round(this.height * s)); + const width = Math.max(1, Math.round(this.width * scale)), height = Math.max(1, Math.round(this.height * scale)); if (width !== map.width || height !== map.height) map = map.clone().resize(width, height); } return { pixels: map.__bytes__(), width: map.width, height: map.height, params: gainMap.__params__(), quality: mapQuality }; } /** - * Encodes the image as JPEG XL: losslessly (the default) like libjxl's `cjxl -e 3` (a palette of up to 1024 colors, - * else palettes of channels using few of their values; YCoCg; the weighted predictor in contexts of its error; - * greyscale if the image is), at effort 0 the codestream byte for byte like `cjxl -e 1` on CPUs with AVX2 or NEON - * (its fast lossless mode: the gradient predictor, a palette if the image has at most 511 colors besides black, - * else YCoCg), or lossy with a quality (like `cjxl -q`: XYB, varblocks of libjxl's search, chroma from luma, the - * edge preserving filter). Alpha (if the image has transparency) is lossless either way. The codestream is in the - * container, with the metadata as Exif + * Encodes the image as JPEG XL: losslessly (the default), or lossy with a quality. Alpha (if the image has + * transparency) is lossless either way. The codestream is in the container, with the metadata as Exif + * @remarks + * Lossless works like libjxl's `cjxl -e 3` (a palette of up to 1024 colors, else palettes of channels using few of + * their values; YCoCg; the weighted predictor in contexts of its error; grayscale if the image is), at effort 0 the + * codestream byte for byte like `cjxl -e 1` on CPUs with AVX2 or NEON (its fast lossless mode: the gradient predictor, + * a palette if the image has at most 511 colors besides black, else YCoCg). Lossy works like `cjxl -q`: XYB, varblocks + * of libjxl's search, chroma from luma, the edge preserving filter * @param options See {@link JXLEncodeOptions} */ - async encodeJXL({ quality, effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true }: JXLEncodeOptions = {}): Promise { + async encodeJXL(options: JXLEncodeOptions = {}): Promise> { + checkOptions(options, 'image.encodeJXL({ quality: 90 })'); + const { quality, effort = 1, threads = defaultThreads(), metadata = {}, gainMap = true } = options; checkEffort(effort, 2); checkThreads(threads); // (cjxl's distance of a quality) @@ -3137,28 +2909,43 @@ export class Image { } /** - * Encodes the image as the smallest fitting Netpbm format: PBM for black and white images, PGM for greyscale ones, + * Encodes the image as the smallest fitting Netpbm format: PBM for black and white images, PGM for grayscale ones, * PPM for others, PAM if the image has transparency */ - async encodePNM(): Promise { + async encodePNM(): Promise> { return netpbm.encode(this.__bytes__(), this.width, this.height); } /** * Decodes an image (PNG, JPEG, TIFF, WebP, BMP, ICO, CUR, QOI, PBM, PGM, PPM, PAM, PFM, Radiance HDR, TGA, AVIF or - * JPEG XL). For APNGs this is the default image; animated WebPs and GIFs have no single image, decode those with - * {@link Animation.decode}; for icons and cursors it's their largest image, for AVIF image sequences and JPEG XL - * animations their first frame + * JPEG XL) + * @remarks + * For animations (GIFs, animated WebPs, AVIF image sequences, JPEG XL animations) this is the first frame, composed + * onto the canvas as {@link Animation.decode} has it, and decoding stops after it: use {@link Animation.decode} for all + * frames. For APNGs this is the default image, which is what viewers without APNG support show; for icons and cursors + * it's their largest image + * @example + * ```ts + * const image = await Image.decode(bytes); // the file's bytes, e.g. from fs.readFile() or fetch() + * const webp = await image.resize({ width: 800 }).encodeWebP({ quality: 80 }); + * ``` * @param input The binary data to decode - * @param options See {@link DecodeOptions}. JPEGs, TIFFs and PNGs are rotated/mirrored as their orientation tag + * @param options See {@link DecodeOptions}. JPEGs, TIFFs, PNGs, WebPs and JPEG XLs are rotated/mirrored as their orientation * (Exif, for PNGs also XMP) says by default: photos taken with a rotated camera are stored sideways * @return The decoded image + * @throws {@link LimitError} if the image has more than `options.maxPixels` pixels (checked before its pixels are + * allocated) + * @throws `Error` if the data isn't a supported image, or is damaged or truncated (the underlying error is its `cause`) */ static async decode(input: BinaryData, options: DecodeOptions = {}): Promise { + checkOptions(options, 'Image.decode(data, { maxPixels: 1e8 })'); const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads(), gainMap = true } = options; checkThreads(threads); - if (!(Number(maxPixels) > 0)) throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`); - if (toneMapping !== 'reinhard' && toneMapping !== 'clamp') throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`); + pixelLimit(maxPixels); + oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping'); + boolean(applyOrientation, 'applyOrientation'); + boolean(applyColorProfile, 'applyColorProfile'); + boolean(gainMap, 'gainMap'); const data = view(input); const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); @@ -3167,8 +2954,10 @@ export class Image { if (ImageType.isJPEG(dataView)) return jpeg.decode(data, { maxPixels }); if (ImageType.isTIFF(dataView)) return tiff.decode(data, maxPixels); if (ImageType.isWebP(dataView)) { - if (webp.isAnimated(data)) throw new Error('Animated WebPs have to be decoded with Animation.decode()'); - return webp.decode(data, maxPixels); + if (!webp.isAnimated(data)) return webp.decode(data, maxPixels); + // the first frame only: the rest of the file isn't decoded + const animation = webp.decodeAnimation(data, true, maxPixels); + return { width: animation.width, height: animation.height, pixels: webp.composite(animation)[0].pixels, orientation: animation.orientation, icc: animation.icc }; } // bitmaps can hold a JPEG or PNG, icons PNGs const bitmap = async (decoded: bmp.Decoded): Promise<{ width: number, height: number, pixels: Uint8Array }> => { @@ -3180,12 +2969,18 @@ export class Image { if (ImageType.isAVIF(dataView)) return avif.decode(data, maxPixels, toneMapping, threads, gainMap); if (ImageType.isJXL(dataView)) return jxl.decode(data, maxPixels, toneMapping, threads, gainMap); if (ImageType.isBMP(dataView)) return bitmap(bmp.decode(data, maxPixels)); - if (ImageType.isICO(dataView)) return bitmap(ico.decode(data, maxPixels)); + if (ImageType.isICO(dataView) || ImageType.isCUR(dataView)) return bitmap(ico.decode(data, maxPixels)); if (ImageType.isQOI(dataView)) return qoi.decode(data, maxPixels); if (ImageType.isPNM(dataView)) return netpbm.decode(data, maxPixels, toneMapping); if (ImageType.isHDR(dataView)) return hdr.decode(data, maxPixels, toneMapping); if (ImageType.isTGA(dataView)) return tga.decode(data, maxPixels); - if (ImageType.isGIF(dataView)) throw new Error('GIFs have to be decoded with Animation.decode() (or decode(), which returns an image or an animation)'); + if (ImageType.isGIF(dataView)) { + // the first frame only: the rest of the file isn't decoded + const gifData = gif.decode(data, true, maxPixels); + const [first] = gif.composite(gifData); + if (!first) throw new Error('GIF: no frames'); + return { width: gifData.width, height: gifData.height, pixels: first.pixels }; + } throw new Error('Unsupported image type'); }); @@ -3194,15 +2989,18 @@ export class Image { const { icc, cicp, colorSpace } = decoded; (icc ? profileTransform(icc) : cicp ? cicpTransform(...cicp) : colorSpace ? colorSpaceTransform(colorSpace.xy, colorSpace.curve) : null)?.(decoded.pixels); } + // (a decoder that reads sizes from damaged data can end up with none, or with other pixels than they say) + if (!(decoded.width >= 1 && decoded.height >= 1) || decoded.pixels.length !== decoded.width * decoded.height * 4) + throw new Error('Image: damaged or truncated image data'); // the decoded pixels become the bitmap, without a copy const image = new Image(decoded.width, decoded.height); - image.bitmap = decoded.pixels; + image.bitmap = alignedPixels(decoded.pixels); // (a gain map that can't be read leaves the image without one, it doesn't fail the decoding) if (gainMap && ImageType.isJPEG(dataView)) { try { const found = gainMapCodec.find(data); const size = found && gainMapCodec.dimensions(found.map); - if (found && size && size.width * size.height <= maxPixels) image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple); + if (found && size && size.width * size.height <= maxPixels) image.__gain_map__ = GainMap.__from_jpeg__(found.map, found.params, found.apple, maxPixels); } catch { image.__gain_map__ = null; } @@ -3210,7 +3008,7 @@ export class Image { if (decoded.gainMap) { const { width, height, pixels, params } = decoded.gainMap; const map = new Image(width, height); - map.bitmap = pixels; + map.bitmap = alignedPixels(pixels); image.__gain_map__ = GainMap.__from_pixels__(map, params); } if (applyOrientation && decoded.orientation && decoded.orientation > 1) { @@ -3261,30 +3059,16 @@ export class Image { return this.__apply__(out); } - /** - * @deprecated Use `renderSVG(svg, { scale })`: `Image.SVG_MODE_*` and `SVGScaleModes` are removed in 4.0 - * @group Deprecated - */ - static readonly SVG_MODE_SCALE = 1; - - /** - * @deprecated Use `renderSVG(svg, { width })`: `Image.SVG_MODE_*` and `SVGScaleModes` are removed in 4.0 - * @group Deprecated - */ - static readonly SVG_MODE_WIDTH = 2; - - /** - * @deprecated Use `renderSVG(svg, { height })`: `Image.SVG_MODE_*` and `SVGScaleModes` are removed in 4.0 - * @group Deprecated - */ - static readonly SVG_MODE_HEIGHT = 3; - /** * Creates a new image from the given SVG + * @remarks * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths, * masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs - * (PNG, JPEG, GIF, WebP, SVG) or given with {@link SVGOptions.images}, and text with the given or embedded fonts - * (see {@link SVGOptions.fonts}). Hrefs are resolved from the options and the data URIs only, never from files or URLs. + * (PNG, JPEG, GIF, WebP, SVG) or given with {@link SVGResourceOptions.images}, and text with the given or embedded fonts + * (see {@link SVGResourceOptions.font}). Hrefs are resolved from the options and the data URIs only, never from files or URLs: + * drawing an image that isn't given, or can't be decoded, throws. SVGs from untrusted sources are fine to render: the + * size of the output, the layers and the images are limited by the options, and so is the work nested masks, clip + * paths, patterns, markers and filter images can multiply * @example * ```ts * const logo = await Image.renderSVG( @@ -3293,77 +3077,80 @@ export class Image { * ); * ``` * @param svg The SVG content - * @param options See {@link SVGOptions} - * @return The rendered SVG graphic - */ - static renderSVG(svg: string | BinaryData, options?: SVGOptions): Promise; - /** - * Creates a new image from the given SVG - * @param svg The SVG content - * @param size The size to use - * @param mode The SVG resizing mode to use (one of {@link SVGScaleModes.SCALE}, {@link SVGScaleModes.WIDTH}, {@link SVGScaleModes.HEIGHT}) + * @param options See {@link RenderSVGOptions} * @return The rendered SVG graphic - * @deprecated Pass {@link SVGOptions} instead, `renderSVG(svg, { width: 512 })` (or `height`, `scale`). The - * positional arguments will be removed in 4.0 - */ - static renderSVG(svg: string | BinaryData, size?: number, mode?: SVGScaleMode): Promise; - static async renderSVG(svg: string | BinaryData, sizeOrOptions: number | SVGOptions = 1, modeArgument: SVGScaleMode = SVGScaleModes.SCALE): Promise { - const options: SVGOptions = isOptions(sizeOrOptions) ? sizeOrOptions : { size: sizeOrOptions, mode: modeArgument }; - // (the 4.0 names: width, height or scale for size and mode, font for fonts) - const sizes = [options.width, options.height, options.scale].filter(value => value !== undefined).length; + * @throws {@link LimitError} if the output, the layers or the images exceed the limits of the options, or the SVG + * exceeds a fixed limit of the work it may take: more than 100000 elements drawn through `` references and + * markers, more than 10000 markers, masks, clip paths, patterns, markers and filter images nested so deeply that + * they would multiply, entities that expand past the size limit, or filters past their budget + * @throws `RangeError` if the requested size is below 1 pixel (or a scale isn't above 0) + * @throws `Error` if the SVG can't be parsed (it has no `` element) or an image in it can't be drawn (it isn't + * given or can't be decoded) + */ + static renderSVG(svg: string | BinaryData, options?: RenderSVGOptions): Promise; + static async renderSVG(svg: string | BinaryData, options: RenderSVGOptions = {}): Promise { + checkOptions(options, 'Image.renderSVG(svg, { width: 512 })'); + const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, font: fonts = [], images: givenImages = {} } = options; + pixelLimit(maxPixels); + const { maxLayerPixels = 4 * maxPixels, maxImagePixels = maxPixels } = options; + pixelLimit(maxLayerPixels, 'maxLayerPixels'); + pixelLimit(maxImagePixels, 'maxImagePixels'); + const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length; if (sizes > 1) throw new TypeError('renderSVG() takes one of width, height and scale'); - if (sizes && (options.size !== undefined || options.mode !== undefined)) throw new TypeError('renderSVG() takes width, height or scale, or the deprecated size and mode, not both'); - if (options.font !== undefined && options.fonts !== undefined) throw new TypeError('renderSVG() takes font, or the deprecated fonts, not both'); - const { size = 1, mode: givenMode = SVGScaleModes.SCALE } = options.width !== undefined ? { size: options.width, mode: SVGScaleModes.WIDTH } - : options.height !== undefined ? { size: options.height, mode: SVGScaleModes.HEIGHT } - : options.scale !== undefined ? { size: options.scale, mode: SVGScaleModes.SCALE } : options; - const { images: givenImages = {} } = options; - const fonts = options.font === undefined ? options.fonts ?? [] : Array.isArray(options.font) ? options.font : [options.font]; - const mode = LEGACY_SVG_MODES.get(givenMode) ?? givenMode; - if (mode !== 'scale' && mode !== 'width' && mode !== 'height') - throw new Error('Invalid SVG scaling mode'); - - finite(size, 'SVG size'); - if (mode === SVGScaleModes.SCALE && size <= 0) - throw new RangeError('SVG scale must be > 0'); - if (mode !== SVGScaleModes.SCALE && size < 1) - throw new RangeError('SVG size must be >= 1'); + const mode = givenWidth !== undefined ? 'width' : givenHeight !== undefined ? 'height' : 'scale'; + const size = finite(mode === 'width' ? givenWidth as number : mode === 'height' ? givenHeight as number : scale === undefined ? 1 : scale, `SVG ${mode}`); + if (mode === 'scale') positive(size, 'SVG scale'); + else atLeast(size, 1, `SVG ${mode}`); // the images given by href, checked before anything is decoded if (typeof givenImages !== 'object' || givenImages === null || Array.isArray(givenImages) || givenImages instanceof Map) + // eslint-disable-next-line no-restricted-syntax -- the images of an SVG are only checked here throw new TypeError('SVG images must be an object of hrefs to image data'); const given = new Map(); for (const href of Object.keys(givenImages)) { const value = givenImages[href]; - if (!(value instanceof Image) && !(value instanceof ArrayBuffer || ArrayBuffer.isView(value))) + if (!(value instanceof Image) && !isBinaryData(value)) throw new TypeError(`SVG image ${JSON.stringify(href)} must be BinaryData or an Image`); given.set(href, value); } // the raster images it references are decoded first (decoding can be asynchronous), the SVG is rendered at once. - // A given image wins over a data URI with the same href; each is decoded once, and only if the SVG uses it + // A given image wins over a data URI with the same href; each is decoded once, and only if the SVG references + // it. One that can't be decoded (or doesn't fit maxImagePixels) throws once it's drawn const source = typeof svg === 'string' ? svg : view(svg); - const images = new Map(); + const images = new Map(); + const shown = (href: string): string => JSON.stringify(href.length > 100 ? `${href.slice(0, 100)}...` : href); + let imagePixels = maxImagePixels; for (const { href, data } of svgRenderer.imageReferences(source)) { const value = given.get(href) ?? data; if (!value) continue; + if (value instanceof Image) { + images.set(href, { width: value.width, height: value.height, pixels: value.bitmap }); + continue; + } + const tooLarge = (cause?: unknown): LimitError => new LimitError(`SVG: the image ${shown(href)} exceeds what's left of the ${maxImagePixels} pixels the SVG's images may decode to (the render options' maxImagePixels)`, { cause }); + if (!(imagePixels >= 1)) { + images.set(href, { error: tooLarge() }); + continue; + } try { - if (value instanceof Image) { - images.set(href, { width: value.width, height: value.height, pixels: value.bitmap }); - } else if (ImageType.getType(value) === 'gif') { + let decoded: svgRenderer.RasterImage; + if (ImageType.getType(value) === 'gif') { // (a GIF's first frame) - const decoded = gif.decode(view(value), true); - images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels }); + const gifData = await decoding(() => gif.decode(view(value), true, imagePixels)); + decoded = { width: gifData.width, height: gifData.height, pixels: gif.composite(gifData)[0].pixels }; } else { - const image = await Image.decode(value); - images.set(href, { width: image.width, height: image.height, pixels: image.bitmap }); + const image = await Image.decode(value, { maxPixels: imagePixels }); + decoded = { width: image.width, height: image.height, pixels: image.bitmap }; } - } catch { - // (images that can't be decoded aren't drawn, like resvg's) + imagePixels -= decoded.width * decoded.height; + images.set(href, decoded); + } catch (err) { + images.set(href, { error: err instanceof LimitError ? tooLarge(err) : new Error(`SVG: the image ${shown(href)} can't be decoded`, { cause: err }) }); } } - const {width, height, pixels} = svgRenderer.render(source, mode, size, images, fonts.map(font => view(font))); + const {width, height, pixels} = svgRenderer.render(source, mode, size, images, Array.from(Array.isArray(fonts) ? fonts : [fonts], font => view(font)), maxPixels, maxLayerPixels); const image = new Image(width, height); image.bitmap.set(pixels); @@ -3371,74 +3158,49 @@ export class Image { } /** - * Creates a new image containing the rendered text. - * @param text Text to render - * @param options The font and size, color, layout and style, see {@link RenderTextOptions}; the image grows by the - * outline width on every side - * @return The rendered text - */ - static renderText(text: string, options: RenderTextOptions): Promise; - /** - * Creates a new image containing the rendered text. - * @param font TrueType (ttf/ttc), OpenType (otf) or WOFF font buffer to use, or several by priority: every - * character comes from the first font that has it (e.g. `[text, emoji]`), the first one sets the line height. - * Color glyphs (COLR layers and paints, CBDT and sbix bitmaps, as in emoji fonts) keep their colors. Text in any - * script is shaped like browsers do (right to left and bidirectional text, Arabic joining, Indic conjuncts, - * marks) - * @param size Font size in pixels (per em) - * @param text Text to render - * @param options Color, layout and style, see {@link TextOptions}; the image grows by the outline width on every - * side - * @return The rendered text - * @deprecated Pass the text first and everything else as options, `Image.renderText(text, { font, size })`. - * This signature will be removed in 4.0 - */ - static renderText(font: BinaryData | BinaryData[], size: number, text: string, options?: TextOptions): Promise; - /** - * Creates a new image containing the rendered text. - * @param font TrueType (ttf/ttc), OpenType (otf) or WOFF font buffer to use, or several by priority: every - * character comes from the first font that has it (e.g. `[text, emoji]`), the first one sets the line height. - * Color glyphs (COLR layers and paints, CBDT and sbix bitmaps, as in emoji fonts) keep their colors. Text in any - * script is shaped like browsers do (right to left and bidirectional text, Arabic joining, Indic conjuncts, - * marks) - * @param size Font size in pixels (per em) + * Creates a new image containing the rendered text + * @example + * ```ts + * const label = await Image.renderText('Hello, world', { font: fontBytes, size: 48, color: 0xffffffff }); + * ``` * @param text Text to render - * @param [color=0xffffffff] Text color to use - * @param [layout] The text layout to use - * @param style Outline, see {@link TextStyle}; the image grows by the outline width on every side + * @param options The font and size, color, layout and style, see {@link RenderTextOptions}. Without a `width` or + * `height`, the image grows by the outline width on every side; with one, it has exactly that size * @return The rendered text - * @deprecated Pass the text first and everything else as options, `Image.renderText(text, { font, size })`. - * This signature will be removed in 4.0 - */ - static renderText(font: BinaryData | BinaryData[], size: number, text: string, color?: Color, layout?: TextLayout, style?: TextStyle): Promise; - static async renderText(fontOrText: BinaryData | BinaryData[] | string, sizeOrOptions: number | RenderTextOptions, textArgument?: string, colorOrOptions: Color | TextOptions = 0xffffffff, layoutArgument?: TextLayout, styleArgument: TextStyle = {}): Promise { - let font: BinaryData | BinaryData[], size: number, text: string, options: Omit & { layout?: TextLayoutOptions | TextLayout }; - if (typeof fontOrText === 'string') { - if (!isOptions(sizeOrOptions) || sizeOrOptions.font === undefined) throw new TypeError('renderText(text, options) needs the font in the options'); - ({ font, size, ...options } = sizeOrOptions); - text = fontOrText; - } else { - font = fontOrText; - size = sizeOrOptions as number; - text = textArgument as string; - options = isOptions(colorOrOptions) ? colorOrOptions : { ...styleArgument, color: colorOrOptions, layout: layoutArgument }; - } - const { color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {} } = options; - const layout = options.layout instanceof TextLayout ? options.layout : new TextLayout(options.layout); + * @throws `TypeError` if the text isn't a string, or the options aren't an object with a `font` + * @throws `Error` if the font can't be read + * @throws {@link LimitError} if the image would have more than `options.maxPixels` pixels (checked before anything is + * allocated) + */ + static async renderText(text: string, options: RenderTextOptions): Promise { + if (typeof text !== 'string') throw new TypeError(`Image.renderText() takes the text as a string, like Image.renderText('Hello', { font, size: 32 }), not ${shown(text)}`); + if (!isOptions(options)) throw new TypeError(`Image.renderText() takes an options object, like Image.renderText('Hello', { font, size: 32 }), not ${options === undefined ? 'undefined' : shown(options)}`); + if (options.font === undefined) throw new TypeError('Image.renderText(text, options) needs the font in the options'); + const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options; + pixelLimit(maxPixels); + boolean(hinting, 'hinting'); + const { width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign } = options; + const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign }); const axes = textRenderer.axisValues(variations); - size = finite(size, 'font size'); - if (size < 0) throw new RangeError(`Invalid font size: ${size}`); - if (finite(strokeWidth, 'stroke width') < 0) - throw new RangeError('Invalid stroke width'); + const size = positive(options.size, 'font size'); + nonNegative(strokeWidth, 'stroke width'); const fonts = Array.isArray(font) ? font : [font]; - if (!fonts.length) throw new RangeError('No font given'); + // eslint-disable-next-line no-restricted-syntax -- the one list of fonts + if (!fonts.length) throw new TypeError('font must be a font or an array of one or more fonts, not an empty array'); const [r, g, b, a] = Colors.toRGBA(color); + // (checked with the stroke width at 0 too: a wrong color doesn't pass until a stroke is set) + const [sr, sg, sb, sa] = Colors.toRGBA(strokeColor); + // the outline needs room around the glyphs (checked against maxPixels with them): a given size is the image's, + // the text goes inside the outline + const pad = Math.ceil(strokeWidth); + if (layout.width !== undefined && layout.width <= 2 * pad) throw new RangeError(`The width (${layout.width}) leaves no room for the text inside the ${strokeWidth} pixel outline`); + if (layout.height !== undefined && layout.height <= 2 * pad) throw new RangeError(`The height (${layout.height}) leaves no room for the text inside the ${strokeWidth} pixel outline`); + if (layout.width !== undefined) layout.width -= 2 * pad; + if (layout.height !== undefined) layout.height -= 2 * pad; // color glyph layers in the text color take it without its alpha, which applies to the whole color glyph - const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes); + const rendered = await textRenderer.render(Array.from(fonts, view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features), axes, maxPixels, pad); - // the outline needs room around the glyphs - const pad = Math.ceil(strokeWidth); const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad; const coverage = new Uint8Array(width * height); for (let y = 0; y < rendered.height; y++) @@ -3455,7 +3217,7 @@ export class Image { if (!strokeWidth && !colored) { // the pixel for each coverage value, written as one word - const pixels = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >> 2), lut = new Uint32Array(256); + const pixels = new Uint32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >>> 2), lut = new Uint32Array(256); const bytes = new Uint8ClampedArray(lut.buffer); for (let v = 1; v < 256; v++) bytes.set([r, g, b, v * a / 255], v * 4); for (let i = 0; i < coverage.length; i++) if (coverage[i]) pixels[i] = lut[coverage[i]]; @@ -3469,7 +3231,6 @@ export class Image { for (let i = 0; i < shape.length; i++) shape[i] = Math.max(shape[i], colored[i * 4 + 3]); } const stroke = strokeWidth ? outline(shape, width, height, strokeWidth) : null; - const [sr, sg, sb, sa] = Colors.toRGBA(strokeColor); // color glyphs over the text (premultiplied, with the text's alpha), both within their outline for (let i = 0; i < coverage.length; i++) { @@ -3531,30 +3292,48 @@ interface HSLA { a: number; } -// the deprecated upper case resize modes (Image.RESIZE_*) and the names they stand for -const LEGACY_RESIZE_MODES = new Map([ - ['RESIZE_NEAREST_NEIGHBOR', 'nearest-neighbor'], ['RESIZE_BILINEAR', 'bilinear'], ['RESIZE_BICUBIC', 'bicubic'], ['RESIZE_AREA', 'area'] -]); +/** + * Decoded pixels as an image's bitmap: as they are, or copied if they don't start at an offset the 32-bit pixel views + * need (the bitmap setter refuses those, so a decoder returning a view into a larger buffer doesn't fail) + * @internal + */ +export function alignedPixels(pixels: T): T { + return pixels.byteOffset % 4 ? pixels.slice() as T : pixels; +} /** - * The width, height and mode of resize()'s signatures, a side missing from the options as {@link ResizeModes.AUTO} + * The width, height and mode of resize()'s signatures: a side left out of the options is `undefined` * @internal */ -export function resizeArguments(widthOrOptions: number | ResizeToOptions, height?: number, modeOrOptions?: ResizeMode | ResizeOptions): [width: number, height: number, modeOrOptions: ResizeMode | ResizeOptions | undefined] { - if (!isOptions(widthOrOptions)) return [widthOrOptions, height as number, modeOrOptions]; - const { width, height: optionsHeight, ...options } = widthOrOptions; +export function resizeArguments(widthOrOptions: number | ResizeToOptions, height?: number, options?: ResizeOptions): [width: number | undefined, height: number | undefined, options: ResizeRuntimeOptions | undefined, fit: ResizeFit] { + if (!isOptions(widthOrOptions)) { + if (typeof widthOrOptions !== 'number') throw new TypeError(`resize() takes a width and a height, like resize(300, 200), or an options object, like resize({ width: 300 }), not ${shown(widthOrOptions)}`); + checkOptions(options, 'resize(width, height, { mode: \'area\' })'); + return [finite(widthOrOptions, 'width'), finite(height as number, 'height'), options, 'fill']; + } + const { width, height: optionsHeight, fit = 'fill', ...rest } = widthOrOptions; if (width === undefined && optionsHeight === undefined) throw new TypeError('resize() needs a width, a height or both'); - return [width ?? ResizeModes.AUTO, optionsHeight ?? ResizeModes.AUTO, options]; + oneOf(fit, RESIZE_FITS, 'fit'); + return [width === undefined ? undefined : finite(width, 'width'), optionsHeight === undefined ? undefined : finite(optionsHeight, 'height'), rest, fit]; } -function resizeOptions(modeOrOptions?: ResizeMode | ResizeOptions): { mode: ResizeMode, fast: boolean } { - const options = isOptions(modeOrOptions) ? modeOrOptions : { mode: modeOrOptions }; - const mode = options.mode ?? ResizeModes.BILINEAR; - return { mode: LEGACY_RESIZE_MODES.get(mode) ?? mode, fast: options.fast ?? true }; +/** + * The size of an image of `width` x `height` resized to fit inside a box of `boxWidth` x `boxHeight`, keeping its aspect + * ratio: the limiting side matches the box exactly (rounded instead of floored), the other one is at least 1 pixel + */ +export function insideSize(width: number, height: number, boxWidth: number, boxHeight: number): [width: number, height: number] { + boxWidth = Math.floor(boxWidth); + boxHeight = Math.floor(boxHeight); + const scale = Math.min(boxWidth / width, boxHeight / height); + return [Math.max(1, Math.min(boxWidth, Math.round(width * scale))), Math.max(1, Math.min(boxHeight, Math.round(height * scale)))]; } -// the deprecated SVG scale mode numbers (Image.SVG_MODE_*) and the names they stand for -const LEGACY_SVG_MODES = new Map([[1, 'scale'], [2, 'width'], [3, 'height']]); +const RESIZE_MODES: readonly ResizeMode[] = ['nearest-neighbor', 'bilinear', 'bicubic', 'area']; + +// the resize options with their defaults, the mode checked before anything changes +function resizeOptions(options?: ResizeOptions): { mode: ResizeMode } { + return { mode: options?.mode === undefined ? 'bilinear' : oneOf(options.mode, RESIZE_MODES, 'resize mode') }; +} // separable blend functions of normalized channel values (W3C Compositing and Blending Level 1) const hardLight = (b: number, s: number): number => s <= 0.5 ? b * 2 * s : 1 - (1 - b) * (1 - (2 * s - 1)); @@ -3581,11 +3360,7 @@ const BLEND_MODES: Record numbe // the color at every position of a gradient, from its stops function gradientFunction(stops: Record | Color[]): (position: number) => Color { - if (!Array.isArray(stops)) return Colors.gradient(stops); - if (!stops.length) throw new RangeError('Invalid gradient point count'); - // (one color is a gradient of two equal ones) - const colors = stops.length === 1 ? [stops[0], stops[0]] : stops; - return Colors.gradient(Object.fromEntries(colors.map((color, i) => [i / (colors.length - 1), color]))); + return Colors.gradient(stops); } /** @@ -3710,3 +3485,5 @@ function distanceTransform(f: Float64Array, n: number, d: Float64Array, v: Int32 nearest[q] = v[j]; } } + +describe(Image, image => ({ width: image.width, height: image.height })); diff --git a/src/index.ts b/src/index.ts index 49e1c7d4..c4dace2e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,52 +1,55 @@ +/** + * @packageDocumentation + * @document ../guides/Migrating to 4.0.md + */ +// (the guide is attached to the entry module: as a project document it turned the docs into a module "index", every +// page's file name prefixed with it, e.g. classes/index.Image.html instead of classes/Image.html) import { BinaryData } from './util/mem.ts'; import { Image, DecodeOptions } from './image.ts'; -import { GIF } from './gif.ts'; -import { Animation, AnimationDecodeOptions } from './animation.ts'; -import { isOptions } from './util/options.ts'; +import { Animation } from './animation.ts'; +import { checkOptions } from './util/options.ts'; +import * as png from './codecs/png.ts'; import * as webp from './codecs/webp.ts'; import { view } from './util/mem.ts'; import { ImageType } from './image-type.ts'; -export { Image, ResizeModes, SVGScaleModes } from './image.ts'; +export { Image } from './image.ts'; export { Colors } from './colors.ts'; -export type { Color, ColorFunction, ResizeMode, SVGScaleMode, PNGMetadata, TextStyle, DecodeOptions, CompositeOptions, BlendMode, CropCircleOptions, DominantColorOptions, RotateOptions, ColorToAlphaOptions, ResizeOptions, ResizeToOptions, AdjustOptions, SharpenOptions, PNGEncodeOptions, JPEGEncodeOptions, WebPEncodeOptions, AVIFEncodeOptions, JXLEncodeOptions, EncodeOptions, SVGOptions, RenderSVGOptions, TextOptions, RenderTextOptions, ShadowOptions, OutlineOptions, QuantizeOptions, TransformOptions, TransformMode, GradientOptions, LinearGradientOptions, RadialGradientOptions, RoundCornersOptions, FisheyeOptions, TrimOptions } from './image.ts'; -export { Frame, FrameDisposalModes } from './frame.ts'; -export type { FrameDisposalMode, FrameDisposalModeName, FrameDisposalModeId, FrameOptions } from './frame.ts'; +export type { Color, ColorFunction, ResizeMode, ResizeFit, TextStyleOptions, DecodeOptions, CompositeOptions, BlendMode, CropCircleOptions, DominantColorOptions, RotateOptions, ColorToAlphaOptions, ResizeOptions, ResizeToOptions, SharpenOptions, PNGEncodeOptions, JPEGEncodeOptions, WebPEncodeOptions, AVIFEncodeOptions, JXLEncodeOptions, EncodeOptions, TGAEncodeOptions, GIFEncodeOptions, DitherMethod, DitherOptions, GainMapEmbedOptions, RenderSVGOptions, SVGResourceOptions, RenderTextOptions, ShadowOptions, OutlineOptions, QuantizeOptions, TransformOptions, TransformMode, FlipDirection, AffineTransform, GradientOptions, LinearGradientOptions, RadialGradientOptions, RoundCornersOptions, FisheyeOptions, TrimOptions } from './image.ts'; +export { Frame } from './frame.ts'; +export type { FrameDisposalMode, FrameOptions } from './frame.ts'; export { GainMap } from './gainmap.ts'; -export type { GainMapOptions, GainMapEncodeOptions } from './gainmap.ts'; -export { GIF } from './gif.ts'; +export type { GainMapOptions, GainMapEncodeOptions, GainMapChannelValues } from './gainmap.ts'; export { Animation } from './animation.ts'; -export type { AnimationOptions, AnimationDecodeOptions, AnimationEncodeOptions, WebPAnimationEncodeOptions, GIFEncodeOptions, APNGEncodeOptions } from './animation.ts'; +export type { AnimationOptions, AnimationCanvasOptions, AnimationEncodeOptions, WebPAnimationEncodeOptions, GIFAnimationEncodeOptions, APNGEncodeOptions } from './animation.ts'; export { AnimationEncoder } from './animation-encoder.ts'; -export type { AnimationEncoderOptions, WebPAnimationEncoderOptions, GIFAnimationEncoderOptions, APNGAnimationEncoderOptions } from './animation-encoder.ts'; -export { TextLayout } from './text-layout.ts'; export type { TextLayoutOptions, WrapStyle, HorizontalAlign, VerticalAlign } from './text-layout.ts'; export { ImageType } from './image-type.ts'; +export { LimitError } from './util/limits.ts'; export type { ImageTypeName } from './image-type.ts'; export type { ToneMapping } from './codecs/hdr.ts'; export type { BinaryData } from './util/mem.ts'; export type { Metadata } from './metadata.ts'; /** - * Decodes any supported image: GIFs are returned as {@link GIF} (an {@link Animation}), animated WebPs as - * {@link Animation}, everything else (including APNGs, as their default image) as {@link Image}. - * {@link Animation.decode} decodes the frames of GIFs, APNGs and WebPs - * @param data The image data - * @param options See {@link AnimationDecodeOptions} (for animations) and {@link DecodeOptions} (for images) + * Decodes any supported image. A file with more than one frame or an explicit animation marker (including a one-frame + * APNG or animated WebP) is returned as an {@link Animation}; otherwise it is an {@link Image}. A one-frame animation + * keeps its timing, offsets and loop metadata. Static formats (PNG, JPEG, AVIF, ...) are Images, and AVIF image + * sequences decode to their first frame, as {@link Image.decode} does. The options are passed on to + * {@link Animation.decode} or {@link Image.decode}. + * @param input The image data + * @param options See {@link DecodeOptions} */ -export function decode(data: BinaryData, options?: AnimationDecodeOptions & DecodeOptions): Promise; -/** - * Decodes any supported image: GIFs are returned as {@link GIF} (an {@link Animation}), animated WebPs as - * {@link Animation}, everything else (including APNGs, as their default image) as {@link Image}. - * {@link Animation.decode} decodes the frames of GIFs, APNGs and WebPs - * @param data The image data - * @param onlyExtractFirstFrame Whether to end animation decoding after the first frame - */ -export function decode(data: BinaryData, onlyExtractFirstFrame?: boolean): Promise; -export function decode(data: BinaryData, onlyFirstFrameOrOptions: boolean | (AnimationDecodeOptions & DecodeOptions) = false): Promise { - const { onlyFirstFrame = false, applyOrientation, maxPixels, toneMapping } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions }; - const type = ImageType.getType(data); - if (type === 'gif') return GIF.decode(data, { onlyFirstFrame, maxPixels }); - if (type === 'webp' && webp.isAnimated(view(data))) return Animation.decode(data, { onlyFirstFrame, maxPixels }); - return Image.decode(data, { applyOrientation, maxPixels, toneMapping }); +export function decode(input: BinaryData, options?: DecodeOptions): Promise; +export async function decode(input: BinaryData, options: DecodeOptions = {}): Promise { + checkOptions(options, 'decode(data, { maxPixels: 1e8 })'); + const bytes = view(input); + const type = ImageType.getType(bytes); + const animated = type === 'gif' || type === 'jxl' || (type === 'webp' && webp.isAnimated(bytes)) || (type === 'png' && png.isAnimated(bytes)); + if (!animated) return Image.decode(input, options); + + const animation = await Animation.decode(input, options); + if (animation.length !== 1 || Animation.__is_animated__(animation)) return animation; + // the only frame, as an image: its pixels and gain map + return animation.frames[0].image; } diff --git a/src/metadata.ts b/src/metadata.ts index f2dca830..c3ef4b5d 100644 --- a/src/metadata.ts +++ b/src/metadata.ts @@ -1,7 +1,19 @@ -import { VERSION } from './version.ts'; import { encode as utf8 } from './util/utf8.ts'; +import { shown } from './util/options.ts'; import * as exif from './codecs/exif.ts'; +/** whether a value is a Date, also one of another realm (an iframe's or Jest's isn't an instance here) */ +function isDate(value: unknown): value is Date { + if (typeof value !== 'object' || value === null) return false; + try { + // (getTime() checks it is a Date: the tag, which any object can claim, doesn't) + Date.prototype.getTime.call(value); + return true; + } catch { + return false; + } +} + /** * Metadata written by the encoders. Each format stores the fields it has a place for: * @@ -13,8 +25,20 @@ import * as exif from './codecs/exif.ts'; * | GIF | software, comment (comment extensions) | * | TGA | author, comment, creation time, software (extension area) | * - * Empty fields are left out + * The Exif and TGA text fields are ASCII in the file format; other characters are written as UTF-8, which readers + * that follow the format show wrongly. PNG text chunks take any text. + * + * Decoding doesn't read metadata: it applies the orientation and the ICC profile to the pixels and drops the rest + * (Exif, XMP, text), so a decoded image is written with only the metadata given to the encoder. + * + * Some formats limit the length: in JPEG the comment and the Exif fields together hold up to 65533 bytes each, and + * longer ones throw a `RangeError` before encoding. TGA cuts the author and the software to 40 bytes and the comment to + * 4 lines of 80 bytes. + * + * Empty fields (and `null` ones) are left out. Without metadata, the files only say which software made them (`software`), so the same + * image always encodes to the same bytes */ + export interface Metadata { /** The image's title */ title?: string; @@ -24,10 +48,17 @@ export interface Metadata { description?: string; /** The image's copyright info */ copyright?: string; - /** The image's creation time. Default: now */ - creationTime?: string | number | Date; - /** The software used to create the image. Default: `'ImageScript vX.X.X'`, `''` leaves it out */ - software?: string; + /** + * The image's creation time (a date, a timestamp or a date string, in the years 1000 to 9999: the formats write + * the year with 4 digits) + * @defaultValue None (`null` leaves it out, too) + */ + creationTime?: string | number | Date | null; + /** + * The software used to create the image + * @defaultValue `'ImageScript'` (without a version), `null` leaves it out + */ + software?: string | null; /** A disclaimer for the image */ disclaimer?: string; /** A warning for the image */ @@ -47,7 +78,7 @@ export interface ResolvedMetadata { author?: string; description?: string; copyright?: string; - creationTime: Date; + creationTime?: Date; software?: string; disclaimer?: string; warning?: string; @@ -62,14 +93,30 @@ const TEXT_FIELDS = ['title', 'author', 'description', 'copyright', 'software', * @ignore */ export function resolveMetadata(metadata: Metadata = {}): ResolvedMetadata { - const { creationTime, software } = metadata || {}; - const time = new Date(creationTime === undefined ? Date.now() : creationTime); - if (isNaN(time.getTime())) throw new RangeError('Invalid creation time'); - - const resolved: ResolvedMetadata = { creationTime: time }; + if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)) + throw new TypeError(`metadata takes an object, like { title: 'Sunset' }, not ${shown(metadata)}`); + const { creationTime, software } = metadata; + const resolved: ResolvedMetadata = {}; + if (creationTime !== undefined && creationTime !== null) { + // (other types than these were turned into a date anyway: true was 1970) + if (!isDate(creationTime) && typeof creationTime !== 'number' && typeof creationTime !== 'string') { + // eslint-disable-next-line no-restricted-syntax -- the one date in the options + throw new TypeError(`creationTime must be a Date, a number or a string, not ${typeof creationTime === 'object' ? shown(creationTime) : typeof creationTime}`); + } + const time = new Date(creationTime); + // eslint-disable-next-line no-restricted-syntax -- the one date in the options + if (isNaN(time.getTime())) throw new RangeError(`creationTime must be a date, a timestamp or a date string, not ${shown(creationTime)}`); + // (the year has 4 digits in Exif and PNG's text, and TGA stores it in 16 bits: years outside of them were written wrapped) + const year = time.getUTCFullYear(); + // eslint-disable-next-line no-restricted-syntax -- the year is part of the one date in the options + if (year < 1000 || year > 9999) throw new RangeError(`creationTime's year must be from 1000 to 9999, not ${year}`); + resolved.creationTime = time; + } for (const key of TEXT_FIELDS) { - const value = key === 'software' && software === undefined ? `ImageScript v${VERSION}` : metadata?.[key]; - if (value) resolved[key] = String(value); + const value = key === 'software' && software === undefined ? 'ImageScript' : metadata[key]; + if (value === undefined || value === null || value === '') continue; + if (typeof value !== 'string') throw new TypeError(`metadata ${key} must be a string, not ${shown(value)}`); + resolved[key] = value; } return resolved; } @@ -84,7 +131,7 @@ export function pngText(m: ResolvedMetadata): Record Author: m.author, Description: m.description, Copyright: m.copyright, - 'Creation Time': m.creationTime.toUTCString(), + 'Creation Time': m.creationTime?.toUTCString(), Software: m.software, Disclaimer: m.disclaimer, Warning: m.warning, @@ -97,7 +144,9 @@ export function pngText(m: ResolvedMetadata): Record * @internal Exif data (a TIFF header and IFDs) for JPEG, WebP, AVIF and JPEG XL * @ignore */ -export function exifData(m: ResolvedMetadata): Uint8Array { +export function exifData(m: ResolvedMetadata): Uint8Array | undefined { + // (an Exif block without any field is left out) + if (!m.description && !m.software && !m.creationTime && !m.author && !m.copyright) return undefined; return exif.encode({ description: m.description, software: m.software, diff --git a/src/render/color.ts b/src/render/color.ts index 16086c62..e47269b9 100644 --- a/src/render/color.ts +++ b/src/render/color.ts @@ -8,6 +8,19 @@ export interface ColorLayer { color: number | null; } +/** the most pixels a bitmap glyph may have: emoji fonts have strikes of 160 at most, one that said 16383x16383 took 1 GB */ +export const MAX_BITMAP_GLYPH_PIXELS = 2048 * 2048; + +/** + * The pixels a bitmap glyph's PNG says it has (its header), what decoding it costs whether it succeeds or not; NaN if it + * isn't a PNG + */ +export function bitmapPixels(png: Uint8Array): number { + if (png.length < 24 || png[12] !== 0x49 || png[13] !== 0x48 || png[14] !== 0x44 || png[15] !== 0x52) return NaN; + const view = new DataView(png.buffer, png.byteOffset, png.length); + return view.getUint32(16) * view.getUint32(20); +} + /** a glyph's PNG and where it goes, in pixels of its strike */ export interface BitmapGlyph { png: Uint8Array; @@ -54,7 +67,7 @@ export function parseColorLayers(font: Font): ((glyph: number) => ColorLayer[] | result = null; // base glyph records are sorted by glyph for (let lo = 0, hi = baseCount - 1; lo <= hi;) { - const mid = lo + hi >> 1, record = bases + mid * 6, id = font.u16(record); + const mid = lo + hi >>> 1, record = bases + mid * 6, id = font.u16(record); if (id < glyph) lo = mid + 1; else if (id > glyph) hi = mid - 1; else { @@ -95,7 +108,9 @@ function parseSbix(font: Font, size: number): ((glyph: number) => BitmapGlyph | const sbix = font.tables.sbix?.offset; if (sbix === undefined) return null; const strikes = Array.from({ length: font.u32(sbix + 4) }, (_, i) => sbix + font.u32(sbix + 8 + i * 4)); - const index = closestStrike(strikes.map(strike => font.u16(strike)), size); + const ppems = strikes.map(strike => font.u16(strike)); + if (ppems.includes(0)) throw new Error('Font: damaged sbix table (a strike of 0 pixels per em)'); + const index = closestStrike(ppems, size); if (index < 0) return null; const strike = strikes[index], ppem = font.u16(strike); @@ -127,7 +142,10 @@ function parseCBDT(font: Font, size: number): ((glyph: number) => BitmapGlyph | const cblc = font.tables.CBLC?.offset, cbdt = font.tables.CBDT?.offset; if (cblc === undefined || cbdt === undefined) return null; - const ppems = Array.from({ length: font.u32(cblc + 4) }, (_, i) => font.u8(cblc + 8 + i * 48 + 45)); + // (u8() doesn't throw past the end of the font, so a damaged count would only run out of memory) + const strikes = font.count(font.u32(cblc + 4), cblc + 8, 48, 'CBLC table'); + const ppems = Array.from({ length: strikes }, (_, i) => font.u8(cblc + 8 + i * 48 + 45)); + if (ppems.includes(0)) throw new Error('Font: damaged CBLC table (a strike of 0 pixels per em)'); const index = closestStrike(ppems, size); if (index < 0) return null; const strike = cblc + 8 + index * 48, strikePpem = ppems[index]; diff --git a/src/render/colr.ts b/src/render/colr.ts index 151a2da1..15c6c069 100644 --- a/src/render/colr.ts +++ b/src/render/colr.ts @@ -58,13 +58,13 @@ export function parsePaintGlyphs(font: Font): PaintGlyphs | null { const baseList = font.u32(colr + 14) ? colr + font.u32(colr + 14) : 0; if (!baseList) return null; const clipList = font.u32(colr + 22) ? colr + font.u32(colr + 22) : 0; - const count = font.u32(baseList), clips = clipList ? font.u32(clipList + 1) : 0; + const count = font.count(font.u32(baseList), baseList + 4, 6, 'COLR table'), clips = clipList ? font.count(font.u32(clipList + 1), clipList + 5, 7, 'COLR table') : 0; return { paint: glyph => { // records sorted by glyph for (let lo = 0, hi = count - 1; lo <= hi;) { - const mid = lo + hi >> 1, record = baseList + 4 + mid * 6, id = font.u16(record); + const mid = lo + hi >>> 1, record = baseList + 4 + mid * 6, id = font.u16(record); if (id < glyph) lo = mid + 1; else if (id > glyph) hi = mid - 1; else return baseList + font.u32(record + 2); @@ -73,7 +73,7 @@ export function parsePaintGlyphs(font: Font): PaintGlyphs | null { }, clip: glyph => { for (let lo = 0, hi = clips - 1; lo <= hi;) { - const mid = lo + hi >> 1, record = clipList + 5 + mid * 7; + const mid = lo + hi >>> 1, record = clipList + 5 + mid * 7; if (font.u16(record + 2) < glyph) lo = mid + 1; else if (font.u16(record) > glyph) hi = mid - 1; else { @@ -523,7 +523,7 @@ function composite(mode: number, source: Layer, backdrop: Layer): Layer { else src.fill(0); const as = src[3], ab = d[o + 3]; // Porter-Duff: result = source * fa + backdrop * fb - let fa = 0, fb = 0; + let fa: number, fb: number; switch (mode) { case 0: fa = 0; fb = 0; break; case 1: fa = 1; fb = 0; break; diff --git a/src/render/filter.ts b/src/render/filter.ts index b3b6a79e..005d7cc9 100644 --- a/src/render/filter.ts +++ b/src/render/filter.ts @@ -209,15 +209,28 @@ const scaleOf = (m: Matrix): [number, number] => [Math.hypot(m[0], m[1]), Math.h * Applies a filter to pixels rendered with a matrix (user space to the pixels), in place; an invalid region leaves * them transparent (like resvg's apply) */ -export function applyFilter(filter: Filter, ts: Matrix, source: Pixmap): void { - const result = filterResult(filter, ts, source); +export function applyFilter(filter: Filter, ts: Matrix, source: Pixmap, budget: FilterBudget = UNBOUNDED): void { + const result = filterResult(filter, ts, source, budget); source.data.fill(0); if (!result) return; const { image, region } = result; draw(source, inColorSpace(image, false).pixmap, region.x, region.y); } -function filterResult(filter: Filter, ts: Matrix, full: Pixmap): { image: Result, region: Rect } | null { +/** + * What a filter may cost: `work(pixels)` is called before a primitive works on that many pixels, `keep(pixels)` for each + * result the filter keeps (for `result=` references) until it is done, and `free(pixels)` with all of them then. They + * throw to stop a filter that costs too much + */ +export interface FilterBudget { + work(pixels: number): void; + keep(pixels: number): void; + free(pixels: number): void; +} + +const UNBOUNDED: FilterBudget = { work() {}, keep() {}, free() {} }; + +function filterResult(filter: Filter, ts: Matrix, full: Pixmap, budget: FilterBudget): { image: Result, region: Rect } | null { // the filter region, within the pixels const r = intRect(filter.rect, ts); const x0 = Math.max(r.x, 0), y0 = Math.max(r.y, 0), x1 = Math.min(r.x + r.width, full.width), y1 = Math.min(r.y + r.height, full.height); @@ -244,8 +257,30 @@ function filterResult(filter: Filter, ts: Matrix, full: Pixmap): { image: Result return input('SourceGraphic'); }; + let kept = 0; + try { + return runPrimitives(filter, matrix, region, outputRegion, input, results, pixels => { + budget.keep(pixels); + kept += pixels; + }, budget); + } finally { + budget.free(kept); + } +} + +// what a primitive costs per pixel of its region, in passes over it (a blur or a morphology is about one): a +// convolution its kernel's taps (a 3x3 kernel is one pass), turbulence its octaves, a merge its nodes +function cost(kind: Kind): number { + if (kind.type === 'convolve') return Math.max(1, kind.columns * kind.rows / 9); + if (kind.type === 'turbulence') return Math.max(1, kind.octaves); + if (kind.type === 'merge') return Math.max(1, kind.inputs.length); + return 1; +} + +function runPrimitives(filter: Filter, matrix: Matrix, region: Rect, outputRegion: Rect, input: (value: Input) => Result, results: Array<{ name: string, image: Result }>, keep: (pixels: number) => void, budget: FilterBudget): { image: Result, region: Rect } | null { for (const primitive of filter.primitives) { const { kind } = primitive; + budget.work(region.width * region.height * cost(kind)); let subregion = intRect(primitive.rect, matrix); if (kind.type === 'offset' && typeof kind.input === 'object') { const name = kind.input.result; @@ -263,6 +298,7 @@ function filterResult(filter: Filter, ts: Matrix, full: Pixmap): { image: Result if (kind.type !== 'offset') clearOutside(pixmap, subregion); result = { pixmap, region: subregion, linear: result.linear }; } + keep(result.pixmap.width * result.pixmap.height); results.push({ name: primitive.result, image: result }); } diff --git a/src/render/font.ts b/src/render/font.ts index dd7355d3..50bc7b42 100644 --- a/src/render/font.ts +++ b/src/render/font.ts @@ -105,6 +105,7 @@ export class Font { const head = this.tables.head.offset; this.unitsPerEm = this.u16(head + 18); + if (!this.unitsPerEm) throw new Error('Font: damaged head table (0 units per em)'); this.indexToLocFormat = this.i16(head + 50); const hhea = this.tables.hhea.offset; @@ -168,9 +169,19 @@ export class Font { const base = Object.getPrototypeOf(this) instanceof Font ? Object.getPrototypeOf(this) as Font : this; const key = coords.join(','); const cached = base.instances?.get(key); - if (cached) return cached; + if (cached) { + // (the least recently used is the one dropped: used again, an instance goes to the back) + base.instances!.delete(key); + base.instances!.set(key, cached); + return cached; + } const instance = Object.create(base) as Font; - (base.instances ??= new Map()).set(key, instance); + // (at most 64 instances a font (a chart of 5 sizes and 4 weights is 20, with an optical size axis), the least + // recently used dropped: a new weight each render kept one for each, with its sizes, until the process ran out of + // memory) + const instances = base.instances ??= new Map(); + if (instances.size >= 64) instances.delete(instances.keys().next().value as string); + instances.set(key, instance); instance.coords = coords; instance.outlineCache = new Map(); // (the metrics MVAR varies) @@ -201,6 +212,16 @@ export class Font { u32(o: number): number { return this.view.getUint32(o); } i32(o: number): number { return this.view.getInt32(o); } + /** + * A count read from the font (`what` is the table it is in, for the error), checked against the font: it can't be + * more than the records of `size` bytes that fit after `start`. Counts of damaged fonts can be up to 2^32 - 1, which + * made searches over them endless and lists of them run out of memory + */ + count(count: number, start: number, size: number, what: string): number { + if (start + count * size > this.data.length) throw new Error(`Font: damaged ${what}`); + return count; + } + /** * @param {number} codepoint * @return {number} glyph index, 0 (.notdef) if the font has no glyph for it @@ -377,7 +398,7 @@ export class Font { private components(offset: number): { components: Array<{ glyph: number, flags: number, arg1: number, arg2: number, matrix: [number, number, number, number] }>, end: number } { const components = []; const f2dot14 = (o: number): number => this.i16(o) / 16384; - let p = offset + 10, flags = 0; + let p = offset + 10, flags: number; do { flags = this.u16(p); const glyph = this.u16(p + 2); @@ -590,7 +611,7 @@ function parseCmap(font: Font, offset: number): (codepoint: number) => number { // binary search over segment end codes let lo = 0, hi = segments - 1; while (lo < hi) { - const mid = lo + hi >> 1; + const mid = lo + hi >>> 1; if (font.u16(ends + mid * 2) < c) lo = mid + 1; else hi = mid; } @@ -606,11 +627,11 @@ function parseCmap(font: Font, offset: number): (codepoint: number) => number { return glyph ? glyph + delta & 0xffff : 0; }; } else { - const groups = font.u32(table + 12); + const groups = font.count(font.u32(table + 12), table + 16, 12, 'cmap table'); lookup = (c: number): number => { let lo = 0, hi = groups - 1; while (lo <= hi) { - const mid = lo + hi >> 1; + const mid = lo + hi >>> 1; const group = table + 16 + mid * 12; if (c < font.u32(group)) hi = mid - 1; else if (c > font.u32(group + 4)) lo = mid + 1; @@ -637,20 +658,20 @@ function parseVariations(font: Font, offset: number): ((codepoint: number, selec } if (table < 0) return null; const u24 = (o: number): number => font.u8(o) << 16 | font.u16(o + 1); - const records = font.u32(table + 6); + const records = font.count(font.u32(table + 6), table + 10, 11, 'cmap table'); return (codepoint, selector) => { let lo = 0, hi = records - 1; while (lo <= hi) { - const mid = lo + hi >> 1, record = table + 10 + mid * 11, vs = u24(record); + const mid = lo + hi >>> 1, record = table + 10 + mid * 11, vs = u24(record); if (vs < selector) lo = mid + 1; else if (vs > selector) hi = mid - 1; else { const defaults = font.u32(record + 3), others = font.u32(record + 7); if (others) { const o = table + others; - let l = 0, h = font.u32(o) - 1; + let l = 0, h = font.count(font.u32(o), o + 4, 5, 'cmap table') - 1; while (l <= h) { - const m = l + h >> 1, u = u24(o + 4 + m * 5); + const m = l + h >>> 1, u = u24(o + 4 + m * 5); if (u < codepoint) l = m + 1; else if (u > codepoint) h = m - 1; else return font.u16(o + 4 + m * 5 + 3); @@ -658,9 +679,9 @@ function parseVariations(font: Font, offset: number): ((codepoint: number, selec } if (defaults) { const o = table + defaults; - let l = 0, h = font.u32(o) - 1; + let l = 0, h = font.count(font.u32(o), o + 4, 4, 'cmap table') - 1; while (l <= h) { - const m = l + h >> 1, start = u24(o + 4 + m * 4); + const m = l + h >>> 1, start = u24(o + 4 + m * 4); if (codepoint < start) h = m - 1; else if (codepoint > start + font.u8(o + 4 + m * 4 + 3)) l = m + 1; else return -1; @@ -684,7 +705,7 @@ export function parseCoverage(font: Font, table: number): (glyph: number) => num return glyph => { let lo = 0, hi = count - 1; while (lo <= hi) { - const mid = lo + hi >> 1; + const mid = lo + hi >>> 1; if (format === 1) { const value = font.u16(table + 4 + mid * 2); if (value < glyph) lo = mid + 1; @@ -713,7 +734,7 @@ export function parseClassDef(font: Font, table: number): (glyph: number) => num return glyph => { let lo = 0, hi = count - 1; while (lo <= hi) { - const mid = lo + hi >> 1; + const mid = lo + hi >>> 1; const range = table + 4 + mid * 6; if (font.u16(range + 2) < glyph) lo = mid + 1; else if (font.u16(range) > glyph) hi = mid - 1; @@ -745,7 +766,7 @@ function parseKern(font: Font, kern: number): ((left: number, right: number) => for (const { pairs, start } of tables) { let lo = 0, hi = pairs - 1; while (lo <= hi) { - const mid = lo + hi >> 1; + const mid = lo + hi >>> 1; const pair = start + mid * 6; const value = font.u32(pair); if (value < key) lo = mid + 1; @@ -795,6 +816,7 @@ function parseCFF(font: Font, base: number): CFF { const strings = readIndex(topDicts.end); const globalSubrs = readIndex(strings.end).items; + if (!topDicts.items.length) throw new Error('Font: CFF font has no Top DICT'); const top = parseDict(topDicts.items[0]); if (!top[17]) throw new Error('Font: CFF font has no charstrings'); @@ -811,19 +833,26 @@ function parseCFF(font: Font, base: number): CFF { // CID-keyed fonts select a private dict per glyph let privateFor: CFF['privateFor']; if (top[1236]) { + if (!top[1237]) throw new Error('Font: CID-keyed CFF font has no FDSelect'); const fdArray = readIndex(base + top[1236][0]).items.map(dict => readPrivate(parseDict(dict)[18])); const fdSelect = base + top[1237][0]; const format = data[fdSelect]; + // (an FDSelect that names a private dict the FDArray doesn't have is damaged data) + const fd = (index: number): { subrs: Uint8Array[] } => { + const dict = fdArray[index]; + if (!dict) throw new Error(`Font: damaged CFF font (glyph selects private dict ${index} of ${fdArray.length})`); + return dict; + }; privateFor = glyph => { - if (format === 0) return fdArray[data[fdSelect + 1 + glyph]]; + if (format === 0) return fd(data[fdSelect + 1 + glyph]); const ranges = font.u16(fdSelect + 1); for (let i = 0; i < ranges; i++) { const r = fdSelect + 3 + i * 3; const next = font.u16(r + 3); - if (glyph >= font.u16(r) && glyph < next) return fdArray[data[r + 2]]; + if (glyph >= font.u16(r) && glyph < next) return fd(data[r + 2]); } - return fdArray[0]; + return fd(0); }; } else { const shared = readPrivate(top[18]); @@ -853,6 +882,8 @@ function parseDict(bytes: Uint8Array): Dict { } else if (b0 === 30) { let s = ''; for (let done = false; !done;) { + // (a number that runs past the dict has no terminator: it can't be read) + if (i >= bytes.length) throw new Error('Font: damaged CFF dict (a real number without its end)'); const byte = bytes[i++]; for (const nibble of [byte >> 4, byte & 15]) { if (nibble === 15) { @@ -1113,8 +1144,17 @@ function fromWOFF(data: Uint8Array): Uint8Array { const tables: Array<{ tag: number, data: Uint8Array, checksum: number }> = []; for (let i = 0; i < count; i++) { const e = 44 + i * 20, offset = view.getUint32(e + 4), compressed = view.getUint32(e + 8), length = view.getUint32(e + 12); + if (offset + compressed > data.length) throw new Error('Font: damaged or truncated font data'); const raw = data.subarray(offset, offset + compressed); - tables.push({ tag: view.getUint32(e), checksum: view.getUint32(e + 16), data: compressed < length ? decompress(raw, length).subarray(0, length) : raw }); + let table = raw; + if (compressed < length) { + try { + table = decompress(raw, length).subarray(0, length); + } catch (err) { + throw new Error('Font: damaged WOFF table', { cause: err }); + } + } + tables.push({ tag: view.getUint32(e), checksum: view.getUint32(e + 16), data: table }); } const header = 12 + count * 16; let size = header; diff --git a/src/render/layout.ts b/src/render/layout.ts index 52251440..ecfb0d74 100644 --- a/src/render/layout.ts +++ b/src/render/layout.ts @@ -540,7 +540,7 @@ export class LayoutTable { // their defaults) private featureVariations(table: number): void { const f = this.font; - for (let i = 0, count = f.u32(table + 4); i < count; i++) { + for (let i = 0, count = f.count(f.u32(table + 4), table + 8, 8, 'GSUB table'); i < count; i++) { const record = table + 8 + i * 8; const conditions = f.u32(record), substitution = f.u32(record + 4); let matches = true; @@ -962,7 +962,7 @@ export class LayoutTable { const second = buffer.info[pos].codepoint; let lo = 0, hi = count - 1, record = -1; while (lo <= hi) { - const mid = lo + hi >> 1, g = f.u16(set + 2 + mid * recordSize); + const mid = lo + hi >>> 1, g = f.u16(set + 2 + mid * recordSize); if (g < second) lo = mid + 1; else if (g > second) hi = mid - 1; else { @@ -1123,7 +1123,7 @@ export class LayoutTable { if (!isMarkGlyph(info[it.idx])) return false; const j = it.idx; const id1 = ligId(buffer.cur()), id2 = ligId(info[j]), comp1 = ligComp(buffer.cur()), comp2 = ligComp(info[j]); - let good = false; + let good: boolean; if (id1 === id2) good = id1 === 0 || comp1 === comp2; else good = id1 > 0 && !comp1 || id2 > 0 && !comp2; if (!good) return false; diff --git a/src/render/linebreak.ts b/src/render/linebreak.ts index a2da5ab8..54664450 100644 --- a/src/render/linebreak.ts +++ b/src/render/linebreak.ts @@ -51,18 +51,15 @@ export function lineBreaks(codepoints: ArrayLike): Uint8Array { } } - // the character before index i, skipping attached marks (-1 at the start) - const before = (i: number): number => { - let j = i - 1; - while (j >= 0 && attached[j]) j--; - return j; - }; - // the character from index i on that isn't an attached mark (n at the end) - const after = (i: number): number => { - let j = i; - while (j < n && attached[j]) j++; - return j; - }; + // the character before index i, skipping attached marks (-1 at the start), and the one from index i on that isn't + // an attached mark (n at the end): precomputed, a walk for each index took quadratic time for many marks + const previous = new Int32Array(n + 1), next = new Int32Array(n + 1); + previous[0] = -1; + for (let i = 1; i <= n; i++) previous[i] = attached[i - 1] ? previous[i - 1] : i - 1; + next[n] = n; + for (let i = n - 1; i >= 0; i--) next[i] = attached[i] ? next[i + 1] : i; + const before = (i: number): number => i <= 0 ? -1 : previous[Math.min(i, n)]; + const after = (i: number): number => i >= n ? n : next[Math.max(i, 0)]; // the character before index i, skipping spaces (and attached marks) const beforeSpaces = (i: number): number => { let j = before(i); diff --git a/src/render/segment.ts b/src/render/segment.ts index 75c2f89c..8eba3506 100644 --- a/src/render/segment.ts +++ b/src/render/segment.ts @@ -17,7 +17,7 @@ export function graphemeBoundaries(codepoints: ArrayLike): Uint8Array { pictographic[i] = valueIndex(extendedPictographic, codepoints[i]) ? 1 : 0; } // GB11: whether an Extended_Pictographic Extend* is before, and with ZWJ; GB12/13: the regional indicators before - let emoji = false, emojiZWJ = false, ri = 0; + let emoji = false, emojiZWJ: boolean, ri = 0; // GB9c: whether a linker is before (with InCB=Extend characters after it) let linker = false; for (let i = 1; i < n; i++) { diff --git a/src/render/shapers/hangul.ts b/src/render/shapers/hangul.ts index 4ada0b79..66e858c3 100644 --- a/src/render/shapers/hangul.ts +++ b/src/render/shapers/hangul.ts @@ -112,7 +112,7 @@ function preprocessText(_plan: Plan, buffer: Buffer, font: ShapeFont): void { let i = start; info[i++].category = Jamo.LJMO; info[i++].category = Jamo.VJMO; - if (i < end) info[i++].category = Jamo.TJMO; + if (i < end) info[i].category = Jamo.TJMO; buffer.mergeOutClusters(start, end); continue; } diff --git a/src/render/svg-text.ts b/src/render/svg-text.ts index 425d0782..8f57d37b 100644 --- a/src/render/svg-text.ts +++ b/src/render/svg-text.ts @@ -16,6 +16,7 @@ import { loadFont } from './text.ts'; import { parseColorLayers, parseBitmaps, ColorLayer, BitmapGlyph } from './color.ts'; import { parsePaintGlyphs, PaintGlyphs } from './colr.ts'; import { Matrix, multiply } from '../util/matrix.ts'; +import { LimitError } from '../util/limits.ts'; export interface BBox { x: number; @@ -79,8 +80,14 @@ function names(font: Font, ids: number): string[] { /** * A font's face: its names, weight, style and stretch from its tables, unless given (@font-face descriptors), and - * the generic families its OS/2 and post tables say it fits + * the generic families its OS/2 and post tables say it fits. Null for a font that can't be read, as browsers leave out + * such a font of an SVG */ +/** appends items to an array (a loop, not a spread: long text has more glyphs than a call takes arguments) */ +function append(target: T[], items: readonly T[]): void { + for (const item of items) target.push(item); +} + export function fontFace(data: Uint8Array, descriptors?: { family?: string, weight?: number, style?: FontStyle }): FontFace | null { let font: Font; try { @@ -90,6 +97,44 @@ export function fontFace(data: Uint8Array, descriptors?: { family?: string, weig } const cached = !descriptors && faces.get(font); if (cached) return cached; + // (reading past the end of a damaged font throws a RangeError: the font isn't used, like one that doesn't load) + try { + return describeFace(font, descriptors); + } catch (err) { + if (err instanceof RangeError && !(err instanceof LimitError)) return null; + throw err; + } +} + +/** + * The face of a font the caller gave (renderSVG's `font` option): one that can't be read throws, like in renderText, + * instead of being left out without a word + */ +export function givenFontFace(data: Uint8Array): FontFace { + let font: Font; + try { + font = loadFont(data); + } catch (err) { + throw damaged(err); + } + const cached = faces.get(font); + if (cached) return cached; + try { + return describeFace(font); + } catch (err) { + throw damaged(err); + } +} + +/** + * The error for a font the caller gave that turned out damaged while it was read: reading past its end throws a + * RangeError, which becomes an Error like the other damage renderText reports (anything else is returned as it is) + */ +export function damaged(err: unknown): unknown { + return err instanceof RangeError && !(err instanceof LimitError) ? new Error('Font: damaged (a table lies outside of the font)', { cause: err }) : err; +} + +function describeFace(font: Font, descriptors?: { family?: string, weight?: number, style?: FontStyle }): FontFace { const os2 = font.tables['OS/2'] && font.tables['OS/2'].length >= 78 ? font.tables['OS/2'].offset : -1; const post = font.tables.post && font.tables.post.length >= 16 ? font.tables.post.offset : -1; @@ -224,10 +269,11 @@ export function variedFace(face: FontFace, query: FontQuery, fontSize: number): /** * The face for a span: the first family that has faces (embedded ones before given ones; a generic family is the - * first face fitting it and the faces of its family), else the first face's family + * first face fitting it and the faces of its family), else the family of `fallback` (the caller's first font, like a + * browser's default font; else the first face) */ -export function matchFont(fonts: FontFace[], query: FontQuery): FontFace | null { - if (!fonts.length) return null; +export function matchFont(fonts: FontFace[], query: FontQuery, fallback: FontFace | undefined = fonts[0]): FontFace | null { + if (!fonts.length || !fallback) return null; const family = (name: string): FontFace[] => fonts.filter(f => f.families.includes(name)); for (const name of query.families) { let candidates: FontFace[]; @@ -237,7 +283,7 @@ export function matchFont(fonts: FontFace[], query: FontQuery): FontFace | null } else candidates = family(name); if (candidates.length) return bestMatch(candidates, query); } - return bestMatch(family(fonts[0].families[0]).length ? family(fonts[0].families[0]) : [fonts[0]], query); + return bestMatch(family(fallback.families[0]).length ? family(fallback.families[0]) : [fallback], query); } // a fallback face that has a grapheme's characters: not tried yet, of a compatible style (like usvg's) @@ -389,6 +435,8 @@ export interface TextInput { vertical: boolean; /** the scale the text is drawn at, for the precision of text on paths */ scale: number; + /** called with the number of commands of each glyph outline before it is placed, to bound long texts */ + charge?: (commands: number) => void; } export interface SpanOutput { @@ -456,7 +504,19 @@ function upright(u: number): boolean { || (u >= 0x2460 && u <= 0x24ff) || (u >= 0x2600 && u <= 0x27bf && u !== 0x2771 && u !== 0x2770); } -const spanAt = (chunk: ChunkInput, i: number): SpanInput | undefined => chunk.spans.find(s => i >= s.start && i < s.end); +// (the spans of a chunk are disjoint: found by a binary search over their starts, kept per chunk, as a find over them +// made many spans, a tspan each, quadratic) +const sortedSpans = new WeakMap(); +const spanAt = (chunk: ChunkInput, i: number): SpanInput | undefined => { + let spans = sortedSpans.get(chunk.spans) as SpanInput[] | undefined; + if (!spans) sortedSpans.set(chunk.spans, spans = chunk.spans.slice().sort((a, b) => a.start - b.start)); + let low = 0, high = spans.length - 1, found = -1; + while (low <= high) { + const mid = (low + high) >>> 1; + if (spans[mid].start <= i) { found = mid; low = mid + 1; } else high = mid - 1; + } + return found >= 0 && i < spans[found].end ? spans[found] : undefined; +}; /** * Shapes a chunk (in visual order): runs of one embedding level, script and features, and of the span faces or one @@ -497,7 +557,7 @@ function shapeChunk(chunk: ChunkInput, fonts: FontFace[], primary: Map(chunk: ChunkInput, fonts: FontFace[], primary: Map(chunk: ChunkInput, fonts: FontFace[], primary: Map v > c) ?? re; const other = faceOf[c] && others.get(faceOf[c]); - if (!other) glyphs.push(...shaped.slice(i, j)); + if (!other) append(glyphs, shaped.slice(i, j)); else { const own = other.filter(g => g.cluster >= c && g.cluster < end); const before = other.reduce((m, g) => g.cluster <= c ? Math.max(m, g.cluster) : m, -1); - if (own.length) glyphs.push(...own); - else if (!(before >= 0 && before < c)) glyphs.push(...shaped.slice(i, j)); + if (own.length) append(glyphs, own); + else if (!(before >= 0 && before < c)) append(glyphs, shaped.slice(i, j)); } i = j; } @@ -959,11 +1019,11 @@ function rectPath(m: Matrix, x: number, y: number, w: number, h: number): PathCo * text-anchor, or along a path) and shifted to their baselines; its spans become outlines with their decorations * @returns null without fonts or anything to show */ -export function layOutText(text: TextInput, fonts: FontFace[]): TextOutput | null { +export function layOutText(text: TextInput, fonts: FontFace[], fallback: FontFace | undefined = fonts[0]): TextOutput | null { if (!fonts.length) return null; const primary = new Map, FontFace>(); for (const chunk of text.chunks) for (const span of chunk.spans) { - const face = matchFont(fonts, span.font); + const face = matchFont(fonts, span.font, fallback); if (face) primary.set(span, variedFace(face, span.font, span.fontSize)); } @@ -998,6 +1058,21 @@ export function layOutText(text: TextInput, fonts: FontFace[]): TextOutput const position = chunk.path ? positionOnPath(text, chunk, clusters, shiftOf) : positionLinear(text, chunk, clusters); const textMatrix = text.vertical && !chunk.path ? rotate(IDENTITY, 90, x, y) : IDENTITY; + // the clusters of each span, by their index (the spans are disjoint, in order): a span looks at its own, not at + // all of the chunk's, which took quadratic time for many spans (a tspan each) + const owned = new Map, number[]>(), ordered = chunk.spans.slice().sort((a, b) => a.start - b.start); + clusters.forEach((c, i) => { + let low = 0, high = ordered.length - 1, found = -1; + while (low <= high) { + const mid = (low + high) >>> 1; + if (ordered[mid].start <= c.start) { found = mid; low = mid + 1; } else high = mid - 1; + } + if (found < 0 || c.start >= ordered[found].end) return; + const list = owned.get(ordered[found]); + if (list) list.push(i); else owned.set(ordered[found], [i]); + }); + // (the bounding box of all clusters, from the metrics, is the same for spans with the same shift) + const boxed = new Set(); for (const span of chunk.spans) { const face = primary.get(span); if (!face) continue; @@ -1009,13 +1084,16 @@ export function layOutText(text: TextInput, fonts: FontFace[]): TextOutput // decorations: one line per run of the span's clusters without relative shifts between them const runs: Array<{ width: number, transform: Matrix }> = []; - let current: { width: number, transform: Matrix } | null = null; - for (const c of clusters) { - if (c.start >= span.start && c.start < span.end) { - if (current && c.hasRelativeShift) current = null; - if (!current) runs.push(current = { width: c.advance, transform: c.transform }); - else current.width += c.advance; - } else current = null; + let current: { width: number, transform: Matrix } | null = null, previous = -2; + const own = owned.get(span) ?? []; + for (const i of own) { + const c = clusters[i]; + // (a cluster of another span between two of this one ends the run) + if (i !== previous + 1) current = null; + previous = i; + if (current && c.hasRelativeShift) current = null; + if (!current) runs.push(current = { width: c.advance, transform: c.transform }); + else current.width += c.advance; } const decoration = (paint: S | null, offset: number, list: Array<{ path: PathCommand[], paint: S }>): void => { if (!paint || !runs.length) return; @@ -1031,18 +1109,29 @@ export function layOutText(text: TextInput, fonts: FontFace[]): TextOutput decoration(span.lineThrough, text.vertical ? 0 : -face.lineThroughPosition * s, out.after); let any = false; - for (const c of clusters) { + const shift = chunk.path ? 0 : shiftOf(span); + if (!boxed.has(shift)) { + boxed.add(shift); + for (const c of clusters) { + if (!c.visible) continue; + // (the bounding box from the metrics, of all clusters) + extend(rectPath(multiply(spanMatrix, multiply(c.transform, c.pathTransform)), 0, -c.ascent, c.advance > 0 ? c.advance : 1, c.ascent - c.descent)); + } + } + for (const i of own) { + const c = clusters[i]; if (!c.visible) continue; - // (the bounding box from the metrics, of all clusters) const m = multiply(spanMatrix, multiply(c.transform, c.pathTransform)); - extend(rectPath(m, 0, -c.ascent, c.advance > 0 ? c.advance : 1, c.ascent - c.descent)); - if (c.start < span.start || c.start >= span.end) continue; any = true; for (const g of c.glyphs) { const gs = c.fontSize / g.face.font.unitsPerEm, matrix = scale(translate(scale(m, gs, gs), g.x, -g.y), 1, -1); const kind = colorKind(g.face, g.glyph, c.fontSize); if (kind) out.colors.push({ face: g.face, glyph: g.glyph, kind, fontSize: c.fontSize, matrix }); - else placeOutline(out.glyphs, g.face.font.outline(g.glyph), matrix); + else { + const outline = g.face.font.outline(g.glyph); + text.charge?.(outline.length); + placeOutline(out.glyphs, outline, matrix); + } } } if (any || out.before.length || out.after.length) spans.push(out); diff --git a/src/render/svg.ts b/src/render/svg.ts index 5e421eb5..ff0bbad7 100644 --- a/src/render/svg.ts +++ b/src/render/svg.ts @@ -4,7 +4,8 @@ * ${text(2000)}`, {maxPixels: 100})], + // 64 glyphs from a strike at ppem 1 in a 10x10 box, at 3 sizes of one font: the scaled glyphs were kept with the + // font (1 GB a size, never given back) + ['64 scaled glyphs at 3 sizes', async () => { + const data = font('a0-p1-64'); + for (const size of [16, 17, 18]) await Image.renderText(text(64), {font: data, size, width: 10, height: 10, maxPixels: 100}).catch(err => { + if (!(err instanceof LimitError)) throw err; + }); + }], + // the rasters of outline glyphs at a huge size were kept with the font: 62 letters at size 6000 in a 10x10 box + // kept 774 MB (24 of them over 280 MB), a size more ran out of memory + ['24 huge letters', async () => { + const data = fs.readFileSync(`${__dirname}/fonts/opensans bold.ttf`); + for (const size of [6000]) for (const c of 'ABCDEFGHIJKLMNOPQRSTUVWX') await Image.renderText(c, {font: data, size, width: 10, height: 10, maxPixels: 100}); + }], + // color glyphs (COLR) were kept for every text color: a new color each render grew without end + ['color glyphs in 200 colors', async () => { + const data = fs.readFileSync(`${__dirname}/fonts/noto colrv1 subset.ttf`); + for (let i = 0; i < 200; i++) await Image.renderText('\u{1F600}', {font: data, size: 500, width: 10, height: 10, maxPixels: 100, color: ((i * 0x01020300 + 0x10000000) | 0xff) >>> 0}); + }], + // glyphs too large to keep, over each other (no advance) 1000 times at size 8000: drawn again each time, 260 s + ['2000 huge glyphs without advance', () => Image.renderText(text(2).repeat(1000), {font: font('zero'), size: 8000, width: 10, height: 10, maxPixels: 100})], + ].filter(([name]) => !process.env.NODE_V8_COVERAGE || !/huge|colors/.test(name))) { + // (not under coverage: the huge cases take most of what a test may take there) + collect?.(); + const begin = Date.now(), before = process.memoryUsage().arrayBuffers; + const result = await run().then(() => 'ok', err => err); + if (result !== 'ok' && !(result instanceof LimitError)) panic(`${name}: ${result}`); + if (Date.now() - begin > 20000 * slack) panic(`${name}: took ${Date.now() - begin} ms`); + globalThis.gc?.(); + collect?.(); + // (the rasters of a render that weren't kept are freed later, not on the collection: that case's check is its time) + if (collect && !name.startsWith('2000 huge') && process.memoryUsage().arrayBuffers - before > 128 * 2 ** 20) panic(`${name}: kept ${(process.memoryUsage().arrayBuffers - before) >> 20} MB`); + } +})(); diff --git a/tests/bmp.js b/tests/bmp.js index 88a501a9..cc5e0691 100644 --- a/tests/bmp.js +++ b/tests/bmp.js @@ -1,6 +1,6 @@ const fs = require('fs').promises; const crypto = require('crypto'); -const {Image, ImageType} = require('..'); +const {Image, ImageType, Colors, LimitError} = require('..'); const panic = message => { console.error(message); @@ -55,18 +55,18 @@ const expected = { if (sha(jpeg) !== expected.rgb24jpeg) panic('the embedded JPEG decodes differently than by itself'); // damaged files throw, or decode as far as they can - for (const [name, error] of [['shortfile', /truncated/], ['badbitcount', /bit depth/], ['reallybig', /too large/]]) { - if (!await Image.decode(await fs.readFile(`./tests/bmp/${name}.bmp`)).then(() => false, e => error.test(e.message))) panic(`${name} should throw ${error}`); + for (const [name, type] of [['shortfile', Error], ['badbitcount', Error], ['reallybig', LimitError]]) { + if (!await Image.decode(await fs.readFile(`./tests/bmp/${name}.bmp`)).then(() => false, e => e instanceof type)) panic(`${name} should throw a ${type.name}`); } for (const name of ['badrle4', 'pal8badindex']) await Image.decode(await fs.readFile(`./tests/bmp/${name}.bmp`)); // encoding: the smallest bit depth that holds the image, alpha with a version 4 header const cases = [ [new Image(13, 5).fill((x, y) => (x + y) & 1 ? 0xffffffff : 0x000000ff), 1], - [new Image(17, 6).fill((x, y) => Image.rgbaToColor(x % 4 * 80, y % 4 * 80, 40, 255)), 4], - [new Image(33, 9).fill((x, y) => Image.rgbaToColor(x * 7, y % 7 * 30, 99, 255)), 8], - [new Image(31, 9).fill((x, y) => Image.rgbaToColor(x * 8, y * 28, (x * 13 + y * 7) & 255, 255)), 24], - [new Image(29, 6).fill((x, y) => Image.rgbaToColor(x * 8, 200 - y * 30, x * y, (x * 9) & 255)), 32], + [new Image(17, 6).fill((x, y) => Colors.fromRGBA(x % 4 * 80, y % 4 * 80, 40, 255)), 4], + [new Image(33, 9).fill((x, y) => Colors.fromRGBA(x * 7, y % 7 * 30, 99, 255)), 8], + [new Image(31, 9).fill((x, y) => Colors.fromRGBA(x * 8, y * 28, (x * 13 + y * 7) & 255, 255)), 24], + [new Image(29, 6).fill((x, y) => Colors.fromRGBA(x * 8, 200 - y * 30, x * y, (x * 9) & 255)), 32], [new Image(1, 1).fill(0x123456ff), 1], ]; for (const [image, bits] of cases) { diff --git a/tests/browser/page.mjs b/tests/browser/page.mjs index ec45bbe5..c8dd909c 100644 --- a/tests/browser/page.mjs +++ b/tests/browser/page.mjs @@ -1,6 +1,6 @@ // the browser test's page script: AVIF and JXL with and without threads (the same files and pixels), the codecs' smoke // test -import { Image } from 'imagescript'; +import { Image, Colors } from 'imagescript'; import { smoke } from '../edge/smoke.mjs'; const digest = async data => [...new Uint8Array(await crypto.subtle.digest('SHA-256', data))].map(b => b.toString(16).padStart(2, '0')).join(''); @@ -8,7 +8,7 @@ const digest = async data => [...new Uint8Array(await crypto.subtle.digest('SHA- const results = { isolated: self.crossOriginIsolated }; try { const image = new Image(640, 512); - for (let y = 0; y < 512; y++) for (let x = 0; x < 640; x++) image.setPixelAt(x, y, Image.rgbaToColor(x * 3 & 255, y * 5 & 255, (x ^ y) & 255, 255)); + for (let y = 0; y < 512; y++) for (let x = 0; x < 640; x++) image.setPixelAt(x, y, Colors.fromRGBA(x * 3 & 255, y * 5 & 255, (x ^ y) & 255, 255)); results.single = await digest(await image.encodeAVIF({ effort: 1, threads: 1, metadata: { creationTime: 0 } })); results.threaded = await digest(await image.encodeAVIF({ effort: 1, threads: 4, metadata: { creationTime: 0 } })); results.jxlSingle = await digest(await image.encodeJXL({ quality: 85, threads: 1, metadata: { creationTime: 0 } })); diff --git a/tests/browser/run.mjs b/tests/browser/run.mjs index e66f916a..bd7dc97f 100644 --- a/tests/browser/run.mjs +++ b/tests/browser/run.mjs @@ -24,6 +24,23 @@ try { } if (!fs.readdirSync(path.join(out, 'assets')).some(f => f.startsWith('worker'))) throw new Error('Vite did not bundle the worker'); +// "sideEffects": false of the build lets bundlers drop what isn't used: a page that only needs Colors doesn't get the library +{ + const small = path.join(here, 'dist-small'); + fs.writeFileSync(path.join(here, 'small.html'), '\n'); + try { + await build({ + root: here, logLevel: 'error', build: { outDir: small, emptyOutDir: true, target: 'es2022', rollupOptions: { input: path.join(here, 'small.html') } }, + resolve: { alias: { imagescript: path.join(here, '../../dist/index.js') } } + }); + const bytes = fs.readdirSync(path.join(small, 'assets')).filter(f => f.endsWith('.js')).reduce((sum, f) => sum + fs.statSync(path.join(small, 'assets', f)).size, 0); + if (bytes > 20000) throw new Error(`a page that only uses Colors bundles ${bytes} bytes of JavaScript: tree shaking doesn't work (sideEffects in dist/package.json?)`); + } finally { + fs.rmSync(path.join(here, 'small.html')); + fs.rmSync(small, { recursive: true, force: true }); + } +} + let failed = false; const browser = await chromium.launch(process.env.CHROMIUM ? { executablePath: process.env.CHROMIUM } : {}); try { diff --git a/tests/circle.js b/tests/circle.js index db96c174..30da8b8b 100644 --- a/tests/circle.js +++ b/tests/circle.js @@ -8,38 +8,12 @@ const panic = message => { }; (async () => { - { - const image = new Image(512, 512); - image.drawCircle(256, 256, 128, 0xffffffff); - - const encoded = await image.encode(1, {creationTime: 0, software: ''}); - - if (process.env.OVERWRITE_TEST) - await fs.writeFile('./tests/targets/circle.png', encoded); - - const target = await fs.readFile('./tests/targets/circle.png'); - if (!await samePixels(target, encoded)) panic('drawCircle 128 failed'); - } - - { - const image = new Image(512, 512); - image.drawCircle(256, 256, 320, 0x000000ff); - - const encoded = await image.encode(1, {creationTime: 0, software: ''}); - - if (process.env.OVERWRITE_TEST) - await fs.writeFile('./tests/targets/circle2.png', encoded); - - const target = await fs.readFile('./tests/targets/circle2.png'); - if (!await samePixels(target, encoded)) panic('drawCircle 320 failed'); - } - { const image = new Image(256, 512); image.fill(0x000000ff); image.cropCircle(); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/circle3.png', encoded); @@ -51,9 +25,9 @@ const panic = message => { { const image = new Image(256, 512); image.fill(0x000000ff); - image.cropCircle(true, .5); + image.cropCircle({ fit: 'cover', feathering: .5 }); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/circle4.png', encoded); diff --git a/tests/color-matrix.js b/tests/color-matrix.js index 6d5af9cc..6bd1403e 100644 --- a/tests/color-matrix.js +++ b/tests/color-matrix.js @@ -1,4 +1,4 @@ -const {Image, Frame, GainMap} = require('..'); +const {Image, Frame, GainMap, Colors} = require('..'); const panic = message => { console.error(message); @@ -15,7 +15,7 @@ const throwsA = (fn, type, label) => { const px = (image, x, y) => Array.from(image.bitmap.subarray((y * image.width + x) * 4, (y * image.width + x) * 4 + 4)); const same = (a, b) => a.width === b.width && a.height === b.height && Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap)); // an opaque image where every pixel is different -const photo = (width, height) => new Image(width, height).fill((x, y) => Image.rgbaToColor((x * 37 + y * 11) % 256, (x * 5 + y * 91) % 256, (x * y + x) % 256, 255)); +const photo = (width, height) => new Image(width, height).fill((x, y) => Colors.fromRGBA((x * 37 + y * 11) % 256, (x * 5 + y * 91) % 256, (x * y + x) % 256, 255)); const IDENTITY = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; (async () => { @@ -43,20 +43,21 @@ const IDENTITY = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; const sepia = [0.393, 0.769, 0.189, 0, 0, 0.349, 0.686, 0.168, 0, 0, 0.272, 0.534, 0.131, 0, 0, 0, 0, 0, 1, 0]; check(same(photo(20, 15).colorMatrix(sepia), photo(20, 15).sepia()), 'colorMatrix: the sepia matrix is sepia()'); + // (what isn't an array of numbers is a TypeError, the wrong number of values or a bad value a RangeError) for (const [label, bad] of Object.entries({ 'eight values': new Array(8).fill(1), 'twenty-one values': new Array(21).fill(0), 'none': [], 'a number': 5, 'null': null, 'NaN': [...IDENTITY.slice(0, 19), NaN], 'a string': [...IDENTITY.slice(0, 19), '1'], 'Infinity': [Infinity, ...IDENTITY.slice(1)] })) { const image = photo(4, 4), before = image.bitmap.slice(); - throwsA(() => image.colorMatrix(bad), RangeError, `colorMatrix with ${label}`); + throwsA(() => image.colorMatrix(bad), Array.isArray(bad) && bad.every(v => typeof v === 'number') ? RangeError : TypeError, `colorMatrix with ${label}`); check(Buffer.from(image.bitmap).equals(Buffer.from(before)), `colorMatrix with ${label}: the image should be unchanged`); } - const frame = Frame.from(photo(4, 4), {duration: 40, xOffset: 2, yOffset: 3}).colorMatrix(sepia); - check(frame instanceof Frame && frame.duration === 40 && frame.xOffset === 2 && frame.yOffset === 3 && same(frame, photo(4, 4).sepia()), 'colorMatrix on a frame'); + const frame = new Frame(photo(4, 4).colorMatrix(sepia), {duration: 40, xOffset: 2, yOffset: 3}); + check(frame instanceof Frame && frame.duration === 40 && frame.xOffset === 2 && frame.yOffset === 3 && same(frame.image, photo(4, 4).sepia()), 'colorMatrix on a frame'); const hdr = photo(8, 8); - hdr.gainMap = new GainMap(new Image(4, 4).fill(0xc0c0c0ff), {gainMapMin: 0, gainMapMax: 2}); + hdr.gainMap = new GainMap(new Image(4, 4).fill(0xc0c0c0ff), {min: 0, max: 2}); hdr.colorMatrix(sepia); check(hdr.gainMap && hdr.gainMap.width === 4 && hdr.gainMap.height === 4, 'colorMatrix with a gain map keeps it'); check((await Image.decode(await hdr.encodeJPEG())).gainMap, 'colorMatrix: the gain map is still encoded'); diff --git a/tests/crop.js b/tests/crop.js index e3f78352..faa44384 100644 --- a/tests/crop.js +++ b/tests/crop.js @@ -1,13 +1,13 @@ const fs = require('fs').promises; -const {Image, Frame} = require('..'); +const {Image, Frame, Colors} = require('..'); const samePixels = require('./util/pixels'); (async () => { const image = new Image(512, 512); - image.fill((x, y) => Image.hslToColor((x + y) / (image.width + image.height), 1, .5)); + image.fill((x, y) => Colors.fromHSL((x + y) / (image.width + image.height) * 360, 1, .5)); image.crop(128, 128, 128, 128); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/crop.png', encoded); @@ -15,28 +15,29 @@ const samePixels = require('./util/pixels'); const target = await fs.readFile('./tests/targets/crop.png'); if (!await samePixels(target, encoded)) process.exit(1); - // region: the same pixels as a new image, the source unchanged; clipped like crop + // extract: the same pixels as a new image, the source unchanged; clipped like crop const panic = message => { console.error(message); process.exit(1); }; - const source = new Image(512, 512).fill((x, y) => Image.hslToColor((x + y) / 1024, 1, .5)); + const source = new Image(512, 512).fill((x, y) => Colors.fromHSL((x + y) / 1024 * 360, 1, .5)); const before = Buffer.from(source.bitmap); - const region = source.region(128, 128, 128, 128); - if (!await samePixels(target, await region.encode(1, {creationTime: 0, software: ''}))) panic('region: wrong pixels'); - if (!Buffer.from(source.bitmap).equals(before)) panic('region: changed the source'); + const region = source.extract(128, 128, 128, 128); + if (!await samePixels(target, await region.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}))) panic('extract: wrong pixels'); + if (!Buffer.from(source.bitmap).equals(before)) panic('extract: changed the source'); region.fill(0); - if (!Buffer.from(source.bitmap).equals(before)) panic('region: shares memory with the source'); + if (!Buffer.from(source.bitmap).equals(before)) panic('extract: shares memory with the source'); - const clipped = source.region(-10, 500, 30, 30); - if (clipped.width !== 20 || clipped.height !== 12) panic(`region: clipped to ${clipped.width}x${clipped.height} instead of 20x12`); - if (clipped.getPixelAt(1, 1) !== source.getPixelAt(1, 501)) panic('region: clipped region has wrong pixels'); + const clipped = source.extract(-10, 500, 30, 30); + if (clipped.width !== 20 || clipped.height !== 12) panic(`extract: clipped to ${clipped.width}x${clipped.height} instead of 20x12`); + if (clipped.getPixelAt(1, 1) !== source.getPixelAt(1, 501)) panic('extract: clipped region has wrong pixels'); let threw = false; - try { source.region(600, 0, 10, 10); } catch (err) { threw = err instanceof RangeError; } - if (!threw) panic('region: a region outside the image should throw a RangeError'); + try { source.extract(600, 0, 10, 10); } catch (err) { threw = err instanceof RangeError; } + if (!threw) panic('extract: a region outside the image should throw a RangeError'); - // a frame's region is a plain image, the frame stays as it is - const frame = Frame.from(source, {duration: 100, xOffset: 4, yOffset: 6}); - const part = frame.region(0, 0, 10, 10); - if (part instanceof Frame || part.width !== 10 || frame.width !== 512 || frame.xOffset !== 4) panic('region: frames'); + // a frame's crop moves its offsets, so the pixels stay where they are in the animation + const frame = new Frame(source.clone(), {duration: 100, xOffset: 4, yOffset: 6}); + const pixel = source.getPixelAt(30, 20); + frame.crop(20, 10, 40, 30); + if (frame.width !== 40 || frame.height !== 30 || frame.xOffset !== 24 || frame.yOffset !== 16 || frame.image.getPixelAt(10, 10) !== pixel) panic('crop: frames'); })(); diff --git a/tests/cut-animations.js b/tests/cut-animations.js new file mode 100644 index 00000000..c2aee89b --- /dev/null +++ b/tests/cut-animations.js @@ -0,0 +1,39 @@ +const fs = require('fs').promises; +const crypto = require('crypto'); +const {Image, Frame, Animation} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +const sha256 = bytes => crypto.createHash('sha256').update(new Uint8Array(bytes)).digest('hex'); + +(async () => { + // a cut-off animation (GIF, APNG, WebP, JPEG XL) has the frames that arrived whole and nothing else: no frame of it + // is a partly decoded one (its pixels are those of the full file's), and fewer bytes never give more frames + { + const make = (format, options) => { + const frames = Array.from({length: 6}, (_, i) => new Frame(new Image(64, 64).fill((x, y) => ((x * 4 + i * 30 & 255) << 24 | (y * 4 & 255) << 16 | (x ^ y) * 4 << 8 | 255) >>> 0), {duration: 40})); + return new Animation(frames)[`encode${format}`](options); + }; + const inputs = { + GIF: await fs.readFile('./bench/inputs/animation.gif'), 'WebP lossless': await make('WebP'), 'WebP lossy': await make('WebP', {quality: 80}), APNG: await make('APNG'), + 'JPEG XL': await fs.readFile('./tests/jxl/animation-lossy.jxl'), 'JPEG XL lossless': await fs.readFile('./tests/jxl/animation.jxl') + }; + for (const [name, data] of Object.entries(inputs)) { + const full = await Animation.decode(data); + let decoded = 0, previous = 0; + for (let cut = Math.floor(data.length / 16); cut < data.length; cut += Math.max(1, data.length >> 5)) { + const part = await Animation.decode(data.subarray(0, cut)).catch(() => null); + if (!part) continue; + decoded++; + if (part.length > full.length || part.length < previous) panic(`${name} cut at ${cut}: ${part.length} frames of ${full.length} (before: ${previous})`); + previous = part.length; + part.frames.forEach((frame, i) => { + if (sha256(frame.image.bitmap) !== sha256(full.frames[i].image.bitmap)) panic(`${name} cut at ${cut}: frame ${i} differs from the full file's`); + }); + } + if (name !== "JPEG XL" && name !== "JPEG XL lossless" && decoded < 3) panic(`${name}: only ${decoded} cuts decoded`); + } + } +})(); diff --git a/tests/damaged-fonts.js b/tests/damaged-fonts.js new file mode 100644 index 00000000..1d66db15 --- /dev/null +++ b/tests/damaged-fonts.js @@ -0,0 +1,140 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const child_process = require('child_process'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// Damaged fonts end with a plain Error (or render), never an internal TypeError or RangeError, a hang or a process abort, +// both through Image.renderText() and through an SVG's @font-face (an untrusted SVG brings its own font) + +const fonts = './tests/fonts/'; +// a copy of a font with some bytes changed +const patched = (name, changes) => { + const data = Buffer.from(fs.readFileSync(fonts + name)); + for (const [offset, from, to] of changes) { + if (data[offset] !== from) panic(`${name}: byte ${offset} isn't ${from}, the fixture changed`); + data[offset] = to; + } + return data; +}; + +// the offset of a table of the font in its file +const tableOffset = (data, tag) => { + for (let i = 0, count = data.readUInt16BE(4); i < count; i++) if (data.toString('latin1', 12 + i * 16, 16 + i * 16) === tag) return data.readUInt32BE(20 + i * 16); + panic(`no ${tag} table`); +}; +// a count (a 32-bit number) at `offset` of a table, changed to `value` +const withCount = (name, tag, offset, value) => { + const data = Buffer.from(fs.readFileSync(fonts + name)); + data.writeUInt32BE(value, tableOffset(data, tag) + offset); + return data; +}; +// the first cmap subtable of format 14 (variation sequences), as an offset in the cmap table +const cmap14 = name => { + const data = fs.readFileSync(fonts + name), cmap = tableOffset(data, 'cmap'); + for (let i = 0, count = data.readUInt16BE(cmap + 2); i < count; i++) { + const subtable = data.readUInt32BE(cmap + 4 + i * 8 + 4); + if (data.readUInt16BE(cmap + subtable) === 14) return subtable; + } + panic(`${name} has no cmap format 14`); +}; + +const cases = { + // the CFF table's Top DICT INDEX is empty (the offset of the table after the head is moved) + 'cff without a top dict': patched('sourcesans3 regular.otf', [[0x27, 216, 88]]), + // a CID-keyed CFF font with an FDArray but no FDSelect (its Top DICT entry is changed to the FDArray operator) + 'cff fdarray without fdselect': patched('source han sans cid subset.otf', [[0x4f4, 37, 214]]), + // a CFF DICT whose real number has no 0xf terminator before the end of the dict: the number's loop read past the end + // and appended '0' forever until V8 aborted the process (a 2 KB font, through renderText and an @font-face alike) + 'cff real number without a terminator': fs.readFileSync(fonts + 'damaged/cff-real-operand.bin'), + // a CID-keyed CFF font whose FDSelect names a private dict past the FDArray: an internal TypeError + 'cff fdselect past the fdarray': fs.readFileSync(fonts + 'damaged/cff-fdselect-past-fdarray.bin'), + // the CBLC table (its offset is moved) holds a strike count of 0x0c000000 and more: a list of that many strikes + // ran the process out of memory (a count too big for the sbix table's reads is caught when they leave the font) + // a 1.5 KB font with a cmap format 12 subtable that claims 0xffffffff groups: the binary search over them, with a + // middle that went negative, ended in an endless loop + 'cmap format 12 with a huge group count': fs.readFileSync(fonts + 'damaged cmap format 12.ttf'), + // the counts of the COLRv1 base glyph list (at the offset the table's header gives, 14) and clip list (22) and of the + // cmap format 14 records are 32-bit numbers: the searches over them ended in an endless loop, or ran past the font + 'colr base glyph list with a huge count': (() => { + const data = Buffer.from(fs.readFileSync(fonts + 'noto colrv1 subset.ttf')), colr = tableOffset(data, 'COLR'); + data.writeUInt32BE(0xffffffff, colr + data.readUInt32BE(colr + 14)); + return data; + })(), + 'colr clip list with a huge count': (() => { + const data = Buffer.from(fs.readFileSync(fonts + 'noto colrv1 subset.ttf')), colr = tableOffset(data, 'COLR'); + data.writeUInt32BE(0x80000001, colr + data.readUInt32BE(colr + 22) + 1); + return data; + })(), + // the clip list holds one clip box, which covers every glyph and lies outside of the font: drawing a color glyph read past its end (an SVG + // doesn't show a glyph it can't draw, like text it can't lay out) + 'colr clip box outside of the font': (() => { + const data = Buffer.from(fs.readFileSync(fonts + 'noto colrv1 subset.ttf')), colr = tableOffset(data, 'COLR'); + const clips = colr + data.readUInt32BE(colr + 22); + data.writeUInt32BE(1, clips + 1); + data.writeUInt16BE(0, clips + 5); + data.writeUInt16BE(0xffff, clips + 7); + data.writeUIntBE(0xffffff, clips + 9, 3); + return data; + })(), + // units per em of 0 made the size of the text NaN by Infinity pixels (a LimitError) + 'head with 0 units per em': (() => { + const data = Buffer.from(fs.readFileSync(fonts + 'carbon phyber.ttf')); + data.writeUInt16BE(0, tableOffset(data, 'head') + 18); + return data; + })(), + // a name record and a cmap format 4 subtable whose offsets lie outside of the font: an SVG doesn't use such a font, + // like one that doesn't load (it threw a RangeError) + 'name record outside of the font': (() => { + const data = Buffer.from(fs.readFileSync(fonts + 'carbon phyber.ttf')); + data.writeUInt32BE(0x7fffffff, 141352); + return data; + })(), + 'cmap format 4 outside of the font': (() => { + const data = Buffer.from(fs.readFileSync(fonts + 'resvg/NotoMono-Regular.ttf')); + data.writeUInt32BE(0x7fffffff, 952); + return data; + })(), + // a CBLC strike of 0 pixels per em: the text's bitmaps were scaled by Infinity (a LimitError) + 'cblc strike of 0 ppem': (() => { + const data = Buffer.from(fs.readFileSync(fonts + 'noto color emoji subset.ttf')), cblc = tableOffset(data, 'CBLC'); + data[cblc + 8 + 45] = 0; + return data; + })(), + // an sbix strike of 0 pixels per em (like the CBLC one) + 'sbix strike of 0 ppem': (() => { + const data = Buffer.from(fs.readFileSync(fonts + 'sbix.ttf')), sbix = tableOffset(data, 'sbix'); + data.writeUInt16BE(0, sbix + data.readUInt32BE(sbix + 8)); + return data; + })(), + // fonts cut off inside their header or table directory: loading them reads past the end + 'font cut to 12 bytes': fs.readFileSync(fonts + 'carbon phyber.ttf').subarray(0, 12), + 'font cut to 100 bytes': fs.readFileSync(fonts + 'carbon phyber.ttf').subarray(0, 100), + 'cmap format 14 with a huge record count': withCount('font features.ttf', 'cmap', cmap14('font features.ttf') + 6, 0xffffffff), + 'cblc with a huge strike count': patched('noto color emoji subset.ttf', [[0x27, 44, 12]]) +}; + +const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'damaged-fonts-')); +try { + // the runtime running this script: node, deno or bun + const [command, ...flags] = typeof Deno !== 'undefined' ? [process.execPath, 'run', '-A'] : [process.execPath]; + for (const [name, font] of Object.entries(cases)) { + const file = path.join(directory, 'font'); + fs.writeFileSync(file, font); + for (const via of ['text', 'svg', 'option', 'mixed']) { + let result; + try { + result = child_process.execFileSync(command, [...flags, './tests/util/damaged-font.js', file, via], {timeout: 20000, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']}).trim(); + } catch (error) { + result = error.signal === 'SIGTERM' ? 'hung for 20 s' : `crashed (${error.signal || `exit ${error.status}`})`; + } + if (result !== 'ok') panic(`${name}, rendered as ${via}: ${result}`); + } + } +} finally { + fs.rmSync(directory, {recursive: true, force: true}); +} diff --git a/tests/decode-frames.js b/tests/decode-frames.js new file mode 100644 index 00000000..5ff36f40 --- /dev/null +++ b/tests/decode-frames.js @@ -0,0 +1,256 @@ +const fs = require('fs').promises; +const crypto = require('crypto'); +const {Image, Frame, Animation, Colors, decode} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +const sha256 = bytes => crypto.createHash('sha256').update(new Uint8Array(bytes)).digest('hex'); +const throwsA = async (fn, type, label) => { + let error = null; + try { await fn(); } catch (e) { error = e; } + if (!(error instanceof type)) panic(`${label}: should throw a ${type.name}, got ${error}`); +}; + +(async () => { + const photo = new Image(12, 8).fill((x, y) => Colors.fromRGBA(x * 20, y * 30, 90, 255)); + const two = new Animation([new Frame(photo.clone(), {duration: 50}), new Frame(photo.clone().invert(), {duration: 70})]); + + // an APNG that is cut off keeps the frames that arrived whole, like a GIF does; one that ends properly with fewer + // frames than it announces, or has no whole frame, doesn't (the default image shows, or it throws) + { + const frames = [0xff0000ff, 0x00ff00ff, 0x0000ffff, 0xffff00ff].map(color => new Frame(new Image(48, 48).fill((x, y) => (color ^ (x * 0x01000000 + y * 0x00010000)) >>> 0 | 0xff), {duration: 40})); + const apng = await new Animation(frames).encodeAPNG({compression: 0}); + const complete = await Animation.decode(apng); + if (complete.length !== 4) panic(`the APNG should have 4 frames, got ${complete.length}`); + const counts = []; + for (let cut = apng.length - 12; cut > apng.length / 3; cut -= 997) { + const decoded = await Animation.decode(apng.subarray(0, cut)).catch(() => null); + if (!decoded) continue; + counts.push(decoded.length); + decoded.frames.forEach((frame, i) => { if (sha256(frame.image.bitmap) !== sha256(complete.frames[i].image.bitmap)) panic(`a frame of the APNG cut at ${cut} differs from the whole file's`); }); + } + if (!counts.includes(2) && !counts.includes(3)) panic(`cut APNGs should decode with the frames that arrived whole, got ${counts}`); + if (counts.some((n, i) => i && n > counts[i - 1])) panic('more frames from less data'); + await throwsA(() => Animation.decode(apng.subarray(0, 60)), Error, 'an APNG cut before its first frame'); + } + + // multiple frames: an Animation, with every frame + const gif = await fs.readFile('./tests/targets/gif.gif'); + const gifFrames = await decode(gif); + if (!(gifFrames instanceof Animation) || gifFrames.length !== 30) panic(`GIF: ${gifFrames.constructor.name} with ${gifFrames.length} frames instead of 30`); + if ((await Animation.decode(gif)).length !== 30) panic('GIF: Animation.decode frame count changed'); + + const apng = await two.encodeAPNG({optimize: false}); + const apngFrames = await decode(apng); + if (!(apngFrames instanceof Animation) || apngFrames.length !== 2 || apngFrames.frames[1].duration !== 70) panic('APNG: expected an Animation of 2 frames'); + + const webp = await fs.readFile('./tests/webp/animated.webp'); + const webpFrames = await decode(webp); + if (!(webpFrames instanceof Animation) || webpFrames.length !== 4) panic(`animated WebP: ${webpFrames.constructor.name} with ${webpFrames.length} frames instead of 4`); + + // (JPEG XL animations: the frames of the APNG reference) + const jxlAnimation = await fs.readFile('./tests/jxl/animation.jxl'); + const jxlRef = await Animation.decode(await fs.readFile('./tests/jxl/animation.png')); + const jxlFrames = await decode(jxlAnimation); + if (!(jxlFrames instanceof Animation) || jxlFrames.length !== jxlRef.length) panic(`JPEG XL: ${jxlFrames.constructor.name} with ${jxlFrames.length} frames instead of ${jxlRef.length}`); + + // a file with one frame is an Animation only when the format signals animation + const single = new Animation([new Frame(new Image(12, 8).fill((x, y) => Colors.fromRGBA(x * 20, y * 30, 90, 255)), {duration: 90, xOffset: 0, yOffset: 0})]); + for (const [format, bytes] of [['GIF', await single.encodeGIF()], ['APNG', await single.encodeAPNG()], ['WebP', await single.encodeWebP({quality: 90})]]) { + const decoded = await decode(bytes); + if (!(decoded instanceof Animation) || decoded.length !== 1) panic(`single frame ${format}: got ${decoded.constructor.name}`); + if (format === 'GIF' && decoded.loopCount !== Infinity) panic(`single-frame GIF loop count: ${decoded.loopCount}`); + const reference = (await Animation.decode(bytes)).frames[0].image; + const image = decoded instanceof Animation ? decoded.frames[0].image : decoded; + if (image.width !== reference.width || image.height !== reference.height) panic(`single frame ${format}: ${image.width}x${image.height} instead of ${reference.width}x${reference.height}`); + if (sha256(image.bitmap) !== sha256(reference.bitmap)) panic(`single frame ${format}: pixels differ from Animation.decode's first frame`); + } + + // a single-frame animated GIF keeps its canvas and frame metadata + const offset = await new Animation([new Frame(new Image(4, 3).fill(0xff0000ff), {xOffset: 2, yOffset: 1, duration: 40})]).encodeGIF({optimize: false}); + const offsetAnimation = await decode(offset); + if (!(offsetAnimation instanceof Animation) || offsetAnimation.width !== 6 || offsetAnimation.height !== 4 || offsetAnimation.frames[0].duration !== 40) + panic(`single frame with an offset: ${offsetAnimation.constructor.name}`); + const stillGif = await decode(await new Animation([single.frames[0].clone()], {loopCount: 0}).encodeGIF()); + if (stillGif instanceof Animation || !(stillGif instanceof Image)) panic('one-frame GIF without a loop extension should be an Image'); + + // a still JPEG XL is an Image with the pixels Image.decode gives + const still = await fs.readFile('./tests/jxl/lossy.jxl'); + const stillImage = await decode(still), stillRef = await Image.decode(still); + if (stillImage instanceof Animation || stillImage.width !== stillRef.width || sha256(stillImage.bitmap) !== sha256(stillRef.bitmap)) panic('still JPEG XL: pixels differ from Image.decode'); + + // static formats: always Images, the pixels of Image.decode + for (const [name, path] of [['PNG', './tests/targets/external.png'], ['JPEG', './tests/targets/external.jpg'], ['still WebP', './tests/webp/lossy.webp']]) { + const bytes = await fs.readFile(path); + const image = await decode(bytes), reference = await Image.decode(bytes); + if (image instanceof Animation || !(image instanceof Image)) panic(`${name}: not an Image`); + if (sha256(image.bitmap) !== sha256(reference.bitmap)) panic(`${name}: pixels differ from Image.decode`); + } + + // options pass through: Image.decode gives the first frame as an Image, maxPixels applies to both kinds + const first = await Image.decode(gif); + if (first instanceof Animation || !(first instanceof Image)) panic('Image.decode: expected an Image'); + if (sha256(first.bitmap) !== sha256((await Animation.decode(gif)).frames[0].image.bitmap)) panic('Image.decode: wrong frame'); + await throwsA(() => decode(gif, {maxPixels: 100}), RangeError, 'maxPixels on a GIF'); + const jpeg = await fs.readFile('./tests/targets/external.jpg'); + await throwsA(() => decode(jpeg, {maxPixels: 100}), RangeError, 'maxPixels on a JPEG'); + if ((await decode(gif, {threads: 2})).length !== 30) panic('threads: frames changed'); + + // Animation.decode wraps still images too; top-level decode uses explicit animation markers + const alwaysAnimation = async (name, bytes) => { + const animation = await Animation.decode(bytes); + if (!(animation instanceof Animation) || animation.length !== 1) panic(`${name}: Animation.decode gives ${animation.constructor.name} with ${animation.length} frames, not an Animation of 1`); + }; + const stillFiles = { + PNG: await photo.encodePNG(), + JPEG: await photo.encodeJPEG(), + 'WebP still': await photo.encodeWebP(), + AVIF: await photo.encodeAVIF({effort: 0}), + 'JPEG XL': await photo.encodeJXL(), + TGA: await photo.encodeTGA() + }; + for (const [name, bytes] of Object.entries(stillFiles)) { + await alwaysAnimation(name, bytes); + const image = await decode(bytes); + if (image instanceof Animation || !(image instanceof Image)) panic(`${name}: decode() should give an Image`); + } + const oneFrameFiles = {GIF: await single.encodeGIF(), APNG: await single.encodeAPNG(), 'WebP animation': await single.encodeWebP({quality: 90})}; + for (const [name, bytes] of Object.entries(oneFrameFiles)) await alwaysAnimation(name, bytes); + + // a one-frame APNG cut from a two-frame file, with its play count retained + const crcTable = Array.from({length: 256}, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; + }); + const crc32 = bytes => { + let c = 0xffffffff; + for (const b of bytes) c = crcTable[(c ^ b) & 255] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; + }; + const pngChunk = (type, data) => { + const out = new Uint8Array(12 + data.length), view = new DataView(out.buffer); + view.setUint32(0, data.length); + for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i); + out.set(data, 8); + view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length))); + return out; + }; + const apngBytes = new Uint8Array(apng); + const apngView = new DataView(apngBytes.buffer, apngBytes.byteOffset, apngBytes.byteLength); + const chunks = []; + for (let at = 8; at < apngBytes.length;) { + const length = apngView.getUint32(at); + chunks.push({type: String.fromCharCode(...apngBytes.subarray(at + 4, at + 8)), data: apngBytes.subarray(at + 8, at + 8 + length)}); + at += 12 + length; + } + let fcTLs = 0; + const second = chunks.findIndex(c => c.type === 'fcTL' && ++fcTLs === 2); + if (second < 0) panic('the two-frame APNG has no second fcTL'); + const parts = [apngBytes.subarray(0, 8)]; + for (const c of chunks.slice(0, second)) { + if (c.type !== 'acTL') { parts.push(pngChunk(c.type, c.data)); continue; } + const actl = new Uint8Array(c.data); + const actlView = new DataView(actl.buffer); + actlView.setUint32(0, 1); + actlView.setUint32(4, 3); + parts.push(pngChunk('acTL', actl)); + } + parts.push(pngChunk('IEND', new Uint8Array(0))); + const oneApng = new Uint8Array(parts.reduce((n, part) => n + part.length, 0)); + for (let at = 0, i = 0; i < parts.length; i++) { oneApng.set(parts[i], at); at += parts[i].length; } + if (!chunks.some(c => c.type === 'acTL')) panic('the two-frame APNG has no acTL'); + + const oneAnimation = await Animation.decode(oneApng); + if (!(oneAnimation instanceof Animation) || oneAnimation.length !== 1) panic(`one-frame APNG with acTL: Animation.decode gives ${oneAnimation.constructor.name} with ${oneAnimation.length} frames`); + if (oneAnimation.loopCount !== 2) panic(`one-frame APNG: loop count ${oneAnimation.loopCount} instead of 2`); + if (sha256(oneAnimation.frames[0].image.bitmap) !== sha256((await Animation.decode(apng)).frames[0].image.bitmap)) panic('one-frame APNG with acTL: the frame differs from the first frame of the two-frame file'); + const oneImage = await decode(oneApng); + if (!(oneImage instanceof Animation) || oneImage.length !== 1 || oneImage.loopCount !== 2) panic('one-frame APNG with acTL: decode() should preserve the Animation'); + if (sha256(oneImage.frames[0].image.bitmap) !== sha256(oneAnimation.frames[0].image.bitmap)) panic('one-frame APNG with acTL: decode() pixels differ from Animation.decode'); + + // Image.decode of an animation is its first frame, an Image composed like Animation.decode's first frame: frames that + // differ, with offsets and disposal modes, from our encoders (GIF, APNG, animated WebP, lossless and lossy) + const moving = new Animation([ + new Frame(new Image(12, 8).fill((x, y) => Colors.fromRGBA(x * 20, y * 30, 90, 255)), {duration: 50}), + new Frame(new Image(5, 4).fill((x, y) => Colors.fromRGBA(255, x * 50, y * 60, 128)), {duration: 70, xOffset: 3, yOffset: 2, disposalMode: 'background'}), + new Frame(new Image(6, 3).fill(0x00ff00ff), {duration: 40, xOffset: 1, yOffset: 4, disposalMode: 'previous'}), + new Frame(new Image(4, 4).fill((x, y) => Colors.fromRGBA(Math.min(y * 90, 255), 0, 200, 255 - x * 60)), {duration: 60, xOffset: 8, yOffset: 4}) + ]); + const movingFiles = { + GIF: await moving.encodeGIF(), + 'GIF without optimization': await moving.encodeGIF({optimize: false}), + APNG: await moving.encodeAPNG(), + 'APNG without optimization': await moving.encodeAPNG({optimize: false}), + 'animated WebP': await moving.encodeWebP(), + 'lossy animated WebP': await moving.encodeWebP({quality: 80}) + }; + for (const [name, bytes] of Object.entries(movingFiles)) { + const image = await Image.decode(bytes); + if (image.constructor !== Image) panic(`${name}: Image.decode gives ${image.constructor.name}, not an Image`); + const frames = (await Animation.decode(bytes)).frames; + if (frames.length !== 4) panic(`${name}: ${frames.length} frames instead of 4`); + const reference = frames[0].image; + if (image.width !== reference.width || image.height !== reference.height) panic(`${name}: ${image.width}x${image.height} instead of ${reference.width}x${reference.height}`); + if (sha256(image.bitmap) !== sha256(reference.bitmap)) panic(`${name}: Image.decode is not the first frame of Animation.decode`); + if (sha256(image.bitmap) === sha256(frames[1].image.bitmap)) panic(`${name}: the frames should differ`); + } + // options apply to the first frame: maxPixels counts the canvas + await throwsA(() => Image.decode(movingFiles.GIF, {maxPixels: 10}), RangeError, 'Image.decode maxPixels of an animated GIF'); + if ((await Image.decode(movingFiles.GIF, {maxPixels: 96})).width !== 12) panic('Image.decode: a GIF whose canvas fits maxPixels should decode'); + + // an APNG whose default image (IDAT) isn't part of the animation: Image.decode gives that image, what viewers without + // APNG support show, and Animation.decode only the frames of the animation + const pngList = bytes => { + const list = [], view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + for (let at = 8; at < bytes.length;) { + const length = view.getUint32(at); + list.push({type: String.fromCharCode(...bytes.subarray(at + 4, at + 8)), data: bytes.subarray(at + 8, at + 8 + length)}); + at += 12 + length; + } + return list; + }; + // (more colors than a palette holds, so both are truecolor PNGs without a PLTE chunk to copy) + const defaultPNG = new Uint8Array(await new Image(32, 32).fill((x, y) => Colors.fromRGBA(x * 7, y * 7, (x * y) & 255, 255)).encodePNG()); + const framePNG = new Uint8Array(await new Image(32, 32).fill((x, y) => Colors.fromRGBA(0, x * 7, y * 7, 255)).encodePNG()); + const ihdr = pngList(defaultPNG).find(c => c.type === 'IHDR').data; + const defaultIDAT = pngList(defaultPNG).find(c => c.type === 'IDAT').data; + const frameIDAT = pngList(framePNG).find(c => c.type === 'IDAT').data; + const actl = new Uint8Array(8); + new DataView(actl.buffer).setUint32(0, 1); // one frame in the animation, which the IDAT isn't part of + const fcTL = new Uint8Array(26), fcView = new DataView(fcTL.buffer); + fcView.setUint32(0, 0); // sequence number + fcView.setUint32(4, 32); // width + fcView.setUint32(8, 32); // height + fcView.setUint16(20, 100); // delay: 100/1000 s + fcView.setUint16(22, 1000); + const fdAT = new Uint8Array(4 + frameIDAT.length); + new DataView(fdAT.buffer).setUint32(0, 1); // sequence number + fdAT.set(frameIDAT, 4); + const separate = Buffer.concat([ + defaultPNG.subarray(0, 8), pngChunk('IHDR', ihdr), pngChunk('acTL', actl), pngChunk('IDAT', defaultIDAT), + pngChunk('fcTL', fcTL), pngChunk('fdAT', fdAT), pngChunk('IEND', new Uint8Array(0)) + ]); + const shown = await Image.decode(separate); + if (shown.constructor !== Image || sha256(shown.bitmap) !== sha256((await Image.decode(defaultPNG)).bitmap)) panic('APNG with a separate default image: Image.decode should give the default image'); + const animated = await Animation.decode(separate); + if (animated.length !== 1 || sha256(animated.frames[0].image.bitmap) !== sha256((await Image.decode(framePNG)).bitmap)) panic('APNG with a separate default image: Animation.decode should give only the animation\'s frame'); + + // a large animation: Image.decode stops after its first frame, so it takes a fraction of the time of all 50 frames + const many = new Animation(Array.from({length: 50}, (_, i) => new Frame(new Image(480, 360).fill((x, y) => Colors.fromRGBA((x * 7 + i * 13) & 255, (y * 5 + x * i) & 255, (x ^ y) & 255, 255)), {duration: 40}))); + const large = await many.encodeGIF(); + const median = async fn => { + const times = []; + for (let i = 0; i < 3; i++) { + const start = process.hrtime.bigint(); + await fn(); + times.push(Number(process.hrtime.bigint() - start) / 1e6); + } + return times.sort((a, b) => a - b)[1]; + }; + const firstMs = await median(() => Image.decode(large)); + const allMs = await median(() => Animation.decode(large)); + if (firstMs * 3 > allMs) panic(`Image.decode of 50 frames took ${firstMs.toFixed(1)} ms, Animation.decode ${allMs.toFixed(1)} ms: not a third`); +})().catch(error => panic(error.stack || String(error))); diff --git a/tests/doc-examples.js b/tests/doc-examples.js new file mode 100644 index 00000000..1668aae4 --- /dev/null +++ b/tests/doc-examples.js @@ -0,0 +1,55 @@ +// the @example blocks of the doc comments run: each one against the names the docs use for its inputs (a decoded photo +// as `image`, an overlay, the bytes of a JPEG, a GIF, a font and a PNG) +const fs = require('fs'); +const {Image, Frame, Animation, Colors, GainMap} = require('..'); + +const panic = msg => { + console.error(msg); + process.exit(1); +}; + +// the examples of a source file: the fenced blocks of every `@example` tag +function examples(file) { + const found = []; + const lines = fs.readFileSync(file, 'utf8').split('\n'); + for (let i = 0; i < lines.length; i++) { + if (!/^\s*\* @example\s*$/.test(lines[i])) continue; + const code = []; + let fenced = false; + for (i++; i < lines.length && !/^\s*\*\/|^\s*\* @/.test(lines[i]); i++) { + const line = lines[i].replace(/^\s*\* ?/, ''); + if (line.startsWith('```')) { fenced = !fenced; continue; } + if (fenced) code.push(line); + } + i--; + found.push({file, line: i, code: code.join('\n')}); + } + return found; +} + +(async () => { + const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; + const photo = await Image.decode(fs.readFileSync('./bench/inputs/photo.jpg')); + const small = photo.clone().crop(700, 300, 400, 300); + const inputs = { + bytes: await small.encodeJPEG(), + gifBytes: fs.readFileSync('./bench/inputs/animation.gif'), + fontBytes: fs.readFileSync('./tests/fonts/sourcesans3 regular.otf'), + logoPNG: await new Image(16, 16).fill(0x336699ff).encodePNG() + }; + + const files = fs.readdirSync('./src').filter(f => f.endsWith('.ts')).map(f => './src/' + f); + const all = files.flatMap(examples); + if (all.length < 10) panic(`doc examples: only ${all.length} found, the extraction is broken`); + for (const example of all) { + // a fresh image and overlay for each example, which runs in a block of its own (so it can declare its own names) + const image = small.clone(), overlay = new Image(80, 60).fill((x, y) => Colors.fromRGBA(255, x * 3, y * 4, 200)); + const names = ['Image', 'Frame', 'Animation', 'Colors', 'GainMap', 'image', 'overlay', ...Object.keys(inputs)]; + try { + await new AsyncFunction(...names, `{\n${example.code}\n}`)(Image, Frame, Animation, Colors, GainMap, image, overlay, ...Object.values(inputs)); + } catch (error) { + panic(`doc example ${example.file}:${example.line} failed: ${error.stack ?? error}\n${example.code}`); + } + } + console.log(`${all.length} doc examples ran`); +})().catch(e => panic(e.stack ?? e)); diff --git a/tests/edge/smoke.mjs b/tests/edge/smoke.mjs index 83777db9..285cc6a2 100644 --- a/tests/edge/smoke.mjs +++ b/tests/edge/smoke.mjs @@ -12,7 +12,7 @@ export async function smoke() { results[name] = `FAIL ${e && e.stack || e}`; } }; - const photo = (await Image.decode(png)).resize(256, Image.RESIZE_AUTO), alpha = photo.clone(); + const photo = (await Image.decode(png)).resize({width: 256}), alpha = photo.clone(); for (let i = 3; i < alpha.bitmap.length; i += 4) alpha.bitmap[i] = (i >> 2) % 256; // (decoded back, the same size) const back = async data => { @@ -20,15 +20,15 @@ export async function smoke() { if (image.width !== photo.width || image.height !== photo.height) throw new Error(`decoded as ${image.width}x${image.height}`); return `${data.length} B`; }; - await step('png', async () => back(await alpha.encode())); - await step('jpeg', async () => back(await photo.encodeJPEG(80))); + await step('png', async () => back(await alpha.encodePNG())); + await step('jpeg', async () => back(await photo.encodeJPEG({quality: 80}))); await step('webp lossless', async () => back(await alpha.encodeWebP())); await step('webp lossy', async () => back(await alpha.encodeWebP({ quality: 75 }))); await step('avif', async () => back(await alpha.encodeAVIF({ effort: 0 }))); await step('jxl lossless', async () => back(await alpha.encodeJXL())); await step('jxl lossy', async () => back(await alpha.encodeJXL({ quality: 85, effort: 2 }))); await step('tga, bmp, qoi, pnm', async () => (await Promise.all([photo.encodeTGA(), photo.encodeBMP(), photo.encodeQOI(), photo.encodePNM()].map(async d => back(await d)))).join(', ')); - const frames = [Frame.from(photo.clone().resize(64, 64), 100), Frame.from(photo.clone().resize(64, 64).invert(), 100)]; + const frames = [new Frame(photo.clone().resize(64, 64), {duration: 100}), new Frame(photo.clone().resize(64, 64).invert(), {duration: 100})]; for (const [name, encode] of [['gif', a => a.encodeGIF()], ['apng', a => a.encodeAPNG()], ['animated webp', a => a.encodeWebP({ quality: 70 })]]) { await step(name, async () => { const decoded = await Animation.decode(await encode(new Animation(frames))); @@ -37,13 +37,13 @@ export async function smoke() { }); } await step('text', async () => { - const text = await Image.renderText(font, 24, 'Edge äöü fi', 0x000000ff); + const text = await Image.renderText('Edge äöü fi', { font, size: 24, color: 0x000000ff }); return `${text.width}x${text.height}`; }); await step('svg', async () => { const svg = '' + 'Hallo'; - const image = await Image.renderSVG(svg, { fonts: [font] }); + const image = await Image.renderSVG(svg, { font: [font] }); return `${image.width}x${image.height}`; }); return results; diff --git a/tests/effects.js b/tests/effects.js index 27727952..92627cc3 100644 --- a/tests/effects.js +++ b/tests/effects.js @@ -1,26 +1,26 @@ const fs = require('fs').promises; -const {Image} = require('..'); +const {Image, Colors} = require('..'); const samePixels = require('./util/pixels'); (async () => { const photo = await Image.decode(await fs.readFile('./tests/targets/external.jpg')); const tile = () => photo.clone().resize(128, 128); - const gradient = new Image(128, 128).fill((x, y) => Image.rgbToColor(x * 2, 255 - y * 2, 140)); + const gradient = new Image(128, 128).fill((x, y) => Colors.fromRGB(x * 2, 255 - y * 2, 140)); const font = await fs.readFile('./tests/fonts/opensans bold.ttf'); const tiles = [ - tile().blur(3), tile().sharpen(2, 2), tile().greyscale(), tile().sepia(), + tile().blur(3), tile().sharpen({amount: 2, radius: 2}), tile().grayscale(), tile().sepia(), tile().brightness(1.3), tile().contrast(1.6), tile().gamma(2), - tile().composite(gradient, 0, 0, {opacity: 0.4}), + tile().composite(gradient, {opacity: 0.4}), ...['multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'add'] - .map(mode => tile().composite(gradient, 0, 0, {mode})) + .map(mode => tile().composite(gradient, {mode})) ]; const image = new Image(5 * 128, 4 * 128 + 80).fill(0x404040ff); - tiles.forEach((t, i) => image.composite(t, (i % 5) * 128, (i / 5 | 0) * 128)); - image.composite(await Image.renderText(font, 56, 'Outlined', 0xffffffff, undefined, {strokeWidth: 5}), 8, 4 * 128 + 4); + tiles.forEach((t, i) => image.composite(t, {x: (i % 5) * 128, y: (i / 5 | 0) * 128})); + image.composite(await Image.renderText('Outlined', { font, size: 56, color: 0xffffffff, strokeWidth: 5 }), {x: 8, y: 4 * 128 + 4}); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/effects.png', encoded); diff --git a/tests/empty-animation.js b/tests/empty-animation.js new file mode 100644 index 00000000..bd6b4f9a --- /dev/null +++ b/tests/empty-animation.js @@ -0,0 +1,28 @@ +const {Animation, Image} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// an animation without frames can be made (its canvas can be set, frames assigned later), but encoding it is a mistake +// of the caller, a RangeError (a count of 0), like the other methods that need something to work with +(async () => { + const empty = () => new Animation([], {width: 4, height: 4}); + for (const [name, encode] of [ + ['encodeGIF', () => empty().encodeGIF()], + ['encodeAPNG', () => empty().encodeAPNG()], + ['encodeWebP', () => empty().encodeWebP()], + ['gifEncoder', () => Animation.gifEncoder(4, 4).finish()], + ['apngEncoder', () => Animation.apngEncoder(4, 4).finish()], + ['webpEncoder', () => Animation.webpEncoder(4, 4).finish()] + ]) { + let error = null; + try { await encode(); } catch (err) { error = err; } + if (!(error instanceof RangeError) || !/at least one frame, not 0$/.test(error.message)) panic(`${name}: ${error?.constructor?.name}: ${error?.message}, expected a RangeError about at least one frame`); + } + // frames assigned later encode + const later = empty(); + later.frames = [new (require('..').Frame)(new Image(4, 4).fill(0xff0000ff))]; + await later.encodeGIF(); +})(); diff --git a/tests/encoder-size-errors.js b/tests/encoder-size-errors.js new file mode 100644 index 00000000..9356ccbb --- /dev/null +++ b/tests/encoder-size-errors.js @@ -0,0 +1,53 @@ +const {Image, Animation, Frame} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// an image beyond what a format can store throws a RangeError of one shape, naming the format, the limit and the +// size: `: images can be at most N pixels wide and high, not WxH` +const sizes = (async () => { + const wide = (width, height = 1) => new Image(width, height).fill(0x336699ff); + const cases = [ + ['JPEG', 65535, image => image.encodeJPEG()], + ['WebP', 16383, image => image.encodeWebP({quality: 80})], + ['WebP', 16384, image => image.encodeWebP()], + ['AVIF', 65536, image => image.encodeAVIF({threads: 1})], + ['TGA', 65535, image => image.encodeTGA()], + ['GIF', 65535, image => image.encodeGIF()] + ]; + for (const [format, limit, encode] of cases) { + for (const [width, height] of [[limit + 1, 1], [1, limit + 1]]) { + let error = null; + try { await encode(wide(width, height)); } catch (err) { error = err; } + const expected = `${format}: images can be at most ${limit} pixels wide and high, not ${width}x${height}`; + if (!(error instanceof RangeError) || error.message !== expected) panic(`${format} ${width}x${height}: ${error?.constructor?.name}: ${error?.message}, expected '${expected}'`); + } + // the limit itself is fine (a 1-pixel wide image: not worth the time of the big ones) + if (limit <= 16384) await encode(wide(limit)); + } + // the other limits stay where they were: the formats that take any size + for (const format of ['encodePNG', 'encodeBMP']) await wide(70000)[format](); +})(); + +// the size is checked before any work on the pixels: a pass over a too large image (a gray check, compositing onto +// the background, the conversion for lossless WebP) only to throw took seconds and a copy of the image +sizes.then(async () => { + const work = () => { throw new Error('the encoder worked on the pixels before checking the size'); }; + // (__bytes__ is only a view of the pixels, not a pass over them) + for (const name of ['__is_gray__', '__flatRows__', '__flattened__']) { + const original = Image.prototype[name]; + Image.prototype[name] = work; + try { + for (const [encode, size] of [[image => image.encodeJPEG(), [65536, 1]], [image => image.encodeWebP(), [16385, 1]], [image => image.encodeWebP({quality: 80}), [16384, 1]], [image => image.encodeAVIF({threads: 1}), [65537, 1]], [image => image.encodeTGA(), [65536, 1]], [image => image.encodeGIF(), [65536, 1]]]) { + const image = new Image(...size).fill(0x80808080); + let error = null; + try { await encode(image); } catch (err) { error = err; } + if (!(error instanceof RangeError) || !/images can be at most/.test(error.message)) panic(`${name}, ${size[0]}x${size[1]}: ${error?.message}`); + } + } finally { + Image.prototype[name] = original; + } + } +}); diff --git a/tests/endian.js b/tests/endian.js index 54bdcfc4..f16266b3 100644 --- a/tests/endian.js +++ b/tests/endian.js @@ -31,7 +31,7 @@ const close = (a, b) => { 'JPEG XL decoding': async () => (await Image.decode(await fs.readFile('./tests/jxl/jpeg.jxl'))).bitmap, 'JPEG encoding': () => photo.encodeJPEG({quality: 80, metadata: {creationTime: 0}}), 'WebP encoding': () => photo.encodeWebP({quality: 75, metadata: {creationTime: 0}}), - resizing: () => photo.clone().resize(317, Image.RESIZE_AUTO).bitmap, + resizing: () => photo.clone().resize({width: 317}).bitmap, blurring: () => photo.clone().blur(4).bitmap, rotating: () => photo.clone().rotate(30).bitmap, }; diff --git a/tests/error-messages.js b/tests/error-messages.js new file mode 100644 index 00000000..1e79a128 --- /dev/null +++ b/tests/error-messages.js @@ -0,0 +1,177 @@ +const fs = require('fs'); +const {Image, Frame, Animation, Colors, GainMap, LimitError} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// A value outside of what an argument takes throws a RangeError that says which argument, what it takes, and which +// value it got: ` must be , not ` (or ` must have , not `, or ` +// takes , not `). Only that shape is checked here, the wording of each message is free +const shape = /^[\w(). ]+ (must be|must have|takes) .+, not .+$/; + +(async () => { + const font = fs.readFileSync('./tests/fonts/carbon phyber.ttf'); + const image = () => new Image(8, 8).fill(0x336699ff); + const gradient = options => () => Image.radialGradient(8, 8, {stops: [0xff0000ff, 0x0000ffff], ...options}); + + const cases = { + 'frame.duration': () => { new Frame(image()).duration = -1; }, + 'frame.duration NaN': () => { new Frame(image()).duration = NaN; }, + 'animation.scale(0)': () => new Animation([new Frame(image())]).scale(0), + 'animation canvas size': () => new Animation([], {width: 0.5, height: 2}), + 'opacity': () => image().opacity(-1), + 'red': () => image().red(-1), + 'green': () => image().green(-1), + 'blue': () => image().blue(-1), + 'lightness': () => image().lightness(-1), + 'saturation': () => image().saturation(-1), + 'brightness': () => image().brightness(-1), + 'contrast': () => image().contrast(-1), + 'gamma': () => image().gamma(0), + 'blur': () => image().dropShadow({blur: -1}), + 'spread': () => image().dropShadow({spread: -1}), + 'outline': () => image().outline({width: -1}), + 'trim': () => image().trim({tolerance: 2}), + 'colorToAlpha': () => image().colorToAlpha({transparencyThreshold: 1, opacityThreshold: 0.5}), + 'radialGradient radius': gradient({radius: 0}), + 'radialGradient x NaN': gradient({x: NaN}), + 'gradient without colors': () => Colors.gradient([]), + 'gradient position NaN': () => Colors.gradient([0xff0000ff, 0x0000ffff])(NaN), + 'creationTime': () => image().encodePNG({metadata: {creationTime: 'no date'}}), + 'SVG scale': () => Image.renderSVG('', {scale: 0}), + 'SVG width': () => Image.renderSVG('', {width: 0}), + 'stroke width': () => Image.renderText('A', {font, size: 20, strokeWidth: -1}), + 'feature tag': () => Image.renderText('A', {font, size: 20, features: {ab: true}}), + 'new Image width': () => new Image(0, 1), + 'new Image height': () => new Image(1, 0.5), + 'new Image too large': () => new Image(2 ** 31, 1), + 'resize width': () => image().resize(0, 1), + 'resize contain': () => image().resize({width: 0, height: 4, fit: 'contain'}), + 'resize cover': () => image().resize({width: 4, height: 0, fit: 'cover'}), + 'scale 0': () => image().scale(0), + 'crop outside': () => image().crop(20, 20, 4, 4), + 'getPixelAt x': () => image().getPixelAt(8, 0), + 'getPixelAt y': () => image().getPixelAt(0, -1), + 'setPixelAt': () => image().setPixelAt(0, 8, 0xff), + 'color': () => image().setPixelAt(0, 0, 1.5), + 'fill color': () => image().fill(2 ** 32), + 'animation width': () => new Animation([], {width: 0, height: 1}), + 'animation resize': () => new Animation([new Frame(image())]).resize({width: 0}), + 'animation crop': () => new Animation([new Frame(image())]).crop(20, 20, 4, 4), + 'palette size': () => image().quantize({palette: []}), + 'color matrix size': () => image().colorMatrix([1]), + 'transform size': () => image().transform([1]), + 'dominantColor threshold': () => image().dominantColor({threshold: 300}), + 'feature value': () => Image.renderText('A', {font, size: 20, features: {abcd: 300}}), + 'hdrCapacityMin': () => new GainMap(new Image(2, 2), {hdrCapacityMin: -1}), + 'bitmap length': () => { image().bitmap = new Uint8Array(4); }, + 'text width': () => Image.renderText('A', {font, size: 20, width: 0.5}) + }; + // a value of the wrong type throws a TypeError that names the argument and shows the value + const typeCases = { + 'new GainMap(5)': () => new GainMap(5), + 'gainMap.image': () => { new GainMap(new Image(2, 2)).image = 5; }, + 'frame.image': () => { new Frame(image()).image = 5; }, + 'animation frames': () => new Animation([5]), + 'encoder.add': () => Animation.gifEncoder(4, 4).add(5), + 'bitmap type': () => { image().bitmap = [1, 2, 3, 4]; }, + 'renderText without a font': () => Image.renderText('A', {font: [], size: 20}) + }; + const typeShape = /^[\w()[\]. ]+ must be .+, not .+$/; + + const failures = []; + for (const [name, fn] of Object.entries(cases)) { + try { + await fn(); + failures.push(`${name}: accepted`); + } catch (error) { + if (!(error instanceof RangeError)) failures.push(`${name}: ${error?.constructor?.name}: ${error?.message}, not a RangeError`); + else if (!shape.test(error.message)) failures.push(`${name}: the message doesn't say which argument, what it takes and what it got: ${error.message}`); + } + } + for (const [name, fn] of Object.entries(typeCases)) { + try { + await fn(); + failures.push(`${name}: accepted`); + } catch (error) { + if (!(error instanceof TypeError)) failures.push(`${name}: ${error?.constructor?.name}: ${error?.message}, not a TypeError`); + else if (!typeShape.test(error.message)) failures.push(`${name}: the message doesn't say which argument, what it takes and what it got: ${error.message}`); + } + } + // the message names the argument that is wrong: the scale factor, not the width it would give; the stops of a + // gradient before an image of its size is allocated + for (const [name, fn, start] of [ + ['image.scale(2 ** 31)', () => image().scale(2 ** 31), 'scale factor'], + ['animation.scale(2 ** 31)', () => new Animation([new Frame(image())]).scale(2 ** 31), 'scale factor'], + ['radialGradient without stops', () => Image.radialGradient(1e6, 1e6, {stops: []}), 'Colors.gradient()'] + ]) { + try { + fn(); + failures.push(`${name}: accepted`); + } catch (error) { + if (!(error instanceof RangeError) || !error.message.startsWith(start)) failures.push(`${name}: ${error.message}, expected a RangeError about the ${start}`); + } + } + // the article fits the class ('an Image'), and a sparse array of fonts names what is missing instead of failing + // inside (Array.prototype.map skips the holes) + for (const [name, fn, expected] of [ + ['frame.image article', () => { new Frame(image()).image = 5; }, /must be an Image,/], + ['metadata field value', () => image().encodePNG({metadata: {title: 42}}), /must be a string, not 42$/], + // a wrong argument is named by its value, not by its type ('abc', 42, an array, an object), like everywhere else + ['Animation frames', () => new Animation('abc'), /not 'abc'$/], + ['gradient stops', () => Colors.gradient('abc'), /not 'abc'$/], + ['binary data', () => Image.decode('abc'), /not 'abc'$/], + ['binary data, a long string', () => Image.decode('x'.repeat(5000)), /^.{0,200}$/], + ['colorMatrix', () => image().colorMatrix('abc'), /not 'abc'$/], + ['transform matrix', () => image().transform(42), /not 42$/], + ['transform origin', () => image().transform([1, 0, 0, 1, 0, 0], {origin: 'abc'}), /not 'abc'$/], + ['gain map parameter', () => new GainMap(new Image(4, 4), {max: 'abc'}), /not 'abc'$/], + ['font feature value', () => Image.renderText('A', {font, size: 20, features: {liga: 'x'}}), /not 'x'$/], + ['font variation value', () => Image.renderText('A', {font, size: 20, variations: {wght: 'x'}}), /not 'x'$/], + ['resize(null)', () => image().resize(null), /^resize\(\)/], + // a creation time is a Date, a timestamp or a string: other types throw a TypeError, not a RangeError (and + // true isn't 1970) + ['creationTime true', () => image().encodePNG({metadata: {creationTime: true}}), /^creationTime must be a Date, a number or a string, not boolean$/], + ['creationTime object', () => image().encodePNG({metadata: {creationTime: {}}}), /, not an object$/], + ['creationTime array', () => image().encodePNG({metadata: {creationTime: []}}), /, not an array$/], + // a cut string keeps whole characters (no lone half of a surrogate pair) + // statics are named with their class, like Image.decode(), and constructors' examples use new + ['Colors.gradient', () => Colors.gradient(5), /^Colors\.gradient\(\) takes/], + ['Frame options', () => new Frame(image(), 5), /^Frame\(\) takes an options object, like new Frame\(/], + ['Animation options', () => new Animation([], 5), /^Animation\(\) takes an options object, like new Animation\(/], + ['renderSVG options', () => Image.renderSVG('', 5), /^Image\.renderSVG\(\) takes an options object.*, not 5$/], + ['renderText options', () => Image.renderText('A', 5), /^Image\.renderText\(\) takes an options object.*, not 5$/], + ['renderText text', () => Image.renderText(5, {}), /^Image\.renderText\(\) takes the text as a string.*, not 5$/], + ['cut string', () => Image.decode('x'.repeat(39) + '\u{1F600}' + 'x'.repeat(10)), /not 'x{39}\u{1F600}\.\.\.'$/u], + // the options check names the method, not its receiver + ['encodeWebP(5)', () => image().encodeWebP(5), /^encodeWebP\(\) takes an options object, like image\.encodeWebP\(/], + ['new GainMap(image, 5)', () => new GainMap(new Image(4, 4), 5), /^GainMap\(\) takes an options object/], + ['Image.decode(data, 5)', () => Image.decode(new Uint8Array(4), 5), /^Image\.decode\(\) takes an options object/], + ['renderText sparse fonts', () => Image.renderText('A', {font: new Array(2), size: 20}), /^(?!Cannot read)/], + ['renderSVG sparse fonts', () => Image.renderSVG('', {font: new Array(2)}), /^(?!Cannot read)/] + ]) { + try { + await fn(); + failures.push(`${name}: accepted`); + } catch (error) { + if (!(error instanceof TypeError) || !expected.test(error.message)) failures.push(`${name}: ${error?.constructor?.name}: ${error?.message}`); + } + } + // a gain map's JPEG takes the qualities of Image.encodeJPEG() (0 is 1) + for (const encode of [() => new GainMap(new Image(4, 4)).encodeJPEG({quality: 0}), () => { const i = image(); i.gainMap = new GainMap(new Image(4, 4)); return i.encodeJPEG({gainMap: {quality: 0}}); }]) { + try { + await encode(); + } catch (error) { + failures.push(`gain map quality 0: ${error.message}, Image.encodeJPEG() takes 0`); + } + } + // limits of what an image can become are LimitErrors, like the ones of dropShadow() and outline() + try { + image().transform([1e5, 0, 0, 1e5, 0, 0]); + } catch (error) { + if (!(error instanceof LimitError)) failures.push(`transform past the limit: ${error.constructor.name}, not a LimitError`); + } + if (failures.length) panic(failures.join('\n')); +})(); diff --git a/tests/fill.js b/tests/fill.js index fa78f398..c808f7ae 100644 --- a/tests/fill.js +++ b/tests/fill.js @@ -1,5 +1,5 @@ const fs = require('fs').promises; -const {Image} = require('..'); +const {Image, Colors} = require('..'); const samePixels = require('./util/pixels'); const panic = message => { @@ -12,7 +12,7 @@ const panic = message => { const image = new Image(512, 512); image.fill(0xff8000ff); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/fill-static.png', encoded); @@ -23,9 +23,9 @@ const panic = message => { { const image = new Image(512, 512); - image.fill((x, y) => Image.hslToColor((x + y) / (image.width + image.height), 1, .5)); + image.fill((x, y) => Colors.fromHSL((x + y) / (image.width + image.height) * 360, 1, .5)); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/fill-func.png', encoded); diff --git a/tests/fisheye.js b/tests/fisheye.js index 87732e92..44dff86e 100644 --- a/tests/fisheye.js +++ b/tests/fisheye.js @@ -8,7 +8,7 @@ const samePixels = require('./util/pixels'); const image = await Image.decode(input); image.fisheye(); - const output = await image.encode(1, {creationTime: 0, software: ''}); + const output = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/fisheye.png', output); diff --git a/tests/flip.js b/tests/flip.js index acda5331..5e5e19ae 100644 --- a/tests/flip.js +++ b/tests/flip.js @@ -9,7 +9,7 @@ const samePixels = require('./util/pixels'); const image = await Image.decode(input); image.flip('horizontal'); - const output = await image.encode(1, {creationTime: 0, software: ''}); + const output = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/flip-horizontal.png', output); @@ -24,7 +24,7 @@ const samePixels = require('./util/pixels'); const image = await Image.decode(input); image.flip('vertical'); - const output = await image.encode(1, {creationTime: 0, software: ''}); + const output = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/flip-vertical.png', output); diff --git a/tests/font-instances.js b/tests/font-instances.js new file mode 100644 index 00000000..818b481d --- /dev/null +++ b/tests/font-instances.js @@ -0,0 +1,31 @@ +const fs = require('fs'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// the instances of a variable font (one for each weight, and each size for a font with an optical size axis) are kept +// in a bounded number, the least recently used dropped: a chart of 5 sizes and 4 weights is 20 instances, and rebuilt +// each time it took 3 times as long. A new weight each render doesn't grow memory without end +(async () => { + const {Font} = await import('../dist/render/font.js'); + const font = new Font(fs.readFileSync(`${__dirname}/fonts/resvg/RobotoFlex.subset.ttf`)); + const used = []; + for (let size = 0; size < 5; size++) for (let weight = 0; weight < 4; weight++) used.push(font.withVariations({opsz: 12 + size * 6, wght: 300 + weight * 200})); + if (new Set(used).size !== 20) panic(`20 combinations should be 20 instances, not ${new Set(used).size}`); + for (let round = 0; round < 3; round++) { + let i = 0; + for (let size = 0; size < 5; size++) for (let weight = 0; weight < 4; weight++) { + if (font.withVariations({opsz: 12 + size * 6, wght: 300 + weight * 200}) !== used[i++]) panic(`round ${round}: an instance of 20 was rebuilt`); + } + } + // a hot instance stays while new ones come: one used between every two new weights isn't dropped + const hot = font.withVariations({wght: 900}); + for (let i = 0; i < 500; i++) { + font.withVariations({wght: 100 + i * 1.5}); + if (font.withVariations({wght: 900}) !== hot) panic(`the instance in use was dropped after ${i} new weights`); + } + // and 500 weights kept no more than a bounded number + if (font.instances.size > 64) panic(`${font.instances.size} instances kept`); +})(); diff --git a/tests/font.js b/tests/font.js index bdebc84e..1bfb7303 100644 --- a/tests/font.js +++ b/tests/font.js @@ -6,7 +6,7 @@ https://notofonts.github.io (subsets of Noto Sans Hebrew, Noto Naskh Arabic and Noto Sans Devanagari, SIL OFL, see ../shaping/OFL-Noto.md; noto naskh arabic subset.woff is the .ttf as WOFF, by fontTools) https://github.com/googlefonts/noto-emoji (subsets of Noto Color Emoji and Noto-COLRv1, SIL OFL, see OFL-NotoColorEmoji.md; - damaged noto colrv1 subset.ttf is a damaged copy for tests/regressions.js) + damaged noto colrv1 subset.ttf is a damaged copy for tests/regressions.js, damaged cmap format 12.ttf one for tests/damaged-fonts.js) colrv1 paints.ttf is built by colrv1-paints.py, sbix.ttf by sbix.py, hinting instructions.ttf by scripts/hinting-fixtures.py font features.ttf and the cmap format fonts by scripts/font-fixtures.py, which also copies cff flex.otf and source han sans cid subset.otf from HarfBuzz's test fonts (SIL OFL, see OFL-HarfBuzz-Source.md) @@ -14,7 +14,7 @@ */ const fs = require('fs').promises; -const {Image, TextLayout} = require('..'); +const {Image, Colors, LimitError} = require('..'); const samePixels = require('./util/pixels'); const panic = message => { @@ -23,23 +23,21 @@ const panic = message => { }; (async () => { - // WOFF fonts render like the fonts they compress; WOFF2 ones are refused with a clear message + // WOFF fonts render like the fonts they compress; WOFF2 ones are refused { const text = 'مرحبا بالعالم'; - const ttf = await Image.renderText(await fs.readFile('./tests/fonts/noto naskh arabic subset.ttf'), 48, text); - const woff = await Image.renderText(await fs.readFile('./tests/fonts/noto naskh arabic subset.woff'), 48, text); + const ttf = await Image.renderText(text, { font: await fs.readFile('./tests/fonts/noto naskh arabic subset.ttf'), size: 48 }); + const woff = await Image.renderText(text, { font: await fs.readFile('./tests/fonts/noto naskh arabic subset.woff'), size: 48 }); if (!Buffer.from(ttf.bitmap).equals(Buffer.from(woff.bitmap))) panic('WOFF font doesn\'t render like its TTF'); const woff2 = new Uint8Array(64); woff2.set([0x77, 0x4f, 0x46, 0x32]); - await Image.renderText(woff2, 48, text).then(() => panic('WOFF2 font was accepted'), err => { - if (!/WOFF2/.test(err.message)) panic(`unexpected WOFF2 error: ${err.message}`); - }); + if (!await Image.renderText(text, { font: woff2, size: 48 }).then(() => false, error => error instanceof Error)) panic('WOFF2 font was accepted'); } { - const font = await Image.renderText(await fs.readFile('./tests/fonts/carbon phyber.ttf'), 128, 'ThE qUiCk'); - const encoded = await font.encode(1, {creationTime: 0, software: ''}); + const font = await Image.renderText('ThE qUiCk', { font: await fs.readFile('./tests/fonts/carbon phyber.ttf'), size: 128 }); + const encoded = await font.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/font-1.png', encoded); @@ -49,8 +47,8 @@ const panic = message => { } { - const font = await Image.renderText(await fs.readFile('./tests/fonts/ethnocentric rg.ttf'), 128, 'BrOwN fOx'); - const encoded = await font.encode(1, {creationTime: 0, software: ''}); + const font = await Image.renderText('BrOwN fOx', { font: await fs.readFile('./tests/fonts/ethnocentric rg.ttf'), size: 128 }); + const encoded = await font.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/font-2.png', encoded); @@ -60,8 +58,8 @@ const panic = message => { } { - const font = await Image.renderText(await fs.readFile('./tests/fonts/opensans bold.ttf'), 128, 'Extra\n-Test\nnewline'); - const encoded = await font.encode(1, {creationTime: 0, software: ''}); + const font = await Image.renderText('Extra\n-Test\nnewline', { font: await fs.readFile('./tests/fonts/opensans bold.ttf'), size: 128 }); + const encoded = await font.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/font-3.png', encoded); @@ -72,8 +70,8 @@ const panic = message => { { // OpenType font with CFF outlines - const font = await Image.renderText(await fs.readFile('./tests/fonts/sourcesans3 regular.otf'), 64, 'Quartz glyph job, vex!'); - const encoded = await font.encode(1, {creationTime: 0, software: ''}); + const font = await Image.renderText('Quartz glyph job, vex!', { font: await fs.readFile('./tests/fonts/sourcesans3 regular.otf'), size: 64 }); + const encoded = await font.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/font-4.png', encoded); @@ -85,7 +83,7 @@ const panic = message => { { const font = await fs.readFile('./tests/fonts/opensans bold.ttf'); // (unhinted: the layout places glyphs with subpixel precision) - const render = (text, options) => Image.renderText(font, 40, text, 0xffffffff, new TextLayout(options), {hinting: false}); + const render = (text, options) => Image.renderText(text, { font, size: 40, color: 0xffffffff, ...options, hinting: false }); // first column with ink in the given row const inkStart = (image, y) => { for (let x = 0; x < image.width; x++) @@ -93,33 +91,60 @@ const panic = message => { return -1; }; - // line metrics match the previous (fontdue based) renderer, glyphs are placed with subpixel precision + // line metrics, glyphs placed with subpixel precision const single = await render('Hi'); if (single.width !== 40 || single.height !== 55) panic(`layout: unexpected size ${single.width}x${single.height}`); // alignment is relative to the widest line const left = await render('Hi\nHello there'); const center = await render('Hi\nHello there', {horizontalAlign: 'center'}); - const right = await render('Hi\nHello there', {verticalAlign: 'right'}); // pre 3.0 option name + const right = await render('Hi\nHello there', {horizontalAlign: 'right'}); const row = 30; if (!(inkStart(left, row) < inkStart(center, row) && inkStart(center, row) < inkStart(right, row))) panic('layout: horizontal alignment has no effect'); // kerning pulls 'To' together (without it, the pair is wider than both glyphs' ink) - const big = text => Image.renderText(font, 200, text, 0xffffffff, undefined, {hinting: false}); + const big = text => Image.renderText(text, { font, size: 200, color: 0xffffffff, hinting: false }); if ((await big('To')).width > (await big('T')).width + (await big('o')).width - 5) panic('layout: kerning has no effect'); // wrapping - const word = await render('Hello world foo bar', {maxWidth: 160}); - const char = await render('Hello world foo bar', {maxWidth: 160, wrapStyle: 'char'}); - if (word.height !== 3 * 55 || word.width > 160) panic('layout: word wrapping failed'); - if (char.width > 160 || char.width <= word.width) panic('layout: char wrapping failed'); - - // maxHeight keeps whole lines, chosen by the vertical alignment - const top = await render('one\ntwo\nthree\nfour\nfive', {maxHeight: 120}); - const bottom = await render('one\ntwo\nthree\nfour\nfive', {maxHeight: 120, verticalAlign: 'bottom'}); - if (top.height !== 110 || bottom.height !== 110) panic('layout: maxHeight failed'); + const word = await render('Hello world foo bar', {width: 160}); + const char = await render('Hello world foo bar', {width: 160, wrapStyle: 'char'}); + if (word.height !== 3 * 55 || word.width !== 160) panic('layout: word wrapping failed'); + if (char.width !== 160 || char.height > word.height || Buffer.from(char.bitmap).equals(Buffer.from(word.bitmap))) panic('layout: char wrapping failed'); + + // a height keeps whole lines, chosen by the vertical alignment, and is the image's height + const top = await render('one\ntwo\nthree\nfour\nfive', {height: 120}); + const bottom = await render('one\ntwo\nthree\nfour\nfive', {height: 120, verticalAlign: 'bottom'}); + if (top.height !== 120 || bottom.height !== 120) panic('layout: height failed'); if (Buffer.from(top.bitmap).equals(Buffer.from(bottom.bitmap))) panic('layout: vertical alignment has no effect'); + + // the size is the image's: the text is aligned in it (also with an outline, which stays inside it) + const inkRows = image => { + const rows = []; + for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) if (image.bitmap[(y * image.width + x) * 4 + 3]) { rows.push(y); break; } + return [rows[0], rows[rows.length - 1]]; + }; + const inkColumns = image => { + let first = Infinity, last = -1; + for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) if (image.bitmap[(y * image.width + x) * 4 + 3]) { first = Math.min(first, x); last = Math.max(last, x); } + return [first, last]; + }; + for (const strokeWidth of [0, 3]) { + const boxed = options => render('Hi', {width: 300, height: 200, strokeWidth, ...options}); + const [topLeft, middleCenter, bottomRight] = await Promise.all([boxed({}), boxed({horizontalAlign: 'center', verticalAlign: 'middle'}), boxed({horizontalAlign: 'right', verticalAlign: 'bottom'})]); + for (const image of [topLeft, middleCenter, bottomRight]) if (image.width !== 300 || image.height !== 200) panic(`layout: a box of 300x200 with a ${strokeWidth} pixel outline gave ${image}`); + const [left, right] = [inkColumns(topLeft), inkColumns(bottomRight)], center = inkColumns(middleCenter); + const [top, bottom] = [inkRows(topLeft), inkRows(bottomRight)], middle = inkRows(middleCenter); + if (!(left[0] < 20 && right[1] > 280 && Math.abs(center[0] + center[1] - 300) <= 4)) panic(`layout: horizontal alignment in the box (outline ${strokeWidth}): ${left} ${center} ${right}`); + if (!(top[0] < 40 && bottom[1] > 170 && middle[0] > top[0] + 40 && middle[1] < bottom[1] - 40)) panic(`layout: vertical alignment in the box (outline ${strokeWidth}): ${top} ${middle} ${bottom}`); + if (strokeWidth && !(left[0] >= 0 && right[1] <= 299 && top[0] >= 0 && bottom[1] <= 199)) panic('layout: the outline should stay inside the box'); + } + // a width or height only sets that side + const wide = await render('Hi', {width: 300}); + if (wide.width !== 300 || wide.height !== 55) panic(`layout: width only: ${wide}`); + const high = await render('Hi', {height: 200}); + if (high.height !== 200 || high.width >= 300) panic(`layout: height only: ${high}`); } // TrueType hinting (#31): hinted outlines match FreeType's (v35 interpreter) point for point { @@ -221,22 +246,22 @@ const panic = message => { return count; }; // the alpha of each column, as a string per column - const columns = image => Array.from({length: image.width}, (_, x) => Array.from({length: image.height}, (_, y) => image.getRGBAAt(x, y)[3]).join()); + const columns = image => Array.from({length: image.width}, (_, x) => Array.from({length: image.height}, (_, y) => Colors.toRGBA(image.getPixelAt(x, y))[3]).join()); const repeats = image => { const cols = columns(image).filter(c => c.split(',').some(v => +v)); return new Set(cols).size; }; - const plain = await Image.renderText(data, 11, 'lllll', 0x000000ff, undefined, {hinting: false}); - const hinted = await Image.renderText(data, 11, 'lllll', 0x000000ff); + const plain = await Image.renderText('lllll', { font: data, size: 11, color: 0x000000ff, hinting: false }); + const hinted = await Image.renderText('lllll', { font: data, size: 11, color: 0x000000ff }); if (repeats(hinted) >= repeats(plain)) panic(`hinting: repeated glyphs should render identically (${repeats(hinted)} vs ${repeats(plain)} distinct columns)`); - const word = await Image.renderText(data, 11, 'Hamburg', 0x000000ff); - if (blurry(word) >= blurry(await Image.renderText(data, 11, 'Hamburg', 0x000000ff, undefined, {hinting: false}))) panic('hinting: text should be crisper'); + const word = await Image.renderText('Hamburg', { font: data, size: 11, color: 0x000000ff }); + if (blurry(word) >= blurry(await Image.renderText('Hamburg', { font: data, size: 11, color: 0x000000ff, hinting: false }))) panic('hinting: text should be crisper'); // fonts without TrueType instructions (CFF, or TrueType without them) render as without hinting for (const file of ['sourcesans3 regular.otf', 'carbon phyber.ttf']) { const font = await fs.readFile(`./tests/fonts/${file}`); - const on = await Image.renderText(font, 11, 'Hamburg', 0x000000ff); - const off = await Image.renderText(font, 11, 'Hamburg', 0x000000ff, undefined, {hinting: false}); + const on = await Image.renderText('Hamburg', { font, size: 11, color: 0x000000ff }); + const off = await Image.renderText('Hamburg', { font, size: 11, color: 0x000000ff, hinting: false }); if (!Buffer.from(on.bitmap).equals(Buffer.from(off.bitmap))) panic(`hinting: ${file} has no instructions and should render unchanged`); } } @@ -247,8 +272,8 @@ const panic = message => { const sans = await fs.readFile('./tests/fonts/sourcesans3 regular.otf'); for (const [file, target] of [['noto color emoji subset.ttf', 'emoji-cbdt'], ['twemoji mozilla subset.ttf', 'emoji-colr'], ['noto colrv1 subset.ttf', 'emoji-colrv1']]) { const emoji = await fs.readFile(`./tests/fonts/${file}`); - const image = await Image.renderText([sans, emoji], 48, 'Hi 😀🔥 👍🏽 🇩🇪 1️⃣ ❤️ 👨‍👩‍👧', {color: 0x000000ff}); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const image = await Image.renderText('Hi 😀🔥 👍🏽 🇩🇪 1️⃣ ❤️ 👨‍👩‍👧', { font: [sans, emoji], size: 48, color: 0x000000ff }); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile(`./tests/targets/${target}.png`, encoded); if (!await samePixels(await fs.readFile(`./tests/targets/${target}.png`), encoded)) panic(`${target} doesn't match`); @@ -259,28 +284,28 @@ const panic = message => { if (colored < 500) panic(`${file}: emoji should keep their colors`); // joiners and variation selectors take no room, even where the font has glyphs for them - const plain = await Image.renderText([sans, emoji], 48, '😀😀'), joined = await Image.renderText([sans, emoji], 48, '😀\u200d\ufe0f😀'); + const plain = await Image.renderText('😀😀', { font: [sans, emoji], size: 48 }), joined = await Image.renderText('😀\u200d\ufe0f😀', { font: [sans, emoji], size: 48 }); if (plain.width !== joined.width) panic(`${file}: invisible characters should take no room (${plain.width} vs ${joined.width})`); // sequences are one glyph (GSUB ligatures): skin tones, flags, keycaps, joined ones - const one = (await Image.renderText(emoji, 48, '👍')).width; + const one = (await Image.renderText('👍', { font: emoji, size: 48 })).width; for (const sequence of ['👍🏽', '🇩🇪', '1️⃣', '👨‍👩‍👧']) - if ((await Image.renderText([sans, emoji], 48, sequence)).width > one * 1.2) panic(`${file}: ${sequence} should be a single glyph`); + if ((await Image.renderText(sequence, { font: [sans, emoji], size: 48 })).width > one * 1.2) panic(`${file}: ${sequence} should be a single glyph`); // the emoji variation selector picks the color glyph over the text font's heart - const heart = await Image.renderText([sans, emoji], 48, '❤️', {color: 0x000000ff}); + const heart = await Image.renderText('❤️', { font: [sans, emoji], size: 48, color: 0x000000ff }); let red = 0; for (let i = 0; i < heart.bitmap.length; i += 4) if (heart.bitmap[i + 3] > 128 && heart.bitmap[i] > 150 && heart.bitmap[i + 1] < 100) red++; if (red < 100) panic(`${file}: ❤️ should be the red emoji`); // characters the emoji font doesn't have come from the next font (the first one still sets the line height) - const fallback = await Image.renderText([emoji, sans], 48, 'Hi'), direct = await Image.renderText(sans, 48, 'Hi'); + const fallback = await Image.renderText('Hi', { font: [emoji, sans], size: 48 }), direct = await Image.renderText('Hi', { font: sans, size: 48 }); const ink = image => image.bitmap.reduce((sum, v, i) => (i & 3) === 3 ? sum + v : sum, 0); if (fallback.width !== direct.width || ink(fallback) !== ink(direct)) panic(`${file}: missing characters should come from the next font`); } // fonts with only bitmap glyphs render on their own - const bitmapOnly = await Image.renderText(await fs.readFile('./tests/fonts/noto color emoji subset.ttf'), 32, '🔥'); + const bitmapOnly = await Image.renderText('🔥', { font: await fs.readFile('./tests/fonts/noto color emoji subset.ttf'), size: 32 }); if (bitmapOnly.width < 20) panic('bitmap font should render on its own'); } @@ -288,18 +313,18 @@ const panic = message => { // every COLR version 1 paint feature: gradients, transforms, composite modes, the text color const font = await fs.readFile('./tests/fonts/colrv1 paints.ttf'); const glyphs = Array.from({length: 17}, (_, k) => String.fromCodePoint(0xe000 + k)).join(''); - const image = await Image.renderText(font, 48, glyphs, {color: 0x00aaaaff}); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const image = await Image.renderText(glyphs, { font, size: 48, color: 0x00aaaaff }); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/colrv1-paints.png', encoded); if (!await samePixels(await fs.readFile('./tests/targets/colrv1-paints.png'), encoded)) panic('colrv1-paints doesn\'t match'); // the linear gradient runs from red (left) to blue (right), the last glyph's square is in the text color - const linear = await Image.renderText(font, 100, '\ue000'); - const [lr, , lb] = linear.getRGBAAt(Math.round(linear.width * 0.15), linear.height >> 1), [rr, , rb] = linear.getRGBAAt(Math.round(linear.width * 0.85), linear.height >> 1); + const linear = await Image.renderText('\ue000', { font, size: 100 }); + const [lr, , lb] = Colors.toRGBA(linear.getPixelAt(Math.round(linear.width * 0.15), linear.height >> 1)), [rr, , rb] = Colors.toRGBA(linear.getPixelAt(Math.round(linear.width * 0.85), linear.height >> 1)); if (!(lr > 150 && lb < 100 && rb > 150 && rr < 100)) panic(`colrv1: linear gradient should go from red to blue (${lr},${lb} -> ${rr},${rb})`); - const foreground = await Image.renderText(font, 100, '\ue010', {color: 0x00aaaaff}); - const [fr, fg, fb, fa] = foreground.getRGBAAt(Math.round(foreground.width * 0.12), foreground.height >> 1); + const foreground = await Image.renderText('\ue010', { font, size: 100, color: 0x00aaaaff }); + const [fr, fg, fb, fa] = Colors.toRGBA(foreground.getPixelAt(Math.round(foreground.width * 0.12), foreground.height >> 1)); if (fr > 2 || Math.abs(fg - 0xaa) > 2 || Math.abs(fb - 0xaa) > 2 || fa < 253) panic(`colrv1: layers in the text color should take it (${fr},${fg},${fb},${fa})`); // the other blend modes: a disc (source) over a square (backdrop), both opaque, where they overlap (the center, @@ -328,42 +353,42 @@ const panic = message => { }; let glyph = 0xe011; for (const [name, blend] of Object.entries(blends)) { - const image = await Image.renderText(font, 100, String.fromCodePoint(glyph++)); - const actual = image.getRGBAAt(image.width >> 1, 50), expected = blend(backdrop, source).map(v => Math.round(v * 255)); + const image = await Image.renderText(String.fromCodePoint(glyph++), { font, size: 100 }); + const actual = Colors.toRGBA(image.getPixelAt(image.width >> 1, 50)), expected = blend(backdrop, source).map(v => Math.round(v * 255)); if (expected.some((v, i) => Math.abs(v - actual[i]) > 1) || actual[3] !== 255) panic(`colrv1 ${name}: ${actual} instead of ${expected}`); } // a radial gradient whose circles touch (red at the left edge of the inner one, blue around the outer one), a // solid paint (green) inside a disc, and a glyph without a clip box sized by its outlines - const touching = await Image.renderText(font, 100, '\ue01a'); - const [tr, , tb] = touching.getRGBAAt(31, 50), [, , ob] = touching.getRGBAAt(88, 50); + const touching = await Image.renderText('\ue01a', { font, size: 100 }); + const [tr, , tb] = Colors.toRGBA(touching.getPixelAt(31, 50)), [, , ob] = Colors.toRGBA(touching.getPixelAt(88, 50)); if (!(tr > 200 && tb < 50 && ob > 200)) panic(`colrv1: touching radial gradient (${tr},${tb} / ${ob})`); - const solidFill = await Image.renderText(font, 100, '\ue01b'); - if (solidFill.getRGBAAt(solidFill.width >> 1, 50).join() !== '0,153,0,255' || solidFill.getRGBAAt(12, 85)[3] !== 0) - panic(`colrv1: a solid paint should fill the disc only (${solidFill.getRGBAAt(solidFill.width >> 1, 50)})`); - const unclipped = await Image.renderText(font, 100, '\ue01c'); + const solidFill = await Image.renderText('\ue01b', { font, size: 100 }); + if (Colors.toRGBA(solidFill.getPixelAt(solidFill.width >> 1, 50)).join() !== '0,153,0,255' || Colors.toRGBA(solidFill.getPixelAt(12, 85))[3] !== 0) + panic(`colrv1: a solid paint should fill the disc only (${Colors.toRGBA(solidFill.getPixelAt(solidFill.width >> 1, 50))})`); + const unclipped = await Image.renderText('\ue01c', { font, size: 100 }); if (unclipped.width < 80 || unclipped.width > 110) panic(`colrv1: a glyph without a clip box should be sized by its outlines (${unclipped.width})`); } { // sbix bitmaps: the PNG placed by its origin offset (8, -4 at 64 ppem), and a 'dupe' of it const font = await fs.readFile('./tests/fonts/sbix.ttf'); - const square = await Image.renderText(font, 64, '\ue000'), dupe = await Image.renderText(font, 64, '\ue001'); + const square = await Image.renderText('\ue000', { font, size: 64 }), dupe = await Image.renderText('\ue001', { font, size: 64 }); if (!Buffer.from(square.bitmap).equals(Buffer.from(dupe.bitmap))) panic('sbix: a dupe should render as the glyph it refers to'); // the baseline is at the ascender (0.9 em), the bitmap's bottom 4 pixels below it, its left edge at 8 - const [r, g, b] = square.getRGBAAt(8 + 24, Math.ceil(0.9 * 64) + 4 - 24), [cr, , cb] = square.getRGBAAt(8 + 4, Math.ceil(0.9 * 64) + 4 - 44); + const [r, g, b] = Colors.toRGBA(square.getPixelAt(8 + 24, Math.ceil(0.9 * 64) + 4 - 24)), [cr, , cb] = Colors.toRGBA(square.getPixelAt(8 + 4, Math.ceil(0.9 * 64) + 4 - 44)); if (!(r > 200 && g < 50 && b < 50 && cb > 200 && cr < 50)) panic(`sbix: the bitmap should be placed by its origin offset (${r},${g},${b} / ${cr},${cb})`); - if (square.getRGBAAt(8 - 2, 30)[3] !== 0) panic('sbix: nothing left of the bitmap'); + if (Colors.toRGBA(square.getPixelAt(8 - 2, 30))[3] !== 0) panic('sbix: nothing left of the bitmap'); } { // text without anything to show renders a transparent pixel wide, it doesn't throw const font = await fs.readFile('./tests/fonts/sourcesans3 regular.otf'); for (const text of ['', ' ', '\u200b\ufe0f']) - if ((await Image.renderText(font, 32, text)).width !== 1) panic(`empty text: ${JSON.stringify(text)} should render a pixel wide`); + if ((await Image.renderText(text, { font, size: 32 })).width !== 1) panic(`empty text: ${JSON.stringify(text)} should render a pixel wide`); // combining sequences are composed where the font has the composed character - const composed = await Image.renderText(font, 32, 'Café Müller'), decomposed = await Image.renderText(font, 32, 'Cafe\u0301 Mu\u0308ller'); + const composed = await Image.renderText('Café Müller', { font, size: 32 }), decomposed = await Image.renderText('Cafe\u0301 Mu\u0308ller', { font, size: 32 }); if (!Buffer.from(composed.bitmap).equals(Buffer.from(decomposed.bitmap))) panic('combining sequences should render like the composed characters'); } @@ -373,8 +398,8 @@ const panic = message => { const fonts = await Promise.all(['opensans bold.ttf', 'noto sans hebrew subset.ttf', 'noto naskh arabic subset.ttf', 'noto sans devanagari subset.ttf'] .map(name => fs.readFile(`./tests/fonts/${name}`))); const text = 'Hi שָׁלוֹם עוֹלָם (2024) and مرحبا بالعالم!\nمرحبا بالعالم، هذا نص (2024)!\nनमस्ते क्षत्रिय र्क्ष'; - const font = await Image.renderText(fonts, 40, text, 0xffffffff, new TextLayout({maxWidth: 420, horizontalAlign: 'right'})); - const encoded = await font.encode(1, {creationTime: 0, software: ''}); + const font = await Image.renderText(text, { font: fonts, size: 40, color: 0xffffffff, width: 420, horizontalAlign: 'right' }); + const encoded = await font.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/font-bidi.png', encoded); @@ -383,10 +408,10 @@ const panic = message => { if (!await samePixels(desired, encoded)) panic('bidirectional text doesn\'t match'); // a right to left paragraph's line starts on the right: its first word is the rightmost - const line = await Image.renderText(fonts, 40, 'مرحبا Hi', 0xffffffff); - const arabic = await Image.renderText(fonts, 40, 'مرحبا', 0xffffffff); + const line = await Image.renderText('مرحبا Hi', { font: fonts, size: 40, color: 0xffffffff }); + const arabic = await Image.renderText('مرحبا', { font: fonts, size: 40, color: 0xffffffff }); const right = line.clone().crop(line.width - arabic.width, 0, arabic.width, line.height); - if (!await samePixels(await arabic.encode(1, {creationTime: 0, software: ''}), await right.encode(1, {creationTime: 0, software: ''}))) + if (!await samePixels(await arabic.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}), await right.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}))) panic('the right to left paragraph should start on the right'); } @@ -394,15 +419,15 @@ const panic = message => { // OpenType features: on (small caps, fractions), off (default ligatures); unknown ones and defaults change nothing const font = await fs.readFile('./tests/fonts/sourcesans3 regular.otf'); const text = '1111 office 2/3'; - const base = await Image.renderText(font, 32, text); + const base = await Image.renderText(text, { font, size: 32 }); const same = (a, b) => a.width === b.width && a.height === b.height && a.bitmap.every((v, i) => v === b.bitmap[i]); for (const features of [{smcp: true}, {liga: false}, {frac: true}]) - if (same(base, await Image.renderText(font, 32, text, {features}))) panic(`features ${JSON.stringify(features)} should change the text`); + if (same(base, await Image.renderText(text, { font, size: 32, features }))) panic(`features ${JSON.stringify(features)} should change the text`); for (const features of [{zzzz: true}, {liga: true}, {kern: 1}]) - if (!same(base, await Image.renderText(font, 32, text, {features}))) panic(`features ${JSON.stringify(features)} shouldn't change the text`); + if (!same(base, await Image.renderText(text, { font, size: 32, features }))) panic(`features ${JSON.stringify(features)} shouldn't change the text`); for (const features of [{toolong: true}, {salt: 1.5}, {salt: -1}, {'ab': true}]) { let error = null; - try { await Image.renderText(font, 32, text, {features}); } catch (err) { error = err; } + try { await Image.renderText(text, { font, size: 32, features }); } catch (err) { error = err; } if (!(error instanceof RangeError)) panic(`features ${JSON.stringify(features)} should be rejected`); } } @@ -413,7 +438,7 @@ const panic = message => { const flex = await fs.readFile('./tests/fonts/resvg/RobotoFlex.subset.ttf'), text = 'Bold Thin'; const same = (a, b) => a.width === b.width && a.height === b.height && a.bitmap.every((v, i) => v === b.bitmap[i]); const ink = image => image.bitmap.reduce((sum, v, i) => (i & 3) === 3 ? sum + v : sum, 0); - const render = variations => Image.renderText(flex, 32, text, {variations}); + const render = variations => Image.renderText(text, { font: flex, size: 32, variations }); const regular = await render({}), bold = await render({weight: 900}), thin = await render({weight: 100}); if (!(ink(thin) < ink(regular) && ink(regular) < ink(bold))) panic('variable font: weight should change the strokes'); if (!same(bold, await render({wght: 900}))) panic('variable font: weight and wght should be the same'); @@ -425,31 +450,77 @@ const panic = message => { if (same(regular, await render({GRAD: 150}))) panic('variable font: custom axes by tag'); if (!same(regular, await render({ZZZZ: 1}))) panic('variable font: axes it doesn\'t have should be ignored'); const plain = await fs.readFile('./tests/fonts/sourcesans3 regular.otf'); - if (!same(await Image.renderText(plain, 32, text), await Image.renderText(plain, 32, text, {variations: {weight: 900}}))) panic('fonts without axes shouldn\'t change'); - for (const variations of [{wieght: 700}, {weight: NaN}, {weight: '700'}]) { + if (!same(await Image.renderText(text, { font: plain, size: 32 }), await Image.renderText(text, { font: plain, size: 32, variations: {weight: 900} }))) panic('fonts without axes shouldn\'t change'); + // (an unknown axis or a value out of range is a RangeError, a value of the wrong type a TypeError) + for (const [variations, type] of [[{wieght: 700}, RangeError], [{weight: NaN}, RangeError], [{weight: '700'}, TypeError], [{weight: null}, TypeError]]) { let error = null; try { await render(variations); } catch (err) { error = err; } - if (!(error instanceof RangeError)) panic(`variations ${JSON.stringify(variations)} should be rejected`); + if (!(error instanceof type)) panic(`variations ${JSON.stringify(variations)} should be rejected with a ${type.name}`); } } - // renderText(text, options) renders like the deprecated renderText(font, size, text, ...) (removed in 4.0) + // renderText rejects options without a font or size { const font = await fs.readFile('./tests/fonts/sourcesans3 regular.otf'); const text = 'Hello wrapped world'; - const layout = new TextLayout({maxWidth: 90, horizontalAlign: 'center'}); - const cases = [ - [await Image.renderText(font, 32, text), await Image.renderText(text, {font, size: 32})], - [await Image.renderText(font, 24, text, 0xff8800ff, layout), await Image.renderText(text, {font, size: 24, color: 0xff8800ff, layout})], - [await Image.renderText(font, 24, text, 0xff8800ff, layout), await Image.renderText(text, {font, size: 24, color: 0xff8800ff, layout: {maxWidth: 90, horizontalAlign: 'center'}})], - [await Image.renderText(font, 24, text, {strokeWidth: 2, strokeColor: 0xff0000ff, features: {smcp: true}}), await Image.renderText(text, {font, size: 24, strokeWidth: 2, strokeColor: 0xff0000ff, features: {smcp: true}})], - [await Image.renderText([font, font], 20, text), await Image.renderText(text, {font: [font, font], size: 20})] - ]; - cases.forEach(([old, now], i) => { if (old.width !== now.width || old.height !== now.height || !Buffer.from(old.bitmap).equals(Buffer.from(now.bitmap))) panic(`renderText(text, options) case ${i} differs from the old signature`); }); for (const options of [undefined, {size: 20}, {font}, {font, size: NaN}]) { let error = null; try { await Image.renderText(text, options); } catch (err) { error = err; } if (!error) panic(`renderText(text, ${JSON.stringify(options && Object.keys(options))}) should be rejected`); } } + + // maxPixels limits the rendered image, its outline included, before its pixels are allocated + { + const font = await fs.readFile('./tests/fonts/sourcesans3 regular.otf'); + const plain = await Image.renderText('hi', {font, size: 16}); + const fits = await Image.renderText('hi', {font, size: 16, maxPixels: plain.width * plain.height}); + if (fits.width !== plain.width || fits.height !== plain.height) panic('text exactly at maxPixels should render'); + const tooLarge = async (label, options) => { + let error = null; + try { await Image.renderText('hi', {font, size: 16, ...options}); } catch (err) { error = err; } + if (!(error instanceof LimitError)) panic(`${label} should throw a LimitError, got ${error}`); + }; + await tooLarge('text over maxPixels', {maxPixels: plain.width * plain.height - 1}); + await tooLarge('an outline over maxPixels', {strokeWidth: 2000, maxPixels: 1e6}); + await tooLarge('an outline over the default maxPixels', {strokeWidth: 10000}); + const unlimited = await Image.renderText('hi', {font, size: 16, strokeWidth: 3, maxPixels: Infinity}); + if (unlimited.width !== plain.width + 6) panic('maxPixels: Infinity should lift the limit'); + // a size of 0 draws nothing (it was a 1x1 image), like a negative one it throws + for (const size of [0, -1, NaN]) { + if (!await Image.renderText('hi', {font, size}).then(() => false, error => error instanceof RangeError)) panic(`renderText size ${size} should throw a RangeError`); + } + for (const [maxPixels, type] of [[0, RangeError], [-1, RangeError], [NaN, RangeError], ['many', TypeError], ['100', TypeError]]) { + let error = null; + try { await Image.renderText('hi', {font, size: 16, maxPixels}); } catch (err) { error = err; } + if (!(error instanceof type)) panic(`renderText maxPixels ${maxPixels} should throw a ${type.name}`); + } + } + + { + // a WOFF cut off inside its tables is a damaged font, like a cut-off TrueType file (its zlib error said nothing + // about the font) + const woff = await fs.readFile('./tests/fonts/noto naskh arabic subset.woff'); + for (const length of [200, 1000, woff.length - 50]) { + let error = null; + try { await Image.renderText('hi', {font: woff.subarray(0, length), size: 16}); } catch (err) { error = err; } + if (!error || error.constructor !== Error || !error.message.startsWith('Font: ')) panic(`a WOFF cut to ${length} bytes: ${error}, expected a "Font: ..." Error`); + } + } +})(); + +// text without a font-family gets the first font of renderSVG's font option, also when the SVG embeds fonts of its own +// (those are used for their family names, like browsers use them): it was the embedded font +(async () => { + const sbix = await fs.readFile('./tests/fonts/sbix.ttf'); + const other = (await fs.readFile('./tests/fonts/carbon phyber.ttf')).toString('base64'); + const svg = style => `${style}\ue000`; + const red = image => { + let count = 0; + for (let i = 0; i < image.bitmap.length; i += 4) count += image.bitmap[i] > 200 && image.bitmap[i + 1] < 50 && image.bitmap[i + 3] > 200; + return count; + }; + const alone = red(await Image.renderSVG(svg(''), {font: sbix})); + const embedded = red(await Image.renderSVG(svg(``), {font: sbix})); + if (!alone || embedded !== alone) panic(`text without a family next to an embedded font: ${embedded} red pixels of the caller's font, ${alone} without the embedded font`); })(); diff --git a/tests/fonts/bitmap-limits/a0-p1-64.ttf b/tests/fonts/bitmap-limits/a0-p1-64.ttf new file mode 100644 index 00000000..7c3b7399 Binary files /dev/null and b/tests/fonts/bitmap-limits/a0-p1-64.ttf differ diff --git a/tests/fonts/bitmap-limits/mksbix.py b/tests/fonts/bitmap-limits/mksbix.py new file mode 100644 index 00000000..188160f4 --- /dev/null +++ b/tests/fonts/bitmap-limits/mksbix.py @@ -0,0 +1,29 @@ +# python mksbix.py out.ttf N SIZE MODE: sbix font, U+E000+i -> distinct SIZExSIZE RGBA PNG; MODE ok|badfilter (last row filter 5)|trunc +import sys, struct, zlib +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.ttGlyphPen import TTGlyphPen +from fontTools.ttLib import newTable +from fontTools.ttLib.tables.sbixStrike import Strike +from fontTools.ttLib.tables.sbixGlyph import Glyph as SbixGlyph +out, n, size, mode = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4] +def chunk(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d)) +def png(i): + c = zlib.compressobj(9); parts = [] + row = b'\0' + bytes([i & 255, i >> 8 & 255, 0, 255]) * size + for y in range(size): + r = row if not (mode == 'badfilter' and y == size - 1) else b'\5' + row[1:] + if mode == 'trunc' and y == size - 1: break + parts.append(c.compress(r)) + parts.append(c.flush()) + return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'') +names = ['.notdef'] + [f'g{i}' for i in range(n)] +fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names) +fb.setupCharacterMap({0xE000 + i: f'g{i}' for i in range(n)}) +fb.setupGlyf({k: TTGlyphPen(None).glyph() for k in names}) +fb.setupHorizontalMetrics({k: (1000, 0) for k in names}) +fb.setupHorizontalHeader(ascent=900, descent=-100) +fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost() +st = Strike(ppem=64, resolution=72) +for i in range(n): st.glyphs[f'g{i}'] = SbixGlyph(glyphName=f'g{i}', graphicType='png ', originOffsetX=0, originOffsetY=0, imageData=png(i)) +sb = newTable('sbix'); sb.version = 1; sb.flags = 1; sb.strikes = {64: st}; fb.font['sbix'] = sb +fb.save(out) diff --git a/tests/fonts/bitmap-limits/mksbix3.py b/tests/fonts/bitmap-limits/mksbix3.py new file mode 100644 index 00000000..5b115e08 --- /dev/null +++ b/tests/fonts/bitmap-limits/mksbix3.py @@ -0,0 +1,30 @@ +# python mksbix3.py out.ttf N SIZE MODE PPEM ADV: sbix font, U+E000+i -> distinct SIZExSIZE PNGs in one strike at PPEM, advance ADV units (of 1000) +import sys, struct, zlib +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.ttGlyphPen import TTGlyphPen +from fontTools.ttLib import newTable +from fontTools.ttLib.tables.sbixStrike import Strike +from fontTools.ttLib.tables.sbixGlyph import Glyph as SbixGlyph +out, n, size, mode = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]; PPEM = int(sys.argv[5]) if len(sys.argv) > 5 else 64 +def chunk(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d)) +def png(i): + c = zlib.compressobj(9); parts = [] + row = b'\0' + bytes([i & 255, i >> 8 & 255, 0, 255]) * size + for y in range(size): + r = row if not (mode == 'badfilter' and y == size - 1) else b'\5' + row[1:] + if mode == 'trunc' and y == size - 1: break + parts.append(c.compress(r)) + parts.append(c.flush()) + return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'') +ADV = int(sys.argv[6]) if len(sys.argv) > 6 else 1000 +names = ['.notdef'] + [f'g{i}' for i in range(n)] +fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names) +fb.setupCharacterMap({0xE000 + i: f'g{i}' for i in range(n)}) +fb.setupGlyf({k: TTGlyphPen(None).glyph() for k in names}) +fb.setupHorizontalMetrics({k: (ADV, 0) for k in names}) +fb.setupHorizontalHeader(ascent=900, descent=-100) +fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost() +st = Strike(ppem=PPEM, resolution=72) +for i in range(n): st.glyphs[f'g{i}'] = SbixGlyph(glyphName=f'g{i}', graphicType='png ', originOffsetX=0, originOffsetY=0, imageData=png(i)) +sb = newTable('sbix'); sb.version = 1; sb.flags = 1; sb.strikes = {64: st}; fb.font['sbix'] = sb +fb.save(out) diff --git a/tests/fonts/bitmap-limits/mkshared.py b/tests/fonts/bitmap-limits/mkshared.py new file mode 100644 index 00000000..5ce22d00 --- /dev/null +++ b/tests/fonts/bitmap-limits/mkshared.py @@ -0,0 +1,29 @@ +# python mkshared.py out.ttf M SIZE MODE: sbix font with 2M+1 glyphs; glyph 2k (U+E000+k) = the SAME PNG bytes at one +# start offset, with end = start+len+k (distinct (offset,length) cache keys); odd glyphs are fillers (end null) +import sys, struct, zlib +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.ttGlyphPen import TTGlyphPen +from fontTools.ttLib.tables.DefaultTable import DefaultTable +out, M, size, mode = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4] +def chunk(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d)) +c = zlib.compressobj(9); row = b'\0' + b'\xff\x00\x00\xff' * size; parts = [] +for y in range(size): parts.append(c.compress(b'\5' + row[1:] if mode == 'badfilter' and y == size - 1 else row)) +parts.append(c.flush()) +png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'') +n = 2 * M + 2 # .notdef + 2M+1 glyphs +names = ['.notdef'] + [f'g{i}' for i in range(n - 1)] +fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names) +fb.setupCharacterMap({0xE000 + k: f'g{2 * k}' for k in range(M)}) +fb.setupGlyf({k: TTGlyphPen(None).glyph() for k in names}) +fb.setupHorizontalMetrics({k: (1000, 0) for k in names}) +fb.setupHorizontalHeader(ascent=900, descent=-100) +fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost() +hdr = 4 + 4 * (n + 1); S = hdr; L = 8 + len(png) +offs = [] +for gid in range(n + 1): + if gid == 0: offs.append(S + L + M + 10) # .notdef: start beyond, end S -> null + elif (gid - 1) % 2 == 0: offs.append(S) # glyph g{2k}: start S + else: offs.append(S + L + (gid - 2) // 2) # end of g{2k} = S+L+k +strike = struct.pack('>HH', 64, 72) + b''.join(struct.pack('>I', o) for o in offs) + struct.pack('>hh4s', 0, 0, b'png ') + png + b'\0' * (M + 16) +t = DefaultTable('sbix'); t.data = struct.pack('>HHII', 1, 1, 1, 12) + strike +fb.font['sbix'] = t; fb.save(out); print('png', len(png), 'font', len(open(out, 'rb').read())) diff --git a/tests/fonts/bitmap-limits/mkshared0.py b/tests/fonts/bitmap-limits/mkshared0.py new file mode 100644 index 00000000..d9946e98 --- /dev/null +++ b/tests/fonts/bitmap-limits/mkshared0.py @@ -0,0 +1,29 @@ +# python mkshared.py out.ttf M SIZE MODE: sbix font with 2M+1 glyphs; glyph 2k (U+E000+k) = the SAME PNG bytes at one +# start offset, with end = start+len+k (distinct (offset,length) cache keys); odd glyphs are fillers (end null) +import sys, struct, zlib +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.ttGlyphPen import TTGlyphPen +from fontTools.ttLib.tables.DefaultTable import DefaultTable +out, M, size, mode = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4] +def chunk(k, d): return struct.pack('>I', len(d)) + k + d + struct.pack('>I', zlib.crc32(k + d)) +c = zlib.compressobj(9); row = b'\0' + b'\xff\x00\x00\xff' * size; parts = [] +for y in range(size): parts.append(c.compress(b'\5' + row[1:] if mode == 'badfilter' and y == size - 1 else row)) +parts.append(c.flush()) +png = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'') +n = 2 * M + 2 # .notdef + 2M+1 glyphs +names = ['.notdef'] + [f'g{i}' for i in range(n - 1)] +fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names) +fb.setupCharacterMap({0xE000 + k: f'g{2 * k}' for k in range(M)}) +fb.setupGlyf({k: TTGlyphPen(None).glyph() for k in names}) +fb.setupHorizontalMetrics({k: (0, 0) for k in names}) +fb.setupHorizontalHeader(ascent=900, descent=-100) +fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost() +hdr = 4 + 4 * (n + 1); S = hdr; L = 8 + len(png) +offs = [] +for gid in range(n + 1): + if gid == 0: offs.append(S + L + M + 10) # .notdef: start beyond, end S -> null + elif (gid - 1) % 2 == 0: offs.append(S) # glyph g{2k}: start S + else: offs.append(S + L + (gid - 2) // 2) # end of g{2k} = S+L+k +strike = struct.pack('>HH', 64, 72) + b''.join(struct.pack('>I', o) for o in offs) + struct.pack('>hh4s', 0, 0, b'png ') + png + b'\0' * (M + 16) +t = DefaultTable('sbix'); t.data = struct.pack('>HHII', 1, 1, 1, 12) + strike +fb.font['sbix'] = t; fb.save(out); print('png', len(png), 'font', len(open(out, 'rb').read())) diff --git a/tests/fonts/bitmap-limits/mkzero.py b/tests/fonts/bitmap-limits/mkzero.py new file mode 100644 index 00000000..769db98c --- /dev/null +++ b/tests/fonts/bitmap-limits/mkzero.py @@ -0,0 +1,15 @@ +# python -I mkzero.py out.ttf N : TrueType font, N glyphs (U+E000..) each a full-em square, advance 0 (no third-party data) +import sys +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.ttGlyphPen import TTGlyphPen +out, n = sys.argv[1], int(sys.argv[2]) +names = ['.notdef'] + [f'g{i}' for i in range(n)] +fb = FontBuilder(1000, isTTF=True); fb.setupGlyphOrder(names) +fb.setupCharacterMap({0xE000 + i: f'g{i}' for i in range(n)}) +def sq(i): + p = TTGlyphPen(None); d = i % 7 + p.moveTo((d, 0)); p.lineTo((d, 1000)); p.lineTo((1000, 1000)); p.lineTo((1000, d)); p.closePath(); return p.glyph() +glyf = {'.notdef': TTGlyphPen(None).glyph()}; glyf.update({f'g{i}': sq(i) for i in range(n)}) +fb.setupGlyf(glyf); fb.setupHorizontalMetrics({k: (0, 0) for k in names}) +fb.setupHorizontalHeader(ascent=1000, descent=0) +fb.setupNameTable({'familyName': 'x', 'styleName': 'Regular'}); fb.setupOS2(); fb.setupPost(); fb.save(out) diff --git a/tests/fonts/bitmap-limits/p1.ttf b/tests/fonts/bitmap-limits/p1.ttf new file mode 100644 index 00000000..146e1f53 Binary files /dev/null and b/tests/fonts/bitmap-limits/p1.ttf differ diff --git a/tests/fonts/bitmap-limits/sh-bad-1000.ttf b/tests/fonts/bitmap-limits/sh-bad-1000.ttf new file mode 100644 index 00000000..462ea7a1 Binary files /dev/null and b/tests/fonts/bitmap-limits/sh-bad-1000.ttf differ diff --git a/tests/fonts/bitmap-limits/z-ok-1000.ttf b/tests/fonts/bitmap-limits/z-ok-1000.ttf new file mode 100644 index 00000000..54984c13 Binary files /dev/null and b/tests/fonts/bitmap-limits/z-ok-1000.ttf differ diff --git a/tests/fonts/bitmap-limits/zero.ttf b/tests/fonts/bitmap-limits/zero.ttf new file mode 100644 index 00000000..ab3ffc96 Binary files /dev/null and b/tests/fonts/bitmap-limits/zero.ttf differ diff --git a/tests/fonts/damaged cmap format 12.ttf b/tests/fonts/damaged cmap format 12.ttf new file mode 100644 index 00000000..b7b82b74 Binary files /dev/null and b/tests/fonts/damaged cmap format 12.ttf differ diff --git a/tests/fonts/damaged/cff-fdselect-past-fdarray.bin b/tests/fonts/damaged/cff-fdselect-past-fdarray.bin new file mode 100644 index 00000000..9a48e68b Binary files /dev/null and b/tests/fonts/damaged/cff-fdselect-past-fdarray.bin differ diff --git a/tests/fonts/damaged/cff-real-operand.bin b/tests/fonts/damaged/cff-real-operand.bin new file mode 100644 index 00000000..319ea84c Binary files /dev/null and b/tests/fonts/damaged/cff-real-operand.bin differ diff --git a/tests/fonts/emoji-4096.ttf b/tests/fonts/emoji-4096.ttf new file mode 100644 index 00000000..118edb48 Binary files /dev/null and b/tests/fonts/emoji-4096.ttf differ diff --git a/tests/forward-options.js b/tests/forward-options.js deleted file mode 100644 index 834472e2..00000000 --- a/tests/forward-options.js +++ /dev/null @@ -1,62 +0,0 @@ -const fs = require('fs').promises; -const {Image, GainMap} = require('..'); - -const panic = message => { - console.error(message); - process.exit(1); -}; -const alpha = image => { - let sum = 0; - for (let i = 3; i < image.bitmap.length; i += 4) sum += image.bitmap[i]; - return sum; -}; -const same = (a, b) => a.width === b.width && a.height === b.height && Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap)); - -// the 4.0 names of options that 4.0 would ignore under their 3.x names: following the deprecation hints of 3.x leads to -// them, and they give what the 3.x names give -(async () => { - // cropCircle({ fit }), the 4.0 name of size - for (const fit of ['contain', 'cover']) { - const byFit = new Image(20, 10).fill(0xff0000ff).cropCircle({fit}); - const bySize = new Image(20, 10).fill(0xff0000ff).cropCircle({size: fit}); - if (alpha(byFit) !== alpha(bySize)) panic(`cropCircle({ fit: '${fit}' }) differs from { size: '${fit}' }`); - } - if (alpha(new Image(20, 10).fill(0xff0000ff).cropCircle({fit: 'cover'})) === alpha(new Image(20, 10).fill(0xff0000ff).cropCircle())) panic('cropCircle({ fit: \'cover\' }) should cover'); - let error = null; - try { new Image(4, 4).cropCircle({fit: 'fill'}); } catch (err) { error = err; } - if (!(error instanceof TypeError)) panic(`cropCircle({ fit: 'fill' }) should throw a TypeError, got ${error}`); - - // renderSVG({ width }), { height }, { scale } and { font }, the 4.0 forms of { size, mode } and { fonts } - const svg = 'Hi'; - const font = await fs.readFile('./tests/fonts/carbon phyber.ttf'); - for (const [now, before] of [ - [{width: 80}, {size: 80, mode: 'width'}], - [{height: 60}, {size: 60, mode: 'height'}], - [{scale: 2}, {size: 2, mode: 'scale'}], - [{scale: 0.5}, {size: 0.5}], - [{font}, {fonts: [font]}], - [{font: [font]}, {fonts: [font]}], - [{width: 80, font}, {size: 80, mode: 'width', fonts: [font]}] - ]) { - const a = await Image.renderSVG(svg, now), b = await Image.renderSVG(svg, before); - if (!same(a, b)) panic(`renderSVG(${JSON.stringify(Object.keys(now))}) differs from its 3.x form`); - } - for (const [options, type] of [[{width: 0}, RangeError], [{scale: -1}, RangeError], [{width: 10, height: 10}, TypeError], [{width: 10, scale: 2}, TypeError], [{width: 10, size: 10}, TypeError]]) { - error = null; - try { await Image.renderSVG(svg, options); } catch (err) { error = err; } - if (!(error instanceof type)) panic(`renderSVG(${JSON.stringify(options)}) should throw a ${type.name}, got ${error}`); - } - - // new GainMap(image, { min, max }) and map.min, map.max, the 4.0 names of gainMapMin and gainMapMax - const pixels = new Image(4, 4).fill(0x808080ff); - const byName = new GainMap(pixels, {min: -1, max: [1, 2, 3]}), old = new GainMap(pixels, {gainMapMin: -1, gainMapMax: [1, 2, 3]}); - if (JSON.stringify(byName.min) !== JSON.stringify(old.gainMapMin) || JSON.stringify(byName.max) !== JSON.stringify(old.gainMapMax)) panic('new GainMap({ min, max }) differs from { gainMapMin, gainMapMax }'); - if (byName.hdrCapacityMax !== old.hdrCapacityMax) panic('new GainMap({ max }) should default hdrCapacityMax like gainMapMax'); - byName.min = [0, 0, 0]; - if (JSON.stringify(byName.gainMapMin) !== '[0,0,0]') panic('map.min should set gainMapMin'); - byName.gainMapMax = [4, 4, 4]; - if (JSON.stringify(byName.max) !== '[4,4,4]') panic('map.max should read gainMapMax'); - error = null; - try { new GainMap(pixels, {min: 0, gainMapMin: 0}); } catch (err) { error = err; } - if (!(error instanceof TypeError)) panic(`new GainMap({ min, gainMapMin }) should throw a TypeError, got ${error}`); -})(); diff --git a/tests/frame-count.js b/tests/frame-count.js new file mode 100644 index 00000000..e2a0bc9f --- /dev/null +++ b/tests/frame-count.js @@ -0,0 +1,36 @@ +const {Image, Frame, Animation, LimitError} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// every frame of an animation counts as at least 1024 pixels of maxPixels: a frame takes memory however small it is +// (200000 frames of 1x1, a 4.6 MB GIF, took 720 MB), so maxPixels bounds the memory of tiny frames too +(async () => { + const frames = count => Array.from({length: count}, (_, i) => new Frame(new Image(1, 1).fill((i * 0x01030507 | 0xff) >>> 0), {duration: 10})); + for (const format of ['GIF', 'APNG', 'WebP']) { + const encode = animation => format === 'GIF' ? animation.encodeGIF({optimize: false}) : format === 'APNG' ? animation.encodeAPNG({optimize: false}) : animation.encodeWebP({optimize: false, quality: 100}); + const few = await encode(new Animation(frames(99))); + const many = await encode(new Animation(frames(101))); + const fewDecoded = await Animation.decode(few, {maxPixels: 1024 * 100}); + if (fewDecoded.length !== 99) panic(`${format}: ${fewDecoded.length} frames decoded, expected 99`); + let error = null; + try { await Animation.decode(many, {maxPixels: 1024 * 100}); } catch (err) { error = err; } + if (!(error instanceof LimitError)) panic(`${format}: 101 frames of 1x1 with maxPixels 102400 should throw a LimitError, got ${error}`); + // a single image isn't charged for it + await Image.decode(many, {maxPixels: 1}); + } + + // the floor applies while the frames are decoded, not after all of them: 1000000 frames of 1x1 (23 MB) took 77 s and + // 1.8 GB before the LimitError + { + const frame = Buffer.from([0x21, 0xf9, 4, 0, 1, 0, 0, 0, 0x2c, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x44, 1, 0]); + const header = Buffer.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 1, 0, 1, 0, 0x80, 0, 0, 0, 0, 0, 255, 255, 255]); + const gif = Buffer.concat([header, Buffer.alloc(frame.length * 200000).map((_, i) => frame[i % frame.length]), Buffer.from([0x3b])]); + const start = Date.now(); + let error = null; + try { await Animation.decode(gif, {maxPixels: 1024 * 1000}); } catch (err) { error = err; } + if (!(error instanceof LimitError) || Date.now() - start > 1000) panic(`200000 GIF frames of 1x1 with room for 1000: ${error} after ${Date.now() - start} ms, expected a LimitError at once`); + } +})(); diff --git a/tests/gain-redraw.js b/tests/gain-redraw.js index bd2ef2fc..39339805 100644 --- a/tests/gain-redraw.js +++ b/tests/gain-redraw.js @@ -6,7 +6,7 @@ const panic = message => { process.exit(1); }; // the map's log2 gain at a map pixel (red channel) -const gain = (map, x, y) => map.gainMapMin[0] + (map.gainMapMax[0] - map.gainMapMin[0]) * (map.image.bitmap[4 * (y * map.width + x)] / 255) ** (1 / map.gamma[0]); +const gain = (map, x, y) => map.min[0] + (map.max[0] - map.min[0]) * (map.image.bitmap[4 * (y * map.width + x)] / 255) ** (1 / map.gamma[0]); const mapBytes = image => Buffer.from(image.gainMap.image.bitmap); (async () => { @@ -15,48 +15,48 @@ const mapBytes = image => Buffer.from(image.gainMap.image.bitmap); // drawing in a small area only changes the map where it was drawn: the rest of the map keeps its stored values, // and the range stays { - const image = await Image.decode(file), before = mapBytes(image), range = [image.gainMap.gainMapMin.slice(), image.gainMap.gainMapMax.slice()]; + const image = await Image.decode(file), before = mapBytes(image), range = [image.gainMap.min.slice(), image.gainMap.max.slice()]; const map = image.gainMap, sx = map.width / image.width, sy = map.height / image.height; const box = {x: 100, y: 80, width: 60, height: 40}; - image.drawBox(box.x, box.y, box.width, box.height, 0x000000ff); - if (JSON.stringify([map.gainMapMin, map.gainMapMax]) !== JSON.stringify(range)) panic('drawBox: the range of the map changed'); + image.composite(new Image(box.width, box.height).fill(0x000000ff), {x: box.x, y: box.y}); + if (JSON.stringify([map.min, map.max]) !== JSON.stringify(range)) panic('composite: the range of the map changed'); const after = mapBytes(image); let changed = 0; for (let y = 0; y < map.height; y++) for (let x = 0; x < map.width; x++) { const i = 4 * (y * map.width + x), inside = x >= Math.floor(box.x * sx) && x < Math.ceil((box.x + box.width) * sx) && y >= Math.floor(box.y * sy) && y < Math.ceil((box.y + box.height) * sy); const differs = before[i] !== after[i] || before[i + 1] !== after[i + 1] || before[i + 2] !== after[i + 2]; - if (differs && !inside) panic(`drawBox: the map changed outside the box at ${x},${y}`); + if (differs && !inside) panic(`composite: the map changed outside the box at ${x},${y}`); if (differs) changed++; } - if (changed === 0) panic('drawBox: black over highlights should change the map'); + if (changed === 0) panic('composite: black over highlights should change the map'); // black has no highlight: no boost where it covers the map pixel completely const cx = Math.floor((box.x + box.width / 2) * sx), cy = Math.floor((box.y + box.height / 2) * sy); - if (Math.abs(gain(map, cx, cy)) > 0.02) panic(`drawBox: the gain under black is ${gain(map, cx, cy)}`); + if (Math.abs(gain(map, cx, cy)) > 0.02) panic(`composite: the gain under black is ${gain(map, cx, cy)}`); } - // many thin boxes: the same map as drawing them one by one on a copy without a shortcut (the order doesn't matter) + // many thin translucent white lines (translucent black wouldn't change the gain: it dims the SDR and HDR light alike): the same map as drawing them one by one on a copy without a shortcut (the order doesn't matter) { const a = await Image.decode(file), b = await Image.decode(file); - for (let y = 0; y < a.height; y += 8) a.drawBox(0, y, a.width, 1, 0x00000055); - for (let y = a.height - (a.height % 8 || 8); y >= 0; y -= 8) b.drawBox(0, y, b.width, 1, 0x00000055); + for (let y = 0; y < a.height; y += 8) a.composite(new Image(a.width, 1).fill(0xffffff55), {x: 0, y: y}); + for (let y = a.height - (a.height % 8 || 8); y >= 0; y -= 8) b.composite(new Image(b.width, 1).fill(0xffffff55), {x: 0, y: y}); let worst = 0; for (let y = 0; y < a.gainMap.height; y += 7) for (let x = 0; x < a.gainMap.width; x += 7) worst = Math.max(worst, Math.abs(gain(a.gainMap, x, y) - gain(b.gainMap, x, y))); - if (worst > 0.05) panic(`drawBox: scanlines in a different order give different maps (${worst})`); - if (mapBytes(a).equals(mapBytes(await Image.decode(file)))) panic('drawBox: scanlines should change the map'); + if (worst > 0.05) panic(`composite: scanlines in a different order give different maps (${worst})`); + if (mapBytes(a).equals(mapBytes(await Image.decode(file)))) panic('composite: scanlines should change the map'); } // a drawing brighter than the map's range grows it, and the pixels the drawing didn't touch keep their gain { const image = await Image.decode(file), map = image.gainMap; const before = Array.from({length: 20}, (_, i) => gain(map, i * 7 % map.width, i * 11 % map.height)); - const max = map.gainMapMax[0]; + const max = map.max[0]; // an HDR source with a stronger map, composited over a part of the image const source = new Image(80, 80).fill(0xffffffff); source.gainMap = (await Image.decode(file)).gainMap.clone(); - source.gainMap.gainMapMax = [max + 2, max + 2, max + 2]; + source.gainMap.max = [max + 2, max + 2, max + 2]; source.gainMap.image.fill(0xffffffff); - image.composite(source, 10, 10); - if (!(map.gainMapMax[0] > max)) panic(`composite: the range should have grown beyond ${max}, it is ${map.gainMapMax[0]}`); + image.composite(source, {x: 10, y: 10}); + if (!(map.max[0] > max)) panic(`composite: the range should have grown beyond ${max}, it is ${map.max[0]}`); for (let i = 0; i < 20; i++) { const x = i * 7 % map.width, y = i * 11 % map.height; // (not where the source went: the map pixels of the image's 10 to 90) diff --git a/tests/gainmap-avif-colors.js b/tests/gainmap-avif-colors.js new file mode 100644 index 00000000..d76a0760 --- /dev/null +++ b/tests/gainmap-avif-colors.js @@ -0,0 +1,37 @@ +const {Image, GainMap} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +// the nclx colr boxes of an AVIF file: [offset of the primaries, primaries, transfer, matrix] +const nclx = data => { + const found = []; + for (let i = 0; i + 14 <= data.length; i++) + if (data[i] === 0x63 && data[i + 1] === 0x6f && data[i + 2] === 0x6c && data[i + 3] === 0x72 && String.fromCharCode(...data.subarray(i + 4, i + 8)) === 'nclx') + found.push([i + 8, data[i + 8] << 8 | data[i + 9], data[i + 10] << 8 | data[i + 11], data[i + 12] << 8 | data[i + 13]]); + return found; +}; + +// the colors of the HDR rendition (the tone mapped item's colr) stay through a decode and an encode: libavif writes +// BT.2020 there for a BT.709 base with useBaseColorSpace false, and the gains apply in those colors +(async () => { + const image = new Image(16, 16).fill(0x808080ff); + image.gainMap = new GainMap(new Image(8, 8).fill(0x808080ff), {max: 2, useBaseColorSpace: false}); + const file = await image.encodeAVIF({threads: 1}); + // the base, the map and the tone mapped item, in that order + const boxes = nclx(file); + if (boxes.length !== 3) panic(`expected 3 nclx boxes, found ${boxes.length}`); + const [offset] = boxes[2]; + file[offset] = 0; + file[offset + 1] = 9; + const decoded = await Image.decode(file); + const again = nclx(await decoded.encodeAVIF({threads: 1})); + if (again[2][1] !== 9 || again[2][2] !== boxes[2][2]) panic(`the HDR rendition's colors became primaries ${again[2][1]}, transfer ${again[2][2]} instead of 9, ${boxes[2][2]}`); + if (again[0][1] !== boxes[0][1]) panic('the base\'s colors changed'); + // a clone of the map keeps them too + const copy = decoded.clone(); + if (nclx(await copy.encodeAVIF({threads: 1}))[2][1] !== 9) panic('a clone lost the HDR rendition\'s colors'); + // a new map has the base's primaries with PQ, as before + if (boxes[2][1] !== boxes[0][1] || boxes[2][2] !== 16) panic(`a new map's HDR colors: ${boxes[2]}`); +})(); diff --git a/tests/gainmap-range.js b/tests/gainmap-range.js new file mode 100644 index 00000000..6fba17e8 --- /dev/null +++ b/tests/gainmap-range.js @@ -0,0 +1,37 @@ +const {Image, GainMap} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +const map = new Image(4, 4).fill(0x808080ff); +const LIMIT = 2 ** 31 - 1; + +// the parameters are limited to what the ISO 21496-1 fractions of JPEG, AVIF and JPEG XL hold: beyond them they were +// written wrapped (an offset of 1e12 came back as -727379968), or as 0, and decoders dropped the map +(async () => { + for (const options of [{min: -LIMIT - 1}, {max: LIMIT + 1, hdrCapacityMax: 2}, {max: 1e12, hdrCapacityMax: 2}, {offsetSDR: 1e12}, {offsetHDR: -LIMIT - 1}, {hdrCapacityMax: LIMIT + 1}, {hdrCapacityMin: LIMIT + 1, hdrCapacityMax: LIMIT + 2}, {gamma: 1e-10}, {gamma: LIMIT + 1}]) { + let error = null; + try { new GainMap(map, options); } catch (err) { error = err; } + if (!(error instanceof RangeError) || !/must be/.test(error.message)) panic(`new GainMap(${JSON.stringify(options)}) should throw a RangeError, got ${error}`); + const gainMap = new GainMap(map); + const [name] = Object.keys(options); + const before = JSON.stringify(gainMap[name]); + try { gainMap[name] = options[name]; } catch {} + if (JSON.stringify(gainMap[name]) !== before) panic(`gainMap.${name} = ${options[name]} should keep the old value`); + } + // the edges are written and read back exactly + const base = new Image(8, 8).fill(0x808080ff); + for (const options of [{min: -LIMIT, max: LIMIT, hdrCapacityMax: 2}, {offsetSDR: LIMIT, offsetHDR: -LIMIT}, {hdrCapacityMax: LIMIT}, {gamma: 2 ** -31}, {gamma: LIMIT}]) { + for (const format of ['encodeJPEG', 'encodeAVIF', 'encodeJXL']) { + const image = base.clone(); + image.gainMap = new GainMap(map, options); + const back = (await Image.decode(await image[format]({threads: 1}))).gainMap; + if (!back) panic(`${format} with ${JSON.stringify(options)} lost the gain map`); + for (const [name, value] of Object.entries(options)) { + const got = typeof back[name] === 'number' ? back[name] : back[name][0]; + if (got !== value) panic(`${format} with ${JSON.stringify(options)} read ${name} back as ${got}`); + } + } + } +})(); diff --git a/tests/gainmap.js b/tests/gainmap.js index 74762208..4e3643b5 100644 --- a/tests/gainmap.js +++ b/tests/gainmap.js @@ -1,5 +1,5 @@ const fs = require('fs').promises; -const {Image, GainMap} = require('..'); +const {Image, GainMap, Colors} = require('..'); const panic = message => { console.error(message); @@ -8,7 +8,7 @@ const panic = message => { const close = (a, b, epsilon = 1e-4) => a.every((v, i) => Math.abs(v - b[i]) <= epsilon); const same = (a, b) => Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap)); // the map's value for a gain (log2), channel 0 -const stored = (map, gain) => 255 * Math.min(1, Math.max(0, (gain - map.gainMapMin[0]) / (map.gainMapMax[0] - map.gainMapMin[0]))) ** map.gamma[0]; +const stored = (map, gain) => 255 * Math.min(1, Math.max(0, (gain - map.min[0]) / (map.max[0] - map.min[0]))) ** map.gamma[0]; // the mean of the map's red channel over an area of the image const meanValue = (image, left, top, right, bottom) => { const map = image.gainMap.image, sx = map.width / image.width, sy = map.height / image.height; @@ -32,11 +32,11 @@ const meanValue = (image, left, top, right, bottom) => { const map = image.gainMap; if (!(map instanceof GainMap)) panic(`${name}: no gain map`); if (map.channels !== channels || map.width !== 512 || map.height !== 384) panic(`${name}: ${map.channels} channels, ${map.width}x${map.height}`); - if (Math.abs(map.gainMapMax[0] - 2.1814) > 1e-3 || Math.abs(map.hdrCapacityMax - 2.3) > 1e-3 || map.hdrCapacityMin !== 0 || map.gamma[0] !== 1 || map.useBaseColorSpace) - panic(`${name}: parameters ${map.gainMapMax} ${map.hdrCapacityMax} ${map.gamma} ${map.useBaseColorSpace}`); + if (Math.abs(map.max[0] - 2.1814) > 1e-3 || Math.abs(map.hdrCapacityMax - 2.3) > 1e-3 || map.hdrCapacityMin !== 0 || map.gamma[0] !== 1 || map.useBaseColorSpace) + panic(`${name}: parameters ${map.max} ${map.hdrCapacityMax} ${map.gamma} ${map.useBaseColorSpace}`); if (!same(image, await Image.decode(files[name], {gainMap: false}))) panic(`${name}: the base differs with the gain map`); } - if (single.gainMap.gainMapMin[0] > -0.47 || single.gainMap.gainMapMin[0] < -0.49) panic(`single-channel: gainMapMin ${single.gainMap.gainMapMin[0]}`); + if (single.gainMap.min[0] > -0.47 || single.gainMap.min[0] < -0.49) panic(`single-channel: min ${single.gainMap.min[0]}`); if ((await Image.decode(files['single-channel'], {gainMap: false})).gainMap !== null) panic('gainMap: false still read the map'); // a cut off map (the MPF index pointing past the end) and a broken ISO block: no map, the base decodes @@ -49,10 +49,10 @@ const meanValue = (image, left, top, right, bottom) => { // out for (const name of ['single-channel', 'multi-channel']) { const image = await Image.decode(files[name]); - const encoded = await image.encodeJPEG(90); + const encoded = await image.encodeJPEG({quality: 90}); const plain = await image.encodeJPEG({quality: 90, gainMap: false}); const back = await Image.decode(encoded); - if (!back.gainMap || !close(back.gainMap.gainMapMax, image.gainMap.gainMapMax) || !close(back.gainMap.gainMapMin, image.gainMap.gainMapMin) || back.gainMap.hdrCapacityMax !== image.gainMap.hdrCapacityMax) + if (!back.gainMap || !close(back.gainMap.max, image.gainMap.max) || !close(back.gainMap.min, image.gainMap.min) || back.gainMap.hdrCapacityMax !== image.gainMap.hdrCapacityMax) panic(`${name}: the written map's parameters differ`); { let sum = 0; @@ -65,7 +65,6 @@ const meanValue = (image, left, top, right, bottom) => { // re-encoded (its pixels used): close; a quarter of the size const used = await Image.decode(files[name]); - void used.gainMap.image; const reencoded = await Image.decode(await used.encodeJPEG({quality: 90, gainMap: {quality: 90}})); let sum = 0; const a = reencoded.gainMap.image.bitmap, b = used.gainMap.image.bitmap; @@ -77,25 +76,56 @@ const meanValue = (image, left, top, right, bottom) => { // a map alone, without ISO 21496-1 (only hdrgm XMP): read from the XMP { - const alone = Buffer.from(await single.gainMap.encode()); + const alone = Buffer.from(await single.gainMap.encodeJPEG()); const iso = alone.indexOf('urn:iso:std:iso:ts:21496:-1'); const start = iso - 4, length = alone.readUInt16BE(iso - 2); const xmpOnly = Buffer.concat([alone.subarray(0, start), alone.subarray(start + 2 + length)]); if (xmpOnly.includes('urn:iso:std:iso:ts:21496:-1') || !xmpOnly.includes('hdrgm:GainMapMax')) panic('XMP only map: test file wrong'); const map = await GainMap.decode(xmpOnly); - if (!close(map.gainMapMax, single.gainMap.gainMapMax) || !close(map.gainMapMin, single.gainMap.gainMapMin) || Math.abs(map.hdrCapacityMax - single.gainMap.hdrCapacityMax) > 1e-5) - panic(`XMP only map: ${map.gainMapMin} ${map.gainMapMax} ${map.hdrCapacityMax} vs ${single.gainMap.gainMapMin} ${single.gainMap.gainMapMax}`); + if (!close(map.max, single.gainMap.max) || !close(map.min, single.gainMap.min) || Math.abs(map.hdrCapacityMax - single.gainMap.hdrCapacityMax) > 1e-5) + panic(`XMP only map: ${map.min} ${map.max} ${map.hdrCapacityMax} vs ${single.gainMap.min} ${single.gainMap.max}`); + } + + // decoding a map alone takes the limit of the decode options, and a damaged one says so (like Image.decode) + { + const alone = await single.gainMap.encodeJPEG(); + const lib = require('..'); + const map = await GainMap.decode(alone, {maxPixels: single.gainMap.width * single.gainMap.height}); + if (map.width !== single.gainMap.width) panic('GainMap.decode with a limit that fits'); + let error = null; + try { await GainMap.decode(alone, {maxPixels: 10}); } catch (err) { error = err; } + if (!(error instanceof lib.LimitError)) panic(`GainMap.decode over the limit: ${error}`); + error = null; + try { await GainMap.decode(new Uint8Array(100)); } catch (err) { error = err; } + if (!error || error instanceof lib.LimitError) panic(`GainMap.decode of garbage: ${error}`); + for (const bad of [5, 'x', null]) { + error = null; + try { await GainMap.decode(alone, bad); } catch (err) { error = err; } + if (!(error instanceof TypeError)) panic(`GainMap.decode(data, ${bad}) should throw a TypeError`); + } + } + + // the checks between the values run when the map is cloned or encoded, not when one is set + { + const map = new GainMap(new Image(4, 4).fill(0x808080ff), {max: 2}); + map.min = 5; + let error = null; + try { map.clone(); } catch (err) { error = err; } + if (!(error instanceof RangeError)) panic(`min above max: ${error}`); + error = null; + try { new GainMap(new Image(4, 4), {max: 0}); } catch (err) { error = err; } + if (!(error instanceof RangeError)) panic(`max 0: ${error}`); } // made by hand: parameters checked, written and read back; per channel values { const image = new Image(64, 48).fill(0x808080ff); - image.gainMap = new GainMap(new Image(16, 12).fill((x, y) => Image.rgbaToColor(x * 16, y * 20, 255 - x * 16, 255)), {gainMapMax: [2, 3, 4], gainMapMin: -1, gamma: 2}); - const back = await Image.decode(await image.encodeJPEG(95)); + image.gainMap = new GainMap(new Image(16, 12).fill((x, y) => Colors.fromRGBA(x * 16, y * 20, 255 - x * 16, 255)), {max: [2, 3, 4], min: -1, gamma: 2}); + const back = await Image.decode(await image.encodeJPEG({quality: 95})); const map = back.gainMap; - if (!map || map.channels !== 3 || !close(map.gainMapMax, [2, 3, 4]) || !close(map.gainMapMin, [-1, -1, -1]) || !close(map.gamma, [2, 2, 2]) || map.hdrCapacityMax !== 4 || map.width !== 16) - panic(`hand made map: ${map ? [map.channels, map.gainMapMin, map.gainMapMax, map.gamma, map.hdrCapacityMax, map.width] : 'none'}`); - for (const [options, error] of [[{gamma: 0}, RangeError], [{gainMapMax: -2}, RangeError], [{gainMapMax: [1, 2]}, RangeError], [{gainMapMax: NaN}, RangeError], [{hdrCapacityMin: 3, hdrCapacityMax: 2}, RangeError]]) + if (!map || map.channels !== 3 || !close(map.max, [2, 3, 4]) || !close(map.min, [-1, -1, -1]) || !close(map.gamma, [2, 2, 2]) || map.hdrCapacityMax !== 4 || map.width !== 16) + panic(`hand made map: ${map ? [map.channels, map.min, map.max, map.gamma, map.hdrCapacityMax, map.width] : 'none'}`); + for (const [options, error] of [[{gamma: 0}, RangeError], [{max: -2}, RangeError], [{max: [1, 2]}, RangeError], [{max: NaN}, RangeError], [{hdrCapacityMin: 3, hdrCapacityMax: 2}, RangeError]]) try { new GainMap(new Image(4, 4), options); panic(`GainMap ${JSON.stringify(options)} didn't throw`); @@ -127,7 +157,7 @@ const meanValue = (image, left, top, right, bottom) => { const quarter = await Image.decode(await multi.encodeJPEG({gainMap: {scale: 0.25}})); quarter.crop(100, 40, 200, 160).resize(100, 80); if (quarter.gainMap.width !== 25 || quarter.gainMap.height !== 20) panic(`crop + resize: map ${quarter.gainMap.width}x${quarter.gainMap.height}`); - const region = multi.region(10, 20, 100, 50); + const region = multi.extract(10, 20, 100, 50); if (region.gainMap.width !== 100 || multi.gainMap.width !== 512) panic('region: the map'); } @@ -140,25 +170,25 @@ const meanValue = (image, left, top, right, bottom) => { const oriented = Buffer.concat([files['multi-channel'].subarray(0, app0End), segment, files['multi-channel'].subarray(app0End)]); const image = await Image.decode(oriented); if (image.width !== 384 || !image.gainMap || image.gainMap.width !== 384) panic(`orientation: ${image.width}, map ${image.gainMap?.width}`); - // (orientation 6: turned clockwise, rotate(270)) - if (!same(image, multi.clone().rotate(270))) panic('orientation: test file wrong'); - if (!same(image.gainMap.image, multi.gainMap.image.clone().rotate(270))) panic('orientation: the map wasn\'t turned like the image'); + // (orientation 6: turned clockwise, rotate(90)) + if (!same(image, multi.clone().rotate(90))) panic('orientation: test file wrong'); + if (!same(image.gainMap.image, multi.gainMap.image.clone().rotate(90))) panic('orientation: the map wasn\'t turned like the image'); } // drawing over it: no boost where something without one went, the rest as it was { const image = single.clone(); - image.composite(new Image(100, 100).fill(0x336699ff), 200, 100); + image.composite(new Image(100, 100).fill(0x336699ff), {x: 200, y: 100}); const neutral = stored(image.gainMap, 0); if (Math.abs(meanValue(image, 204, 104, 296, 196) - neutral) > 1.5) panic(`composite: ${meanValue(image, 204, 104, 296, 196)} under the box, no boost is ${neutral}`); // (the range can grow: compared as gains) - const gainAt = (img, value) => img.gainMap.gainMapMin[0] + (img.gainMap.gainMapMax[0] - img.gainMap.gainMapMin[0]) * (value / 255) ** (1 / img.gainMap.gamma[0]); + const gainAt = (img, value) => img.gainMap.min[0] + (img.gainMap.max[0] - img.gainMap.min[0]) * (value / 255) ** (1 / img.gainMap.gamma[0]); const outside = gainAt(image, meanValue(image, 0, 0, 512, 90)), before = gainAt(single, meanValue(single, 0, 0, 512, 90)); if (Math.abs(outside - before) > 0.02) panic(`composite: changed outside the box (${outside} vs ${before})`); - const boxed = single.clone().drawBox(0, 0, 64, 64, 0xffffffff); - if (Math.abs(meanValue(boxed, 0, 0, 60, 60) - stored(boxed.gainMap, 0)) > 1.5) panic('drawBox: boost left under the box'); + const boxed = single.clone().composite(new Image(64, 64).fill(0xffffffff), {x: 0, y: 0}); + if (Math.abs(meanValue(boxed, 0, 0, 60, 60) - stored(boxed.gainMap, 0)) > 1.5) panic('composite: boost left under the box'); // (an image with a map composited onto one without: the canvas gets one, its own part as the source's) - const canvas = new Image(600, 500).fill(0x000000ff).composite(single, 40, 60); + const canvas = new Image(600, 500).fill(0x000000ff).composite(single, {x: 40, y: 60}); if (!canvas.gainMap || Math.abs(meanValue(canvas, 50, 70, 540, 150) - meanValue(single, 10, 10, 500, 90)) > 6) panic('composite onto a canvas: the map'); } @@ -166,7 +196,7 @@ const meanValue = (image, left, top, right, bottom) => { { const image = single.clone().brightness(1).contrast(1); if (!same(image.gainMap.image, single.gainMap.image)) panic('brightness(1): the map changed'); - const grey = single.clone().greyscale(); + const grey = single.clone().grayscale(); if (!same(grey.gainMap.image, single.gainMap.image)) panic('greyscale: a single channel map changed'); } @@ -182,7 +212,7 @@ const meanValue = (image, left, top, right, bottom) => { + '131072' + (headroomXMP ? `${headroomXMP}` : '') + 'urn:com:apple:photo:2020:aux:hdrgainmap'; - return Promise.all([new Image(128, 64).fill(0x808080ff).encodeJPEG(90), ramp.encodeJPEG(100)]).then(([base, map]) => { + return Promise.all([new Image(128, 64).fill(0x808080ff).encodeJPEG({quality: 90}), ramp.encodeJPEG({quality: 100})]).then(([base, map]) => { map = afterSOI(Buffer.from(map), segment(0xe1, Buffer.concat([Buffer.from('http://ns.adobe.com/xap/1.0/\0'), Buffer.from(xmp)]))); // the primary's MPF index (big endian), offsets from its TIFF header const mpf = Buffer.alloc(4 + 82); @@ -217,18 +247,18 @@ const meanValue = (image, left, top, right, bottom) => { for (const [name, file, headroom] of [['XMP headroom', await appleFile('4', null), 4], ['maker note headroom', await appleFile(null, exif), 2 ** 1.8]]) { const image = await Image.decode(file); const map = image.gainMap; - if (!map || Math.abs(map.gainMapMax[0] - Math.log2(headroom)) > 1e-4 || map.gainMapMin[0] !== 0 || map.hdrCapacityMax !== map.gainMapMax[0]) panic(`Apple, ${name}: ${map ? map.gainMapMax : 'no map'}`); + if (!map || Math.abs(map.max[0] - Math.log2(headroom)) > 1e-4 || map.min[0] !== 0 || map.hdrCapacityMax !== map.max[0]) panic(`Apple, ${name}: ${map ? map.max : 'no map'}`); // the ramp's values as Apple applies them const px = map.image.bitmap; for (let x = 0; x < 64; x += 9) { const stored = Math.min(255, x * 4) / 255; const want = Math.log2(1 + (headroom - 1) * stored ** 1.961); - const got = map.gainMapMax[0] * px[4 * x] / 255; + const got = map.max[0] * px[4 * x] / 255; if (Math.abs(want - got) > 0.03) panic(`Apple, ${name}: value ${x * 4} gives ${got} stops, not ${want}`); } // written as an Ultra HDR JPEG (ISO 21496-1 and hdrgm), the same boosts - const back = (await Image.decode(await image.encodeJPEG(90))).gainMap; - if (!back || !close(back.gainMapMax, map.gainMapMax)) panic(`Apple, ${name}: not written back`); + const back = (await Image.decode(await image.encodeJPEG({quality: 90}))).gainMap; + if (!back || !close(back.max, map.max)) panic(`Apple, ${name}: not written back`); } } @@ -237,8 +267,8 @@ const meanValue = (image, left, top, right, bottom) => { const avif = await image.encodeAVIF({quality: 80}); const back = await Image.decode(avif); const map = back.gainMap; - if (!map || map.channels !== image.gainMap.channels || map.width !== image.gainMap.width || !close(map.gainMapMax, image.gainMap.gainMapMax) || !close(map.gainMapMin, image.gainMap.gainMapMin) || Math.abs(map.hdrCapacityMax - image.gainMap.hdrCapacityMax) > 1e-6) - panic(`AVIF ${name}: ${map ? `${map.channels} channels, ${map.width}, ${map.gainMapMax}` : 'no gain map'}`); + if (!map || map.channels !== image.gainMap.channels || map.width !== image.gainMap.width || !close(map.max, image.gainMap.max) || !close(map.min, image.gainMap.min) || Math.abs(map.hdrCapacityMax - image.gainMap.hdrCapacityMax) > 1e-6) + panic(`AVIF ${name}: ${map ? `${map.channels} channels, ${map.width}, ${map.max}` : 'no gain map'}`); let sum = 0; const a = map.image.bitmap, b = image.gainMap.image.bitmap; for (let i = 0; i < a.length; i += 4) sum += Math.abs(a[i] - b[i]); @@ -256,8 +286,8 @@ const meanValue = (image, left, top, right, bottom) => { const jxl = await image.encodeJXL(options); const back = await Image.decode(jxl); const map = back.gainMap; - if (!map || map.channels !== image.gainMap.channels || map.width !== image.gainMap.width || !close(map.gainMapMax, image.gainMap.gainMapMax) || !close(map.gainMapMin, image.gainMap.gainMapMin) || Math.abs(map.hdrCapacityMax - image.gainMap.hdrCapacityMax) > 1e-6) - panic(`JXL ${name} ${JSON.stringify(options)}: ${map ? `${map.channels} channels, ${map.width}, ${map.gainMapMax}` : 'no gain map'}`); + if (!map || map.channels !== image.gainMap.channels || map.width !== image.gainMap.width || !close(map.max, image.gainMap.max) || !close(map.min, image.gainMap.min) || Math.abs(map.hdrCapacityMax - image.gainMap.hdrCapacityMax) > 1e-6) + panic(`JXL ${name} ${JSON.stringify(options)}: ${map ? `${map.channels} channels, ${map.width}, ${map.max}` : 'no gain map'}`); let sum = 0; const a = map.image.bitmap, b = image.gainMap.image.bitmap; for (let i = 0; i < a.length; i += 4) sum += Math.abs(a[i] - b[i]); @@ -271,7 +301,8 @@ const meanValue = (image, left, top, right, bottom) => { } // invalid arguments throw before the image or its map changes - for (const [name, call] of [['blur', i => i.blur('5')], ['fill', i => i.fill('red')], ['cover', i => i.cover(-1, 10)]]) { + for (const [name, call] of [['blur', i => i.blur('5')], ['fill', i => i.fill('red')], ['resize cover', i => i.resize({width: -1, height: 10, fit: 'cover'})], + ['resize cover that can\'t be allocated', i => i.resize({width: 2 ** 31 - 1, height: 2 ** 31 - 1, fit: 'cover'})], ['fill that throws halfway', i => i.fill((x, y) => y > 2 ? NaN : 0xff0000ff)]]) { const image = single.clone(); let threw = false; try { call(image); } catch { threw = true; } @@ -284,24 +315,44 @@ const meanValue = (image, left, top, right, bottom) => { { const gainsOf = map => { const px = map.image.bitmap, out = []; - for (let i = 0; i < px.length; i += 4) out.push(map.gainMapMin[0] + (map.gainMapMax[0] - map.gainMapMin[0]) * (px[i] / 255) ** (1 / map.gamma[0])); + for (let i = 0; i < px.length; i += 4) out.push(map.min[0] + (map.max[0] - map.min[0]) * (px[i] / 255) ** (1 / map.gamma[0])); return out; }; const bright = new Image(64, 64).fill((x, y) => ((y * 4) * 0x1010100 | 255) >>> 0); - bright.gainMap = new GainMap(new Image(64, 64).fill(x => ((x * 4) * 0x1010100 | 255) >>> 0), {gainMapMin: 0, gainMapMax: 2, offsetSDR: 0, offsetHDR: 0}); + bright.gainMap = new GainMap(new Image(64, 64).fill(x => ((x * 4) * 0x1010100 | 255) >>> 0), {min: 0, max: 2, offsetSDR: 0, offsetHDR: 0}); for (const [name, edit] of [['contrast 1.4', i => i.contrast(1.4)], ['contrast 0.6', i => i.contrast(0.6)], ['brightness 1.3', i => i.brightness(1.3)], ['gamma 1.5', i => i.gamma(1.5)], ['lightness 1.2', i => i.lightness(1.2)]]) { const out = edit(bright.clone()); const lowest = Math.min(...gainsOf(out.gainMap)); if (lowest < -0.05) panic(`${name}: the HDR rendition got darker than SDR (gain ${lowest})`); } - if (!(Math.max(...bright.clone().contrast(1.4).gainMap.gainMapMax) > 2)) panic('contrast 1.4: the highlights didn\'t stretch'); + if (!(Math.max(...bright.clone().contrast(1.4).gainMap.max) > 2)) panic('contrast 1.4: the highlights didn\'t stretch'); const inverted = bright.clone().invert().gainMap; if (gainsOf(inverted).some(g => Math.abs(g) > 0.02)) panic('invert: the map still boosts'); } + // a map given to images is copied: resizing or cropping one image leaves the others' maps (and the map given) alone + { + const given = new GainMap(new Image(8, 8).fill(0x808080ff), {max: 2}); + const a = new Image(64, 64), b = new Image(64, 64), c = new Image(64, 64); + a.gainMap = given; + b.gainMap = given; + c.gainMap = given; + b.resize(32, 32); + c.crop(0, 0, 16, 16); + const size = image => `${image.gainMap.image.width}x${image.gainMap.image.height}`; + if (size(a) !== '8x8' || given.image.width !== 8) panic(`a map shared by images: ${size(a)} and ${given.image.width}x${given.image.height} after the others changed, expected 8x8`); + if (size(b) !== '4x4' || size(c) !== '2x2') panic(`the images' own maps: ${size(b)} and ${size(c)}, expected 4x4 and 2x2`); + given.max = 4; + if (a.gainMap.max[0] !== 2) panic('a map changed after it was given to an image reached the image'); + // (the image's own map stays live: it is the object the getter returns, and the image's operations update it) + const own = a.gainMap; + a.resize(32, 32); + if (a.gainMap !== own || own.image.width !== 4) panic('the image\'s own map should be the same object, resized'); + } + // other formats don't carry it, removing works const removed = single.clone(); removed.gainMap = null; if ((await Image.decode(await removed.encodeJPEG())).gainMap !== null) panic('removed map still written'); - if ((await Image.decode(await single.encode())).gainMap !== null) panic('PNG with a gain map'); + if ((await Image.decode(await single.encodePNG())).gainMap !== null) panic('PNG with a gain map'); })(); diff --git a/tests/gif.js b/tests/gif.js index 2e13e759..967c1605 100644 --- a/tests/gif.js +++ b/tests/gif.js @@ -1,6 +1,6 @@ const fs = require('fs').promises; const crypto = require('crypto'); -const {Frame, GIF} = require('..'); +const {Image, Frame, Animation, Colors} = require('..'); const panic = message => { console.error(message); @@ -10,19 +10,19 @@ const panic = message => { (async () => { const frames = []; for (let i = 0; i < 30; i++) { - const frame = new Frame(256, 256); - frame.fill(x => Frame.hslToColor(x / frame.width + i / 30, 1, 0.5)); + const frame = new Frame(new Image(256, 256)); + frame.image.fill(x => Colors.fromHSL((x / frame.width + i / 30) * 360, 1, 0.5)); frames.push(frame); } - const gif = new GIF(frames); + const gif = new Animation(frames); if (process.env.OVERWRITE_TEST) - await fs.writeFile('./tests/targets/gif.gif', await gif.encode(1)); + await fs.writeFile('./tests/targets/gif.gif', await gif.encodeGIF({colors: 8})); { const binary = await fs.readFile('./tests/targets/gif.gif'); - const decoded = await GIF.decode(binary); + const decoded = await Animation.decode(binary); if (decoded.width !== gif.width) panic('decode: incorrect width'); if (decoded.height !== gif.height) @@ -31,42 +31,42 @@ const panic = message => { panic('decode: incorrect frame count'); for (let i = 0; i < gif.length; i++) { - if (gif[i].bitmap.length !== decoded[i].bitmap.length) + if (gif.frames[i].image.bitmap.length !== decoded.frames[i].image.bitmap.length) panic('decode: incorrect frame bitmap length'); } - const first = await GIF.decode(binary, true); - if (first.length !== 1) - panic('decode: onlyExtractFirstFrame returned more than one frame'); + const first = await Image.decode(binary); + if (first.constructor !== Image) + panic('decode: Image.decode should return the first frame as an Image'); } { // frames with <= 256 colors survive a roundtrip losslessly - const decoded = await GIF.decode(await gif.encode()); + const decoded = await Animation.decode(await gif.encodeGIF()); for (let i = 0; i < gif.length; i++) - if (!Buffer.from(decoded[i].bitmap).equals(Buffer.from(gif[i].bitmap))) + if (!Buffer.from(decoded.frames[i].image.bitmap).equals(Buffer.from(gif.frames[i].image.bitmap))) panic(`roundtrip: frame ${i} differs`); - if (decoded[0].duration !== gif[0].duration) + if (decoded.frames[0].duration !== gif.frames[0].duration) panic('roundtrip: incorrect duration'); - if (decoded.loopCount !== -1) + if (decoded.loopCount !== Infinity) panic('roundtrip: incorrect loop count'); } { // offsets, transparency, disposal modes and finite loop counts - const black = Frame.rgbaToColor(0, 0, 0, 255); - const white = Frame.rgbaToColor(255, 255, 255, 255); - - const background = new Frame(4, 4, 100); - background.fill(black); - const dot = new Frame(1, 1, 100, 1, 1, Frame.DISPOSAL_PREVIOUS); - dot.fill(white); - const hole = new Frame(2, 2, 100, 2, 2, Frame.DISPOSAL_BACKGROUND); - hole.fill((x, y) => x === y ? white : 0); - const last = new Frame(1, 1, 100, 0, 0); - last.fill(white); - - const decoded = await GIF.decode(await new GIF([background, dot, hole, last], 2).encode()); + const black = Colors.fromRGBA(0, 0, 0, 255); + const white = Colors.fromRGBA(255, 255, 255, 255); + + const background = new Frame(new Image(4, 4), {duration: 100}); + background.image.fill(black); + const dot = new Frame(new Image(1, 1), {duration: 100, xOffset: 1, yOffset: 1, disposalMode: 'previous'}); + dot.image.fill(white); + const hole = new Frame(new Image(2, 2), {duration: 100, xOffset: 2, yOffset: 2, disposalMode: 'background'}); + hole.image.fill((x, y) => x === y ? white : 0); + const last = new Frame(new Image(1, 1), {duration: 100, xOffset: 0, yOffset: 0}); + last.image.fill(white); + + const decoded = await Animation.decode(await new Animation([background, dot, hole, last], {loopCount: 2}).encodeGIF()); if (decoded.loopCount !== 2) panic('disposal: incorrect loop count'); @@ -74,7 +74,7 @@ const panic = message => { for (let y = 0; y < 4; y++) for (let x = 0; x < 4; x++) { const want = pixels[y * 4 + x]; - const got = decoded[frame].getPixelAt(x, y); + const got = decoded.frames[frame].image.getPixelAt(x, y); if (want === 'B' ? got !== black : want === 'W' ? got !== white : got !== 0) panic(`disposal: frame ${frame} pixel ${x},${y} is ${got.toString(16)}`); } @@ -88,19 +88,33 @@ const panic = message => { // interlaced: written by Pillow (scripts/gif-fixtures.py), the sha256 of its RGBA pixels as Pillow decodes them { - const [frame] = await GIF.decode(await fs.readFile('./tests/gifs/interlaced.gif')); + const [frame] = (await Animation.decode(await fs.readFile('./tests/gifs/interlaced.gif'))).frames; if (frame.width !== 80 || frame.height !== 37) panic('interlaced: dimensions don\'t match'); - if (crypto.createHash('sha256').update(new Uint8Array(frame.bitmap)).digest('hex') !== '854e5e98f2124a6009d5bc28748772ede25af244a2503021ef4f52e323309d46') + if (crypto.createHash('sha256').update(new Uint8Array(frame.image.bitmap)).digest('hex') !== '854e5e98f2124a6009d5bc28748772ede25af244a2503021ef4f52e323309d46') panic('interlaced: pixels don\'t match'); } // damaged files keep the frames decoded so far: cut off, or an unknown block before the trailer { const binary = await fs.readFile('./tests/targets/gif.gif'); - const cut = await GIF.decode(binary.subarray(0, binary.length >> 1)); + const cut = await Animation.decode(binary.subarray(0, binary.length >> 1)); if (!cut.length || cut.length >= 30) panic(`truncated: ${cut.length} frames decoded`); - const unknown = await GIF.decode(Buffer.concat([binary.subarray(0, -1), Buffer.from([0x99, 0x3b])])); + const unknown = await Animation.decode(Buffer.concat([binary.subarray(0, -1), Buffer.from([0x99, 0x3b])])); if (unknown.length !== 30) panic(`unknown block: ${unknown.length} frames decoded`); + + // a screen of no pixels is a decoding error, not a RangeError from making an image of it + const flat = Buffer.from(binary); + flat.writeUInt16LE(0, 8); + for (const [name, decode] of [['Animation.decode', () => Animation.decode(flat)], ['Image.decode', () => Image.decode(flat)]]) { + if (!await decode().then(() => false, error => error.constructor === Error)) panic(`${name} of a GIF without height should throw an Error`); + } + + // cut off before the first frame is whole: there is no image, not a blank one + for (const length of [13, 20, 40]) { + for (const [name, decode] of [['Animation.decode', () => Animation.decode(binary.subarray(0, length))], ['Image.decode', () => Image.decode(binary.subarray(0, length))]]) { + if (!await decode().then(() => false, error => error instanceof Error)) panic(`${name} of ${length} bytes should throw`); + } + } } })(); diff --git a/tests/hdr.js b/tests/hdr.js index 7712cec9..78f560be 100644 --- a/tests/hdr.js +++ b/tests/hdr.js @@ -40,6 +40,6 @@ const sha = image => crypto.createHash('sha256').update(new Uint8Array(image.bit // invalid data throws for (const text of ['#?RADIANCE\nFORMAT=32-bit_rle_cmyk\n\n-Y 1 +X 1\n\0\0\0\0', '#?RADIANCE\n\n-Y 1 -Y 1\n\0\0\0\0', '#?RADIANCE\n\n-Y 2 +X 8\n\x02\x02\x00\x09']) { const data = Uint8Array.from(text, c => c.charCodeAt(0)); - if (!await Image.decode(data).then(() => false, e => /HDR/.test(e.message))) panic(`invalid HDR accepted: ${JSON.stringify(text)}`); + if (!await Image.decode(data).then(() => false, e => e instanceof Error)) panic(`invalid HDR accepted: ${JSON.stringify(text)}`); } })(); diff --git a/tests/icc.js b/tests/icc.js index 4b84c522..46bdb2e0 100644 --- a/tests/icc.js +++ b/tests/icc.js @@ -53,11 +53,11 @@ const difference = (a, b) => { const animation = await Animation.decode(await fs.readFile('./tests/icc/display-p3-animated.webp')); for (const i of [0, 1]) { const ref = await Image.decode(await fs.readFile(`./tests/icc/display-p3-animated-${i + 1}.ref.png`)); - if (difference(animation[i], ref) > 1) panic(`animated WebP frame ${i + 1}: differs from LittleCMS`); + if (difference(animation.frames[i].image, ref) > 1) panic(`animated WebP frame ${i + 1}: differs from LittleCMS`); } // (JPEG XLs through Animation.decode too) const jxlFrames = await Animation.decode(await fs.readFile('./tests/icc/display-p3.jxl')); - if (difference(jxlFrames[0], await Image.decode(await fs.readFile('./tests/icc/display-p3.ref.png'))) > 1) panic('JPEG XL through Animation.decode: differs from LittleCMS'); + if (difference(jxlFrames.frames[0].image, await Image.decode(await fs.readFile('./tests/icc/display-p3.ref.png'))) > 1) panic('JPEG XL through Animation.decode: differs from LittleCMS'); // lossless JPEG XLs in an enumerated color space (no ICC profile, like cjxl writes Display P3): converted to sRGB // like an embedded profile. The Display P3 values, losslessly encoded, with the image header's color encoding @@ -72,7 +72,7 @@ const difference = (a, b) => { const p3Decoded = await Image.decode(enumerated); if (difference(p3Decoded, p3Ref) > 1) panic(`enumerated Display P3 JPEG XL: differs from LittleCMS by ${difference(p3Decoded, p3Ref)}`); if (difference(await Image.decode(enumerated, {applyColorProfile: false}), p3) !== 0) panic('enumerated Display P3 JPEG XL, applyColorProfile: false: should keep the stored colors'); - if (difference((await Animation.decode(enumerated))[0], p3Ref) > 1) panic('enumerated Display P3 JPEG XL through Animation.decode: differs from LittleCMS'); + if (difference((await Animation.decode(enumerated)).frames[0].image, p3Ref) > 1) panic('enumerated Display P3 JPEG XL through Animation.decode: differs from LittleCMS'); })(); // the codestream of a JPEG XL in the container (our encoder's: one jxlc box) diff --git a/tests/ico.js b/tests/ico.js index 251d5ac9..39261be3 100644 --- a/tests/ico.js +++ b/tests/ico.js @@ -32,7 +32,8 @@ const expected = { for (const [name, [type, size, hash]] of Object.entries(expected)) { const binary = await fs.readFile(`./tests/ico/${name}`); if (ImageType.getType(binary) !== type) panic(`${name}: not detected as ${type}`); - if (!ImageType.isICO(binary)) panic(`${name}: isICO should be true`); + if (ImageType.isICO(binary) !== (type === 'ico')) panic(`${name}: isICO should match the file type`); + if (ImageType.isCUR(binary) !== (type === 'cur')) panic(`${name}: isCUR should match the file type`); const image = await Image.decode(binary); if (image.width !== size || image.height !== size) panic(`${name}: ${image.width}x${image.height} instead of ${size}x${size}`); if (sha(image) !== hash) panic(`${name}: decoded pixels don't match`); diff --git a/tests/image.js b/tests/image.js index 36a19142..d43b0349 100644 --- a/tests/image.js +++ b/tests/image.js @@ -1,12 +1,12 @@ const fs = require('fs').promises; -const {Image} = require('..'); +const {Image, Colors} = require('..'); const samePixels = require('./util/pixels'); module.exports = (async () => { const image = new Image(128, 128); - image.fill(x => Image.hslToColor(x / image.width, 1, 0.5)); + image.fill(x => Colors.fromHSL(x / image.width * 360, 1, 0.5)); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/image.png', encoded); diff --git a/tests/invert.js b/tests/invert.js index 569997f3..19c34dda 100644 --- a/tests/invert.js +++ b/tests/invert.js @@ -1,5 +1,5 @@ const fs = require('fs').promises; -const {Image} = require('..'); +const {Image, Colors} = require('..'); const samePixels = require('./util/pixels'); (async () => { @@ -8,7 +8,7 @@ const samePixels = require('./util/pixels'); image.fill(0xff8000ff); image.invert(); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/invert.png', encoded); @@ -22,7 +22,7 @@ const samePixels = require('./util/pixels'); image.fill(0xff8000ff); image.invertLightness(); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/invert-lightness.png', encoded); @@ -33,10 +33,10 @@ const samePixels = require('./util/pixels'); { const image = new Image(512, 512); - image.fill((x, y) => Image.rgbToColor(x / 2, y / 2, 255 - x / 2)); + image.fill((x, y) => Colors.fromRGB(Math.min(x / 2, 255), Math.min(y / 2, 255), 255 - x / 2)); image.invertValue(); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/invert-value.png', encoded); @@ -50,7 +50,7 @@ const samePixels = require('./util/pixels'); image.fill(0xff8000ff); image.hueShift(180); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/invert-hueshift.png', encoded); diff --git a/tests/jpeg-flatten.js b/tests/jpeg-flatten.js new file mode 100644 index 00000000..a2ac5e5c --- /dev/null +++ b/tests/jpeg-flatten.js @@ -0,0 +1,35 @@ +const {Image} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +let seed = 11; +const random = () => (seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296; + +// encodeJPEG composites transparent pixels onto the background row by row, without a copy of the image: the file is the +// one of the image composited the plain way (composite() onto a filled image), for every kind of alpha +(async () => { + const alphas = { + 'random alpha': () => random() * 256 | 0, + 'mostly opaque': () => random() < 0.9 ? 255 : random() * 256 | 0, + 'mostly clear': () => random() < 0.9 ? 0 : random() * 256 | 0, + 'two levels': () => random() < 0.5 ? 0 : 128 + }; + for (const [name, alpha] of Object.entries(alphas)) for (const [width, height] of [[17, 9], [1, 1], [64, 33]]) for (const gray of [false, true]) { + const image = new Image(width, height).fill(() => { + const v = random() * 256 | 0; + return gray ? (v << 24 | v << 16 | v << 8 | alpha()) >>> 0 : ((random() * 2 ** 24) << 8 | alpha()) >>> 0; + }); + for (const background of [0x000000ff, 0xff8800ff, 0x808080ff]) for (const quality of [50, 90, 95]) { + const flat = new Image(width, height).fill(background).composite(image); + const expected = await flat.encodeJPEG({quality, subsampling: quality > 90 ? '4:4:4' : '4:2:0'}); + const got = await image.encodeJPEG({quality, background, subsampling: quality > 90 ? '4:4:4' : '4:2:0'}); + if (!Buffer.from(expected).equals(Buffer.from(got))) panic(`${name} ${width}x${height} ${gray ? 'gray' : 'color'} background ${background.toString(16)} q${quality}: ${got.length} bytes, expected ${expected.length}`); + } + } + // the image isn't changed + const image = new Image(4, 4).fill(0xff000080), before = Buffer.from(image.bitmap); + await image.encodeJPEG(); + if (!Buffer.from(image.bitmap).equals(before)) panic('encodeJPEG changed the image'); +})(); diff --git a/tests/jpeg.js b/tests/jpeg.js index 8f8385c8..fc030e2d 100644 --- a/tests/jpeg.js +++ b/tests/jpeg.js @@ -46,7 +46,7 @@ const withoutExif = data => { for (const [key, hash] of Object.entries(encoded)) { const [name, quality] = key.split('@'); const file = name === 'external' ? './tests/targets/external.jpg' : `./tests/jpegs/${name}.jpg`; - const data = withoutExif(await (await Image.decode(await fs.readFile(file))).encodeJPEG(Number(quality))); + const data = withoutExif(await (await Image.decode(await fs.readFile(file))).encodeJPEG({quality: Number(quality)})); if (crypto.createHash('sha256').update(data).digest('hex') !== hash) panic(`${key}: encoded bytes don't match cjpeg's`); } @@ -75,26 +75,21 @@ const withoutExif = data => { panic('stray bytes: decoded pixels don\'t match'); } - // a scan with restart markers that ends early (cut, then EOI): what was decoded is kept + // a scan with restart markers that ends early (cut, then EOI) is a decoding error, like a cut-off scan without them { const data = await fs.readFile('./tests/jpegs/restart.jpg'); const sos = data.indexOf(Buffer.from([0xff, 0xda])); const cut = Buffer.concat([data.subarray(0, sos + (data.length - sos >> 1)), Buffer.from([0xff, 0xd9])]); - const decoded = await Image.decode(cut); - if (decoded.width !== 227 || decoded.height !== 149) panic('early ending scan: dimensions don\'t match'); + const error = await Image.decode(cut).then(() => null, e => e); + if (!error || error.constructor !== Error) panic(`a scan cut short should throw an Error, got ${error}`); } - try { - await Image.decode(await fs.readFile('./tests/jpegs/arithmetic.jpg')); - panic('arithmetic coded JPEG was accepted'); - } catch (err) { - if (!/arithmetic/.test(err.message)) panic(`unexpected error: ${err.message}`); - } + if (!await Image.decode(await fs.readFile('./tests/jpegs/arithmetic.jpg')).then(() => false, error => error instanceof Error)) panic('arithmetic coded JPEG was accepted'); // encoding: higher quality must be larger and closer to the source let previous = null; for (const quality of [10, 50, 90, 100]) { - const encoded = await image.encodeJPEG(quality); + const encoded = await image.encodeJPEG({quality: quality}); const decoded = await Image.decode(encoded); if (decoded.width !== image.width || decoded.height !== image.height) panic(`q${quality}: dimensions don't match`); @@ -110,4 +105,19 @@ const withoutExif = data => { panic(`q${quality}: not better than the previous quality`); previous = {size: encoded.length, psnr}; } + + // a frame header cut short is a decoding error of the codec, not a read of missing bytes + { + const error = await Image.decode(await fs.readFile('./tests/jpegs/damaged-truncated-frame-header.jpg')).then(() => null, e => e); + if (!error || error.constructor !== Error) panic(`a truncated frame header should throw an Error, got ${error}`); + } + + // a baseline file far too small for the size it declares (every block takes at least 2 bits of scan data) is + // refused before its planes are allocated: 19 KB declaring 16383x16383 took 16 s and 1.1 GB to end truncated + // (damaged-declares-16383.jpg: a CMYK baseline JPEG of 19 KB) + { + const start = Date.now(); + const error = await Image.decode(await fs.readFile('./tests/jpegs/damaged-declares-16383.jpg')).then(() => null, e => e); + if (!error || error.constructor !== Error || !/truncated/.test(error.message) || Date.now() - start > 1000) panic(`a 19 KB baseline JPEG declaring 16383x16383 should throw a truncated Error at once, got ${error} after ${Date.now() - start} ms`); + } })(); diff --git a/tests/jpegs/damaged-declares-16383.jpg b/tests/jpegs/damaged-declares-16383.jpg new file mode 100644 index 00000000..0b0d1b25 Binary files /dev/null and b/tests/jpegs/damaged-declares-16383.jpg differ diff --git a/tests/jpegs/damaged-truncated-frame-header.jpg b/tests/jpegs/damaged-truncated-frame-header.jpg new file mode 100644 index 00000000..090e86d6 Binary files /dev/null and b/tests/jpegs/damaged-truncated-frame-header.jpg differ diff --git a/tests/jxl-encode.js b/tests/jxl-encode.js index ae13cc0f..d59128fa 100644 --- a/tests/jxl-encode.js +++ b/tests/jxl-encode.js @@ -152,24 +152,22 @@ const codestream = jxl => { if (effort === 0) effort0 = jxl.length; else if (jxl.length > effort0 * 1.02) panic(`effort ${effort}: ${jxl.length} B, effort 0 ${effort0} B`); } - for (const effort of [-1, 3, 1.5]) if (!await shot.encodeJXL({quality: 90, effort}).then(() => false, e => e instanceof RangeError)) panic(`effort ${effort} should throw`); // threads (XYB, the quantization field, the varblock search, the coefficients and their tokens in parallel): the // same files as without; at effort 0 from 1024x1024 pixels on, with alpha { - const big = photo.clone().resize(640, Image.RESIZE_AUTO), large = photo.clone().resize(1024, 1032); + const big = photo.clone().resize({width: 640}), large = photo.clone().resize(1024, 1032); for (let i = 3; i < large.bitmap.length; i += 4) large.bitmap[i] = (i >> 2) % large.width & 255; for (const [image, effort] of [[big, 1], [big, 2], [large, 0]]) { const one = await image.encodeJXL({quality: 85, effort, threads: 1, metadata: {creationTime: 0}}); const four = await image.encodeJXL({quality: 85, effort, threads: 4, metadata: {creationTime: 0}}); if (Buffer.compare(Buffer.from(one), Buffer.from(four))) panic(`threads, effort ${effort}: not the same file`); } - for (const threads of [0, 2.5]) if (!await big.encodeJXL({quality: 85, threads}).then(() => false, e => e instanceof RangeError)) panic(`threads ${threads} should throw`); } // patches (effort 2): repeated glyphs of text on a flat background are found, stored in a reference frame and // added back { - const text = await Image.renderText(await fs.readFile('./tests/fonts/opensans bold.ttf'), 18, 'abba cabbage\nbeach bag cab\nabba cabbage', 0x202020ff); - const page = new Image(text.width + 16, text.height + 16).fill(0xf4f4f4ff).composite(text, 8, 8); + const text = await Image.renderText('abba cabbage\nbeach bag cab\nabba cabbage', { font: await fs.readFile('./tests/fonts/opensans bold.ttf'), size: 18, color: 0x202020ff }); + const page = new Image(text.width + 16, text.height + 16).fill(0xf4f4f4ff).composite(text, {x: 8, y: 8}); const {findPatches} = await import('../dist/codecs/jxl/patches-enc.js'); const w = page.width, h = page.height, planes = [0, 1, 2].map(c => Float32Array.from({length: w * h}, (_, i) => page.bitmap[i * 4 + c] / 255)); if (!findPatches(planes, w, w, h, 1, 0)) panic('patches: none found in text'); diff --git a/tests/jxl.js b/tests/jxl.js index 126cf02c..ed851494 100644 --- a/tests/jxl.js +++ b/tests/jxl.js @@ -1,5 +1,5 @@ const fs = require('fs').promises; -const {Image, ImageType, Animation} = require('..'); +const {Image, ImageType, Animation, Colors} = require('..'); const panic = message => { console.error(message); @@ -42,19 +42,20 @@ const difference = (bitmap, width, height, reference, step = 1, premultiplied = const animation = await Animation.decode(binary); const references = await Animation.decode(await fs.readFile(`./tests/jxl/${name}.png`)); if (animation.length !== references.length) panic(`${name}: ${animation.length} frames instead of ${references.length}`); - animation.forEach((frame, i) => { - if (frame.duration !== references[i].duration) panic(`${name}: frame ${i} lasts ${frame.duration} ms instead of ${references[i].duration}`); - max = Math.max(max, difference(frame.bitmap, frame.width, frame.height, references[i])); + animation.frames.forEach((frame, i) => { + if (frame.duration !== references.frames[i].duration) panic(`${name}: frame ${i} lasts ${frame.duration} ms instead of ${references.frames[i].duration}`); + max = Math.max(max, difference(frame.image.bitmap, frame.width, frame.height, references.frames[i].image)); }); } if (max > (premultiplied ? 2 : 1)) panic(`${name}: differs by ${max} from djxl's`); } // the first frame only; Animation.decode of a still image - const first = await Animation.decode(await fs.readFile('./tests/jxl/animation.jxl'), {onlyFirstFrame: true}); - if (first.length !== 1) panic(`onlyFirstFrame: ${first.length} frames`); + const animated = await fs.readFile('./tests/jxl/animation.jxl'); + const first = await Image.decode(animated); + if (first.constructor !== Image || !Buffer.from(first.bitmap).equals(Buffer.from((await Animation.decode(animated)).frames[0].image.bitmap))) panic('Image.decode: the first frame of an animated JPEG XL should be Animation.decode\'s first frame'); const still = await Animation.decode(await fs.readFile('./tests/jxl/lossy.jxl')); - if (still.length !== 1 || still[0].width !== 64) panic('a still JPEG XL as an animation'); + if (still.length !== 1 || still.frames[0].width !== 64) panic('a still JPEG XL as an animation'); // truncated or corrupted data throws const lossy = await fs.readFile('./tests/jxl/lossy.jxl'); @@ -64,10 +65,19 @@ const difference = (bitmap, width, height, reference, step = 1, premultiplied = // the pixel limit if (await Image.decode(lossy, {maxPixels: 100}).then(() => true, () => false)) panic('maxPixels was ignored'); + // an animation's frames count together, like those of the other formats + { + const animation = await Animation.decode(animated); + const total = animation.frames.reduce((sum, frame) => sum + frame.width * frame.height, 0); + if (animation.length < 2) panic('the animated file should have frames'); + if (await Animation.decode(animated, {maxPixels: total - 1}).then(() => false, error => error.name === 'LimitError') !== true) panic('maxPixels should count every frame'); + await Animation.decode(animated, {maxPixels: total}); + } + // threads (groups, Gaborish, EPF and the XYB conversion in parallel, from 4 megapixels): the same pixels as without, // lossy (with alpha) and lossless const big = new Image(2304, 2048); - for (let y = 0; y < big.height; y++) for (let x = 0; x < big.width; x++) big.setPixelAt(x, y, Image.rgbaToColor(x * 7 & 255, (x ^ y) & 255, y * 3 & 255, x < 64 ? 128 : 255)); + for (let y = 0; y < big.height; y++) for (let x = 0; x < big.width; x++) big.setPixelAt(x, y, Colors.fromRGBA(x * 7 & 255, (x ^ y) & 255, y * 3 & 255, x < 64 ? 128 : 255)); for (const options of [{quality: 80, effort: 0}, {effort: 0}]) { const data = await big.encodeJXL(options); const one = await Image.decode(data, {threads: 1}), four = await Image.decode(data, {threads: 4}); @@ -75,7 +85,16 @@ const difference = (bitmap, width, height, reference, step = 1, premultiplied = // (not in shared memory, which some APIs reject) if (four.bitmap.buffer instanceof SharedArrayBuffer) panic('threads: the bitmap is in shared memory'); const animation = await Animation.decode(data, {threads: 4}); - if (Buffer.compare(Buffer.from(animation[0].bitmap), Buffer.from(one.bitmap))) panic('threads, Animation.decode: different pixels'); + if (Buffer.compare(Buffer.from(animation.frames[0].image.bitmap), Buffer.from(one.bitmap))) panic('threads, Animation.decode: different pixels'); + } + + // damaged blending info (blendmodes.jxl with flipped bits): a blend alpha channel that doesn't exist is an error, + // not a TypeError from the blending + for (const name of await fs.readdir('./tests/jxl/damaged')) { + const data = await fs.readFile(`./tests/jxl/damaged/${name}`); + for (const decode of [() => Image.decode(data, {threads: 1}), () => Animation.decode(data, {threads: 1})]) { + const error = await decode().then(() => null, e => e); + if (!error || error instanceof TypeError) panic(`damaged/${name}: ${error && error.constructor.name}: ${error && error.message}`); + } } - for (const threads of [0, 1.5]) if (!await Image.decode(lossy, {threads}).then(() => false, e => e instanceof RangeError)) panic(`threads ${threads} should throw`); })(); diff --git a/tests/jxl/damaged/blend-alpha-1.jxl b/tests/jxl/damaged/blend-alpha-1.jxl new file mode 100644 index 00000000..41965f40 Binary files /dev/null and b/tests/jxl/damaged/blend-alpha-1.jxl differ diff --git a/tests/jxl/damaged/blend-alpha-2.jxl b/tests/jxl/damaged/blend-alpha-2.jxl new file mode 100644 index 00000000..1ce88320 Binary files /dev/null and b/tests/jxl/damaged/blend-alpha-2.jxl differ diff --git a/tests/loop-count.js b/tests/loop-count.js new file mode 100644 index 00000000..fc5e89b6 --- /dev/null +++ b/tests/loop-count.js @@ -0,0 +1,116 @@ +const {Image, Frame, Animation} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +const throwsA = (fn, type, label) => { + let error = null; + try { fn(); } catch (e) { error = e; } + if (!(error instanceof type)) panic(`${label}: should throw a ${type.name}, got ${error}`); +}; + +const frames = () => [new Frame(new Image(4, 4).fill(0xff0000ff), {duration: 40}), new Frame(new Image(4, 4).fill(0x00ff00ff), {duration: 60})]; +const metadata = {creationTime: 0}; +// each format: its encode method, its encoder factory, and the count the file stores when it loops forever or plays +// (the GIF's NETSCAPE block counts repetitions, APNG and WebP count plays) +const formats = {GIF: ['encodeGIF', 'gifEncoder'], APNG: ['encodeAPNG', 'apngEncoder'], WebP: ['encodeWebP', 'webpEncoder']}; + +// the NETSCAPE2.0 loop count of a GIF (0 = forever), or null if it has none (it plays once) +const netscape = bytes => { + const at = Buffer.from(bytes).indexOf('NETSCAPE2.0'); + return at < 0 ? null : Buffer.from(bytes).readUInt16LE(at + 13); +}; + +(async () => { + // the default is forever, everywhere + if (new Animation(frames()).loopCount !== Infinity || new Animation([]).loopCount !== Infinity) panic('the default loop count should be Infinity'); + for (const [format, [encode, factory]] of Object.entries(formats)) { + const animation = new Animation(frames()); + const bytes = await animation[encode]({metadata}); + const encoder = Animation[factory](4, 4, {metadata}); + for (const frame of frames()) await encoder.add(frame); + if (!Buffer.from(await encoder.finish()).equals(Buffer.from(bytes))) panic(`${format}: the encoder's default isn't the animation's`); + if (encode === 'encodeGIF' && netscape(bytes) !== 0) panic(`${format}: forever should be stored as NETSCAPE count 0, not ${netscape(bytes)}`); + + // decoded: a file that loops forever is Infinity + const back = await Animation.decode(bytes); + if (back.loopCount !== Infinity) panic(`${format}: a file that loops forever decodes as ${back.loopCount}`); + } + + // Infinity is forever, explicitly, in every entry point + for (const [format, [encode, factory]] of Object.entries(formats)) { + const forever = await new Animation(frames(), {loopCount: Infinity})[encode]({metadata}); + if (!Buffer.from(forever).equals(Buffer.from(await new Animation(frames())[encode]({metadata})))) panic(`${format}: Infinity isn't the default`); + const encoder = Animation[factory](4, 4, {loopCount: Infinity, metadata}); + for (const frame of frames()) await encoder.add(frame); + if (!Buffer.from(await encoder.finish()).equals(Buffer.from(forever))) panic(`${format}: the encoder with Infinity`); + const setter = new Animation(frames(), {loopCount: 2}); + setter.loopCount = Infinity; + if (setter.loopCount !== Infinity) panic(`${format}: the loopCount setter`); + } + + // finite counts: 0 plays once, n repeats n times, through the constructor, the setter and each encoder + for (const count of [0, 1, 5]) { + for (const [format, [encode, factory]] of Object.entries(formats)) { + const bytes = await new Animation(frames(), {loopCount: count})[encode]({metadata}); + if (format === 'GIF' && netscape(bytes) !== (count === 0 ? null : count)) panic(`GIF: loop count ${count} stored as ${netscape(bytes)}`); + const back = await Animation.decode(bytes); + if (back.loopCount !== count) panic(`${format}: loop count ${count} decodes as ${back.loopCount}`); + + const encoder = Animation[factory](4, 4, {loopCount: count, metadata}); + for (const frame of frames()) await encoder.add(frame); + if (!Buffer.from(await encoder.finish()).equals(Buffer.from(bytes))) panic(`${format}: encoder with loop count ${count} differs`); + + const set = new Animation(frames()); + set.loopCount = count; + if (set.loopCount !== count || !Buffer.from(await set[encode]({metadata})).equals(Buffer.from(bytes))) panic(`${format}: setter with loop count ${count}`); + } + } + + // a single frame has no loop count of its own: it's the default, forever + if ((await Animation.decode(await new Animation([frames()[0]]).encodeAPNG())).loopCount !== Infinity) panic('a still APNG should decode as Infinity'); + + // the largest count each format stores round-trips (GIF's 16 bits, WebP's 16 bits of plays, APNG's 31 bits of plays); + // one more would wrap around (65536 as a GIF is forever), so every entry point throws a RangeError instead + const limits = {GIF: 65535, WebP: 65534, APNG: 2 ** 31 - 2}; + for (const [format, max] of Object.entries(limits)) { + const [encode, factory] = formats[format]; + const bytes = await new Animation(frames(), {loopCount: max})[encode]({metadata}); + if (format === 'GIF' && netscape(bytes) !== max) panic(`GIF: the largest count ${max} is stored as ${netscape(bytes)}`); + const back = await Animation.decode(bytes); + if (back.loopCount !== max) panic(`${format}: the largest count ${max} decodes as ${back.loopCount}`); + const encoder = Animation[factory](4, 4, {loopCount: max, metadata}); + for (const frame of frames()) await encoder.add(frame); + if (!Buffer.from(await encoder.finish()).equals(Buffer.from(bytes))) panic(`${format}: the encoder with the largest count ${max} differs`); + + const over = max + 1; + let error = null; + try { await new Animation(frames(), {loopCount: over})[encode](); } catch (e) { error = e; } + if (!(error instanceof RangeError)) panic(`${format}: ${over} should throw a RangeError, got ${error}`); + throwsA(() => Animation[factory](4, 4, {loopCount: over}), RangeError, `${format} encoder with ${over}`); + } + + // what isn't a loop count is refused by every entry point, with a RangeError for numbers and a TypeError for the rest, + // and a refused value changes nothing + const numbers = [-1, -5, NaN, 1.5]; + const others = ['2', null, true]; + for (const value of [...numbers, ...others]) { + const expected = numbers.includes(value) ? RangeError : TypeError; + const label = `loop count ${typeof value === 'string' ? JSON.stringify(value) : value}`; + + throwsA(() => new Animation(frames(), {loopCount: value}), expected, `new Animation(frames, { loopCount: ${label} })`); + const list = frames(); + throwsA(() => new Animation(list, {loopCount: value}), expected, `new Animation with ${label}`); + if (list.length !== 2) panic(`${label}: the frames given were changed`); + + const animation = new Animation(frames(), {loopCount: 3}); + throwsA(() => { animation.loopCount = value; }, expected, `loopCount = ${label}`); + if (animation.loopCount !== 3) panic(`${label}: a refused loopCount changed the animation to ${animation.loopCount}`); + + throwsA(() => Animation.gifEncoder(4, 4, {loopCount: value}), expected, `gifEncoder with ${label}`); + throwsA(() => Animation.apngEncoder(4, 4, {loopCount: value}), expected, `apngEncoder with ${label}`); + throwsA(() => Animation.webpEncoder(4, 4, {loopCount: value}), expected, `webpEncoder with ${label}`); + } + +})().catch(error => panic(error.stack || String(error))); diff --git a/tests/loop-limits.js b/tests/loop-limits.js deleted file mode 100644 index 8ad2e8de..00000000 --- a/tests/loop-limits.js +++ /dev/null @@ -1,40 +0,0 @@ -const {Animation, Frame} = require('..'); - -const panic = message => { - console.error(message); - process.exit(1); -}; - -// loop counts are stored in fixed-size fields: a count that doesn't fit used to wrap around (65536 repeats became 0, which -// plays forever), now it's refused; the largest count of each format round trips -(async () => { - const frames = () => [0xff0000ff, 0x00ff00ff].map(color => Frame.from(new Animation([new Frame(4, 4)])[0].fill(color), {duration: 50})); - const limits = {GIF: 65535, WebP: 65534, APNG: 2 ** 31 - 2}; - const encode = {GIF: a => a.encodeGIF(), WebP: a => a.encodeWebP(), APNG: a => a.encodeAPNG()}; - const factory = {GIF: Animation.gifEncoder, WebP: Animation.webpEncoder, APNG: Animation.apngEncoder}; - - for (const [format, max] of Object.entries(limits)) { - const decoded = await Animation.decode(await encode[format](new Animation(frames(), {loopCount: max}))); - if (decoded.loopCount !== max) panic(`${format}: loop count ${max} read back as ${decoded.loopCount}`); - for (const forever of [-1, Infinity]) { - const again = await Animation.decode(await encode[format](new Animation(frames(), {loopCount: forever}))); - if (again.loopCount !== -1 && again.loopCount !== Infinity) panic(`${format}: loop count ${forever} read back as ${again.loopCount}`); - } - - for (const count of [max + 1, max + 1000, 2 ** 40]) { - let error = null; - try { await encode[format](new Animation(frames(), {loopCount: count})); } catch (e) { error = e; } - if (!(error instanceof RangeError) || !error.message.includes(String(max))) panic(`${format}: loop count ${count} should be refused with the largest count, got ${error}`); - - error = null; - try { factory[format].call(Animation, 4, 4, {loopCount: count}); } catch (e) { error = e; } - if (!(error instanceof RangeError)) panic(`${format} encoder: loop count ${count} should be refused, got ${error}`); - } - - // the streaming encoder writes the same count - const encoder = factory[format].call(Animation, 4, 4, {loopCount: max}); - for (const frame of frames()) await encoder.add(frame); - const streamed = await Animation.decode(await encoder.finish()); - if (streamed.loopCount !== max) panic(`${format} encoder: loop count ${max} read back as ${streamed.loopCount}`); - } -})().catch(error => panic(error.stack || String(error))); diff --git a/tests/metadata.js b/tests/metadata.js index e24cbbfb..82d24e62 100644 --- a/tests/metadata.js +++ b/tests/metadata.js @@ -9,13 +9,13 @@ const has = (data, text) => Buffer.from(data).includes(Buffer.from(text)); const latin1 = (data, text) => Buffer.from(data).includes(Buffer.from(text, 'latin1')); (async () => { - const {VERSION} = await import('../dist/version.js'); - const software = `ImageScript v${VERSION}`; + // (without the version: it would tell which release made a file) + const software = 'ImageScript'; const image = new Image(8, 4).fill(0xff000080); - const animation = new Animation([Frame.from(image, 100), Frame.from(new Image(8, 4).fill(0x00ff00ff), 100)]); + const animation = new Animation([new Frame(image.clone(), {duration: 100}), new Frame(new Image(8, 4).fill(0x00ff00ff), {duration: 100})]); const encoders = { - png: m => image.encode(m), + png: m => image.encodePNG({metadata: m}), jpeg: m => image.encodeJPEG({quality: 90, metadata: m}), webp: m => image.encodeWebP({metadata: m}), tga: m => image.encodeTGA({metadata: m}), @@ -30,10 +30,22 @@ const latin1 = (data, text) => Buffer.from(data).includes(Buffer.from(text, 'lat for (const [format, encode] of Object.entries(encoders)) { const tagged = await encode(); if (!has(tagged, software)) panic(`${format}: software missing by default`); + if (has(tagged, `${software} v`)) panic(`${format}: the default software names the version`); + // no creation time unless one is given: the same image encodes to the same bytes, whenever it's encoded + const now = Date.now; + Date.now = () => 0; + const early = await encode(); + Date.now = () => 4e12; + const late = await encode(); + Date.now = now; + if (!Buffer.from(early).equals(Buffer.from(late))) panic(`${format}: encoding depends on the time`); if (has(await encode({software: ''}), 'ImageScript')) panic(`${format}: software: '' should leave it out`); + if (has(await encode({software: null}), 'ImageScript')) panic(`${format}: software: null should leave it out`); + // (null is no time: not the epoch) + if (!Buffer.from(await encode({creationTime: null})).equals(Buffer.from(await encode({})))) panic(`${format}: creationTime: null should be the default`); if (!has(await encode({software: 'custom tool'}), 'custom tool')) panic(`${format}: custom software missing`); - const decoded = /gif|apng|animated/.test(format) ? (await Animation.decode(tagged))[0] : await Image.decode(tagged); + const decoded = /gif|apng|animated/.test(format) ? (await Animation.decode(tagged)).frames[0] : await Image.decode(tagged); if (decoded.width !== 8 || decoded.height !== 4) panic(`${format}: doesn't decode with metadata`); } @@ -41,11 +53,12 @@ const latin1 = (data, text) => Buffer.from(data).includes(Buffer.from(text, 'lat // PNG: tEXt is Latin-1, other text goes into iTXt (UTF-8), before the image data { - const png = Buffer.from(await image.encode(metadata)); + const png = Buffer.from(await image.encodePNG({metadata: metadata})); if (!latin1(png, 'Author\0Jörg')) panic('png: Latin-1 text should be a tEXt chunk'); if (!has(png, 'iTXtCopyright\0\0\0\0\0Ⓒ someone')) panic('png: other text should be an iTXt chunk'); if (png.indexOf('tEXt') > png.indexOf('IDAT')) panic('png: text chunks should come before the image data'); if (!has(png, 'Thu, 15 Oct 2026 12:34:56 GMT')) panic('png: creation time missing'); + if (has(await image.encodePNG(), 'Creation Time')) panic('png: a creation time without one given'); } // JPEG, WebP, AVIF and JPEG XL: Exif (IFD0 strings, UTC date; AVIF and JPEG XL: the TIFF header's offset first), @@ -80,5 +93,21 @@ const latin1 = (data, text) => Buffer.from(data).includes(Buffer.from(text, 'lat if (tga[area + 494] !== 3) panic('tga: attributes type should be "useful alpha"'); } - if (await image.encode({creationTime: 'not a date'}).then(() => true, () => false)) panic('an invalid creation time should throw'); + if (await image.encodePNG({metadata: {creationTime: 'not a date'}}).then(() => true, () => false)) panic('an invalid creation time should throw'); + + // the creation time's year is 4 digits in Exif and fits what TGA stores: other years throw instead of being written + // wrapped or without 4 digits ('1:01:01') + for (const creationTime of [new Date(Date.UTC(999, 0, 1)), new Date(8.64e15), '+010000-01-01T00:00:00Z', new Date(Date.UTC(-1, 0, 1))]) { + const error = await image.encodePNG({metadata: {creationTime}}).then(() => null, err => err); + if (!(error instanceof RangeError) || !/creationTime/.test(error.message) || !/1000/.test(error.message)) panic(`creationTime ${creationTime}: ${error?.constructor?.name}: ${error?.message}`); + } + await image.encodeTGA({metadata: {creationTime: new Date(Date.UTC(1000, 0, 1))}}); + await image.encodeJPEG({metadata: {creationTime: new Date(Date.UTC(9999, 11, 31, 23, 59, 59))}}); + + // a JPEG segment holds 65533 bytes: metadata beyond that throws a RangeError naming the field, before encoding + for (const [metadata, field] of [[{comment: 'x'.repeat(65534)}, 'comment'], [{description: 'x'.repeat(65534)}, 'description'], [{author: 'x'.repeat(40000), software: 'x'.repeat(40000)}, 'author']]) { + const error = await image.encodeJPEG({metadata}).then(() => null, err => err); + if (!(error instanceof RangeError) || !error.message.includes(field) || !error.message.includes('65533')) panic(`encodeJPEG with too long ${field}: ${error}`); + } + await image.encodeJPEG({metadata: {comment: 'x'.repeat(65533)}}); })(); diff --git a/tests/misc.js b/tests/misc.js index 82b07661..5403d02b 100644 --- a/tests/misc.js +++ b/tests/misc.js @@ -1,4 +1,4 @@ -const {Image, Frame, GIF} = require('..'); +const {Image, Frame, Animation, Colors} = require('..'); const panic = msg => { console.error(msg); process.exit(1); @@ -16,33 +16,30 @@ try { } catch { } -if (new Image(1, 1).toString() !== 'Image<1x1>') - panic('toString failed'); +for (const [x, y] of new Image(1, 1).pixels()) + if (x !== 0 || y !== 0) panic('pixels failed'); -for (const [x, y] of new Image(1, 1)) - if (x !== 0 || y !== 0) panic('Symbol.iterator failed'); +for (const [x, y, color] of new Image(1, 1).fill(0xff8000ff).pixels()) + if (x !== 0 || y !== 0 || color !== 0xff8000ff) panic('pixels failed'); -for (const [x, y, color] of new Image(1, 1).fill(0xff8000ff).iterateWithColors()) - if (x !== 0 || y !== 0 || color !== 0xff8000ff) panic('iterateWithColors failed'); - -if (Image.rgbToColor(0xff, 0x80, 0x00) !== 0xff8000ff) +if (Colors.fromRGB(0xff, 0x80, 0x00) !== 0xff8000ff) panic('rgbToColor failed'); -if (Image.hslaToColor(0, 0, 1, 0xff) !== 0xffffffff) +if (Colors.fromHSLA(0, 0, 1, 1) !== 0xffffffff) panic('hslaToColor for s=0 failed'); { - for (const rgba of [0xff0000ff, 0x00ff00ff, 0x0000ffff, 0x000000ff, 0xffffffff].map(x => Image.colorToRGBA(x))) { - const hsla = Image.rgbaToHSLA(...rgba); - const rgbaBacktransform = Image.colorToRGBA(Image.hslaToColor(...hsla)); + for (const rgba of [0xff0000ff, 0x00ff00ff, 0x0000ffff, 0x000000ff, 0xffffffff].map(x => Colors.toRGBA(x))) { + const hsla = Colors.toHSLA(Colors.fromRGBA(...rgba)); + const rgbaBacktransform = Colors.toRGBA(Colors.fromHSLA(...hsla)); for (let i = 0; i < 4; i++) if (rgba[i] !== rgbaBacktransform[i]) - panic('rgbaToHSLA failed'); + panic('Colors.toHSLA failed'); } } { - const rgb = Image.colorToRGB(0xff8000ff); + const rgb = Colors.toRGB(0xff8000ff); const target = [0xff, 0x80, 0x00]; for (let i = 0; i < 3; i++) if (rgb[i] !== target[i]) @@ -56,45 +53,11 @@ if (Image.hslaToColor(0, 0, 1, 0xff) !== 0xffffffff) const pixel = image.getPixelAt(0, 0); if (pixel !== 0xff8000ff) panic('getPixelAt fails'); - const rgba = image.getRGBAAt(0, 0); + const rgba = Colors.toRGBA(image.getPixelAt(0, 0)); const target = [0xff, 0x80, 0x00, 0xff]; for (let i = 0; i < 4; i++) if (rgba[i] !== target[i]) - panic('colorToRGB failed'); -} - -{ - const image = new Image(1, 1); - try { - image.__check_boundaries__('a', 1); - panic('check boundaries for x as NaN failed'); - } catch { - } - try { - image.__check_boundaries__(1, 'a'); - panic('check boundaries for y as NaN failed'); - } catch { - } - try { - image.__check_boundaries__(0, 1); - panic('check boundaries for x as 0 failed'); - } catch { - } - try { - image.__check_boundaries__(1, 0); - panic('check boundaries for y as 0 failed'); - } catch { - } - try { - image.__check_boundaries__(2, 1); - panic('check boundaries for x as 2 failed'); - } catch { - } - try { - image.__check_boundaries__(1, 2); - panic('check boundaries for y as 2 failed'); - } catch { - } + panic('Colors.toRGBA failed'); } { @@ -128,27 +91,12 @@ if (Image.hslaToColor(0, 0, 1, 0xff) !== 0xffffffff) } catch { } try { - image.resize(1, 1, 'garbage'); + image.resize(1, 1, {mode: 'garbage'}); panic('resize with invalid mode failed'); } catch { } - try { - image.resize(Image.RESIZE_AUTO, Image.RESIZE_AUTO); - panic('resize with RESIZE_AUTO for both x and y failed'); - } catch { - } } -{ - const image = new Image(1, 1); - image.drawBox(0, 0, 1, 1, 0xff8000ff); - if (image.getPixelAt(0, 0) !== 0xff8000ff) - panic('static drawBox failed'); - - image.drawBox(0, 0, 1, 1, () => 0x00ff00ff); - if (image.getPixelAt(0, 0) !== 0x00ff00ff) - panic('fn drawBox failed'); -} { const image = new Image(1, 1); @@ -157,54 +105,30 @@ if (Image.hslaToColor(0, 0, 1, 0xff) !== 0xffffffff) for (const func of funcs) for (const value of toFail) try { - func.call(image, toFail); + func.call(image, value); panic(`${func.name} failed with value ${JSON.stringify(value)}`); } catch { } - - const toPass = [[1, true], [1, false], [0, true], [0, false]]; - for (const func of funcs) - for (const value of toPass) - func.call(image, ...value); } { const image = new Image(512, 256); const overlay = new Image(1024, 512); - image.composite(overlay, -512, -256); + image.composite(overlay, {x: -512, y: -256}); overlay.fill(0x80); - image.composite(overlay, -512, -256); + image.composite(overlay, {x: -512, y: -256}); overlay.fill(0xff); - image.composite(overlay, -512, -256); + image.composite(overlay, {x: -512, y: -256}); } try { - new Frame(1, 1, -1); + new Frame(new Image(1, 1), {duration: -1}); panic('frame duration failed'); } catch { } -if (new Frame(1, 2, 3).toString() !== 'Frame<1x2x3ms>') panic('frame toString failed'); - -{ - const image = new Image(512, 512); - Frame.from(image, 10); - try { - Frame.from({}, 10); - panic('frame instanceof image failed'); - } catch { - } -} - -try { - new GIF([{}]); - panic('gif frame instanceof failed'); -} catch { -} - { - const frame = new Frame(512, 128, 123); - const gif = new GIF([frame]); - if (gif.toString() !== 'GIF<512x128x123ms>') panic('gif tostring failed'); - if (gif.duration !== 123) panic('gif duration failed'); + const frame = new Frame(new Image(512, 128), {duration: 123}); + const animation = new Animation([frame]); + if (animation.duration !== 123) panic('animation duration failed'); } diff --git a/tests/option-checks.js b/tests/option-checks.js index 26711025..fcbb7e34 100644 --- a/tests/option-checks.js +++ b/tests/option-checks.js @@ -1,17 +1,17 @@ -const {Image, Frame, Animation} = require('..'); +const {Image, Frame, Animation, LimitError} = require('..'); const panic = message => { console.error(message); process.exit(1); }; -// invalid options throw a RangeError (or TypeError) naming them, before any work, instead of failing somewhere inside +// invalid options throw a RangeError (or TypeError), before any work, instead of failing somewhere inside // an encoder or being ignored -const rejects = async (name, fn, Type, pattern) => { +const rejects = async (name, fn, Type) => { try { await fn(); } catch (error) { - if (!(error instanceof Type) || !pattern.test(error.message)) panic(`${name}: wrong error ${error?.constructor?.name}: ${error?.message}`); + if (!(error instanceof Type)) panic(`${name}: wrong error ${error?.constructor?.name}: ${error?.message}`); return; } panic(`${name}: accepted`); @@ -19,51 +19,246 @@ const rejects = async (name, fn, Type, pattern) => { (async () => { const image = new Image(8, 8).fill(0x336699ff); - const animation = () => new Animation([new Frame(8, 8, {duration: 100}).fill(0xff0000ff), new Frame(8, 8, {duration: 100}).fill(0x00ff00ff)]); - const encoded = async (encoder) => { - await encoder.add(new Frame(8, 8).fill(0xff0000ff)); + const animation = () => new Animation([new Frame(new Image(8, 8).fill(0xff0000ff), {duration: 100}), new Frame(new Image(8, 8).fill(0x00ff00ff), {duration: 100})]); + const encoded = async (encoder, options) => { + await encoder.add(new Frame(new Image(8, 8).fill(0xff0000ff)), options); return encoder.finish(); }; for (const effort of [-1, 3, 1.5, NaN, '1', null]) { - await rejects(`encodeAVIF effort ${effort}`, () => image.encodeAVIF({effort}), RangeError, /effort must be an integer 0-2/); - await rejects(`encodeJXL effort ${effort}`, () => image.encodeJXL({effort}), RangeError, /effort must be an integer 0-2/); + // (what isn't a number is a TypeError) + const type = typeof effort === 'number' ? RangeError : TypeError; + await rejects(`encodeAVIF effort ${effort}`, () => image.encodeAVIF({effort}), type); + await rejects(`encodeJXL effort ${effort}`, () => image.encodeJXL({effort}), type); } for (const effort of [-1, 7, 1.5, NaN]) { // (lossless WebP doesn't use it, but checks it) - await rejects(`encodeWebP lossless effort ${effort}`, () => image.encodeWebP({effort}), RangeError, /effort must be an integer 0-6/); - await rejects(`encodeWebP effort ${effort}`, () => image.encodeWebP({quality: 80, effort}), RangeError, /effort must be an integer 0-6/); - await rejects(`Animation.encodeWebP effort ${effort}`, () => animation().encodeWebP({effort}), RangeError, /effort must be an integer 0-6/); - await rejects(`webpEncoder effort ${effort}`, () => encoded(Animation.webpEncoder(8, 8, {effort})), RangeError, /effort must be an integer 0-6/); + await rejects(`encodeWebP lossless effort ${effort}`, () => image.encodeWebP({effort}), RangeError); + await rejects(`encodeWebP effort ${effort}`, () => image.encodeWebP({quality: 80, effort}), RangeError); + await rejects(`Animation.encodeWebP effort ${effort}`, () => animation().encodeWebP({effort}), RangeError); + await rejects(`webpEncoder effort ${effort}`, () => encoded(Animation.webpEncoder(8, 8, {effort})), RangeError); } + // (out-of-range JPEG qualities throw, they aren't clamped) + for (const quality of [-5, 101, 1000, NaN, Infinity]) { + await rejects(`encodeJPEG quality ${quality}`, () => image.encodeJPEG({quality}), RangeError); + } + for (const quality of [0, 1, 100]) await image.encodeJPEG({quality}); for (const quality of [-1, 101, NaN]) { - await rejects(`encodeAVIF quality ${quality}`, () => image.encodeAVIF({quality}), RangeError, /quality/); - await rejects(`encodeAVIF alphaQuality ${quality}`, () => image.encodeAVIF({alphaQuality: quality}), RangeError, /alphaQuality/); + await rejects(`encodeAVIF quality ${quality}`, () => image.encodeAVIF({quality}), RangeError); + await rejects(`encodeAVIF alphaQuality ${quality}`, () => image.encodeAVIF({alphaQuality: quality}), RangeError); } for (const subsampling of ['4:2:2', '', null]) - await rejects(`encodeAVIF subsampling ${subsampling}`, () => image.encodeAVIF({subsampling}), TypeError, /subsampling must be/); + await rejects(`encodeAVIF subsampling ${subsampling}`, () => image.encodeAVIF({subsampling}), TypeError); // GIF quality and APNG compression are clamped (like PNG's), but have to be numbers - await rejects('encodeGIF quality NaN', () => animation().encodeGIF({quality: NaN}), RangeError, /quality/); - await rejects('gifEncoder quality NaN', () => encoded(Animation.gifEncoder(8, 8, {quality: NaN})), RangeError, /quality/); - await rejects('encodeAPNG compression NaN', () => animation().encodeAPNG({compression: NaN}), RangeError, /compression level/); - await rejects('apngEncoder compression NaN', () => encoded(Animation.apngEncoder(8, 8, {compression: NaN})), RangeError, /compression level/); - if (!(await animation().encodeGIF({quality: 1000})).length || !(await animation().encodeAPNG({compression: 12})).length) panic('clamped values rejected'); - - await rejects('Animation loopCount 1.5', () => new Animation([new Frame(8, 8)], {loopCount: 1.5}), RangeError, /loop count/); - await rejects('dominantColor threshold NaN', () => image.dominantColor({threshold: NaN}), RangeError, /threshold/); - await rejects('renderSVG size NaN', () => Image.renderSVG('', {size: NaN}), RangeError, /SVG size/); - await rejects('renderText size -1', () => Image.renderText(new Uint8Array(0), -1, 'x'), RangeError, /font size/); - const png = await image.encode(); + await rejects('encodeGIF colors NaN', () => animation().encodeGIF({colors: NaN}), RangeError); + await rejects('gifEncoder colors NaN', () => encoded(Animation.gifEncoder(8, 8, {colors: NaN})), RangeError); + await rejects('encodeGIF colors 1', () => animation().encodeGIF({colors: 1}), RangeError); + await rejects('encodeGIF dither', () => animation().encodeGIF({dither: 'random'}), TypeError); + await rejects('encodeAPNG compression NaN', () => animation().encodeAPNG({compression: NaN}), RangeError); + await rejects('apngEncoder compression NaN', () => encoded(Animation.apngEncoder(8, 8, {compression: NaN})), RangeError); + await rejects('encodeAPNG compression 12', () => animation().encodeAPNG({compression: 12}), RangeError); + + await rejects('Animation loopCount 1.5', () => new Animation([new Frame(new Image(8, 8))], {loopCount: 1.5}), RangeError); + await rejects('dominantColor threshold NaN', () => image.dominantColor({threshold: NaN}), RangeError); + await rejects('renderSVG scale NaN', () => Image.renderSVG('', {scale: NaN}), RangeError); + await rejects('renderSVG maxPixels 0', () => Image.renderSVG('', {maxPixels: 0}), RangeError); + await rejects('renderSVG maxPixels names the render options', () => Image.renderSVG('', {maxPixels: 15}), LimitError); + await rejects('renderSVG maxPixels exceeded', () => Image.renderSVG('', {maxPixels: 15}), RangeError); + if ((await Image.renderSVG('', {maxPixels: 16})).width !== 4) + panic('renderSVG: maxPixels should allow an output that fits'); + await rejects('renderText size -1', () => Image.renderText('x', { font: new Uint8Array(0), size: -1 }), RangeError); + if (new Image(2.9, 1).width !== 2) panic('Image constructor: fractional dimensions should still be truncated'); + await rejects('Image width wraps to small positive dimension', () => new Image(2 ** 32 + 2, 1), RangeError); + const png = await image.encodePNG(); for (const maxPixels of [NaN, -1, 0]) { - await rejects(`Image.decode maxPixels ${maxPixels}`, () => Image.decode(png, {maxPixels}), RangeError, /maxPixels/); - await rejects(`Animation.decode maxPixels ${maxPixels}`, () => Animation.decode(png, {maxPixels}), RangeError, /maxPixels/); + await rejects(`Image.decode maxPixels ${maxPixels}`, () => Image.decode(png, {maxPixels}), RangeError); + await rejects(`Animation.decode maxPixels ${maxPixels}`, () => Animation.decode(png, {maxPixels}), RangeError); + } + await rejects('Animation.decode threads 0', () => Animation.decode(png, {threads: 0}), RangeError); + // (the shared checks of the limits and of threads: every option that takes one says so by its name) + { + const map = await new Image(8, 8).fill(0x808080ff).encodeJPEG(); + for (const bad of [0, -1, NaN]) await rejects(`GainMap.decode maxPixels ${bad}`, () => require('..').GainMap.decode(map, {maxPixels: bad}), RangeError); + for (const threads of [0, -1, 1.5, NaN]) + for (const [name, call] of Object.entries({'Image.decode': () => Image.decode(png, {threads}), 'encodeWebP': () => image.encodeWebP({threads}), 'encodeAVIF': () => image.encodeAVIF({threads}), 'encodeJXL': () => image.encodeJXL({threads})})) + await rejects(`${name} threads ${threads}`, call, RangeError); + } + + // a value outside a fixed set of choices is a TypeError + await rejects('resize mode', () => image.clone().resize(4, 4, {mode: 'lanczos'}), TypeError); + await rejects('scale mode', () => image.clone().scale(2, {mode: 'lanczos'}), TypeError); + await rejects('blend mode', () => image.clone().composite(image, {mode: 'nope'}), TypeError); + for (const source of [undefined, null, {}, 5, new Frame(image)]) await rejects(`composite source ${String(source)}`, () => image.clone().composite(source), TypeError); + + // scale() doesn't shrink a side below one pixel, like resize({ width }) keeping the aspect ratio + { + const thin = new Image(7, 1).scale(0.5); + if (thin.width !== 3 || thin.height !== 1) panic(`new Image(7, 1).scale(0.5) is ${thin.width}x${thin.height}`); + const tiny = new Image(10, 3).scale(0.01); + if (tiny.width !== 1 || tiny.height !== 1) panic(`scale(0.01) is ${tiny.width}x${tiny.height}`); + for (const factor of [0, -1, NaN]) await rejects(`scale(${factor})`, () => image.clone().scale(factor), RangeError); + } + await rejects('flip direction', () => image.clone().flip('diagonal'), TypeError); + await rejects('disposal mode', () => new Frame(image, {disposalMode: 'none'}), TypeError); + await rejects('wrapStyle', () => Image.renderText('hi', {font: new Uint8Array(4), size: 8, wrapStyle: 'line'}), TypeError); + // (an invalid mode is found before anything changes: a frame's offsets stay) + { + const frame = new Frame(new Image(100, 50), {xOffset: 10, yOffset: 10}); + await rejects('cover mode', () => frame.resize({width: 20, height: 20, fit: 'cover', mode: 'lanczos'}), TypeError); + if (frame.xOffset !== 10 || frame.yOffset !== 10 || frame.width !== 100) panic('an invalid cover mode moved the frame'); + } + + // compression levels are integers 0-9, like efforts (out of range ones aren't clamped) + for (const compression of [-1, 10, 99, 4.5, NaN, '4', null]) { + const type = typeof compression === 'number' ? RangeError : TypeError; + await rejects(`encodePNG compression ${compression}`, () => image.encodePNG({compression}), type); + await rejects(`encodeAPNG compression ${compression}`, () => animation().encodeAPNG({compression}), type); + } + + // colors are integers from -2^31 (what bitwise operators return) to 2^32 - 1: others throw instead of wrapping + for (const color of [2 ** 32, 2 ** 32 + 5, -(2 ** 31) - 1, 1.5, NaN, Infinity]) { + await rejects(`setPixelAt color ${color}`, () => image.clone().setPixelAt(0, 0, color), RangeError); + await rejects(`fill color ${color}`, () => image.clone().fill(color), RangeError); + await rejects(`fill function color ${color}`, () => image.clone().fill(() => color), RangeError); + } + // values that do nothing useful throw: a negative radius, a fisheye strength that leaves an empty image + await rejects('roundCorners radius -1', () => image.clone().roundCorners({radius: -1}), RangeError); + await rejects('fisheye strength -1', () => image.clone().fisheye({strength: -1}), RangeError); + await rejects('fisheye strength 0', () => image.clone().fisheye({strength: 0}), RangeError); + image.clone().roundCorners({radius: 0}); + image.clone().roundCorners({radius: 1e6}); + await rejects('fill function without a color', () => image.clone().fill(() => undefined), TypeError); + if (new Image(1, 1).setPixelAt(0, 0, 0xff << 24 | 0xff).getPixelAt(0, 0) !== 0xff0000ff) panic('a negative (signed) color should be read as unsigned'); + if (new Image(1, 1).fill(-1).getPixelAt(0, 0) !== 0xffffffff) panic('fill(-1) should be white'); + + // coordinates are truncated like sizes, without wrapping around at 2^32 + await rejects('getPixelAt 2^32', () => image.getPixelAt(2 ** 32, 0), RangeError); + await rejects('setPixelAt 2^32 + 1', () => image.clone().setPixelAt(2 ** 32 + 1, 0, 0), RangeError); + { + const canvas = new Image(4, 1); + canvas.composite(new Image(1, 1).fill(0xffffffff), {x: 2 ** 32 + 1}); + if (canvas.getPixelAt(1, 0) !== 0) panic('composite at x = 2^32 + 1 drew at x = 1'); + await rejects('crop at 2^32', () => new Image(4, 4).crop(2 ** 32, 0, 2, 2), RangeError); + } + + // a gradient position that isn't a number throws, whatever the number of stops; stops at one position are an edge + { + const {Colors} = require('..'); + await rejects('gradient of 2 at NaN', () => Colors.gradient([0xff0000ff, 0x0000ffff])(NaN), RangeError); + await rejects('gradient of 3 at NaN', () => Colors.gradient([0xff0000ff, 0x00ff00ff, 0x0000ffff])(NaN), RangeError); + await rejects('gradient of 1 at NaN', () => Colors.gradient([0xff0000ff])(NaN), RangeError); + for (const stops of [[0xff0000ff], [0xff0000ff, 0x0000ffff], [0xff0000ff, 0x00ff00ff, 0x0000ffff]]) + await rejects(`gradient of ${stops.length} at 'x'`, () => Colors.gradient(stops)('x'), TypeError); + + // colors blend premultiplied, like CSS: what fades out leaves no dark color behind + const fade = Colors.gradient([0x00000000, 0xff0000ff]); + const [fr, fg, fb, fa] = Colors.toRGBA(fade(0.5)); + if (fr !== 255 || fg !== 0 || fb !== 0 || Math.abs(fa - 127.5) > 1) panic(`transparent to red at the middle: ${[fr, fg, fb, fa]}, CSS gives 255,0,0,~128`); + if (fade(0) !== 0 || fade(1) !== 0xff0000ff) panic('a gradient should start and end with its colors'); + const [gr, gg, gb] = Colors.toRGBA(Colors.gradient([0xff0000ff, 0x0000ff00])(0.5)); + if (gr !== 255 || gg !== 0 || gb !== 0) panic(`red to transparent blue at the middle: ${[gr, gg, gb]}, the invisible end shouldn't tint it`); + if (Colors.gradient([0xff0000ff, 0x0000ffff])(0.5) !== 0x7f007fff) panic('opaque colors blend as they did'); + const edge = Colors.gradient({0: 0xff0000ff, 0.5: 0x00ff00ff, '0.50': 0x0000ffff, 1: 0xffffffff}); + if ([0.25, 0.5, 0.75].some(p => Number.isNaN(edge(p)))) panic('a gradient with two stops at one position'); + const single = Colors.gradient({0.5: 0xff0000ff, '0.50': 0x00ff00ff, '5e-1': 0x0000ffff}); + if (single(0.2) !== 0xff0000ff || single(0.8) !== 0x0000ffff) panic('a gradient with all stops at one position'); + } + + // bitmaps are used without copying, so they have to start at a byte offset divisible by 4 + { + const target = new Image(2, 2); + await rejects('unaligned bitmap', () => { target.bitmap = new Uint8Array(17).subarray(1); }, TypeError); + const aligned = new Uint8Array(20).subarray(4); + target.bitmap = aligned; + aligned[0] = 7; + if (target.bitmap[0] !== 7) panic('an aligned bitmap should be used without copying'); + } + + // frame offsets are truncated to integers, like image sizes + { + const frame = new Frame(new Image(1, 1), {xOffset: 2.7, yOffset: -0.5}); + if (frame.xOffset !== 2 || !Object.is(frame.yOffset, 0)) panic(`frame offsets should be truncated, got ${frame.xOffset}, ${frame.yOffset}`); + frame.xOffset = -3.9; + if (frame.xOffset !== -3) panic(`frame.xOffset = -3.9 should be -3, got ${frame.xOffset}`); + } + + // frame durations a format can't store throw, like loop counts (and frames merged for being unchanged are split) + { + const long = duration => new Animation([new Frame(new Image(2, 2).fill(0xff0000ff), {duration})]); + for (const [format, max] of [['GIF', 655350], ['APNG', 655350], ['WebP', 0xffffff]]) { + await rejects(`encode${format} duration ${max + 1}`, () => long(max + 1)[`encode${format}`](), RangeError); + await rejects(`${format} encoder duration ${max + 1}`, () => encoded(Animation[`${format.toLowerCase()}Encoder`](8, 8, {}), {duration: max + 1}), RangeError); + await long(max)[`encode${format}`](); + const frames = () => [1, 2, 3].map(() => new Frame(new Image(2, 2).fill(0xff0000ff), {duration: 400000})); + const decoded = await Animation.decode(await new Animation(frames())[`encode${format}`]()); + if (decoded.duration !== 1200000 || decoded.frames.some(f => f.duration > max)) panic(`${format}: merged frames should be split at the limit, got ${decoded.frames.map(f => f.duration)}`); + } + await rejects('encodeGIF without frames', () => new Animation([]).encodeGIF(), Error); } - await rejects('Animation.decode threads 0', () => Animation.decode(png, {threads: 0}), RangeError, /threads must be/); - // GIFs are refused by Image.decode() with a hint at Animation.decode() - const gif = await new Animation([new Frame(4, 4).fill(0xff0000ff)]).encodeGIF(); - await rejects('Image.decode GIF', () => Image.decode(gif), Error, /Animation\.decode\(\)/); + // numbers have to be numbers everywhere: a string, null or a boolean is a TypeError, also as an option's value (null + // isn't "not given") and in the setters of a gain map; a number outside of what the argument takes is a RangeError + { + const {GainMap} = require('..'); + const gain = () => new GainMap(new Image(2, 2).fill(0x808080ff), {max: 2}); + const typeErrors = { + 'scale("2")': () => image.clone().scale('2'), 'scale(true)': () => image.clone().scale(true), 'blur("2")': () => image.clone().blur('2'), 'blur(null)': () => image.clone().blur(null), + 'composite opacity null': () => image.clone().composite(image, {opacity: null}), 'composite x null': () => image.clone().composite(image, {x: null}), + 'roundCorners radius null': () => image.clone().roundCorners({radius: null}), 'fisheye strength null': () => image.clone().fisheye({strength: null}), + 'sharpen amount "1"': () => image.clone().sharpen({amount: '1'}), 'cropCircle feathering "0.5"': () => image.clone().cropCircle({feathering: '0.5'}), + 'gain map max true': () => { gain().max = true; }, 'gain map min null': () => { gain().min = null; }, 'gain map hdrCapacityMax null': () => new GainMap(new Image(2, 2), {hdrCapacityMax: null}), + 'encoder frame duration null': () => encoded(Animation.gifEncoder(8, 8), {duration: null}), 'encoder frame xOffset "1"': () => encoded(Animation.gifEncoder(8, 8), {xOffset: '1'}) + }; + for (const [name, call] of Object.entries(typeErrors)) await rejects(name, call, TypeError); + for (const [name, call] of Object.entries({ + 'cropCircle feathering -1': () => image.clone().cropCircle({feathering: -1}), 'cropCircle feathering 5': () => image.clone().cropCircle({feathering: 5}), + 'composite opacity 2': () => image.clone().composite(image, {opacity: 2}), 'blur NaN': () => image.clone().blur(NaN), 'sharpen radius 0': () => image.clone().sharpen({radius: 0}) + })) await rejects(name, call, RangeError); + image.clone().cropCircle({feathering: 0}); + image.clone().cropCircle({feathering: 1}); + } + + // a shadow or outline too large for an image fails with a LimitError, before it allocates + { + const {LimitError} = require('..'); + const small = new Image(10, 10).fill(0xff0000ff); + await rejects('dropShadow blur 1e5', () => small.clone().dropShadow({blur: 1e5}), LimitError); + await rejects('dropShadow x 1e9', () => small.clone().dropShadow({x: 1e9}), LimitError); + await rejects('outline width 1e5', () => small.clone().outline({width: 1e5}), LimitError); + } + + // a canvas the format can't store throws instead of wrapping (GIF stores 16 bits, an empty one has nothing to store) + { + const wide = new Animation([new Frame(new Image(2, 1).fill(0xff0000ff))], {width: 70000, height: 1}); + await rejects('encodeGIF canvas 70000 wide', () => wide.encodeGIF(), RangeError); + await rejects('gifEncoder canvas 70000 wide', () => encoded(Animation.gifEncoder(70000, 1)), RangeError); + const empty = new Animation([new Frame(new Image(4, 4).fill(0xff0000ff), {xOffset: -10, yOffset: -10})]); + for (const format of ['GIF', 'APNG', 'WebP']) await rejects(`encode${format} canvas without area`, () => empty[`encode${format}`](), RangeError); + const decoded = await Animation.decode(await wide.clone().resize(65535, 1).encodeGIF()); + if (decoded.width !== 65535) panic(`GIF at the largest canvas: width ${decoded.width}`); + } + + // out-of-range values and wrong types throw (nothing is clamped or ignored) + await rejects('dominantColor threshold 300', () => image.dominantColor({threshold: 300}), RangeError); + await rejects('dominantColor threshold -1', () => image.dominantColor({threshold: -1}), RangeError); + image.dominantColor({threshold: 256}); + const {GainMap} = require('..'); + const map = new GainMap(new Image(4, 4).fill(0x808080ff), {max: 2}); + await rejects('gain map quality -1', () => map.encodeJPEG({quality: -1}), RangeError); + for (const metadata of ['hi', 5, true]) await rejects(`encodePNG metadata ${metadata}`, () => image.encodePNG({metadata}), TypeError); + await rejects('new AnimationEncoder()', () => new (require('..').AnimationEncoder)(), TypeError); + + // a self composite reads the source before it is written + { + const base = new Image(40, 30).fill((x, y) => ((x * 7 % 256) << 24 | (y * 13 % 256) << 16 | ((x ^ y) % 256) << 8 | 0xff) >>> 0); + for (const options of [{x: 10, y: 10}, {x: 10, y: 0}, {x: 0, y: 10}, {x: 10, y: 10, mode: 'multiply'}, {x: 5, y: 5, opacity: 0.5}]) { + const a = base.clone().composite(base.clone(), options); + const self = base.clone(); + self.composite(self, options); + if (Buffer.compare(Buffer.from(a.bitmap), Buffer.from(self.bitmap))) panic(`composite onto itself differs from a clone: ${JSON.stringify(options)}`); + } + } // valid values keep working for (const effort of [0, 1, 2]) await image.encodeAVIF({effort}); diff --git a/tests/options-objects.js b/tests/options-objects.js new file mode 100644 index 00000000..497399bc --- /dev/null +++ b/tests/options-objects.js @@ -0,0 +1,198 @@ +const fs = require('fs').promises; +const {Image, Frame, Animation, GainMap, decode} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// the options of every method that takes them must be an object (or left out): a stray number, string, boolean or null, +// or positional values, is a call in a form that doesn't exist, so it throws a TypeError instead of being ignored +const refuses = async (label, call) => { + let error = null; + try { await call(); } catch (e) { error = e; } + if (!(error instanceof TypeError)) panic(`${label}: should throw a TypeError, got ${error}`); + return error; +}; + +const sameImage = (image, reference, label) => { + if (image.width !== reference.width || image.height !== reference.height || !Buffer.from(image.bitmap).equals(Buffer.from(reference.bitmap))) + panic(`${label}: the image should be unchanged`); +}; + +(async () => { + const photo = new Image(20, 12).fill((x, y) => 0x336699ff + x * 0x01000000 + y * 0x00010000 >>> 0); + const font = await fs.readFile('./tests/fonts/opensans bold.ttf'); + + // resize, scale and the frames' resize take the sampling mode in the options only + for (const [label, mode] of Object.entries({'a mode name': 'area', 'a string': 'bilinear', 'an unknown mode': 'Area', 'null': null})) { + const image = photo.clone(); + await refuses(`resize(10, 6, ${label})`, () => image.resize(10, 6, mode)); + sameImage(image, photo, `resize(10, 6, ${label})`); + const scaled = photo.clone(); + await refuses(`scale(0.5, ${label})`, () => scaled.scale(0.5, mode)); + sameImage(scaled, photo, `scale(0.5, ${label})`); + const resizedFrame = new Frame(new Image(20, 12), {duration: 50}); + await refuses(`Frame.resize(10, 6, ${label})`, () => resizedFrame.resize(10, 6, mode)); + if (resizedFrame.width !== 20 || resizedFrame.height !== 12) panic(`Frame.resize(10, 6, ${label}): the frame should keep its size`); + const animation = new Animation([new Frame(new Image(20, 12))]); + await refuses(`Animation.resize(10, 6, ${label})`, () => animation.resize(10, 6, mode)); + if (animation.frames[0].width !== 20 || animation.frames[0].height !== 12) panic(`Animation.resize(10, 6, ${label}): the frames should keep their size`); + } + + // the image operations take their values in the options object only + const patch = new Image(2, 2).fill(0xff0000ff); + const positional = { + 'composite(patch, 3, 4)': image => image.composite(patch, 3, 4), + 'composite(patch, 3)': image => image.composite(patch, 3), + 'composite(patch, 3, 4, { opacity: 0.5 })': image => image.composite(patch, 3, 4, {opacity: 0.5}), + 'trim(0xffffffff)': image => image.trim(0xffffffff), + 'trim(0xffffffff, { tolerance: 0.1 })': image => image.trim(0xffffffff, {tolerance: 0.1}), + 'colorToAlpha(0xffffffff)': image => image.colorToAlpha(0xffffffff), + 'colorToAlpha(0xffffffff, { opacityThreshold: 0.5 })': image => image.colorToAlpha(0xffffffff, {opacityThreshold: 0.5}), + 'sharpen(2, 3)': image => image.sharpen(2, 3), + 'sharpen(2)': image => image.sharpen(2), + 'dominantColor(true)': image => image.dominantColor(true), + 'dominantColor(true, false, 4)': image => image.dominantColor(true, false, 4), + 'rotate(45, false)': image => image.rotate(45, false), + 'rotate(45, true)': image => image.rotate(45, true), + 'roundCorners(3)': image => image.roundCorners(3), + 'fisheye(3)': image => image.fisheye(3) + }; + for (const [label, call] of Object.entries(positional)) { + const image = photo.clone(); + await refuses(label, () => call(image)); + sameImage(image, photo, label); + } + { + const frame = new Frame(new Image(20, 12), {xOffset: 4, yOffset: 5}); + await refuses('Frame.trim(0xffffffff)', () => frame.trim(0xffffffff)); + if (frame.xOffset !== 4 || frame.yOffset !== 5 || frame.width !== 20) panic('Frame.trim(0xffffffff): the frame should be unchanged'); + } + const solid = new Image(6, 6).fill(0xffffffff).composite(new Image(2, 2).fill(0x000000ff), {x: 2, y: 2}); + if (solid.clone().trim({color: 0xffffffff}).width !== 2) panic('trim({ color }) should trim the color'); + if (solid.clone().composite(patch, {x: 1, y: 1}).getPixelAt(1, 1) !== 0xff0000ff) panic('composite(patch, { x, y }) should place the patch'); + if (solid.clone().sharpen({amount: 0}).getPixelAt(2, 2) !== 0x000000ff) panic('sharpen({ amount: 0 }) should not change the pixels'); + if (solid.clone().roundCorners({radius: 0}).getPixelAt(0, 0) !== 0xffffffff) panic('roundCorners({ radius: 0 }) should not change the pixels'); + if (solid.clone().rotate(90, {expand: false}).width !== 6) panic('rotate(90, { expand: false })'); + + // the encoders take their values in the options object only; the metadata goes in { metadata } + const makeAnimation = () => new Animation([new Frame(new Image(4, 4))]); + const gainMap = new GainMap(new Image(4, 4).fill(0x808080ff), {min: 0, max: 2}); + for (const [label, call] of Object.entries({ + 'encodePNG(1)': () => photo.encodePNG(1), + 'encodePNG(1, { author })': () => photo.encodePNG(1, {author: 'me'}), + 'encodeJPEG(80)': () => photo.encodeJPEG(80), + 'encodeGIF(10)': () => makeAnimation().encodeGIF(10), + 'encodeAPNG(9)': () => makeAnimation().encodeAPNG(9), + 'GainMap.encodeJPEG(70)': () => gainMap.encodeJPEG(70) + })) await refuses(label, call); + if (!Buffer.from(await photo.encodePNG({compression: 1, metadata: {author: 'me'}})).includes('me')) panic('encodePNG({ metadata }): the metadata is missing'); + if (!(await photo.encodeJPEG({quality: 80})).length || !(await makeAnimation().encodeGIF({colors: 16})).length) panic('encoders with options'); + if (!(await gainMap.encodeJPEG({quality: 70})).length || !(await gainMap.encodeJPEG()).length) panic('GainMap.encodeJPEG with options'); + + // renderSVG takes its size and mode in the options object only + const svgSource = ''; + for (const [label, call] of Object.entries({ + 'renderSVG(svg, 2)': () => Image.renderSVG(svgSource, 2), + 'renderSVG(svg, 2, width)': () => Image.renderSVG(svgSource, 2, 'width'), + 'renderSVG(svg, width)': () => Image.renderSVG(svgSource, 'width') + })) await refuses(label, call); + if ((await Image.renderSVG(svgSource, {scale: 2})).width !== 20) panic('renderSVG(svg, { scale }) should scale'); + const byWidth = await Image.renderSVG(svgSource, {width: 30}); + if (byWidth.width !== 30 || byWidth.height !== 30) panic(`renderSVG(svg, { width }): ${byWidth.width}x${byWidth.height}`); + + // frames and animations take their duration, offsets, disposal mode and loop count in the options object only + const frame = new Frame(new Image(4, 4), {duration: 40, xOffset: 2, yOffset: 3, disposalMode: 'background'}); + if (frame.duration !== 40 || frame.xOffset !== 2 || frame.yOffset !== 3 || frame.disposalMode !== 'background') panic('new Frame(new Image(width, height), options)'); + if (new Frame(photo.clone(), {duration: 40, xOffset: 2}).xOffset !== 2 || new Frame(photo.clone()).duration !== 100) panic('new Frame(image.clone(), options)'); + if (new Animation([new Frame(new Image(4, 4))], {loopCount: 2}).loopCount !== 2 || new Animation([new Frame(new Image(4, 4))]).loopCount !== Infinity) panic('new Animation(frames, options)'); + const encodedGIF = await makeAnimation().encodeGIF(); + for (const [label, call] of Object.entries({ + 'new Frame(new Image(4, 4), 100)': () => new Frame(new Image(4, 4), 100), + 'new Frame(new Image(4, 4), 100, 1, 1, "keep")': () => new Frame(new Image(4, 4), 100, 1, 1, 'keep'), + 'new Frame(photo.clone(), 100)': () => new Frame(photo.clone(), 100), + 'new Frame(photo.clone(), 100, 1, 1, "keep")': () => new Frame(photo.clone(), 100, 1, 1, 'keep'), + 'new Animation([frame], 2)': () => new Animation([frame], 2), + 'new Animation([frame], Infinity)': () => new Animation([frame], Infinity), + 'Animation.decode(gif, true)': () => Animation.decode(encodedGIF, true), + 'decode(gif, true)': () => decode(encodedGIF, true) + })) await refuses(label, call); + + let nanError = null; + try { photo.clone().resize(NaN, 6); } catch (e) { nanError = e; } + if (!(nanError instanceof RangeError)) panic(`resize(NaN, 6) should throw a RangeError, got ${nanError}`); + + // the options form still resizes; undefined stays fine + if (photo.clone().resize(10, 6, {mode: 'area'}).width !== 10) panic('resize(10, 6, { mode })'); + if (photo.clone().resize(10, 6).height !== 6) panic('resize(10, 6)'); + if (photo.clone().resize(10, 6, undefined).height !== 6) panic('resize(10, 6, undefined)'); + if (photo.clone().scale(0.5, {mode: 'area'}).width !== 10) panic('scale(0.5, { mode })'); + if (photo.clone().resize({width: 10, height: 10, fit: 'inside', mode: 'area'}).width !== 10) panic('resize({ width, height, fit: \'inside\', mode })'); + if (photo.clone().resize({width: 10, height: 10, fit: 'contain', mode: 'area'}).height !== 10) panic('resize({ fit: \'contain\', mode })'); + if (photo.clone().resize({width: 10, height: 10, fit: 'cover', mode: 'area'}).width !== 10) panic('resize({ fit: \'cover\', mode })'); + if (new Frame(new Image(20, 12)).resize(10, 6, {mode: 'area'}).width !== 10) panic('Frame.resize(10, 6, { mode })'); + if (new Animation([new Frame(new Image(20, 12))]).resize(10, 6, {mode: 'area'}).frames[0].width !== 10) panic('Animation.resize(10, 6, { mode })'); + + // cropCircle takes its fit and feathering in the options object only + for (const [label, bad] of Object.entries({'true': true, 'false': false, 'a number': 0.5, 'a string': 'cover', 'null': null, 'a typed array': new Uint8Array(2)})) { + const image = photo.clone(); + await refuses(`cropCircle(${label})`, () => image.cropCircle(bad)); + sameImage(image, photo, `cropCircle(${label})`); + } + for (const fine of [undefined, {}, {fit: 'cover'}, {fit: 'contain', feathering: 0.1}]) photo.clone().cropCircle(fine); + await refuses('cropCircle with an unknown fit', () => photo.clone().cropCircle({fit: 'huge'})); + + // renderText(text, { font, size, ... }) is the only form: the font first is refused too + const ok = await Image.renderText('Hi', {font, size: 24}); + if (ok.width < 4 || ok.height < 4) panic(`renderText: ${ok.width}x${ok.height}`); + for (const [label, call] of Object.entries({ + 'the font first': () => Image.renderText(font, 32, 'Hi'), + 'no options': () => Image.renderText('Hi'), + 'null options': () => Image.renderText('Hi', null), + 'a size instead of options': () => Image.renderText('Hi', 32), + 'a number as the text': () => Image.renderText(5, {font, size: 10}) + })) await refuses(`renderText with ${label}`, call); + await refuses('renderText without a font', () => Image.renderText('Hi', {size: 10})); + + // the methods that only take options, with every value that isn't one + const still = new Frame(photo.clone()); + const calls = { + 'quantize': bad => photo.clone().quantize(bad), + 'transform': bad => photo.clone().transform([1, 0, 0, 1, 0, 0], bad), + 'dropShadow': bad => photo.clone().dropShadow(bad), + 'outline': bad => photo.clone().outline(bad), + 'Image.linearGradient': bad => Image.linearGradient(8, 8, bad), + 'Image.radialGradient': bad => Image.radialGradient(8, 8, bad), + 'Image.decode': async bad => Image.decode(await photo.encodePNG(), bad), + 'encodeWebP': bad => photo.encodeWebP(bad), + 'encodeAVIF': bad => photo.encodeAVIF(bad), + 'encodeJXL': bad => photo.encodeJXL(bad), + 'encodeTGA': bad => photo.encodeTGA(bad), + 'Animation.encodeWebP': bad => new Animation([still]).encodeWebP(bad), + 'Animation.webpEncoder': bad => Animation.webpEncoder(8, 8, bad), + 'Animation.gifEncoder': bad => Animation.gifEncoder(8, 8, bad), + 'Animation.apngEncoder': bad => Animation.apngEncoder(8, 8, bad), + 'AnimationEncoder.add': async bad => { const encoder = Animation.gifEncoder(20, 12); await encoder.add(photo, bad); }, + 'new GainMap': bad => new GainMap(new Image(2, 2), bad) + }; + for (const [name, call] of Object.entries(calls)) + for (const [label, bad] of Object.entries({'a number': 80, 'a string': 'fast', 'true': true, 'null': null})) + await refuses(`${name}(${label})`, () => call(bad)); + + // refused calls leave the image as it was + const image = photo.clone(); + for (const [label, call] of Object.entries({ + 'quantize(16)': () => image.quantize(16), + 'dropShadow(8)': () => image.dropShadow(8), + 'outline(2)': () => image.outline(2), + 'transform(..., "bicubic")': () => image.transform([1, 0, 0, 1, 0, 0], 'bicubic') + })) await refuses(label, call); + sameImage(image, photo, 'a refused call'); + + // the options forms (and no options at all) still work + photo.clone().quantize().quantize({colors: 4}); + photo.clone().dropShadow().outline({width: 1}); + if ((await photo.encodeWebP({quality: 50})).length < 10 || (await photo.encodeWebP()).length < 10) panic('encodeWebP with and without options'); + if (new GainMap(new Image(4, 3).fill(0x808080ff), {max: 2}).width !== 4) panic('GainMap options'); +})().catch(error => panic(error.stack || String(error))); diff --git a/tests/options.js b/tests/options.js index 15f7fdaf..5461abfb 100644 --- a/tests/options.js +++ b/tests/options.js @@ -1,5 +1,5 @@ const fs = require('fs').promises; -const {Image, Frame, Animation, GIF, decode} = require('..'); +const {Image, Frame, Animation, decode} = require('..'); const panic = message => { console.error(message); @@ -8,81 +8,47 @@ const panic = message => { const same = (name, a, b) => { const x = a.bitmap ?? a, y = b.bitmap ?? b; - if (x.length !== y.length || x.some((v, i) => v !== y[i])) panic(`${name}: options object and positional arguments differ`); + if (x.length !== y.length || x.some((v, i) => v !== y[i])) panic(`${name}: the results differ`); }; -// every method with optional arguments takes them as an options object too, with the same result +// the defaults: leaving out the options and passing an empty object give the same result (async () => { const photo = await Image.decode(await fs.readFile('./tests/targets/external.jpg')); const tile = () => photo.clone().resize(64, 48); const logo = new Image(16, 16).fill(0xff000080); - same('scale', tile().scale(0.5, Image.RESIZE_NEAREST_NEIGHBOR), tile().scale(0.5, {mode: Image.RESIZE_NEAREST_NEIGHBOR})); - for (const method of ['resize', 'contain', 'fit', 'cover']) - same(method, tile()[method](30, 40, Image.RESIZE_BICUBIC), tile()[method](30, 40, {mode: Image.RESIZE_BICUBIC})); // the default mode same('resize default', tile().resize(30, 40), tile().resize(30, 40, {})); - for (const method of ['opacity', 'red', 'green', 'blue', 'lightness', 'saturation']) { - same(method, tile()[method](0.5, true), tile()[method](0.5, {absolute: true})); - same(`${method} default`, tile()[method](0.5), tile()[method](0.5, {})); - } - - same('composite', tile().composite(logo, 5, 7, {opacity: 0.5, mode: 'multiply'}), tile().composite(logo, {x: 5, y: 7, opacity: 0.5, mode: 'multiply'})); same('composite default', tile().composite(logo), tile().composite(logo, {})); - same('sharpen', tile().sharpen(2, 3), tile().sharpen({amount: 2, radius: 3})); - same('roundCorners', tile().roundCorners(9), tile().roundCorners({radius: 9})); same('roundCorners default', tile().roundCorners(), tile().roundCorners({})); - same('fisheye', tile().fisheye(3), tile().fisheye({strength: 3})); same('fisheye default', tile().fisheye(), tile().fisheye({})); - // encoders: decoded, since the metadata has a creation time - const pixelsOf = async data => (await Image.decode(data)).bitmap; - same('encode', await pixelsOf(await tile().encode(9)), await pixelsOf(await tile().encode({compression: 9}))); - same('encodeJPEG', await pixelsOf(await tile().encodeJPEG(40)), await pixelsOf(await tile().encodeJPEG({quality: 40}))); - // metadata as the first argument (3.x), and in the options + // the metadata goes in { metadata } const author = 'options test'; - for (const data of [await tile().encode({author}), await tile().encode({metadata: {author}}), await tile().encode(1, {author})]) + for (const data of [await tile().encodePNG({metadata: {author}}), await tile().encodePNG({compression: 1, metadata: {author}})]) if (!Buffer.from(data).includes(author)) panic('encode: metadata missing'); if (!Buffer.from(await tile().encodeJPEG({metadata: {author}})).includes(author)) panic('encodeJPEG: metadata missing'); for (const method of ['encodeWebP', 'encodeTGA']) if (!Buffer.from(await tile()[method]({metadata: {author}})).includes(author)) panic(`${method}: metadata missing`); const svg = await fs.readFile('./tests/svgs/crown.svg'); - same('renderSVG', await Image.renderSVG(svg, 40, Image.SVG_MODE_WIDTH), await Image.renderSVG(svg, {size: 40, mode: Image.SVG_MODE_WIDTH})); - - const font = await fs.readFile('./tests/fonts/opensans bold.ttf'); - same('renderText', await Image.renderText(font, 24, 'Options', 0x3366ffff, undefined, {strokeWidth: 2, strokeColor: 0xffffffff}), - await Image.renderText(font, 24, 'Options', {color: 0x3366ffff, strokeWidth: 2, strokeColor: 0xffffffff})); // frames and animations - const a = new Frame(8, 6, 40, 2, 3, 'background'), b = new Frame(8, 6, {duration: 40, xOffset: 2, yOffset: 3, disposalMode: 'background'}); - const c = Frame.from(logo, {duration: 40, xOffset: 2, yOffset: 3, disposalMode: 'background'}); + const b = new Frame(new Image(8, 6), {duration: 40, xOffset: 2, yOffset: 3, disposalMode: 'background'}); + const c = new Frame(logo.clone(), {duration: 40, xOffset: 2, yOffset: 3, disposalMode: 'background'}); for (const frame of [b, c]) if (frame.duration !== 40 || frame.xOffset !== 2 || frame.yOffset !== 3 || frame.disposalMode !== 'background') panic('Frame: options not applied'); - if (new Frame(1, 1, {}).duration !== 100 || new Frame(1, 1, {}).disposalMode !== 'keep') panic('Frame: wrong defaults'); - same('Frame', a, b); + if (new Frame(new Image(1, 1), {}).duration !== 100 || new Frame(new Image(1, 1), {}).disposalMode !== 'keep') panic('Frame: wrong defaults'); - const frames = () => [Frame.from(tile(), {duration: 50}), Frame.from(tile().invert(), {duration: 50})]; - if (new Animation(frames(), {loopCount: 2}).loopCount !== 2 || new GIF(frames(), {loopCount: 2}).loopCount !== 2) panic('Animation: loopCount not applied'); + const frames = () => [new Frame(tile(), {duration: 50}), new Frame(tile().invert(), {duration: 50})]; + if (new Animation(frames(), {loopCount: 2}).loopCount !== 2) panic('Animation: loopCount not applied'); const animation = new Animation(frames()); - const sameFrames = async (name, x, y) => { - const fx = await Animation.decode(x), fy = await Animation.decode(y); - if (fx.length !== fy.length) panic(`${name}: options object and positional arguments differ`); - fx.forEach((f, i) => same(`${name} frame ${i}`, f, fy[i])); - }; - await sameFrames('encodeGIF', await animation.encodeGIF(10), await animation.encodeGIF({quality: 10})); - await sameFrames('encodeAPNG', await animation.encodeAPNG(9), await animation.encodeAPNG({compression: 9})); // (GIFs only store comments) for (const method of ['encodeGIF', 'encodeAPNG', 'encodeWebP']) if (!Buffer.from(await animation[method]({metadata: {author, comment: author}})).includes(author)) panic(`${method}: metadata missing`); - same('Animation.resize', (await Animation.decode(await animation.encodeAPNG())).resize(20, 10, Image.RESIZE_NEAREST_NEIGHBOR)[1], - (await Animation.decode(await animation.encodeAPNG())).resize(20, 10, {mode: Image.RESIZE_NEAREST_NEIGHBOR})[1]); - const gif = await animation.encodeGIF(); - for (const decoded of [await Animation.decode(gif, {onlyFirstFrame: true}), await GIF.decode(gif, {onlyFirstFrame: true}), await decode(gif, {onlyFirstFrame: true})]) - if (decoded.length !== 1) panic('decode: onlyFirstFrame not applied'); if ((await decode(gif, {})).length !== 2) panic('decode: wrong default'); // decode() passes applyOrientation on to Image.decode() diff --git a/tests/other-realms.js b/tests/other-realms.js new file mode 100644 index 00000000..c93435e9 --- /dev/null +++ b/tests/other-realms.js @@ -0,0 +1,39 @@ +const vm = require('vm'); +const {Image, ImageType} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// values made in another realm (a vm context, an iframe, Jest's environment) are accepted like local ones: instanceof +// is false for them +(async () => { + if (typeof Deno !== 'undefined' || process.versions.bun) return; // (node:vm contexts) + const context = vm.createContext({}); + const png = await new Image(2, 2).fill(0xff0000ff).encodePNG(); + const buffer = vm.runInContext(`new ArrayBuffer(${png.length})`, context); + new Uint8Array(buffer).set(png); + for (const [name, data] of [['ArrayBuffer', buffer], ['Uint8Array', vm.runInContext('b => new Uint8Array(b)', context)(buffer)]]) { + const image = await Image.decode(data).catch(err => err); + if (!(image instanceof Image) || image.getPixelAt(0, 0) !== 0xff0000ff) panic(`${name} of another realm: ${image}`); + if (ImageType.getType(data) !== 'png') panic(`ImageType.getType(${name} of another realm)`); + } + // objects that only claim to be one by their tag are not + for (const [name, fake] of [['ArrayBuffer', {[Symbol.toStringTag]: 'ArrayBuffer', byteLength: 8}], ['SharedArrayBuffer', {[Symbol.toStringTag]: 'SharedArrayBuffer', byteLength: 8}], ['proxied ArrayBuffer', new Proxy(new ArrayBuffer(8), {})]]) { + const err = await Image.decode(fake).then(() => null, err => err); + if (!(err instanceof TypeError) || !/^Binary data has to be/.test(err.message)) panic(`a fake ${name}: ${err}`); + } + const fakeDate = await new Image(1, 1).encodePNG({metadata: {creationTime: {[Symbol.toStringTag]: 'Date'}}}).then(() => null, err => err); + if (!(fakeDate instanceof TypeError) || !/^creationTime must be a Date/.test(fakeDate.message)) panic(`a fake Date: ${fakeDate}`); + // a detached buffer (transferred to a worker) is said to be one + const detached = png.buffer.slice(0), detachedView = new Uint8Array(detached); + structuredClone(detached, {transfer: [detached]}); + for (const data of [detached, detachedView]) { + const err = await Image.decode(data).then(() => null, err => err); + if (!(err instanceof TypeError) || !/detached/.test(err.message) || !/^Binary data/.test(err.message)) panic(`a detached buffer: ${err}`); + } + const date = vm.runInContext('new Date(Date.UTC(2020, 1, 1))', context); + const file = await new Image(1, 1).encodePNG({metadata: {creationTime: date}}).catch(err => err); + if (!(file instanceof Uint8Array) || !Buffer.from(file).toString('latin1').includes('2020')) panic(`a Date of another realm: ${file}`); +})(); diff --git a/tests/palette.js b/tests/palette.js index 8a3f416e..4a986cc9 100644 --- a/tests/palette.js +++ b/tests/palette.js @@ -1,4 +1,4 @@ -const {Image, Frame, GainMap} = require('..'); +const {Image, Frame, GainMap, Colors} = require('..'); const panic = message => { console.error(message); @@ -19,7 +19,7 @@ const colorsOf = image => { }; // pseudo-random colors: many distinct ones -const photo = (width, height) => new Image(width, height).fill((x, y) => Image.rgbaToColor((x * 37 + y * 11) % 256, (x * 5 + y * 91) % 256, (x * y) % 256, 255)); +const photo = (width, height) => new Image(width, height).fill((x, y) => Colors.fromRGBA((x * 37 + y * 11) % 256, (x * 5 + y * 91) % 256, (x * y) % 256, 255)); const DITHERS = ['none', 'floyd-steinberg', 'atkinson', 'ordered']; // the mean absolute error of the red channel between 8x8 block averages of two images @@ -69,15 +69,21 @@ const blockError = (original, result) => { } // dithering averages out: 8x8 block averages of a gradient with 4 colors are closer to the original than undithered - const ramp = new Image(128, 16).fill(x => Image.rgbaToColor(Math.round(x * 255 / 127), Math.round(x * 255 / 127), Math.round(x * 255 / 127), 255)); - const plain = blockError(ramp, ramp.clone().quantize({colors: 4})); + const ramp = new Image(128, 16).fill(x => Colors.fromRGBA(Math.round(x * 255 / 127), Math.round(x * 255 / 127), Math.round(x * 255 / 127), 255)); + const plain = blockError(ramp, ramp.clone().quantize({colors: 4, dither: 'none'})); for (const dither of ['floyd-steinberg', 'atkinson', 'ordered']) { const error = blockError(ramp, ramp.clone().quantize({colors: 4, dither})); if (!(error < plain)) panic(`${dither} block error ${error} is not below the undithered ${plain}`); } + // the defaults are the GIF encoders': Floyd-Steinberg at 0.85 + { + const byDefault = photo(30, 20).quantize({colors: 6}); + const explicit = photo(30, 20).quantize({colors: 6, dither: 'floyd-steinberg', ditherStrength: 0.85}); + if (!Buffer.from(byDefault.bitmap).equals(Buffer.from(explicit.bitmap))) panic('quantize defaults: not floyd-steinberg at 0.85'); + } // strength 0 is the same as no dithering for (const dither of ['floyd-steinberg', 'atkinson', 'ordered']) { - const none = photo(20, 20).quantize({colors: 4}); + const none = photo(20, 20).quantize({colors: 4, dither: 'none'}); const zero = photo(20, 20).quantize({colors: 4, dither, ditherStrength: 0}); if (!Buffer.from(none.bitmap).equals(Buffer.from(zero.bitmap))) panic(`${dither} with ditherStrength 0 differs from none`); } @@ -131,8 +137,8 @@ const blockError = (original, result) => { ]; for (const [fn, type, label] of bad) throwsA(fn, type, label); if (!Buffer.from(image.bitmap).equals(snapshot)) panic('a failed quantize changed the image'); - // numeric strings are accepted like the other numeric options - if (colorsOf(photo(9, 9).quantize({colors: '4'})).size > 4) panic('colors: "4" not accepted'); + // numeric strings are refused like they are by the other numeric options + throwsA(() => photo(9, 9).quantize({colors: '4'}), TypeError, 'colors: "4"'); } // edge sizes, and a plain pixel stays what it was @@ -141,17 +147,10 @@ const blockError = (original, result) => { const thin = photo(1, 9).quantize({colors: 3, dither: 'floyd-steinberg'}); if (thin.width !== 1 || thin.height !== 9 || colorsOf(thin).size > 3) panic('1x9 quantize'); - // frames: quantize their own pixels and return the frame - { - const frame = new Frame(20, 10, {duration: 100}).fill((x, y) => Image.rgbaToColor(x * 12, y * 25, 128, 255)); - if (frame.quantize({colors: 2, dither: 'ordered'}) !== frame) panic('quantize does not return this for a frame'); - if (colorsOf(frame).size > 2) panic('frame quantize'); - } - // an image with a gain map keeps a valid one { - const hdr = new Image(8, 8).fill((x, y) => Image.rgbaToColor(x * 30, y * 30, 200, 255)); - hdr.gainMap = new GainMap(new Image(4, 4).fill(0x808080ff), {gainMapMin: 0, gainMapMax: 2}); + const hdr = new Image(8, 8).fill((x, y) => Colors.fromRGBA(x * 30, y * 30, 200, 255)); + hdr.gainMap = new GainMap(new Image(4, 4).fill(0x808080ff), {min: 0, max: 2}); hdr.quantize({colors: 4, dither: 'floyd-steinberg'}); if (!(hdr.gainMap instanceof GainMap)) panic('gain map removed by quantize'); if (colorsOf(hdr).size > 4) panic('quantize with a gain map'); diff --git a/tests/png.js b/tests/png.js index b0de4a45..df22caef 100644 --- a/tests/png.js +++ b/tests/png.js @@ -1,6 +1,6 @@ const fs = require('fs').promises; const crypto = require('crypto'); -const {Image, Animation, Frame} = require('..'); +const {Image, Animation, Frame, Colors} = require('..'); // (for chunks the tests change) const crc32 = data => { @@ -42,17 +42,12 @@ const expected = { } // corrupted checksum must be rejected - try { - await Image.decode(await fs.readFile('./tests/pngsuite/xcsn0g01.png')); - panic('xcsn0g01: corrupted chunk was accepted'); - } catch (err) { - if (!/checksum/.test(err.message)) panic(`xcsn0g01: unexpected error ${err.message}`); - } + if (!await Image.decode(await fs.readFile('./tests/pngsuite/xcsn0g01.png')).then(() => false, error => error instanceof Error)) panic('xcsn0g01: corrupted chunk was accepted'); // encode/decode roundtrip const image = new Image(97, 61); - image.fill((x, y) => Image.rgbaToColor(x * 2, y * 4, (x * y) & 0xff, (x + y) & 0xff)); - const decoded = await Image.decode(await image.encode(3)); + image.fill((x, y) => Colors.fromRGBA(x * 2, y * 4, (x * y) & 0xff, (x + y) & 0xff)); + const decoded = await Image.decode(await image.encodePNG({compression: 3})); if (!Buffer.from(decoded.bitmap).equals(Buffer.from(image.bitmap))) panic('roundtrip failed'); // a file cut off after its image data (in IEND) still decodes @@ -66,8 +61,8 @@ const expected = { // browsers do (here a wrong sequence number in the second fcTL) { const frames = [100, 70000, 100].map((duration, i) => { - const frame = new Frame(8, 8, duration); - frame.fill(0xff0000ff + i * 0x1000); + const frame = new Frame(new Image(8, 8), {duration}); + frame.image.fill(0xff0000ff + i * 0x1000); return frame; }); const encoded = Buffer.from(await new Animation(frames).encodeAPNG({optimize: false})); diff --git a/tests/pnm.js b/tests/pnm.js index 274ad1c2..3eac9055 100644 --- a/tests/pnm.js +++ b/tests/pnm.js @@ -1,4 +1,4 @@ -const {Image, ImageType} = require('..'); +const {Image, ImageType, Colors} = require('..'); const panic = message => { console.error(message); @@ -48,16 +48,16 @@ const pixels = image => Array.from({length: image.width * image.height}, (_, i) if (ImageType.getType(ascii('P7 332\n#XVVERSION:Version 2.28\n')) !== null) panic('XV thumbnails detected as PAM'); // truncated and invalid data throws for (const data of [bytes('P6\n2 2\n255\n', [1, 2, 3]), ascii('P2\n2 1\n255\n0 256\n'), ascii('P5\n0 1\n255\n')]) { - if (!await Image.decode(data).then(() => false, e => /Netpbm/.test(e.message))) panic(`invalid data accepted: ${String.fromCharCode(...data.subarray(0, 12))}`); + if (!await Image.decode(data).then(() => false, e => e instanceof Error)) panic(`invalid data accepted: ${String.fromCharCode(...data.subarray(0, 12))}`); } // encoding: PBM for black and white, PGM for greyscale, PPM, PAM with alpha const cases = [ [new Image(13, 5).fill((x, y) => (x + y) & 1 ? 0xffffffff : 0x000000ff), 'P4'], - [new Image(15, 4).fill((x, y) => Image.rgbaToColor(x * 17, x * 17, x * 17, 255)), 'P5'], - [new Image(7, 3).fill((x, y) => Image.rgbaToColor(x * 30, y * 80, 7, 255)), 'P6'], - [new Image(5, 2).fill((x, y) => Image.rgbaToColor(x * 50, x * 50, x * 50, y * 99)), 'P7', 'GRAYSCALE_ALPHA'], - [new Image(5, 2).fill((x, y) => Image.rgbaToColor(x * 50, 3, 9, y * 99)), 'P7', 'RGB_ALPHA'], + [new Image(15, 4).fill((x, y) => Colors.fromRGBA(x * 17, x * 17, x * 17, 255)), 'P5'], + [new Image(7, 3).fill((x, y) => Colors.fromRGBA(x * 30, y * 80, 7, 255)), 'P6'], + [new Image(5, 2).fill((x, y) => Colors.fromRGBA(x * 50, x * 50, x * 50, y * 99)), 'P7', 'GRAYSCALE_ALPHA'], + [new Image(5, 2).fill((x, y) => Colors.fromRGBA(x * 50, 3, 9, y * 99)), 'P7', 'RGB_ALPHA'], ]; for (const [image, magic, type] of cases) { const encoded = await image.encodePNM(); diff --git a/tests/qoi.js b/tests/qoi.js index ef5a7406..e0be8c45 100644 --- a/tests/qoi.js +++ b/tests/qoi.js @@ -1,5 +1,5 @@ const fs = require('fs').promises; -const {Image, ImageType} = require('..'); +const {Image, ImageType, Colors} = require('..'); const panic = message => { console.error(message); @@ -21,16 +21,11 @@ const panic = message => { // every operation: runs of 62 and longer, the index, small and larger differences, alpha changes const image = new Image(97, 3).fill((x, y) => y === 0 ? 0x336699ff : y === 1 ? [0x336699ff, 0x346799ff, 0x50779aff, 0x336699ff, 0x33669980, 0xffffff00][x % 6] - : Image.rgbaToColor(x * 37 & 255, x * 11 & 255, 255 - x, x & 1 ? 255 : 200)); + : Colors.fromRGBA(x * 37 & 255, x * 11 & 255, 255 - x, x & 1 ? 255 : 200)); const back = await Image.decode(await image.encodeQOI()); if (!Buffer.from(back.bitmap).equals(Buffer.from(image.bitmap))) panic('QOI didn\'t round trip'); const opaque = await new Image(4, 4).fill(0xff0000ff).encodeQOI(); if (opaque[12] !== 3) panic('opaque images should be stored with 3 channels'); - try { - await Image.decode((await image.encodeQOI()).subarray(0, 40)); - panic('truncated QOI accepted'); - } catch (err) { - if (!/QOI/.test(err.message)) panic(`QOI: unexpected error ${err.message}`); - } + if (!await Image.decode((await image.encodeQOI()).subarray(0, 40)).then(() => false, error => error instanceof Error)) panic('truncated QOI accepted'); })(); diff --git a/tests/readme.js b/tests/readme.js index 76f3ff2b..a8dfec12 100644 --- a/tests/readme.js +++ b/tests/readme.js @@ -1,5 +1,5 @@ // the image in the README: a weather card of frosted glass over an SVG landscape -const {Image} = require('..'); +const {Image, Colors} = require('..'); const fs = require('fs'); const samePixels = require('./util/pixels'); @@ -29,16 +29,16 @@ const font = name => fs.readFileSync('./tests/fonts/' + name); // a frosted glass card: the background behind it, blurred and lightened, with a soft shadow const card = {x: 40, y: 40, width: 520, height: 520, radius: 28}; - const shadow = new Image(card.width + 80, card.height + 80).drawBox(40, 48, card.width, card.height, 0x00000060).blur(16); - image.composite(shadow, card.x - 40, card.y - 40); - const glass = image.region(card.x, card.y, card.width, card.height).blur(24) - .composite(new Image(card.width, card.height).fill(0xffffffff), 0, 0, {opacity: 0.18}) - .roundCorners(card.radius); - image.composite(glass, card.x, card.y); + const shadow = new Image(card.width + 80, card.height + 80).composite(new Image(card.width, card.height).fill(0x00000060), {x: 40, y: 48}).blur(16); + image.composite(shadow, {x: card.x - 40, y: card.y - 40}); + const glass = image.extract(card.x, card.y, card.width, card.height).blur(24) + .composite(new Image(card.width, card.height).fill(0xffffffff), {opacity: 0.18}) + .roundCorners({radius: card.radius}); + image.composite(glass, {x: card.x, y: card.y}); const text = async (fonts, size, string, color, x, y) => { - const rendered = await Image.renderText(fonts, size, string, {color}); - image.composite(rendered, x, y); + const rendered = await Image.renderText(string, { font: fonts, size, color }); + image.composite(rendered, {x, y}); return rendered; }; const left = card.x + 40; @@ -53,32 +53,32 @@ const font = name => fs.readFileSync('./tests/fonts/' + name); `); - image.composite(icon, card.x + card.width - 40 - icon.width, card.y + 150); + image.composite(icon, {x: card.x + card.width - 40 - icon.width, y: card.y + 150}); // the week: bars from the lowest to the highest temperature, in a gradient from cool to warm const days = [['Mon', 14, 21], ['Tue', 13, 19], ['Wed', 15, 23], ['Thu', 16, 25], ['Fri', 14, 22], ['Sat', 12, 18], ['Sun', 13, 20]]; - const gradient = Image.gradient({0: 0x5ac8faff, 0.5: 0xffd166ff, 1: 0xff7a59ff}); + const gradient = Colors.gradient({0: 0x5ac8faff, 0.5: 0xffd166ff, 1: 0xff7a59ff}); const chart = {top: card.y + 300, height: 100, min: 10, max: 26}; const step = (card.width - 80) / days.length; for (const [i, [day, low, high]] of days.entries()) { const cx = left + step * i + step / 2; const y0 = chart.top + chart.height * (1 - (high - chart.min) / (chart.max - chart.min)); const y1 = chart.top + chart.height * (1 - (low - chart.min) / (chart.max - chart.min)); - const track = new Image(14, chart.height).fill(0xffffff30).roundCorners(7); - image.composite(track, cx - 7, chart.top); + const track = new Image(14, chart.height).fill(0xffffff30).roundCorners({radius: 7}); + image.composite(track, {x: cx - 7, y: chart.top}); const bar = new Image(14, y1 - y0).fill((x, y) => gradient((chart.max - (y0 + y - chart.top) / chart.height * (chart.max - chart.min) - chart.min) / (chart.max - chart.min))); - image.composite(bar.roundCorners(7), cx - 7, y0); - const label = await Image.renderText(regular, 20, day, {color: 0xffffffc0}); - image.composite(label, cx - label.width / 2, chart.top + chart.height + 10); + image.composite(bar.roundCorners({radius: 7}), {x: cx - 7, y: y0}); + const label = await Image.renderText(day, { font: regular, size: 20, color: 0xffffffc0 }); + image.composite(label, {x: cx - label.width / 2, y: chart.top + chart.height + 10}); } // a divider, then greetings in a few scripts - image.drawBox(left, card.y + 446, card.width - 80, 1, 0xffffff40); - const greeting = await Image.renderText(scripts, 26, 'Bom dia · مرحبا · नमस्ते 😀', {color: 0xffffffe0}); - image.composite(greeting, left, card.y + 446 + (card.height - 446 - greeting.height) / 2); + image.composite(new Image(card.width - 80, 1).fill(0xffffff40), {x: left, y: card.y + 446}); + const greeting = await Image.renderText('Bom dia · مرحبا · नमस्ते 😀', { font: scripts, size: 26, color: 0xffffffe0 }); + image.composite(greeting, {x: left, y: card.y + 446 + (card.height - 446 - greeting.height) / 2}); - image.roundCorners(24); - const encoded = await image.encode({metadata: {creationTime: 0, software: ''}}); + image.roundCorners({radius: 24}); + const encoded = await image.encodePNG({metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) fs.writeFileSync('./tests/targets/readme.png', encoded); diff --git a/tests/regressions.js b/tests/regressions.js index 243a8dcf..9bde848c 100644 --- a/tests/regressions.js +++ b/tests/regressions.js @@ -1,5 +1,5 @@ -const {Image, Frame, GIF, Animation, TextLayout} = require('..'); -const {ResizeModes, SVGScaleModes, FrameDisposalModes, Colors: ColorHelpers} = require('..'); +const {Image, Frame, Animation, LimitError} = require('..'); +const {Colors} = require('..'); const zlib = require('zlib'); // (encoders stamp the current time into the metadata: tests that compare two encodes freeze it, or they differ when a second ends in between) const withFrozenTime = async run => { @@ -14,46 +14,40 @@ const assert = (condition, message) => { process.exit(1); }; -const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); +const rgba = (image, x, y) => Colors.toRGBA(image.getPixelAt(x, y)); (async () => { - // rotating non-square images by right angles (#29) + // rotating non-square images by right angles (#29): rotate() turns clockwise { - const image = new Image(3, 2).fill((x, y) => Image.rgbaToColor(x + 1, y + 1, 0, 255)); - const ccw = image.clone().rotate(90); - assert(ccw.width === 2 && ccw.height === 3, 'rotate(90): dimensions not swapped'); - assert(rgba(ccw, 0, 2).slice(0, 2).join() === '1,1', 'rotate(90): top left should end up bottom left'); - assert(rgba(ccw, 1, 0).slice(0, 2).join() === '3,2', 'rotate(90): bottom right should end up top right'); - - const cw = image.clone().rotate(270); - assert(rgba(cw, 1, 0).slice(0, 2).join() === '1,1', 'rotate(270): top left should end up top right'); - for (const [x, y, color] of cw.iterateWithColors()) assert((color & 0xff) === 255, `rotate(270): hole at ${x},${y}`); + const image = new Image(3, 2).fill((x, y) => Colors.fromRGBA(x + 1, y + 1, 0, 255)); + const ccw = image.clone().rotate(270); + assert(ccw.width === 2 && ccw.height === 3, 'rotate(270): dimensions not swapped'); + assert(rgba(ccw, 0, 2).slice(0, 2).join() === '1,1', 'rotate(270): top left should end up bottom left'); + assert(rgba(ccw, 1, 0).slice(0, 2).join() === '3,2', 'rotate(270): bottom right should end up top right'); + + const cw = image.clone().rotate(90); + assert(rgba(cw, 1, 0).slice(0, 2).join() === '1,1', 'rotate(90): top left should end up top right'); + for (const [x, y, color] of cw.pixels()) assert((color & 0xff) === 255, `rotate(90): hole at ${x},${y}`); } // free rotation keeps the edges { - const image = new Image(4, 4).fill(0xff0000ff).rotate(0.001, false); - for (const [x, y, color] of image.iterateWithColors()) assert((color & 0xff) > 250, `rotate: edge pixel ${x},${y} lost`); + const image = new Image(4, 4).fill(0xff0000ff).rotate(0.001, {expand: false}); + for (const [x, y, color] of image.pixels()) assert((color & 0xff) > 250, `rotate: edge pixel ${x},${y} lost`); } // compositing respects the destination alpha { - const image = new Image(1, 1).composite(new Image(1, 1).fill(Image.rgbaToColor(255, 255, 255, 128))); + const image = new Image(1, 1).composite(new Image(1, 1).fill(Colors.fromRGBA(255, 255, 255, 128))); assert(rgba(image, 0, 0).join() === '255,255,255,128', 'composite: semi-transparent white onto transparent turned ' + rgba(image, 0, 0)); - const blend = new Image(1, 1).fill(Image.rgbaToColor(255, 0, 0, 128)).composite(new Image(1, 1).fill(Image.rgbaToColor(0, 0, 255, 128))); + const blend = new Image(1, 1).fill(Colors.fromRGBA(255, 0, 0, 128)).composite(new Image(1, 1).fill(Colors.fromRGBA(0, 0, 255, 128))); assert(rgba(blend, 0, 0)[3] === 192, 'composite: alpha should combine to 0.75'); } - // cropCircle(max) - { - const count = image => [...image.iterateWithColors()].filter(([, , c]) => c & 0xff).length; - assert(count(new Image(8, 2).fill(0xffffffff).cropCircle(true)) > count(new Image(8, 2).fill(0xffffffff).cropCircle(false)), 'cropCircle: max has no effect'); - } - // crop is clipped to the image { - const image = new Image(10, 2).fill((x, y) => Image.rgbaToColor(x + 1, y + 1, 0, 255)).crop(5, 0, 10, 2); + const image = new Image(10, 2).fill((x, y) => Colors.fromRGBA(x + 1, y + 1, 0, 255)).crop(5, 0, 10, 2); assert(image.width === 5 && image.height === 2, 'crop: region not clipped'); assert(rgba(image, 0, 1).slice(0, 2).join() === '6,2', 'crop: wrong pixels'); @@ -62,16 +56,9 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert(threw, 'crop: region outside the image should throw'); } - // drawBox outside of the image - { - new Image(10, 10).drawBox(0, 20, 5, 5, 0xffffffff).drawBox(20, 0, 5, 5, 0xffffffff).drawBox(-10, -10, 5, 5, 0xffffffff); - const image = new Image(4, 4).drawBox(-2, -2, 3, 3, 0xffffffff); - assert(image.getPixelAt(0, 0) === 0xffffffff && image.getPixelAt(1, 1) === 0, 'drawBox: clipping failed'); - } - // averageColor is weighted by alpha { - assert(new Image(2, 2).fill(Image.rgbaToColor(255, 0, 0, 128)).averageColor() === 0xff0000ff, 'averageColor: semi-transparent red'); + assert(new Image(2, 2).fill(Colors.fromRGBA(255, 0, 0, 128)).averageColor() === 0xff0000ff, 'averageColor: semi-transparent red'); const image = new Image(2, 1); image.setPixelAt(0, 0, 0x00ff00ff); image.setPixelAt(1, 0, 0xff000000); @@ -79,17 +66,11 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); } // gradients return unsigned colors like rgbaToColor - assert(Image.gradient({0: 0xff0000ff, 1: 0xff0000ff})(0.5) === 0xff0000ff, 'gradient: signed color'); - - // PNG metadata as the only argument - { - const encoded = await new Image(1, 1).encode({title: 'regression'}); - assert(Buffer.from(encoded).includes(Buffer.from('regression')), 'encode(metadata): title missing'); - } + assert(Colors.gradient({0: 0xff0000ff, 1: 0xff0000ff})(0.5) === 0xff0000ff, 'gradient: signed color'); // frames keep their metadata { - const frame = new Frame(10, 10, 500, 2, 4, Frame.DISPOSAL_BACKGROUND); + const frame = new Frame(new Image(10, 10), {duration: 500, xOffset: 2, yOffset: 4, disposalMode: 'background'}); const clone = frame.clone(); assert(clone instanceof Frame && clone.duration === 500 && clone.xOffset === 2 && clone.disposalMode === 'background', 'Frame.clone lost metadata'); @@ -97,20 +78,20 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert(resized === frame && frame.duration === 500 && frame.xOffset === 1 && frame.yOffset === 2, 'Frame.resize lost metadata'); } - // GIFs behave like arrays + // the frames are the array: the animation's frames have the array methods, the animation itself none { - const gif = new GIF([new Frame(4, 4), new Frame(4, 4), new Frame(4, 4)], 2); - assert(gif.slice(1).length === 2 && gif.slice(1).loopCount === 2, 'GIF.slice(start)'); - assert(gif.slice(-1).length === 1, 'GIF.slice(negative)'); - assert(gif.map(frame => frame.width).join() === '4,4,4', 'GIF.map'); - assert(gif.filter(() => true).length === 3, 'GIF.filter'); + const gif = new Animation([new Frame(new Image(4, 4)), new Frame(new Image(4, 4)), new Frame(new Image(4, 4))], {loopCount: 2}); + assert(new Animation(gif.frames.slice(1), {loopCount: gif.loopCount}).length === 2, 'frames.slice(start)'); + assert(gif.frames.slice(-1).length === 1, 'frames.slice(negative)'); + assert(gif.frames.map(frame => frame.width).join() === '4,4,4', 'frames.map'); + assert(gif.frames.filter(() => true).length === 3, 'frames.filter'); } // resizing GIFs scales partial frames proportionally { - const gif = new GIF([new Frame(10, 10), new Frame(4, 4, 100, 6, 6)]).resize(5, 5); + const gif = new Animation([new Frame(new Image(10, 10)), new Frame(new Image(4, 4), {duration: 100, xOffset: 6, yOffset: 6})]).resize(5, 5); assert(gif.width === 5 && gif.height === 5, `GIF.resize: canvas is ${gif.width}x${gif.height}`); - assert(gif[1].width === 2 && gif[1].xOffset === 3, 'GIF.resize: partial frame not scaled'); + assert(gif.frames[1].width === 2 && gif.frames[1].xOffset === 3, 'GIF.resize: partial frame not scaled'); } // coordinates are 0-based everywhere @@ -118,7 +99,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const image = new Image(3, 3); image.setPixelAt(0, 0, 0xff0000ff); assert(image.bitmap[0] === 0xff, 'setPixelAt(0, 0) should set the first pixel'); - assert([...image][0].join() === '0,0' && [...image].pop().join() === '2,2', 'iterator should be 0-based'); + assert([...image.pixels()][0].slice(0, 2).join() === '0,0' && [...image.pixels()].pop().slice(0, 2).join() === '2,2', 'pixels() should be 0-based'); let threw = false; try { image.getPixelAt(3, 0); } catch { threw = true; } @@ -128,13 +109,10 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); new Image(2, 1).fill((x, y) => (filled.push([x, y]), 0)); assert(filled.join(';') === '0,0;1,0', 'fill callback should be 0-based'); - const box = new Image(3, 3).drawBox(1, 1, 1, 1, 0xffffffff); - assert(box.getPixelAt(1, 1) === 0xffffffff && box.getPixelAt(0, 0) === 0, 'drawBox should be 0-based'); - - const target = new Image(3, 3).composite(new Image(1, 1).fill(0xffffffff), 1, 1); + const target = new Image(3, 3).composite(new Image(1, 1).fill(0xffffffff), {x: 1, y: 1}); assert(target.getPixelAt(1, 1) === 0xffffffff, 'composite and getPixelAt should agree'); - const corners = new Image(8, 8).fill(0xffffffff).roundCorners(3); + const corners = new Image(8, 8).fill(0xffffffff).roundCorners({radius: 3}); const alpha = (x, y) => corners.getPixelAt(x, y) & 0xff; for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) @@ -142,17 +120,20 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert(alpha(0, 0) < 64 && alpha(3, 0) === 255 && alpha(0, 1) > 0 && alpha(0, 1) < 255, 'roundCorners should antialias the arc'); } - // text layout accepts the pre 3.0 (swapped) option names + // text alignments only take the values of their own axis { - const legacy = new TextLayout({verticalAlign: 'center', horizontalAlign: 'bottom'}); - assert(legacy.horizontalAlign === 'center' && legacy.verticalAlign === 'bottom', 'TextLayout: legacy names'); - const current = new TextLayout({horizontalAlign: 'right', verticalAlign: 'middle'}); - assert(current.horizontalAlign === 'right' && current.verticalAlign === 'middle', 'TextLayout: names'); + const font = require('fs').readFileSync('./tests/fonts/opensans bold.ttf'); + await Image.renderText('a', {font, size: 12, horizontalAlign: 'right', verticalAlign: 'middle'}); + for (const options of [{verticalAlign: 'center', horizontalAlign: 'bottom'}, {horizontalAlign: 'top'}, {verticalAlign: 'left'}, {horizontalAlign: 'middle'}]) { + let error = null; + try { await Image.renderText('a', {font, size: 12, ...options}); } catch (e) { error = e; } + assert(error instanceof TypeError, `layout ${JSON.stringify(options)} should throw a TypeError, got ${error}`); + } } // HSL conversions round instead of truncating, so identity operations keep the image { - const image = new Image(64, 64).fill((x, y) => Image.rgbaToColor(x * 4, y * 4, (x * y) & 255, 255 - x)); + const image = new Image(64, 64).fill((x, y) => Colors.fromRGBA(x * 4, y * 4, (x * y) & 255, 255 - x)); const original = Buffer.from(image.bitmap); assert(Buffer.from(image.clone().lightness(1).bitmap).equals(original), 'lightness(1) should not change the image'); assert(Buffer.from(image.clone().saturation(1).bitmap).equals(original), 'saturation(1) should not change the image'); @@ -161,25 +142,27 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); // negative hues wrap around { - const color = Image.rgbToColor(255, 40, 0); + const color = Colors.fromRGB(255, 40, 0); const shifted = new Image(1, 1).fill(color).hueShift(-300).getPixelAt(0, 0); - assert(shifted === new Image(1, 1).fill(color).hueShift(60).getPixelAt(0, 0), 'hueShift(-300) should equal hueShift(60), got ' + Image.colorToRGBA(shifted)); + assert(shifted === new Image(1, 1).fill(color).hueShift(60).getPixelAt(0, 0), 'hueShift(-300) should equal hueShift(60), got ' + Colors.toRGBA(shifted)); } // compositing rounds to the nearest value instead of up { - const image = new Image(1, 1).fill(Image.rgbaToColor(0, 0, 0, 255)).composite(new Image(1, 1).fill(Image.rgbaToColor(100, 100, 100, 51))); + const image = new Image(1, 1).fill(Colors.fromRGBA(0, 0, 0, 255)).composite(new Image(1, 1).fill(Colors.fromRGBA(100, 100, 100, 51))); assert(rgba(image, 0, 0)[0] === 20, 'composite: 100 at 20% over black should be 20, got ' + rgba(image, 0, 0)[0]); } - // cover and contain hit the requested dimensions despite floating point scale factors + // cover and contain fit modes hit the requested dimensions despite floating point scale factors { for (let width = 1; width < 200; width++) { for (const target of [7, 50, 99, 128]) { - const covered = new Image(width, 61).cover(target, 33); + const covered = new Image(width, 61).resize({width: target, height: 33, fit: 'cover'}); assert(covered.width === target && covered.height === 33, `cover(${target}, 33) of ${width}x61 returned ${covered}`); - const contained = new Image(width, 61).contain(target, 33); - assert((contained.width === target || contained.height === 33) && contained.width <= target && contained.height <= 33, `contain(${target}, 33) of ${width}x61 returned ${contained}`); + const contained = new Image(width, 61).resize({width: target, height: 33, fit: 'contain'}); + assert(contained.width === target && contained.height === 33, `contain(${target}, 33) of ${width}x61 returned ${contained}`); + const inside = new Image(width, 61).resize({width: target, height: 33, fit: 'inside'}); + assert((inside.width === target || inside.height === 33) && inside.width <= target && inside.height <= 33, `resize({ width: ${target}, height: 33, fit: 'inside' }) of ${width}x61 returned ${inside}`); } } } @@ -235,15 +218,15 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const svg = `${'&e4;'.repeat(50)}`; let error = null; try { await Image.renderSVG(svg); } catch (err) { error = err; } - assert(error && /entity expansion/.test(error.message), 'SVG: entity expansion should be limited'); + assert(error instanceof LimitError, `SVG: entity expansion should be limited with a LimitError (${error})`); } // resizing filters average instead of skipping pixels, in premultiplied alpha { const checker = new Image(64, 64).fill((x, y) => (x + y) & 1 ? 0xffffffff : 0x000000ff); - for (const mode of [Image.RESIZE_BILINEAR, Image.RESIZE_BICUBIC, Image.RESIZE_AREA]) { - const small = checker.clone().resize(8, 8, mode); - for (const [x, y, color] of small.iterateWithColors()) + for (const mode of ['bilinear', 'bicubic', 'area']) { + const small = checker.clone().resize(8, 8, {mode}); + for (const [x, y, color] of small.pixels()) assert(Math.abs((color >>> 24) - 128) <= 2, `${mode}: checkerboard should average to grey at ${x},${y}, got ${color >>> 24}`); } @@ -251,32 +234,15 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const half = new Image(4, 1).fill((x) => x < 2 ? 0xff000000 : 0x0000ffff).resize(2, 1); assert(rgba(half, 0, 0).slice(0, 3).join() === '0,0,255', 'resize: transparent pixels bled into the result: ' + rgba(half, 0, 0)); - const nearest = new Image(4, 1).fill((x) => Image.rgbToColor(x, 0, 0)).resize(2, 1, Image.RESIZE_NEAREST_NEIGHBOR); + const nearest = new Image(4, 1).fill((x) => Colors.fromRGB(x, 0, 0)).resize(2, 1, {mode: 'nearest-neighbor'}); assert(rgba(nearest, 0, 0)[0] === 1 && rgba(nearest, 1, 0)[0] === 3, 'nearest neighbor should sample pixel centers'); - let threw = false; - try { checker.clone().resize(8, 8, 'RESIZE_FOO'); } catch { threw = true; } - assert(threw, 'resize should reject unknown modes'); - } - - // circles are antialiased and symmetric around the pixel center - { - const circle = new Image(9, 9).drawCircle(4, 4, 3.5, 0xffffffff); - const alpha = (x, y) => circle.getPixelAt(x, y) & 0xff; - for (let y = 0; y < 9; y++) - for (let x = 0; x < 9; x++) - assert(alpha(x, y) === alpha(8 - x, y) && alpha(x, y) === alpha(y, x), `drawCircle should be symmetric (${x}, ${y})`); - assert(alpha(4, 4) === 255 && alpha(0, 0) === 0 && alpha(1, 2) > 0 && alpha(1, 2) < 255, 'drawCircle should antialias its edge'); - - const cropped = new Image(6, 6).fill(0xffffffff).cropCircle(); - const a = (x, y) => cropped.getPixelAt(x, y) & 0xff; - for (let y = 0; y < 6; y++) - for (let x = 0; x < 6; x++) - assert(a(x, y) === a(5 - x, y) && a(x, y) === a(x, 5 - y), `cropCircle should be symmetric (${x}, ${y})`); - - const feathered = new Image(41, 41).fill(0xffffffff).cropCircle(false, 0.5); - const f = x => feathered.getPixelAt(x, 20) & 0xff; - assert(f(20) === 255 && f(12) === 255 && f(5) > 0 && f(5) < 255 && f(0) < 32, 'cropCircle feathering should only soften the outer part'); + // (upper case names are unknown modes too) + for (const unknown of ['RESIZE_FOO', 'RESIZE_BILINEAR', 'RESIZE_AREA']) { + let threw = false; + try { checker.clone().resize(8, 8, {mode: unknown}); } catch { threw = true; } + assert(threw, `resize should reject unknown mode ${unknown}`); + } } // dominant colors are exact and dark saturated colors aren't treated as black @@ -284,57 +250,59 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert(new Image(4, 4).fill(0xff0000ff).dominantColor() === 0xff0000ff, 'dominantColor of pure red'); assert(new Image(4, 4).fill(0x336699ff).dominantColor() === 0x336699ff, 'dominantColor of #336699'); - const navy = new Image(10, 10).fill(0x00006eff).drawBox(0, 0, 2, 2, 0xc8c800ff); + const navy = new Image(10, 10).fill(0x00006eff).composite(new Image(2, 2).fill(0xc8c800ff), {x: 0, y: 0}); assert(navy.dominantColor() === 0x00006eff, 'dominantColor: navy should beat a small yellow area'); assert(new Image(4, 4).fill(0x000000ff).dominantColor() === 0x000000ff, 'dominantColor: all black falls back to black'); assert(new Image(4, 4).dominantColor() === 0x000000ff, 'dominantColor: transparent image'); + // the fullest bin of 16 levels per channel, averaged over its pixels: a color the image has, not the mix of two hues + { + const two = new Image(10, 1).fill(x => x < 6 ? 0xff0000ff : 0x0000ffff); + assert(two.dominantColor() === 0xff0000ff, 'dominantColor: the larger of two hues, not their mix'); + const close = new Image(10, 1).fill(x => [0x40a0c0ff, 0x42a2c2ff, 0x44a4c4ff][x % 3]); + assert(close.dominantColor() === 0x42a2c2ff, 'dominantColor: the average of the pixels in the winning bin'); + // (pixels that are less than half opaque don't count) + const faint = new Image(10, 1).fill(x => x < 8 ? 0x00ff0040 : 0xff0000ff); + assert(faint.dominantColor() === 0xff0000ff, 'dominantColor: faint pixels are ignored'); + } } // PNGs use the smallest lossless color type { const cases = { palette: [new Image(20, 10).fill((x) => x & 1 ? 0xff000080 : 0x00ff00ff), 3], - greys: [new Image(300, 1).fill((x) => Image.rgbToColor(x & 255, x & 255, x & 255)), 3], - greyAlpha: [new Image(300, 3).fill((x, y) => Image.rgbaToColor(x & 255, x & 255, x & 255, 100 + y)), 4], - rgb: [new Image(300, 2).fill((x, y) => Image.rgbToColor(x & 255, x >> 8, y)), 2], - rgba: [new Image(300, 2).fill((x, y) => Image.rgbaToColor(x & 255, x >> 8, y, 200)), 6] + greys: [new Image(300, 1).fill((x) => Colors.fromRGB(x & 255, x & 255, x & 255)), 3], + greyAlpha: [new Image(300, 3).fill((x, y) => Colors.fromRGBA(x & 255, x & 255, x & 255, 100 + y)), 4], + rgb: [new Image(300, 2).fill((x, y) => Colors.fromRGB(x & 255, x >> 8, y)), 2], + rgba: [new Image(300, 2).fill((x, y) => Colors.fromRGBA(x & 255, x >> 8, y, 200)), 6] }; for (const [name, [image, type]] of Object.entries(cases)) { - const encoded = await image.encode(); + const encoded = await image.encodePNG(); const decoded = await Image.decode(encoded); assert(Buffer.from(decoded.bitmap).equals(Buffer.from(image.bitmap)), `PNG ${name}: roundtrip failed`); assert(encoded[25] === type, `PNG ${name}: expected color type ${type}, got ${encoded[25]}`); } // truecolor rows are filtered, which makes smooth gradients tiny - const gradient = new Image(512, 512).fill((x, y) => Image.rgbToColor(x / 2, y / 2, (x + y) / 4)); - const size = (await gradient.encode()).length; + const gradient = new Image(512, 512).fill((x, y) => Colors.fromRGB(Math.min(x / 2, 255), Math.min(y / 2, 255), Math.min((x + y) / 4, 255))); + const size = (await gradient.encodePNG()).length; assert(size < 20000, `PNG: gradient should compress well with row filters, got ${size} bytes`); - assert(Buffer.from((await Image.decode(await gradient.encode(9))).bitmap).equals(Buffer.from(gradient.bitmap)), 'PNG: filtered roundtrip failed'); + assert(Buffer.from((await Image.decode(await gradient.encodePNG({compression: 9}))).bitmap).equals(Buffer.from(gradient.bitmap)), 'PNG: filtered roundtrip failed'); } // invertValue inverts HSV value and invertLightness HSL lightness { - const value = new Image(3, 1).fill(x => [Image.rgbaToColor(200, 100, 50, 128), Image.rgbToColor(0, 0, 0), Image.rgbToColor(255, 128, 0)][x]).invertValue(); + const value = new Image(3, 1).fill(x => [Colors.fromRGBA(200, 100, 50, 128), Colors.fromRGB(0, 0, 0), Colors.fromRGB(255, 128, 0)][x]).invertValue(); assert([0, 1, 2].map(x => rgba(value, x, 0).join(' ')).join() === '55 28 14 128,255 255 255 255,0 0 0 255', 'invertValue should invert HSV value, got ' + [0, 1, 2].map(x => rgba(value, x, 0))); - const lightness = new Image(1, 1).fill(Image.rgbToColor(200, 100, 50)).invertLightness(); + const lightness = new Image(1, 1).fill(Colors.fromRGB(200, 100, 50)).invertLightness(); assert(rgba(lightness, 0, 0).join() === '205,105,55,255', 'invertLightness should invert HSL lightness, got ' + rgba(lightness, 0, 0)); } - // encodePNG is an alias of encode - { - const image = new Image(3, 3).fill((x, y) => Image.rgbaToColor(x * 80, y * 80, 7, 200)); - const meta = {creationTime: 0, software: 'test'}; - assert(Buffer.from(await image.encodePNG(meta)).equals(Buffer.from(await image.encode(meta))), 'encodePNG(meta) should equal encode(meta)'); - assert(Buffer.from(await image.encodePNG(0, meta)).equals(Buffer.from(await image.encode(0, meta))), 'encodePNG(level, meta) should equal encode(level, meta)'); - } - // gif frame durations are rounded to centiseconds { // (different frames: identical ones are merged) - const gif = new GIF([new Frame(2, 2, 16), new Frame(2, 2, 14).fill(0xff0000ff)]); - const decoded = await GIF.decode(await gif.encode()); - assert(decoded[0].duration === 20 && decoded[1].duration === 10, `gif durations should round, got ${decoded[0].duration}, ${decoded[1].duration}`); + const gif = new Animation([new Frame(new Image(2, 2), {duration: 16}), new Frame(new Image(2, 2).fill(0xff0000ff), {duration: 14})]); + const decoded = await Animation.decode(await gif.encodeGIF()); + assert(decoded.frames[0].duration === 20 && decoded.frames[1].duration === 10, `gif durations should round, got ${decoded.frames[0].duration}, ${decoded.frames[1].duration}`); } // jpegs are rotated as their exif orientation says (fixtures written by Pillow, checked against ImageOps.exif_transpose) @@ -343,7 +311,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const read = n => fs.readFileSync(`./tests/jpegs/exif-orientation-${n}.jpg`); const raw = await Image.decode(read(3), {applyOrientation: false}); assert(raw.width === 48 && raw.height === 32, 'decode: applyOrientation: false should keep the stored pixels'); - for (const [n, angle] of [[3, 180], [6, 270], [8, 90]]) { + for (const [n, angle] of [[3, 180], [6, 90], [8, 270]]) { const oriented = await Image.decode(read(n)); const expected = (await Image.decode(read(n), {applyOrientation: false})).rotate(angle); assert(oriented.width === expected.width && Buffer.from(oriented.bitmap).equals(Buffer.from(expected.bitmap)), `decode: orientation ${n} not applied`); @@ -362,124 +330,99 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert(threw, 'bitmap setter should reject a wrong size'); } - // color components are rounded and clamped instead of wrapping + // color components are rounded; values outside of their range throw instead of wrapping (or being clamped, as in 3.x) { - assert(Image.rgbaToColor(256, -1, 127.6, 300) === 0xff0080ff, 'rgbaToColor should clamp and round, got ' + Image.rgbaToColor(256, -1, 127.6, 300).toString(16)); - let threw = false; - try { Image.rgbToColor(NaN, 0, 0); } catch (e) { threw = e instanceof RangeError; } - assert(threw, 'rgbToColor(NaN) should throw a RangeError'); + assert(Colors.fromRGBA(255.4, 0, 127.6, 0.4) === 0xff008000, 'Colors.fromRGBA should round, got ' + Colors.fromRGBA(255.4, 0, 127.6, 0.4).toString(16)); + const rejects = (name, fn) => { + let error; + try { fn(); } catch (e) { error = e; } + assert(error instanceof RangeError, `${name} should throw a RangeError, got ${error}`); + }; + for (const [name, rgba] of Object.entries({red: [256, 0, 0, 0], green: [0, -1, 0, 0], blue: [0, 0, 255.5, 0], alpha: [0, 0, 0, 300], NaN: [NaN, 0, 0, 0]})) rejects(`fromRGBA(${name})`, () => Colors.fromRGBA(...rgba)); + rejects('fromRGB(NaN)', () => Colors.fromRGB(NaN, 0, 0)); + rejects('fromHSLA(saturation 2)', () => Colors.fromHSLA(0, 2, 0.5, 1)); + rejects('fromHSLA(lightness -1)', () => Colors.fromHSLA(0, 1, -1, 1)); + rejects('fromHSLA(alpha 255)', () => Colors.fromHSLA(0, 1, 0.5, 255)); } // disposal modes read back as the names they are set with { - const frame = new Frame(1, 1, 100, 0, 0, Frame.DISPOSAL_PREVIOUS); + const frame = new Frame(new Image(1, 1), {duration: 100, xOffset: 0, yOffset: 0, disposalMode: 'previous'}); assert(frame.disposalMode === 'previous', 'disposalMode should be a name, got ' + frame.disposalMode); - frame.disposalMode = 0; - assert(frame.disposalMode === Frame.DISPOSAL_ANY, 'disposalMode set by id should read back as name'); - const decoded = await GIF.decode(await new GIF([new Frame(2, 2, 100, 0, 0, 'background'), new Frame(2, 2).fill(0xff0000ff)]).encode()); + // disposal modes are names: the numeric ids are a TypeError + let threw = false; + try { frame.disposalMode = 0; } catch (e) { threw = e instanceof TypeError; } + assert(threw && frame.disposalMode === 'previous', 'disposalMode should only take names'); + const decoded = await Animation.decode(await new Animation([new Frame(new Image(2, 2), {duration: 100, xOffset: 0, yOffset: 0, disposalMode: 'background'}), new Frame(new Image(2, 2).fill(0xff0000ff))]).encodeGIF()); assert(decoded.length === 2, 'gif with disposal modes should roundtrip'); } - // the constant classes hold the new names, the deprecated Image/Frame constants (removed in 4.0) keep their values, - // and both work everywhere with the same results + // SVG sizes and resize modes { - const pairs = [ - [Image.RESIZE_NEAREST_NEIGHBOR, 'RESIZE_NEAREST_NEIGHBOR', ResizeModes.NEAREST_NEIGHBOR, 'nearest-neighbor'], - [Image.RESIZE_BILINEAR, 'RESIZE_BILINEAR', ResizeModes.BILINEAR, 'bilinear'], - [Image.RESIZE_BICUBIC, 'RESIZE_BICUBIC', ResizeModes.BICUBIC, 'bicubic'], - [Image.RESIZE_AREA, 'RESIZE_AREA', ResizeModes.AREA, 'area'], - [Image.RESIZE_AUTO, -1, ResizeModes.AUTO, -1], - [Frame.RESIZE_AUTO, -1, ResizeModes.AUTO, -1], - [Image.SVG_MODE_SCALE, 1, SVGScaleModes.SCALE, 'scale'], - [Image.SVG_MODE_WIDTH, 2, SVGScaleModes.WIDTH, 'width'], - [Image.SVG_MODE_HEIGHT, 3, SVGScaleModes.HEIGHT, 'height'], - [Frame.DISPOSAL_ANY, 'any', FrameDisposalModes.ANY, 'any'], - [Frame.DISPOSAL_KEEP, 'keep', FrameDisposalModes.KEEP, 'keep'], - [Frame.DISPOSAL_PREVIOUS, 'previous', FrameDisposalModes.PREVIOUS, 'previous'], - [Frame.DISPOSAL_BACKGROUND, 'background', FrameDisposalModes.BACKGROUND, 'background'] - ]; - for (const [old, oldValue, now, nowValue] of pairs) - assert(old === oldValue && now === nowValue, `constants: ${old} should be ${oldValue}, ${now} should be ${nowValue}`); const svg = ''; - for (const [old, now, size, width, height] of [[Image.SVG_MODE_SCALE, SVGScaleModes.SCALE, 2, 20, 10], [Image.SVG_MODE_WIDTH, SVGScaleModes.WIDTH, 20, 20, 10], [Image.SVG_MODE_HEIGHT, SVGScaleModes.HEIGHT, 20, 40, 20]]) { - const a = await Image.renderSVG(svg, size, old), b = await Image.renderSVG(svg, {size, mode: now}); - assert(a.width === width && a.height === height, `renderSVG mode ${now}: ${a.width}x${a.height}`); - assert(b.width === width && b.height === height && Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap)), `renderSVG mode ${old} vs ${now}`); + for (const [size, width, height] of [[{scale: 2}, 20, 10], [{width: 20}, 20, 10], [{height: 20}, 40, 20], [{}, 10, 5]]) { + const rendered = await Image.renderSVG(svg, size); + assert(rendered.width === width && rendered.height === height, `renderSVG ${JSON.stringify(size)}: ${rendered.width}x${rendered.height}`); } - const photo = new Image(9, 7).fill((x, y) => ColorHelpers.fromRGBA(x * 28, y * 36, (x ^ y) * 16, 255 - x * 10)); - for (const [old, now] of pairs.slice(0, 4)) - for (const method of ['resize', 'contain', 'fit', 'cover']) - assert(Buffer.from(photo.clone()[method](5, 4, old).bitmap).equals(Buffer.from(photo.clone()[method](5, 4, {mode: now}).bitmap)), `${method} ${old} vs ${now}`); - assert(new Image(8, 4).resize(4, Image.RESIZE_AUTO, Image.RESIZE_AREA).height === 2, 'resize with deprecated constants'); + let twoSizes = null; + try { await Image.renderSVG(svg, {width: 20, height: 20}); } catch (e) { twoSizes = e; } + assert(twoSizes instanceof TypeError, 'renderSVG: width and height together should throw a TypeError'); + assert(new Image(8, 4).resize({width: 4, mode: 'area'}).height === 2, 'resize({width}) with a mode keeps the aspect ratio'); + const photo = new Image(9, 7).fill((x, y) => Colors.fromRGBA(x * 28, y * 36, (x ^ y) * 16, 255 - x * 10)); let threw = false; - try { photo.clone().resize(4, 4, 'Area'); } catch { threw = true; } + try { photo.clone().resize(4, 4, {mode: 'Area'}); } catch { threw = true; } assert(threw, 'resize modes are case sensitive'); } - // resize({width}) / resize({height}) keep the aspect ratio like ResizeModes.AUTO (deprecated, removed in 4.0) + // resize({width}) / resize({height}) keep the aspect ratio { const {Animation} = require('..'); - const photo = new Image(12, 8).fill((x, y) => ColorHelpers.fromRGBA(x * 20, y * 30, 90, 255)); + const photo = new Image(12, 8).fill((x, y) => Colors.fromRGBA(x * 20, y * 30, 90, 255)); const same = (a, b) => a.width === b.width && a.height === b.height && Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap)); - assert(same(photo.clone().resize({width: 6}), photo.clone().resize(6, Image.RESIZE_AUTO)), 'resize({width})'); + assert(same(photo.clone().resize({width: 6}), photo.clone().resize(6, 4)), 'resize({width})'); assert(photo.clone().resize({width: 6}).height === 4, 'resize({width}) keeps the aspect ratio'); - assert(same(photo.clone().resize({height: 4, mode: 'bicubic'}), photo.clone().resize(ResizeModes.AUTO, 4, Image.RESIZE_BICUBIC)), 'resize({height, mode})'); - assert(same(photo.clone().resize({width: 5, height: 9, fast: false}), photo.clone().resize(5, 9, {fast: false})), 'resize({width, height, fast})'); + assert(same(photo.clone().resize({height: 4, mode: 'bicubic'}), photo.clone().resize(6, 4, {mode: 'bicubic'})), 'resize({height, mode})'); + assert(same(photo.clone().resize({width: 5, height: 9, mode: 'area'}), photo.clone().resize(5, 9, {mode: 'area'})), 'resize({width, height, mode})'); let threw = false; try { photo.clone().resize({}); } catch (e) { threw = e instanceof TypeError; } assert(threw, 'resize({}) throws'); - const frame = Frame.from(photo.clone(), 100, 4, 2); + const frame = new Frame(photo.clone(), {duration: 100, xOffset: 4, yOffset: 2}); frame.resize({width: 6}); assert(frame.width === 6 && frame.height === 4 && frame.xOffset === 2 && frame.yOffset === 1, `Frame.resize({width}): ${frame.width}x${frame.height}+${frame.xOffset}+${frame.yOffset}`); - const animation = new Animation([Frame.from(photo.clone(), 100), Frame.from(photo.clone().invert(), 100)]); - const other = new Animation([Frame.from(photo.clone(), 100), Frame.from(photo.clone().invert(), 100)]); + const animation = new Animation([new Frame(photo.clone(), {duration: 100}), new Frame(photo.clone().invert(), {duration: 100})]); + const other = new Animation([new Frame(photo.clone(), {duration: 100}), new Frame(photo.clone().invert(), {duration: 100})]); animation.resize({height: 4}); - other.resize(Image.RESIZE_AUTO, 4); - assert(animation.width === 6 && animation.height === 4 && [...animation].every((f, i) => same(f, other[i])), 'Animation.resize({height})'); + other.resize(6, 4); + assert(animation.width === 6 && animation.height === 4 && [...animation].every((f, i) => same(f.image, other.frames[i].image)), 'Animation.resize({height})'); } - // coordinates(), pixels(), the iterator and iterateWithColors() (all but pixels() deprecated, removed in 4.0) yield the same + // pixels() yields every pixel row by row { - const image = new Image(3, 2).fill((x, y) => ColorHelpers.fromRGBA(x * 50, y * 100, 7, 255)); - const coordinates = [...image.coordinates()], pixels = [...image.pixels()]; - assert(coordinates.length === 6 && pixels.length === 6, 'coordinates()/pixels() count'); - assert(JSON.stringify(coordinates) === JSON.stringify([...image]), 'coordinates() vs the iterator'); - assert(JSON.stringify(pixels) === JSON.stringify([...image.iterateWithColors()]), 'pixels() vs iterateWithColors()'); - assert(coordinates[4].join() === '1,1' && pixels[4][2] === ColorHelpers.fromRGBA(50, 100, 7, 255), 'coordinates() and pixels() are row by row'); + const image = new Image(3, 2).fill((x, y) => Colors.fromRGBA(x * 50, y * 100, 7, 255)); + const pixels = [...image.pixels()]; + assert(pixels.length === 6, 'pixels() count'); + assert(pixels.every(([x, y, color], i) => x === i % 3 && y === Math.floor(i / 3) && color === Colors.fromRGBA(x * 50, y * 100, 7, 255)), 'pixels() row by row'); + assert(pixels[4].slice(0, 2).join() === '1,1' && pixels[4][2] === Colors.fromRGBA(50, 100, 7, 255), 'pixels() is row by row'); } - // encodePNG() is the implementation, encode() (deprecated, removed in 4.0) an alias of it - await withFrozenTime(async () => { - const image = new Image(5, 4).fill((x, y) => ColorHelpers.fromRGBA(x * 40, y * 60, 9, 200)); - for (const args of [[], [9], [0, {title: 'x'}], [{compression: 1}], [{title: 'y'}]]) { - const a = await image.encodePNG(...args), b = await image.encode(...args); - assert(Buffer.from(a).equals(Buffer.from(b)), `encode(${JSON.stringify(args)}) vs encodePNG`); - } - }); - - // cropCircle({size}): 'contain' is the default, `max` (deprecated, removed in 4.0) maps to 'cover' + // cropCircle({fit}): 'contain' is the default { - const wide = new Image(40, 20).fill(ColorHelpers.fromRGBA(200, 100, 50, 255)); + const wide = new Image(40, 20).fill(Colors.fromRGBA(200, 100, 50, 255)); const same = (a, b) => Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap)); - assert(same(wide.clone().cropCircle(), wide.clone().cropCircle({size: 'contain'})), 'cropCircle() is contain'); - assert(same(wide.clone().cropCircle(false), wide.clone().cropCircle({size: 'contain'})), 'cropCircle(false)'); - assert(same(wide.clone().cropCircle({max: false}), wide.clone().cropCircle({size: 'contain'})), 'cropCircle({max: false})'); - assert(same(wide.clone().cropCircle(true), wide.clone().cropCircle({size: 'cover'})), 'cropCircle(true)'); - assert(same(wide.clone().cropCircle({max: true, feathering: .5}), wide.clone().cropCircle({size: 'cover', feathering: .5})), 'cropCircle({max: true, feathering})'); - assert(same(wide.clone().cropCircle({max: true, size: 'contain'}), wide.clone().cropCircle({size: 'contain'})), 'size wins over max'); - assert(!same(wide.clone().cropCircle({size: 'cover'}), wide.clone().cropCircle({size: 'contain'})), 'cover differs from contain'); - assert(wide.clone().cropCircle({size: 'contain'}).getPixelAt(20, 1) >>> 0 !== 0 && (wide.clone().cropCircle({size: 'contain'}).getPixelAt(1, 10) & 0xff) === 0, 'contain: the circle fits the height'); + assert(same(wide.clone().cropCircle(), wide.clone().cropCircle({fit: 'contain'})), 'cropCircle() is contain'); + assert(!same(wide.clone().cropCircle({fit: 'cover'}), wide.clone().cropCircle({fit: 'contain'})), 'cover differs from contain'); + assert(wide.clone().cropCircle({fit: 'contain'}).getPixelAt(20, 1) >>> 0 !== 0 && (wide.clone().cropCircle({fit: 'contain'}).getPixelAt(1, 10) & 0xff) === 0, 'contain: the circle fits the height'); let threw = false; - try { wide.clone().cropCircle({size: 'max'}); } catch (e) { threw = e instanceof TypeError; } - assert(threw, 'cropCircle({size}) validates'); + try { wide.clone().cropCircle({fit: 'max'}); } catch (e) { threw = e instanceof TypeError; } + assert(threw, 'cropCircle({fit}) validates'); } - // the encoders take the options of the encode functions (the *AnimationEncoderOptions types are deprecated aliases, removed in 4.0) + // the encoders take the options of the encode functions await withFrozenTime(async () => { const {Animation} = require('..'); - const frames = () => [Frame.from(new Image(6, 6).fill(0x336699ff), 100), Frame.from(new Image(6, 6).fill(0x996633ff), 100)]; + const frames = () => [new Frame(new Image(6, 6).fill(0x336699ff), {duration: 100}), new Frame(new Image(6, 6).fill(0x996633ff), {duration: 100})]; for (const [format, options] of [['GIF', {quality: 80, optimize: false}], ['APNG', {compression: 9}], ['WebP', {quality: 70, effort: 1}]]) { const animation = new Animation(frames(), {loopCount: 3}); const encoder = Animation[`${format.toLowerCase()}Encoder`](6, 6, {...options, loopCount: 3}); @@ -488,41 +431,16 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); } }); - // Infinity is a loop count for ever (like -1, which is removed in 4.0), the encoders take the options of the encode functions - await withFrozenTime(async () => { - const {Animation} = require('..'); - const still = new Image(6, 6).fill(0x336699ff); - const frames = () => [Frame.from(still.clone(), 100), Frame.from(still.clone().invert(), 100)]; - const forever = new Animation(frames(), {loopCount: Infinity}), minusOne = new Animation(frames(), {loopCount: -1}); - assert(forever.loopCount === Infinity && new Animation(frames(), Infinity).loopCount === Infinity, 'Animation keeps Infinity'); - for (const format of ['GIF', 'APNG', 'WebP']) { - const a = await forever[`encode${format}`](), b = await minusOne[`encode${format}`](); - assert(Buffer.from(a).equals(Buffer.from(b)), `${format}: Infinity vs -1`); - assert((await Animation.decode(a)).loopCount === -1, `${format}: decodes as -1 until 4.0`); - const encoder = Animation[`${format.toLowerCase()}Encoder`](6, 6, {loopCount: Infinity}); - for (const frame of frames()) await encoder.add(frame); - assert(Buffer.from(await encoder.finish()).equals(Buffer.from(a)), `${format}: encoder with Infinity`); - } - for (const loopCount of [1.5, -2, NaN]) { - let threw = false; - try { new Animation(frames(), {loopCount}); } catch (e) { threw = e instanceof RangeError || e instanceof TypeError; } - assert(threw, `loopCount ${loopCount} is rejected`); - threw = false; - try { Animation.gifEncoder(6, 6, {loopCount}); } catch (e) { threw = e instanceof RangeError; } - assert(threw, `encoder loopCount ${loopCount} is rejected`); - } - }); - // Animation.decode: orientation, tone mapping and gain maps like Image.decode { const {GainMap} = require('..'); const fs = require('fs'); const pixel = (image, x, y) => Array.from(image.bitmap.subarray((y * image.width + x) * 4, (y * image.width + x) * 4 + 4)); const tiff = orientation => Buffer.from([0x4d, 0x4d, 0, 42, 0, 0, 0, 8, 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1, 0, orientation, 0, 0, 0, 0, 0, 0, 0, 0]); - const source = () => [0, 1].map(i => Frame.from(new Image(3, 2).fill((x, y) => ColorHelpers.fromRGBA(x * 100, y * 100, i * 120, 255)), 100)); + const source = () => [0, 1].map(i => new Frame(new Image(3, 2).fill((x, y) => Colors.fromRGBA(x * 100, y * 100, i * 120, 255)), {duration: 100})); // APNG (eXIf) and animated WebP (EXIF): orientation 6 turns the top left into the top right - const png = Buffer.from(await new Animation(source(), 2).encodeAPNG({metadata: {software: ''}})); + const png = Buffer.from(await new Animation(source(), {loopCount: 2}).encodeAPNG({metadata: {software: ''}})); const chunk = (type, body) => { const out = Buffer.alloc(12 + body.length); out.writeUInt32BE(body.length); @@ -532,12 +450,10 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); return out; }; const withExif = Buffer.concat([png.subarray(0, png.length - 12), chunk('eXIf', tiff(6)), png.subarray(png.length - 12)]); - const webp = Buffer.from(await new Animation(source(), 2).encodeWebP({metadata: {software: ''}})); + const webp = Buffer.from(await new Animation(source(), {loopCount: 2}).encodeWebP({metadata: {software: ''}})); const exifChunk = Buffer.concat([Buffer.from('EXIF'), Buffer.from(new Uint8Array(new Uint32Array([tiff(6).length]).buffer)), tiff(6)]); - // (the encoder's own EXIF chunk, with the creation time, becomes one decoders skip) - const own = webp.indexOf('EXIF', 12, 'latin1'); - assert(own > 12, 'the animated WebP has an EXIF chunk of its own'); - webp.write('JUNK', own, 'latin1'); + // (without metadata to write, the encoder adds no EXIF chunk of its own) + assert(webp.indexOf('EXIF', 12, 'latin1') === -1, 'the animated WebP without metadata has an EXIF chunk'); const webpWithExif = Buffer.concat([webp, exifChunk]); webpWithExif.writeUInt32LE(webpWithExif.length - 8, 4); // (the VP8X flags: bit 3 is Exif) @@ -550,7 +466,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const oriented = await Animation.decode(data, options); assert(oriented.width === 2 && oriented.height === 3 && oriented.length === 2, `${name}: rotated (${JSON.stringify(options)})`); for (let i = 0; i < 2; i++) - assert(pixel(oriented[i], 1, 0).join() === pixel(stored[i], 0, 0).join() && pixel(oriented[i], 0, 2).join() === pixel(stored[i], 2, 1).join(), `${name}: frame ${i} not oriented like Image.decode`); + assert(pixel(oriented.frames[i].image, 1, 0).join() === pixel(stored.frames[i].image, 0, 0).join() && pixel(oriented.frames[i].image, 0, 2).join() === pixel(stored.frames[i].image, 2, 1).join(), `${name}: frame ${i} not oriented like Image.decode`); } } // (without an orientation tag nothing changes) @@ -575,16 +491,16 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); return out; }; const mapped = new Image(8, 8).fill(0x808080ff); - mapped.gainMap = new GainMap(new Image(4, 4).fill(0xc0c0c0ff), {gainMapMin: 0, gainMapMax: 2}); + mapped.gainMap = new GainMap(new Image(4, 4).fill(0xc0c0c0ff), {min: 0, max: 2}); const jhgm = boxes(Buffer.from(await mapped.encodeJXL())).find(b => b.type === 'jhgm').box; const codestream = fs.readFileSync('./tests/jxl/animation.jxl'); const container = Buffer.concat([box('JXL ', Buffer.from([0x0d, 0x0a, 0x87, 0x0a])), box('ftyp', Buffer.from('jxl \0\0\0\0jxl ', 'latin1')), jhgm, box('jxlc', codestream)]); const plain = await Animation.decode(container, {gainMap: false}); const withMap = await Animation.decode(container); assert(plain.length > 1 && withMap.length === plain.length, 'JPEG XL animation with a jhgm box decodes'); - assert(plain.every(f => f.gainMap === null) && (await Animation.decode(codestream)).every(f => f.gainMap === null), 'JPEG XL: gainMap false, or no jhgm box'); - assert(withMap.every(f => f.gainMap && f.gainMap.width === 4 && f.gainMap.gainMapMax[0] === 2), 'JPEG XL: every frame has the gain map'); - assert(withMap[0].gainMap !== withMap[1].gainMap && withMap.every((f, i) => Buffer.from(f.bitmap).equals(Buffer.from(plain[i].bitmap))), 'JPEG XL: the frames are the same with the map, with maps of their own'); + assert(plain.frames.every(f => f.image.gainMap === null) && (await Animation.decode(codestream)).frames.every(f => f.image.gainMap === null), 'JPEG XL: gainMap false, or no jhgm box'); + assert(withMap.frames.every(f => f.image.gainMap && f.image.gainMap.width === 4 && f.image.gainMap.max[0] === 2), 'JPEG XL: every frame has the gain map'); + assert(withMap.frames[0].image.gainMap !== withMap.frames[1].image.gainMap && withMap.frames.every((f, i) => Buffer.from(f.image.bitmap).equals(Buffer.from(plain.frames[i].image.bitmap))), 'JPEG XL: the frames are the same with the map, with maps of their own'); // toneMapping is checked let threw = false; @@ -593,24 +509,17 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert((await Animation.decode(codestream, {toneMapping: 'clamp'})).length === plain.length, 'Animation.decode with toneMapping clamp'); } - // trim, colorToAlpha and GainMap.encode take their values in options too (the positional color and quality are deprecated, removed in 4.0) + // trim and colorToAlpha take their color in the options too { const {GainMap} = require('..'); const bordered = () => new Image(6, 5).fill(0x102030ff).setPixelAt(2, 2, 0xffffffff).setPixelAt(3, 2, 0x00000000); const same = (a, b) => a.width === b.width && a.height === b.height && Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap)); - assert(same(bordered().trim({color: 0x102030ff}), bordered().trim(0x102030ff)), 'trim({color}) vs trim(color)'); - assert(same(bordered().trim({color: 0x102030ff, tolerance: 0.1}), bordered().trim(0x102030ff, {tolerance: 0.1})), 'trim({color, tolerance})'); - assert(same(bordered().trim({tolerance: 0.1}), bordered().trim(undefined, {tolerance: 0.1})), 'trim({tolerance}) keeps the top left color'); assert(same(bordered().trim(), bordered().trim(undefined)) && same(bordered().trim(), bordered().trim({})), 'trim() without arguments'); - const frame = () => Frame.from(bordered(), 100, 3, 4); - assert(same(frame().trim({color: 0x102030ff}), frame().trim(0x102030ff)) && frame().trim({color: 0x102030ff}).xOffset === 5, 'Frame.trim({color}) moves the offsets'); - assert(same(bordered().colorToAlpha({color: 0x102030ff}), bordered().colorToAlpha(0x102030ff)), 'colorToAlpha({color}) vs colorToAlpha(color)'); - assert(same(bordered().colorToAlpha({transparencyThreshold: 0.2}), bordered().colorToAlpha(undefined, {transparencyThreshold: 0.2})), 'colorToAlpha({transparencyThreshold})'); + const frame = () => new Frame(bordered(), {duration: 100, xOffset: 3, yOffset: 4}); + assert(frame().trim({color: 0x102030ff}).xOffset === 5, 'Frame.trim({color}) moves the offsets'); assert(same(bordered().colorToAlpha(), bordered().colorToAlpha(undefined)) && same(bordered().colorToAlpha(), bordered().colorToAlpha({})), 'colorToAlpha() without arguments'); - const map = new GainMap(new Image(4, 4).fill(0x808080ff), {gainMapMin: 0, gainMapMax: 2}); - const a = await map.encode({quality: 70}), b = await map.encode(70); - assert(Buffer.from(a).equals(Buffer.from(b)), 'GainMap.encode({quality}) vs encode(quality)'); - assert(Buffer.from(await map.encode()).equals(Buffer.from(await map.encode({}))), 'GainMap.encode() without arguments'); + const map = new GainMap(new Image(4, 4).fill(0x808080ff), {min: 0, max: 2}); + assert(Buffer.from(await map.encodeJPEG()).equals(Buffer.from(await map.encodeJPEG({}))), 'GainMap.encodeJPEG() without arguments'); } // gradients, recolor with an image, drop shadows / glows and outlines @@ -624,8 +533,8 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert(error instanceof type, `${message}: should throw a ${type.name}, got ${error}`); }; const stops = {0: 0xff0000ff, 0.5: 0x00ff00ff, 1: 0x0000ffff}; - const gradient = ColorHelpers.gradient(stops); - const rgba = color => ColorHelpers.toRGBA(color); + const gradient = Colors.gradient(stops); + const rgba = color => Colors.toRGBA(color); // linear gradients follow Colors.gradient along CSS' directions (0 up, 90 right, 180 down, 270 left) for (const [angle, at] of [[90, x => [x, 0, (x + 0.5) / 4]], [270, x => [x, 0, 1 - (x + 0.5) / 4]]]) { @@ -645,7 +554,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const diagonal = Image.linearGradient(8, 8, {stops: [0x000000ff, 0xffffffff], angle: 135}); assert(px(diagonal, 0, 0)[0] < 20 && px(diagonal, 7, 7)[0] > 235 && px(diagonal, 7, 0).join() === px(diagonal, 0, 7).join(), 'linearGradient at 135deg runs from corner to corner'); // (an array of colors is evenly spaced, one color is a plain fill, alpha is part of the color) - assert(px(Image.linearGradient(3, 1, {stops: [0xff0000ff, 0x00ff00ff, 0x0000ffff], angle: 90}), 1, 0).join() === rgba(ColorHelpers.gradient({0: 0xff0000ff, 0.5: 0x00ff00ff, 1: 0x0000ffff})(0.5)).join(), 'linearGradient with an array of colors'); + assert(px(Image.linearGradient(3, 1, {stops: [0xff0000ff, 0x00ff00ff, 0x0000ffff], angle: 90}), 1, 0).join() === rgba(Colors.gradient({0: 0xff0000ff, 0.5: 0x00ff00ff, 1: 0x0000ffff})(0.5)).join(), 'linearGradient with an array of colors'); assert(px(Image.linearGradient(3, 3, {stops: [0x336699ff]}), 2, 2).join() === '51,102,153,255', 'linearGradient with one color'); assert(px(Image.linearGradient(2, 1, {stops: [0xff000000, 0xff0000ff], angle: 90}), 0, 0)[3] < 100, 'linearGradient keeps alpha'); @@ -654,6 +563,11 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert(px(radial, 4, 4)[0] > 240 && px(radial, 0, 0)[0] < 40 && px(radial, 0, 8).join() === px(radial, 8, 0).join(), 'radialGradient from the center to the farthest corner'); const circle = Image.radialGradient(20, 20, {stops: [0xff0000ff, 0x0000ffff], x: 5.5, y: 5.5, radius: 4}); assert(px(circle, 5, 5)[0] > 240 && px(circle, 15, 15).join() === '0,0,255,255' && px(circle, 9, 5)[2] > 200, 'radialGradient with a center and a radius'); + // sizes with a fraction are truncated like Image's: the same gradient as the whole sizes + for (const [name, make] of [['linearGradient', (w, h) => Image.linearGradient(w, h, {stops, angle: 70})], ['radialGradient', (w, h) => Image.radialGradient(w, h, {stops})]]) { + const fractional = make(5.7, 3.2), whole = make(5, 3); + assert(fractional.width === 5 && fractional.height === 3 && Buffer.from(fractional.bitmap).equals(Buffer.from(whole.bitmap)), `${name} with fractional sizes`); + } for (const [name, call] of Object.entries({ 'no stops': () => Image.linearGradient(2, 2, {stops: []}), 'no stops (object)': () => Image.radialGradient(2, 2, {stops: {}}), @@ -672,7 +586,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); throws(() => shape.clone().recolor(new Image(3, 1)), RangeError, 'recolor(image) with another size'); assert(shape.clone().recolor(0x336699ff).bitmap[0] === 0x33, 'recolor(color) still works'); const mapped = new Image(8, 8).fill(0xffffffff); - mapped.gainMap = new GainMap(new Image(4, 4).fill(0x808080ff), {gainMapMin: 0, gainMapMax: 2}); + mapped.gainMap = new GainMap(new Image(4, 4).fill(0x808080ff), {min: 0, max: 2}); mapped.recolor(Image.linearGradient(8, 8, {stops: [0xff0000ff, 0x0000ffff], angle: 90})); assert(px(mapped, 0, 0)[0] > 200 && px(mapped, 7, 0)[2] > 200 && mapped.gainMap && mapped.gainMap.width === 4, 'recolor(image) keeps the gain map'); @@ -702,18 +616,11 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); throws(() => square().dropShadow({x: NaN}), RangeError, 'NaN offset'); const translucent = new Image(6, 6).fill(0xffffff80); const shadowed = translucent.clone().dropShadow({color: 0x000000ff}); - assert(px(shadowed, 2, 2).join() === px(translucent, 2, 2).join() || px(shadowed, 2, 2)[3] >= 128, 'dropShadow keeps translucent pixels over their shadow'); - - // frames stay in place: the offsets move with the growth, up and left only as far as they allow - const frame = Frame.from(square(), {duration: 40, xOffset: 2, yOffset: 5}).dropShadow({blur: 2}); - assert(frame.xOffset === 0 && frame.yOffset === 0 && frame.width === 10 + 2 + 6 && frame.height === 10 + 5 + 6 && frame.duration === 40, `Frame.dropShadow: ${frame.width}x${frame.height} at ${frame.xOffset},${frame.yOffset}`); - assert(px(frame, 2 + 4, 5 + 4).join() === '255,128,64,255', 'Frame.dropShadow: the pixels stay where they were on the animation canvas'); - const farFrame = Frame.from(square(), {xOffset: 20, yOffset: 20}).dropShadow({blur: 1}); - assert(farFrame.xOffset === 17 && farFrame.yOffset === 17, 'Frame.dropShadow with room moves the offsets by the growth'); + assert(px(shadowed, 2, 2)[3] >= 128, 'dropShadow keeps translucent pixels over their shadow'); // gain maps grow with the image const hdr = square(); - hdr.gainMap = new GainMap(new Image(5, 5).fill(0xc0c0c0ff), {gainMapMin: 0, gainMapMax: 2}); + hdr.gainMap = new GainMap(new Image(5, 5).fill(0xc0c0c0ff), {min: 0, max: 2}); const hdrShadow = hdr.clone().dropShadow({x: 5, y: 0, blur: 1}); assert(hdrShadow.gainMap && Math.abs(hdrShadow.gainMap.width / hdrShadow.width - 0.5) < 0.1 && Math.abs(hdrShadow.gainMap.height / hdrShadow.height - 0.5) < 0.1, 'dropShadow keeps the gain map at its scale'); @@ -726,29 +633,19 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const clipped = square().outline({width: 2, expand: false}); assert(clipped.width === 10 && px(clipped, 2, 4).join() === '0,0,0,255' && px(clipped, 4, 4).join() === '255,128,64,255', 'outline({expand: false}) keeps the size'); assert(square().outline({width: 0}).width === 10 && Buffer.from(square().outline({width: 0}).bitmap).equals(Buffer.from(square().bitmap)), 'outline({width: 0}) does nothing'); - assert(px(square().outline({width: 1, color: 0x00ff0080}), 2 + 2, 2 + 4).slice(3).join() === '128' || Math.abs(alphaAt(square().outline({width: 1, color: 0x00ff0080}), 3 - 1 + 1, 3 + 2 + 1) - 128) <= 1, 'outline with a translucent color'); + assert(Math.abs(alphaAt(square().outline({width: 1, color: 0x00ff0080}), 3 - 1 + 1, 3 + 2 + 1) - 128) <= 1, 'outline with a translucent color'); const holey = new Image(9, 9).fill((x, y) => x >= 2 && x < 7 && y >= 2 && y < 7 && !(x === 4 && y === 4) ? 0xffffffff : 0); assert(alphaAt(holey.clone().outline({width: 1, color: 0x000000ff}), 1 + 4, 1 + 4) === 255, 'outline fills small holes of the shape'); throws(() => square().outline({width: -1}), RangeError, 'negative outline width'); throws(() => square().outline({width: Infinity}), RangeError, 'infinite outline width'); - const outlinedFrame = Frame.from(square(), {xOffset: 1, yOffset: 4}).outline({width: 3}); - assert(outlinedFrame.xOffset === 0 && outlinedFrame.yOffset === 1 && outlinedFrame.width === 10 + 1 + 3 && outlinedFrame.height === 10 + 3 + 3, `Frame.outline: ${outlinedFrame.width}x${outlinedFrame.height} at ${outlinedFrame.xOffset},${outlinedFrame.yOffset}`); const glowOnText = new Image(12, 12).fill((x, y) => (x - 5.5) ** 2 + (y - 5.5) ** 2 < 16 ? 0xffffffff : 0).outline({width: 2, color: 0xfacc15ff}).dropShadow({blur: 1, y: 2}); assert(glowOnText.width > 16 && glowOnText.height > 18, 'outline and dropShadow chain'); } - // Colors: the color helpers, and the deprecated Image ones they replaced, give the same values + // Colors: the color helpers { - const { Colors } = require('..'); - assert(Colors.fromRGBA(10, 20, 30, 40) === Image.rgbaToColor(10, 20, 30, 40), 'Colors.fromRGBA'); - assert(Colors.fromRGB(1, 2, 3) === Image.rgbToColor(1, 2, 3), 'Colors.fromRGB'); - assert(Colors.fromHSLA(0.3, 0.5, 0.6, 0.7) === Image.hslaToColor(0.3, 0.5, 0.6, 0.7), 'Colors.fromHSLA'); - assert(Colors.fromHSL(0.9, 1, 0.25) === Image.hslToColor(0.9, 1, 0.25), 'Colors.fromHSL'); - assert(Colors.toRGBA(0x11223344).join() === Image.colorToRGBA(0x11223344).join(), 'Colors.toRGBA'); assert(Colors.toRGB(0x11223344).join() === '17,34,51', 'Colors.toRGB ignores alpha'); - assert(Colors.toHSLA(0xff0000ff).join() === Image.rgbaToHSLA(255, 0, 0, 255).join() && Colors.toHSLA(0xff0000ff)[0] === 0, 'Colors.toHSLA'); - const stops = {0: 0xff0000ff, 0.5: 0x00ff00ff, 1: 0x0000ffff}; - assert(Colors.gradient(stops)(0.25) === Image.gradient(stops)(0.25) && Colors.gradient(stops)(0.75) === Image.gradient(stops)(0.75), 'Colors.gradient'); + assert(Colors.toHSLA(0xff0000ff)[0] === 0, 'Colors.toHSLA'); // HSLA round trip: each channel comes back within one step const rgba = Colors.toRGBA(Colors.fromRGBA(200, 100, 50, 255)), [h, s2, l, a2] = Colors.toHSLA(Colors.fromRGBA(200, 100, 50, 255)); const back = Colors.toRGBA(Colors.fromHSLA(h, s2, l, a2)); @@ -769,25 +666,26 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); // options objects as alternatives to positional arguments { const base = new Image(20, 20).fill(0xff0000ff); - assert(Buffer.from(base.clone().cropCircle({max: true, feathering: 0.3}).bitmap).equals(Buffer.from(base.clone().cropCircle(true, 0.3).bitmap)), 'cropCircle options'); - assert(base.clone().rotate(45, {resize: false}).width === 20 && base.clone().rotate(45).width > 20, 'rotate options'); - const navy = new Image(10, 10).fill(0x00002aff).drawBox(0, 0, 3, 3, 0xc8c800ff); - assert(navy.dominantColor({threshold: 0}) === 0x00002aff && navy.dominantColor({ignoreBlack: true}) === navy.dominantColor(true), 'dominantColor options'); + assert(base.clone().rotate(45, {expand: false}).width === 20 && base.clone().rotate(45).width > 20, 'rotate options'); + const navy = new Image(10, 10).fill(0x00002aff).composite(new Image(3, 3).fill(0xc8c800ff), {x: 0, y: 0}); + assert(navy.dominantColor({threshold: 0}) === 0x00002aff, 'dominantColor options'); + // the threshold is in channel values: navy's brightest channel is 42 (the default is 60) + assert(navy.dominantColor({threshold: 42}) === 0x00002aff && navy.dominantColor({threshold: 43}) !== 0x00002aff && navy.dominantColor() === navy.dominantColor({threshold: 60}), 'dominantColor threshold in channel values'); } // type checks take any binary data { const {ImageType} = require('..'); - const png = await new Image(1, 1).encode(); + const png = await new Image(1, 1).encodePNG(); assert(ImageType.isPNG(png) && ImageType.isPNG(Buffer.from(png)) && ImageType.isPNG(new DataView(png.buffer)) && !ImageType.isGIF(png), 'ImageType checks'); } // blur and sharpen: uniform images stay as they are, transparent pixels don't bleed their color { const flat = new Image(16, 16).fill(0x336699ff); - for (const [name, op] of [['blur', i => i.blur(3)], ['blur small', i => i.blur(0.8)], ['sharpen', i => i.sharpen(2, 1.5)]]) + for (const [name, op] of [['blur', i => i.blur(3)], ['blur small', i => i.blur(0.8)], ['sharpen', i => i.sharpen({amount: 2, radius: 1.5})]]) assert(Buffer.from(op(flat.clone()).bitmap).equals(Buffer.from(flat.bitmap)), `${name} changed a uniform image`); - assert(Buffer.from(flat.clone().blur(0).bitmap).equals(Buffer.from(flat.bitmap)) && Buffer.from(flat.clone().sharpen(0).bitmap).equals(Buffer.from(flat.bitmap)), 'blur(0)/sharpen(0) should do nothing'); + assert(Buffer.from(flat.clone().blur(0).bitmap).equals(Buffer.from(flat.bitmap)) && Buffer.from(flat.clone().sharpen({amount: 0}).bitmap).equals(Buffer.from(flat.bitmap)), 'blur(0)/sharpen(0) should do nothing'); const half = new Image(16, 16).fill((x) => x < 8 ? 0xff000000 : 0x0000ffff).blur(2); for (let x = 0; x < 16; x++) { @@ -796,16 +694,16 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); } const edge = new Image(16, 1).fill((x) => x < 8 ? 0x000000ff : 0xffffffff); - const sharpened = edge.clone().sharpen(1, 1); + const sharpened = edge.clone().sharpen({amount: 1, radius: 1}); assert(rgba(sharpened, 7, 0)[0] === 0 && rgba(sharpened, 8, 0)[0] === 255, 'sharpen should keep a hard edge hard'); - const soft = new Image(16, 1).fill((x) => Image.rgbToColor(x * 16, x * 16, x * 16)).blur(1); - const sharp = soft.clone().sharpen(3, 2); + const soft = new Image(16, 1).fill((x) => Colors.fromRGB(x * 16, x * 16, x * 16)).blur(1); + const sharp = soft.clone().sharpen({amount: 3, radius: 2}); assert(rgba(sharp, 15, 0)[0] >= rgba(soft, 15, 0)[0] && rgba(sharp, 0, 0)[0] <= rgba(soft, 0, 0)[0], 'sharpen should increase contrast'); } // rgb adjustments { - const image = new Image(64, 4).fill((x, y) => Image.rgbaToColor(x * 4, 255 - x * 4, y * 60, 200)); + const image = new Image(64, 4).fill((x, y) => Colors.fromRGBA(x * 4, 255 - x * 4, y * 60, 200)); for (const [name, op] of [['brightness(1)', i => i.brightness(1)], ['contrast(1)', i => i.contrast(1)], ['gamma(1)', i => i.gamma(1)]]) assert(Buffer.from(op(image.clone()).bitmap).equals(Buffer.from(image.bitmap)), `${name} should not change the image`); @@ -813,11 +711,11 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); assert(rgba(px(0x804020ff).brightness(2), 0, 0).join() === '255,128,64,255', 'brightness(2)'); assert(rgba(px(0x804020ff).contrast(0), 0, 0).join() === '128,128,128,255', 'contrast(0) should be grey'); assert(rgba(px(0x40404080).gamma(2), 0, 0).join() === '128,128,128,128', 'gamma(2) should brighten and keep alpha, got ' + rgba(px(0x40404080).gamma(2), 0, 0)); - assert(rgba(px(0xff0000ff).greyscale(), 0, 0).join() === '76,76,76,255', 'greyscale should use the 601 luma'); + assert(rgba(px(0xff0000ff).grayscale(), 0, 0).join() === '76,76,76,255', 'greyscale should use the 601 luma'); assert(rgba(px(0xffffff80).sepia(), 0, 0).join() === '255,255,239,128', 'sepia, got ' + rgba(px(0xffffff80).sepia(), 0, 0)); let threw = 0; - for (const op of [i => i.brightness(-1), i => i.contrast(NaN), i => i.gamma(0), i => i.blur(-1), i => i.sharpen(1, 0)]) + for (const op of [i => i.brightness(-1), i => i.contrast(NaN), i => i.gamma(0), i => i.blur(-1), i => i.sharpen({amount: 1, radius: 0})]) try { op(px(0)); } catch { threw++; } assert(threw === 5, 'invalid adjustment arguments should throw'); } @@ -826,51 +724,51 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); { const base = new Image(2, 1).fill((x) => x ? 0x808080ff : 0x00000000); const top = new Image(2, 1).fill(0x4080c0ff); - assert(Buffer.from(base.clone().composite(top, 0, 0, {opacity: 0}).bitmap).equals(Buffer.from(base.bitmap)), 'opacity 0 should change nothing'); - assert(rgba(base.clone().composite(top, 0, 0, {opacity: 0.5}), 1, 0).join() === '96,128,160,255', 'opacity 0.5'); - assert(rgba(base.clone().composite(top, 0, 0, {mode: 'multiply'}), 1, 0).join() === '32,64,96,255', 'multiply'); - assert(rgba(base.clone().composite(top, 0, 0, {mode: 'screen'}), 1, 0).join() === '160,192,224,255', 'screen'); + assert(Buffer.from(base.clone().composite(top, {x: 0, y: 0, opacity: 0}).bitmap).equals(Buffer.from(base.bitmap)), 'opacity 0 should change nothing'); + assert(rgba(base.clone().composite(top, {x: 0, y: 0, opacity: 0.5}), 1, 0).join() === '96,128,160,255', 'opacity 0.5'); + assert(rgba(base.clone().composite(top, {x: 0, y: 0, mode: 'multiply'}), 1, 0).join() === '32,64,96,255', 'multiply'); + assert(rgba(base.clone().composite(top, {x: 0, y: 0, mode: 'screen'}), 1, 0).join() === '160,192,224,255', 'screen'); // over a transparent backdrop blend modes draw the plain source - assert(rgba(base.clone().composite(top, 0, 0, {mode: 'multiply'}), 0, 0).join() === '64,128,192,255', 'blend over transparency'); - assert(Buffer.from(base.clone().composite(top, 0, 0, {mode: 'normal', opacity: 1}).bitmap).equals(Buffer.from(base.clone().composite(top).bitmap)), 'normal mode'); + assert(rgba(base.clone().composite(top, {x: 0, y: 0, mode: 'multiply'}), 0, 0).join() === '64,128,192,255', 'blend over transparency'); + assert(Buffer.from(base.clone().composite(top, {x: 0, y: 0, mode: 'normal', opacity: 1}).bitmap).equals(Buffer.from(base.clone().composite(top).bitmap)), 'normal mode'); // normal mode with an opacity (source over with the source alpha scaled) matches the general compositing model, // also for translucent pixels, off the edges let seed = 3; const random = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) / 2 ** 32; - const pixel = () => Image.rgbaToColor(random() * 256 | 0, random() * 256 | 0, random() * 256 | 0, [0, 255, random() * 256 | 0][random() * 3 | 0]); + const pixel = () => Colors.fromRGBA(random() * 256 | 0, random() * 256 | 0, random() * 256 | 0, [0, 255, random() * 256 | 0][random() * 3 | 0]); const backdrop = new Image(24, 16).fill(pixel), source = new Image(16, 24).fill(pixel); for (const opacity of [0.3, 0.85, 0.999]) { const expected = backdrop.clone().__blend__(source, 12, -4, opacity, (_, s) => s).bitmap; - const actual = backdrop.clone().composite(source, 12, -4, {opacity}).bitmap; + const actual = backdrop.clone().composite(source, {x: 12, y: -4, opacity}).bitmap; assert(actual.every((v, i) => Math.abs(v - expected[i]) <= 1), `normal mode with opacity ${opacity} differs from the compositing model`); } let threw = 0; for (const options of [{mode: 'foo'}, {mode: 'toString'}, {opacity: 2}, {opacity: NaN}]) - try { base.clone().composite(top, 0, 0, options); } catch { threw++; } + try { base.clone().composite(top, {x: 0, y: 0, ...options}); } catch { threw++; } assert(threw === 4, 'invalid composite options should throw'); } // outlined text grows by the stroke width and puts the stroke color around the glyphs { const font = require('fs').readFileSync('./tests/fonts/opensans bold.ttf'); - const plain = await Image.renderText(font, 40, 'Hi'); - const outlined = await Image.renderText(font, 40, 'Hi', 0xffffffff, undefined, {strokeWidth: 3, strokeColor: 0xff0000ff}); + const plain = await Image.renderText('Hi', { font, size: 40 }); + const outlined = await Image.renderText('Hi', { font, size: 40, color: 0xffffffff, strokeWidth: 3, strokeColor: 0xff0000ff }); assert(outlined.width === plain.width + 6 && outlined.height === plain.height + 6, 'stroke should grow the image'); let red = 0, white = 0; - for (const [, , color] of outlined.iterateWithColors()) { + for (const [, , color] of outlined.pixels()) { if (color === 0xff0000ff) red++; if (color === 0xffffffff) white++; } assert(red > 100 && white > 100, `outlined text should contain both colors (${red} red, ${white} white)`); // the stroke goes around translucent text, it doesn't show through it - const translucent = await Image.renderText(font, 40, 'Hi', 0x0000ff80, undefined, {strokeWidth: 3, strokeColor: 0xff0000ff}); - const fill = await Image.renderText(font, 40, 'Hi', 0x0000ff80); + const translucent = await Image.renderText('Hi', { font, size: 40, color: 0x0000ff80, strokeWidth: 3, strokeColor: 0xff0000ff }); + const fill = await Image.renderText('Hi', { font, size: 40, color: 0x0000ff80 }); let inside = 0, tinted = 0; // pixels the glyphs cover fully (the stroked image is 3 pixels larger on every side) - for (const [x, y, color] of fill.iterateWithColors()) { + for (const [x, y, color] of fill.pixels()) { if (color !== 0x0000ff80) continue; inside++; if (translucent.getPixelAt(x + 3, y + 3) !== 0x0000ff80) tinted++; @@ -899,8 +797,8 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); xmp: o => chunk('iTXt', Buffer.concat([Buffer.from('XML:com.adobe.xmp\0\x01\0\0\0', 'latin1'), zlib.deflateSync(xmp(o))])), }; - const source = new Image(3, 2).fill((x, y) => Image.rgbaToColor(x * 100, y * 100, 0, 255)); - const encoded = Buffer.from(await source.encode()); + const source = new Image(3, 2).fill((x, y) => Colors.fromRGBA(x * 100, y * 100, 0, 255)); + const encoded = Buffer.from(await source.encodePNG()); const withChunks = (...extra) => Buffer.concat([encoded.subarray(0, encoded.length - 12), ...extra, encoded.subarray(encoded.length - 12)]); for (const [name, make] of Object.entries(chunks)) { @@ -916,16 +814,19 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); // colorToAlpha removes the color, so compositing the result over that color gives the original back (#39) { - const image = new Image(40, 40).fill(0xffffffff).drawCircle(20, 20, 12, 0xff0000ff); + const image = new Image(40, 40).fill(0xffffffff).composite(new Image(24, 24).fill(0xff0000ff).cropCircle(), {x: 8, y: 8}); const cut = image.clone().colorToAlpha(); assert(cut.getPixelAt(0, 0) === 0xffffff00, 'colorToAlpha: the background should become transparent'); assert(cut.getPixelAt(20, 20) === 0xff0000ff, 'colorToAlpha: other colors should stay opaque'); const back = new Image(40, 40).fill(0xffffffff).composite(cut); assert(Buffer.from(back.bitmap).equals(Buffer.from(image.bitmap)), 'colorToAlpha: compositing over the color should give the original'); - const edge = cut.getRGBAAt(32, 20); - assert(edge[3] > 0 && edge[3] < 255 && edge[0] === 255 && edge[1] === 0, 'colorToAlpha: antialiased edges should become translucent red'); - const loose = image.clone().colorToAlpha(0xffffffff, {transparencyThreshold: 0.5}); - assert(loose.getRGBAAt(32, 20)[3] < edge[3], 'colorToAlpha: the threshold should make more of the edge transparent'); + // (an antialiased edge pixel of the circle: the first one on the diagonal that is neither the color nor red) + let ex = 8; + while ((image.getPixelAt(ex, ex) & 0xffffff00) >>> 0 === 0xffffff00) ex++; + const edge = Colors.toRGBA(cut.getPixelAt(ex, ex)); + assert(edge[3] > 0 && edge[3] < 255 && edge[0] === 255 && edge[1] === 0, `colorToAlpha: antialiased edges should become translucent red (${edge})`); + const loose = image.clone().colorToAlpha({color: 0xffffffff, transparencyThreshold: 0.5}); + assert(Colors.toRGBA(loose.getPixelAt(ex, ex))[3] < edge[3], 'colorToAlpha: the threshold should make more of the edge transparent'); } // slice-by-16 crc32 matches zlib for every length around the 16 byte steps and for unaligned views (#12) @@ -949,7 +850,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); // noisy rows on top and a noisy strip in the bottom left, the rest transparent const image = new Image(width, height).fill((x, y) => { const c = y < rows || y > height * 2 / 3 && x < 64 ? random() * colors | 0 : 0; - return c ? Image.rgbaToColor(c * 37, c * 11, c, 255) : 0; + return c ? Colors.fromRGBA(Math.min(c * 37, 255), c * 11, c, 255) : 0; }); for (const options of [{}, {quality: 85}]) { const decoded = await Image.decode(await image.encodeWebP(options)).catch(err => assert(false, `WebP ${JSON.stringify(options)} of the ${width}x${height} mask: ${err.message}`)); @@ -967,7 +868,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const random = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) / 2 ** 32; // (a damaged copy of the Noto-COLRv1 subset with 3329 contours of decreasing end points in a glyph ran out of memory) const start = Date.now(); - await Image.renderText(fs.readFileSync('./tests/fonts/damaged noto colrv1 subset.ttf'), 40, '😀🔥👍❤️').catch(err => assert(/^Font: /.test(err.message), err.message)); + await Image.renderText('😀🔥👍❤️', { font: fs.readFileSync('./tests/fonts/damaged noto colrv1 subset.ttf'), size: 40 }).catch(err => assert(err instanceof Error, err.message)); assert(Date.now() - start < 3000, 'the damaged Noto-COLRv1 subset took too long'); for (const file of ['sourcesans3 regular.otf', 'opensans bold.ttf', 'noto colrv1 subset.ttf', 'noto color emoji subset.ttf']) { const original = fs.readFileSync(`./tests/fonts/${file}`); @@ -979,9 +880,9 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); } const start = Date.now(); try { - await Image.renderText(data, 40, 'Hi office 😀🔥 👍🏽 🇩🇪 1️⃣ e\u0301'); + await Image.renderText('Hi office 😀🔥 👍🏽 🇩🇪 1️⃣ e\u0301', { font: data, size: 40 }); } catch (err) { - assert(/^Font: /.test(err.message), `${file} #${k}: unexpected error for a damaged font: ${err.message}`); + assert(err instanceof Error, `${file} #${k}: unexpected error for a damaged font: ${err.message}`); } assert(Date.now() - start < 3000, `${file} #${k}: a damaged font took ${Date.now() - start} ms`); } @@ -1029,7 +930,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); const start = Date.now(); let error = null; try { await decode(); } catch (err) { error = err; } - assert(error instanceof RangeError && /too large/.test(error.message), `${name}: should be too large (${error && error.message})`); + assert(error instanceof LimitError, `${name}: should be too large (${error && error.message})`); assert(Date.now() - start < 1000, `${name}: took ${Date.now() - start} ms`); }; await tooLarge('png', () => Image.decode(png(30000, 30000))); @@ -1037,15 +938,23 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); await tooLarge('jpeg', () => Image.decode(jpeg)); await tooLarge('tiff samples', () => Image.decode(tiff)); await tooLarge('gif frames', () => Animation.decode(gif, {maxPixels: 4000 * 4000 * 10})); - await tooLarge('gif frames through GIF.decode', () => GIF.decode(gif, {maxPixels: 4000 * 4000 * 10})); - await tooLarge('maxPixels', () => Image.decode(png(100, 100), {maxPixels: 9999})); + await tooLarge('maxPixels', () => Image.decode(png(100, 100), {maxPixels: 9999})); + // (the limit's error is a LimitError, which is a RangeError) + { + let error = null; + try { await Image.decode(png(100, 100), {maxPixels: 9999}); } catch (err) { error = err; } + assert(error instanceof LimitError && error instanceof RangeError, `LimitError: ${error}`); + error = null; + try { await Image.renderSVG('', {maxPixels: 15}); } catch (err) { error = err; } + assert(error instanceof require('..').LimitError, `SVG maxPixels: ${error && error.constructor.name}`); + } // without a limit, the PNG gets as far as its data (which is too short) let error = null; try { await Image.decode(png(30000, 30000), {maxPixels: Infinity}); } catch (err) { error = err; } - assert(error && /truncated/.test(error.message), `maxPixels: Infinity should lift the limit (${error && error.message})`); + assert(error && !(error instanceof LimitError), `maxPixels: Infinity should lift the limit (${error && error.message})`); // the first frame alone fits - assert((await Animation.decode(gif, {maxPixels: 4000 * 4000 * 10, onlyFirstFrame: true})).length === 1, 'the first frame should fit the limit'); + assert((await Image.decode(gif, {maxPixels: 4000 * 4000 * 10})) instanceof Image, 'the first frame should fit the limit'); // damaged data error = null; @@ -1071,29 +980,29 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); let defs = ''; for (let i = 1; i <= 9; i++) defs += `${``.repeat(10)}`; let start = Date.now(), error = null; - try { await Image.renderSVG(`${defs}`, {size: 100, mode: Image.SVG_MODE_WIDTH}); } catch (err) { error = err; } - assert(error && / references/.test(error.message) && Date.now() - start < 3000, `billion laughs should throw quickly (${error && error.message}, ${Date.now() - start} ms)`); + try { await Image.renderSVG(`${defs}`, {width: 100}); } catch (err) { error = err; } + assert(error instanceof LimitError && Date.now() - start < 10000, `billion laughs should throw quickly (${error && error.message}, ${Date.now() - start} ms)`); start = Date.now(); - const dashed = await Image.renderSVG(``, {size: 100, mode: Image.SVG_MODE_WIDTH}); - assert(Date.now() - start < 3000 && dashed.getRGBAAt(50, 50)[3] === 255, 'a dash pattern too fine to dash should stroke solid, quickly'); + const dashed = await Image.renderSVG(``, {width: 100}); + assert(Date.now() - start < 10000 && Colors.toRGBA(dashed.getPixelAt(50, 50))[3] === 255, 'a dash pattern too fine to dash should stroke solid, quickly'); - const nested = await Image.renderSVG(`${''.repeat(100000)}${''.repeat(100000)}`, {size: 100, mode: Image.SVG_MODE_WIDTH}); + const nested = await Image.renderSVG(`${''.repeat(100000)}${''.repeat(100000)}`, {width: 100}); assert(nested.width === 100, 'deeply nested elements should render'); } { - // NaN and the infinities throw instead of drawing black, transparent or nothing; numeric strings still work - const {Frame, Animation, TextLayout} = require('..'); + // NaN and the infinities throw instead of drawing black, transparent or nothing; numeric strings are refused + const {Image, Frame, Animation} = require('..'); const image = () => new Image(8, 8).fill(0xff0000ff); const calls = { - rgbaToColor: v => Image.rgbaToColor(v, 0, 0, 255), hslaToColor: v => Image.hslaToColor(v, 0.5, 0.5, 1), colorToRGBA: v => Image.colorToRGBA(v), - getPixelAt: v => image().getPixelAt(v, 1), setPixelAt: v => image().setPixelAt(1, 1, v), fill: v => image().fill(v), contain: v => image().contain(v, 4), - crop: v => image().crop(v, 0, 2, 2), trim: v => image().trim(v), drawBox: v => image().drawBox(0, 0, v, 2, 0), drawCircle: v => image().drawCircle(2, 2, v, 0), - cropCircle: v => image().cropCircle(false, v), opacity: v => image().opacity(v), red: v => image().red(v), lightness: v => image().lightness(v), - composite: v => image().composite(image(), v, 0), hueShift: v => image().hueShift(v), brightness: v => image().brightness(v), gamma: v => image().gamma(v), - colorToAlpha: v => image().colorToAlpha(v), rotate: v => image().rotate(v, false), gradient: v => Image.gradient({0: v, 1: 0}), - roundCorners: v => image().roundCorners(v), fisheye: v => image().fisheye(v), encode: v => image().encode(v), encodeJPEG: v => image().encodeJPEG(v), - frame: v => new Frame(4, 4, v), animation: v => new Animation([new Frame(4, 4)], v), + rgbaToColor: v => Colors.fromRGBA(v, 0, 0, 255), hslaToColor: v => Colors.fromHSLA(v, 0.5, 0.5, 1), colorToRGBA: v => Colors.toRGBA(v), + getPixelAt: v => image().getPixelAt(v, 1), setPixelAt: v => image().setPixelAt(1, 1, v), fill: v => image().fill(v), contain: v => image().resize({width: v, height: 4, fit: 'contain'}), + crop: v => image().crop(v, 0, 2, 2), trim: v => image().trim({color: v}), + cropCircle: v => image().cropCircle({ feathering: v }), opacity: v => image().opacity(v), red: v => image().red(v), lightness: v => image().lightness(v), + composite: v => image().composite(image(), {x: v, y: 0}), hueShift: v => image().hueShift(v), brightness: v => image().brightness(v), gamma: v => image().gamma(v), + colorToAlpha: v => image().colorToAlpha({color: v}), rotate: v => image().rotate(v, {expand: false}), gradient: v => Colors.gradient({0: v, 1: 0}), + roundCorners: v => image().roundCorners({radius: v}), fisheye: v => image().fisheye({strength: v}), encodePNG: v => image().encodePNG({compression: v}), encodeJPEG: v => image().encodeJPEG({quality: v}), + frame: v => new Frame(new Image(4, 4), {duration: v}), animation: v => new Animation([new Frame(new Image(4, 4))], {loopCount: v}), }; for (const [name, call] of Object.entries(calls)) for (const value of [NaN, Infinity, -Infinity]) { @@ -1108,14 +1017,24 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); if (!(error instanceof RangeError)) panic(`${name}(${value}) should throw a RangeError, got ${error}`); } const font = require('fs').readFileSync('./tests/fonts/opensans bold.ttf'); - for (const [name, call] of Object.entries({size: v => Image.renderText(font, v, 'a'), color: v => Image.renderText(font, 12, 'a', v), - maxWidth: v => new TextLayout({maxWidth: v})})) + for (const [name, call] of Object.entries({size: v => Image.renderText('a', { font, size: v }), color: v => Image.renderText('a', { font, size: 12, color: v }), + width: v => Image.renderText('a', { font, size: 12, width: v }), height: v => Image.renderText('a', { font, size: 12, height: v })})) if (!await Promise.resolve().then(() => call(NaN)).then(() => false, e => e instanceof RangeError)) panic(`renderText: a NaN ${name} should throw a RangeError`); - // (no limit is a valid layout) - new TextLayout({maxWidth: Infinity, maxHeight: Infinity}); + // (no size is a valid layout; an infinite one, 0 and one the outline fills aren't) + await Image.renderText('a', { font, size: 12, width: undefined, height: undefined }); + for (const side of ['width', 'height']) { + for (const value of [Infinity, 0, -5]) + if (!await Image.renderText('a', { font, size: 12, [side]: value }).then(() => false, e => e instanceof RangeError)) panic(`renderText: ${side} ${String(value)} should throw a RangeError`); + // (a numeric string is the wrong type, like everywhere else) + if (!await Image.renderText('a', { font, size: 12, [side]: '20' }).then(() => false, e => e instanceof TypeError)) panic(`renderText: ${side} '20' should throw a TypeError`); + } + if (!await Image.renderText('a', { font, size: 12, width: 6, strokeWidth: 3 }).then(() => false, e => e instanceof RangeError)) panic('renderText: a width the outline fills should throw'); - const strings = image().crop('1', '1', '4', '4').rotate('45').opacity('0.5').composite(image(), '1', '2'); - if (strings.width !== 6) panic('numeric strings should keep working'); + for (const [name, call] of Object.entries({crop: () => image().crop('1', 1, 4, 4), rotate: () => image().rotate('45'), opacity: () => image().opacity('0.5'), + composite: () => image().composite(image(), {x: '1', y: 2}), resize: () => image().resize('4', 4), quantize: () => image().quantize({colors: '4'}), + trim: () => image().trim({tolerance: '0.1'}), colorToAlpha: () => image().colorToAlpha({transparencyThreshold: '0'}), gradient: () => Colors.gradient([1, 2])('0.5'), + maxPixels: () => Image.decode(new Uint8Array(1), {maxPixels: '100'}), threads: () => Image.decode(new Uint8Array(1), {threads: '2'}), null: () => image().rotate(null)})) + assert(await Promise.resolve().then(call).then(() => false, e => e instanceof TypeError), `${name}: a numeric string (or null) should throw a TypeError`); } { // SVG parsing doesn't backtrack: long malformed styles, references, lengths and colors parse in linear time @@ -1133,7 +1052,7 @@ const rgba = (image, x, y) => Image.colorToRGBA(image.getPixelAt(x, y)); }; for (const [name, content] of Object.entries(svgs)) { const start = Date.now(); - await Image.renderSVG(`${content}`, 1).catch(() => {}); + await Image.renderSVG(`${content}`, {scale: 1}).catch(() => {}); if (Date.now() - start > 1000) panic(`SVG ${name}: took ${Date.now() - start} ms`); } } diff --git a/tests/resize.js b/tests/resize.js index 15f151be..7e20de96 100644 --- a/tests/resize.js +++ b/tests/resize.js @@ -4,9 +4,9 @@ const samePixels = require('./util/pixels'); (async () => { const binary = await fs.readFile('./tests/targets/image.png'); const image = await Image.decode(binary); - image.resize(image.width / 4, Image.RESIZE_AUTO); + image.resize({width: image.width / 4}); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/resize.png', encoded); @@ -14,7 +14,7 @@ const samePixels = require('./util/pixels'); const target = await fs.readFile('./tests/targets/resize.png'); if (!await samePixels(target, encoded)) process.exit(1); - // the fast resampling (the default) stays within a step of the precise one for opaque images, transparent ones + // the resampling (with 8-bit rounding between its passes) stays within a step of the precise one for opaque images, transparent ones // within 2.5 steps where it shows (premultiplied, alpha within 2), bicubic resizing is left to the precise one const opaque = (await Image.decode(await fs.readFile('./bench/inputs/photo.jpg'))).crop(700, 300, 400, 300); const transparent = opaque.clone(); @@ -23,12 +23,14 @@ const samePixels = require('./util/pixels'); const spot = opaque.clone(); spot.bitmap[(spot.height >> 1) * spot.width * 4 + 403] = 128; const sizes = [[0.5, 0.5], [1 / 3, 0.4], [2, 1.5], [1, 0.7]]; + const {resample, BOX, TRIANGLE, CUBIC} = await import('../dist/util/resample.js'); for (const source of [opaque, transparent, spot]) - for (const mode of [Image.RESIZE_BILINEAR, Image.RESIZE_AREA, Image.RESIZE_BICUBIC]) + for (const mode of ['bilinear', 'area', 'bicubic']) for (const [sx, sy] of sizes) { const width = Math.round(source.width * sx), height = Math.round(source.height * sy); - const a = source.clone().resize(width, height, {mode, fast: false}).bitmap, b = source.clone().resize(width, height, {mode}).bitmap; - const limit = mode === Image.RESIZE_BICUBIC ? 0 : source === opaque ? 1 : 2.5; + const a = new Uint8ClampedArray(width * height * 4), b = source.clone().resize(width, height, {mode}).bitmap; + resample(source.bitmap, source.width, source.height, width, height, {bilinear: TRIANGLE, area: BOX, bicubic: CUBIC}[mode], a, false); + const limit = mode === 'bicubic' ? 0 : source === opaque ? 1 : 2.5; let max = 0, differ = false; for (let i = 0; i < a.length; i++) { if (a[i] === b[i]) continue; @@ -36,8 +38,8 @@ const samePixels = require('./util/pixels'); const alpha = (i & 3) === 3, al = a[i | 3], bl = b[i | 3]; max = Math.max(max, source === opaque || alpha ? Math.abs(a[i] - b[i]) : Math.abs(a[i] * al - b[i] * bl) / 255); } - if (max > limit || mode !== Image.RESIZE_BICUBIC && sx === 0.5 && !differ) { - console.error('fast resize', mode, sx, sy, source === opaque ? 'opaque' : source === spot ? 'spot' : 'transparent', max); + if (max > limit || mode !== 'bicubic' && sx === 0.5 && !differ) { + console.error('resize vs the precise resampling', mode, sx, sy, source === opaque ? 'opaque' : source === spot ? 'spot' : 'transparent', max); process.exit(1); } } diff --git a/tests/review10-animation.js b/tests/review10-animation.js new file mode 100644 index 00000000..ca1b83f9 --- /dev/null +++ b/tests/review10-animation.js @@ -0,0 +1,59 @@ +const {Animation, Frame, Image, Colors} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +let seed = 7; +const random = () => (seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296; +const noise = (width, height) => new Image(width, height).fill(() => ((random() * 2 ** 24) << 8 | 255) >>> 0); + +(async () => { + // the streaming WebP encoder makes the same file as encodeWebP, also without optimizing and with frames WebP can't + // store as they are (disposed to the previous frame, or disposed with odd offsets) + const cases = { + previous: [new Frame(noise(10, 10), {duration: 20}), new Frame(noise(4, 4), {xOffset: 3, yOffset: 3, disposalMode: 'previous', duration: 20}), new Frame(noise(4, 4), {xOffset: 2, yOffset: 2, duration: 20})], + 'odd background': [new Frame(noise(4, 4), {xOffset: 1, yOffset: 3, disposalMode: 'background'}), new Frame(noise(3, 3), {xOffset: 5, yOffset: 1})] + }; + for (const [name, frames] of Object.entries(cases)) for (const quality of [undefined, 80]) { + const options = {optimize: false, ...(quality ? {quality} : {})}; + const whole = await new Animation(frames, {width: 10, height: 10}).encodeWebP(options); + const encoder = Animation.webpEncoder(10, 10, options); + for (const frame of frames) await encoder.add(frame); + const streamed = await encoder.finish(); + if (!Buffer.from(whole).equals(Buffer.from(streamed))) panic(`${name}, quality ${quality}: encodeWebP made ${whole.length} bytes, webpEncoder ${streamed.length}`); + } + + // trim's default color is the top left pixel of the canvas as the first frame shows it + const offset = new Animation([new Frame(new Image(4, 4).fill(0xff0000ff), {xOffset: 2, yOffset: 2})], {width: 8, height: 8}); + offset.trim(); + if (offset.width !== 4 || offset.height !== 4) panic(`trim: ${offset.width}x${offset.height}`); + + // a gradient of 3 or more stops has the colors of its first and last stop before and after them, like one of 2 + const red = 0xff0000ff, clear = 0xff000000, blue = 0x0000ffff; + const ends = Colors.gradient({0.2: red, 0.5: blue, 0.8: clear}); + if (ends(0) !== red || ends(1) !== clear || ends(0.8) !== clear) panic(`gradient ends: ${ends(0).toString(16)} ${ends(1).toString(16)}`); + const doubled = Colors.gradient({0.2: red, 0.2001: red, 0.5: blue, 0.8: blue, 0.8001: clear}); + if (doubled(1) !== clear || doubled(0) !== red) panic('gradient ends with close stops'); + // at a hard edge, the later stop's color (like CSS) + const edge = Colors.gradient({0.2: red, 0.5: blue, 0.5000001: 0x00ff00ff, 1: 0x00ff00ff}); + if (edge(0.5000001) !== 0x00ff00ff) panic('gradient after a hard edge'); + + // at a hard edge (two stops at one position) the later stop's color, like CSS: inside, at the ends, with 2 stops + // and with every stop at one position; at any stop's position its exact color + const green = 0x00ff00ff; + const inner = Colors.gradient({0: red, 0.5: blue, '0.5000': green, 1: green}); + if (inner(0.5) !== green) panic(`gradient at an inner hard edge: ${inner(0.5).toString(16)}`); + const two = Colors.gradient({0.5: red, '0.50': blue}); + if (two(0.5) !== blue || two(0.4) !== red || two(0.6) !== blue) panic(`gradient of 2 stops at one position: ${two(0.5).toString(16)}`); + const same = Colors.gradient({0.5: red, '0.50': blue, '0.500': green}); + if (same(0.5) !== green || same(0.4) !== red) panic(`gradient of stops at one position: ${same(0.5).toString(16)}`); + const exact = Colors.gradient({0: red, 0.3: 0x12345678, 1: blue}); + if (exact(0.3) !== 0x12345678) panic(`gradient at a stop: ${exact(0.3).toString(16)}`); + + // many stops don't overflow the call stack + const stops = {}; + for (let i = 0; i < 200000; i++) stops[i / 200000] = i & 1 ? red : blue; + const many = Colors.gradient(stops); + if (many(0) !== blue) panic('a gradient of 200000 stops'); +})(); diff --git a/tests/review10-image.js b/tests/review10-image.js new file mode 100644 index 00000000..18dd7737 --- /dev/null +++ b/tests/review10-image.js @@ -0,0 +1,25 @@ +const {Image} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// resize({ fit: 'inside' }) checks the box like the other fits: a side below 1 pixel throws instead of making 1x1 +for (const box of [{width: 0, height: 10}, {width: -5, height: 10}, {width: 0.5, height: 10}, {width: 10, height: 0}, {width: NaN, height: 10}]) { + let error = null; + try { new Image(8, 4).resize({...box, fit: 'inside'}); } catch (err) { error = err; } + if (!(error instanceof RangeError)) panic(`resize(${JSON.stringify(box)}, inside): ${error ? error.constructor.name : 'no error'}`); + const image = new Image(8, 4); + try { image.resize({...box, fit: 'inside'}); } catch {} + if (image.width !== 8 || image.height !== 4) panic('a resize that throws should leave the image as it was'); +} +const inside = new Image(8, 4).resize({width: 4, height: 4, fit: 'inside'}); +if (inside.width !== 4 || inside.height !== 2) panic(`inside 4x4: ${inside.width}x${inside.height}`); + +// pixels() goes over the pixels the image has when it is called, also if it is resized before the first value is taken +const image = new Image(2, 2).fill(0xff0000ff); +const pixels = image.pixels(); +image.resize(4, 4); +const all = [...pixels]; +if (all.length !== 4) panic(`pixels() called on 2x2 and resized to 4x4 before iterating gave ${all.length} pixels`); diff --git a/tests/review9-api.js b/tests/review9-api.js new file mode 100644 index 00000000..b9d2c7ce --- /dev/null +++ b/tests/review9-api.js @@ -0,0 +1,27 @@ +const fs = require('fs'); +const {Image, Animation, Frame} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +(async () => { + // renderText checks strokeColor like color, with or without a stroke: a wrong one doesn't pass until the width is set + const font = fs.readFileSync('./tests/fonts/carbon phyber.ttf'); + for (const strokeWidth of [0, 2]) { + const error = await Image.renderText('Hi', {font, size: 32, strokeWidth, strokeColor: 'bad'}).then(() => null, err => err); + if (!(error instanceof TypeError) || !/not 'bad'$/.test(error.message)) panic(`strokeColor 'bad' with strokeWidth ${strokeWidth}: ${error?.constructor?.name}: ${error?.message}`); + } + await Image.renderText('Hi', {font, size: 32, strokeColor: 0xff0000ff}); + + // an encoder that has no frame at finish() isn't used up by the error: frames can be added and it finishes + const encoder = Animation.gifEncoder(4, 4); + const error = await encoder.finish().then(() => null, err => err); + if (!(error instanceof RangeError)) panic(`finish() without frames: ${error?.constructor?.name}`); + await encoder.add(new Frame(new Image(4, 4).fill(0xff0000ff))); + const file = await encoder.finish(); + if (file.length < 20) panic('the encoder should finish after the frame was added'); + const again = await encoder.finish().then(() => null, err => err); + if (!(again instanceof Error) || /frame/.test(again.message)) panic(`finish() twice: ${again?.message}`); +})(); diff --git a/tests/rotate.js b/tests/rotate.js index 1aeb197a..0fccc38e 100644 --- a/tests/rotate.js +++ b/tests/rotate.js @@ -1,5 +1,5 @@ const fs = require('fs').promises; -const {Image} = require('..'); +const {Image, Colors} = require('..'); const samePixels = require('./util/pixels'); const panic = msg => { console.error(msg); @@ -10,9 +10,9 @@ const panic = msg => { { const binary = await fs.readFile('./tests/targets/image.png'); const image = await Image.decode(binary); - image.rotate(45); + image.rotate(-45); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/rotate-45.png', encoded); @@ -23,9 +23,9 @@ const panic = msg => { { const binary = await fs.readFile('./tests/targets/image.png'); const image = await Image.decode(binary); - image.rotate(45, false); + image.rotate(-45, {expand: false}); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/rotate-45-noresize.png', encoded); @@ -37,9 +37,9 @@ const panic = msg => { { const binary = await fs.readFile('./tests/targets/image.png'); const image = await Image.decode(binary); - image.rotate(90); + image.rotate(-90); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/rotate-90.png', encoded); @@ -52,7 +52,7 @@ const panic = msg => { const image = await Image.decode(binary); image.rotate(180); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/rotate-180.png', encoded); @@ -63,9 +63,9 @@ const panic = msg => { { const binary = await fs.readFile('./tests/targets/image.png'); const image = await Image.decode(binary); - image.rotate(270); + image.rotate(-270); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/rotate-270.png', encoded); @@ -75,20 +75,40 @@ const panic = msg => { { const image = new Image(512, 512); - image.fill((x) => Image.hslToColor(x / image.width, 1, .5)); + image.fill((x) => Colors.fromHSL(x / image.width * 360, 1, .5)); if (!Buffer.from(image.bitmap).equals(Buffer.from(image.rotate(360).bitmap))) panic('rotate 360 failed'); } - // the fast sampling (the default) stays within a step of the precise one for opaque pixels, transparent ones - // within 2.5 steps where it shows (premultiplied, alpha within 2) + // rotate() turns clockwise; the modes sample like transform()'s, nearest-neighbor only keeps source colors + { + const source = new Image(8, 6).fill((x, y) => Colors.fromRGBA(x * 30, y * 40, 100, 255)); + const colors = new Set(source.bitmap.length ? [...source.pixels()].map(([, , c]) => c) : []); + const nearest = source.clone().rotate(30, {mode: 'nearest-neighbor'}); + for (const [x, y, c] of nearest.pixels()) if ((c & 0xff) && !colors.has(c)) panic(`rotate nearest-neighbor: new color at ${x},${y}`); + const bicubic = source.clone().rotate(30, {mode: 'bicubic'}), bilinear = source.clone().rotate(30); + if (bicubic.width !== bilinear.width || Buffer.from(bicubic.bitmap).equals(Buffer.from(bilinear.bitmap))) panic('rotate bicubic should differ from bilinear'); + const angle = 30 * Math.PI / 180; + const viaTransform = source.clone().transform([Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0], {expand: false, mode: 'bicubic'}); + const viaRotate = source.clone().rotate(30, {expand: false, mode: 'bicubic'}); + if (!Buffer.from(viaTransform.bitmap).equals(Buffer.from(viaRotate.bitmap))) panic('rotate should sample like transform'); + let error = null; + try { source.clone().rotate(30, {mode: 'area'}); } catch (e) { error = e; } + if (!(error instanceof TypeError)) panic(`rotate mode 'area' should throw a TypeError, got ${error}`); + } + + // the bilinear rotation samples 8-bit pixels (about twice as fast as the precise sampling transform() does): it + // stays within a step of it for opaque pixels, translucent ones within 2.5 steps where they show (premultiplied, + // alpha within 2) { const photo = (await Image.decode(await fs.readFile('./bench/inputs/photo.jpg'))).crop(700, 300, 400, 300); const transparent = photo.clone(); for (let i = 0; i < transparent.bitmap.length; i += 4) transparent.bitmap[i + 3] = (i >> 2) % transparent.width * 255 / (transparent.width - 1); for (const source of [photo, transparent]) - for (const [angle, resize] of [[30, true], [-17.5, true], [123, false], [0.3, true]]) { - const a = source.clone().rotate(angle, {resize, fast: false}).bitmap, b = source.clone().rotate(angle, {resize}).bitmap; + for (const [angle, expand] of [[30, false], [-17.5, false], [123, false], [0.3, false]]) { + // (transform's turn is clockwise as well: the same matrix as the rotation's) + const rad = angle * Math.PI / 180; + const a = source.clone().transform([Math.cos(rad), Math.sin(rad), -Math.sin(rad), Math.cos(rad), 0, 0], {expand}).bitmap, b = source.clone().rotate(angle, {expand}).bitmap; let opaque = 0, shown = 0; for (let i = 0; i < a.length; i++) { if (a[i] === b[i]) continue; @@ -97,7 +117,30 @@ const panic = msg => { else if (al === 255 && bl === 255) opaque = Math.max(opaque, Math.abs(a[i] - b[i])); else shown = Math.max(shown, Math.abs(a[i] * al - b[i] * bl) / 255); } - if (opaque > 1 || shown > 2.5) panic(`fast rotate ${angle}: ${opaque} (opaque), ${shown} (shown)`); + if (opaque > 1 || shown > 2.5) panic(`bilinear rotate ${angle}: ${opaque} (opaque), ${shown} (shown)`); + } + } + + // right angles with `expand: false` keep the size like every other angle : + // the turned image is centered, what doesn't fit is cut off + { + for (const [width, height] of [[4, 2], [5, 2], [2, 5], [3, 3], [6, 4]]) { + const source = new Image(width, height).fill((x, y) => Colors.fromRGBA(x * 10 + 1, y * 10 + 1, 7, 255)); + for (const angle of [90, 180, 270, -90, 450]) { + const kept = source.clone().rotate(angle, {expand: false}); + if (kept.width !== width || kept.height !== height) panic(`${width}x${height}.rotate(${angle}, { expand: false }) is ${kept.width}x${kept.height}`); + const turned = source.clone().rotate(angle); + const left = Math.floor((width - turned.width) / 2), top = Math.floor((height - turned.height) / 2); + for (let y = 0; y < height; y++) + for (let x = 0; x < width; x++) { + const tx = x - left, ty = y - top; + const inside = tx >= 0 && ty >= 0 && tx < turned.width && ty < turned.height; + const expected = inside ? turned.getPixelAt(tx, ty) : 0; + if (kept.getPixelAt(x, y) !== expected) panic(`${width}x${height}.rotate(${angle}, { expand: false }): pixel ${x},${y} is ${kept.getPixelAt(x, y).toString(16)} instead of ${expected.toString(16)}`); + } + if (angle !== 90 && angle !== 270 && angle !== -90 && angle !== 450 || width === height) + if (Buffer.compare(Buffer.from(kept.bitmap), Buffer.from(turned.bitmap))) panic(`${width}x${height}.rotate(${angle}, { expand: false }) should equal the expanded one`); } + } } })(); diff --git a/tests/run.js b/tests/run.js index 174a0527..40259065 100644 --- a/tests/run.js +++ b/tests/run.js @@ -1,40 +1,75 @@ const fs = require('fs'); const child_process = require('child_process'); +const os = require('os'); // runs every test with the runtime running this script: node, deno or bun const runtime = `"${process.execPath}"`; const command = typeof Deno !== 'undefined' ? `${runtime} run -A` : typeof Bun !== 'undefined' ? runtime : `${runtime} --unhandled-rejections=strict`; +// Determine safe max concurrency based on available CPU cores +const concurrencyLimit = os.availableParallelism ? os.availableParallelism() : (os.cpus()?.length || 4); + (async () => { - for (const file of fs.readdirSync('./tests/')) { - if (file === 'run.js' || file.slice(-3) !== '.js') continue; - - console.log(`running test ${file}`); - const start = Date.now(); - const proc = child_process.exec(`${command} ./tests/${file}`); - proc.stderr.pipe(process.stderr); - proc.stdout.pipe(process.stdout); - await new Promise(resolve => { + const testFiles = fs.readdirSync('./tests/').filter(file => file !== 'run.js' && file.slice(-3) === '.js'); + + const runTest = (file) => { + return new Promise((resolve) => { + console.log(`[started] test ${file}`); + const start = Date.now(); + const proc = child_process.exec(`${command} ./tests/${file}`); + + // Buffer outputs to prevent interleaving + let stdoutData = ''; + let stderrData = ''; + + proc.stdout.on('data', chunk => { stdoutData += chunk; }); + proc.stderr.on('data', chunk => { stderrData += chunk; }); + let timedOut = false; const timeout = setTimeout(() => { - console.log('script timeout'); timedOut = true; proc.kill('SIGTERM'); - }, 60000); + }, 1000 * 60 * 2); proc.on('exit', code => { clearTimeout(timeout); + const duration = Date.now() - start; + + // Print the buffered output atomically once the test finishes + if (stdoutData) process.stdout.write(stdoutData); + if (stderrData) process.stderr.write(stderrData); if (code !== 0 || timedOut) { - console.error(`test ${file} failed in ${Date.now() - start}ms`); - process.exit(1); + if (timedOut) console.error(`script timeout: ${file}`); + console.error(`test ${file} failed in ${duration}ms`); + resolve(false); } else { - console.log(`test ${file} passed in ${Date.now() - start}ms`); - resolve(); + console.log(`test ${file} passed in ${duration}ms`); + resolve(true); } }); }); + }; + + // Concurrency pool runner to cap active tests at concurrencyLimit + let index = 0; + const results = []; + async function worker() { + while (index < testFiles.length) { + const currentIndex = index++; + const file = testFiles[currentIndex]; + results[currentIndex] = await runTest(file); + } } - console.log('all tests passed'); + console.log(`Running tests with a max concurrency of ${concurrencyLimit}...`); + const workers = Array(Math.min(concurrencyLimit, testFiles.length)).fill(null).map(() => worker()); + await Promise.all(workers); + + if (results.every(Boolean)) { + console.log('all tests passed'); + } else { + console.error('some tests failed'); + process.exit(1); + } })(); \ No newline at end of file diff --git a/tests/svg-arcs.js b/tests/svg-arcs.js new file mode 100644 index 00000000..23826826 --- /dev/null +++ b/tests/svg-arcs.js @@ -0,0 +1,122 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const child_process = require('child_process'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// Curves between far-apart points: an arc's radius grows to half the distance of its ends, and the number of curves +// and points it was drawn with grew with the radius, without a limit: a 139-byte path killed the process with an out +// of memory error. Each renders, or throws a LimitError, in a bounded time and memory (in a process of its own, which +// can die without taking this one along) +const NS = 'xmlns="http://www.w3.org/2000/svg"'; +const svg = shape => `${shape}`; +let many = 'M -1e12 100'; +for (let i = 0; i < 1000; i++) many += i & 1 ? ' A 1 1 0 0 1 -1e12 100' : ' A 1 1 0 0 1 1e12 100'; +const cases = { + 'stroked arc from 1e25': svg(''), + 'filled arc from 1e25': svg(''), + 'stroked arc from 301e30': svg(''), + 'arc from 1e300': svg(''), + 'arc of radius 1e300': svg(''), + '1000 arcs between 1e12 and -1e12': svg(``), + 'circle of radius 1e30': svg(''), + // many such arcs in one path: their curves were made while the path was read, before any budget counted them + '20000 arcs between 1e30 and -1e30': svg(``), + '100000 arcs between 1e12 and -1e12': svg(``), + // many different long paths in SVGs embedded as images: the paths read were kept until the render ended + 'many long paths in embedded SVGs': (() => { + const body = 'L1 1L0 0'.repeat(50000); + const uri = k => { + let s = ``; + for (let p = 0; p < 40; p++) s += ``; + return 'data:image/svg+xml;base64,' + require('zlib').gzipSync(s + '', {level: 9}).toString('base64'); + }; + return `${Array.from({length: 8}, (_, k) => ``).join('')}`; + })(), + // a long path a textPath follows, through : measuring the path for each copy wasn't counted + 'textPath through use': (() => { + let defs = `A`; + for (let i = 1; i <= 4; i++) defs += `${``.repeat(10)}`; + return `${defs}${''.repeat(9)}`; + })(), + // a path a textPath follows that is longer than a path may be + 'textPath along a too long path': `A`, + // long text in a clip path and as text: its glyphs were collected with spreads, past the call stack's limit + 'long text in a clip path': `${'W'.repeat(50000)}`, + 'long text': `${'W'.repeat(50000)}`, + // a long path with one label (a map's contour line), at a normal size: only many copies of it are too much + 'textPath on one long path': `A`, + // long text builds every glyph's outline: they count against the budget before they are made + 'long text with complex glyphs': `${'A'.repeat(20000)}`, + // the outlines of all texts are kept until the render ends: they count against the render's budget, not each text's + '20 texts of complex glyphs': `${`${'A'.repeat(1000)}`.repeat(20)}`, + // but one long text isn't held to the limit of one path (a long article rendered before) + 'one long text at a large size': `${'A'.repeat(120000)}`, + // bitmap emoji copied through decoded their PNG for each draw + 'bitmap emoji through use': (() => { + let d = `${'\u{1F600}'.repeat(5)}`; + for (let i = 1; i < 8; i++) d += `${``.repeat(4)}`; + return `${d}`; + })(), + // a large bitmap emoji at many sizes: decoded once, not once a size + 'large emoji at 12 sizes': (() => { + const font = require('fs').readFileSync('./tests/fonts/emoji-4096.ttf').toString('base64'); + let texts = ''; + for (let i = 0; i < 12; i++) texts += `\u{1F600}`; + return `${texts}`; + })(), + // a bitmap emoji that says it is 16383x16383: not decoded (it was allocated, 1 GB) + 'huge emoji': (() => { + const font = require('fs').readFileSync('./tests/fonts/emoji-4096.ttf'); + const at = font.indexOf('IHDR'); + font.writeUInt32BE(16383, at + 4); + font.writeUInt32BE(16383, at + 8); + let crc = ~0; + for (const byte of font.subarray(at, at + 17)) { + crc ^= byte; + for (let k = 0; k < 8; k++) crc = crc & 1 ? crc >>> 1 ^ 0xedb88320 : crc >>> 1; + } + font.writeUInt32BE(~crc >>> 0, at + 17); + let texts = ''; + for (let i = 0; i < 4; i++) texts += `\u{1F600}`; + const faces = Array.from({length: 4}, (_, i) => `@font-face{font-family:f${i};src:url(data:font/ttf;base64,${font.toString('base64')})}`).join(''); + return `${texts}`; + })(), + // many tspans in one text took quadratic time + 'many tspans': `${'A'.repeat(10000)}`, + // a path of lines only, drawn 90000 times through without painting anything: no budget counted its points + 'lines through use': (() => { + let defs = ``; + for (let i = 1; i <= 4; i++) defs += `${``.repeat(10)}`; + return `${defs}${''.repeat(9)}`; + })() +}; +const [command, ...flags] = typeof Deno !== 'undefined' ? [process.execPath, 'run', '-A', '--v8-flags=--max-old-space-size=1024'] : [process.execPath, ...(process.versions.bun ? [] : ['--max-old-space-size=1024'])]; +const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'svg-arcs-')); +try { + for (const [name, document] of Object.entries(cases)) { + const file = path.join(directory, 'svg'); + fs.writeFileSync(file, document); + const begin = Date.now(); + let output; + try { + output = JSON.parse(child_process.execFileSync(command, [...flags, './tests/util/render-svg.js', file], {timeout: 60000, maxBuffer: 1 << 24, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']}).trim()); + } catch (error) { + panic(`${name}: ${error.signal === 'SIGTERM' ? 'hung for 60 s' : `crashed (${error.signal || `exit ${error.status}`})`}`); + } + if (output.result !== 'ok' && !output.result.startsWith('LimitError')) panic(`${name}: ${output.result}`); + if (name === 'textPath along a too long path' && !output.result.startsWith('LimitError')) panic(`${name}: should throw a LimitError`); + if (name === 'one long text at a large size' && output.result !== 'ok') panic(`${name}: ${output.result}`); + if (name === 'bitmap emoji through use' && output.result !== 'ok') panic(`${name}: ${output.result}`); + if (name === 'textPath on one long path' && output.result !== 'ok') panic(`${name}: ${output.result}, it is a normal document`); + if (Date.now() - begin > 20000) panic(`${name}: took ${Date.now() - begin} ms`); + if (output.mb > 768 && name !== 'one long text at a large size') panic(`${name}: took ${output.mb} MB`); + console.log(name, output.result.slice(0, 60), `${Date.now() - begin} ms`, `${output.mb} MB`); + } +} finally { + fs.rmSync(directory, {recursive: true, force: true}); +} diff --git a/tests/svg-dos-markers.js b/tests/svg-dos-markers.js new file mode 100644 index 00000000..af88c21a --- /dev/null +++ b/tests/svg-dos-markers.js @@ -0,0 +1,49 @@ +const {Image} = require('..'); + +// SVGs against denial of service, part 3 (split from svg-dos-paint.js for the time a test may take): markers and the +// pixels shapes and layers paint; small documents that must render (or throw) quickly +const NS = 'xmlns="http://www.w3.org/2000/svg"'; + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// (Bun's JavaScriptCore runs the rasterizer several times slower than V8: 12 s where Node takes 2 s) +const slack = process.versions.bun ? 4 : 1; + +(async () => { + // (not under coverage: reaching the budgets takes most of what a test may take there) + if (!process.env.NODE_V8_COVERAGE) { + let error = null; + // markers are limited like the elements of references: 120000 marker-mid instances took 135 s + { + const points = Array.from({length: 120000}, (_, i) => `${i % 1000} ${i / 1000 | 0}`).join(' L'); + const markers = ``; + const begin = Date.now(); + error = null; + try { await Image.renderSVG(markers); } catch (err) { error = err; } + if (!error || error.name !== 'LimitError' || !/markers/.test(error.message) || Date.now() - begin > 30000 * slack) panic(`120000 markers: expected the marker limit within 30 s, got ${error} after ${Date.now() - begin} ms`); + } + // what counts is what is painted, not the bounding boxes of the shapes: a chart of 1000 thin lines across the + // image renders (each line's box is the whole image) + { + let lines = ''; + for (let i = 0; i < 1000; i++) lines += ``; + const begin = Date.now(); + const chart = await Image.renderSVG(`${lines}`).catch(err => err); + if (!(chart instanceof Image) || Date.now() - begin > 60000 * slack) panic(`a chart of 1000 lines: ${chart} after ${Date.now() - begin} ms, it should render`); + } + // the pixels shapes and layers fill are bounded like the filters' work: 1000 copies of a full-canvas group + // with opacity (16 KB) took 260 s at 4000x4000, 9999 markers of a 400x400 group 36 s + for (const [name, svg] of [ + [' copies', `${''.repeat(1000)}`], + ['markers', ``] + ]) { + const begin = Date.now(); + error = null; + try { await Image.renderSVG(svg); } catch (err) { error = err; } + if (!error || error.name !== 'LimitError' || Date.now() - begin > 30000 * slack) panic(`${name}: expected a LimitError within 30 s, got ${error} after ${Date.now() - begin} ms`); + } + } +})(); diff --git a/tests/svg-dos-paint.js b/tests/svg-dos-paint.js new file mode 100644 index 00000000..293d2919 --- /dev/null +++ b/tests/svg-dos-paint.js @@ -0,0 +1,67 @@ +const {Image} = require('..'); + +// SVGs against denial of service, part 2 (split from svg-dos.js for the time a test may take): filters, the pixels +// shapes and layers paint, markers; small documents that must render (or throw) quickly +const NS = 'xmlns="http://www.w3.org/2000/svg"'; + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// (Bun's JavaScriptCore runs the rasterizer several times slower than V8: 12 s where Node takes 2 s) +const slack = process.versions.bun ? 4 : 1; + +(async () => { + // a filter of hundreds of primitives over a large region: a LimitError (the work is bounded) instead of minutes of + // work, and the results it keeps for `result=` references count against maxLayerPixels (600 such pairs over a + // megapixel took more than 3 GB, also with a lower maxLayerPixels) + // (not under coverage: reaching the budget takes most of what a test may take there) + if (!process.env.NODE_V8_COVERAGE) { + const chain = n => `${''.repeat(n)}`; + const start = Date.now(); + let error = null; + try { await Image.renderSVG(chain(600)); } catch (err) { error = err; } + const time = Date.now() - start; + if (!error || error.name !== 'LimitError') panic(`filter chain: expected a LimitError, got ${error} after ${time} ms`); + if (time > 30000 * slack) panic(`filter chain: took ${time} ms`); + error = null; + try { await Image.renderSVG(chain(8), {maxLayerPixels: 4e6}); } catch (err) { error = err; } + if (!error || error.name !== 'LimitError') panic(`filter chain within maxLayerPixels: expected a LimitError, got ${error}`); + // one primitive that costs far more than its pixels: a convolution of order 200 took 341 s over a megapixel (80 KB + // of SVG); it is charged for its kernel's taps + const convolve = ``; + const convolveStart = Date.now(); + error = null; + try { await Image.renderSVG(convolve); } catch (err) { error = err; } + if (!error || error.name !== 'LimitError' || Date.now() - convolveStart > 15000 * slack) panic(`a convolution of order 200: expected a LimitError within 15 s, got ${error} after ${Date.now() - convolveStart} ms`); + // the work allowed scales with the size of the render: a drop shadow on a 4096x4096 image (rendered by rc.5) stays within it + { + const big = await Image.renderSVG(``); + if (big.getPixelAt(2000, 2000) !== 0xff0000ff) panic('a drop shadow on a 4096x4096 image should render'); + } + // primitives that cost more than one pass over their pixels are charged for it: turbulence per octave (83 of 24 + // octaves, 5.7 KB, took 238 s), a merge per node (5000 nodes took 107 s) + for (const [name, filter] of [ + ['turbulence', ''.repeat(83)], + ['merge', `${''.repeat(5000)}`] + ]) { + const begin = Date.now(); + error = null; + try { await Image.renderSVG(`${filter}`); } catch (err) { error = err; } + if (!error || error.name !== 'LimitError' || Date.now() - begin > 15000 * slack) panic(`${name}: expected a LimitError within 15 s, got ${error} after ${Date.now() - begin} ms`); + } + // a filter region is a layer like the others: over maxLayerPixels it's a LimitError, not a silently missing + // element, and the limit is what the option says (a fixed 2^26 pixels refused a filter on the whole of 6900x6900) + error = null; + try { await Image.renderSVG(``, {maxLayerPixels: 9.5e6}); } catch (err) { error = err; } + if (!error || error.name !== 'LimitError' || !/maxLayerPixels/.test(error.message)) panic(`a filter region over maxLayerPixels: expected a LimitError naming it, got ${error}`); + // a declared size no integer can hold is a LimitError like the other sizes past maxPixels + error = null; + try { await Image.renderSVG(``); } catch (err) { error = err; } + if (!error || error.name !== 'LimitError') panic(`a declared width of 1e17: expected a LimitError, got ${error}`); + // a real filter on a large image still renders + const shadow = await Image.renderSVG(``); + if (shadow.width !== 2000) panic('a drop shadow on a large image should render'); + } +})(); diff --git a/tests/svg-dos.js b/tests/svg-dos.js new file mode 100644 index 00000000..6178cd84 --- /dev/null +++ b/tests/svg-dos.js @@ -0,0 +1,170 @@ +const {Image, Colors} = require('..'); + +// SVGs against denial of service: small documents that must render (or throw) quickly +const NS = 'xmlns="http://www.w3.org/2000/svg"'; + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// (Bun's JavaScriptCore runs the rasterizer several times slower than V8: 12 s where Node takes 2 s) +const slack = process.versions.bun ? 4 : 1; +const timed = async (name, svg, limit = 5000) => { + limit *= slack; + const start = Date.now(); + let error = null, image = null; + try { image = await Image.renderSVG(svg, {width: 100}); } catch (err) { error = err; } + const time = Date.now() - start; + if (process.env.SVG_DOS_TIMES) console.log(name, time); + if (time > limit) panic(`${name}: took ${time} ms`); + return {image, error, time}; +}; + +(async () => { + // shapes whose edges cross every row of the image tens of thousands of times: a LimitError (the work is bounded), and + // quickly (thousands of huge overlapping strokes took 38 s from 51 KB of SVG) + // (not under coverage: reaching the budget takes 20 seconds there, which is most of what a test may take) + if (!process.env.NODE_V8_COVERAGE) { + let d = ''; + for (let i = 0; i < 16000; i++) d += `M${(i % 7) / 10} 0h1v300h-1z`; + const {error, time} = await timed('edges crossing every row', ``, 10000); + if (!error || error.name !== 'LimitError') panic(`edges crossing every row: expected a LimitError, got ${error} after ${time} ms`); + } + + // many shapes starting in different rows, most of them beside the canvas: activating the edges of a row shifted + // half of the active ones for each (80000 triangles took 8.7 s) + { + let d = ''; + for (let i = 0; i < 80000; i++) d += `M${(i * 7919) % 100000} ${(i * 7) % 30} l4 0 l-2 ${30 + i % 10} z`; + // an element with 140000 children: the walks over the tree pushed them with a spread, past the call stack's limit + // (a bare RangeError for a 4 MB SVG); a LimitError or a render is the answer + { + const {error} = await timed('140000 siblings', `${''.repeat(140000)}`, 15000); + if (error && (error.name !== 'LimitError')) panic(`140000 siblings: ${error.name}: ${error.message}`); + } + const {error} = await timed('80000 triangles', ``); + if (error) panic(`80000 triangles: ${error.message}`); + } + + // edges far above the canvas: their sub-scanline range wrapped in an Int32Array and ran two billion iterations + for (const [name, shape] of [ + ['circle r=1e9', ''], + ['scale(1e9)', ''], + ['arc', ''] + ]) { + const {error} = await timed(name, `${shape}`); + if (error) panic(`${name}: ${error.message}`); + } + { + // the visible part of a huge circle is still painted + const {image} = await timed('huge circle', ``); + if (Colors.toRGBA(image.getPixelAt(50, 50)).join() !== '0,255,0,255') panic('huge circle: not painted'); + } + + // feTurbulence: the cost is linear in numOctaves, which has no limit in the format; octaves past the 24th add nothing + { + const turbulence = octaves => ``; + const {image: reference, error} = await timed('numOctaves 24', turbulence(24)); + if (error) panic(`numOctaves 24: ${error.message}`); + for (const octaves of [25, 1000, 1e9]) { + const {image, error} = await timed(`numOctaves ${octaves}`, turbulence(octaves), 3000); + if (error) panic(`numOctaves ${octaves}: ${error.message}`); + if (Buffer.compare(Buffer.from(image.bitmap), Buffer.from(reference.bitmap))) panic(`numOctaves ${octaves}: differs from 24`); + } + } + + // masks, clip paths, patterns, markers and filter images that reference each other, three per level: the renders + // multiplied without a limit (minutes at ten levels, from two kilobytes) + { + const three = text => text.repeat(3); + const vectors = { + masks: n => { + let defs = ''; + for (let i = 1; i <= n; i++) defs += `${three(``)}`; + return `${defs}`; + }, + 'clip paths': n => { + let defs = ''; + for (let i = 1; i <= n; i++) defs += `${three(``)}`; + return `${defs}`; + }, + markers: n => { + let defs = ''; + for (let i = 1; i <= n; i++) defs += `${three(``)}`; + return `${defs}`; + }, + 'filter images': n => { + let defs = ''; + for (let i = 1; i <= n; i++) defs += `${three(``)}`; + return `${defs}`; + }, + patterns: n => { + let defs = ''; + for (let i = 1; i <= n; i++) defs += `${three(``)}`; + return `${defs}`; + } + }; + { + // (an ordinary document at 1080p: a mask of 24 masked shapes, each mask rendered inside the outer one) + const shapes = Array.from({length: 24}, (_, i) => ``).join(''); + const svg = `${shapes}`; + const start = Date.now(); + const image = await Image.renderSVG(svg); + if (Colors.toRGBA(image.getPixelAt(10, 10)).join() !== '255,0,0,255') panic('masked shapes inside a masked group: not rendered'); + if (process.env.SVG_DOS_TIMES) console.log('1080p masks', Date.now() - start); + } + for (const [name, vector] of Object.entries(vectors)) { + // (a few levels are an ordinary document) + const ordinary = await timed(`${name}, 3 levels`, `${vector(3)}`); + if (ordinary.error) panic(`${name}, 3 levels: ${ordinary.error.message}`); + const {error} = await timed(`${name}, 14 levels`, `${vector(14)}`, 30000); + if (!error || error.name !== 'LimitError') panic(`${name}, 14 levels: should throw a LimitError (${error})`); + } + } + + // transform lists with many unclosed functions parsed in quadratic time (5 s at 280 KB) + { + const {error, time, image} = await timed('transform', ``, 1000); + if (error) panic(`transform: ${error.message} after ${time} ms`); + // (and a function after the unclosed ones still applies) + const moved = await Image.renderSVG(``); + if (Colors.toRGBA(moved.getPixelAt(15, 5))[3] !== 255 || Colors.toRGBA(moved.getPixelAt(5, 5))[3] !== 0) panic('transform: the closed function should apply'); + } + + // half a million dashes or more render in a 64 MB heap: the ones beside the image are left out, the others are + // stroked a batch at a time (a 157 byte SVG took 650 MB, and failed in a 256 MB heap) + { + let zigzag = 'M0 0'; + for (let i = 1; i <= 200; i++) zigzag += ` L${i % 2 ? 500 : 0} ${i * 2.5}`; + const script = ` + const {Image} = require(${JSON.stringify(require.resolve('..'))}); + const NS = 'xmlns="http://www.w3.org/2000/svg"'; + (async () => { + const beside = await Image.renderSVG(\`\`); + const across = await Image.renderSVG(\`\`); + let a = 0, b = 0; + for (let i = 3; i < beside.bitmap.length; i += 4) a += beside.bitmap[i]; + for (let i = 3; i < across.bitmap.length; i += 4) b += across.bitmap[i]; + console.log(a, b); + })();`; + // (the heap is limited with Node's flag: Deno and Bun take other ones, they run it in the test's process) + let output; + if (typeof Deno === 'undefined' && !process.versions.bun) { + const child = require('child_process').spawnSync(process.execPath, ['--max-old-space-size=64', '-e', script], {encoding: 'utf8'}); + if (child.status !== 0) panic(`dashes in a 64 MB heap: ${child.stderr.split('\n').find(line => /heap|Error/.test(line)) ?? child.status}`); + output = child.stdout; + } else { + const log = console.log; + output = await new Promise(resolve => { + console.log = (...values) => resolve(values.join(' ')); + new Function('require', script)(require); + }).finally(() => { console.log = log; }); + } + const [beside, across] = output.trim().split(' ').map(Number); + // (half of the line shows: dashes of 0.1 with gaps as long; the zigzag about half of its length too) + if (Math.abs(beside / (100 * 255) - 0.5) > 0.05) panic(`dashes beside the image: ${beside / 255} pixels covered of the line's 100, expected about half`); + if (!(across > 0)) panic('the dashed zigzag shows nothing'); + } + +})(); diff --git a/tests/svg-images.js b/tests/svg-images.js index 93a68217..ae6f6464 100644 --- a/tests/svg-images.js +++ b/tests/svg-images.js @@ -1,4 +1,4 @@ -const {Image, Animation, Frame} = require('..'); +const {Image, Animation, Frame, Colors} = require('..'); const panic = message => { console.error(message); @@ -44,14 +44,14 @@ const crc32 = bytes => { }; (async () => { - const logo = new Image(4, 3).fill((x, y) => Image.rgbaToColor(x * 60, y * 80, 128, x === 0 ? 0 : 255)); - const other = new Image(4, 3).fill((x, y) => Image.rgbaToColor(255 - x * 60, y * 40, 200, 255)); - const opaque = new Image(4, 3).fill((x, y) => Image.rgbaToColor(x * 60, y * 80, 128, 255)); - const png = await logo.encode(1); + const logo = new Image(4, 3).fill((x, y) => Colors.fromRGBA(x * 60, y * 80, 128, x === 0 ? 0 : 255)); + const other = new Image(4, 3).fill((x, y) => Colors.fromRGBA(255 - x * 60, y * 40, 200, 255)); + const opaque = new Image(4, 3).fill((x, y) => Colors.fromRGBA(x * 60, y * 80, 128, 255)); + const png = await logo.encodePNG({compression: 1}); const webp = await logo.encodeWebP(); - const jpeg = await opaque.encodeJPEG(90); - const gif = await new Animation([Frame.from(opaque)]).encodeGIF(); - const otherPNG = await other.encode(1); + const jpeg = await opaque.encodeJPEG({quality: 90}); + const gif = await new Animation([new Frame(opaque.clone())]).encodeGIF(); + const otherPNG = await other.encodePNG({compression: 1}); // images given by href render exactly like the same images as data URIs, in every format and placement const formats = [['image/png', png], ['image/webp', webp], ['image/jpeg', jpeg], ['image/gif', gif]]; @@ -64,8 +64,8 @@ const crc32 = bytes => { // the same, with preserveAspectRatio and scaling for (const aspect of ['none', 'xMidYMid meet', 'xMinYMin slice']) { const element = (href) => ``; - const viaURI = await Image.renderSVG(svg(element(dataURI('image/png', png)), 8, 6), {size: 2}); - const viaMap = await Image.renderSVG(svg(element('logo.png'), 8, 6), {size: 2, images: {'logo.png': png}}); + const viaURI = await Image.renderSVG(svg(element(dataURI('image/png', png)), 8, 6), {scale: 2}); + const viaMap = await Image.renderSVG(svg(element('logo.png'), 8, 6), {scale: 2, images: {'logo.png': png}}); if (!same(viaURI, viaMap)) panic(`preserveAspectRatio="${aspect}" differs between data URIs and given images`); } @@ -115,12 +115,24 @@ const crc32 = bytes => { if (transparent(viaMap)) panic(`${name}: nothing drawn`); } - // hrefs that aren't given draw nothing, like before; the empty SVG is the reference + // drawing an href that isn't given throws (the SVG can't be rendered as it is); images that aren't drawn don't { + await throwsA(Image.renderSVG(svg('')), Error, 'a missing href'); + await throwsA(Image.renderSVG(svg(''), {images: {'logo.png': png}}), Error, 'a missing href next to a given one'); + await throwsA(Image.renderSVG(svg('')), Error, 'a URL'); + await throwsA(Image.renderSVG(svg(``)), Error, 'an unsupported data URI type'); + await throwsA(Image.renderSVG(svg(``)), Error, 'a data URI SVG without '); const empty = await Image.renderSVG(svg('')); - const missing = await Image.renderSVG(svg('')); - const missingWithOthers = await Image.renderSVG(svg(''), {images: {'logo.png': png}}); - if (!same(empty, missing) || !same(empty, missingWithOthers) || !transparent(missing)) panic('a missing href draws something'); + for (const [label, body] of [ + ['in ', ''], + ['display="none"', ''], + ['visibility="hidden"', ''], + ['in a group\'s bounding box', ''], + ['without an href', ''], + ]) { + const result = await Image.renderSVG(svg(body)).catch(error => panic(`a missing image that isn't drawn (${label}) throws: ${error.message}`)); + if (label !== 'in a group\'s bounding box' && !same(result, empty)) panic(`a missing image that isn't drawn (${label}) draws something`); + } } // images that are given but not referenced are not decoded (garbage bytes don't throw) @@ -132,11 +144,14 @@ const crc32 = bytes => { if (transparent(result)) panic('the used image was not drawn next to an unused one'); } - // an undecodable image under a used href behaves like a broken data URI: nothing is drawn, nothing throws + // drawing an undecodable image throws, given by href or as a data URI (with the decoding error as its cause) { - const broken = await Image.renderSVG(svg(''), {images: {'logo.png': new Uint8Array([1, 2, 3, 4])}}); - const brokenURI = await Image.renderSVG(svg(``)); - if (!transparent(broken) || !same(broken, brokenURI)) panic('a broken image under a used href is not like a broken data URI'); + const broken = await throwsA(Image.renderSVG(svg(''), {images: {'logo.png': new Uint8Array([1, 2, 3, 4])}}), Error, 'a broken given image'); + if (!broken.cause) panic(`a broken image's error has no cause: ${broken.message}`); + await throwsA(Image.renderSVG(svg(``)), Error, 'a broken data URI'); + await throwsA(Image.renderSVG(svg(``)), Error, 'a broken feImage'); + // (one that isn't drawn doesn't throw) + await Image.renderSVG(svg(''), {images: {'logo.png': new Uint8Array([1, 2, 3, 4])}}); } // validation before anything is decoded @@ -150,22 +165,50 @@ const crc32 = bytes => { if (calls !== 0) panic(`images were decoded before validation failed (${calls})`); } - // a huge declared image doesn't get around the decoding limit: it draws nothing, like a broken image + // a huge declared image doesn't get around the decoding limit: drawing it throws a RangeError { - const tiny = await new Image(1, 1).fill(0xffffffff).encode(1); + const tiny = await new Image(1, 1).fill(0xffffffff).encodePNG({compression: 1}); const huge = Uint8Array.from(tiny); const view = new DataView(huge.buffer); view.setUint32(16, 20000); view.setUint32(20, 20000); view.setUint32(29, crc32(huge.subarray(12, 29))); await throwsA(Image.decode(huge), RangeError, 'the huge PNG decodes on its own'); - const result = await Image.renderSVG(svg(''), {images: {'big.png': huge}}); - if (!transparent(result)) panic('a huge image was drawn'); + await throwsA(Image.renderSVG(svg(''), {images: {'big.png': huge}}), RangeError, 'a huge image'); + } + + // maxImagePixels: the images together (Image values don't count), by default maxPixels + { + const body = ''; + const two = {'a.png': png, 'b.png': otherPNG}; + await Image.renderSVG(svg(body), {images: two, maxImagePixels: 24}); + await throwsA(Image.renderSVG(svg(body), {images: two, maxImagePixels: 23}), RangeError, 'two images over maxImagePixels'); + // (a 4x3 output: only the images exceed maxPixels) + await throwsA(Image.renderSVG(svg(body, 4, 3), {images: two, maxPixels: 23}), RangeError, 'two images over maxPixels'); + await Image.renderSVG(svg(body), {images: {'a.png': logo, 'b.png': other}, maxImagePixels: 1}); + await Image.renderSVG(svg(body, 4, 3), {images: two, maxPixels: 23, maxImagePixels: Infinity}); + for (const [value, type] of [[0, RangeError], [-1, RangeError], [NaN, RangeError], ['many', TypeError], ['100', TypeError]]) + await throwsA(Image.renderSVG(svg(body), {images: two, maxImagePixels: value}), type, `maxImagePixels ${value}`); + } + + // maxLayerPixels: the layers alive at once (nested groups with opacity each take one), by default 4 * maxPixels + { + const nest = depth => ''.repeat(depth) + '' + ''.repeat(depth); + // the canvas and 3 layers fit 4 * maxPixels + await Image.renderSVG(svg(nest(3)), {maxPixels: 24}); + await throwsA(Image.renderSVG(svg(nest(4)), {maxPixels: 24}), RangeError, 'nested layers over 4 * maxPixels'); + await throwsA(Image.renderSVG(svg(nest(2)), {maxLayerPixels: 24 * 2}), RangeError, 'nested layers over maxLayerPixels'); + await Image.renderSVG(svg(nest(20)), {maxPixels: 24, maxLayerPixels: Infinity}); + // layers that are done are given back: many groups after each other only take one at a time + await Image.renderSVG(svg(nest(1).repeat(100) + ``.repeat(50) + + ''), {maxLayerPixels: 24 * 8}); + for (const value of [0, -1, NaN]) + await throwsA(Image.renderSVG(svg(nest(1)), {maxLayerPixels: value}), RangeError, `maxLayerPixels ${value}`); } // quantized images can be given too (the palette of an SVG's image) { - const reduced = await new Image(4, 3).fill((x, y) => Image.rgbaToColor(x * 60, y * 80, 128, 255)).quantize({colors: 4}).encode(1); + const reduced = await new Image(4, 3).fill((x, y) => Colors.fromRGBA(x * 60, y * 80, 128, 255)).quantize({colors: 4}).encodePNG({compression: 1}); const result = await Image.renderSVG(svg(''), {images: {'logo.png': reduced}}); if (transparent(result)) panic('a reduced image was not drawn'); } diff --git a/tests/svg-primitives.js b/tests/svg-primitives.js index d7386fc7..5c4bbd69 100644 --- a/tests/svg-primitives.js +++ b/tests/svg-primitives.js @@ -11,7 +11,7 @@ const panic = message => { // feDisplacementMap applies its scale once (resvg multiplies by it twice) and reads the map's colors unpremultiplied, // like browsers: a map of R = 1 (half transparent) moves every pixel's source 0.5 * scale to the right (async () => { - const {Image} = require('..'); + const {Image, Colors} = require('..'); const svg = opacity => ` @@ -22,7 +22,7 @@ const panic = message => { const image = await Image.renderSVG(svg(opacity)); // y offset: (alpha - 0.5) * 20, 10 rows down at opacity 1, none at 0.5; x: the rect drawn 10 pixels left const row = opacity === 1 ? 5 : 10; - const covered = [...Array(100).keys()].filter(x => image.getRGBAAt(x, row)[3] > 128); + const covered = [...Array(100).keys()].filter(x => Colors.toRGBA(image.getPixelAt(x, row))[3] > 128); if (covered[0] !== 30 || covered.at(-1) !== 49) panic(`feDisplacementMap (map opacity ${opacity}): covers ${covered[0]}-${covered.at(-1)}, not 30-49`); } })(); diff --git a/tests/svg.js b/tests/svg.js index 266aa6bb..1e4f3d9c 100644 --- a/tests/svg.js +++ b/tests/svg.js @@ -1,4 +1,4 @@ -const {Image} = require('..'); +const {Image, Colors} = require('..'); const fs = require('fs').promises; const samePixels = require('./util/pixels'); @@ -10,8 +10,8 @@ const panic = message => { (async () => { { const svg = await fs.readFile('./tests/svgs/potato.svg'); - const image = await Image.renderSVG(svg.toString(), 256 / 36, Image.SVG_MODE_SCALE); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const image = await Image.renderSVG(svg.toString(), {scale: 256 / 36}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/potato.png', encoded); @@ -23,10 +23,10 @@ const panic = message => { { // gradients, clip paths, masks, style sheets, symbols, strokes and fill rules const svg = await fs.readFile('./tests/svgs/features.svg'); - const image = await Image.renderSVG(svg, 480, Image.SVG_MODE_WIDTH); + const image = await Image.renderSVG(svg, {width: 480}); if (image.width !== 480 || image.height !== 320) panic('features: unexpected size'); - const encoded = await image.encode(1, {creationTime: 0, software: ''}); + const encoded = await image.encodePNG({compression: 1, metadata: {creationTime: 0, software: ''}}); if (process.env.OVERWRITE_TEST) await fs.writeFile('./tests/targets/svg-features.png', encoded); @@ -41,8 +41,8 @@ const panic = message => { { // images embedded as data URIs: placed at their size, the pixels are the decoded image's - const {Animation, Frame} = require('..'); - const pixel = (x, y, alpha) => Image.rgbaToColor(x * 10, y * 15, 128, alpha && x > 20 ? 0 : 255); + const {Animation, Image, Frame} = require('..'); + const pixel = (x, y, alpha) => Colors.fromRGBA(x * 10, y * 15, 128, alpha && x > 20 ? 0 : 255); const source = new Image(24, 16), opaque = new Image(24, 16); for (let y = 0; y < 16; y++) for (let x = 0; x < 24; x++) { @@ -50,12 +50,12 @@ const panic = message => { opaque.setPixelAt(x, y, pixel(x, y, false)); } const rect = ''; - const gif = await new Animation([Frame.from(opaque)]).encodeGIF(); - const jpeg = await opaque.encodeJPEG(90); + const gif = await new Animation([new Frame(opaque.clone())]).encodeGIF(); + const jpeg = await opaque.encodeJPEG({quality: 90}); const cases = [ - ['image/png', await source.encode(1), source], + ['image/png', await source.encodePNG({compression: 1}), source], ['image/webp', await source.encodeWebP(), source], - ['image/gif', gif, (await Animation.decode(gif))[0]], + ['image/gif', gif, (await Animation.decode(gif)).frames[0].image], ['image/jpeg', jpeg, await Image.decode(jpeg)], ['image/svg+xml', require('zlib').gzipSync(rect), await Image.renderSVG(rect)] ]; diff --git a/tests/targets/font-bidi.png b/tests/targets/font-bidi.png index f5befd4a..abc1d525 100644 Binary files a/tests/targets/font-bidi.png and b/tests/targets/font-bidi.png differ diff --git a/tests/targets/readme.png b/tests/targets/readme.png index a17d4256..88d24810 100644 Binary files a/tests/targets/readme.png and b/tests/targets/readme.png differ diff --git a/tests/targets/svg-features.png b/tests/targets/svg-features.png index 6c7340a6..104e800a 100644 Binary files a/tests/targets/svg-features.png and b/tests/targets/svg-features.png differ diff --git a/tests/text-spreads.js b/tests/text-spreads.js new file mode 100644 index 00000000..61169fc0 --- /dev/null +++ b/tests/text-spreads.js @@ -0,0 +1,40 @@ +const {Image, LimitError} = require('..'); +const fs = require('fs'); + +// (Bun's JavaScriptCore runs the layout several times slower than V8) +const slack = process.versions.bun ? 4 : 1; + +const panic = message => { + console.error(message); + process.exit(1); +}; + +// text with 200,000 combining marks or lines is laid out like any other: the arrays of its parts are not spread into a +// call (past the stack's limit), and a failure doesn't blame the font +(async () => { + const font = fs.readFileSync(__dirname + '/fonts/resvg/NotoSans-Regular.ttf'); + // a bitmap emoji that says it is 16383x16383 isn't decoded (it was allocated, 1 GB) + const emoji = fs.readFileSync(__dirname + '/fonts/emoji-4096.ttf'), at = emoji.indexOf('IHDR'); + emoji.writeUInt32BE(16383, at + 4); + emoji.writeUInt32BE(16383, at + 8); + let crc = ~0; + for (const byte of emoji.subarray(at, at + 17)) { + crc ^= byte; + for (let k = 0; k < 8; k++) crc = crc & 1 ? crc >>> 1 ^ 0xedb88320 : crc >>> 1; + } + emoji.writeUInt32BE(~crc >>> 0, at + 17); + const before = process.memoryUsage().rss; + await Image.renderText('\u{1F600}', {font: emoji, size: 8}); + if (process.memoryUsage().rss - before > 512 * 2 ** 20) panic(`a huge emoji: took ${(process.memoryUsage().rss - before) >> 20} MB`); + for (const [name, text, options] of [ + ['combining marks', 'a' + '\u0301'.repeat(200000), {}], + ['lines', 'a '.repeat(200000), {width: 1}], + ['marks between letters', 'a\u0301'.repeat(200000), {}], + ]) { + // (and in linear time: 400,000 lines took minutes) + const begin = Date.now(); + const result = await Image.renderText(text, {font, size: 1, maxPixels: 1e8, ...options}).then(() => 'ok', err => err); + if (result !== 'ok' && !(result instanceof LimitError)) panic(`${name}: ${result}`); + if (Date.now() - begin > 15000 * slack) panic(`${name}: took ${Date.now() - begin} ms`); + } +})(); diff --git a/tests/tga.js b/tests/tga.js index 2db631c6..38123079 100644 --- a/tests/tga.js +++ b/tests/tga.js @@ -1,4 +1,4 @@ -const {Image, ImageType} = require('..'); +const {Image, ImageType, Colors} = require('..'); const panic = message => { console.error(message); @@ -12,7 +12,7 @@ function tga({type, depth, width, height, descriptor = 0, map = null, mapFirst = return Uint8Array.from([...header, ...id, ...(map || []), ...data]); } -const rgba = (image, x, y) => image.getRGBAAt(x, y).join(); +const rgba = (image, x, y) => Colors.toRGBA(image.getPixelAt(x, y)).join(); (async () => { // uncompressed 24 bit, default bottom left origin: the first stored row is the bottom one @@ -53,7 +53,7 @@ const rgba = (image, x, y) => image.getRGBAAt(x, y).join(); // encoding round trips, opaque images are stored with 24 bits for (const image of [ - new Image(50, 7).fill((x, y) => Image.rgbaToColor(x * 5, y * 30, (x >> 2) * 40, x % 3 ? 255 : 100)), + new Image(50, 7).fill((x, y) => Colors.fromRGBA(x * 5, y * 30, Math.min((x >> 2) * 40, 255), x % 3 ? 255 : 100)), new Image(300, 2).fill(0x336699ff), new Image(1, 1).fill(0x00000000), // a header per pixel: one pixel rows, alternating @@ -77,10 +77,5 @@ const rgba = (image, x, y) => image.getRGBAAt(x, y).join(); if (opaque[16] !== 24) panic('TGA: opaque images should be stored with 24 bits'); // truncated data is rejected, not read past - try { - await Image.decode(tga({type: 10, depth: 24, width: 4, height: 4}, [0x83, 1, 2, 3]).subarray(0, 21)); - panic('TGA: truncated data accepted'); - } catch (err) { - if (!/TGA|Unsupported/.test(err.message)) panic(`TGA: unexpected error ${err.message}`); - } + if (!await Image.decode(tga({type: 10, depth: 24, width: 4, height: 4}, [0x83, 1, 2, 3]).subarray(0, 21)).then(() => false, error => error instanceof Error)) panic('TGA: truncated data accepted'); })(); diff --git a/tests/tiff.js b/tests/tiff.js index 509841e0..87acdfe7 100644 --- a/tests/tiff.js +++ b/tests/tiff.js @@ -46,5 +46,18 @@ const expected = { const tiff = await import('../dist/codecs/tiff.js'); const broken = await fs.readFile('./tests/tiffs/l2.tif'); broken[0] = broken[1] = 0x58; - if (!await tiff.decode(broken).then(() => false, error => /byte order/.test(error.message))) panic('an invalid byte order should throw'); + if (!await tiff.decode(broken).then(() => false, error => error instanceof Error)) panic('an invalid byte order should throw'); + + // files that ask for more memory than they are: refused before anything is allocated, so quickly + // (YCbCr subsampling factors of 65534x65535 made 4 GB of units out of 32 KB; 1024 samples per pixel took 1 GB) + // (and a BitsPerSample tag that points outside the file, or pixels that don't fit the size, are decoding errors too) + for (const name of ['damaged-bits-per-sample', 'damaged-bitmap-size']) { + const error = await Image.decode(await fs.readFile(`./tests/tiffs/${name}.tif`)).then(() => null, e => e); + if (!error || error.constructor !== Error) panic(`${name}: should throw an Error, got ${error}`); + } + for (const name of ['damaged-ycbcr-subsampling', 'damaged-samples-per-pixel']) { + const started = Date.now(); + if (!await Image.decode(await fs.readFile(`./tests/tiffs/${name}.tif`)).then(() => false, error => error instanceof Error)) panic(`${name}: should be refused`); + if (Date.now() - started > 2000) panic(`${name}: refusing it took ${Date.now() - started} ms`); + } })(); diff --git a/tests/tiffs/README.md b/tests/tiffs/README.md index ab6e1689..643c0c41 100644 --- a/tests/tiffs/README.md +++ b/tests/tiffs/README.md @@ -1,3 +1,6 @@ Written by `scripts/tiff-fixtures.py`: first with Pillow (libtiff) from `tests/targets/external.png` in different modes and compressions, then what Pillow doesn't write: BigTIFF, YCbCr, old-style LZW, fill order 2, odd tile widths, associated alpha, 2- and 32-bit samples. + +`damaged-*.tif` are files that ask for far more memory than they are, which the decoder has to refuse: YCbCr subsampling +factors of 65534 by 65535 and 1024 samples per pixel. diff --git a/tests/tiffs/damaged-bitmap-size.tif b/tests/tiffs/damaged-bitmap-size.tif new file mode 100644 index 00000000..2e4b306a Binary files /dev/null and b/tests/tiffs/damaged-bitmap-size.tif differ diff --git a/tests/tiffs/damaged-bits-per-sample.tif b/tests/tiffs/damaged-bits-per-sample.tif new file mode 100644 index 00000000..1e3c2f41 Binary files /dev/null and b/tests/tiffs/damaged-bits-per-sample.tif differ diff --git a/tests/tiffs/damaged-samples-per-pixel.tif b/tests/tiffs/damaged-samples-per-pixel.tif new file mode 100644 index 00000000..4ad0b791 Binary files /dev/null and b/tests/tiffs/damaged-samples-per-pixel.tif differ diff --git a/tests/tiffs/damaged-ycbcr-subsampling.tif b/tests/tiffs/damaged-ycbcr-subsampling.tif new file mode 100644 index 00000000..61999f66 Binary files /dev/null and b/tests/tiffs/damaged-ycbcr-subsampling.tif differ diff --git a/tests/transform.js b/tests/transform.js index c0259447..28419c1e 100644 --- a/tests/transform.js +++ b/tests/transform.js @@ -1,4 +1,4 @@ -const {Image, Frame, GainMap} = require('..'); +const {Image, Frame, GainMap, Colors} = require('..'); const panic = message => { console.error(message); @@ -15,7 +15,7 @@ const throwsA = (fn, type, label) => { const px = (image, x, y) => Array.from(image.bitmap.subarray((y * image.width + x) * 4, (y * image.width + x) * 4 + 4)); const same = (a, b) => a.width === b.width && a.height === b.height && Buffer.from(a.bitmap).equals(Buffer.from(b.bitmap)); // an opaque image where every pixel is different -const photo = (width, height) => new Image(width, height).fill((x, y) => Image.rgbaToColor((x * 37 + y * 11) % 256, (x * 5 + y * 91) % 256, (x * y + x) % 256, 255)); +const photo = (width, height) => new Image(width, height).fill((x, y) => Colors.fromRGBA((x * 37 + y * 11) % 256, (x * 5 + y * 91) % 256, (x * y + x) % 256, 255)); (async () => { // transform @@ -28,16 +28,16 @@ const photo = (width, height) => new Image(width, height).fill((x, y) => Image.r // flips and quarter turns are exact (the library's rotate() turns counterclockwise) check(same(source.clone().transform([-1, 0, 0, 1, 0, 0]), source.clone().flip('horizontal')), 'transform: flipped horizontally'); check(same(source.clone().transform([1, 0, 0, -1, 0, 0]), source.clone().flip('vertical')), 'transform: flipped vertically'); - check(same(source.clone().transform([0, -1, 1, 0, 0, 0]), source.clone().rotate(90)), 'transform: turned 90 degrees counterclockwise'); + check(same(source.clone().transform([0, -1, 1, 0, 0, 0]), source.clone().rotate(-90)), 'transform: turned 90 degrees counterclockwise'); check(same(source.clone().transform([-1, 0, 0, -1, 0, 0]), source.clone().rotate(180)), 'transform: turned 180 degrees'); - check(same(source.clone().transform([0, 1, -1, 0, 0, 0]), source.clone().rotate(270)), 'transform: turned 270 degrees'); + check(same(source.clone().transform([0, 1, -1, 0, 0, 0]), source.clone().rotate(-270)), 'transform: turned 270 degrees'); const turned = source.clone().transform([0, -1, 1, 0, 0, 0]); check(turned.width === 9 && turned.height === 13, `transform: a quarter turn swaps the size: ${turned.width}x${turned.height}`); - // any angle: close to rotate() (counterclockwise 30 degrees), on a canvas that keeps its size + // any angle: rotate() (counterclockwise 30 degrees: -30), on a canvas that keeps its size const angle = 30 * Math.PI / 180, big = photo(40, 30); const ours = big.clone().transform([Math.cos(angle), -Math.sin(angle), Math.sin(angle), Math.cos(angle), 0, 0], {expand: false}); - const theirs = big.clone().rotate(30, {resize: false}); + const theirs = big.clone().rotate(-30, {expand: false}); let total = 0; for (let i = 0; i < ours.bitmap.length; i++) total += Math.abs(ours.bitmap[i] - theirs.bitmap[i]); check(ours.width === 40 && ours.height === 30 && total / ours.bitmap.length < 3, `transform: a rotation by any angle is rotate()'s (mean difference ${total / ours.bitmap.length})`); @@ -94,8 +94,8 @@ const photo = (width, height) => new Image(width, height).fill((x, y) => Image.r // invalid input is refused, before the image changes for (const [label, bad, type] of [ - ['five values', [1, 0, 0, 1, 0], RangeError], ['seven values', [1, 0, 0, 1, 0, 0, 0], RangeError], ['null', null, RangeError], ['NaN', [1, 0, 0, NaN, 0, 0], RangeError], - ['Infinity', [1, 0, 0, 1, Infinity, 0], RangeError], ['a string', [1, 0, 0, 1, 0, '0'], RangeError], ['all zeros', [0, 0, 0, 0, 0, 0], RangeError], + ['five values', [1, 0, 0, 1, 0], RangeError], ['seven values', [1, 0, 0, 1, 0, 0, 0], RangeError], ['null', null, TypeError], ['a string', 'matrix(1 0 0 1 0 0)', TypeError], ['NaN', [1, 0, 0, NaN, 0, 0], RangeError], + ['Infinity', [1, 0, 0, 1, Infinity, 0], RangeError], ['a string', [1, 0, 0, 1, 0, '0'], TypeError], ['all zeros', [0, 0, 0, 0, 0, 0], RangeError], ['a flat matrix', [1, 2, 2, 4, 0, 0], RangeError], ['a zero scale', [0, 0, 0, 1, 0, 0], RangeError], ['too large', [1e6, 0, 0, 1e6, 0, 0], RangeError] ]) { const image = photo(5, 5), before = image.bitmap.slice(); @@ -106,15 +106,9 @@ const photo = (width, height) => new Image(width, height).fill((x, y) => Image.r throwsA(() => photo(5, 5).transform([1, 0, 0, 1, 0, 0], {origin: {x: NaN}}), RangeError, 'transform with a NaN origin'); throwsA(() => photo(5, 5).transform([1, 0, 0, 1, 0, 0], null), TypeError, 'transform with null options'); - // a frame stays where it is: it grows up and left as far as its offset allows - const frame = Frame.from(photo(20, 20), {duration: 40, xOffset: 3, yOffset: 50}).transform([Math.cos(Math.PI / 4), Math.sin(Math.PI / 4), -Math.sin(Math.PI / 4), Math.cos(Math.PI / 4), 0, 0]); - check(frame instanceof Frame && frame.duration === 40 && frame.xOffset === 0 && frame.yOffset >= 45 && frame.yOffset < 50, `Frame.transform: offsets ${frame.xOffset},${frame.yOffset}`); - const middle = Frame.from(photo(20, 20), {xOffset: 100, yOffset: 100}).transform([1, 0, 0.5, 1, 0, 0]); - check(middle.width === 30 && middle.xOffset === 95 && middle.yOffset === 100, `Frame.transform with room grows left, its pixels stay where they were: ${middle.width}, offsets ${middle.xOffset},${middle.yOffset}`); - // gain maps move with the image const hdr = photo(20, 10); - hdr.gainMap = new GainMap(new Image(10, 5).fill((x) => x < 5 ? 0x000000ff : 0xffffffff), {gainMapMin: 0, gainMapMax: 2}); + hdr.gainMap = new GainMap(new Image(10, 5).fill((x) => x < 5 ? 0x000000ff : 0xffffffff), {min: 0, max: 2}); const flipped = hdr.clone().transform([-1, 0, 0, 1, 0, 0]); check(flipped.gainMap && flipped.gainMap.width === 10 && flipped.gainMap.height === 5, 'transform keeps the gain map'); check(px(flipped.gainMap.image, 0, 2)[0] > 200 && px(flipped.gainMap.image, 9, 2)[0] < 60, 'transform: the gain map is flipped with the image'); diff --git a/tests/trim.js b/tests/trim.js index a6783b74..92e5d811 100644 --- a/tests/trim.js +++ b/tests/trim.js @@ -12,7 +12,7 @@ const size = image => `${image.width}x${image.height}`; { const image = new Image(10, 8); image.setPixelAt(1, 1, 0xffffff00); // transparent white - image.drawBox(3, 4, 4, 2, 0xff0000ff); + image.composite(new Image(4, 2).fill(0xff0000ff), {x: 3, y: 4}); image.setPixelAt(9, 2, 0x00ff00ff); image.trim(); if (size(image) !== '7x4') panic(`trim: ${size(image)} instead of 7x4`); @@ -21,20 +21,20 @@ const size = image => `${image.width}x${image.height}`; // the top left pixel's color by default, or a given one { - const make = () => new Image(6, 6).fill(0xffffffff).drawBox(3, 2, 2, 3, 0x000000ff); + const make = () => new Image(6, 6).fill(0xffffffff).composite(new Image(2, 3).fill(0x000000ff), {x: 3, y: 2}); if (size(make().trim()) !== '2x3') panic('trim: solid background not trimmed'); - if (size(make().trim(0x000000ff)) !== '6x6') panic('trim: explicit color should only trim that color'); + if (size(make().trim({color: 0x000000ff})) !== '6x6') panic('trim: explicit color should only trim that color'); const marked = make().setPixelAt(1, 1, 0xff0000ff); - if (size(marked.trim(0xffffffff)) !== '4x4') panic(`trim: explicit color: ${size(marked)}`); + if (size(marked.trim({color: 0xffffffff})) !== '4x4') panic(`trim: explicit color: ${size(marked)}`); } // tolerance, e.g. for JPEG artifacts { const make = () => new Image(5, 5).fill(0xffffffff).setPixelAt(1, 0, 0xf8f8f8ff).setPixelAt(3, 3, 0x000000ff); if (size(make().trim()) !== '3x4') panic('trim: without tolerance, near colors stay'); - if (size(make().trim(undefined, {tolerance: 0.05})) !== '1x1') panic('trim: tolerance has no effect'); + if (size(make().trim({tolerance: 0.05})) !== '1x1') panic('trim: tolerance has no effect'); for (const tolerance of [-0.1, 1.5, NaN]) - if (!(() => { try { make().trim(undefined, {tolerance}); } catch { return true; } })()) panic(`trim: tolerance ${tolerance} accepted`); + if (!(() => { try { make().trim({tolerance}); } catch { return true; } })()) panic(`trim: tolerance ${tolerance} accepted`); } // an image of only the color stays unchanged @@ -42,8 +42,8 @@ const size = image => `${image.width}x${image.height}`; // frames keep their position { - const frame = new Frame(10, 10, 100, 5, 7); - frame.drawBox(2, 3, 4, 4, 0xffffffff); + const frame = new Frame(new Image(10, 10), {duration: 100, xOffset: 5, yOffset: 7}); + frame.image.composite(new Image(4, 4).fill(0xffffffff), {x: 2, y: 3}); frame.trim(); if (size(frame) !== '4x4' || frame.xOffset !== 7 || frame.yOffset !== 10) panic(`trim: frame ${size(frame)} at ${frame.xOffset},${frame.yOffset}`); } diff --git a/tests/truncated.js b/tests/truncated.js new file mode 100644 index 00000000..c8720d1a --- /dev/null +++ b/tests/truncated.js @@ -0,0 +1,77 @@ +const {Image, Animation, Frame, Colors} = require('..'); +const {inspect} = require('util'); + +const panic = message => { + console.error(message); + process.exit(1); +}; + +(async () => { + // a cut-off JPEG or lossy WebP is a decoding error, not an image with gray or smeared parts (cuts that leave the + // pixels whole, like a missing end marker or metadata after the data, still decode) + const photo = new Image(120, 90).fill((x, y) => Colors.fromRGBA(x * 2 % 256, y * 3 % 256, (x * y) % 256, 255)); + const decodes = async bytes => { try { await Image.decode(bytes); return true; } catch { return false; } }; + + for (const [name, bytes] of [ + ['JPEG', await photo.encodeJPEG({quality: 80})], + ['WebP', await photo.encodeWebP({quality: 80})] + ]) { + const whole = await Image.decode(bytes); + if (whole.width !== 120) panic(`${name}: the whole file doesn't decode`); + let failed = 0; + const cuts = 40; + // (the last bytes of a JPEG are its end marker, and of a WebP its metadata: cuts only in the data before) + for (let i = 1; i < cuts; i++) if (!await decodes(bytes.subarray(0, Math.floor(bytes.length * 0.9 * i / cuts)))) failed++; + if (failed !== cuts - 1) panic(`${name}: ${cuts - 1 - failed} of ${cuts - 1} cut-off files decoded without an error`); + } + + // a small lossy WebP cut anywhere inside of its image data, not only where the data is read to (every cut before the + // bitstream's size is reached) + { + const small = await Image.linearGradient(67, 41, {stops: [0xff2040ff, 0x3040ffff], angle: 135}).encodeWebP({quality: 80}); + const view = new DataView(small.buffer, small.byteOffset); + // (the VP8 chunk of the extended format, after the VP8X chunk of 18 bytes) + let at = 12; + while (String.fromCharCode(...small.subarray(at, at + 4)) !== 'VP8 ') at += 8 + view.getUint32(at + 4, true) + (view.getUint32(at + 4, true) & 1); + const end = at + 8 + view.getUint32(at + 4, true); + for (let cut = at + 8; cut < end; cut++) + if (await decodes(small.subarray(0, cut))) panic(`a lossy WebP cut ${end - cut} bytes before the end of its image data decoded`); + if (!await decodes(small)) panic('the whole small WebP does not decode'); + } + + // a JPEG without its end marker has all its pixels + const jpeg = await photo.encodeJPEG({quality: 80}); + if (!await decodes(jpeg.subarray(0, jpeg.length - 2))) panic('a JPEG without its end marker is rejected'); + + // iterating while the image is resized yields the pixels the image had at the start + { + const image = new Image(2, 2); + let count = 0; + for (const _ of image.pixels()) { + count++; + image.resize(4, 4); + } + if (count !== 4) panic(`pixels() of an image resized meanwhile yielded ${count} pixels`); + } + + // a still image is a frame of the default duration + for (const bytes of [await photo.encodePNG(), await photo.encodeJXL(), await photo.encodeJPEG()]) { + const animation = await Animation.decode(bytes); + if (animation.frames[0].duration !== new Frame(photo).duration) panic(`a still image's frame lasts ${animation.frames[0].duration} ms (${bytes.slice(0, 4)})`); + } + + // logging and serializing don't write the pixels + const frame = new Frame(photo); + const animation = new Animation([frame]); + if (JSON.stringify(photo) !== '{"width":120,"height":90}') panic(`JSON.stringify(image): ${JSON.stringify(photo)}`); + if (inspect(photo) !== 'Image<120x90>') panic(`inspect(image): ${inspect(photo)}`); + if (inspect(animation) !== String(animation) || inspect(frame) !== String(frame)) panic('inspect(animation or frame)'); + if (JSON.stringify(frame).length > 80 || JSON.stringify(animation).length > 100) panic('JSON.stringify(frame or animation) is long'); + + try { + new Colors(); + panic('new Colors() works'); + } catch (error) { + if (!(error instanceof TypeError)) panic(`new Colors(): ${error}`); + } +})(); diff --git a/tests/user-report-3.js b/tests/user-report-3.js new file mode 100644 index 00000000..c15a5ee9 --- /dev/null +++ b/tests/user-report-3.js @@ -0,0 +1,172 @@ +const fs = require('fs').promises; +const {Image, Animation, Frame, GainMap, Colors} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +const rejects = async (name, fn, Type) => { + try { + await fn(); + } catch (error) { + if (!(error instanceof Type)) panic(`${name}: wrong error ${error?.constructor?.name}: ${error?.message}`); + return; + } + panic(`${name}: accepted`); +}; +const has = (bytes, text) => Buffer.from(bytes).includes(Buffer.from(text, 'latin1')); + +(async () => { + const image = new Image(8, 8).fill((x, y) => Colors.fromRGB(x * 30, y * 30, 128)); + + // a gain map's hdrCapacityMin and hdrCapacityMax are checked against each other when they are set (the old value + // stays), so a map is never in a state that clone(), image.gainMap = map or an encoder refuses + { + const map = new GainMap(new Image(4, 4).fill(0x808080ff), {max: 2}); + await rejects('hdrCapacityMax below hdrCapacityMin', () => { map.hdrCapacityMax = -0.5; }, RangeError); + await rejects('hdrCapacityMax equal to hdrCapacityMin', () => { map.hdrCapacityMax = 0; }, RangeError); + await rejects('hdrCapacityMin above hdrCapacityMax', () => { map.hdrCapacityMin = 3; }, RangeError); + if (map.hdrCapacityMax !== 2 || map.hdrCapacityMin !== 0) panic(`gain map capacities changed by refused values: ${map.hdrCapacityMin} ${map.hdrCapacityMax}`); + map.hdrCapacityMax = 3; + map.hdrCapacityMin = 1; + map.clone(); + image.clone().gainMap = map; + await rejects('new GainMap capacities crossed', () => new GainMap(new Image(4, 4), {hdrCapacityMin: 2, hdrCapacityMax: 1}), RangeError); + // a channel value is a number or [r, g, b] (a one-element array is neither) + await rejects('gain map max [1]', () => { map.max = [1]; }, RangeError); + await rejects('gain map min [1, 2]', () => { map.min = [1, 2]; }, RangeError); + if (map.max.join() !== '2,2,2') panic('gain map max changed by a refused value'); + } + + // the gain map embed options and the lossy WebP options are checked whether they are used or not + { + const map = new GainMap(new Image(8, 8).fill(0x808080ff), {max: 2}); + const hdr = image.clone(); + hdr.gainMap = map; + for (const [name, encode] of Object.entries({jpeg: o => hdr.encodeJPEG(o), avif: o => hdr.encodeAVIF(o), jxl: o => hdr.encodeJXL(o)})) { + await rejects(`${name} gain map quality -1`, () => encode({gainMap: {quality: -1}}), RangeError); + await rejects(`${name} gain map quality 101`, () => encode({gainMap: {quality: 101}}), RangeError); + await rejects(`${name} gain map scale 0`, () => encode({gainMap: {scale: 0}}), RangeError); + await rejects(`${name} gain map quality "90"`, () => encode({gainMap: {quality: '90'}}), TypeError); + // (also for an image without a map) + await rejects(`${name} gain map quality -1 without a map`, () => (name === 'jpeg' ? image.encodeJPEG : name === 'avif' ? image.encodeAVIF : image.encodeJXL).call(image, {gainMap: {quality: -1}}), RangeError); + await encode({gainMap: {quality: 1, scale: 0.5}}); + } + await rejects('encodeWebP alphaQuality 101', () => image.encodeWebP({alphaQuality: 101}), RangeError); + await rejects('encodeWebP lossy alphaQuality 101', () => image.encodeWebP({quality: 80, alphaQuality: 101}), RangeError); + await rejects('encodeWebP alphaQuality -1', () => image.encodeWebP({quality: 80, alphaQuality: -1}), RangeError); + } + + // boolean options take true or false only: a string like 'yes' is a TypeError, not true + { + const png = await image.encodePNG(); + const animation = new Animation([new Frame(image.clone()), new Frame(image.clone().invert())]); + const booleans = { + 'decode applyOrientation': () => Image.decode(png, {applyOrientation: 'no'}), 'decode applyColorProfile': () => Image.decode(png, {applyColorProfile: 0}), + 'decode gainMap': () => Image.decode(png, {gainMap: 'yes'}), 'Animation.decode applyOrientation': () => Animation.decode(png, {applyOrientation: 'no'}), + 'dominantColor ignoreBlack': () => image.dominantColor({ignoreBlack: 'yes'}), 'dominantColor ignoreWhite': () => image.dominantColor({ignoreWhite: 1}), + 'rotate expand': () => image.clone().rotate(45, {expand: 'no'}), 'transform expand': () => image.clone().transform([1, 0, 0, 1, 0, 0], {expand: 'no'}), + 'dropShadow expand': () => image.clone().dropShadow({expand: 'no'}), 'outline expand': () => image.clone().outline({expand: 'no'}), + 'encodeWebP sharpYuv': () => image.encodeWebP({quality: 80, sharpYuv: 'yes'}), 'encodeWebP lossless sharpYuv': () => image.encodeWebP({sharpYuv: 'yes'}), + 'encodeJPEG gainMap': () => image.encodeJPEG({gainMap: 'yes'}), 'encodeAVIF gainMap': () => image.encodeAVIF({gainMap: 'yes'}), 'encodeJXL gainMap': () => image.encodeJXL({gainMap: 'yes'}), + 'encodeGIF optimize': () => animation.encodeGIF({optimize: 'yes'}), 'encodeAPNG optimize': () => animation.encodeAPNG({optimize: 'yes'}), 'encodeWebP optimize': () => animation.encodeWebP({optimize: 'yes'}), + 'gifEncoder optimize': () => Animation.gifEncoder(8, 8, {optimize: 'yes'}), 'apngEncoder optimize': () => Animation.apngEncoder(8, 8, {optimize: 'yes'}), 'webpEncoder optimize': () => Animation.webpEncoder(8, 8, {optimize: 'yes'}), + 'renderText hinting': async () => Image.renderText('x', {font: await fs.readFile('./tests/fonts/opensans bold.ttf'), size: 12, hinting: 'yes'}) + }; + for (const [name, call] of Object.entries(booleans)) await rejects(name, call, TypeError); + // (the valid values keep working) + await Image.decode(png, {applyOrientation: false, applyColorProfile: false, gainMap: false}); + image.dominantColor({ignoreBlack: false, ignoreWhite: false}); + await image.encodeWebP({quality: 80, sharpYuv: true}); + await animation.encodeGIF({optimize: false}); + } + + // the type of an argument that isn't a number is a TypeError (the wrong number of values a RangeError) + { + const font = await fs.readFile('./tests/fonts/sourcesans3 regular.otf'); + await rejects('transform string', () => image.clone().transform('matrix(1 0 0 1 0 0)'), TypeError); + await rejects('transform 5 values', () => image.clone().transform([1, 0, 0, 1, 0]), RangeError); + await rejects('colorMatrix()', () => image.clone().colorMatrix(), TypeError); + await rejects('colorMatrix string', () => image.clone().colorMatrix('1 0 0'), TypeError); + await rejects('colorMatrix 8 values', () => image.clone().colorMatrix([1, 0, 0, 0, 1, 0, 0, 0]), RangeError); + await rejects('feature "on"', () => Image.renderText('x', {font, size: 12, features: {liga: 'on'}}), TypeError); + await rejects('feature 300', () => Image.renderText('x', {font, size: 12, features: {liga: 300}}), RangeError); + await rejects('variation "bold"', () => Image.renderText('x', {font, size: 12, variations: {weight: 'bold'}}), TypeError); + await rejects('variation NaN', () => Image.renderText('x', {font, size: 12, variations: {weight: NaN}}), RangeError); + await rejects('linearGradient without options', () => Image.linearGradient(4, 4), TypeError); + await rejects('radialGradient without options', () => Image.radialGradient(4, 4), TypeError); + await rejects('linearGradient without stops', () => Image.linearGradient(4, 4, {}), TypeError); + await rejects('Colors.gradient(5)', () => Colors.gradient(5), TypeError); + await rejects('metadata title 123', () => image.encodePNG({metadata: {title: 123}}), TypeError); + await rejects('metadata comment object', () => image.encodeJPEG({metadata: {comment: {}}}), TypeError); + await image.encodePNG({metadata: {title: '', comment: null}}); + } + + // software: null (and nothing else) writes no Exif block at all, not an empty one + for (const [name, encode] of Object.entries({jpeg: o => image.encodeJPEG(o), webp: o => image.encodeWebP(o), 'lossy webp': o => image.encodeWebP({quality: 80, ...o}), avif: o => image.encodeAVIF({effort: 0, ...o}), jxl: o => image.encodeJXL(o)})) { + const bare = await encode({metadata: {software: null}}); + if (has(bare, 'MM\0*')) panic(`${name}: software: null still writes an Exif block`); + if (!has(await encode({metadata: {software: null, author: 'me'}}), 'me')) panic(`${name}: the Exif block is missing with an author`); + const decoded = await Image.decode(bare); + if (decoded.width !== 8) panic(`${name}: the file without Exif doesn't decode`); + } + + // grayscale images are grayscale JPEGs (one component, a third the data), decoding to the same pixels as the color + // encoding does + { + const gray = new Image(32, 32).fill((x, y) => Colors.fromRGB(x * 8, x * 8, x * 8)); + const encoded = await gray.encodeJPEG({quality: 90}); + const sof = encoded.indexOf(0xc0, 2); + if (encoded[sof - 1] !== 0xff || encoded[sof + 8] !== 1) panic(`a gray image should be a one component JPEG, got ${encoded[sof + 8]} components`); + const decoded = await Image.decode(encoded); + for (let i = 0; i < decoded.bitmap.length; i += 4) + if (decoded.bitmap[i] !== decoded.bitmap[i + 1] || decoded.bitmap[i] !== decoded.bitmap[i + 2] || Math.abs(decoded.bitmap[i] - gray.bitmap[i]) > 4) panic('the grayscale JPEG decodes to other pixels'); + const color = gray.clone(); + color.setPixelAt(0, 0, 0xff0000ff); + const colorSof = (await color.encodeJPEG()).indexOf(0xc0, 2); + if ((await color.encodeJPEG())[colorSof + 8] !== 3) panic('an image with a colored pixel should be a 3 component JPEG'); + // (translucent gray pixels on a black background stay gray) + const translucent = gray.clone().opacity(0.5); + const t = await translucent.encodeJPEG(); + if (t[t.indexOf(0xc0, 2) + 8] !== 1) panic('a translucent gray image on black should be a grayscale JPEG'); + } + + // an SVG with a viewBox and one of width and height: the other follows the viewBox's aspect ratio (like browsers) + { + const svg = (attrs) => ``; + const byWidth = await Image.renderSVG(svg('viewBox="0 0 100 60" width="50"')); + if (byWidth.width !== 50 || byWidth.height !== 30) panic(`viewBox + width: ${byWidth.width}x${byWidth.height} instead of 50x30`); + if (byWidth.getPixelAt(49, 29) !== 0xff0000ff || byWidth.getPixelAt(0, 0) !== 0xff0000ff) panic('viewBox + width: the content should fill the image'); + const byHeight = await Image.renderSVG(svg('viewBox="0 0 100 60" height="30"')); + if (byHeight.width !== 50 || byHeight.height !== 30) panic(`viewBox + height: ${byHeight.width}x${byHeight.height} instead of 50x30`); + const both = await Image.renderSVG(svg('viewBox="0 0 100 60" width="50" height="60"')); + if (both.width !== 50 || both.height !== 60) panic('width and height given: both are used'); + const percent = await Image.renderSVG(svg('viewBox="0 0 100 60" width="50%"')); + if (percent.width !== 50 || percent.height !== 30) panic(`viewBox + width 50%: ${percent.width}x${percent.height} instead of 50x30`); + const none = await Image.renderSVG(svg('width="50"')); + if (none.width !== 50 || none.height !== 100) panic('without a viewBox the other side is the default 100'); + } + + // a right-to-left paragraph is aligned to the right by default (the start of its direction), a left-to-right one to + // the left; horizontalAlign overrides both + { + const fonts = await Promise.all(['opensans bold.ttf', 'noto naskh arabic subset.ttf'].map(name => fs.readFile(`./tests/fonts/${name}`))); + const inkEdges = image => { + let left = image.width, right = -1; + for (const [x, , color] of image.pixels()) if (color & 0xff) { left = Math.min(left, x); right = Math.max(right, x); } + return [left, right]; + }; + const arabic = await Image.renderText('مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم', {font: fonts, size: 24, width: 150}); + const [, arabicRight] = inkEdges(arabic.extract(0, 0, 150, 30)), [arabicLeft] = inkEdges(arabic); + if (arabicRight < 140) panic(`a right-to-left paragraph should start at the right edge, its first line ends at ${arabicRight}`); + if (arabicLeft < 2) panic('a wrapped right-to-left paragraph should be ragged on the left'); + const latin = await Image.renderText('Hello world hello world hello world hello', {font: fonts, size: 24, width: 150}); + if (inkEdges(latin.extract(0, 0, 150, 30))[0] > 6) panic('a left-to-right paragraph starts at the left'); + const forcedLeft = await Image.renderText('مرحبا بالعالم', {font: fonts, size: 24, width: 150, horizontalAlign: 'left'}); + if (inkEdges(forcedLeft)[0] > 6) panic('horizontalAlign left places right-to-left text on the left'); + // each paragraph by its own direction + const mixed = await Image.renderText('Hello\nمرحبا', {font: fonts, size: 24, width: 150}); + const lineHeight = mixed.height / 2; + if (inkEdges(mixed.extract(0, 0, 150, lineHeight))[0] > 6 || inkEdges(mixed.extract(0, lineHeight, 150, lineHeight))[1] < 140) panic('mixed paragraphs should each start at their own side'); + } +})(); diff --git a/tests/user-report-4.js b/tests/user-report-4.js new file mode 100644 index 00000000..f6926725 --- /dev/null +++ b/tests/user-report-4.js @@ -0,0 +1,149 @@ +const fs = require('fs').promises; +const {Image, Animation, Frame, Colors} = require('..'); + +const panic = message => { + console.error(message); + process.exit(1); +}; +const rejects = async (name, fn, Type) => { + try { + await fn(); + } catch (error) { + if (!(error instanceof Type)) panic(`${name}: wrong error ${error?.constructor?.name}: ${error?.message}`); + return; + } + panic(`${name}: accepted`); +}; + +(async () => { + const image = new Image(8, 8).fill((x, y) => Colors.fromRGB(x * 30, y * 30, 128)); + + // PNG chunks with a bad checksum: metadata chunks are skipped (like libpng and browsers), the image's own are an error + { + const png = Buffer.from(await image.encodePNG({metadata: {title: 'Sunset'}})); + const find = type => { + for (let i = 8; i < png.length;) { + const length = png.readUInt32BE(i); + if (png.toString('latin1', i + 4, i + 8) === type) return i; + i += 12 + length; + } + panic(`no ${type} chunk`); + }; + const broken = type => { + const copy = Buffer.from(png), i = find(type); + copy[i + 8 + copy.readUInt32BE(i)] ^= 0xff; + return copy; + }; + const skipped = await Image.decode(broken('tEXt')); + if (!Buffer.from(skipped.bitmap).equals(Buffer.from(image.bitmap))) panic('a bad checksum on a text chunk should be skipped'); + await rejects('bad checksum on IDAT', () => Image.decode(broken('IDAT')), Error); + await rejects('bad checksum on IHDR', () => Image.decode(broken('IHDR')), Error); + } + + // JPEG: corrupt entropy data in a scan with restart markers decodes on from the next marker (like libjpeg), without + // markers nothing can resync, so it is an error + { + const restart = await fs.readFile('./tests/jpegs/restart.jpg'); + const clean = await Image.decode(restart); + const markers = []; + for (let i = 0; i < restart.length - 1; i++) if (restart[i] === 0xff && restart[i + 1] >= 0xd0 && restart[i + 1] <= 0xd7) markers.push(i); + if (markers.length < 2) panic('restart.jpg should have restart markers'); + const damaged = Buffer.from(restart), from = markers[0] + 2 + (markers[1] - markers[0] >> 2), count = markers[1] - markers[0] >> 2; + for (let i = 0; i < count; i++) damaged[from + i] = i & 1 ? 0 : 0xff; + const decoded = await Image.decode(damaged); + if (decoded.width !== clean.width || decoded.height !== clean.height) panic('a damaged restart interval changed the size'); + let same = 0; + for (let i = 0; i < clean.bitmap.length; i += 4) + if (clean.bitmap[i] === decoded.bitmap[i] && clean.bitmap[i + 1] === decoded.bitmap[i + 1] && clean.bitmap[i + 2] === decoded.bitmap[i + 2]) same++; + if (same < clean.width * clean.height * 0.7) panic(`a damaged restart interval should leave the other intervals intact: ${same} of ${clean.width * clean.height} pixels unchanged`); + // an interval whose data is cut short (the decoder reads into the next marker) is damage too, not a cut-off file + const shortened = Buffer.concat([restart.subarray(0, markers[0] + 40), restart.subarray(markers[1] - 10)]); + if ((await Image.decode(shortened)).width !== clean.width) panic('a shortened restart interval changed the size'); + const cut = Buffer.concat([restart.subarray(0, markers[1] + 40), Buffer.from([0xff, 0xd9])]); + await rejects('a scan cut off after a restart marker', () => Image.decode(cut), Error); + + const plain = (await Promise.all((await fs.readdir('./tests/jpegs')).filter(name => name.endsWith('.jpg')).map(name => fs.readFile(`./tests/jpegs/${name}`)))) + .find(data => data.indexOf(Buffer.from([0xff, 0xdd])) < 0 && data.indexOf(Buffer.from([0xff, 0xda])) > 0 && data.length > data.indexOf(Buffer.from([0xff, 0xda])) + 400); + if (!plain) panic('no JPEG fixture without restart markers'); + const scan = plain.indexOf(Buffer.from([0xff, 0xda])) + 2 + plain.readUInt16BE(plain.indexOf(Buffer.from([0xff, 0xda])) + 2); + const damagedPlain = Buffer.from(plain); + for (let i = 0; i < 60; i++) damagedPlain[scan + 150 + i] = i & 1 ? 0 : 0xff; + await rejects('corrupt scan data without restart markers', () => Image.decode(damagedPlain), Error); + } + + // a fully transparent image round-trips through BMP: the file declares its alpha mask, so its zeros are alpha + { + const back = await Image.decode(await new Image(3, 2).encodeBMP()); + if (back.bitmap[3] !== 0) panic('a fully transparent BMP decoded as opaque'); + const half = await Image.decode(await new Image(3, 2).fill(0xff000080).encodeBMP()); + if (half.bitmap[3] !== 0x80) panic('BMP alpha lost'); + } + + // a right-to-left line with a space at its wrap point (which sits at its visual left) is placed by its ink + { + const font = await fs.readFile('./tests/fonts/noto naskh arabic subset.ttf'); + const inkLeft = image => { + let left = image.width; + for (const [x, , color] of image.pixels()) if (color & 0xff) left = Math.min(left, x); + return left; + }; + const word = await Image.renderText('مرحبا', {font, size: 28, width: 120, horizontalAlign: 'left'}); + const spaced = await Image.renderText('مرحبا ', {font, size: 28, width: 120, horizontalAlign: 'left'}); + if (inkLeft(spaced) !== inkLeft(word)) panic(`a trailing space moved a left-aligned right-to-left line: ${inkLeft(spaced)} instead of ${inkLeft(word)}`); + const wrapped = await Image.renderText('مرحبا بالعالم', {font, size: 28, width: 90, horizontalAlign: 'left'}); + if (inkLeft(wrapped.extract(0, 0, 90, 36)) > 3) panic('the first line of a wrapped right-to-left paragraph should be flush left'); + const centered = await Image.renderText('مرحبا ', {font, size: 28, width: 120, horizontalAlign: 'center'}); + const centeredWord = await Image.renderText('مرحبا', {font, size: 28, width: 120, horizontalAlign: 'center'}); + if (Math.abs(inkLeft(centered) - inkLeft(centeredWord)) > 1) panic('a trailing space moved a centered right-to-left line'); + const right = await Image.renderText('مرحبا ', {font, size: 28, width: 120}); + if (right.width !== 120 || inkLeft(right) < 40) panic('right alignment changed'); + } + + // renderSVG() refuses null sizes (a null width gave a 1x1 image, a null scale was ignored) + { + const svg = ''; + await rejects('renderSVG width null', () => Image.renderSVG(svg, {width: null}), TypeError); + await rejects('renderSVG height null', () => Image.renderSVG(svg, {height: null}), TypeError); + await rejects('renderSVG scale null', () => Image.renderSVG(svg, {scale: null}), TypeError); + if ((await Image.renderSVG(svg, {width: 100})).height !== 60) panic('renderSVG width'); + } + + // more values of the wrong type are TypeErrors, with a designed message + { + const font = await fs.readFile('./tests/fonts/sourcesans3 regular.otf'); + await rejects('renderText width string', () => Image.renderText('Hi', {font, size: 20, width: '300'}), TypeError); + await rejects('renderText height null', () => Image.renderText('Hi', {font, size: 20, height: null}), TypeError); + await rejects('transform string value', () => image.clone().transform([1, 0, 0, 1, 0, '0']), TypeError); + await rejects('colorMatrix string value', () => image.clone().colorMatrix([1, 0, 0, 0, 1, 0, 0, 0, '1']), TypeError); + await rejects('gifEncoder string width', () => Animation.gifEncoder('64', 64), TypeError); + await rejects('apngEncoder string height', () => Animation.apngEncoder(64, '64'), TypeError); + await rejects('Animation canvas string', () => new Animation([new Frame(image)], {width: '8', height: 8}), TypeError); + await rejects('transform origin null', () => image.clone().transform([1, 0, 0, 1, 0, 0], {origin: null}), TypeError); + await rejects('transform origin number', () => image.clone().transform([1, 0, 0, 1, 0, 0], {origin: 0}), TypeError); + await rejects('Animation frames NaN', () => new Animation(NaN), TypeError); + await rejects('Animation frames null', () => new Animation(null), TypeError); + await rejects('decode null', () => Image.decode(null), TypeError); + await rejects('linearGradient without stops', () => Image.linearGradient(4, 4, {}), TypeError); + await rejects('radialGradient without stops', () => Image.radialGradient(4, 4, {}), TypeError); + const messages = []; + for (const fn of [() => Image.renderText('Hi', {font, size: 20, width: {}}), () => image.clone().resize(2, 2, {mode: {}}), () => new Animation(null), () => Image.decode(null), () => image.clone().transform([1, 0, 0, 1, 0, 0], {origin: null})]) { + try { + await fn(); + panic('a wrong type was accepted'); + } catch (error) { + messages.push(error.message); + } + } + for (const message of messages) if (/\[object|Cannot read|not of type|undefined/.test(message)) panic(`raw message: ${message}`); + } + + // options can't be arrays, metadata can't be null or an array + { + await rejects('encodePNG array options', () => image.encodePNG([1]), TypeError); + await rejects('decode array options', async () => Image.decode(await image.encodePNG(), [1]), TypeError); + await rejects('resize array options', () => image.clone().resize(4, 4, []), TypeError); + await rejects('metadata null', () => image.encodePNG({metadata: null}), TypeError); + await rejects('metadata array', () => image.encodeJPEG({metadata: ['Sunset']}), TypeError); + if ((await image.encodePNG({metadata: {}})).length < 50) panic('metadata {}'); + } +})(); diff --git a/tests/util/damaged-font.js b/tests/util/damaged-font.js new file mode 100644 index 00000000..d32f9437 --- /dev/null +++ b/tests/util/damaged-font.js @@ -0,0 +1,36 @@ +// Renders text with the font in the file given as the first argument, directly (`text`), through an SVG's @font-face +// (`svg`, which is how an untrusted font reaches the parser) or through renderSVG's `font` option (`option`), and prints +// `ok` when that rendered or ended with a plain Error, or what it ended with otherwise. A font that renderText refuses +// has to be refused in the `font` option too: a font given there isn't left out without a word, like one of an SVG (a LimitError is no answer to a damaged font: its size isn't damaged data). Run by tests/damaged-fonts.js in a process of its own, because +// a hang or a V8 abort can't be caught inside the process that has to report it +const fs = require('fs'); + +(async () => { + const {Image} = await import('../../dist/index.js'); + const [file, via] = process.argv.slice(2); + const font = fs.readFileSync(file); + // (U+E000 is the bitmap glyph of tests/fonts/sbix.ttf) + const text = 'Hello ffi مرحبا 🙂 \u{1F600}\uFE0F 葛\u{E0100} \uE000'; + try { + if (via === 'option' || via === 'mixed') { + let refused = false; + try { + await Image.renderText(text, {font, size: 40}); + } catch { + refused = true; + } + // (mixed: the SVG embeds a font of its own too, for another family: that mustn't change what the caller's + // damaged font gives) + const embedded = via === 'mixed' ? `` : ''; + await Image.renderSVG(`${embedded}${text}`, {font}); + if (refused) return console.log('renderSVG used a font in its font option that renderText refuses'); + } else if (via === 'svg') { + await Image.renderSVG(`${text}`); + } else { + await Image.renderText(text, {font, size: 40}); + } + console.log('ok'); + } catch (error) { + console.log(error.constructor === Error ? 'ok' : `${error.name}: ${error.message}`); + } +})(); diff --git a/tests/util/render-svg.js b/tests/util/render-svg.js new file mode 100644 index 00000000..f6e24714 --- /dev/null +++ b/tests/util/render-svg.js @@ -0,0 +1,16 @@ +// Renders the SVG given as the first argument (a file) and prints `ok`, the class and message of the error it ended +// with, and the peak memory in MB. Run by tests/svg-arcs.js in a process of its own: a fatal out-of-memory can't be +// caught inside the process that has to report it +const fs = require('fs'); + +(async () => { + const {Image} = await import('../../dist/index.js'); + const svg = fs.readFileSync(process.argv[2], 'utf8'); + let result = 'ok'; + try { + await Image.renderSVG(svg, {...(/width="10"/.test(svg) ? {maxPixels: 100} : /width="4000"/.test(svg) ? {} : {width: 50}), font: fs.readFileSync(svg.includes('font-family="carbon"') ? './tests/fonts/carbon phyber.ttf' : svg.includes('font-family="emoji"') ? './tests/fonts/resvg/NotoColorEmojiCBDT.subset.ttf' : './tests/fonts/resvg/NotoSans-Regular.ttf')}); + } catch (error) { + result = `${error.name}: ${error.message}`; + } + console.log(JSON.stringify({result, mb: Math.round(process.memoryUsage().rss / 2 ** 20)})); +})(); diff --git a/tests/util/resvg.js b/tests/util/resvg.js index 1e3dad30..8f32db45 100644 --- a/tests/util/resvg.js +++ b/tests/util/resvg.js @@ -12,11 +12,11 @@ const fonts = async () => { // test cases of resvg (tests/svgs/resvg, see its LICENSE) next to resvg's renderings, of the directories some returns // true for. Antialiasing differs a little: at most 0.5% of the pixels may differ by more than 24 (premultiplied) module.exports = async (some, panic) => { - const root = './tests/svgs/resvg', options = {mode: Image.SVG_MODE_WIDTH, fonts: await fonts()}; + const root = './tests/svgs/resvg', options = {font: await fonts()}; const files = (await fs.readdir(root, {recursive: true})).filter(f => f.endsWith('.svg') && some(f.replace(/\\/g, '/'))); for (const file of files) { const reference = await Image.decode(await fs.readFile(`${root}/${file.replace(/\.svg$/, '.png')}`)); - const image = await Image.renderSVG(await fs.readFile(`${root}/${file}`, 'utf8'), {...options, size: reference.width}); + const image = await Image.renderSVG(await fs.readFile(`${root}/${file}`, 'utf8'), {...options, width: reference.width}); if (image.width !== reference.width || image.height !== reference.height) panic(`resvg ${file}: ${image.width}x${image.height} instead of ${reference.width}x${reference.height}`); const a = image.bitmap, b = reference.bitmap; let differing = 0; diff --git a/tests/util/without-native.js b/tests/util/without-native.js index f43ccff0..61f6b013 100644 --- a/tests/util/without-native.js +++ b/tests/util/without-native.js @@ -22,15 +22,15 @@ if (mode === 'plain') { const image = await Image.decode(fs.readFileSync('./tests/targets/image.png')); results.decoded = sha256(image.bitmap); for (let level = 0; level <= 9; level++) { - const encoded = await image.encode({compression: level, metadata: {creationTime: 0, software: ''}}); + const encoded = await image.encodePNG({compression: level, metadata: {creationTime: 0, software: ''}}); // the output differs between the deflaters, the pixels must not results[`level ${level}`] = sha256((await Image.decode(encoded)).bitmap); } for (const file of fs.readdirSync('./tests/pngsuite').filter(f => f.endsWith('.png'))) // also the damaged ones, which have to fail the same way - results[file] = await Image.decode(fs.readFileSync(`./tests/pngsuite/${file}`)).then(image => sha256(image.bitmap), error => error.message); - const animation = await Animation.decode(await new Animation([Frame.from(image.clone().resize(32, 32)), Frame.from(image.clone().resize(32, 32).invert())]).encodeAPNG()); - results.apng = sha256(animation.frames[1].bitmap); + results[file] = await Image.decode(fs.readFileSync(`./tests/pngsuite/${file}`)).then(image => sha256(image.bitmap), error => error.constructor.name); + const animation = await Animation.decode(await new Animation([new Frame(image.clone().resize(32, 32)), new Frame(image.clone().resize(32, 32).invert())]).encodeAPNG()); + results.apng = sha256(animation.frames[1].image.bitmap); console.log(JSON.stringify(results)); })().catch(error => { console.error(error); diff --git a/tests/webp-lossy.js b/tests/webp-lossy.js index 65931409..a79c1215 100644 --- a/tests/webp-lossy.js +++ b/tests/webp-lossy.js @@ -1,6 +1,6 @@ const fs = require('fs').promises; const crypto = require('crypto'); -const {Image, Animation, Frame} = require('..'); +const {Image, Animation, Frame, Colors} = require('..'); const panic = message => { console.error(message); @@ -120,29 +120,32 @@ const alphaReferences = { // noisy alpha: stored uncompressed (smaller than compressed), still lossless let seed = 1; const random = () => (seed = seed * 1103515245 + 12345 >>> 0) >>> 24; - const noisy = new Image(24, 24).fill((x, y) => Image.rgbaToColor(x * 10, y * 10, 99, random())); + const noisy = new Image(24, 24).fill((x, y) => Colors.fromRGBA(x * 10, y * 10, 99, random())); const noisyWebp = await noisy.encodeWebP({quality: 50}); if (chunks(noisyWebp).ALPH[0] !== 0) panic('noisy alpha should be stored uncompressed and unfiltered'); const noisyBack = await Image.decode(noisyWebp); for (let i = 3; i < noisy.bitmap.length; i += 4) if (noisyBack.bitmap[i] !== noisy.bitmap[i]) panic('noisy alpha: differs'); - // the quality and effort are validated, lossless stays the default + // the quality is validated, and lossless stays the default const image = new Image(20, 10).fill(0x336699ff); for (const quality of [-1, 101, NaN]) { if (!await image.encodeWebP({quality}).then(() => false, e => e instanceof RangeError)) panic(`quality ${quality} should throw`); } - for (const effort of [-1, 7, 1.5]) { - if (!await image.encodeWebP({quality: 75, effort}).then(() => false, e => e instanceof RangeError)) panic(`effort ${effort} should throw`); - } if (!chunks(await image.encodeWebP()).VP8L) panic('without a quality WebPs should be lossless'); + // quality 100 is lossless like it is for AVIF and JPEG XL, 99 is the best lossy quality + const photo = new Image(24, 16).fill((x, y) => Colors.fromRGBA(x * 10, y * 15, (x * 7 + y * 3) % 256, 255)); + if (!chunks(await photo.encodeWebP({quality: 100})).VP8L) panic('quality 100 should be lossless'); + if (!chunks(await photo.encodeWebP({quality: 99}))['VP8 ']) panic('quality 99 should be lossy'); + if (!String.fromCharCode(...await new Animation([new Frame(photo)]).encodeWebP({quality: 100})).includes('VP8L')) panic('an animation with quality 100 should be lossless'); + // lossy animations const frames = [0xff0000ff, 0x00ff00ff, 0x0000ff80].map((color, i) => { const frame = new Image(40, 30).fill(color); - frame.drawBox(i * 10, 5, 10, 10, 0xffffffff); + frame.composite(new Image(10, 10).fill(0xffffffff), {x: i * 10, y: 5}); return frame; }); - const animation = new Animation(frames.map(f => Frame.from(f, 100)), 0); + const animation = new Animation(frames.map(f => new Frame(f.clone(), {duration: 100})), {loopCount: 0}); const lossy = await animation.encodeWebP({quality: 80}); const decoded = await Animation.decode(lossy); if (decoded.length !== 3) panic(`lossy animation: ${decoded.length} frames instead of 3`); @@ -150,14 +153,14 @@ const alphaReferences = { // (the last frame is half transparent: it's blended over the one before) const lossless = await Animation.decode(await animation.encodeWebP()); for (let f = 0; f < 3; f++) { - const [r, g, b, a] = Image.colorToRGBA(decoded[f].getPixelAt(1, 1)); - const [er, eg, eb, ea] = Image.colorToRGBA(lossless[f].getPixelAt(1, 1)); + const [r, g, b, a] = Colors.toRGBA(decoded.frames[f].image.getPixelAt(1, 1)); + const [er, eg, eb, ea] = Colors.toRGBA(lossless.frames[f].image.getPixelAt(1, 1)); if (Math.abs(r - er) + Math.abs(g - eg) + Math.abs(b - eb) > 12 || a !== ea) panic(`lossy animation: frame ${f} decodes to ${[r, g, b, a]}`); } if (!await animation.encodeWebP({quality: 200}).then(() => false, e => e instanceof RangeError)) panic('animation quality 200 should throw'); // alphaQuality for animations, also encoded a frame at a time - const faded = new Animation([0, 1].map(i => Frame.from(new Image(40, 30).fill((x, y) => Image.rgbaToColor(200, 50 * i, 9, x * 6 + y)), 100)), 0); + const faded = new Animation([0, 1].map(i => new Frame(new Image(40, 30).fill((x, y) => Colors.fromRGBA(200, 50 * i, 9, Math.min(x * 6 + y, 255))), {duration: 100})), {loopCount: 0}); // (the same creation time: it's written in seconds, two encodes can be a second apart) const metadata = {creationTime: 0}; const fadedWebp = await faded.encodeWebP({quality: 80, alphaQuality: 0, optimize: false, metadata}); @@ -166,7 +169,7 @@ const alphaReferences = { if (sha256(await encoder.finish()) !== sha256(fadedWebp)) panic('alphaQuality: the incremental encoder writes another file'); for (const frame of await Animation.decode(fadedWebp)) { const levels = new Set(); - for (let i = 3; i < frame.bitmap.length; i += 4) levels.add(frame.bitmap[i]); + for (let i = 3; i < frame.image.bitmap.length; i += 4) levels.add(frame.image.bitmap[i]); if (levels.size > 2) panic(`alphaQuality 0: ${levels.size} alpha levels instead of 2`); } if (!await faded.encodeWebP({quality: 80, alphaQuality: 101}).then(() => false, e => e instanceof RangeError)) panic('animation alphaQuality 101 should throw'); diff --git a/tests/webp.js b/tests/webp.js index 9c9fa3c9..6d79f8b0 100644 --- a/tests/webp.js +++ b/tests/webp.js @@ -1,6 +1,6 @@ const fs = require('fs').promises; const crypto = require('crypto'); -const {Image, Animation, ImageType, decode} = require('..'); +const {Image, Animation, ImageType, decode, Colors} = require('..'); const panic = message => { console.error(message); @@ -36,20 +36,17 @@ const animated = [ if (sha256(image.bitmap) !== hash) panic(`${name}: decoded pixels don't match libwebp`); } - // animated WebPs: Image.decode refuses them, Animation.decode composites the frames + // animated WebPs: Image.decode gives the first frame as libwebp composites it, Animation.decode all of them const data = await fs.readFile('./tests/webp/animated.webp'); - try { - await Image.decode(data); - panic('Image.decode should reject animated WebPs'); - } catch (err) { - if (!/Animation\.decode/.test(err.message)) panic(`unexpected error ${err.message}`); - } + const firstFrame = await Image.decode(data); + if (firstFrame.constructor !== Image || firstFrame.width !== 96 || firstFrame.height !== 72) panic('animated WebP: Image.decode should give an Image of the canvas'); + if (sha256(firstFrame.bitmap) !== animated[0]) panic('animated WebP: Image.decode is not the first frame libwebp composites'); const animation = await Animation.decode(data); if (!(await decode(data) instanceof Animation)) panic('decode() should return an Animation for animated WebPs'); - if (animation.length !== 4 || animation.loopCount !== -1) panic('animated WebP: wrong frame or loop count'); - if (animation.map(f => f.duration).join() !== '80,120,80,200') panic('animated WebP: wrong durations'); - animation.forEach((frame, i) => { - if (sha256(frame.bitmap) !== animated[i]) panic(`animated WebP: frame ${i} doesn't match libwebp`); + if (animation.length !== 4 || animation.loopCount !== Infinity) panic('animated WebP: wrong frame or loop count'); + if (animation.frames.map(f => f.duration).join() !== '80,120,80,200') panic('animated WebP: wrong durations'); + animation.frames.forEach((frame, i) => { + if (sha256(frame.image.bitmap) !== animated[i]) panic(`animated WebP: frame ${i} doesn't match libwebp`); }); // filtered alpha (horizontal, vertical, gradient), from libwebp-test-data @@ -69,7 +66,7 @@ const animated = [ ]; if (blended.length !== 4) panic('blended WebP: wrong frame count'); blended.frames.forEach((frame, i) => { - if (sha256(frame.bitmap) !== blendedHashes[i]) panic(`blended WebP: frame ${i} doesn't match libwebp`); + if (sha256(frame.image.bitmap) !== blendedHashes[i]) panic(`blended WebP: frame ${i} doesn't match libwebp`); }); // lossless encoding: photo-like content (predictor), few colors (palette), alpha, odd sizes @@ -77,7 +74,7 @@ const animated = [ const cases = [ photo, new Image(37, 23).fill((x, y) => (x ^ y) & 4 ? 0xff0000ff : 0x00000000), - new Image(64, 9).fill((x, y) => Image.rgbaToColor(x * 4, y * 28, 7, (x * 9) & 255)), + new Image(64, 9).fill((x, y) => Colors.fromRGBA(x * 4, y * 28, 7, (x * 9) & 255)), new Image(1, 1).fill(0x12345678) ]; // (every effort: 0 the fast mode, 1 without comparing the reference searches, 2 and up all of it) @@ -92,15 +89,13 @@ const animated = [ } // (the photo: the fast mode a bit larger, effort 6 the same as 2) if (!(sizes[0] > sizes[2] && sizes[0] < sizes[2] * 1.25) || sizes[6] !== sizes[2]) panic(`encodeWebP: unexpected sizes by effort ${JSON.stringify(sizes)}`); - for (const effort of [-1, 7, 1.5]) if (!await photo.encodeWebP({effort}).then(() => false, e => e instanceof RangeError)) panic(`effort ${effort} should throw`); // threads (the predictors and prefix groups searched in parallel, from 1.5 megapixels on): the same file as without { - const big = new Image(1448, 1448).fill((x, y) => Image.rgbaToColor(x * 7 + y & 255, (x * x + y * 3) >> 4 & 255, (x ^ y) & 255, 255)); + const big = new Image(1448, 1448).fill((x, y) => Colors.fromRGBA(x * 7 + y & 255, (x * x + y * 3) >> 4 & 255, (x ^ y) & 255, 255)); const metadata = {creationTime: 0}; for (const effort of [0, 1, 2]) { const one = await big.encodeWebP({threads: 1, metadata, effort}), four = await big.encodeWebP({threads: 4, metadata, effort}); if (Buffer.compare(Buffer.from(one), Buffer.from(four))) panic(`encodeWebP: threads changed the file at effort ${effort}`); } - for (const threads of [0, 1.5]) if (!await big.encodeWebP({threads}).then(() => false, e => e instanceof RangeError)) panic(`threads ${threads} should throw`); } })(); diff --git a/tests/zlib.js b/tests/zlib.js index b5a67377..704ecb29 100644 --- a/tests/zlib.js +++ b/tests/zlib.js @@ -40,7 +40,7 @@ const panic = message => { decompress(new Uint8Array(data), 10); panic(`zlib: an invalid ${name} should throw`); } catch (error) { - if (!/zlib/.test(error.message)) panic(`zlib: an invalid ${name} threw ${error.message}`); + if (!(error instanceof Error)) panic(`zlib: an invalid ${name} threw ${error}`); } // whole images through the paths other runtimes take: CompressionStream (levels 1-6) and DecompressionStream as in diff --git a/tsconfig.json b/tsconfig.json index 16267c1d..9719072d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,8 +5,8 @@ "es2022" ], "types": [], - "module": "es2022", - "moduleResolution": "node", + "module": "esnext", + "moduleResolution": "bundler", "strict": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true,