imagescript 4.0.0-rc.5 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@
5
5
  * (Copyright 2014 Mozilla Foundation, Apache License 2.0). See THIRD_PARTY_NOTICES.md
6
6
  */
7
7
  import { ByteWriter } from "../util/bytes.js";
8
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
8
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
9
9
  import { orientation as exifOrientation } from "./exif.js";
10
10
  import { concat } from "../util/mem.js";
11
11
  import { littleEndian } from "../util/alpha.js";
@@ -92,7 +92,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
92
92
  if (data[start] !== 8)
93
93
  throw new Error(`JPEG: ${data[start]}-bit precision is not supported`);
94
94
  checkPixels(u16(start + 3), u16(start + 1), maxPixels);
95
- frame = createFrame(marker === 0xc2, u16(start + 1), u16(start + 3), data.subarray(start + 5, end));
95
+ frame = createFrame(marker === 0xc2, u16(start + 1), u16(start + 3), data.subarray(start + 5, end), data.length - end);
96
96
  break;
97
97
  }
98
98
  case 0xc3:
@@ -165,7 +165,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
165
165
  const icc = profile.length && Array.from(profile).every(Boolean) ? concat(profile) : undefined;
166
166
  return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation, icc };
167
167
  }
168
- function createFrame(progressive, height, width, componentData) {
168
+ function createFrame(progressive, height, width, componentData, available) {
169
169
  const count = componentData[0];
170
170
  const sampling = [];
171
171
  for (let i = 0; i < count; i++) {
@@ -180,6 +180,13 @@ function createFrame(progressive, height, width, componentData) {
180
180
  const vmax = Math.max(...sampling.map(c => c.v));
181
181
  const mcusPerLine = Math.ceil(width / (8 * hmax));
182
182
  const mcusPerColumn = Math.ceil(height / (8 * vmax));
183
+ if (!progressive) {
184
+ let blocks = 0;
185
+ for (const c of sampling)
186
+ blocks += Math.ceil(Math.ceil(width * c.h / hmax) / 8) * Math.ceil(Math.ceil(height * c.v / vmax) / 8);
187
+ if (blocks * 2 > available * 8)
188
+ throw new Error('JPEG: the scan data is truncated');
189
+ }
183
190
  const components = sampling.map((c) => {
184
191
  const componentWidth = Math.ceil(width * c.h / hmax);
185
192
  const componentHeight = Math.ceil(height * c.v / vmax);
@@ -840,9 +847,10 @@ function reciprocals(table) {
840
847
  }
841
848
  return r;
842
849
  }
843
- export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling } = {}) {
844
- if (!width || !height || width > 0xffff || height > 0xffff)
850
+ export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, rows } = {}) {
851
+ if (!width || !height)
845
852
  throw new RangeError('JPEG: invalid dimensions');
853
+ checkFormatSize('JPEG', width, height, 0xffff);
846
854
  quality = Math.min(100, Math.max(1, Math.round(quality)));
847
855
  const scale = quality < 50 ? Math.floor(5000 / quality) : 200 - quality * 2;
848
856
  const scaleTable = (base) => base.map(v => Math.min(255, Math.max(1, Math.floor((v * scale + 50) / 100))));
@@ -860,10 +868,12 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
860
868
  const Y = new Uint8Array(W * lumaBlocksY * 8), Cb = new Uint8Array(CW * chromaBlocksY * 8), Cr = new Uint8Array(CW * chromaBlocksY * 8);
861
869
  const rowWidth = CW * hmax;
862
870
  const cbRows = subsample ? new Uint8Array(2 * rowWidth) : Cb, crRows = subsample ? new Uint8Array(2 * rowWidth) : Cr;
863
- const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, width * height) : null;
871
+ const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, (rows ? width : width * height)) : null;
864
872
  for (let y = 0; y < height; y++) {
873
+ if (rows)
874
+ rows(y);
865
875
  const row = subsample ? (y & 1) * rowWidth : y * CW;
866
- let i = y * width * 4, o = y * W, c = row;
876
+ let i = rows ? 0 : y * width * 4, o = y * W, c = row;
867
877
  if (words)
868
878
  for (let x = 0, w = i >> 2; x < width; x++, w++, o++, c++) {
869
879
  const p = words[w], r = p & 255, g = p >> 8 & 255, b = p >> 16 & 255;
@@ -258,7 +258,7 @@ export async function encodeRGBA(rgba, width, height, level, text) {
258
258
  }
259
259
  export async function encodeAnimation(frames, width, height, plays, level, text) {
260
260
  if (!frames.length)
261
- throw new Error('PNG: an animation needs at least one frame');
261
+ throw new RangeError('PNG: an animation needs at least one frame, not 0');
262
262
  frames = [coverCanvas(frames[0], width, height), ...frames.slice(1)];
263
263
  for (const f of frames)
264
264
  checkFrame(f, width, height);
@@ -1,5 +1,5 @@
1
1
  import { encode as utf8 } from "../util/utf8.js";
2
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
2
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
3
3
  const SIGNATURE = 'TRUEVISION-XFILE.\0';
4
4
  function readHeader(d) {
5
5
  if (d.length < 18)
@@ -182,8 +182,9 @@ function extensionArea({ author, comment, time, software }, alpha) {
182
182
  return area;
183
183
  }
184
184
  export function encode(rgba, width, height, extension) {
185
- if (width < 1 || height < 1 || width > 65535 || height > 65535)
186
- throw new RangeError('TGA: dimensions must be 1-65535');
185
+ if (width < 1 || height < 1)
186
+ throw new RangeError('TGA: dimensions must be at least 1');
187
+ checkFormatSize('TGA', width, height, 65535);
187
188
  let opaque = true;
188
189
  for (let i = 3; i < rgba.length; i += 4)
189
190
  if (rgba[i] !== 255) {
@@ -6,7 +6,7 @@
6
6
  * Copyright (c) 2012 Google Inc., BSD-3-Clause License
7
7
  */
8
8
  import { ByteWriter } from "../util/bytes.js";
9
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
9
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
10
10
  import { runChunks, shared } from "../util/threads.js";
11
11
  const SIGNATURE = 0x2f;
12
12
  const CODE_LENGTH_ORDER = [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
@@ -1462,8 +1462,9 @@ export function predictorChunks({ p, src, modes, width, height, bits, candidates
1462
1462
  };
1463
1463
  }
1464
1464
  export async function encode(argb, width, height, threads = null, effort = 2) {
1465
- if (width < 1 || height < 1 || width > 16384 || height > 16384)
1466
- throw new RangeError('VP8L: dimensions must be 1-16384');
1465
+ if (width < 1 || height < 1)
1466
+ throw new RangeError('WebP: dimensions must be at least 1');
1467
+ checkFormatSize('WebP', width, height, 16384);
1467
1468
  const tuning = TUNING[Math.min(2, effort)];
1468
1469
  const colors = new Map();
1469
1470
  for (let i = 0; i < argb.length && colors.size <= 256; i++)
@@ -7,7 +7,7 @@ import * as vp8 from "./vp8.js";
7
7
  import { encodeVP8, encodeAlpha } from "./vp8-enc.js";
8
8
  import { rgbaToYUV } from "./vp8-enc-dsp.js";
9
9
  import { orientation as exifOrientation } from "./exif.js";
10
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
10
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
11
11
  import { effort as checkEffort, quality as checkQuality, boolean as checkBoolean } from "../util/options.js";
12
12
  import { startThreads } from "../util/threads.js";
13
13
  const fourCC = (s) => s.charCodeAt(0) | s.charCodeAt(1) << 8 | s.charCodeAt(2) << 16 | s.charCodeAt(3) << 24;
@@ -301,7 +301,8 @@ export function lossyOptions(quality, effort, sharp, alphaQuality) {
301
301
  checkBoolean(sharp, 'sharpYuv');
302
302
  if (quality === undefined)
303
303
  return undefined;
304
- return { quality: checkQuality(quality), method: effort, sharp, alphaQuality: Math.round(a) };
304
+ const q = checkQuality(quality);
305
+ return q === 100 ? undefined : { quality: q, method: effort, sharp, alphaQuality: Math.round(a) };
305
306
  }
306
307
  export async function encodeLossy(rgba, width, height, lossy, exif) {
307
308
  const { alpha, chunks } = await lossyChunks(rgba, width, height, lossy);
@@ -314,8 +315,7 @@ export async function encodeLossy(rgba, width, height, lossy, exif) {
314
315
  return riff([riffChunk('VP8X', vp8x), ...chunks, ...exif ? [riffChunk('EXIF', exif)] : []]);
315
316
  }
316
317
  async function lossyChunks(rgba, width, height, { quality, method, sharp, alphaQuality }) {
317
- if (width > 16383 || height > 16383)
318
- throw new RangeError('WebP: lossy images can be at most 16383 pixels wide and high');
318
+ checkFormatSize('WebP', width, height, 16383);
319
319
  const picture = rgbaToYUV(rgba, width, height, sharp);
320
320
  const frame = encodeVP8(picture, quality, method);
321
321
  const padded = new Uint8Array(frame.length + (frame.length & 1));
@@ -331,9 +331,8 @@ export function lossyTolerance(quality) {
331
331
  }
332
332
  export async function encodeAnimation(frames, width, height, plays, exif, lossy, effort = 2) {
333
333
  if (!frames.length)
334
- throw new Error('WebP: an animation needs at least one frame');
335
- if (width > 1 << 24 || height > 1 << 24)
336
- throw new RangeError('WebP: canvas too large');
334
+ throw new RangeError('WebP: an animation needs at least one frame, not 0');
335
+ checkFormatSize('WebP', width, height, 1 << 24);
337
336
  let alpha = false;
338
337
  for (const [i, f] of frames.entries())
339
338
  alpha ||= needsAlpha(f, i === 0, width, height);
package/dist/colors.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  import type { Color } from './image.js';
2
- /** Clamps and rounds a channel value to 0..255 */
3
- export declare function channel(value: number): number;
4
2
  export declare function wrapHue(h: number): number;
5
3
  export declare function hue2rgb(p: number, q: number, t: number): number;
6
4
  /**
@@ -19,7 +17,7 @@ export declare function rgbaToHSLA(r: number, g: number, b: number, a: number):
19
17
  export declare class Colors {
20
18
  private constructor();
21
19
  /**
22
- * Converts RGBA components to an RGBA value, values are rounded and clamped to 0..255
20
+ * Converts RGBA components to an RGBA value. Fractions are rounded, values outside of 0..255 throw a `RangeError`
23
21
  * @param r red (0..255)
24
22
  * @param g green (0..255)
25
23
  * @param b blue (0..255)
@@ -38,17 +36,17 @@ export declare class Colors {
38
36
  /**
39
37
  * Converts HSLA colors to RGBA colors
40
38
  * @param h hue in degrees (0..360, like CSS' `hsl()`: 0 red, 120 green, 240 blue; other values wrap around)
41
- * @param s saturation (0..1)
42
- * @param l lightness (0..1)
43
- * @param a opacity (0..1)
39
+ * @param s saturation (0..1, else a `RangeError`)
40
+ * @param l lightness (0..1, else a `RangeError`)
41
+ * @param a opacity (0..1, else a `RangeError`)
44
42
  * @returns color
45
43
  */
46
44
  static fromHSLA(h: number, s: number, l: number, a: number): Color;
47
45
  /**
48
46
  * Converts HSL colors to RGBA colors (fully opaque)
49
47
  * @param h hue in degrees (0..360, like CSS' `hsl()`; other values wrap around)
50
- * @param s saturation (0..1)
51
- * @param l lightness (0..1)
48
+ * @param s saturation (0..1, else a `RangeError`)
49
+ * @param l lightness (0..1, else a `RangeError`)
52
50
  * @returns color
53
51
  */
54
52
  static fromHSL(h: number, s: number, l: number): Color;
@@ -76,7 +74,8 @@ export declare class Colors {
76
74
  * or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link GradientOptions.stops}
77
75
  * @remarks A stop may lie outside 0..1 (`{ 0: red, 2: blue }`): it is where it says, so the part between 0 and 1
78
76
  * shows only part of the way between its colors. Before the first stop and after the last one, the gradient has
79
- * their colors
77
+ * their colors, and at a stop its color. Stops at the same position make a hard edge: the gradient jumps from
78
+ * the earlier stop's color to the later one's, which is the color at that position (like CSS)
80
79
  * @return The gradient generator. The function argument is the position in the gradient (0..1).
81
80
  */
82
81
  static gradient(stops: Record<number, Color> | Color[]): (position: number) => Color;
package/dist/colors.js CHANGED
@@ -1,7 +1,4 @@
1
- import { finite, checkNumber, color as checkColor } from "./util/options.js";
2
- export function channel(value) {
3
- return value > 255 ? 255 : value > 0 ? Math.round(value) : 0;
4
- }
1
+ import { shown, finite, notNaN, byte, unitInterval, color as checkColor } from "./util/options.js";
5
2
  export function wrapHue(h) {
6
3
  const t = h - Math.trunc(h) + 1;
7
4
  return t < 1 ? t : t < 2 ? t - 1 : 0;
@@ -49,9 +46,7 @@ export function rgbaToHSLA(r, g, b, a) {
49
46
  return [h, s, l, a / 255];
50
47
  }
51
48
  function checkPosition(position) {
52
- checkNumber(position, 'gradient position');
53
- if (Number.isNaN(position))
54
- throw new RangeError(`Invalid gradient position: ${position}`);
49
+ notNaN(position, 'gradient position');
55
50
  }
56
51
  function gradientBetween(startColor, endColor) {
57
52
  const sr = startColor >>> 24, sg = startColor >> 16 & 0xff, sb = startColor >> 8 & 0xff, sa = startColor & 0xff;
@@ -77,23 +72,16 @@ export class Colors {
77
72
  throw new TypeError('Colors only has static methods, like Colors.fromRGBA()');
78
73
  }
79
74
  static fromRGBA(r, g, b, a) {
80
- r = finite(r, 'red');
81
- g = finite(g, 'green');
82
- b = finite(b, 'blue');
83
- a = finite(a, 'alpha');
84
- return (channel(r) << 24 | channel(g) << 16 | channel(b) << 8 | channel(a)) >>> 0;
75
+ return (byte(r, 'red') << 24 | byte(g, 'green') << 16 | byte(b, 'blue') << 8 | byte(a, 'alpha')) >>> 0;
85
76
  }
86
77
  static fromRGB(r, g, b) {
87
78
  return Colors.fromRGBA(r, g, b, 0xff);
88
79
  }
89
80
  static fromHSLA(h, s, l, a) {
90
81
  h = wrapHue(finite(h, 'hue') / 360);
91
- s = finite(s, 'saturation');
92
- l = finite(l, 'lightness');
93
- a = finite(a, 'alpha');
94
- s = Math.min(1, Math.max(0, s));
95
- l = Math.min(1, Math.max(0, l));
96
- a = Math.min(1, Math.max(0, a));
82
+ s = unitInterval(s, 'saturation');
83
+ l = unitInterval(l, 'lightness');
84
+ a = unitInterval(a, 'alpha');
97
85
  let r, g, b;
98
86
  if (s === 0) {
99
87
  r = g = b = l;
@@ -125,11 +113,11 @@ export class Colors {
125
113
  }
126
114
  static gradient(stops) {
127
115
  if (typeof stops !== 'object' || stops === null)
128
- throw new TypeError(`gradient() takes an array of colors or an object of positions and colors, not ${stops === null ? 'null' : typeof stops}`);
116
+ throw new TypeError(`Colors.gradient() takes an array of colors or an object of positions and colors, not ${shown(stops)}`);
129
117
  let colors;
130
118
  if (Array.isArray(stops)) {
131
119
  if (!stops.length)
132
- throw new RangeError('Invalid gradient point count');
120
+ throw new RangeError('Colors.gradient() takes at least one color, not 0');
133
121
  const list = stops.length === 1 ? [stops[0], stops[0]] : stops;
134
122
  colors = Object.fromEntries(list.map((color, i) => [i / (list.length - 1), color]));
135
123
  }
@@ -139,7 +127,7 @@ export class Colors {
139
127
  const positions = entries.map(e => finite(parseFloat(e[0]), 'gradient position'));
140
128
  const values = entries.map(e => checkColor(e[1]));
141
129
  if (positions.length === 0)
142
- throw new RangeError('Invalid gradient point count');
130
+ throw new RangeError('Colors.gradient() takes at least one color, not 0');
143
131
  else if (positions.length === 1) {
144
132
  return position => {
145
133
  checkPosition(position);
@@ -150,15 +138,15 @@ export class Colors {
150
138
  const gradient = gradientBetween(values[0], values[1]);
151
139
  return position => {
152
140
  checkPosition(position);
153
- if (position <= positions[0])
154
- return values[0];
155
141
  if (position >= positions[1])
156
142
  return values[1];
143
+ if (position <= positions[0])
144
+ return values[0];
157
145
  return gradient((position - positions[0]) / (positions[1] - positions[0]));
158
146
  };
159
147
  }
160
- const minDef = Math.min(...positions);
161
- const maxDef = Math.max(...positions);
148
+ const minDef = positions[0];
149
+ const maxDef = positions[positions.length - 1];
162
150
  const gradients = [];
163
151
  for (let i = 0; i < positions.length; i++) {
164
152
  const minPos = positions[i - 1];
@@ -177,17 +165,22 @@ export class Colors {
177
165
  if (!gradients.length)
178
166
  return position => {
179
167
  checkPosition(position);
180
- return position <= minDef ? values[0] : values[values.length - 1];
168
+ return position < minDef ? values[0] : values[values.length - 1];
181
169
  };
170
+ const atStop = new Map(positions.map((p, i) => [p, values[i]]));
182
171
  return position => {
183
- if (position <= minDef)
184
- return gradients[0].gradient(0);
172
+ checkPosition(position);
173
+ if (position < minDef)
174
+ return values[0];
185
175
  if (position >= maxDef)
186
- return gradients[gradients.length - 1].gradient(1);
176
+ return values[values.length - 1];
177
+ const stop = atStop.get(position);
178
+ if (stop !== undefined)
179
+ return stop;
187
180
  for (const gradient of gradients)
188
- if (position >= gradient.min && position <= gradient.max)
181
+ if (position > gradient.min && position < gradient.max)
189
182
  return gradient.gradient((position - gradient.min) / (gradient.max - gradient.min));
190
- throw new RangeError(`Invalid gradient position: ${position}`);
183
+ throw new RangeError(`The gradient has no color at position ${position}`);
191
184
  };
192
185
  }
193
186
  }
package/dist/frame.d.ts CHANGED
@@ -58,9 +58,10 @@ export declare class Frame {
58
58
  /** The frame's height (its image's) */
59
59
  get height(): number;
60
60
  /**
61
- * The frame's duration in milliseconds (a finite number from 0, else it throws a RangeError). GIFs store
62
- * hundredths of a second, so this is rounded to 10 ms when encoding a GIF; note that browsers play frames shorter
63
- * than 20 ms with 100 ms
61
+ * The frame's duration in milliseconds (a finite number from 0, else it throws a RangeError). It doesn't have to
62
+ * be a whole number: encoding rounds it, to whole milliseconds for APNG and WebP and, as GIFs store hundredths of
63
+ * 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
64
+ * 100 ms
64
65
  */
65
66
  get duration(): number;
66
67
  /**
package/dist/frame.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Image } from "./image.js";
2
- import { checkOptions, finite, oneOf } from "./util/options.js";
2
+ import { instance, checkOptions, finite, nonNegative, oneOf } from "./util/options.js";
3
3
  import { describe } from "./util/inspect.js";
4
4
  const DISPOSAL_MODES = ['any', 'keep', 'previous', 'background'];
5
5
  export class Frame {
@@ -14,7 +14,7 @@ export class Frame {
14
14
  constructor(image, options = {}) {
15
15
  if (!(image instanceof Image))
16
16
  throw new TypeError('A frame takes an Image, like new Frame(image, { duration: 100 })');
17
- checkOptions(options, 'Frame(image, { duration: 100 })');
17
+ checkOptions(options, 'new Frame(image, { duration: 100 })');
18
18
  const { duration = 100, xOffset: x = 0, yOffset: y = 0, disposalMode: disposal = 'keep' } = options;
19
19
  this.__image__ = image;
20
20
  this.duration = duration;
@@ -26,8 +26,7 @@ export class Frame {
26
26
  return this.__image__;
27
27
  }
28
28
  set image(image) {
29
- if (!(image instanceof Image))
30
- throw new TypeError('A frame\'s image has to be an Image');
29
+ instance(image, [Image], 'frame.image');
31
30
  this.__image__ = image;
32
31
  }
33
32
  get width() {
@@ -40,10 +39,7 @@ export class Frame {
40
39
  return this.__duration__;
41
40
  }
42
41
  set duration(duration) {
43
- const value = finite(duration, 'frame duration');
44
- if (value < 0)
45
- throw new RangeError('Invalid frame duration');
46
- this.__duration__ = value;
42
+ this.__duration__ = nonNegative(duration, 'frame duration');
47
43
  }
48
44
  get xOffset() {
49
45
  return this.__x__;
package/dist/gainmap.d.ts CHANGED
@@ -4,7 +4,7 @@ import { BinaryData } from './util/mem.js';
4
4
  /** Options of {@link GainMap.encodeJPEG} */
5
5
  export interface GainMapEncodeOptions {
6
6
  /**
7
- * The JPEG quality (1-100)
7
+ * The JPEG quality (0-100, like {@link Image.encodeJPEG}'s: 0 is 1)
8
8
  * @defaultValue `90`
9
9
  */
10
10
  quality?: number;
@@ -64,8 +64,8 @@ export interface GainMapOptions {
64
64
  * location. For developers who need the exact calculation, the boost is
65
65
  * `2^(min + (max - min) * (v / 255)^(1 / gamma))`, per color channel.
66
66
  *
67
- * The parameters are checked when they are set: a value that isn't finite (or an array of other than 1 or 3 of them)
68
- * throws, and the map keeps its value
67
+ * The parameters are checked when they are set: a value that isn't finite or lies beyond ±(2^31 - 1) (what the
68
+ * 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
69
69
  */
70
70
  export declare class GainMap {
71
71
  /** log2 of the boost of the map's value 0, per channel (red, green, blue; a copy: assign to change it) */
@@ -86,7 +86,7 @@ export declare class GainMap {
86
86
  get gamma(): readonly [red: number, green: number, blue: number];
87
87
  /**
88
88
  * Replaces the value (checked: an invalid one throws and the old one stays)
89
- * @param value One number above 0 for all channels or [r, g, b]
89
+ * @param value One number from 2^-31 for all channels or [r, g, b]
90
90
  */
91
91
  set gamma(value: GainMapChannelValues);
92
92
  /** Added to the SDR image's linear values before the boost, per channel (a copy: assign to change it) */
package/dist/gainmap.js CHANGED
@@ -3,15 +3,23 @@ import { MAX_PIXELS, decoding } from "./util/limits.js";
3
3
  import * as jpeg from "./codecs/jpeg.js";
4
4
  import * as codec from "./codecs/gainmap.js";
5
5
  import { view } from "./util/mem.js";
6
- import { finite, checkOptions, pixelLimit, quality as checkQuality } from "./util/options.js";
6
+ import { shown, instance, nonNegative, finite, checkOptions, pixelLimit, boolean, quality as checkQuality } from "./util/options.js";
7
+ const LIMIT = 2 ** 31 - 1;
8
+ const MIN_GAMMA = 2 ** -31;
9
+ const bounded = (value, name) => {
10
+ finite(value, name);
11
+ if (Math.abs(value) > LIMIT)
12
+ throw new RangeError(`${name} must be from -${LIMIT} to ${LIMIT}, not ${value}`);
13
+ return value;
14
+ };
7
15
  const perChannel = (value, name) => {
8
16
  const given = value;
9
17
  if (typeof given !== 'number' && !Array.isArray(given))
10
- throw new TypeError(`${name} must be a number or an array of 3 numbers, not ${given === null ? 'null' : typeof given}`);
18
+ throw new TypeError(`${name} must be a number or an array of 3 numbers, not ${shown(given)}`);
11
19
  const values = typeof value === 'number' ? [value, value, value] : Array.from(value);
12
20
  if (values.length !== 3)
13
21
  throw new RangeError(`${name} must be a number or an array of 3 numbers, not ${values.length}`);
14
- return values.map(v => finite(v, name));
22
+ return values.map(v => bounded(v, name));
15
23
  };
16
24
  export class GainMap {
17
25
  __min__;
@@ -22,6 +30,7 @@ export class GainMap {
22
30
  __capacityMin__;
23
31
  __capacityMax__;
24
32
  __useBaseColorSpace__;
33
+ __alternate__;
25
34
  get min() { return [this.__min__[0], this.__min__[1], this.__min__[2]]; }
26
35
  set min(value) { this.__min__ = perChannel(value, 'min'); }
27
36
  get max() { return [this.__max__[0], this.__max__[1], this.__max__[2]]; }
@@ -29,8 +38,8 @@ export class GainMap {
29
38
  get gamma() { return [this.__gamma__[0], this.__gamma__[1], this.__gamma__[2]]; }
30
39
  set gamma(value) {
31
40
  const gamma = perChannel(value, 'gamma');
32
- if (gamma.some(g => g <= 0))
33
- throw new RangeError('The gain map\'s gamma must be above 0');
41
+ if (gamma.some(g => g < MIN_GAMMA))
42
+ throw new RangeError(`The gain map's gamma must be 2^-31 or more, not ${gamma.find(g => g < MIN_GAMMA)}`);
34
43
  this.__gamma__ = gamma;
35
44
  }
36
45
  get offsetSDR() { return [this.__offsetSDR__[0], this.__offsetSDR__[1], this.__offsetSDR__[2]]; }
@@ -39,31 +48,26 @@ export class GainMap {
39
48
  set offsetHDR(value) { this.__offsetHDR__ = perChannel(value, 'offsetHDR'); }
40
49
  get hdrCapacityMin() { return this.__capacityMin__; }
41
50
  set hdrCapacityMin(value) {
42
- const capacity = finite(value, 'hdrCapacityMin');
43
- if (capacity < 0)
44
- throw new RangeError('The gain map\'s hdrCapacityMin can\'t be negative');
51
+ const capacity = bounded(nonNegative(value, 'hdrCapacityMin'), 'hdrCapacityMin');
45
52
  if (this.__capacityMax__ !== undefined && !(capacity < this.__capacityMax__))
46
53
  throw new RangeError(`The gain map's hdrCapacityMin must be below its hdrCapacityMax (${capacity} >= ${this.__capacityMax__})`);
47
54
  this.__capacityMin__ = capacity;
48
55
  }
49
56
  get hdrCapacityMax() { return this.__capacityMax__; }
50
57
  set hdrCapacityMax(value) {
51
- const capacity = finite(value, 'hdrCapacityMax');
58
+ const capacity = bounded(value, 'hdrCapacityMax');
52
59
  if (this.__capacityMin__ !== undefined && !(capacity > this.__capacityMin__))
53
60
  throw new RangeError(`The gain map's hdrCapacityMax (by default the largest max) must be above its hdrCapacityMin (${capacity} <= ${this.__capacityMin__})`);
54
61
  this.__capacityMax__ = capacity;
55
62
  }
56
63
  get useBaseColorSpace() { return this.__useBaseColorSpace__; }
57
64
  set useBaseColorSpace(value) {
58
- if (typeof value !== 'boolean')
59
- throw new TypeError('useBaseColorSpace must be a boolean');
60
- this.__useBaseColorSpace__ = value;
65
+ this.__useBaseColorSpace__ = boolean(value, 'useBaseColorSpace');
61
66
  }
62
67
  __pixels__ = null;
63
68
  constructor(image, options = {}) {
64
69
  checkOptions(options, 'new GainMap(image, { max: 2 })');
65
- if (!(image instanceof Image))
66
- throw new TypeError('The gain map has to be an Image');
70
+ instance(image, [Image], 'the gain map image');
67
71
  const { min = 0, max = 2, gamma = 1, offsetSDR = 1 / 64, offsetHDR = 1 / 64, hdrCapacityMin = 0, useBaseColorSpace = true } = options;
68
72
  this.min = min;
69
73
  this.max = max;
@@ -116,12 +120,14 @@ export class GainMap {
116
120
  this.__capacityMin__ = p.capacityMin;
117
121
  this.__capacityMax__ = p.capacityMax;
118
122
  this.__useBaseColorSpace__ = p.useBaseColorSpace;
123
+ this.__alternate__ = p.alternate?.slice();
119
124
  }
120
125
  __params__() {
121
126
  this.__check__();
122
127
  return {
123
128
  min: this.__min__.slice(), max: this.__max__.slice(), gamma: this.__gamma__.slice(), offsetSDR: this.__offsetSDR__.slice(),
124
- offsetHDR: this.__offsetHDR__.slice(), capacityMin: this.__capacityMin__, capacityMax: this.__capacityMax__, useBaseColorSpace: this.__useBaseColorSpace__
129
+ offsetHDR: this.__offsetHDR__.slice(), capacityMin: this.__capacityMin__, capacityMax: this.__capacityMax__, useBaseColorSpace: this.__useBaseColorSpace__,
130
+ ...this.__alternate__ ? { alternate: this.__alternate__.slice() } : {}
125
131
  };
126
132
  }
127
133
  __check__() {
@@ -133,8 +139,7 @@ export class GainMap {
133
139
  return this.__pixels__;
134
140
  }
135
141
  set image(image) {
136
- if (!(image instanceof Image))
137
- throw new TypeError('The gain map has to be an Image');
142
+ instance(image, [Image], 'gainMap.image');
138
143
  this.__pixels__ = image;
139
144
  }
140
145
  get width() {
@@ -210,11 +215,8 @@ export class GainMap {
210
215
  async encodeJPEG(options) {
211
216
  checkOptions(options, 'gainMap.encodeJPEG({ quality: 80 })');
212
217
  const quality = options?.quality;
213
- if (quality !== undefined) {
218
+ if (quality !== undefined)
214
219
  checkQuality(quality);
215
- if (quality < 1)
216
- throw new RangeError(`quality has to be between 1 and 100, not ${quality}`);
217
- }
218
220
  return codec.mapWithMetadata(this.__body__(quality), this.__params__());
219
221
  }
220
222
  static async decode(data, options = {}) {