Skip to content

Commit c17f4ca

Browse files
committed
check pixel limits and threads in options.ts
1 parent edd908f commit c17f4ca

5 files changed

Lines changed: 39 additions & 14 deletions

File tree

‎src/animation.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { ImageType } from './image-type.ts';
1212
import { optimize, OptimizeOptions, OptimizedFrame } from './util/optimize.ts';
1313
import { paletteOptions } from './codecs/quantize.ts';
1414
import { resolveMetadata, pngText, exifData, gifComments } from './metadata.ts';
15-
import { checkOptions, oneOf, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, color as checkColor } from './util/options.ts';
15+
import { checkOptions, oneOf, pixelLimit, checkThreads, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, color as checkColor } from './util/options.ts';
1616
import { MAX_PIXELS, decoding } from './util/limits.ts';
1717
import { AnimationEncoder } from './animation-encoder.ts';
1818

@@ -653,8 +653,8 @@ export class Animation {
653653
// (checked outside of decoding(), which reports RangeErrors as damaged data)
654654
checkOptions(options, 'Animation.decode(data, { maxPixels: 1e8 })');
655655
const { maxPixels = MAX_PIXELS, threads = 1 } = options;
656-
if (!Number.isInteger(threads) || threads < 1) throw new RangeError(`threads must be a positive integer, not ${threads}`);
657-
if (!(Number(maxPixels) > 0)) throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
656+
checkThreads(threads);
657+
pixelLimit(maxPixels);
658658
const { toneMapping = 'reinhard' } = options;
659659
oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
660660
return decoding(() => Animation.__decode__(input, options));

‎src/gainmap.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { MAX_PIXELS, decoding } from './util/limits.ts';
44
import * as jpeg from './codecs/jpeg.ts';
55
import * as codec from './codecs/gainmap.ts';
66
import { BinaryData, view } from './util/mem.ts';
7-
import { finite, checkOptions, quality as checkQuality } from './util/options.ts';
7+
import { finite, checkOptions, pixelLimit, quality as checkQuality } from './util/options.ts';
88

99
/** Options of {@link GainMap.encodeJPEG} */
1010
export interface GainMapEncodeOptions {
@@ -363,7 +363,7 @@ export class GainMap {
363363
static async decode(data: BinaryData, options: Pick<DecodeOptions, 'maxPixels'> = {}): Promise<GainMap> {
364364
checkOptions(options, 'GainMap.decode(data, { maxPixels: 1e8 })');
365365
const { maxPixels = MAX_PIXELS } = options;
366-
if (!(Number(maxPixels) > 0)) throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
366+
pixelLimit(maxPixels);
367367
const bytes = view(data);
368368
return decoding(() => {
369369
const found = codec.find(bytes);

‎src/image.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,6 @@ import { availableThreads } from './util/threads.ts';
1515

1616
// (worker threads: the processors available, at most 8)
1717
const defaultThreads = (): number => Math.max(1, Math.min(availableThreads(), 8));
18-
const checkThreads = (threads: number): void => {
19-
if (!Number.isInteger(threads) || threads < 1) throw new RangeError(`threads must be a positive integer, not ${threads}`);
20-
};
2118
import * as jxl from './codecs/jxl.ts';
2219
import type { ToneMapping } from './codecs/hdr.ts';
2320
import * as quantize from './codecs/quantize.ts';
@@ -32,7 +29,7 @@ import { encode as utf8 } from './util/utf8.ts';
3229
import { resample, BOX, TRIANGLE, CUBIC, type Region } from './util/resample.ts';
3330
import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from './util/blur.ts';
3431
import { Colors, wrapHue, hue2rgb } from './colors.ts';
35-
import { isOptions, checkOptions, finite, oneOf, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from './util/options.ts';
32+
import { isOptions, checkOptions, finite, oneOf, pixelLimit, checkThreads, color as checkColor, quality as checkQuality, effort as checkEffort, compressionLevel } from './util/options.ts';
3633
import { MAX_PIXELS, LimitError, decoding } from './util/limits.ts';
3734
import { GainMap } from './gainmap.ts';
3835
import * as gain from './util/gain.ts';
@@ -2629,7 +2626,7 @@ export class Image {
26292626
checkOptions(options, 'Image.decode(data, { maxPixels: 1e8 })');
26302627
const { applyOrientation = true, applyColorProfile = true, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = defaultThreads(), gainMap = true } = options;
26312628
checkThreads(threads);
2632-
if (!(Number(maxPixels) > 0)) throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
2629+
pixelLimit(maxPixels);
26332630
oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
26342631
const data = view(input);
26352632
const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);
@@ -2763,10 +2760,10 @@ export class Image {
27632760
static async renderSVG(svg: string | BinaryData, options: RenderSVGOptions = {}): Promise<Image> {
27642761
checkOptions(options, 'renderSVG(svg, { width: 512 })');
27652762
const { width: givenWidth, height: givenHeight, scale, maxPixels = MAX_PIXELS, font: fonts = [], images: givenImages = {} } = options;
2766-
if (!(Number(maxPixels) > 0)) throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
2763+
pixelLimit(maxPixels);
27672764
const { maxLayerPixels = 4 * Number(maxPixels), maxImagePixels = Number(maxPixels) } = options;
2768-
if (!(Number(maxLayerPixels) > 0)) throw new RangeError(`maxLayerPixels must be a positive number, not ${maxLayerPixels}`);
2769-
if (!(Number(maxImagePixels) > 0)) throw new RangeError(`maxImagePixels must be a positive number, not ${maxImagePixels}`);
2765+
pixelLimit(maxLayerPixels, 'maxLayerPixels');
2766+
pixelLimit(maxImagePixels, 'maxImagePixels');
27702767
const sizes = [givenWidth, givenHeight, scale].filter(value => value !== undefined).length;
27712768
if (sizes > 1) throw new TypeError('renderSVG() takes one of width, height and scale');
27722769
const mode = givenWidth !== undefined ? 'width' : givenHeight !== undefined ? 'height' : 'scale';
@@ -2841,7 +2838,7 @@ export class Image {
28412838
if (typeof text !== 'string' || !isOptions(options)) throw new TypeError('renderText() takes the text and an options object, like renderText(\'Hello\', { font, size: 32 })');
28422839
if (options.font === undefined) throw new TypeError('renderText(text, options) needs the font in the options');
28432840
const { font, color = 0xffffffff, strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {}, variations = {}, maxPixels = MAX_PIXELS } = options;
2844-
if (!(Number(maxPixels) > 0)) throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
2841+
pixelLimit(maxPixels);
28452842
const { width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign } = options;
28462843
const layout = textLayout({ width: boxWidth, height: boxHeight, wrapStyle, horizontalAlign, verticalAlign });
28472844
const axes = textRenderer.axisValues(variations);

‎src/util/options.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,17 @@ export function quality(value: number, name = 'quality'): number {
9393
return q;
9494
}
9595

96+
/** A limit of pixels (`maxPixels`, ...): a number above 0, `Infinity` lifts it. Returns it as a number */
97+
export function pixelLimit(value: number, name = 'maxPixels'): number {
98+
if (!(Number(value) > 0)) throw new RangeError(`${name} must be a positive number, not ${value}`);
99+
return Number(value);
100+
}
101+
102+
/** The `threads` option: a whole number of at least 1 */
103+
export function checkThreads(threads: number): void {
104+
if (!Number.isInteger(threads) || threads < 1) throw new RangeError(`threads must be a positive integer, not ${threads}`);
105+
}
106+
96107
/** An effort argument: an integer from 0 to max */
97108
export function effort(value: number, max: number): number {
98109
if (!Number.isInteger(value) || value < 0 || value > max) throw new RangeError(`effort must be an integer 0-${max}, not ${value}`);

‎tests/option-checks.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,23 @@ const rejects = async (name, fn, Type, pattern) => {
7373
await rejects(`Animation.decode maxPixels ${maxPixels}`, () => Animation.decode(png, {maxPixels}), RangeError, /maxPixels/);
7474
}
7575
await rejects('Animation.decode threads 0', () => Animation.decode(png, {threads: 0}), RangeError, /threads must be/);
76+
// (the shared checks of the limits and of threads: every option that takes one says so by its name)
77+
{
78+
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"/>';
79+
const font = require('fs').readFileSync('./tests/fonts/opensans bold.ttf');
80+
const map = await new Image(8, 8).fill(0x808080ff).encodeJPEG();
81+
for (const bad of [0, -1, NaN]) {
82+
await rejects(`renderSVG maxLayerPixels ${bad}`, () => Image.renderSVG(svg, {maxLayerPixels: bad}), RangeError, /maxLayerPixels must be a positive number/);
83+
await rejects(`renderSVG maxImagePixels ${bad}`, () => Image.renderSVG(svg, {maxImagePixels: bad}), RangeError, /maxImagePixels must be a positive number/);
84+
await rejects(`renderText maxPixels ${bad}`, () => Image.renderText('a', {font, size: 12, maxPixels: bad}), RangeError, /maxPixels must be a positive number/);
85+
await rejects(`GainMap.decode maxPixels ${bad}`, () => require('..').GainMap.decode(map, {maxPixels: bad}), RangeError, /maxPixels must be a positive number/);
86+
}
87+
for (const threads of [0, -1, 1.5, NaN])
88+
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})}))
89+
await rejects(`${name} threads ${threads}`, call, RangeError, /threads must be a positive integer/);
90+
// (Infinity lifts a limit)
91+
await Image.renderText('a', {font, size: 12, maxPixels: Infinity});
92+
}
7693

7794
// Image.decode takes the options object of a GIF too: maxPixels counts its first frame
7895
const gif = await new Animation([new Frame(new Image(4, 4).fill(0xff0000ff))]).encodeGIF();

0 commit comments

Comments
 (0)