imagescript 3.14.0 → 3.16.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.
@@ -0,0 +1,446 @@
1
+ const XMP_NAMESPACE = 'http://ns.adobe.com/xap/1.0/\0';
2
+ const ISO_NAMESPACE = 'urn:iso:std:iso:ts:21496:-1\0';
3
+ const MPF_SIGNATURE = 'MPF\0';
4
+ const HDRGM_URI = 'http://ns.adobe.com/hdr-gain-map/1.0/';
5
+ const APPLE_GAIN_MAP = 'urn:com:apple:photo:2020:aux:hdrgainmap';
6
+ export const APPLE_GAMMA = 1.961;
7
+ const ascii = (text) => Uint8Array.from(text, c => c.charCodeAt(0));
8
+ const startsWith = (data, offset, text) => {
9
+ if (offset + text.length > data.length)
10
+ return false;
11
+ for (let i = 0; i < text.length; i++)
12
+ if (data[offset + i] !== text.charCodeAt(i))
13
+ return false;
14
+ return true;
15
+ };
16
+ const latin1 = (data) => {
17
+ let text = '';
18
+ for (let i = 0; i < data.length; i += 0x8000)
19
+ text += String.fromCharCode(...data.subarray(i, i + 0x8000));
20
+ return text;
21
+ };
22
+ export function segments(data) {
23
+ const out = [];
24
+ if (data[0] !== 0xff || data[1] !== 0xd8)
25
+ return out;
26
+ let p = 2;
27
+ while (p + 4 <= data.length) {
28
+ if (data[p] !== 0xff)
29
+ break;
30
+ const marker = data[p + 1];
31
+ if (marker === 0xff) {
32
+ p++;
33
+ continue;
34
+ }
35
+ if (marker === 0xda || marker === 0xd9)
36
+ break;
37
+ if (marker >= 0xd0 && marker <= 0xd7 || marker === 0x01) {
38
+ p += 2;
39
+ continue;
40
+ }
41
+ const length = data[p + 2] << 8 | data[p + 3];
42
+ if (length < 2 || p + 2 + length > data.length)
43
+ break;
44
+ out.push({ marker, start: p, end: p + 2 + length, body: data.subarray(p + 4, p + 2 + length) });
45
+ p += 2 + length;
46
+ }
47
+ return out;
48
+ }
49
+ export function componentCount(data) {
50
+ for (const { marker, body } of segments(data))
51
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc)
52
+ return body[5] ?? 0;
53
+ return 0;
54
+ }
55
+ export function dimensions(data) {
56
+ for (const { marker, body } of segments(data))
57
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc && body.length >= 5)
58
+ return { width: body[3] << 8 | body[4], height: body[1] << 8 | body[2] };
59
+ return null;
60
+ }
61
+ function mpfImages(data, primary) {
62
+ const images = [];
63
+ for (const { marker, body, start } of primary) {
64
+ if (marker !== 0xe2 || !startsWith(body, 0, MPF_SIGNATURE))
65
+ continue;
66
+ const tiff = start + 4 + 4;
67
+ const view = new DataView(data.buffer, data.byteOffset + tiff, body.length - 4);
68
+ if (view.byteLength < 8)
69
+ return images;
70
+ const little = view.getUint16(0) === 0x4949;
71
+ const u16 = (o) => view.getUint16(o, little), u32 = (o) => view.getUint32(o, little);
72
+ const ifd = u32(4);
73
+ if (ifd + 2 > view.byteLength)
74
+ return images;
75
+ const count = u16(ifd);
76
+ let entries = -1, imageCount = 0;
77
+ for (let k = 0; k < count; k++) {
78
+ const t = ifd + 2 + 12 * k;
79
+ if (t + 12 > view.byteLength)
80
+ return images;
81
+ const tag = u16(t);
82
+ if (tag === 0xb001)
83
+ imageCount = u32(t + 8);
84
+ if (tag === 0xb002)
85
+ entries = u32(t + 8);
86
+ }
87
+ if (entries < 0 || imageCount < 2)
88
+ return images;
89
+ for (let k = 1; k < imageCount; k++) {
90
+ const e = entries + 16 * k;
91
+ if (e + 16 > view.byteLength)
92
+ return images;
93
+ const size = u32(e + 4), offset = u32(e + 8);
94
+ if (!offset || !size)
95
+ continue;
96
+ const begin = tiff + offset;
97
+ if (begin + size > data.length || data[begin] !== 0xff || data[begin + 1] !== 0xd8)
98
+ continue;
99
+ images.push(data.subarray(begin, begin + size));
100
+ }
101
+ return images;
102
+ }
103
+ return images;
104
+ }
105
+ function containerSecondImage(data, primary) {
106
+ for (const { marker, body } of primary) {
107
+ if (marker !== 0xe1 || !startsWith(body, 0, XMP_NAMESPACE))
108
+ continue;
109
+ const xmp = latin1(body.subarray(XMP_NAMESPACE.length));
110
+ const item = /Item:Semantic\s*=\s*["']GainMap["'][^>]*?Item:Length\s*=\s*["'](\d+)["']|Item:Length\s*=\s*["'](\d+)["'][^>]*?Item:Semantic\s*=\s*["']GainMap["']/.exec(xmp);
111
+ if (!item)
112
+ return null;
113
+ const length = Number(item[1] ?? item[2]), begin = data.length - length;
114
+ if (!(length > 0) || begin <= 0 || data[begin] !== 0xff || data[begin + 1] !== 0xd8)
115
+ return null;
116
+ return data.subarray(begin);
117
+ }
118
+ return null;
119
+ }
120
+ export function find(data) {
121
+ const primary = segments(data);
122
+ const images = mpfImages(data, primary);
123
+ const container = containerSecondImage(data, primary);
124
+ if (container)
125
+ images.push(container);
126
+ for (const map of images) {
127
+ const params = readParams(map);
128
+ if (params)
129
+ return { map, params };
130
+ }
131
+ for (const map of images) {
132
+ const apple = readApple(map, primary);
133
+ if (apple)
134
+ return { map, ...apple };
135
+ }
136
+ return null;
137
+ }
138
+ export const appleValue = (value, headroom) => Math.log2(1 + (headroom - 1) * value ** APPLE_GAMMA) / Math.log2(headroom);
139
+ function readApple(map, primary) {
140
+ let xmp = null;
141
+ for (const { marker, body } of segments(map))
142
+ if (marker === 0xe1 && startsWith(body, 0, XMP_NAMESPACE))
143
+ xmp = latin1(body.subarray(XMP_NAMESPACE.length));
144
+ if (!xmp || !xmp.includes(APPLE_GAIN_MAP) || !/HDRGainMapVersion/.test(xmp))
145
+ return null;
146
+ const value = (name) => {
147
+ const m = new RegExp(`:${name}\\s*(?:=\\s*["']([^"']*)["']|>([^<]*)<)`).exec(xmp);
148
+ return m ? Number((m[1] ?? m[2]).trim()) : null;
149
+ };
150
+ const headroom = value('HDRGainMapHeadroom') ?? makerNoteHeadroom(primary);
151
+ if (!(headroom !== null && headroom > 1 && Number.isFinite(headroom)))
152
+ return null;
153
+ const stops = Math.log2(headroom);
154
+ const params = { min: [0, 0, 0], max: [stops, stops, stops], gamma: [1, 1, 1], offsetSDR: [0, 0, 0], offsetHDR: [0, 0, 0], capacityMin: 0, capacityMax: stops, useBaseColorSpace: true };
155
+ return { params, apple: headroom };
156
+ }
157
+ function makerNoteHeadroom(primary) {
158
+ const exif = primary.find(({ marker, body }) => marker === 0xe1 && startsWith(body, 0, 'Exif\0\0'));
159
+ if (!exif)
160
+ return null;
161
+ const tiff = exif.body.subarray(6);
162
+ if (tiff.length < 8)
163
+ return null;
164
+ const view = new DataView(tiff.buffer, tiff.byteOffset, tiff.byteLength);
165
+ const little = view.getUint16(0) === 0x4949;
166
+ const entries = (v, at, le) => {
167
+ if (at + 2 > v.byteLength)
168
+ return [];
169
+ const out = [];
170
+ for (let k = 0, n = v.getUint16(at, le); k < n && at + 2 + 12 * k + 12 <= v.byteLength; k++) {
171
+ const e = at + 2 + 12 * k;
172
+ out.push({ tag: v.getUint16(e, le), type: v.getUint16(e + 2, le), count: v.getUint32(e + 4, le), value: v.getUint32(e + 8, le) });
173
+ }
174
+ return out;
175
+ };
176
+ const sub = entries(view, view.getUint32(4, little), little).find(e => e.tag === 0x8769);
177
+ const note = sub && entries(view, sub.value, little).find(e => e.tag === 0x927c);
178
+ if (!note || note.value + note.count > tiff.length)
179
+ return null;
180
+ const maker = tiff.subarray(note.value, note.value + note.count);
181
+ if (!startsWith(maker, 0, 'Apple iOS\0\0\x01MM'))
182
+ return null;
183
+ const mv = new DataView(maker.buffer, maker.byteOffset, maker.byteLength);
184
+ let m33 = null, m48 = 0;
185
+ for (const { tag, type, count, value } of entries(mv, 14, false)) {
186
+ if ((tag !== 33 && tag !== 48) || type !== 10 || count < 1 || value + 8 > maker.length)
187
+ continue;
188
+ const d = mv.getUint32(value + 4);
189
+ if (!d)
190
+ continue;
191
+ const r = mv.getInt32(value) / d;
192
+ if (tag === 33)
193
+ m33 = r;
194
+ else
195
+ m48 = r;
196
+ }
197
+ if (m33 === null)
198
+ return null;
199
+ const stops = m33 < 1 ? (m48 <= 0.01 ? -20 * m48 + 1.8 : -0.101 * m48 + 1.601) : (m48 <= 0.01 ? -70 * m48 + 3 : -0.303 * m48 + 2.303);
200
+ return 2 ** Math.max(stops, 0);
201
+ }
202
+ export function readParams(map) {
203
+ const list = segments(map);
204
+ for (const { marker, body } of list)
205
+ if (marker === 0xe2 && startsWith(body, 0, ISO_NAMESPACE)) {
206
+ const params = readISO(body.subarray(ISO_NAMESPACE.length));
207
+ if (params)
208
+ return params;
209
+ }
210
+ for (const { marker, body } of list)
211
+ if (marker === 0xe1 && startsWith(body, 0, XMP_NAMESPACE)) {
212
+ const params = readXMP(latin1(body.subarray(XMP_NAMESPACE.length)));
213
+ if (params)
214
+ return params;
215
+ }
216
+ return null;
217
+ }
218
+ export function valid(p) {
219
+ const ok = (v) => Number.isFinite(v);
220
+ for (let c = 0; c < 3; c++)
221
+ if (!ok(p.min[c]) || !ok(p.max[c]) || !ok(p.gamma[c]) || !ok(p.offsetSDR[c]) || !ok(p.offsetHDR[c]) || p.gamma[c] <= 0 || p.max[c] < p.min[c])
222
+ return false;
223
+ return ok(p.capacityMin) && ok(p.capacityMax) && p.capacityMax > p.capacityMin && p.capacityMin >= 0;
224
+ }
225
+ export function readISO(data) {
226
+ if (data.length < 5)
227
+ return null;
228
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
229
+ if (view.getUint16(0) !== 0)
230
+ return null;
231
+ const flags = data[4];
232
+ if (flags & 4)
233
+ return null;
234
+ const channels = flags & 0x80 ? 3 : 1, common = (flags & 8) !== 0;
235
+ let p = 5;
236
+ const need = (n) => p + n <= data.length;
237
+ let denominator = 1;
238
+ if (common) {
239
+ if (!need(4))
240
+ return null;
241
+ denominator = view.getUint32(p);
242
+ p += 4;
243
+ if (!denominator)
244
+ return null;
245
+ }
246
+ const fraction = (signed) => {
247
+ if (!need(common ? 4 : 8))
248
+ return NaN;
249
+ const n = signed ? view.getInt32(p) : view.getUint32(p);
250
+ const d = common ? denominator : view.getUint32(p + 4);
251
+ p += common ? 4 : 8;
252
+ return d ? n / d : NaN;
253
+ };
254
+ const capacityMin = fraction(false), capacityMax = fraction(false);
255
+ const min = [], max = [], gamma = [], offsetSDR = [], offsetHDR = [];
256
+ for (let c = 0; c < channels; c++) {
257
+ min.push(fraction(true));
258
+ max.push(fraction(true));
259
+ gamma.push(fraction(false));
260
+ offsetSDR.push(fraction(true));
261
+ offsetHDR.push(fraction(true));
262
+ }
263
+ const params = { min: fill3(min), max: fill3(max), gamma: fill3(gamma), offsetSDR: fill3(offsetSDR), offsetHDR: fill3(offsetHDR), capacityMin, capacityMax, useBaseColorSpace: (flags & 0x40) !== 0 };
264
+ return valid(params) ? params : null;
265
+ }
266
+ const fill3 = (values) => values.length === 1 ? [values[0], values[0], values[0]] : values.slice(0, 3);
267
+ function readXMP(xmp) {
268
+ if (!xmp.includes(HDRGM_URI))
269
+ return null;
270
+ const prefix = /xmlns:([\w-]+)\s*=\s*["']http:\/\/ns\.adobe\.com\/hdr-gain-map\/1\.0\/["']/.exec(xmp)?.[1] ?? 'hdrgm';
271
+ const get = (name) => {
272
+ const attribute = new RegExp(`${prefix}:${name}\\s*=\\s*["']([^"']*)["']`).exec(xmp);
273
+ if (attribute)
274
+ return [attribute[1]];
275
+ const element = new RegExp(`<${prefix}:${name}>([\\s\\S]*?)</${prefix}:${name}>`).exec(xmp);
276
+ if (!element)
277
+ return null;
278
+ const items = [...element[1].matchAll(/<rdf:li[^>]*>([^<]*)<\/rdf:li>/g)].map(m => m[1]);
279
+ return items.length ? items : [element[1].trim()];
280
+ };
281
+ const numbers = (name, fallback) => {
282
+ const values = get(name);
283
+ if (!values)
284
+ return fallback === null ? null : [fallback, fallback, fallback];
285
+ if (values.length !== 1 && values.length !== 3)
286
+ return null;
287
+ const parsed = values.map(v => v.trim() === '' ? NaN : Number(v));
288
+ return fill3(parsed);
289
+ };
290
+ if (!get('Version'))
291
+ return null;
292
+ if (/^\s*true\s*$/i.test(get('BaseRenditionIsHDR')?.[0] ?? ''))
293
+ return null;
294
+ const max = numbers('GainMapMax', null), capacityMax = numbers('HDRCapacityMax', null);
295
+ const min = numbers('GainMapMin', 0), gamma = numbers('Gamma', 1);
296
+ const offsetSDR = numbers('OffsetSDR', 1 / 64), offsetHDR = numbers('OffsetHDR', 1 / 64), capacityMin = numbers('HDRCapacityMin', 0);
297
+ if (!max || !capacityMax || !min || !gamma || !offsetSDR || !offsetHDR || !capacityMin)
298
+ return null;
299
+ const params = { min, max, gamma, offsetSDR, offsetHDR, capacityMin: capacityMin[0], capacityMax: capacityMax[0], useBaseColorSpace: true };
300
+ return valid(params) ? params : null;
301
+ }
302
+ const identical = (values) => values[0] === values[1] && values[0] === values[2];
303
+ export function singleChannel(p) {
304
+ return identical(p.min) && identical(p.max) && identical(p.gamma) && identical(p.offsetSDR) && identical(p.offsetHDR);
305
+ }
306
+ function toFraction(value, signed) {
307
+ const limit = signed ? 0x7fffffff : 0xffffffff;
308
+ let d = 1 << 30;
309
+ while (d > 1 && Math.abs(value) * d > limit)
310
+ d /= 2;
311
+ if (!signed && Math.abs(value) * d * 2 <= limit)
312
+ d *= 2;
313
+ return [Math.round(value * d), d];
314
+ }
315
+ export function writeISO(p) {
316
+ const channels = singleChannel(p) ? 1 : 3;
317
+ const out = new Uint8Array(5 + 16 + channels * 40);
318
+ const view = new DataView(out.buffer);
319
+ out[4] = (channels === 3 ? 0x80 : 0) | (p.useBaseColorSpace ? 0x40 : 0);
320
+ let o = 5;
321
+ const write = (value, signed) => {
322
+ const [n, d] = toFraction(value, signed);
323
+ if (signed)
324
+ view.setInt32(o, n);
325
+ else
326
+ view.setUint32(o, n);
327
+ view.setUint32(o + 4, d);
328
+ o += 8;
329
+ };
330
+ write(p.capacityMin, false);
331
+ write(p.capacityMax, false);
332
+ for (let c = 0; c < channels; c++) {
333
+ write(p.min[c], true);
334
+ write(p.max[c], true);
335
+ write(p.gamma[c], false);
336
+ write(p.offsetSDR[c], true);
337
+ write(p.offsetHDR[c], true);
338
+ }
339
+ return out;
340
+ }
341
+ const number = (v) => String(Math.round(v * 1e6) / 1e6);
342
+ export function writeMapXMP(p) {
343
+ const attributes = [`hdrgm:Version="1.0"`];
344
+ const elements = [];
345
+ const add = (name, values) => {
346
+ if (identical(values))
347
+ attributes.push(`hdrgm:${name}="${number(values[0])}"`);
348
+ else
349
+ elements.push(`<hdrgm:${name}><rdf:Seq>${values.map(v => `<rdf:li>${number(v)}</rdf:li>`).join('')}</rdf:Seq></hdrgm:${name}>`);
350
+ };
351
+ add('GainMapMin', p.min);
352
+ add('GainMapMax', p.max);
353
+ add('Gamma', p.gamma);
354
+ add('OffsetSDR', p.offsetSDR);
355
+ add('OffsetHDR', p.offsetHDR);
356
+ attributes.push(`hdrgm:HDRCapacityMin="${number(p.capacityMin)}"`, `hdrgm:HDRCapacityMax="${number(p.capacityMax)}"`, 'hdrgm:BaseRenditionIsHDR="False"');
357
+ const description = `<rdf:Description rdf:about="" xmlns:hdrgm="${HDRGM_URI}" ${attributes.join(' ')}${elements.length ? `>${elements.join('')}</rdf:Description>` : '/>'}`;
358
+ return `<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="ImageScript"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">${description}</rdf:RDF></x:xmpmeta>`;
359
+ }
360
+ export function writePrimaryXMP(mapLength) {
361
+ return '<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="ImageScript"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'
362
+ + `<rdf:Description xmlns:Container="http://ns.google.com/photos/1.0/container/" xmlns:Item="http://ns.google.com/photos/1.0/container/item/" xmlns:hdrgm="${HDRGM_URI}" hdrgm:Version="1.0">`
363
+ + '<Container:Directory><rdf:Seq>'
364
+ + '<rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="Primary" Item:Mime="image/jpeg"/></rdf:li>'
365
+ + `<rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="GainMap" Item:Mime="image/jpeg" Item:Length="${mapLength}"/></rdf:li>`
366
+ + '</rdf:Seq></Container:Directory></rdf:Description></rdf:RDF></x:xmpmeta>';
367
+ }
368
+ const segmentBytes = (marker, body) => {
369
+ if (body.length > 65533)
370
+ throw new RangeError('JPEG: metadata too large');
371
+ const out = new Uint8Array(4 + body.length);
372
+ out.set([0xff, marker, body.length + 2 >> 8, body.length + 2 & 255]);
373
+ out.set(body, 4);
374
+ return out;
375
+ };
376
+ const join = (parts) => {
377
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
378
+ let o = 0;
379
+ for (const p of parts) {
380
+ out.set(p, o);
381
+ o += p.length;
382
+ }
383
+ return out;
384
+ };
385
+ export function stripMetadata(jpeg) {
386
+ const remove = segments(jpeg).filter(({ marker, body }) => marker === 0xe1 && startsWith(body, 0, XMP_NAMESPACE)
387
+ || marker === 0xe2 && (startsWith(body, 0, ISO_NAMESPACE) || startsWith(body, 0, MPF_SIGNATURE)));
388
+ if (!remove.length)
389
+ return jpeg;
390
+ const parts = [];
391
+ let p = 0;
392
+ for (const { start, end } of remove) {
393
+ parts.push(jpeg.subarray(p, start));
394
+ p = end;
395
+ }
396
+ parts.push(jpeg.subarray(p));
397
+ return join(parts);
398
+ }
399
+ function insert(jpeg, added) {
400
+ let at = 2;
401
+ if (jpeg[2] === 0xff && jpeg[3] === 0xe0)
402
+ at = 4 + (jpeg[4] << 8 | jpeg[5]);
403
+ return join([jpeg.subarray(0, at), ...added, jpeg.subarray(at)]);
404
+ }
405
+ export function mapWithMetadata(body, p) {
406
+ const added = [segmentBytes(0xe1, join([ascii(XMP_NAMESPACE), ascii(writeMapXMP(p))])), segmentBytes(0xe2, join([ascii(ISO_NAMESPACE), writeISO(p)]))];
407
+ return insert(stripMetadata(body), added);
408
+ }
409
+ const MPF_LENGTH = 4 + 50 + 32;
410
+ export function primarySegments(mapLength) {
411
+ return [
412
+ segmentBytes(0xe1, join([ascii(XMP_NAMESPACE), ascii(writePrimaryXMP(mapLength))])),
413
+ segmentBytes(0xe2, join([ascii(ISO_NAMESPACE), new Uint8Array(4)])),
414
+ segmentBytes(0xe2, join([ascii(MPF_SIGNATURE), new Uint8Array(MPF_LENGTH - 4)]))
415
+ ];
416
+ }
417
+ export function finish(primary, map) {
418
+ const mpf = segments(primary).find(({ marker, body }) => marker === 0xe2 && startsWith(body, 0, MPF_SIGNATURE));
419
+ if (!mpf)
420
+ throw new Error('JPEG: missing MPF segment');
421
+ const tiff = mpf.start + 4 + 4;
422
+ const view = new DataView(primary.buffer, primary.byteOffset + tiff, MPF_LENGTH - 4);
423
+ view.setUint32(0, 0x4d4d002a);
424
+ view.setUint32(4, 8);
425
+ view.setUint16(8, 3);
426
+ view.setUint16(10, 0xb000);
427
+ view.setUint16(12, 7);
428
+ view.setUint32(14, 4);
429
+ view.setUint32(18, 0x30313030);
430
+ view.setUint16(22, 0xb001);
431
+ view.setUint16(24, 4);
432
+ view.setUint32(26, 1);
433
+ view.setUint32(30, 2);
434
+ view.setUint16(34, 0xb002);
435
+ view.setUint16(36, 7);
436
+ view.setUint32(38, 32);
437
+ view.setUint32(42, 50);
438
+ view.setUint32(46, 0);
439
+ view.setUint32(50, 0x030000);
440
+ view.setUint32(54, primary.length);
441
+ view.setUint32(58, 0);
442
+ view.setUint32(66, 0);
443
+ view.setUint32(70, map.length);
444
+ view.setUint32(74, primary.length - tiff);
445
+ return join([primary, map]);
446
+ }
@@ -187,7 +187,9 @@ function createFrame(progressive, height, width, componentData) {
187
187
  blocksPerColumn: Math.ceil(componentHeight / 8),
188
188
  blocksPerLineForMcu,
189
189
  blocksPerColumnForMcu,
190
- coefficients: new Int16Array(blocksPerLineForMcu * blocksPerColumnForMcu * 64),
190
+ coefficients: new Int16Array(blocksPerLineForMcu * (progressive ? blocksPerColumnForMcu : c.v) * 64),
191
+ plane: progressive ? undefined : new Uint8Array(blocksPerLineForMcu * 8 * blocksPerColumnForMcu * 8),
192
+ done: progressive ? undefined : new Uint8Array(blocksPerColumnForMcu),
191
193
  pred: 0
192
194
  };
193
195
  });
@@ -374,6 +376,15 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
374
376
  ? components[0].blocksPerLine * components[0].blocksPerColumn
375
377
  : frame.mcusPerLine * frame.mcusPerColumn;
376
378
  const interval = restartInterval || total;
379
+ const sequential = !frame.progressive;
380
+ let pending = -1;
381
+ const finish = () => {
382
+ if (pending < 0)
383
+ return;
384
+ for (const component of components)
385
+ render(component, single ? pending : pending * component.v, single ? 1 : component.v);
386
+ pending = -1;
387
+ };
377
388
  for (const component of components)
378
389
  component.pred = 0;
379
390
  for (let unit = 0; unit < total;) {
@@ -382,18 +393,29 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
382
393
  const component = components[0];
383
394
  const row = unit / component.blocksPerLine | 0;
384
395
  const column = unit % component.blocksPerLine;
385
- decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
396
+ if (sequential) {
397
+ pending = row;
398
+ decodeBlock(component, column * 64);
399
+ if (column === component.blocksPerLine - 1)
400
+ finish();
401
+ }
402
+ else
403
+ decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
386
404
  }
387
405
  else {
388
406
  const mcuRow = unit / frame.mcusPerLine | 0;
389
407
  const mcuColumn = unit % frame.mcusPerLine;
408
+ if (sequential)
409
+ pending = mcuRow;
390
410
  for (const component of components)
391
411
  for (let v = 0; v < component.v; v++)
392
412
  for (let h = 0; h < component.h; h++) {
393
- const row = mcuRow * component.v + v;
413
+ const row = sequential ? v : mcuRow * component.v + v;
394
414
  const column = mcuColumn * component.h + h;
395
415
  decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
396
416
  }
417
+ if (sequential && mcuColumn === frame.mcusPerLine - 1)
418
+ finish();
397
419
  }
398
420
  }
399
421
  if (unit >= total)
@@ -401,19 +423,40 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
401
423
  bits = 0;
402
424
  buffer = 0;
403
425
  while (pos + 1 < data.length && !(data[pos] === 0xff && data[pos + 1] >= 0xd0 && data[pos + 1] <= 0xd7)) {
404
- if (data[pos] === 0xff && data[pos + 1] !== 0x00 && data[pos + 1] !== 0xff)
426
+ if (data[pos] === 0xff && data[pos + 1] !== 0x00 && data[pos + 1] !== 0xff) {
427
+ finish();
405
428
  return pos;
429
+ }
406
430
  pos++;
407
431
  }
408
- if (pos + 1 >= data.length)
432
+ if (pos + 1 >= data.length) {
433
+ finish();
409
434
  return pos;
435
+ }
410
436
  pos += 2;
411
437
  eobrun = 0;
412
438
  for (const component of components)
413
439
  component.pred = 0;
414
440
  }
441
+ finish();
415
442
  return pos;
416
443
  }
444
+ function render(component, row, count) {
445
+ const { plane, done, coefficients, blocksPerLineForMcu: line } = component;
446
+ if (!plane || !done)
447
+ return;
448
+ const stride = line * 8, workspace = new Int32Array(64);
449
+ const quantization = component.quantization || new Int32Array(64);
450
+ for (let r = 0; r < count; r++) {
451
+ const blockRow = row + r;
452
+ if (blockRow < component.blocksPerColumn) {
453
+ for (let column = 0; column < component.blocksPerLine; column++)
454
+ idct(coefficients, (r * line + column) * 64, quantization, workspace, plane, blockRow * 8 * stride + column * 8, stride);
455
+ done[blockRow] = 1;
456
+ }
457
+ }
458
+ coefficients.fill(0, 0, count * line * 64);
459
+ }
417
460
  const CONST_BITS = 13;
418
461
  const PASS1_BITS = 2;
419
462
  const FIX_0_298631336 = 2446;
@@ -527,6 +570,14 @@ function idct(coefficients, offset, quantization, workspace, out, outOffset, str
527
570
  }
528
571
  function buildPlane(component) {
529
572
  const stride = component.blocksPerLineForMcu * 8;
573
+ if (component.plane && component.done) {
574
+ const { plane, done } = component;
575
+ for (let row = 0; row < component.blocksPerColumn; row++)
576
+ if (!done[row])
577
+ for (let y = row * 8; y < row * 8 + 8; y++)
578
+ plane.fill(128, y * stride, y * stride + component.blocksPerLine * 8);
579
+ return { plane, stride };
580
+ }
530
581
  const plane = new Uint8Array(stride * component.blocksPerColumnForMcu * 8);
531
582
  const workspace = new Int32Array(64);
532
583
  const quantization = component.quantization || new Int32Array(64);
@@ -756,7 +807,7 @@ function reciprocals(table) {
756
807
  }
757
808
  return r;
758
809
  }
759
- 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 } = {}) {
760
811
  if (!width || !height || width > 0xffff || height > 0xffff)
761
812
  throw new RangeError('JPEG: invalid dimensions');
762
813
  quality = Math.min(100, Math.max(1, Math.round(quality)));
@@ -764,7 +815,7 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
764
815
  const scaleTable = (base) => base.map(v => Math.min(255, Math.max(1, Math.floor((v * scale + 50) / 100))));
765
816
  const tables = [scaleTable(LUMA_QUANTIZATION), scaleTable(CHROMA_QUANTIZATION)];
766
817
  const divisors = tables.map(reciprocals);
767
- const subsample = quality <= 90;
818
+ const subsample = quality <= 90 && !grey && !fullChroma;
768
819
  const hmax = subsample ? 2 : 1;
769
820
  const mcuSize = 8 * hmax;
770
821
  const mcusPerLine = Math.ceil(width / mcuSize);
@@ -818,8 +869,8 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
818
869
  { plane: Y, stride: W, h: hmax, v: hmax, blocksX: lumaBlocksX, blocksY: lumaBlocksY, table: 0 },
819
870
  { plane: Cb, stride: CW, h: 1, v: 1, blocksX: chromaBlocksX, blocksY: chromaBlocksY, table: 1 },
820
871
  { plane: Cr, stride: CW, h: 1, v: 1, blocksX: chromaBlocksX, blocksY: chromaBlocksY, table: 1 }
821
- ];
822
- const blocksPerMcu = hmax * hmax + 2;
872
+ ].slice(0, grey ? 1 : 3);
873
+ const blocksPerMcu = grey ? 1 : hmax * hmax + 2;
823
874
  const count = mcusPerLine * mcusPerColumn * blocksPerMcu;
824
875
  const coefficients = new Int16Array(count * 64);
825
876
  const owners = new Uint8Array(count), ends = new Uint8Array(count);
@@ -827,7 +878,7 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
827
878
  let n = 0;
828
879
  for (let my = 0; my < mcusPerColumn; my++)
829
880
  for (let mx = 0; mx < mcusPerLine; mx++)
830
- for (let c = 0; c < 3; c++) {
881
+ for (let c = 0; c < components.length; c++) {
831
882
  const { plane, stride, h: ch, v: cv, blocksX, blocksY, table } = components[c];
832
883
  const reciprocal = divisors[table];
833
884
  for (let v = 0; v < cv; v++) {
@@ -859,7 +910,7 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
859
910
  const blocks = { coefficients, owners, ends, count };
860
911
  const frequencies = [new Int32Array(257), new Int32Array(257), new Int32Array(257), new Int32Array(257)];
861
912
  countSymbols(blocks, frequencies);
862
- const huffman = frequencies.map(buildOptimalTable);
913
+ const huffman = frequencies.slice(0, grey ? 2 : 4).map(buildOptimalTable);
863
914
  const writer = new BitWriter(width * height);
864
915
  writer.bytes(0xff, 0xd8);
865
916
  writer.bytes(0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00);
@@ -874,14 +925,22 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
874
925
  segment(0xe1, concat([[0x45, 0x78, 0x69, 0x66, 0, 0], exif]));
875
926
  if (comment)
876
927
  segment(0xfe, comment);
877
- for (let t = 0; t < 2; t++) {
928
+ if (segments)
929
+ for (const bytes of segments)
930
+ for (let i = 0; i < bytes.length; i++)
931
+ writer.bytes(bytes[i]);
932
+ for (let t = 0; t < (grey ? 1 : 2); t++) {
878
933
  writer.bytes(0xff, 0xdb, 0x00, 0x43, t);
879
934
  for (let k = 0; k < 64; k++)
880
935
  writer.bytes(tables[t][ZIGZAG[k]]);
881
936
  }
882
- writer.bytes(0xff, 0xc0, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03);
883
- writer.bytes(1, hmax << 4 | hmax, 0, 2, 0x11, 1, 3, 0x11, 1);
884
- for (const [index, id] of [[0, 0x00], [1, 0x10], [2, 0x01], [3, 0x11]]) {
937
+ if (grey)
938
+ writer.bytes(0xff, 0xc0, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0);
939
+ else {
940
+ writer.bytes(0xff, 0xc0, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03);
941
+ writer.bytes(1, hmax << 4 | hmax, 0, 2, 0x11, 1, 3, 0x11, 1);
942
+ }
943
+ for (const [index, id] of [[0, 0x00], [1, 0x10], [2, 0x01], [3, 0x11]].slice(0, grey ? 2 : 4)) {
885
944
  const { bits, values } = huffman[index];
886
945
  const length = 19 + values.length;
887
946
  writer.bytes(0xff, 0xc4, length >> 8, length & 0xff, id);
@@ -890,7 +949,10 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
890
949
  for (const value of values)
891
950
  writer.bytes(value);
892
951
  }
893
- writer.bytes(0xff, 0xda, 0x00, 0x0c, 0x03, 1, 0x00, 2, 0x11, 3, 0x11, 0x00, 0x3f, 0x00);
952
+ if (grey)
953
+ writer.bytes(0xff, 0xda, 0x00, 0x08, 0x01, 1, 0x00, 0x00, 0x3f, 0x00);
954
+ else
955
+ writer.bytes(0xff, 0xda, 0x00, 0x0c, 0x03, 1, 0x00, 2, 0x11, 3, 0x11, 0x00, 0x3f, 0x00);
894
956
  writeBlocks(blocks, huffman, writer);
895
957
  writer.flush();
896
958
  writer.bytes(0xff, 0xd9);