imagescript 3.15.0 → 3.16.1

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.
@@ -807,7 +807,7 @@ function reciprocals(table) {
807
807
  }
808
808
  return r;
809
809
  }
810
- export function encode(pixels, width, height, quality = 90, { exif, comment } = {}) {
810
+ export function encode(pixels, width, height, quality = 90, { exif, comment, segments, grey = false, fullChroma = false } = {}) {
811
811
  if (!width || !height || width > 0xffff || height > 0xffff)
812
812
  throw new RangeError('JPEG: invalid dimensions');
813
813
  quality = Math.min(100, Math.max(1, Math.round(quality)));
@@ -815,7 +815,7 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
815
815
  const scaleTable = (base) => base.map(v => Math.min(255, Math.max(1, Math.floor((v * scale + 50) / 100))));
816
816
  const tables = [scaleTable(LUMA_QUANTIZATION), scaleTable(CHROMA_QUANTIZATION)];
817
817
  const divisors = tables.map(reciprocals);
818
- const subsample = quality <= 90;
818
+ const subsample = quality <= 90 && !grey && !fullChroma;
819
819
  const hmax = subsample ? 2 : 1;
820
820
  const mcuSize = 8 * hmax;
821
821
  const mcusPerLine = Math.ceil(width / mcuSize);
@@ -870,7 +870,8 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
870
870
  { plane: Cb, stride: CW, h: 1, v: 1, blocksX: chromaBlocksX, blocksY: chromaBlocksY, table: 1 },
871
871
  { plane: Cr, stride: CW, h: 1, v: 1, blocksX: chromaBlocksX, blocksY: chromaBlocksY, table: 1 }
872
872
  ];
873
- const blocksPerMcu = hmax * hmax + 2;
873
+ const componentCount = grey ? 1 : 3;
874
+ const blocksPerMcu = grey ? 1 : hmax * hmax + 2;
874
875
  const count = mcusPerLine * mcusPerColumn * blocksPerMcu;
875
876
  const coefficients = new Int16Array(count * 64);
876
877
  const owners = new Uint8Array(count), ends = new Uint8Array(count);
@@ -878,7 +879,7 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
878
879
  let n = 0;
879
880
  for (let my = 0; my < mcusPerColumn; my++)
880
881
  for (let mx = 0; mx < mcusPerLine; mx++)
881
- for (let c = 0; c < 3; c++) {
882
+ for (let c = 0; c < componentCount; c++) {
882
883
  const { plane, stride, h: ch, v: cv, blocksX, blocksY, table } = components[c];
883
884
  const reciprocal = divisors[table];
884
885
  for (let v = 0; v < cv; v++) {
@@ -910,7 +911,7 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
910
911
  const blocks = { coefficients, owners, ends, count };
911
912
  const frequencies = [new Int32Array(257), new Int32Array(257), new Int32Array(257), new Int32Array(257)];
912
913
  countSymbols(blocks, frequencies);
913
- const huffman = frequencies.map(buildOptimalTable);
914
+ const huffman = frequencies.slice(0, grey ? 2 : 4).map(buildOptimalTable);
914
915
  const writer = new BitWriter(width * height);
915
916
  writer.bytes(0xff, 0xd8);
916
917
  writer.bytes(0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00);
@@ -925,14 +926,22 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
925
926
  segment(0xe1, concat([[0x45, 0x78, 0x69, 0x66, 0, 0], exif]));
926
927
  if (comment)
927
928
  segment(0xfe, comment);
928
- for (let t = 0; t < 2; t++) {
929
+ if (segments)
930
+ for (const bytes of segments)
931
+ for (let i = 0; i < bytes.length; i++)
932
+ writer.bytes(bytes[i]);
933
+ for (let t = 0; t < (grey ? 1 : 2); t++) {
929
934
  writer.bytes(0xff, 0xdb, 0x00, 0x43, t);
930
935
  for (let k = 0; k < 64; k++)
931
936
  writer.bytes(tables[t][ZIGZAG[k]]);
932
937
  }
933
- writer.bytes(0xff, 0xc0, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03);
934
- writer.bytes(1, hmax << 4 | hmax, 0, 2, 0x11, 1, 3, 0x11, 1);
935
- for (const [index, id] of [[0, 0x00], [1, 0x10], [2, 0x01], [3, 0x11]]) {
938
+ if (grey)
939
+ writer.bytes(0xff, 0xc0, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0);
940
+ else {
941
+ writer.bytes(0xff, 0xc0, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03);
942
+ writer.bytes(1, hmax << 4 | hmax, 0, 2, 0x11, 1, 3, 0x11, 1);
943
+ }
944
+ for (const [index, id] of [[0, 0x00], [1, 0x10], [2, 0x01], [3, 0x11]].slice(0, grey ? 2 : 4)) {
936
945
  const { bits, values } = huffman[index];
937
946
  const length = 19 + values.length;
938
947
  writer.bytes(0xff, 0xc4, length >> 8, length & 0xff, id);
@@ -941,7 +950,10 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
941
950
  for (const value of values)
942
951
  writer.bytes(value);
943
952
  }
944
- writer.bytes(0xff, 0xda, 0x00, 0x0c, 0x03, 1, 0x00, 2, 0x11, 3, 0x11, 0x00, 0x3f, 0x00);
953
+ if (grey)
954
+ writer.bytes(0xff, 0xda, 0x00, 0x08, 0x01, 1, 0x00, 0x00, 0x3f, 0x00);
955
+ else
956
+ writer.bytes(0xff, 0xda, 0x00, 0x0c, 0x03, 1, 0x00, 2, 0x11, 3, 0x11, 0x00, 0x3f, 0x00);
945
957
  writeBlocks(blocks, huffman, writer);
946
958
  writer.flush();
947
959
  writer.bytes(0xff, 0xd9);
@@ -10,29 +10,37 @@ import { encodeModular } from "./jxl/modular-lossless.js";
10
10
  import { encodeVarDCT } from "./jxl/vardct-enc.js";
11
11
  import { concat } from "../util/mem.js";
12
12
  import { srgbDecode } from "../util/icc.js";
13
+ import { readISO, writeISO } from "./gainmap.js";
13
14
  const CONTAINER = [0, 0, 0, 12, 0x4a, 0x58, 0x4c, 0x20, 0x0d, 0x0a, 0x87, 0x0a];
14
15
  export function isJXL(d) {
15
16
  if (d.length >= 2 && d[0] === 0xff && d[1] === 0x0a)
16
17
  return true;
17
18
  return d.length >= 12 && CONTAINER.every((v, i) => d[i] === v);
18
19
  }
19
- export async function encode(rgba, width, height, exif, distance = 0, effort = 1, threads = 1) {
20
- const stream = distance > 0 ? await encodeVarDCT(rgba, width, height, { distance, effort, threads })
21
- : effort ? await encodeModular(rgba, width, height, threads) : encodeRGBA(rgba, width, height);
22
- if (!exif?.length)
20
+ export async function encode(rgba, width, height, exif, distance = 0, effort = 1, threads = 1, gainMap) {
21
+ const codestreamOf = (pixels, w, h, d) => d > 0 ? encodeVarDCT(pixels, w, h, { distance: d, effort, threads })
22
+ : effort ? encodeModular(pixels, w, h, threads) : encodeRGBA(pixels, w, h);
23
+ const stream = await codestreamOf(rgba, width, height, distance);
24
+ if (!exif?.length && !gainMap)
23
25
  return stream;
24
26
  const jxl = [0x6a, 0x78, 0x6c, 0x20];
25
- return concat([CONTAINER, ...box('ftyp', jxl, [0, 0, 0, 0], jxl), ...box('Exif', [0, 0, 0, 0], exif), ...box('jxlc', stream)]);
27
+ const boxes = [...box('ftyp', jxl, [0, 0, 0, 0], jxl)];
28
+ if (exif?.length)
29
+ boxes.push(...box('Exif', [0, 0, 0, 0], exif));
30
+ if (gainMap) {
31
+ const metadata = writeISO(gainMap.params);
32
+ const map = await codestreamOf(gainMap.pixels, gainMap.width, gainMap.height, gainMap.distance);
33
+ boxes.push(...box('jhgm', [0, metadata.length >> 8, metadata.length & 255], metadata, [0, 0, 0, 0, 0], map));
34
+ }
35
+ return concat([CONTAINER, ...boxes, ...box('jxlc', stream)]);
26
36
  }
27
37
  const box = (type, ...content) => {
28
38
  const size = 8 + content.reduce((n, c) => n + c.length, 0);
29
39
  return [[size >>> 24, size >> 16 & 255, size >> 8 & 255, size & 255, ...Array.from(type, c => c.charCodeAt(0))], ...content];
30
40
  };
31
41
  const fourcc = (d, o) => String.fromCharCode(d[o], d[o + 1], d[o + 2], d[o + 3]);
32
- function codestream(d) {
33
- if (d[0] === 0xff)
34
- return d;
35
- const view = new DataView(d.buffer, d.byteOffset, d.byteLength), parts = [];
42
+ function* boxesOf(d) {
43
+ const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
36
44
  for (let o = 0; o + 8 <= d.length;) {
37
45
  let size = view.getUint32(o), header = 8;
38
46
  const type = fourcc(d, o + 4);
@@ -46,11 +54,19 @@ function codestream(d) {
46
54
  size = d.length - o;
47
55
  if (size < header || o + size > d.length)
48
56
  throw new Error(`JPEG XL: invalid ${type} box`);
57
+ yield { type, content: d.subarray(o + header, o + size) };
58
+ o += size;
59
+ }
60
+ }
61
+ function codestream(d) {
62
+ if (d[0] === 0xff)
63
+ return d;
64
+ const parts = [];
65
+ for (const { type, content } of boxesOf(d)) {
49
66
  if (type === 'jxlc')
50
- return d.subarray(o + header, o + size);
67
+ return content;
51
68
  if (type === 'jxlp')
52
- parts.push(d.subarray(o + header + 4, o + size));
53
- o += size;
69
+ parts.push(content.subarray(4));
54
70
  }
55
71
  if (!parts.length)
56
72
  throw new Error('JPEG XL: no codestream');
@@ -133,8 +149,34 @@ export async function* frames(data, maxPixels = MAX_PIXELS, toneMapping = 'reinh
133
149
  t.terminate();
134
150
  }
135
151
  }
136
- export async function decode(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1) {
137
- for await (const frame of frames(data, maxPixels, toneMapping, threads))
138
- return frame;
152
+ export async function decode(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1, gainMap = false) {
153
+ for await (const frame of frames(data, maxPixels, toneMapping, threads)) {
154
+ if (!gainMap || data[0] === 0xff)
155
+ return frame;
156
+ return { ...frame, gainMap: await decodeGainMap(data, maxPixels).catch(() => undefined) };
157
+ }
139
158
  throw new Error('JPEG XL: no frame shown');
140
159
  }
160
+ async function decodeGainMap(data, maxPixels) {
161
+ for (const { type, content: c } of boxesOf(data)) {
162
+ if (type !== 'jhgm')
163
+ continue;
164
+ if (c.length < 3 || c[0] !== 0)
165
+ return undefined;
166
+ const metadataSize = c[1] << 8 | c[2];
167
+ let o = 3 + metadataSize;
168
+ if (o + 1 > c.length)
169
+ return undefined;
170
+ const metadata = c.subarray(3, o);
171
+ const params = readISO(metadata) ?? (metadata[0] === 0 ? readISO(metadata.subarray(1)) : null);
172
+ o += 1 + c[o];
173
+ if (!params || o + 4 > c.length)
174
+ return undefined;
175
+ o += 4 + (c[o] << 24 >>> 0) + (c[o + 1] << 16 | c[o + 2] << 8 | c[o + 3]);
176
+ if (o >= c.length)
177
+ return undefined;
178
+ for await (const { width, height, pixels } of frames(c.subarray(o), maxPixels, 'clamp', 1))
179
+ return { width, height, pixels, params };
180
+ }
181
+ return undefined;
182
+ }
@@ -0,0 +1,82 @@
1
+ import { Image } from './image.js';
2
+ import { BinaryData } from './util/mem.js';
3
+ /** Options of the {@link GainMap} constructor: per channel values can be one number for all three or [r, g, b] */
4
+ export interface GainMapOptions {
5
+ /** log2 of the boost of the map's value 0 (`-1`: half as bright). Default: `0` */
6
+ gainMapMin?: number | number[];
7
+ /** log2 of the boost of the map's value 255 (`2`: 4 times as bright). Default: `2` */
8
+ gainMapMax?: number | number[];
9
+ /** the gamma the map's values are stored with. Default: `1` */
10
+ gamma?: number | number[];
11
+ /** added to the SDR image's linear values before the boost (keeps black from being boosted forever). Default: `1/64` */
12
+ offsetSDR?: number | number[];
13
+ /** subtracted from the HDR result. Default: `1/64` */
14
+ offsetHDR?: number | number[];
15
+ /** log2 of the display headroom from which on the map starts to apply. Default: `0` */
16
+ hdrCapacityMin?: number;
17
+ /** log2 of the display headroom at which it applies fully. Default: `gainMapMax`'s largest value */
18
+ hdrCapacityMax?: number;
19
+ /** whether the boost applies in the SDR image's color space (`false`: in the HDR image's). Default: `true` */
20
+ useBaseColorSpace?: boolean;
21
+ }
22
+ /**
23
+ * A gain map: a small image saying how much brighter each part of an image gets on an HDR display, as Ultra HDR
24
+ * (JPEG-R) photos from phones carry it. HDR displays show the image boosted by it, the others the image as it is.
25
+ *
26
+ * {@link Image.decode} reads the gain maps of JPEGs, AVIFs and JPEG XLs into {@link Image.gainMap},
27
+ * {@link Image.encodeJPEG}, {@link Image.encodeAVIF} and {@link Image.encodeJXL} write them. The map covers the whole image, at any resolution (phones
28
+ * write a quarter of the width and height). Its value `v` (0-255, per channel or one for all) boosts the linear
29
+ * light of the image by `2^(gainMapMin + (gainMapMax - gainMapMin) * (v / 255)^(1 / gamma))`
30
+ */
31
+ export declare class GainMap {
32
+ /** log2 of the boost of the map's value 0, per channel (red, green, blue) */
33
+ gainMapMin: number[];
34
+ /** log2 of the boost of the map's value 255, per channel */
35
+ gainMapMax: number[];
36
+ /** the gamma the map's values are stored with, per channel */
37
+ gamma: number[];
38
+ /** added to the SDR image's linear values before the boost, per channel */
39
+ offsetSDR: number[];
40
+ /** subtracted from the HDR result, per channel */
41
+ offsetHDR: number[];
42
+ /** log2 of the display headroom from which on the map starts to apply */
43
+ hdrCapacityMin: number;
44
+ /** log2 of the display headroom at which it applies fully */
45
+ hdrCapacityMax: number;
46
+ /** whether the boost applies in the SDR image's color space (else in the HDR image's) */
47
+ useBaseColorSpace: boolean;
48
+ /** its pixels */
49
+ private __pixels__;
50
+ /**
51
+ * Creates a gain map
52
+ * @param image The map's pixels: grey (red, green and blue the same) for one map for all channels. Its alpha is
53
+ * ignored
54
+ * @param options See {@link GainMapOptions}
55
+ */
56
+ constructor(image: Image, options?: GainMapOptions);
57
+ private __set_params__;
58
+ private __check__;
59
+ /** The map's pixels. Changes to them are written when the image is encoded */
60
+ get image(): Image;
61
+ set image(image: Image);
62
+ /** The map's width */
63
+ get width(): number;
64
+ /** The map's height */
65
+ get height(): number;
66
+ /** `1` for a grey map (one boost for red, green and blue), `3` for one per channel */
67
+ get channels(): 1 | 3;
68
+ /** Clones the gain map (its pixels too) */
69
+ clone(): GainMap;
70
+ /**
71
+ * Encodes the gain map alone: a JPEG with its parameters (hdrgm XMP and ISO 21496-1), like the second image in an
72
+ * Ultra HDR JPEG
73
+ * @param quality The JPEG quality (1-100). Default: `90`
74
+ */
75
+ encode(quality?: number): Promise<Uint8Array>;
76
+ /**
77
+ * Decodes a gain map JPEG with its parameters (hdrgm XMP or ISO 21496-1), like the second image in an Ultra HDR
78
+ * JPEG, or the gain map of an Ultra HDR JPEG (or an iPhone's JPEG: its values converted to these parameters)
79
+ * @param data The JPEG
80
+ */
81
+ static decode(data: BinaryData): Promise<GainMap>;
82
+ }
@@ -0,0 +1,195 @@
1
+ import { Image } from "./image.js";
2
+ import * as jpeg from "./codecs/jpeg.js";
3
+ import * as codec from "./codecs/gainmap.js";
4
+ import { view } from "./util/mem.js";
5
+ import { finite, quality as checkQuality } from "./util/options.js";
6
+ const perChannel = (value, name) => {
7
+ const values = typeof value === 'number' ? [value, value, value] : Array.from(value);
8
+ if (values.length === 1)
9
+ values.push(values[0], values[0]);
10
+ if (values.length !== 3)
11
+ throw new RangeError(`${name} must be a number or an array of 3 numbers`);
12
+ return values.map(v => finite(v, name));
13
+ };
14
+ export class GainMap {
15
+ gainMapMin;
16
+ gainMapMax;
17
+ gamma;
18
+ offsetSDR;
19
+ offsetHDR;
20
+ hdrCapacityMin;
21
+ hdrCapacityMax;
22
+ useBaseColorSpace;
23
+ __pixels__ = null;
24
+ constructor(image, options = {}) {
25
+ if (!(image instanceof Image))
26
+ throw new TypeError('The gain map has to be an Image');
27
+ const { gainMapMin = 0, gainMapMax = 2, gamma = 1, offsetSDR = 1 / 64, offsetHDR = 1 / 64, hdrCapacityMin = 0, useBaseColorSpace = true } = options;
28
+ this.gainMapMin = perChannel(gainMapMin, 'gainMapMin');
29
+ this.gainMapMax = perChannel(gainMapMax, 'gainMapMax');
30
+ this.gamma = perChannel(gamma, 'gamma');
31
+ this.offsetSDR = perChannel(offsetSDR, 'offsetSDR');
32
+ this.offsetHDR = perChannel(offsetHDR, 'offsetHDR');
33
+ this.hdrCapacityMin = finite(hdrCapacityMin, 'hdrCapacityMin');
34
+ this.hdrCapacityMax = finite(options.hdrCapacityMax ?? Math.max(...this.gainMapMax), 'hdrCapacityMax');
35
+ this.useBaseColorSpace = Boolean(useBaseColorSpace);
36
+ this.__pixels__ = image;
37
+ this.__check__();
38
+ }
39
+ static __from_jpeg__(map, params, apple = 0) {
40
+ const { width, height, pixels } = jpeg.decode(map);
41
+ const image = new Image(width, height);
42
+ image.bitmap = pixels;
43
+ if (apple) {
44
+ const table = new Uint8Array(256);
45
+ for (let v = 0; v < 256; v++)
46
+ table[v] = Math.round(255 * codec.appleValue(v / 255, apple));
47
+ for (let i = 0; i < pixels.length; i += 4) {
48
+ pixels[i] = table[pixels[i]];
49
+ pixels[i + 1] = table[pixels[i + 1]];
50
+ pixels[i + 2] = table[pixels[i + 2]];
51
+ }
52
+ }
53
+ return GainMap.__from_pixels__(image, params, false);
54
+ }
55
+ static __from_pixels__(image, params, grey = true) {
56
+ const px = image.bitmap;
57
+ if (grey) {
58
+ let spread = 0;
59
+ for (let i = 0; i < px.length && spread <= 2; i += 4)
60
+ spread = Math.max(spread, Math.abs(px[i] - px[i + 1]), Math.abs(px[i] - px[i + 2]));
61
+ if (spread > 0 && spread <= 2)
62
+ for (let i = 0; i < px.length; i += 4)
63
+ px[i] = px[i + 1] = px[i + 2] = Math.round((px[i] + px[i + 1] + px[i + 2]) / 3);
64
+ }
65
+ const gainMap = Object.create(GainMap.prototype);
66
+ gainMap.__pixels__ = image;
67
+ gainMap.__set_params__(params);
68
+ return gainMap;
69
+ }
70
+ __set_params__(p) {
71
+ this.gainMapMin = p.min.slice();
72
+ this.gainMapMax = p.max.slice();
73
+ this.gamma = p.gamma.slice();
74
+ this.offsetSDR = p.offsetSDR.slice();
75
+ this.offsetHDR = p.offsetHDR.slice();
76
+ this.hdrCapacityMin = p.capacityMin;
77
+ this.hdrCapacityMax = p.capacityMax;
78
+ this.useBaseColorSpace = p.useBaseColorSpace;
79
+ }
80
+ __params__() {
81
+ this.__check__();
82
+ return {
83
+ min: this.gainMapMin.slice(), max: this.gainMapMax.slice(), gamma: this.gamma.slice(), offsetSDR: this.offsetSDR.slice(),
84
+ offsetHDR: this.offsetHDR.slice(), capacityMin: this.hdrCapacityMin, capacityMax: this.hdrCapacityMax, useBaseColorSpace: this.useBaseColorSpace
85
+ };
86
+ }
87
+ __check__() {
88
+ const p = {
89
+ min: perChannel(this.gainMapMin, 'gainMapMin'), max: perChannel(this.gainMapMax, 'gainMapMax'), gamma: perChannel(this.gamma, 'gamma'),
90
+ offsetSDR: perChannel(this.offsetSDR, 'offsetSDR'), offsetHDR: perChannel(this.offsetHDR, 'offsetHDR'),
91
+ capacityMin: finite(this.hdrCapacityMin, 'hdrCapacityMin'), capacityMax: finite(this.hdrCapacityMax, 'hdrCapacityMax'), useBaseColorSpace: this.useBaseColorSpace
92
+ };
93
+ for (let c = 0; c < 3; c++) {
94
+ if (p.gamma[c] <= 0)
95
+ throw new RangeError('The gain map\'s gamma must be above 0');
96
+ if (p.max[c] < p.min[c])
97
+ throw new RangeError('The gain map\'s gainMapMax must be at least its gainMapMin');
98
+ }
99
+ if (p.capacityMin < 0 || p.capacityMax <= p.capacityMin)
100
+ throw new RangeError('The gain map\'s hdrCapacityMax must be above its hdrCapacityMin, which can\'t be negative');
101
+ }
102
+ get image() {
103
+ return this.__pixels__;
104
+ }
105
+ set image(image) {
106
+ if (!(image instanceof Image))
107
+ throw new TypeError('The gain map has to be an Image');
108
+ this.__pixels__ = image;
109
+ }
110
+ get width() {
111
+ return this.__pixels__.width;
112
+ }
113
+ get height() {
114
+ return this.__pixels__.height;
115
+ }
116
+ get channels() {
117
+ const bitmap = this.__pixels__.bitmap;
118
+ for (let i = 0; i < bitmap.length; i += 4)
119
+ if (bitmap[i] !== bitmap[i + 1] || bitmap[i] !== bitmap[i + 2])
120
+ return 3;
121
+ return 1;
122
+ }
123
+ clone() {
124
+ const copy = Object.create(GainMap.prototype);
125
+ copy.__set_params__(this.__params__());
126
+ copy.__pixels__ = this.__pixels__.clone();
127
+ return copy;
128
+ }
129
+ __body__(quality, width, height) {
130
+ let image = this.image;
131
+ if (width !== undefined && height !== undefined && (width !== image.width || height !== image.height))
132
+ image = image.clone().resize(width, height);
133
+ const bitmap = image.bitmap;
134
+ const pixels = new Uint8Array(bitmap.buffer, bitmap.byteOffset, bitmap.byteLength);
135
+ const grey = this.channels === 1;
136
+ return jpeg.encode(pixels, image.width, image.height, quality ?? 90, { grey, fullChroma: !grey });
137
+ }
138
+ __neutral__() {
139
+ return [0, 1, 2].map(c => {
140
+ const min = this.gainMapMin[c], max = this.gainMapMax[c];
141
+ const t = max > min ? Math.min(1, Math.max(0, -min / (max - min))) : 0;
142
+ return Math.round(255 * t ** this.gamma[c]);
143
+ });
144
+ }
145
+ __rescale__(oldWidth, oldHeight, width, height) {
146
+ const mapWidth = Math.max(1, Math.round(width * this.width / oldWidth)), mapHeight = Math.max(1, Math.round(height * this.height / oldHeight));
147
+ if (mapWidth === this.width && mapHeight === this.height)
148
+ return;
149
+ this.image = this.image.clone().resize(mapWidth, mapHeight);
150
+ }
151
+ __transform__(oldWidth, oldHeight, width, height, toOld, zoom = 1) {
152
+ let map = this.image;
153
+ const mapWidth = Math.max(1, Math.round(width * map.width / oldWidth)), mapHeight = Math.max(1, Math.round(height * map.height / oldHeight));
154
+ if (zoom < 0.5)
155
+ map = map.clone().resize(Math.max(1, Math.round(map.width * zoom * 2)), Math.max(1, Math.round(map.height * zoom * 2)));
156
+ const sx = map.width / oldWidth, sy = map.height / oldHeight;
157
+ const src = map.bitmap, mw = map.width, mh = map.height;
158
+ const out = new Image(mapWidth, mapHeight), dst = out.bitmap;
159
+ const neutral = this.__neutral__();
160
+ for (let j = 0, d = 0; j < mapHeight; j++) {
161
+ for (let i = 0; i < mapWidth; i++, d += 4) {
162
+ dst[d + 3] = 255;
163
+ const old = toOld((i + 0.5) * width / mapWidth, (j + 0.5) * height / mapHeight);
164
+ if (!old || !(old[0] >= 0 && old[0] <= oldWidth && old[1] >= 0 && old[1] <= oldHeight)) {
165
+ dst[d] = neutral[0];
166
+ dst[d + 1] = neutral[1];
167
+ dst[d + 2] = neutral[2];
168
+ continue;
169
+ }
170
+ const u = Math.min(mw - 1, Math.max(0, old[0] * sx - 0.5)), v = Math.min(mh - 1, Math.max(0, old[1] * sy - 0.5));
171
+ const x0 = Math.floor(u), y0 = Math.floor(v), x1 = Math.min(mw - 1, x0 + 1), y1 = Math.min(mh - 1, y0 + 1);
172
+ const fx = u - x0, fy = v - y0;
173
+ const a = 4 * (y0 * mw + x0), b = 4 * (y0 * mw + x1), c = 4 * (y1 * mw + x0), e = 4 * (y1 * mw + x1);
174
+ for (let k = 0; k < 3; k++)
175
+ dst[d + k] = (src[a + k] * (1 - fx) + src[b + k] * fx) * (1 - fy) + (src[c + k] * (1 - fx) + src[e + k] * fx) * fy;
176
+ }
177
+ }
178
+ this.image = out;
179
+ }
180
+ async encode(quality) {
181
+ if (quality !== undefined)
182
+ quality = Math.max(1, checkQuality(quality));
183
+ return codec.mapWithMetadata(this.__body__(quality), this.__params__());
184
+ }
185
+ static async decode(data) {
186
+ const bytes = view(data);
187
+ const found = codec.find(bytes);
188
+ if (found)
189
+ return GainMap.__from_jpeg__(found.map, found.params, found.apple);
190
+ const params = codec.readParams(bytes);
191
+ if (!params)
192
+ throw new Error('No gain map (or no gain map parameters) found');
193
+ return GainMap.__from_jpeg__(bytes, params);
194
+ }
195
+ }
package/dist/image.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { ToneMapping } from './codecs/hdr.js';
2
2
  import { BinaryData } from './util/mem.js';
3
3
  import { TextLayout } from './text-layout.js';
4
4
  import { Metadata } from './metadata.js';
5
+ import { GainMap } from './gainmap.js';
5
6
  /** A color as a 32-bit RGBA integer (`0xRRGGBBAA`) */
6
7
  export type Color = number;
7
8
  /** Called with a pixel's (0-based) coordinates, returns its color */
@@ -65,6 +66,15 @@ export interface JPEGEncodeOptions {
65
66
  quality?: number;
66
67
  /** Metadata to include, see {@link Metadata} */
67
68
  metadata?: Metadata;
69
+ /**
70
+ * Whether to write the image's {@link Image.gainMap} (an Ultra HDR JPEG, brighter on HDR displays), or how:
71
+ * `quality` the map's JPEG quality (default: `90`), `scale` its size as a factor of the image's (0-1, default: the
72
+ * map's size). Default: `true` (written if there is one)
73
+ */
74
+ gainMap?: boolean | {
75
+ quality?: number;
76
+ scale?: number;
77
+ };
68
78
  }
69
79
  /** Options of {@link Image.encodeWebP} */
70
80
  export interface WebPEncodeOptions {
@@ -171,6 +181,11 @@ export interface DecodeOptions {
171
181
  * brighter than white. Default: `'reinhard'`
172
182
  */
173
183
  toneMapping?: ToneMapping;
184
+ /**
185
+ * Whether to read the gain maps of JPEGs (Ultra HDR, JPEG-R, ISO 21496-1, Apple's), AVIFs (tone mapped items) and
186
+ * JPEG XLs (jhgm boxes) into {@link Image.gainMap}. Default: `true`
187
+ */
188
+ gainMap?: boolean;
174
189
  /**
175
190
  * At most this many worker threads decode in parallel (lossy JPEG XLs from 4 megapixels on, one per 2 megapixels
176
191
  * at most, lossless ones from 1.5 megapixels and 512 KiB on; AVIFs from 4 megapixels on: the conversion to RGB,
@@ -205,6 +220,15 @@ export interface JXLEncodeOptions {
205
220
  threads?: number;
206
221
  /** Metadata to include, see {@link Metadata} */
207
222
  metadata?: Metadata;
223
+ /**
224
+ * Whether to write the image's {@link Image.gainMap} (brighter on HDR displays: a jhgm box, like libjxl's), or how:
225
+ * `quality` (1-100 like `quality`, 100 lossless; default `90`) and `scale` (its size relative to the image, default
226
+ * its own). Default: `true`
227
+ */
228
+ gainMap?: boolean | {
229
+ quality?: number;
230
+ scale?: number;
231
+ };
208
232
  }
209
233
  /** Options of {@link Image.encodeAVIF} */
210
234
  export interface AVIFEncodeOptions {
@@ -225,6 +249,15 @@ export interface AVIFEncodeOptions {
225
249
  threads?: number;
226
250
  /** Metadata to include, see {@link Metadata} */
227
251
  metadata?: Metadata;
252
+ /**
253
+ * Whether to write the image's {@link Image.gainMap} (brighter on HDR displays: a tone mapped item, like libavif
254
+ * writes), or how: `quality` (1-100, default `90`) and `scale` (its size relative to the image, default its own).
255
+ * Default: `true`
256
+ */
257
+ gainMap?: boolean | {
258
+ quality?: number;
259
+ scale?: number;
260
+ };
228
261
  }
229
262
  /** Text style options of {@link Image.renderText} */
230
263
  export interface TextStyle {
@@ -313,6 +346,12 @@ export declare class Image {
313
346
  * @param height
314
347
  */
315
348
  constructor(width: number, height: number);
349
+ /**
350
+ * The image's gain map, if it has one (JPEGs from phones, Ultra HDR): how much brighter each part gets on HDR
351
+ * displays. {@link Image.encodeJPEG} writes it. `null` removes it
352
+ */
353
+ get gainMap(): GainMap | null;
354
+ set gainMap(gainMap: GainMap | null);
316
355
  /**
317
356
  * The image's RGBA pixel data. It can be replaced by any 8-bit array with width * height * 4 bytes
318
357
  * (it is used as is, without copying)
@@ -877,7 +916,7 @@ export declare class Image {
877
916
  * Encodes the image as AVIF (AV1, with an alpha image if the image has transparency)
878
917
  * @param options See {@link AVIFEncodeOptions}
879
918
  */
880
- encodeAVIF({ quality, alphaQuality, subsampling, effort, threads, metadata }?: AVIFEncodeOptions): Promise<Uint8Array>;
919
+ encodeAVIF({ quality, alphaQuality, subsampling, effort, threads, metadata, gainMap }?: AVIFEncodeOptions): Promise<Uint8Array>;
881
920
  /**
882
921
  * Encodes the image as JPEG XL: losslessly (the default) like libjxl's `cjxl -e 3` (a palette of up to 1024 colors,
883
922
  * else palettes of channels using few of their values; YCoCg; the weighted predictor in contexts of its error;
@@ -888,7 +927,7 @@ export declare class Image {
888
927
  * container, with the metadata as Exif
889
928
  * @param options See {@link JXLEncodeOptions}
890
929
  */
891
- encodeJXL({ quality, effort, threads, metadata }?: JXLEncodeOptions): Promise<Uint8Array>;
930
+ encodeJXL({ quality, effort, threads, metadata, gainMap }?: JXLEncodeOptions): Promise<Uint8Array>;
892
931
  /**
893
932
  * Encodes the image as the smallest fitting Netpbm format: PBM for black and white images, PGM for greyscale ones,
894
933
  * PPM for others, PAM if the image has transparency