@aboutgeo/pdiiif 0.0.0-stage → 0.2.7

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.
Files changed (69) hide show
  1. package/README.md +169 -2
  2. package/dist/__tests__/parser.test.d.ts +1 -0
  3. package/dist/__tests__/pdf.spec.d.ts +1 -0
  4. package/dist/__tests__/region.test.d.ts +1 -0
  5. package/dist/__tests__/setupJest.d.ts +0 -0
  6. package/dist/assets/optimization.worker-C8u4PFfM.js +886 -0
  7. package/dist/assets/optimization.worker-C8u4PFfM.js.map +1 -0
  8. package/dist/convert.d.ts +223 -0
  9. package/dist/download.d.ts +115 -0
  10. package/dist/iiif.d.ts +110 -0
  11. package/dist/index.cjs +65 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.mjs +11137 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/io.d.ts +75 -0
  17. package/dist/log.d.ts +21 -0
  18. package/dist/metrics.d.ts +10 -0
  19. package/dist/ocr.d.ts +36 -0
  20. package/dist/optimization.d.ts +48 -0
  21. package/dist/optimization.worker.d.ts +1 -0
  22. package/dist/pdf/annos-text.d.ts +19 -0
  23. package/dist/pdf/annos.d.ts +4 -0
  24. package/dist/pdf/common.d.ts +48 -0
  25. package/dist/pdf/generator.d.ts +197 -0
  26. package/dist/pdf/image.d.ts +34 -0
  27. package/dist/pdf/parser.d.ts +131 -0
  28. package/dist/pdf/pkzip.d.ts +23 -0
  29. package/dist/pdf/png.d.ts +34 -0
  30. package/dist/pdf/util.d.ts +18 -0
  31. package/dist/res/licenses.d.ts +7 -0
  32. package/dist/res/srgbColorspace.d.ts +2 -0
  33. package/dist/util.d.ts +8 -0
  34. package/dist/version.d.ts +2 -0
  35. package/package.json +149 -4
  36. package/src/__tests__/fixtures/deep_toc.json +2953 -0
  37. package/src/__tests__/fixtures/flat_toc.json +2917 -0
  38. package/src/__tests__/fixtures/physdim.json +294 -0
  39. package/src/__tests__/fixtures/region_target.json +58 -0
  40. package/src/__tests__/fixtures/wunder.jpg +0 -0
  41. package/src/__tests__/parser.test.ts +42 -0
  42. package/src/__tests__/pdf.spec.ts +216 -0
  43. package/src/__tests__/region.test.ts +194 -0
  44. package/src/__tests__/setupJest.ts +2 -0
  45. package/src/convert.ts +1098 -0
  46. package/src/download.ts +703 -0
  47. package/src/global.d.ts +10 -0
  48. package/src/iiif.ts +605 -0
  49. package/src/index.ts +7 -0
  50. package/src/io.ts +243 -0
  51. package/src/log.ts +51 -0
  52. package/src/metrics.ts +47 -0
  53. package/src/ocr.ts +176 -0
  54. package/src/optimization.ts +201 -0
  55. package/src/optimization.worker.ts +118 -0
  56. package/src/pdf/annos-text.ts +382 -0
  57. package/src/pdf/annos.ts +240 -0
  58. package/src/pdf/common.ts +158 -0
  59. package/src/pdf/generator.ts +1665 -0
  60. package/src/pdf/image.ts +340 -0
  61. package/src/pdf/parser.ts +811 -0
  62. package/src/pdf/pkzip.ts +228 -0
  63. package/src/pdf/png.ts +397 -0
  64. package/src/pdf/util.ts +111 -0
  65. package/src/res/licenses.ts +266 -0
  66. package/src/res/srgbColorspace.ts +405 -0
  67. package/src/types.d.ts +6 -0
  68. package/src/util.ts +55 -0
  69. package/src/version.ts +1 -0
package/src/io.ts ADDED
@@ -0,0 +1,243 @@
1
+ /** Types for writing to an output stream, with support for Node and Browsers. */
2
+ import type { Writable as NodeWritable } from 'stream';
3
+ import type nodeFs from 'fs';
4
+
5
+ import log from './log.js';
6
+
7
+ /** Base interface to be implemented by all readers. */
8
+ export interface Reader {
9
+ read(
10
+ dst: Uint8Array,
11
+ offset: number,
12
+ position: number,
13
+ length: number
14
+ ): Promise<number>;
15
+ size(): Promise<number>;
16
+ }
17
+
18
+ /** Base interface to be implemented by all writers. */
19
+ export interface Writer {
20
+ /** Write a chunk to the writer */
21
+ write(buffer: Uint8Array | string): Promise<void>;
22
+
23
+ /** Close the writer */
24
+ close(): Promise<void>;
25
+
26
+ /** Wait for the next drainage/flush event */
27
+ waitForDrain(): Promise<void>;
28
+ }
29
+
30
+ /** Reader implementation using the Web `File` API. */
31
+ export class WebReader implements Reader {
32
+ private file: File;
33
+
34
+ constructor(file: File) {
35
+ this.file = file;
36
+ }
37
+
38
+ async read(
39
+ dst: Uint8Array,
40
+ offset: number,
41
+ position: number,
42
+ length: number
43
+ ): Promise<number> {
44
+ const blob = this.file.slice(position, position + length);
45
+ const buf = await blob.arrayBuffer();
46
+ dst.set(new Uint8Array(buf), offset);
47
+ return buf.byteLength;
48
+ }
49
+
50
+ size(): Promise<number> {
51
+ return new Promise((resolve) => resolve(this.file.size));
52
+ }
53
+ }
54
+
55
+ /** Wraps a writer and counts the bytes written to it. */
56
+ export class CountingWriter implements Writer {
57
+ private _writer: Writer;
58
+ bytesWritten = 0;
59
+
60
+ constructor(writer: Writer) {
61
+ this._writer = writer;
62
+ }
63
+
64
+ write(buffer: string | Uint8Array): Promise<void> {
65
+ this.bytesWritten += buffer.length;
66
+ return this._writer.write(buffer);
67
+ }
68
+
69
+ close(): Promise<void> {
70
+ return this._writer.close();
71
+ }
72
+
73
+ waitForDrain(): Promise<void> {
74
+ return this._writer.waitForDrain();
75
+ }
76
+ }
77
+
78
+ /** A Writer implemented using the `File System Access API` available in
79
+ * recent Chrome, Edge and Opera browsers. */
80
+ export class WebWriter implements Writer {
81
+ private _writer: WritableStreamDefaultWriter<any>;
82
+
83
+ constructor(stream: WritableStream) {
84
+ this._writer = stream.getWriter();
85
+ }
86
+
87
+ write(buffer: string | Uint8Array): Promise<void> {
88
+ return this._writer.write(buffer);
89
+ }
90
+
91
+ waitForDrain(): Promise<void> {
92
+ return this._writer.ready;
93
+ }
94
+
95
+ close(): Promise<void> {
96
+ return this._writer.close();
97
+ }
98
+ }
99
+
100
+
101
+ /** Writer implementation using the `Blob` API available in all browsers. */
102
+ export class BlobWriter implements Writer {
103
+ // TODO: A good reference seems to be the mega.nz implementation, which has always worked great for me on desktops at least:
104
+ // https://github.com/meganz/webclient/blob/f19289127b68ceaf19a5e884f2f48f15078304da/js/transfers/meths/memory.js
105
+ private _parts: Array<Uint8Array | string>;
106
+ private _blob?: Blob;
107
+
108
+ constructor() {
109
+ this._parts = [];
110
+ }
111
+
112
+ write(buffer: string | Uint8Array): Promise<void> {
113
+ if (this._blob) {
114
+ return Promise.reject('Cannot write to closed BlobWriter.');
115
+ }
116
+ this._parts.push(buffer);
117
+ return Promise.resolve();
118
+ }
119
+
120
+ waitForDrain(): Promise<void> {
121
+ if (this._blob) {
122
+ return Promise.reject('Cannot wait on a closed BlobWriter.');
123
+ }
124
+ return Promise.resolve();
125
+ }
126
+
127
+ close(): Promise<void> {
128
+ if (this._blob) {
129
+ return Promise.reject('BlobWriter is already closed');
130
+ }
131
+ this._blob = new Blob(this._parts);
132
+ this._parts = [];
133
+ return Promise.resolve();
134
+ }
135
+
136
+ get blob(): Blob {
137
+ if (!this._blob) {
138
+ throw 'BlobWriter must be closed first!';
139
+ }
140
+ return this._blob;
141
+ }
142
+ }
143
+
144
+ /** Reader implentation using the node.js filesystem API. */
145
+ export class NodeReader implements Reader {
146
+ private fileHandle: nodeFs.promises.FileHandle;
147
+
148
+ constructor(handle: nodeFs.promises.FileHandle) {
149
+ this.fileHandle = handle;
150
+ }
151
+
152
+ async read(
153
+ dst: Uint8Array,
154
+ offset: number,
155
+ position: number,
156
+ length: number
157
+ ): Promise<number> {
158
+ const { bytesRead } = await this.fileHandle.read(
159
+ dst,
160
+ offset,
161
+ length,
162
+ position
163
+ );
164
+ return bytesRead;
165
+ }
166
+
167
+ async size(): Promise<number> {
168
+ const stat = await this.fileHandle.stat();
169
+ return stat.size;
170
+ }
171
+ }
172
+ /** Writer implementation using the node.js filesystem API. */
173
+ export class NodeWriter implements Writer {
174
+ _writable: NodeWritable;
175
+ _drainWaiters: Array<() => void> = [];
176
+
177
+ constructor(writable: NodeWritable) {
178
+ this._writable = writable;
179
+ this._writable.on('drain', () => {
180
+ log.debug('Drained writer.');
181
+ for (const waiter of this._drainWaiters) {
182
+ waiter();
183
+ }
184
+ this._drainWaiters = [];
185
+ });
186
+ this._writable.on('close', () => {
187
+ for (const waiter of this._drainWaiters) {
188
+ waiter();
189
+ }
190
+ this._drainWaiters = [];
191
+ });
192
+ }
193
+
194
+ async write(buffer: string | Uint8Array): Promise<void> {
195
+ let waitForDrain = false;
196
+ const out = new Promise<void>((resolve, reject) => {
197
+ if (!this._writable.writable) {
198
+ reject('Cannot write to closed NodeWriter.');
199
+ }
200
+ waitForDrain = !this._writable.write(buffer, (err) =>
201
+ err ? reject(err) : resolve()
202
+ );
203
+ });
204
+ if (waitForDrain) {
205
+ log.debug('Waiting for writer to drain');
206
+ return await this.waitForDrain();
207
+ } else {
208
+ return await out;
209
+ }
210
+ }
211
+
212
+ waitForDrain(): Promise<void> {
213
+ return new Promise((resolve) => this._drainWaiters.push(resolve));
214
+ }
215
+
216
+ close(): Promise<void> {
217
+ return new Promise((resolve) => this._writable.end(() => resolve()));
218
+ }
219
+ }
220
+
221
+ /** Very basic Reader implementation using an Array. */
222
+ export class ArrayReader implements Reader {
223
+ _buf: Uint8Array;
224
+
225
+ constructor(buf: Uint8Array) {
226
+ this._buf = buf;
227
+ }
228
+
229
+ read(
230
+ dst: Uint8Array,
231
+ offset: number,
232
+ position: number,
233
+ length: number
234
+ ): Promise<number> {
235
+ const sub = this._buf.subarray(position, position + length);
236
+ dst.set(sub, offset);
237
+ return Promise.resolve(sub.length);
238
+ }
239
+
240
+ size(): Promise<number> {
241
+ return Promise.resolve(this._buf.length);
242
+ }
243
+ }
package/src/log.ts ADDED
@@ -0,0 +1,51 @@
1
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
+
3
+ export interface Logger {
4
+ setLevel(level: LogLevel): void;
5
+ debug(message: string, ...args: any[]): void;
6
+ info(message: string, ...args: any[]): void;
7
+ warn(message: string, ...args: any[]): void;
8
+ error(message: string, ...args: any[]): void;
9
+ }
10
+
11
+ /** Simple logger that simply outputs to the console */
12
+ export class ConsoleLogger implements Logger {
13
+ private level: LogLevel;
14
+ constructor(level: LogLevel = 'warn') {
15
+ this.level = level;
16
+ }
17
+
18
+ setLevel(level: LogLevel): void {
19
+ this.level = level;
20
+ }
21
+
22
+ debug(message: string, ...args: any[]): void {
23
+ if (this.level === 'debug') {
24
+ console.debug(message, ...args);
25
+ }
26
+ }
27
+
28
+ info(message: string, ...args: any[]): void {
29
+ if (this.level !== 'error' && this.level !== 'warn') {
30
+ console.info(message, ...args);
31
+ }
32
+ }
33
+
34
+ warn(message: string, ...args: any[]): void {
35
+ if (this.level !== 'error') {
36
+ console.warn(message, ...args);
37
+ }
38
+ }
39
+
40
+ error(message: string, ...args: any[]): void {
41
+ console.error(message, ...args);
42
+ }
43
+ }
44
+
45
+ let logger: Logger = new ConsoleLogger();
46
+
47
+ export function setLogger(newLogger: Logger): void {
48
+ logger = newLogger;
49
+ }
50
+
51
+ export { logger as default };
package/src/metrics.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { Histogram } from 'prom-client';
2
+ import prometheus from 'prom-client';
3
+
4
+ import { runningInNode } from './util.js';
5
+
6
+ type Metrics =
7
+ | {
8
+ pageGenerationDuration: Histogram<string>;
9
+ imageFetchDuration: Histogram<string>;
10
+ imageInfoDuration: Histogram<string>;
11
+ ocrFetchDuration: Histogram<string>;
12
+ }
13
+ | undefined;
14
+
15
+ let metrics: Metrics;
16
+
17
+ // Prometheus metrics are only defined when running in node
18
+ if (runningInNode()) {
19
+ metrics = {
20
+ pageGenerationDuration: new prometheus.Histogram({
21
+ name: 'pdiiif_page_generation_duration_seconds',
22
+ help: 'Latency for generating the PDF for a single page',
23
+ buckets: [0.001, 0.005, 0.015, 0.05, 0.1, 0.5, 1, 2],
24
+ labelNames: ['status'],
25
+ }),
26
+ imageFetchDuration: new prometheus.Histogram({
27
+ name: 'pdiiif_image_fetch_duration_seconds',
28
+ help: 'Latency for fetching data from IIIF Image API endpoints',
29
+ buckets: [0.01, 0.05, 0.15, 0.5, 1, 5, 10],
30
+ labelNames: ['status', 'iiif_host', 'limited'],
31
+ }),
32
+ imageInfoDuration: new prometheus.Histogram({
33
+ name: 'pdiiif_image_info_duration_seconds',
34
+ help: 'Latency for fetching info from IIIF Image API endpoints',
35
+ buckets: [0.01, 0.05, 0.15, 0.5, 1, 5, 10],
36
+ labelNames: ['status', 'iiif_host', 'limited'],
37
+ }),
38
+ ocrFetchDuration: new prometheus.Histogram({
39
+ name: 'pdiiif_ocr_fetch_duration_seconds',
40
+ help: 'Latency for fetching OCR data',
41
+ buckets: [0.01, 0.05, 0.15, 0.5, 1, 5, 10],
42
+ labelNames: ['status', 'ocr_host', 'limited'],
43
+ }),
44
+ };
45
+ }
46
+
47
+ export default metrics;
package/src/ocr.ts ADDED
@@ -0,0 +1,176 @@
1
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
2
+ /* eslint-disable complexity */
3
+ /// Utilities for parsing OCR text from hOCR, ALTO and IIIF Annotations
4
+ import {
5
+ Annotation,
6
+ ContentResource,
7
+ } from '@iiif/presentation-3';
8
+ import {
9
+ AnnotationNormalized,
10
+ CanvasNormalized,
11
+ } from '@iiif/presentation-3-normalized';
12
+ import {
13
+ parseAltoPages,
14
+ parseHocrPages,
15
+ type OcrPage,
16
+ type OcrLine,
17
+ Dimensions,
18
+ } from 'ocr-parser';
19
+
20
+ import metrics from './metrics.js';
21
+ import { fetchRespectfully, rateLimitRegistry } from './download.js';
22
+ import {
23
+ isExternalWebResourceWithProfile,
24
+ ExternalWebResourceWithProfile,
25
+ vault,
26
+ } from './iiif.js';
27
+
28
+ export type OcrPageWithMarkup = OcrPage & {
29
+ id: string;
30
+ markup: string;
31
+ mimeType: string;
32
+ };
33
+
34
+ /** Helper to calculate a rough fallback image size from the line coordinates
35
+ *
36
+ * @param {array} lines the parsed OCR lines
37
+ * @returns {object} the page size estimated from the line coordinates
38
+ */
39
+ function getFallbackImageSize(lines: OcrLine[]): Dimensions {
40
+ return {
41
+ width: Math.max(...lines.map(({ x, width }) => x + (width ?? 0))) ?? 0,
42
+ height: Math.max(...lines.map(({ y, height }) => y + height)) ?? 0,
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Parse an OCR document (currently hOCR or ALTO)
48
+ *
49
+ * @param {string} ocrText ALTO or hOCR markup
50
+ * @param {object} referenceSize Reference size to scale coordinates to
51
+ * @returns {OcrPage} the parsed OCR page
52
+ */
53
+ export async function parseOcr(
54
+ id: string,
55
+ ocrText: string,
56
+ referenceSize: Dimensions
57
+ ): Promise<OcrPageWithMarkup | null> {
58
+ let pageIter: AsyncGenerator<OcrPage>;
59
+ const isAlto = ocrText.indexOf('<alto') >= 0;
60
+ if (isAlto) {
61
+ pageIter = parseAltoPages(ocrText, [referenceSize]);
62
+ } else {
63
+ pageIter = parseHocrPages(ocrText, [referenceSize]);
64
+ }
65
+ const page = (await pageIter.next()).value as OcrPage | undefined;
66
+ if (!page) {
67
+ return null;
68
+ }
69
+ return {
70
+ ...page,
71
+ id,
72
+ markup: ocrText,
73
+ mimeType: isAlto ? 'application/xml+alto' : 'text/vnd.hocr+html',
74
+ };
75
+ }
76
+
77
+ /** Parse OCR data from IIIF annotations.
78
+ *
79
+ * Annotations should be pre-filtered so that they all refer to a single canvas/page.
80
+ * Annotations should only contain a single text granularity, that is either line or word.
81
+ *
82
+ * @param {object} annos IIIF annotations with a plaintext body and line or word granularity
83
+ * @param {Dimensions} imgSize Reference width and height of the rendered target image
84
+ * @returns {OcrPage} parsed OCR boxes
85
+ */
86
+ export function parseIiifAnnotations(
87
+ annos: Array<Annotation>,
88
+ imgSize: Dimensions
89
+ ): OcrPage {
90
+ throw 'Currently not supported';
91
+ }
92
+
93
+ /** Checks if a given resource points to an ALTO OCR document */
94
+ const isAlto = (resource: ExternalWebResourceWithProfile) =>
95
+ resource.format === 'application/xml+alto' ||
96
+ resource.profile?.startsWith('http://www.loc.gov/standards/alto/');
97
+
98
+ /** Checks if a given resource points to an hOCR document */
99
+ const isHocr = (resource: ExternalWebResourceWithProfile) =>
100
+ resource.format === 'text/vnd.hocr+html' ||
101
+ resource.profile ===
102
+ 'https://github.com/kba/hocr-spec/blob/master/hocr-spec.md' ||
103
+ resource.profile?.startsWith('http://kba.cloud/hocr-spec/') ||
104
+ resource.profile?.startsWith('http://kba.github.io/hocr-spec/');
105
+
106
+ /** Wrapper around fetch() that returns the content as text */
107
+ async function fetchOcrMarkup(url: string): Promise<string | undefined> {
108
+ const resp = await fetch(url);
109
+ if (resp.status === 404) {
110
+ return undefined;
111
+ }
112
+ if (resp.status != 200) {
113
+ throw new Error(
114
+ `Could not fetch OCR markup from ${url}, got status code ${resp.status}`
115
+ );
116
+ }
117
+ return resp.text();
118
+ }
119
+
120
+ /** Fetch external annotation resource JSON */
121
+ export async function fetchAnnotationResource(url: string): Promise<any> {
122
+ const resp = await fetchRespectfully(url);
123
+ return resp.json();
124
+ }
125
+
126
+ /** Retrieve a supported OCR references from a Canvas' `seeAlso` or `rendering`, if present.
127
+ *
128
+ * 'Supported' currently means external ALTO or hOCR markup.
129
+ */
130
+ export function getOcrReferences(
131
+ canvas: CanvasNormalized
132
+ ): ExternalWebResourceWithProfile | undefined {
133
+ const refs = vault.get<ContentResource>(canvas.seeAlso.map((r) => r.id));
134
+ refs.push(...vault.get<ContentResource>(canvas.rendering.map((r) => r.id)));
135
+ return refs
136
+ .filter(isExternalWebResourceWithProfile)
137
+ .find((r) => isAlto(r) || isHocr(r));
138
+ }
139
+
140
+ export async function fetchAndParseText(
141
+ canvas: CanvasNormalized,
142
+ annotations?: AnnotationNormalized[]
143
+ ): Promise<OcrPageWithMarkup | undefined> {
144
+ // TODO: Annotations are a major PITA due to all the indirection and multiple
145
+ // levels of fetching of external resources that might be neccessary,
146
+ // save for later once text rendering is properly done.
147
+ const ocrRefs = getOcrReferences(canvas);
148
+ if (ocrRefs) {
149
+ const stopMeasuring = metrics?.ocrFetchDuration.startTimer({
150
+ ocr_host: new URL(ocrRefs.id!).host,
151
+ });
152
+ let markup;
153
+ try {
154
+ markup = await fetchOcrMarkup(ocrRefs.id!);
155
+ stopMeasuring?.({
156
+ status: 'success',
157
+ limited: rateLimitRegistry.isLimited(ocrRefs.id!).toString(),
158
+ });
159
+ if (!markup) {
160
+ return undefined;
161
+ }
162
+ } catch (err) {
163
+ stopMeasuring?.({
164
+ status: 'error',
165
+ limited: rateLimitRegistry.isLimited(ocrRefs.id!).toString(),
166
+ });
167
+ throw err;
168
+ }
169
+ return (
170
+ (await parseOcr(ocrRefs.id!, markup, {
171
+ width: canvas.width,
172
+ height: canvas.height,
173
+ })) ?? undefined
174
+ );
175
+ }
176
+ }
@@ -0,0 +1,201 @@
1
+ import type { EncodeOptions } from '@jsquash/jpeg/meta';
2
+ import { randomUUIDv4 } from './util';
3
+ import OptimizationWorker from './optimization.worker.ts?worker';
4
+ import log from './log';
5
+
6
+ export type InitializationRequest = {
7
+ mozjpegWasm: Uint8Array;
8
+ };
9
+
10
+ export type TaskDescription<I> = {
11
+ id: string;
12
+ data: I;
13
+ };
14
+
15
+ export type WorkerMessage<I, O> = { input: { id: string; data: I }; result: O };
16
+ export type WorkerTask<I, O> = {
17
+ resolve: (value: O) => void;
18
+ reject: (reason: any) => void;
19
+ task: TaskDescription<I>;
20
+ };
21
+
22
+ export type MozJPEGParams = {
23
+ method: 'mozjpeg';
24
+ quality: number;
25
+ } & Partial<EncodeOptions>;
26
+
27
+ export type BrowserEncoderParams = {
28
+ method: 'browser';
29
+ quality: number;
30
+ };
31
+
32
+ export type OptimizationParams = MozJPEGParams | BrowserEncoderParams;
33
+
34
+ export type OptimizationRequest = {
35
+ imageData: Uint8Array;
36
+ imageFormat: 'image/jpeg' | 'image/png';
37
+ } & OptimizationParams;
38
+
39
+ export type OptimizedImage = {
40
+ jpegData: Uint8Array;
41
+ sizeFactor: number;
42
+ };
43
+
44
+ export class OptimizationError extends Error {
45
+ constructor(message: string, public taskId: string, public cause?: unknown) {
46
+ super(message);
47
+ }
48
+ }
49
+
50
+ export const MOZJPEG_DEFAULT_PARAMS: EncodeOptions = {
51
+ quality: 75,
52
+ progressive: true,
53
+ optimize_coding: true,
54
+ smoothing: 0,
55
+ color_space: 3, // YCbCr
56
+ quant_table: 3,
57
+ trellis_multipass: false,
58
+ trellis_opt_table: true,
59
+ trellis_opt_zero: true,
60
+ trellis_loops: 0,
61
+ auto_subsample: false,
62
+ chroma_subsample: 2,
63
+ separate_chroma_quality: false,
64
+ chroma_quality: 75,
65
+ arithmetic: false,
66
+ baseline: false,
67
+ };
68
+
69
+ class WorkerPool<I, O> {
70
+ private workers: Worker[] = [];
71
+ private queue: WorkerTask<I, O>[] = [];
72
+ private pendingTasks: Map<string, WorkerTask<I, O>> = new Map();
73
+ private busyWorkers: Set<Worker> = new Set();
74
+
75
+ constructor(public size: number) {}
76
+
77
+ start(): void {
78
+ for (let i = 0; i < this.size; i++) {
79
+ const worker = new OptimizationWorker();
80
+ worker.onmessage = this.handleMessage.bind(this, worker);
81
+ worker.onerror = this.handleError.bind(this, worker);
82
+ this.workers.push(worker);
83
+ }
84
+ }
85
+
86
+ stop(): void {
87
+ this.workers.forEach((worker) => worker.terminate());
88
+ this.workers = [];
89
+ this.queue = [];
90
+ this.busyWorkers.clear();
91
+ }
92
+
93
+ dispatch(data: I): Promise<O> {
94
+ return new Promise((resolve, reject) => {
95
+ this.queue.push({
96
+ resolve,
97
+ reject,
98
+ task: {
99
+ id: randomUUIDv4(),
100
+ data,
101
+ },
102
+ });
103
+ this.processQueue();
104
+ });
105
+ }
106
+
107
+ private processQueue(): void {
108
+ if (this.queue.length === 0) return;
109
+ const availableWorker = this.workers.find((w) => !this.busyWorkers.has(w));
110
+ if (!availableWorker) return;
111
+
112
+ const job = this.queue.shift()!;
113
+ this.pendingTasks.set(job.task.id, job);
114
+ this.busyWorkers.add(availableWorker);
115
+ availableWorker.postMessage(job.task);
116
+ }
117
+
118
+ private handleMessage(
119
+ worker: Worker,
120
+ event: MessageEvent<WorkerMessage<I, O>>
121
+ ): void {
122
+ log.debug(`worker: received message`, event.data);
123
+ const job = this.pendingTasks.get(event.data.input.id);
124
+ if (job) {
125
+ job.resolve(event.data.result);
126
+ log.debug(`worker: resolved job`, job.task.id);
127
+ this.pendingTasks.delete(job.task.id);
128
+ this.busyWorkers.delete(worker);
129
+ this.processQueue();
130
+ } else {
131
+ log.warn(
132
+ `worker: unknown job, known jobs: ${[...this.pendingTasks.keys()].join(
133
+ ', '
134
+ )}`,
135
+ event.data.input.id
136
+ );
137
+ }
138
+ }
139
+
140
+ private handleError(worker: Worker, evt: ErrorEvent): void {
141
+ const optimError = evt.error as OptimizationError;
142
+ const job = this.queue.find((j) => j.task.id === optimError.taskId);
143
+ if (job) {
144
+ job.reject(optimError.cause);
145
+ this.busyWorkers.delete(worker);
146
+ this.processQueue();
147
+ }
148
+ }
149
+ }
150
+
151
+ let pool: WorkerPool<
152
+ OptimizationParams | InitializationRequest,
153
+ OptimizedImage | undefined
154
+ > | null = null;
155
+ let isInitialized = false;
156
+
157
+ export function startWorkerPool(size = navigator.hardwareConcurrency): void {
158
+ if (pool !== null) {
159
+ return;
160
+ }
161
+ pool = new WorkerPool(size);
162
+ pool.start();
163
+ }
164
+
165
+ export function stopWorkerPool(): void {
166
+ if (pool === null) {
167
+ return;
168
+ }
169
+ pool.stop();
170
+ pool = null;
171
+ }
172
+
173
+ export async function initialize(wasmLoader: () => Promise<Uint8Array>): Promise<void> {
174
+ if (pool === null) {
175
+ startWorkerPool();
176
+ }
177
+
178
+ if (isInitialized) {
179
+ return;
180
+ }
181
+
182
+ const mozjpegWasm = await wasmLoader();
183
+ let promises: Promise<undefined>[] = [];
184
+ for (let i = 0; i < pool!.size; i++) {
185
+ promises.push(pool!.dispatch({ mozjpegWasm }) as Promise<undefined>);
186
+ }
187
+ log.debug('main: mozjpegWasm sent to workers');
188
+ await Promise.all(promises);
189
+ log.debug('main: workers initialized with MozJPEG encoder');
190
+ isInitialized = true;
191
+ }
192
+
193
+ export async function optimizeImage(
194
+ params: OptimizationRequest
195
+ ): Promise<OptimizedImage> {
196
+ if (pool === null) {
197
+ startWorkerPool();
198
+ }
199
+
200
+ return pool!.dispatch(params) as Promise<OptimizedImage>;
201
+ }