File: piex_loader.ts

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (676 lines) | stat: -rw-r--r-- 22,509 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Declares the piex-wasm Module interface. The Module has many interfaces
 * but only declare the parts required for PIEX work.
 */
export interface PiexWasmModule {
  calledRun: boolean;
  HEAP8: Uint8Array;
  _malloc: (size: number) => number;
  _free: (size: number) => void;
  image: (width: number, height: number) => PiexWasmImageResult;
}

interface VoidCallback {
  (): void;
}

/**
 * Subset of the Emscripten Module API required for initialization. See
 * https://emscripten.org/docs/api_reference/module.html#module.
 */
interface ModuleInitParams {
  onAbort: (result: Error|string) => void;
}

/**
 * Module defined by 'piex.js.wasm' script upon initialization.
 */
let PiexModule: PiexWasmModule;

declare global {
  function createPiexModule(params: ModuleInitParams): Promise<PiexWasmModule>;
}

/**
 * Module constructor defined by 'piex.js.wasm' script.
 */
const initPiexModule = globalThis.createPiexModule;

console.info(`[PiexLoader] available [init=${typeof initPiexModule}]`);

/**
 * Set true if the Module.onAbort() handler is called.
 */
let piexFailed = false;

const MODULE_SETTINGS = {
  /**
   * Installs an (Emscripten) Module.onAbort handler. Record that the
   * Module has failed in piexFailed and re-throw the error.
   *
   * @throws {!Error|string}
   */
  onAbort: (error: Error|string) => {
    piexFailed = true;
    throw error;
  },
};

let initPiexModulePromise: Promise<void>|null = null;

/**
 * Returns a promise that resolves once initialization is complete. PiexModule
 * may be undefined before this promise resolves.
 */
function piexModuleInitialized(): Promise<void> {
  if (!initPiexModulePromise) {
    initPiexModulePromise = new Promise(resolve => {
      initPiexModule(MODULE_SETTINGS).then(module => {
        PiexModule = module;
        console.info(`[PiexLoader] loaded [module=${typeof module}]`);
        resolve();
      });
    });
  }
  return initPiexModulePromise;
}

/**
 * Module failure recovery: if piexFailed is set via onAbort due to OOM in
 * the C++ for example, or the Module failed to load or call run, then the
 * Module is in a broken, non-functional state.
 *
 * Loading the entire page is the only reliable way to recover from broken
 * Module state. Log the error, and return true to tell caller to initiate
 * failure recovery steps.
 *
 */
function piexModuleFailed(): boolean {
  if (piexFailed || !PiexModule.calledRun) {
    console.error('[PiexLoader] piex wasm module failed');
    return true;
  }
  return false;
}

interface PiexPreviewImageData {
  thumbnail: ArrayBuffer;
  mimeType?: string;
  orientation: number;
  colorSpace: string;
  ifd: string|null;
}

class PiexLoaderResponse {
  readonly thumbnail: ArrayBuffer;
  readonly mimeType: string;

  /** JEITA EXIF image orientation being an integer in [1..8].  */
  readonly orientation: number;

  /** JEITA EXIF image color space: 'sRgb' or 'adobeRgb'.  */
  readonly colorSpace: string;

  /** JSON encoded RAW image photographic details.  */
  readonly ifd: string|null;

  /**
   * @param data The extracted preview image data.
   */
  constructor(data: PiexPreviewImageData) {
    this.thumbnail = data.thumbnail;
    this.mimeType = data.mimeType || 'image/jpeg';
    this.orientation = data.orientation;
    this.colorSpace = data.colorSpace;
    this.ifd = data.ifd || null;
  }
}

/** JFIF APP2 ICC_PROFILE segment containing an AdobeRGB1998 Color Profile. */
const adobeProfile = new Uint8Array([
  // clang-format off
  // APP2 ICC_PROFILE\0 segment header.
  0xff, 0xe2, 0x02, 0x40, 0x49, 0x43, 0x43, 0x5f, 0x50, 0x52, 0x4f, 0x46,
  0x49, 0x4c, 0x45, 0x00, 0x01, 0x01,
  // AdobeRGB1998 ICC Color Profile data.
  0x00, 0x00, 0x02, 0x30, 0x41, 0x44, 0x42, 0x45, 0x02, 0x10, 0x00, 0x00,
  0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
  0x07, 0xd0, 0x00, 0x08, 0x00, 0x0b, 0x00, 0x13, 0x00, 0x33, 0x00, 0x3b,
  0x61, 0x63, 0x73, 0x70, 0x41, 0x50, 0x50, 0x4c, 0x00, 0x00, 0x00, 0x00,
  0x6e, 0x6f, 0x6e, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
  0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x41, 0x44, 0x42, 0x45,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a,
  0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x32,
  0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x30, 0x00, 0x00, 0x00, 0x6b,
  0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x01, 0x9c, 0x00, 0x00, 0x00, 0x14,
  0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x01, 0xb0, 0x00, 0x00, 0x00, 0x14,
  0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0xc4, 0x00, 0x00, 0x00, 0x0e,
  0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0xd4, 0x00, 0x00, 0x00, 0x0e,
  0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x01, 0xe4, 0x00, 0x00, 0x00, 0x0e,
  0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x01, 0xf4, 0x00, 0x00, 0x00, 0x14,
  0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x02, 0x08, 0x00, 0x00, 0x00, 0x14,
  0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x02, 0x1c, 0x00, 0x00, 0x00, 0x14,
  0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x70, 0x79,
  0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x32, 0x30, 0x30, 0x30, 0x20, 0x41,
  0x64, 0x6f, 0x62, 0x65, 0x20, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73,
  0x20, 0x49, 0x6e, 0x63, 0x6f, 0x72, 0x70, 0x6f, 0x72, 0x61, 0x74, 0x65,
  0x64, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x11, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x52, 0x47,
  0x42, 0x20, 0x28, 0x31, 0x39, 0x39, 0x38, 0x29, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc,
  0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x75, 0x72, 0x76,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x33, 0x00, 0x00,
  0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
  0x02, 0x33, 0x00, 0x00, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x01, 0x02, 0x33, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9c, 0x18, 0x00, 0x00, 0x4f, 0xa5,
  0x00, 0x00, 0x04, 0xfc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x34, 0x8d, 0x00, 0x00, 0xa0, 0x2c, 0x00, 0x00, 0x0f, 0x95,
  0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x31,
  0x00, 0x00, 0x10, 0x2f, 0x00, 0x00, 0xbe, 0x9c,
  // clang-format on
]);

/**
 * Piex-wasm extracts the "preview image" from a RAW image. The preview image
 * |format| is either 0 (JPEG), or 1 (RGB), and has a JEITA EXIF |colorSpace|
 * (sRGB or AdobeRGB1998) and a JEITA EXIF image |orientation|.
 *
 * An RGB format preview image has both |width| and |height|, but JPEG format
 * previews have neither (piex-wasm C++ does not parse/decode JPEG).
 *
 * The |offset| to, and |length| of, the preview image relative to the source
 * data is indicated by those fields. They are positive > 0. Note: the values
 * are controlled by a third-party and are untrustworthy (Security).
 */
interface PiexWasmPreviewImageMetadata {
  /** Ether 0 (JPEG), or 1 (RGB). */
  format: number;

  /** JEITA EXIF: sRGB or AdobeRGB1998. */
  colorSpace: string;

  /** JEITA EXIF image orientation.  */
  orientation: number;

  /** Only available for RGB format preview image. */
  width?: number;

  /** Only available for RGB format preview image. */
  height?: number;

  /**
   * The offset of the preview image relative to the source data. They are
   * positive > 0. Note: ths value is controlled by a third-party and are
   * untrustworthy (Security).
   */
  offset: number;

  /**
   * The length of the preview image relative to the source data. They are
   * positive > 0. Note: ths value is controlled by a third-party and are
   * untrustworthy (Security).
   */
  length: number;
}

/**
 * The piex-wasm Module.image(<RAW image source>,...) API returns `error`, or
 * else the source `preview` and/or `thumbnail` image metadata along with the
 * photographic `details` derived from the RAW image EXIF.
 */
interface PiexWasmImageResult {
  error: string|null;

  /** The `preview` images are JPEG.*/
  preview: PiexWasmPreviewImageMetadata|null;

  /**
   * The `thumbnail` images are smaller, lower  quality, JPEG or RGB format
   * images.
   */
  thumbnail: PiexWasmPreviewImageMetadata|null;

  /** The photographic `details` derived from the RAW image EXIF. */
  details: Record<string, any>|null;
}

/**
 * Preview Image EXtractor (PIEX).
 */
class ImageBuffer {
  private readonly source: Uint8Array;
  private readonly length: number;
  private memory = 0;

  /**
   * @param buffer - RAW image source data.
   */
  constructor(buffer: ArrayBuffer) {
    this.source = new Uint8Array(buffer);
    this.length = buffer.byteLength;
  }

  /**
   * Calls Module.image() to process |this.source| and return the result.
   *
   * @throws {!Error} Memory allocation error.
   */
  process(): PiexWasmImageResult {
    this.memory = PiexModule._malloc(this.length);
    if (!this.memory) {
      throw new Error('Image malloc failed: ' + this.length + ' bytes');
    }

    PiexModule.HEAP8.set(this.source, this.memory);
    const result = PiexModule.image(this.memory, this.length);
    if (result.error) {
      throw new Error(result.error);
    }

    return result;
  }

  /**
   * Returns the preview image data. If no preview image was found, returns
   * the thumbnail image.
   *
   * @throws {!Error} Data access security error.
   */
  preview(result: PiexWasmImageResult): PiexPreviewImageData {
    const preview = result.preview;
    if (!preview) {
      return this.thumbnail_(result);
    }

    const offset = preview.offset;
    const length = preview.length;
    if (offset > this.length || (this.length - offset) < length) {
      throw new Error('Preview image access failed');
    }

    const view = new Uint8Array(this.source.buffer, offset, length);
    return {
      thumbnail: this.createImageDataArray_(view, preview).buffer,
      mimeType: 'image/jpeg',
      ifd: this.details_(result, preview.orientation),
      orientation: preview.orientation,
      colorSpace: preview.colorSpace,
    };
  }

  /**
   * Returns the thumbnail image. If no thumbnail image was found, returns
   * an empty thumbnail image.
   *
   * @throws {!Error} Data access security error.
   */
  private thumbnail_(result: PiexWasmImageResult): PiexPreviewImageData {
    const thumbnail = result.thumbnail;
    if (!thumbnail) {
      return {
        thumbnail: new ArrayBuffer(0),
        colorSpace: 'sRgb',
        orientation: 1,
        ifd: null,
      };
    }

    if (thumbnail.format) {
      return this.rgb_(result);
    }

    const offset = thumbnail.offset;
    const length = thumbnail.length;
    if (offset > this.length || (this.length - offset) < length) {
      throw new Error('Thumbnail image access failed');
    }

    const view = new Uint8Array(this.source.buffer, offset, length);
    return {
      thumbnail: this.createImageDataArray_(view, thumbnail).buffer,
      mimeType: 'image/jpeg',
      ifd: this.details_(result, thumbnail.orientation),
      orientation: thumbnail.orientation,
      colorSpace: thumbnail.colorSpace,
    };
  }

  /**
   * Returns the RGB thumbnail. If no RGB thumbnail was found, returns
   * an empty thumbnail image.
   *
   * @throws {!Error} Data access security error.
   */
  private rgb_(result: PiexWasmImageResult): PiexPreviewImageData {
    const thumbnail = result.thumbnail;
    if (!thumbnail || thumbnail.format !== 1) {
      return {
        thumbnail: new ArrayBuffer(0),
        colorSpace: 'sRgb',
        orientation: 1,
        ifd: null,
      };
    }

    // Expect a width and height.
    if (!thumbnail.width || !thumbnail.height) {
      throw new Error('invalid image width or height');
    }

    const offset = thumbnail.offset;
    const length = thumbnail.length;
    if (offset > this.length || (this.length - offset) < length) {
      throw new Error('Thumbnail image access failed');
    }

    const view = new Uint8Array(this.source.buffer, offset, length);

    // Compute output image width and height.
    const usesWidthAsHeight = thumbnail.orientation >= 5;
    const height = usesWidthAsHeight ? thumbnail.width : thumbnail.height;
    const width = usesWidthAsHeight ? thumbnail.height : thumbnail.width;

    // Compute pixel row stride.
    const rowPad = width & 3;
    const rowStride = 3 * width + rowPad;

    // Create bitmap image.
    const pixelDataOffset = 14 + 108;
    const fileSize = pixelDataOffset + rowStride * height;
    const bitmap = new DataView(new ArrayBuffer(fileSize));

    // BITMAPFILEHEADER 14 bytes.
    bitmap.setUint8(0, 'B'.charCodeAt(0));
    bitmap.setUint8(1, 'M'.charCodeAt(0));
    bitmap.setUint32(2, fileSize /* bytes */, true);
    bitmap.setUint32(6, /* Reserved */ 0, true);
    bitmap.setUint32(10, pixelDataOffset, true);

    // DIB BITMAPV4HEADER 108 bytes.
    bitmap.setUint32(14, /* HeaderSize */ 108, true);
    bitmap.setInt32(18, width, true);
    bitmap.setInt32(22, -height /* top-down DIB */, true);
    bitmap.setInt16(26, /* ColorPlanes */ 1, true);
    bitmap.setInt16(28, /* BitsPerPixel BI_RGB */ 24, true);
    bitmap.setUint32(30, /* Compression: BI_RGB none */ 0, true);
    bitmap.setUint32(34, /* ImageSize: 0 not compressed */ 0, true);
    bitmap.setInt32(38, /* XPixelsPerMeter */ 0, true);
    bitmap.setInt32(42, /* YPixelPerMeter */ 0, true);
    bitmap.setUint32(46, /* TotalPalletColors */ 0, true);
    bitmap.setUint32(50, /* ImportantColors */ 0, true);

    bitmap.setUint32(54, /* RedMask */ 0, true);
    bitmap.setUint32(58, /* GreenMask */ 0, true);
    bitmap.setUint32(62, /* BlueMask */ 0, true);
    bitmap.setUint32(66, /* AlphaMask */ 0, true);

    let rx = 0;
    let ry = 0;
    let gx = 0;
    let gy = 0;
    let bx = 0;
    let by = 0;
    let zz = 0;
    let gg = 0;

    if (thumbnail.colorSpace !== 'adobeRgb') {
      bitmap.setUint8(70, 's'.charCodeAt(0));
      bitmap.setUint8(71, 'R'.charCodeAt(0));
      bitmap.setUint8(72, 'G'.charCodeAt(0));
      bitmap.setUint8(73, 'B'.charCodeAt(0));
    } else {
      bitmap.setUint32(70, /* adobeRgb LCS_CALIBRATED_RGB */ 0);
      rx = Math.round(0.6400 * (1 << 30));
      ry = Math.round(0.3300 * (1 << 30));
      gx = Math.round(0.2100 * (1 << 30));
      gy = Math.round(0.7100 * (1 << 30));
      bx = Math.round(0.1500 * (1 << 30));
      by = Math.round(0.0600 * (1 << 30));
      zz = Math.round(1.0000 * (1 << 30));
      gg = Math.round(2.1992187 * (1 << 16));
    }

    // RGB CIEXYZ.
    bitmap.setUint32(74, /* R CIEXYZ x */ rx, true);
    bitmap.setUint32(78, /* R CIEXYZ y */ ry, true);
    bitmap.setUint32(82, /* R CIEXYZ z */ zz, true);
    bitmap.setUint32(86, /* G CIEXYZ x */ gx, true);
    bitmap.setUint32(90, /* G CIEXYZ y */ gy, true);
    bitmap.setUint32(94, /* G CIEXYZ z */ zz, true);
    bitmap.setUint32(98, /* B CIEXYZ x */ bx, true);
    bitmap.setUint32(102, /* B CIEXYZ y */ by, true);
    bitmap.setUint32(106, /* B CIEXYZ z */ zz, true);

    // RGB gamma.
    bitmap.setUint32(110, /* R Gamma */ gg, true);
    bitmap.setUint32(114, /* G Gamma */ gg, true);
    bitmap.setUint32(118, /* B Gamma */ gg, true);

    // Write RGB row pixels in top-down DIB order.
    const h = thumbnail.height - 1;
    const w = thumbnail.width - 1;
    let dx = 0;

    for (let input = 0, y = 0; y <= h; ++y) {
      let output = pixelDataOffset;

      /**
       * Compute affine(a,b,c,d,tx,ty) transform of pixel (x,y)
       *   { x': a * x + c * y + tx, y': d * y + b * x + ty }
       * a,b,c,d in [-1,0,1], to apply the image orientation at
       * (0,y) to find the output location of the input row.
       * The transform derivative in x is used to calculate the
       * relative output location of adjacent input row pixels.
       */
      switch (thumbnail.orientation) {
        case 1:  // affine(+1, 0, 0, +1, 0, 0)
          output += y * rowStride;
          dx = 3;
          break;
        case 2:  // affine(-1, 0, 0, +1, w, 0)
          output += y * rowStride + 3 * w;
          dx = -3;
          break;
        case 3:  // affine(-1, 0, 0, -1, w, h)
          output += (h - y) * rowStride + 3 * w;
          dx = -3;
          break;
        case 4:  // affine(+1, 0, 0, -1, 0, h)
          output += (h - y) * rowStride;
          dx = 3;
          break;
        case 5:  // affine(0, +1, +1, 0, 0, 0)
          output += 3 * y;
          dx = rowStride;
          break;
        case 6:  // affine(0, +1, -1, 0, h, 0)
          output += 3 * (h - y);
          dx = rowStride;
          break;
        case 7:  // affine(0, -1, -1, 0, h, w)
          output += w * rowStride + 3 * (h - y);
          dx = -rowStride;
          break;
        case 8:  // affine(0, -1, +1, 0, 0, w)
          output += w * rowStride + 3 * y;
          dx = -rowStride;
          break;
      }

      for (let x = 0; x <= w; ++x, input += 3, output += dx) {
        bitmap.setUint8(output + 0, view[input + 2]!);  // B
        bitmap.setUint8(output + 1, view[input + 1]!);  // G
        bitmap.setUint8(output + 2, view[input + 0]!);  // R
      }
    }

    // Write pixel row padding bytes if needed.
    if (rowPad) {
      let paddingOffset = pixelDataOffset + 3 * width;

      for (let y = 0; y < height; ++y) {
        let output = paddingOffset;

        switch (rowPad) {
          case 1:
            bitmap.setUint8(output++, 0);
            break;
          case 2:
            bitmap.setUint8(output++, 0);
            bitmap.setUint8(output++, 0);
            break;
          case 3:
            bitmap.setUint8(output++, 0);
            bitmap.setUint8(output++, 0);
            bitmap.setUint8(output++, 0);
            break;
        }

        paddingOffset += rowStride;
      }
    }

    return {
      thumbnail: bitmap.buffer,
      mimeType: 'image/bmp',
      ifd: this.details_(result, thumbnail.orientation),
      colorSpace: thumbnail.colorSpace,
      orientation: 1,
    };
  }

  /**
   * Converts a |view| of the "preview image" to Uint8Array data. Embeds an
   * AdobeRGB1998 ICC Color Profile in that data if the preview is JPEG and
   * it has 'adodeRgb' color space.
   *
   */
  private createImageDataArray_(
      view: Uint8Array,
      preview: PiexWasmPreviewImageMetadata): Uint8Array<ArrayBuffer> {
    const jpeg = view.byteLength > 2 && view[0] === 0xff && view[1] === 0xd8;

    if (jpeg && preview.colorSpace === 'adobeRgb') {
      const data = new Uint8Array(view.byteLength + adobeProfile.byteLength);
      data.set(view.subarray(2), 2 + adobeProfile.byteLength);
      data.set(adobeProfile, 2);
      data.set([0xff, 0xd8], 0);
      return data;
    }

    return new Uint8Array(view);
  }

  /**
   * Returns the RAW image photographic |details| in a JSON-encoded string.
   * Only number and string values are retained, and they are formatted for
   * presentation to the user.
   *
   * @param orientation - image EXIF orientation
   */
  private details_(result: PiexWasmImageResult, orientation: number): null
      |string {
    const details = result.details;
    if (!details) {
      return null;
    }

    const format: Record<string, string|number> = {};
    for (const [key, value] of Object.entries(details)) {
      if (typeof value === 'string') {
        format[key] = value.replace(/\0+$/, '').trim();
      } else if (typeof value === 'number') {
        if (!Number.isInteger(value)) {
          format[key] = Number(value.toFixed(3).replace(/0+$/, ''));
        } else {
          format[key] = value;
        }
      }
    }

    const usesWidthAsHeight = orientation >= 5;
    if (usesWidthAsHeight) {
      const width = format['width']!;
      format['width'] = format['height']!;
      format['height'] = width;
    }

    return JSON.stringify(format);
  }

  /**
   * Release resources.
   */
  close() {
    const memory = this.memory;
    if (memory) {
      PiexModule._free(memory);
      this.memory = 0;
    }
  }
}

/**
 * PiexLoader: is a namespace.
 */
export const PiexLoader = {

  /**
   * Loads a RAW image. Returns the image metadata and the image thumbnail in a
   * PiexLoaderResponse.
   *
   * piexModuleFailed() returns true if the Module is in an unrecoverable error
   * state. This is rare, but possible, and the only reliable way to recover is
   * to reload the page. Callback |onPiexModuleFailed| is used to indicate that
   * the caller should initiate failure recovery steps.
   *
   */
  load(buffer: ArrayBuffer, onPiexModuleFailed: VoidCallback):
      Promise<PiexLoaderResponse> {
        let imageBuffer: ImageBuffer|null;

        return piexModuleInitialized()
            .then(() => {
              if (piexModuleFailed()) {
                throw new Error('piex wasm module failed');
              }
              imageBuffer = new ImageBuffer(buffer);
              return imageBuffer.process();
            })
            .then((result: PiexWasmImageResult) => {
              return new PiexLoaderResponse(imageBuffer!.preview(result));
            })
            .catch((error) => {
              if (piexModuleFailed()) {
                setTimeout(onPiexModuleFailed, 0);
                return Promise.reject('piex wasm module failed');
              }
              console.warn('[PiexLoader] ' + error);
              return Promise.reject(error);
            })
            .finally(() => {
              imageBuffer && imageBuffer.close();
            });
      },
};

export const PIEX_LOADER_TEST_ONLY = {
  getModule: () => PiexModule,
};