imagescript 4.0.0 → 4.1.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.
@@ -1,7 +1,8 @@
1
1
  /*!
2
2
  * JPEG codec. This software is based in part on the work of the Independent JPEG Group: the IDCT, FDCT, upsampling,
3
- * downsampling, color conversion, quantization, progressive refinement and optimal Huffman tables are translated from
4
- * libjpeg/libjpeg-turbo (IJG license, see licenses/README.ijg). The scan decoder follows the structure of pdf.js' jpg.js
3
+ * downsampling, color conversion, quantization, progressive refinement and encoding and optimal Huffman tables are
4
+ * translated from libjpeg/libjpeg-turbo, and the progressive scans are chosen from mozjpeg's scan search (IJG license,
5
+ * see licenses/README.ijg). The scan decoder follows the structure of pdf.js' jpg.js
5
6
  * (Copyright 2014 Mozilla Foundation, Apache License 2.0). See THIRD_PARTY_NOTICES.md
6
7
  */
7
8
  import { ByteWriter } from "../util/bytes.js";
@@ -201,6 +202,7 @@ function createFrame(progressive, height, width, componentData, available) {
201
202
  blocksPerLineForMcu,
202
203
  blocksPerColumnForMcu,
203
204
  coefficients: new Int16Array(blocksPerLineForMcu * (progressive ? blocksPerColumnForMcu : c.v) * 64),
205
+ last: progressive ? new Uint8Array(blocksPerLineForMcu * blocksPerColumnForMcu) : undefined,
204
206
  plane: progressive ? undefined : new Uint8Array(blocksPerLineForMcu * 8 * blocksPerColumnForMcu * 8),
205
207
  done: progressive ? undefined : new Uint8Array(blocksPerColumnForMcu),
206
208
  pred: 0
@@ -302,24 +304,10 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
302
304
  throw new Error('JPEG: the scan data is truncated');
303
305
  };
304
306
  let eobrun = 0;
305
- const decodeBaseline = (component, offset) => {
306
- const coefficients = component.coefficients;
307
- const t = huffman(component.dcTable);
308
- coefficients[offset] = component.pred += receiveExtend(t);
309
- for (let k = 1; k < 64;) {
310
- const rs = huffman(component.acTable);
311
- const s = rs & 15, r = rs >> 4;
312
- if (s === 0) {
313
- if (r < 15)
314
- break;
315
- k += 16;
316
- continue;
317
- }
318
- k += r;
319
- if (k > 63)
320
- break;
321
- coefficients[offset + ZIGZAG[k++]] = receiveExtend(s);
322
- }
307
+ const raise = (component, offset, k) => {
308
+ const last = component.last;
309
+ if (k > last[offset >> 6])
310
+ last[offset >> 6] = k;
323
311
  };
324
312
  const decodeDCFirst = (component, offset) => {
325
313
  const t = huffman(component.dcTable);
@@ -351,6 +339,7 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
351
339
  k += r;
352
340
  if (k > 63)
353
341
  break;
342
+ raise(component, offset, k);
354
343
  coefficients[offset + ZIGZAG[k++]] = receiveExtend(s) * (1 << al);
355
344
  }
356
345
  };
@@ -383,8 +372,10 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
383
372
  break;
384
373
  k++;
385
374
  } while (k <= se);
386
- if (s && k <= se)
375
+ if (s && k <= se) {
376
+ raise(component, offset, k);
387
377
  coefficients[offset + ZIGZAG[k]] = s;
378
+ }
388
379
  }
389
380
  }
390
381
  if (eobrun > 0) {
@@ -397,9 +388,8 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
397
388
  eobrun--;
398
389
  }
399
390
  };
400
- const decodeBlock = !frame.progressive ? decodeBaseline
401
- : ss === 0 ? (ah === 0 ? decodeDCFirst : decodeDCSuccessive)
402
- : (ah === 0 ? decodeACFirst : decodeACSuccessive);
391
+ const decodeBlock = ss === 0 ? (ah === 0 ? decodeDCFirst : decodeDCSuccessive)
392
+ : (ah === 0 ? decodeACFirst : decodeACSuccessive);
403
393
  const single = components.length === 1;
404
394
  const total = single
405
395
  ? components[0].blocksPerLine * components[0].blocksPerColumn
@@ -416,16 +406,44 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
416
406
  };
417
407
  for (const component of components)
418
408
  component.pred = 0;
409
+ const perRow = single ? components[0].blocksPerLine : frame.mcusPerLine;
410
+ const reader = { pos: 0, buffer: 0, bits: 0, padding: 0, broken: false, eobrun: 0 };
419
411
  for (let unit = 0; unit < total;) {
420
412
  for (let n = 0; n < interval && unit < total; n++, unit++) {
413
+ if (sequential && !broken) {
414
+ const count = Math.min(interval - n, perRow - unit % perRow, total - unit);
415
+ pending = unit / perRow | 0;
416
+ reader.pos = pos;
417
+ reader.buffer = buffer;
418
+ reader.bits = bits;
419
+ reader.padding = padding;
420
+ const decoded = decodeSequential(data, reader, components, single, unit % perRow, count, restartInterval !== 0);
421
+ ({ pos, buffer, bits, padding, broken } = reader);
422
+ unit += decoded - 1;
423
+ n += decoded - 1;
424
+ if ((unit + 1) % perRow === 0)
425
+ finish();
426
+ continue;
427
+ }
428
+ if (!sequential && single && ss > 0 && !broken) {
429
+ const count = Math.min(interval - n, total - unit);
430
+ reader.pos = pos;
431
+ reader.buffer = buffer;
432
+ reader.bits = bits;
433
+ reader.padding = padding;
434
+ reader.eobrun = eobrun;
435
+ const decoded = decodeProgressive(data, reader, components[0], ah === 0, ss, se, al, unit, count, restartInterval !== 0);
436
+ ({ pos, buffer, bits, padding, broken, eobrun } = reader);
437
+ unit += decoded - 1;
438
+ n += decoded - 1;
439
+ continue;
440
+ }
421
441
  if (single) {
422
442
  const component = components[0];
423
443
  const row = unit / component.blocksPerLine | 0;
424
444
  const column = unit % component.blocksPerLine;
425
445
  if (sequential) {
426
446
  pending = row;
427
- if (!broken)
428
- decodeBlock(component, column * 64);
429
447
  if (column === component.blocksPerLine - 1)
430
448
  finish();
431
449
  }
@@ -481,6 +499,477 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
481
499
  finish();
482
500
  return pos;
483
501
  }
502
+ function decodeSequential(data, reader, components, single, column, count, resync) {
503
+ let { pos, buffer, bits, padding } = reader;
504
+ let broken = false;
505
+ const length = data.length;
506
+ let m = 0;
507
+ for (; m < count && !broken; m++) {
508
+ for (let c = 0; c < components.length && !broken; c++) {
509
+ const component = components[c];
510
+ const blocksAcross = single ? 1 : component.h, blocksDown = single ? 1 : component.v;
511
+ const coefficients = component.coefficients;
512
+ for (let v = 0; v < blocksDown && !broken; v++)
513
+ for (let h = 0; h < blocksAcross && !broken; h++) {
514
+ const offset = single ? (column + m) * 64 : (v * component.blocksPerLineForMcu + (column + m) * component.h + h) * 64;
515
+ let table = component.dcTable;
516
+ if (!table)
517
+ throw new Error('JPEG: missing huffman table');
518
+ for (let k = 0; k < 64;) {
519
+ if (bits < 16) {
520
+ while (bits <= 24) {
521
+ let byte = 0;
522
+ if (pos < length) {
523
+ byte = data[pos];
524
+ if (byte === 0xff) {
525
+ if (data[pos + 1] === 0x00)
526
+ pos += 2;
527
+ else {
528
+ byte = 0;
529
+ padding++;
530
+ }
531
+ }
532
+ else
533
+ pos++;
534
+ }
535
+ else
536
+ padding++;
537
+ buffer = buffer << 8 | byte;
538
+ bits += 8;
539
+ }
540
+ }
541
+ let symbol;
542
+ const entry = table.lookup[buffer >>> bits - 9 & 511];
543
+ if (entry) {
544
+ bits -= entry >> 8;
545
+ symbol = entry & 255;
546
+ }
547
+ else {
548
+ let size = 10;
549
+ let code = buffer >>> bits - 10 & 1023;
550
+ while (code > table.maxCode[size] && size <= 16) {
551
+ if (++size > 16)
552
+ break;
553
+ code = buffer >>> bits - size & (1 << size) - 1;
554
+ }
555
+ if (size > 16) {
556
+ if (!resync)
557
+ throw new Error('JPEG: invalid huffman code');
558
+ broken = true;
559
+ symbol = 0;
560
+ }
561
+ else {
562
+ bits -= size;
563
+ symbol = table.values[code + table.valueOffset[size]];
564
+ }
565
+ }
566
+ let extra = symbol;
567
+ if (k > 0) {
568
+ extra = symbol & 15;
569
+ if (extra === 0) {
570
+ if (symbol >> 4 < 15)
571
+ break;
572
+ k += 16;
573
+ continue;
574
+ }
575
+ k += symbol >> 4;
576
+ if (k > 63)
577
+ break;
578
+ }
579
+ let value = 0;
580
+ if (extra) {
581
+ if (bits < extra) {
582
+ while (bits <= 24) {
583
+ let byte = 0;
584
+ if (pos < length) {
585
+ byte = data[pos];
586
+ if (byte === 0xff) {
587
+ if (data[pos + 1] === 0x00)
588
+ pos += 2;
589
+ else {
590
+ byte = 0;
591
+ padding++;
592
+ }
593
+ }
594
+ else
595
+ pos++;
596
+ }
597
+ else
598
+ padding++;
599
+ buffer = buffer << 8 | byte;
600
+ bits += 8;
601
+ }
602
+ }
603
+ bits -= extra;
604
+ value = buffer >>> bits & (1 << extra) - 1;
605
+ if (value < 1 << extra - 1)
606
+ value += (-1 << extra) + 1;
607
+ }
608
+ if (k === 0) {
609
+ coefficients[offset] = component.pred += value;
610
+ table = component.acTable;
611
+ if (!table)
612
+ throw new Error('JPEG: missing huffman table');
613
+ k = 1;
614
+ continue;
615
+ }
616
+ coefficients[offset + ZIGZAG[k++]] = value;
617
+ }
618
+ }
619
+ }
620
+ }
621
+ reader.pos = pos;
622
+ reader.buffer = buffer;
623
+ reader.bits = bits;
624
+ reader.padding = padding;
625
+ reader.broken = broken;
626
+ return m;
627
+ }
628
+ function decodeProgressive(data, reader, component, first, ss, se, al, unit, count, resync) {
629
+ let { pos, buffer, bits, padding, eobrun } = reader;
630
+ let broken = false;
631
+ const length = data.length;
632
+ const coefficients = component.coefficients, line = component.blocksPerLine, stride = component.blocksPerLineForMcu;
633
+ const last = component.last;
634
+ const bounded = se <= 63;
635
+ const p1 = 1 << al, m1 = -1 << al;
636
+ let b = 0;
637
+ for (; b < count && !broken; b++) {
638
+ const offset = (((unit + b) / line | 0) * stride + (unit + b) % line) * 64;
639
+ if (first) {
640
+ if (eobrun > 0) {
641
+ eobrun--;
642
+ continue;
643
+ }
644
+ for (let k = ss; k <= se;) {
645
+ const table = component.acTable;
646
+ if (!table)
647
+ throw new Error('JPEG: missing huffman table');
648
+ let rs;
649
+ if (bits < 16) {
650
+ while (bits <= 24) {
651
+ let byte = 0;
652
+ if (pos < length) {
653
+ byte = data[pos];
654
+ if (byte === 0xff) {
655
+ if (data[pos + 1] === 0x00)
656
+ pos += 2;
657
+ else {
658
+ byte = 0;
659
+ padding++;
660
+ }
661
+ }
662
+ else
663
+ pos++;
664
+ }
665
+ else
666
+ padding++;
667
+ buffer = buffer << 8 | byte;
668
+ bits += 8;
669
+ }
670
+ }
671
+ const entry = table.lookup[buffer >>> bits - 9 & 511];
672
+ if (entry) {
673
+ bits -= entry >> 8;
674
+ rs = entry & 255;
675
+ }
676
+ else {
677
+ let size = 10;
678
+ let code = buffer >>> bits - 10 & 1023;
679
+ while (code > table.maxCode[size] && size <= 16) {
680
+ if (++size > 16)
681
+ break;
682
+ code = buffer >>> bits - size & (1 << size) - 1;
683
+ }
684
+ if (size > 16) {
685
+ if (!resync)
686
+ throw new Error('JPEG: invalid huffman code');
687
+ broken = true;
688
+ rs = 0;
689
+ }
690
+ else {
691
+ bits -= size;
692
+ rs = table.values[code + table.valueOffset[size]];
693
+ }
694
+ }
695
+ const s = rs & 15, r = rs >> 4;
696
+ if (s === 0) {
697
+ if (r < 15) {
698
+ eobrun = (1 << r) - 1;
699
+ if (r) {
700
+ if (bits < r) {
701
+ while (bits <= 24) {
702
+ let byte = 0;
703
+ if (pos < length) {
704
+ byte = data[pos];
705
+ if (byte === 0xff) {
706
+ if (data[pos + 1] === 0x00)
707
+ pos += 2;
708
+ else {
709
+ byte = 0;
710
+ padding++;
711
+ }
712
+ }
713
+ else
714
+ pos++;
715
+ }
716
+ else
717
+ padding++;
718
+ buffer = buffer << 8 | byte;
719
+ bits += 8;
720
+ }
721
+ }
722
+ bits -= r;
723
+ const extra = buffer >>> bits & (1 << r) - 1;
724
+ eobrun += extra;
725
+ }
726
+ break;
727
+ }
728
+ k += 16;
729
+ continue;
730
+ }
731
+ k += r;
732
+ if (k > 63)
733
+ break;
734
+ let value;
735
+ if (bits < s) {
736
+ while (bits <= 24) {
737
+ let byte = 0;
738
+ if (pos < length) {
739
+ byte = data[pos];
740
+ if (byte === 0xff) {
741
+ if (data[pos + 1] === 0x00)
742
+ pos += 2;
743
+ else {
744
+ byte = 0;
745
+ padding++;
746
+ }
747
+ }
748
+ else
749
+ pos++;
750
+ }
751
+ else
752
+ padding++;
753
+ buffer = buffer << 8 | byte;
754
+ bits += 8;
755
+ }
756
+ }
757
+ bits -= s;
758
+ value = buffer >>> bits & (1 << s) - 1;
759
+ if (value < 1 << s - 1)
760
+ value += (-1 << s) + 1;
761
+ if (k > last[offset >> 6])
762
+ last[offset >> 6] = k;
763
+ coefficients[offset + ZIGZAG[k++]] = value * (1 << al);
764
+ }
765
+ continue;
766
+ }
767
+ let k = ss;
768
+ if (eobrun === 0) {
769
+ for (; k <= se; k++) {
770
+ const table = component.acTable;
771
+ if (!table)
772
+ throw new Error('JPEG: missing huffman table');
773
+ let rs;
774
+ if (bits < 16) {
775
+ while (bits <= 24) {
776
+ let byte = 0;
777
+ if (pos < length) {
778
+ byte = data[pos];
779
+ if (byte === 0xff) {
780
+ if (data[pos + 1] === 0x00)
781
+ pos += 2;
782
+ else {
783
+ byte = 0;
784
+ padding++;
785
+ }
786
+ }
787
+ else
788
+ pos++;
789
+ }
790
+ else
791
+ padding++;
792
+ buffer = buffer << 8 | byte;
793
+ bits += 8;
794
+ }
795
+ }
796
+ const entry = table.lookup[buffer >>> bits - 9 & 511];
797
+ if (entry) {
798
+ bits -= entry >> 8;
799
+ rs = entry & 255;
800
+ }
801
+ else {
802
+ let size = 10;
803
+ let code = buffer >>> bits - 10 & 1023;
804
+ while (code > table.maxCode[size] && size <= 16) {
805
+ if (++size > 16)
806
+ break;
807
+ code = buffer >>> bits - size & (1 << size) - 1;
808
+ }
809
+ if (size > 16) {
810
+ if (!resync)
811
+ throw new Error('JPEG: invalid huffman code');
812
+ broken = true;
813
+ rs = 0;
814
+ }
815
+ else {
816
+ bits -= size;
817
+ rs = table.values[code + table.valueOffset[size]];
818
+ }
819
+ }
820
+ let r = rs >> 4;
821
+ let s = rs & 15;
822
+ if (s) {
823
+ if (bits < 1) {
824
+ while (bits <= 24) {
825
+ let byte = 0;
826
+ if (pos < length) {
827
+ byte = data[pos];
828
+ if (byte === 0xff) {
829
+ if (data[pos + 1] === 0x00)
830
+ pos += 2;
831
+ else {
832
+ byte = 0;
833
+ padding++;
834
+ }
835
+ }
836
+ else
837
+ pos++;
838
+ }
839
+ else
840
+ padding++;
841
+ buffer = buffer << 8 | byte;
842
+ bits += 8;
843
+ }
844
+ }
845
+ bits -= 1;
846
+ const bit = buffer >>> bits & 1;
847
+ s = bit ? p1 : m1;
848
+ }
849
+ else if (r !== 15) {
850
+ eobrun = 1 << r;
851
+ if (r) {
852
+ if (bits < r) {
853
+ while (bits <= 24) {
854
+ let byte = 0;
855
+ if (pos < length) {
856
+ byte = data[pos];
857
+ if (byte === 0xff) {
858
+ if (data[pos + 1] === 0x00)
859
+ pos += 2;
860
+ else {
861
+ byte = 0;
862
+ padding++;
863
+ }
864
+ }
865
+ else
866
+ pos++;
867
+ }
868
+ else
869
+ padding++;
870
+ buffer = buffer << 8 | byte;
871
+ bits += 8;
872
+ }
873
+ }
874
+ bits -= r;
875
+ const extra = buffer >>> bits & (1 << r) - 1;
876
+ eobrun += extra;
877
+ }
878
+ break;
879
+ }
880
+ const end = bounded ? last[offset >> 6] : 255;
881
+ do {
882
+ if (k > end) {
883
+ k += r;
884
+ if (k > se)
885
+ k = se + 1;
886
+ break;
887
+ }
888
+ const z = offset + ZIGZAG[k];
889
+ const c = coefficients[z];
890
+ if (c !== 0) {
891
+ if (bits < 1) {
892
+ while (bits <= 24) {
893
+ let byte = 0;
894
+ if (pos < length) {
895
+ byte = data[pos];
896
+ if (byte === 0xff) {
897
+ if (data[pos + 1] === 0x00)
898
+ pos += 2;
899
+ else {
900
+ byte = 0;
901
+ padding++;
902
+ }
903
+ }
904
+ else
905
+ pos++;
906
+ }
907
+ else
908
+ padding++;
909
+ buffer = buffer << 8 | byte;
910
+ bits += 8;
911
+ }
912
+ }
913
+ bits -= 1;
914
+ const bit = buffer >>> bits & 1;
915
+ if (bit && (c & p1) === 0)
916
+ coefficients[z] = c >= 0 ? c + p1 : c + m1;
917
+ }
918
+ else if (--r < 0)
919
+ break;
920
+ k++;
921
+ } while (k <= se);
922
+ if (s && k <= se) {
923
+ if (k > last[offset >> 6])
924
+ last[offset >> 6] = k;
925
+ coefficients[offset + ZIGZAG[k]] = s;
926
+ }
927
+ }
928
+ }
929
+ if (eobrun > 0) {
930
+ for (const end = bounded ? Math.min(se, last[offset >> 6]) : se; k <= end; k++) {
931
+ const z = offset + ZIGZAG[k];
932
+ const c = coefficients[z];
933
+ if (c !== 0) {
934
+ if (bits < 1) {
935
+ while (bits <= 24) {
936
+ let byte = 0;
937
+ if (pos < length) {
938
+ byte = data[pos];
939
+ if (byte === 0xff) {
940
+ if (data[pos + 1] === 0x00)
941
+ pos += 2;
942
+ else {
943
+ byte = 0;
944
+ padding++;
945
+ }
946
+ }
947
+ else
948
+ pos++;
949
+ }
950
+ else
951
+ padding++;
952
+ buffer = buffer << 8 | byte;
953
+ bits += 8;
954
+ }
955
+ }
956
+ bits -= 1;
957
+ const bit = buffer >>> bits & 1;
958
+ if (bit && (c & p1) === 0)
959
+ coefficients[z] = c >= 0 ? c + p1 : c + m1;
960
+ }
961
+ }
962
+ eobrun--;
963
+ }
964
+ }
965
+ reader.pos = pos;
966
+ reader.buffer = buffer;
967
+ reader.bits = bits;
968
+ reader.padding = padding;
969
+ reader.broken = broken;
970
+ reader.eobrun = eobrun;
971
+ return b;
972
+ }
484
973
  function render(component, row, count) {
485
974
  const { plane, done, coefficients, blocksPerLineForMcu: line } = component;
486
975
  if (!plane || !done)
@@ -697,6 +1186,71 @@ function upsample(component, frame) {
697
1186
  }
698
1187
  };
699
1188
  }
1189
+ function subsampledChroma({ components, hmax, vmax }) {
1190
+ const [y, cb, cr] = components;
1191
+ return y.h === hmax && y.v === vmax && cb.h === cr.h && cb.v === cr.v && hmax === 2 * cb.h && (vmax === cb.v || vmax === 2 * cb.v)
1192
+ && cb.width > 2 && cr.width > 2;
1193
+ }
1194
+ function convertSubsampled(frame, pixels) {
1195
+ const { width, height, components } = frame;
1196
+ const luma = buildPlane(components[0]), blue = buildPlane(components[1]), red = buildPlane(components[2]);
1197
+ const Y = luma.plane, B = blue.plane, R = red.plane;
1198
+ const cw = components[1].width, ch = components[1].height, stride = blue.stride;
1199
+ const vertical = frame.vmax === 2 * components[1].v;
1200
+ const words = new Uint32Array(pixels.buffer, pixels.byteOffset, width * height);
1201
+ const pixel = (a, b, c) => (CLAMP[a + crR[c]] | CLAMP[a + (cbG[b] + crG[c] >> 16)] << 8 | CLAMP[a + cbB[b]] << 16 | 0xff000000) >>> 0;
1202
+ for (let y = 0; y < height; y++) {
1203
+ const l = y * luma.stride, w = y * width;
1204
+ if (vertical) {
1205
+ const i = (y >> 1) * stride;
1206
+ const other = (y & 1 ? Math.min(ch - 1, (y >> 1) + 1) : Math.max(0, (y >> 1) - 1)) * stride;
1207
+ let thisB = B[i] * 3 + B[other], nextB = B[i + 1] * 3 + B[other + 1];
1208
+ let thisR = R[i] * 3 + R[other], nextR = R[i + 1] * 3 + R[other + 1];
1209
+ words[w] = pixel(Y[l] + CLAMP_OFFSET, thisB * 4 + 8 >> 4, thisR * 4 + 8 >> 4);
1210
+ if (width > 1)
1211
+ words[w + 1] = pixel(Y[l + 1] + CLAMP_OFFSET, thisB * 3 + nextB + 7 >> 4, thisR * 3 + nextR + 7 >> 4);
1212
+ let lastB = thisB, lastR = thisR;
1213
+ thisB = nextB;
1214
+ thisR = nextR;
1215
+ for (let x = 1; x < cw - 1; x++) {
1216
+ nextB = B[i + x + 1] * 3 + B[other + x + 1];
1217
+ nextR = R[i + x + 1] * 3 + R[other + x + 1];
1218
+ const o = 2 * x;
1219
+ if (o < width)
1220
+ words[w + o] = pixel(Y[l + o] + CLAMP_OFFSET, thisB * 3 + lastB + 8 >> 4, thisR * 3 + lastR + 8 >> 4);
1221
+ if (o + 1 < width)
1222
+ words[w + o + 1] = pixel(Y[l + o + 1] + CLAMP_OFFSET, thisB * 3 + nextB + 7 >> 4, thisR * 3 + nextR + 7 >> 4);
1223
+ lastB = thisB;
1224
+ lastR = thisR;
1225
+ thisB = nextB;
1226
+ thisR = nextR;
1227
+ }
1228
+ const o = 2 * cw - 2;
1229
+ if (o < width)
1230
+ words[w + o] = pixel(Y[l + o] + CLAMP_OFFSET, thisB * 3 + lastB + 8 >> 4, thisR * 3 + lastR + 8 >> 4);
1231
+ if (o + 1 < width)
1232
+ words[w + o + 1] = pixel(Y[l + o + 1] + CLAMP_OFFSET, thisB * 4 + 7 >> 4, thisR * 4 + 7 >> 4);
1233
+ }
1234
+ else {
1235
+ const i = y * stride;
1236
+ words[w] = pixel(Y[l] + CLAMP_OFFSET, B[i], R[i]);
1237
+ if (width > 1)
1238
+ words[w + 1] = pixel(Y[l + 1] + CLAMP_OFFSET, B[i] * 3 + B[i + 1] + 2 >> 2, R[i] * 3 + R[i + 1] + 2 >> 2);
1239
+ for (let x = 1; x < cw - 1; x++) {
1240
+ const b = B[i + x] * 3, r = R[i + x] * 3, o = 2 * x;
1241
+ if (o < width)
1242
+ words[w + o] = pixel(Y[l + o] + CLAMP_OFFSET, b + B[i + x - 1] + 1 >> 2, r + R[i + x - 1] + 1 >> 2);
1243
+ if (o + 1 < width)
1244
+ words[w + o + 1] = pixel(Y[l + o + 1] + CLAMP_OFFSET, b + B[i + x + 1] + 2 >> 2, r + R[i + x + 1] + 2 >> 2);
1245
+ }
1246
+ const o = 2 * cw - 2;
1247
+ if (o < width)
1248
+ words[w + o] = pixel(Y[l + o] + CLAMP_OFFSET, B[i + cw - 1] * 3 + B[i + cw - 2] + 1 >> 2, R[i + cw - 1] * 3 + R[i + cw - 2] + 1 >> 2);
1249
+ if (o + 1 < width)
1250
+ words[w + o + 1] = pixel(Y[l + o + 1] + CLAMP_OFFSET, B[i + cw - 1], R[i + cw - 1]);
1251
+ }
1252
+ }
1253
+ }
700
1254
  const crR = new Int32Array(256);
701
1255
  const cbB = new Int32Array(256);
702
1256
  const crG = new Int32Array(256);
@@ -713,7 +1267,6 @@ for (let i = 0; i < 768; i++)
713
1267
  CLAMP[i] = clamp8(i - CLAMP_OFFSET);
714
1268
  function output(frame, adobe, jfif, override) {
715
1269
  const { width, height, components } = frame;
716
- const planes = components.map(component => upsample(component, frame));
717
1270
  const pixels = new Uint8Array(width * height * 4);
718
1271
  const count = components.length;
719
1272
  let transform;
@@ -733,6 +1286,11 @@ function output(frame, adobe, jfif, override) {
733
1286
  transform = adobe && adobe.transform === 2 ? 'ycck' : 'cmyk';
734
1287
  else
735
1288
  throw new Error(`JPEG: ${count} color components are not supported`);
1289
+ if (transform === 'ycc' && littleEndian && subsampledChroma(frame)) {
1290
+ convertSubsampled(frame, pixels);
1291
+ return pixels;
1292
+ }
1293
+ const planes = components.map(component => upsample(component, frame));
736
1294
  const [p0, p1, p2, p3] = planes;
737
1295
  if (transform === 'gray' || transform === 'rgb' || transform === 'ycc') {
738
1296
  const s0 = p0.samples, s1 = (p1 ?? p0).samples, s2 = (p2 ?? p0).samples;
@@ -812,6 +1370,7 @@ const CHROMA_QUANTIZATION = [
812
1370
  99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
813
1371
  99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99
814
1372
  ];
1373
+ const FLAT_QUANTIZATION = new Array(64).fill(16);
815
1374
  const fix16 = (x) => Math.round(x * 65536);
816
1375
  const Y_R = new Int32Array(256), Y_G = new Int32Array(256), Y_B = new Int32Array(256);
817
1376
  const CB_R = new Int32Array(256), CB_G = new Int32Array(256), CB_B = new Int32Array(256);
@@ -847,14 +1406,14 @@ function reciprocals(table) {
847
1406
  }
848
1407
  return r;
849
1408
  }
850
- export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, rows } = {}) {
1409
+ export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, quantization, progressive = false, rows, maxTokens = MAX_TOKENS } = {}) {
851
1410
  if (!width || !height)
852
1411
  throw new RangeError('JPEG: invalid dimensions');
853
1412
  checkFormatSize('JPEG', width, height, 0xffff);
854
1413
  quality = Math.min(100, Math.max(1, Math.round(quality)));
855
1414
  const scale = quality < 50 ? Math.floor(5000 / quality) : 200 - quality * 2;
856
1415
  const scaleTable = (base) => base.map(v => Math.min(255, Math.max(1, Math.floor((v * scale + 50) / 100))));
857
- const tables = [scaleTable(LUMA_QUANTIZATION), scaleTable(CHROMA_QUANTIZATION)];
1416
+ const tables = quantization === 'flat' ? [scaleTable(FLAT_QUANTIZATION), scaleTable(FLAT_QUANTIZATION)] : [scaleTable(LUMA_QUANTIZATION), scaleTable(CHROMA_QUANTIZATION)];
858
1417
  const divisors = tables.map(reciprocals);
859
1418
  const subsample = !gray && !fullChroma && (subsampling ? subsampling === '4:2:0' : quality <= 90);
860
1419
  const hmax = subsample ? 2 : 1;
@@ -917,7 +1476,7 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
917
1476
  const blocksPerMcu = gray ? 1 : hmax * hmax + 2;
918
1477
  const count = mcusPerLine * mcusPerColumn * blocksPerMcu;
919
1478
  const coefficients = new Int16Array(count * 64);
920
- const owners = new Uint8Array(count), ends = new Uint8Array(count);
1479
+ const owners = new Uint8Array(count), ends = new Uint8Array(count), masks = new Uint32Array(count * 2);
921
1480
  const block = new Int32Array(64);
922
1481
  let n = 0;
923
1482
  for (let my = 0; my < mcusPerColumn; my++)
@@ -939,22 +1498,30 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
939
1498
  continue;
940
1499
  }
941
1500
  fdct(plane, by * 8 * stride + bx * 8, stride, block);
942
- let end = 0;
1501
+ let end = 0, low = 0, high = 0;
943
1502
  for (let k = 0; k < 64; k++) {
944
1503
  const i = ZIGZAG[k], t = block[i], sign = t >> 31;
945
1504
  const value = (Math.imul((t ^ sign) - sign + reciprocal[64 + i], reciprocal[i]) >>> reciprocal[128 + i] ^ sign) - sign;
946
1505
  coefficients[o + k] = value;
947
- if (value)
1506
+ if (value) {
948
1507
  end = k;
1508
+ if (k < 32)
1509
+ low |= 1 << k;
1510
+ else
1511
+ high |= 1 << k - 32;
1512
+ }
949
1513
  }
950
1514
  ends[n] = end;
1515
+ masks[n * 2] = low;
1516
+ masks[n * 2 + 1] = high;
951
1517
  }
952
1518
  }
953
1519
  }
954
- const blocks = { coefficients, owners, ends, count };
1520
+ const blocks = { coefficients, owners, ends, masks, count };
955
1521
  const frequencies = [new Int32Array(257), new Int32Array(257), new Int32Array(257), new Int32Array(257)];
956
- countSymbols(blocks, frequencies);
957
- const huffman = frequencies.slice(0, gray ? 2 : 4).map(buildOptimalTable);
1522
+ if (!progressive)
1523
+ countSymbols(blocks, frequencies);
1524
+ const huffman = progressive ? [] : frequencies.slice(0, gray ? 2 : 4).map(buildOptimalTable);
958
1525
  const writer = new BitWriter(width * height);
959
1526
  writer.bytes(0xff, 0xd8);
960
1527
  writer.bytes(0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00);
@@ -978,12 +1545,19 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
978
1545
  for (let k = 0; k < 64; k++)
979
1546
  writer.bytes(tables[t][ZIGZAG[k]]);
980
1547
  }
1548
+ const sof = progressive ? 0xc2 : 0xc0;
981
1549
  if (gray)
982
- writer.bytes(0xff, 0xc0, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0);
1550
+ writer.bytes(0xff, sof, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0);
983
1551
  else {
984
- writer.bytes(0xff, 0xc0, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03);
1552
+ writer.bytes(0xff, sof, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03);
985
1553
  writer.bytes(1, hmax << 4 | hmax, 0, 2, 0x11, 1, 3, 0x11, 1);
986
1554
  }
1555
+ if (progressive) {
1556
+ const layout = components.slice(0, componentCount).map((component, c) => ({ ...component, offset: c === 0 ? 0 : hmax * hmax + c - 1 }));
1557
+ writeProgressive(writer, progressiveScans(componentCount), blocks, layout, mcusPerLine, blocksPerMcu, maxTokens);
1558
+ writer.bytes(0xff, 0xd9);
1559
+ return writer.finish();
1560
+ }
987
1561
  for (const [index, id] of [[0, 0x00], [1, 0x10], [2, 0x01], [3, 0x11]].slice(0, gray ? 2 : 4)) {
988
1562
  const { bits, values } = huffman[index];
989
1563
  const length = 19 + values.length;
@@ -1002,6 +1576,323 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
1002
1576
  writer.bytes(0xff, 0xd9);
1003
1577
  return writer.finish();
1004
1578
  }
1579
+ function progressiveScans(componentCount) {
1580
+ const dc = { comps: Array.from({ length: componentCount }, (_, c) => c), ss: 0, se: 0, ah: 0, al: 0 };
1581
+ const ac = (comp, ss, se, ah, al) => ({ comps: [comp], ss, se, ah, al });
1582
+ const luma = [ac(0, 1, 2, 0, 1), ac(0, 3, 63, 0, 1), ac(0, 1, 63, 1, 0)];
1583
+ if (componentCount === 1)
1584
+ return [dc, ...luma];
1585
+ return [dc, ...luma, ac(1, 1, 8, 0, 0), ac(1, 9, 63, 0, 0), ac(2, 1, 8, 0, 0), ac(2, 9, 63, 0, 0)];
1586
+ }
1587
+ const MAX_TOKENS = 1 << 24;
1588
+ const MAX_CORR_BITS = 1000;
1589
+ class ScanCoder {
1590
+ eobrun = 0;
1591
+ pending = new Uint8Array(MAX_CORR_BITS);
1592
+ waiting = 0;
1593
+ emitEobrun(table) {
1594
+ if (this.eobrun === 0)
1595
+ return;
1596
+ const nbits = 31 - Math.clz32(this.eobrun);
1597
+ this.symbol(table, nbits << 4);
1598
+ if (nbits)
1599
+ this.bits(this.eobrun, nbits);
1600
+ this.eobrun = 0;
1601
+ this.buffered(0, this.waiting);
1602
+ this.waiting = 0;
1603
+ }
1604
+ dcFirst(coefficients, owners, count, last, al) {
1605
+ for (let n = 0; n < count; n++) {
1606
+ const component = owners[n], table = component === 0 ? 0 : 1;
1607
+ const value = coefficients[n * 64] >> al, diff = value - last[component];
1608
+ last[component] = value;
1609
+ const nbits = 32 - Math.clz32(Math.abs(diff));
1610
+ this.symbol(table, nbits);
1611
+ if (nbits)
1612
+ this.bits(diff < 0 ? diff - 1 : diff, nbits);
1613
+ }
1614
+ }
1615
+ skip(table) {
1616
+ this.eobrun++;
1617
+ if (this.eobrun === 0x7fff)
1618
+ this.emitEobrun(table);
1619
+ }
1620
+ acFirst(coefficients, o, low, high, table, ss, se, al) {
1621
+ let previous = ss - 1;
1622
+ for (let half = 0; half < 2; half++) {
1623
+ let bits = half === 0 ? low : high;
1624
+ while (bits !== 0) {
1625
+ const lowest = bits & -bits;
1626
+ bits ^= lowest;
1627
+ const k = (half << 5) + 31 - Math.clz32(lowest);
1628
+ let value = coefficients[o + k], coded;
1629
+ if (value < 0) {
1630
+ value = -value >> al;
1631
+ coded = ~value;
1632
+ }
1633
+ else {
1634
+ value >>= al;
1635
+ coded = value;
1636
+ }
1637
+ if (value === 0)
1638
+ continue;
1639
+ this.emitEobrun(table);
1640
+ let run = k - previous - 1;
1641
+ for (; run > 15; run -= 16)
1642
+ this.symbol(table, 0xf0);
1643
+ const nbits = 32 - Math.clz32(value);
1644
+ this.symbol(table, run << 4 | nbits);
1645
+ this.bits(coded, nbits);
1646
+ previous = k;
1647
+ }
1648
+ }
1649
+ if (previous < se) {
1650
+ this.eobrun++;
1651
+ if (this.eobrun === 0x7fff)
1652
+ this.emitEobrun(table);
1653
+ }
1654
+ }
1655
+ acRefine(coefficients, o, end, low, high, table, ss, se, al) {
1656
+ const stop = Math.min(se, end);
1657
+ let eob = 0;
1658
+ for (let k = stop; k >= ss; k--) {
1659
+ const value = coefficients[o + k];
1660
+ if ((value < 0 ? -value : value) >> al === 1) {
1661
+ eob = k;
1662
+ break;
1663
+ }
1664
+ }
1665
+ let last = ss - 1, run = 0, start = this.waiting, count = 0;
1666
+ for (let half = 0; half < 2; half++) {
1667
+ let bits = half === 0 ? low : high;
1668
+ while (bits !== 0) {
1669
+ const lowest = bits & -bits;
1670
+ bits ^= lowest;
1671
+ const k = (half << 5) + 31 - Math.clz32(lowest);
1672
+ run += k - last - 1;
1673
+ last = k;
1674
+ const coefficient = coefficients[o + k], value = (coefficient < 0 ? -coefficient : coefficient) >> al;
1675
+ if (value === 0) {
1676
+ run++;
1677
+ continue;
1678
+ }
1679
+ for (; run > 15 && k <= eob; run -= 16) {
1680
+ this.emitEobrun(table);
1681
+ this.symbol(table, 0xf0);
1682
+ this.buffered(start, count);
1683
+ start = 0;
1684
+ count = 0;
1685
+ }
1686
+ if (value > 1) {
1687
+ this.pending[start + count++] = value & 1;
1688
+ continue;
1689
+ }
1690
+ this.emitEobrun(table);
1691
+ this.symbol(table, run << 4 | 1);
1692
+ this.bits(coefficient < 0 ? 0 : 1, 1);
1693
+ this.buffered(start, count);
1694
+ start = 0;
1695
+ count = 0;
1696
+ run = 0;
1697
+ }
1698
+ }
1699
+ run += se - last;
1700
+ if (run > 0 || count > 0) {
1701
+ this.eobrun++;
1702
+ this.waiting += count;
1703
+ if (this.eobrun === 0x7fff || this.waiting > MAX_CORR_BITS - 63)
1704
+ this.emitEobrun(table);
1705
+ }
1706
+ }
1707
+ finish(table) {
1708
+ this.emitEobrun(table);
1709
+ }
1710
+ }
1711
+ class CountingCoder extends ScanCoder {
1712
+ counts = [new Int32Array(257), new Int32Array(257)];
1713
+ tokens;
1714
+ length = 0;
1715
+ overflow;
1716
+ max;
1717
+ constructor(tokens, overflow, max) {
1718
+ super();
1719
+ this.tokens = tokens;
1720
+ this.overflow = overflow;
1721
+ this.max = max;
1722
+ }
1723
+ push(token) {
1724
+ if (this.overflow)
1725
+ return;
1726
+ if (this.length === this.tokens.length) {
1727
+ if (this.length >= this.max) {
1728
+ this.overflow = true;
1729
+ return;
1730
+ }
1731
+ const grown = new Uint32Array(Math.min(this.length * 2, this.max));
1732
+ grown.set(this.tokens);
1733
+ this.tokens = grown;
1734
+ }
1735
+ this.tokens[this.length++] = token;
1736
+ }
1737
+ symbol(table, symbol) {
1738
+ this.counts[table][symbol]++;
1739
+ this.push(table << 8 | symbol);
1740
+ }
1741
+ bits(value, size) {
1742
+ this.push(0x80000000 | size << 16 | value & (1 << size) - 1);
1743
+ }
1744
+ buffered(start, count) {
1745
+ const pending = this.pending;
1746
+ while (count > 0) {
1747
+ const n = Math.min(count, 16);
1748
+ let value = 0;
1749
+ for (let i = 0; i < n; i++)
1750
+ value = value << 1 | pending[start + i];
1751
+ this.push(0x80000000 | n << 16 | value);
1752
+ start += n;
1753
+ count -= n;
1754
+ }
1755
+ }
1756
+ }
1757
+ class WritingCoder extends ScanCoder {
1758
+ writer;
1759
+ tables;
1760
+ acc;
1761
+ pendingBits;
1762
+ out;
1763
+ length;
1764
+ constructor(writer, tables) {
1765
+ super();
1766
+ this.writer = writer;
1767
+ this.tables = tables;
1768
+ this.acc = writer.bits;
1769
+ this.pendingBits = writer.count;
1770
+ this.out = writer.buffer;
1771
+ this.length = writer.length;
1772
+ }
1773
+ put(value, size) {
1774
+ const acc = this.acc << size | value & (1 << size) - 1;
1775
+ let n = this.pendingBits + size;
1776
+ while (n >= 8) {
1777
+ n -= 8;
1778
+ const byte = acc >>> n & 0xff;
1779
+ if (this.length + 2 > this.out.length)
1780
+ this.grow();
1781
+ this.out[this.length++] = byte;
1782
+ if (byte === 0xff)
1783
+ this.out[this.length++] = 0x00;
1784
+ }
1785
+ this.acc = acc & (1 << n) - 1;
1786
+ this.pendingBits = n;
1787
+ }
1788
+ grow() {
1789
+ this.writer.length = this.length;
1790
+ this.writer.reserve(2);
1791
+ this.out = this.writer.buffer;
1792
+ }
1793
+ symbol(table, symbol) {
1794
+ const { codes, sizes } = this.tables[table];
1795
+ this.put(codes[symbol], sizes[symbol]);
1796
+ }
1797
+ bits(value, size) {
1798
+ this.put(value, size);
1799
+ }
1800
+ buffered(start, count) {
1801
+ const pending = this.pending;
1802
+ while (count > 0) {
1803
+ const n = Math.min(count, 16);
1804
+ let value = 0;
1805
+ for (let i = 0; i < n; i++)
1806
+ value = value << 1 | pending[start + i];
1807
+ this.put(value, n);
1808
+ start += n;
1809
+ count -= n;
1810
+ }
1811
+ }
1812
+ replay(tokens, length) {
1813
+ const tables = this.tables;
1814
+ for (let i = 0; i < length; i++) {
1815
+ const token = tokens[i];
1816
+ if (token >= 0x80000000)
1817
+ this.put(token & 0xffff, token >>> 16 & 0x1f);
1818
+ else {
1819
+ const { codes, sizes } = tables[token >> 8];
1820
+ this.put(codes[token & 0xff], sizes[token & 0xff]);
1821
+ }
1822
+ }
1823
+ }
1824
+ done() {
1825
+ this.writer.bits = this.acc;
1826
+ this.writer.count = this.pendingBits;
1827
+ this.writer.length = this.length;
1828
+ }
1829
+ }
1830
+ function writeProgressive(writer, scans, { coefficients, owners, ends, masks, count }, layout, mcusPerLine, blocksPerMcu, maxTokens) {
1831
+ const slot = (comp) => comp === 0 ? 0 : 1;
1832
+ const run = (coder, { comps, ss, se, ah, al }) => {
1833
+ if (ss === 0) {
1834
+ coder.dcFirst(coefficients, owners, count, [0, 0, 0], al);
1835
+ return;
1836
+ }
1837
+ const comp = comps[0], { h, v, blocksX, blocksY, offset } = layout[comp];
1838
+ const table = slot(comp);
1839
+ const lowBand = ss > 31 ? 0 : -1 << ss & (se > 30 ? -1 : (1 << se + 1) - 1);
1840
+ const highBand = se < 32 ? 0 : (ss > 32 ? -1 << ss - 32 : -1) & (se > 62 ? -1 : (1 << se - 31) - 1);
1841
+ const columns = new Int32Array(blocksX);
1842
+ for (let bx = 0; bx < blocksX; bx++)
1843
+ columns[bx] = (bx / h | 0) * blocksPerMcu + bx % h;
1844
+ for (let by = 0; by < blocksY; by++) {
1845
+ const row = (by / v | 0) * mcusPerLine * blocksPerMcu + offset + by % v * h;
1846
+ for (let bx = 0; bx < blocksX; bx++) {
1847
+ const n = row + columns[bx];
1848
+ if (ends[n] < ss)
1849
+ coder.skip(table);
1850
+ else if (ah === 0)
1851
+ coder.acFirst(coefficients, n * 64, masks[n * 2] & lowBand, masks[n * 2 + 1] & highBand, table, ss, se, al);
1852
+ else
1853
+ coder.acRefine(coefficients, n * 64, ends[n], masks[n * 2] & lowBand, masks[n * 2 + 1] & highBand, table, ss, se, al);
1854
+ }
1855
+ }
1856
+ coder.finish(table);
1857
+ };
1858
+ let tokens = new Uint32Array(Math.min(1 << 16, maxTokens));
1859
+ let tooLong = false;
1860
+ for (const scan of scans) {
1861
+ const { comps, ss, se, ah, al } = scan;
1862
+ const dcScan = ss === 0;
1863
+ const counter = new CountingCoder(tokens, tooLong, maxTokens);
1864
+ run(counter, scan);
1865
+ tokens = counter.tokens;
1866
+ tooLong = counter.overflow;
1867
+ const counts = counter.counts;
1868
+ const used = [];
1869
+ for (const comp of comps)
1870
+ if (!used.includes(slot(comp)))
1871
+ used.push(slot(comp));
1872
+ const tables = [];
1873
+ for (const table of used)
1874
+ tables[table] = buildOptimalTable(counts[table]);
1875
+ for (const table of used) {
1876
+ const { bits, values } = tables[table];
1877
+ writer.bytes(0xff, 0xc4, 19 + values.length >> 8, 19 + values.length & 0xff, table | (dcScan ? 0x00 : 0x10));
1878
+ for (let i = 1; i <= 16; i++)
1879
+ writer.bytes(bits[i]);
1880
+ for (const value of values)
1881
+ writer.bytes(value);
1882
+ }
1883
+ writer.bytes(0xff, 0xda, 0x00, 2 * comps.length + 6, comps.length);
1884
+ for (const comp of comps)
1885
+ writer.bytes(comp + 1, dcScan ? slot(comp) << 4 : slot(comp));
1886
+ writer.bytes(ss, se, ah << 4 | al);
1887
+ const coder = new WritingCoder(writer, tables);
1888
+ if (counter.overflow)
1889
+ run(coder, scan);
1890
+ else
1891
+ coder.replay(tokens, counter.length);
1892
+ coder.done();
1893
+ writer.flush();
1894
+ }
1895
+ }
1005
1896
  function countSymbols({ coefficients, owners, ends, count }, frequencies) {
1006
1897
  const pred = [0, 0, 0];
1007
1898
  for (let n = 0; n < count; n++) {