qrdx 0.0.56 → 0.0.58

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 (263) hide show
  1. package/README.md +27 -6
  2. package/dist/angular.js +33 -3
  3. package/dist/angular.js.map +1 -1
  4. package/dist/angular.mjs +33 -3
  5. package/dist/angular.mjs.map +1 -1
  6. package/dist/core.js +7 -7
  7. package/dist/core.js.map +1 -1
  8. package/dist/core.mjs +7 -7
  9. package/dist/core.mjs.map +1 -1
  10. package/dist/element.browser.mjs +6 -6
  11. package/dist/element.browser.mjs.map +1 -1
  12. package/dist/element.js +1 -1
  13. package/dist/element.js.map +1 -1
  14. package/dist/element.mjs +1 -1
  15. package/dist/element.mjs.map +1 -1
  16. package/dist/frames-index.js +1 -1
  17. package/dist/frames-index.js.map +1 -1
  18. package/dist/frames-index.mjs +1 -1
  19. package/dist/frames-index.mjs.map +1 -1
  20. package/dist/frames-official.js +1 -1
  21. package/dist/frames-official.js.map +1 -1
  22. package/dist/frames-official.mjs +1 -1
  23. package/dist/frames-official.mjs.map +1 -1
  24. package/dist/index.js +7 -7
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +7 -7
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/qr-code-canvas.js +1 -1
  29. package/dist/qr-code-canvas.js.map +1 -1
  30. package/dist/qr-code-canvas.mjs +1 -1
  31. package/dist/qr-code-canvas.mjs.map +1 -1
  32. package/dist/schemas.js +1 -1
  33. package/dist/schemas.js.map +1 -1
  34. package/dist/schemas.mjs +1 -1
  35. package/dist/schemas.mjs.map +1 -1
  36. package/dist/src/angular.d.ts +9 -3
  37. package/dist/src/bmp.d.ts +7 -0
  38. package/dist/src/bmp.d.ts.map +1 -0
  39. package/dist/src/download.d.ts +39 -6
  40. package/dist/src/download.d.ts.map +1 -1
  41. package/dist/src/element.d.ts +10 -1
  42. package/dist/src/element.d.ts.map +1 -1
  43. package/dist/src/engine.d.ts +6 -2
  44. package/dist/src/engine.d.ts.map +1 -1
  45. package/dist/src/eps.d.ts.map +1 -1
  46. package/dist/src/export.d.ts.map +1 -1
  47. package/dist/src/frame.d.ts +24 -0
  48. package/dist/src/frame.d.ts.map +1 -1
  49. package/dist/src/frames/catalogue/all.d.ts.map +1 -1
  50. package/dist/src/frames/catalogue/batches.d.ts +6 -0
  51. package/dist/src/frames/catalogue/batches.d.ts.map +1 -0
  52. package/dist/src/frames/catalogue/call-to-action.d.ts.map +1 -1
  53. package/dist/src/frames/catalogue/counts.d.ts +4 -2
  54. package/dist/src/frames/catalogue/counts.d.ts.map +1 -1
  55. package/dist/src/frames/catalogue/index.d.ts.map +1 -1
  56. package/dist/src/frames/catalogue/objects.d.ts +5 -0
  57. package/dist/src/frames/catalogue/objects.d.ts.map +1 -0
  58. package/dist/src/frames/catalogue/playful.d.ts +5 -0
  59. package/dist/src/frames/catalogue/playful.d.ts.map +1 -0
  60. package/dist/src/frames/catalogue/tags.d.ts.map +1 -1
  61. package/dist/src/frames/collections.d.ts.map +1 -1
  62. package/dist/src/frames/official-types.d.ts +1 -1
  63. package/dist/src/frames/official-types.d.ts.map +1 -1
  64. package/dist/src/frames/official.d.ts.map +1 -1
  65. package/dist/src/gif.d.ts +40 -0
  66. package/dist/src/gif.d.ts.map +1 -0
  67. package/dist/src/helpers.d.ts +1 -1
  68. package/dist/src/helpers.d.ts.map +1 -1
  69. package/dist/src/ico.d.ts +11 -0
  70. package/dist/src/ico.d.ts.map +1 -0
  71. package/dist/src/index.d.ts +2 -1
  72. package/dist/src/index.d.ts.map +1 -1
  73. package/dist/src/looks.d.ts +101 -0
  74. package/dist/src/looks.d.ts.map +1 -0
  75. package/dist/src/plain.d.ts.map +1 -1
  76. package/dist/src/print.d.ts.map +1 -1
  77. package/dist/src/qr-code-canvas.d.ts.map +1 -1
  78. package/dist/src/qr-code-props.d.ts.map +1 -1
  79. package/dist/src/qr-frame-svg.d.ts +10 -0
  80. package/dist/src/qr-frame-svg.d.ts.map +1 -0
  81. package/dist/src/scan-score.d.ts.map +1 -1
  82. package/dist/src/utils/bmp.d.ts +18 -0
  83. package/dist/src/utils/bmp.d.ts.map +1 -0
  84. package/dist/src/utils/gif.d.ts +61 -0
  85. package/dist/src/utils/gif.d.ts.map +1 -0
  86. package/dist/src/utils/ico.d.ts +30 -0
  87. package/dist/src/utils/ico.d.ts.map +1 -0
  88. package/dist/src/utils/parse-color.d.ts +1 -1
  89. package/dist/src/utils/parse-color.d.ts.map +1 -1
  90. package/dist/src/utils/print-shared.d.ts.map +1 -1
  91. package/dist/src/utils/svg-painter.d.ts +13 -0
  92. package/dist/src/utils/svg-painter.d.ts.map +1 -1
  93. package/dist/src/utils.d.ts.map +1 -1
  94. package/dist/src/vanilla-api.d.ts +2 -2
  95. package/dist/src/vanilla-api.d.ts.map +1 -1
  96. package/dist/src/vue.d.ts +2 -2
  97. package/dist/src/vue.d.ts.map +1 -1
  98. package/dist/types/constants.d.ts +41 -0
  99. package/dist/types/constants.d.ts.map +1 -1
  100. package/dist/types/index.js +2 -2
  101. package/dist/types/index.js.map +1 -1
  102. package/dist/types/index.mjs +2 -2
  103. package/dist/types/index.mjs.map +1 -1
  104. package/dist/types/plain.d.ts +2 -2
  105. package/dist/types/plain.d.ts.map +1 -1
  106. package/dist/types/qr.d.ts +399 -1
  107. package/dist/types/qr.d.ts.map +1 -1
  108. package/dist/types/react.d.ts +10 -1
  109. package/dist/types/react.d.ts.map +1 -1
  110. package/dist/types/schemas.d.ts +1 -1
  111. package/dist/types/schemas.d.ts.map +1 -1
  112. package/dist/vanilla.browser.mjs +34 -34
  113. package/dist/vanilla.browser.mjs.map +1 -1
  114. package/dist/vue.js +1 -1
  115. package/dist/vue.js.map +1 -1
  116. package/dist/vue.mjs +1 -1
  117. package/dist/vue.mjs.map +1 -1
  118. package/package.json +6 -2
  119. package/src/angular.ts +14 -2
  120. package/src/bmp.ts +25 -0
  121. package/src/download.tsx +128 -8
  122. package/src/element.ts +16 -1
  123. package/src/engine.ts +23 -0
  124. package/src/eps.ts +8 -1
  125. package/src/export.ts +22 -0
  126. package/src/frame.tsx +51 -0
  127. package/src/frames/catalogue/all.ts +202 -0
  128. package/src/frames/catalogue/batches.ts +114 -0
  129. package/src/frames/catalogue/call-to-action.ts +58 -0
  130. package/src/frames/catalogue/counts.ts +4 -2
  131. package/src/frames/catalogue/index.ts +808 -0
  132. package/src/frames/catalogue/objects.ts +65 -0
  133. package/src/frames/catalogue/playful.ts +97 -0
  134. package/src/frames/catalogue/tags.ts +137 -0
  135. package/src/frames/collections.ts +2 -0
  136. package/src/frames/official/badge-bottom-light.json +91 -0
  137. package/src/frames/official/badge-bottom.json +79 -0
  138. package/src/frames/official/billboard-campaign.json +274 -0
  139. package/src/frames/official/billboard-light.json +287 -0
  140. package/src/frames/official/bookmark-light.json +88 -0
  141. package/src/frames/official/bookmark-strip.json +83 -0
  142. package/src/frames/official/border-medium.json +71 -0
  143. package/src/frames/official/border-thick.json +71 -0
  144. package/src/frames/official/border-thin.json +71 -0
  145. package/src/frames/official/bottle-label.json +136 -0
  146. package/src/frames/official/bottle-light.json +133 -0
  147. package/src/frames/official/camera-viewfinder.json +174 -0
  148. package/src/frames/official/cassette-tape.json +236 -0
  149. package/src/frames/official/cat-with-card-light.json +246 -0
  150. package/src/frames/official/cat-with-card.json +234 -0
  151. package/src/frames/official/cinema-marquee.json +537 -0
  152. package/src/frames/official/circle-viewfinder.json +87 -0
  153. package/src/frames/official/clapperboard-light.json +163 -0
  154. package/src/frames/official/clapperboard-scene.json +151 -0
  155. package/src/frames/official/comic-panel.json +386 -0
  156. package/src/frames/official/corner-tab-light.json +101 -0
  157. package/src/frames/official/corner-tab.json +89 -0
  158. package/src/frames/official/crystal-ball.json +105 -0
  159. package/src/frames/official/delivery-box-light.json +132 -0
  160. package/src/frames/official/delivery-box-track.json +132 -0
  161. package/src/frames/official/fish-tank.json +276 -0
  162. package/src/frames/official/flag-light.json +136 -0
  163. package/src/frames/official/flag-team.json +127 -0
  164. package/src/frames/official/floppy-disk.json +106 -0
  165. package/src/frames/official/flying-saucer.json +128 -0
  166. package/src/frames/official/gallery-frame.json +195 -0
  167. package/src/frames/official/globe-stand.json +136 -0
  168. package/src/frames/official/gumball-machine.json +451 -0
  169. package/src/frames/official/heart-light.json +59 -0
  170. package/src/frames/official/heart-scan.json +51 -0
  171. package/src/frames/official/hexagon-light.json +87 -0
  172. package/src/frames/official/hexagon-scan.json +72 -0
  173. package/src/frames/official/hot-air-balloon.json +132 -0
  174. package/src/frames/official/jigsaw-piece-light.json +68 -0
  175. package/src/frames/official/jigsaw-piece.json +60 -0
  176. package/src/frames/official/laptop-screen.json +137 -0
  177. package/src/frames/official/lighthouse-tower.json +132 -0
  178. package/src/frames/official/magnifying-glass.json +85 -0
  179. package/src/frames/official/mailbox-flag.json +112 -0
  180. package/src/frames/official/mailbox-light.json +120 -0
  181. package/src/frames/official/map-pin-light.json +76 -0
  182. package/src/frames/official/map-pin.json +58 -0
  183. package/src/frames/official/matchbox-drawer.json +170 -0
  184. package/src/frames/official/microwave-door.json +220 -0
  185. package/src/frames/official/milk-carton.json +129 -0
  186. package/src/frames/official/monitor-screen.json +111 -0
  187. package/src/frames/official/monster-mouth.json +180 -0
  188. package/src/frames/official/mug-light.json +138 -0
  189. package/src/frames/official/mug-refill.json +125 -0
  190. package/src/frames/official/museum-plaque-light.json +187 -0
  191. package/src/frames/official/museum-plaque.json +187 -0
  192. package/src/frames/official/music-player-light.json +151 -0
  193. package/src/frames/official/music-player.json +136 -0
  194. package/src/frames/official/octagon-light.json +126 -0
  195. package/src/frames/official/octagon-sign.json +120 -0
  196. package/src/frames/official/open-book.json +156 -0
  197. package/src/frames/official/parking-meter.json +107 -0
  198. package/src/frames/official/passport-stamp.json +132 -0
  199. package/src/frames/official/pizza-box.json +122 -0
  200. package/src/frames/official/polka-dot-border.json +502 -0
  201. package/src/frames/official/popcorn-bucket.json +305 -0
  202. package/src/frames/official/porthole.json +264 -0
  203. package/src/frames/official/raised-card-thin.json +111 -0
  204. package/src/frames/official/raised-card.json +99 -0
  205. package/src/frames/official/retro-radio.json +180 -0
  206. package/src/frames/official/ribbon-top-light.json +125 -0
  207. package/src/frames/official/ribbon-top.json +113 -0
  208. package/src/frames/official/robot-chest.json +197 -0
  209. package/src/frames/official/roll-up-banner-light.json +137 -0
  210. package/src/frames/official/roll-up-banner.json +125 -0
  211. package/src/frames/official/round-tag-light.json +86 -0
  212. package/src/frames/official/round-tag.json +79 -0
  213. package/src/frames/official/sailboat-sail.json +99 -0
  214. package/src/frames/official/scroll-story.json +184 -0
  215. package/src/frames/official/sketch-border.json +92 -0
  216. package/src/frames/official/sketch-circle.json +57 -0
  217. package/src/frames/official/snow-globe.json +170 -0
  218. package/src/frames/official/soda-can.json +160 -0
  219. package/src/frames/official/spin-rays.json +126 -0
  220. package/src/frames/official/spiral-notebook.json +476 -0
  221. package/src/frames/official/stage-curtains.json +303 -0
  222. package/src/frames/official/starburst-light.json +128 -0
  223. package/src/frames/official/starburst.json +118 -0
  224. package/src/frames/official/swirl-border.json +122 -0
  225. package/src/frames/official/tablet-screen.json +130 -0
  226. package/src/frames/official/text-frame.json +79 -0
  227. package/src/frames/official/toaster-toast.json +114 -0
  228. package/src/frames/official/train-window.json +176 -0
  229. package/src/frames/official/treasure-map.json +207 -0
  230. package/src/frames/official/tv-set.json +256 -0
  231. package/src/frames/official/vending-machine.json +218 -0
  232. package/src/frames/official/video-player.json +118 -0
  233. package/src/frames/official/video-tape.json +137 -0
  234. package/src/frames/official/vinyl-sleeve-light.json +139 -0
  235. package/src/frames/official/vinyl-sleeve.json +127 -0
  236. package/src/frames/official/washing-machine.json +146 -0
  237. package/src/frames/official-types.ts +3 -1
  238. package/src/frames/official.ts +4 -3
  239. package/src/gif.ts +188 -0
  240. package/src/helpers.ts +12 -0
  241. package/src/ico.ts +55 -0
  242. package/src/index.tsx +2 -0
  243. package/src/looks.ts +467 -0
  244. package/src/plain.tsx +6 -0
  245. package/src/print.ts +12 -0
  246. package/src/qr-code-canvas.tsx +23 -2
  247. package/src/qr-code-props.ts +22 -0
  248. package/src/qr-frame-svg.tsx +26 -0
  249. package/src/scan-score.ts +38 -6
  250. package/src/utils/bmp.ts +126 -0
  251. package/src/utils/gif.ts +632 -0
  252. package/src/utils/ico.ts +150 -0
  253. package/src/utils/parse-color.ts +163 -23
  254. package/src/utils/print-shared.ts +25 -1
  255. package/src/utils/svg-painter.ts +18 -0
  256. package/src/utils.tsx +136 -17
  257. package/src/vanilla-api.ts +2 -2
  258. package/src/vue.ts +8 -2
  259. package/types/constants.ts +47 -0
  260. package/types/plain.ts +19 -0
  261. package/types/qr.ts +98 -0
  262. package/types/react.ts +11 -1
  263. package/types/schemas.ts +5 -0
@@ -0,0 +1,632 @@
1
+ /** biome-ignore-all lint/style/noMagicNumbers: GIF format constants and color maths */
2
+ /** biome-ignore-all lint/suspicious/noBitwiseOperators: LZW codes, packed fields and color keys */
3
+ // A GIF writer in plain TypeScript with no DOM. Canvases can't encode GIF
4
+ // (toBlob("image/gif") hands back a PNG), so every browser and the CLI use
5
+ // this one; the server uses sharp.
6
+ //
7
+ // A GIF holds at most 256 colors and one of them may be transparent, so the
8
+ // pixels are first reduced to a palette (`quantizeRGBA`): the image's own
9
+ // colors when it has few enough (lossless, which a QR code in flat colors
10
+ // almost always does), otherwise a median-cut palette with no dithering,
11
+ // because dither noise is what stops a code scanning. The indexed pixels are
12
+ // then written as one GIF89a image with LZW compression (`encodeGIF`).
13
+
14
+ /** Most colors a GIF palette holds. */
15
+ export const GIF_MAX_COLORS = 256;
16
+
17
+ /** Largest width or height written (the format allows 65 535). */
18
+ export const GIF_MAX_DIMENSION = 16_384;
19
+
20
+ /** A pixel with less alpha than this is transparent; with this or more, opaque. */
21
+ export const GIF_ALPHA_THRESHOLD = 128;
22
+
23
+ const OPAQUE = 255;
24
+ /**
25
+ * Bits kept of each channel to bucket colors for median cut: 6 means colors
26
+ * within 3 of each other (out of 255) share a bucket, which no eye or scanner
27
+ * tells apart, and keeps the histogram to 262 144 buckets.
28
+ */
29
+ const BUCKET_BITS = 6;
30
+ const BUCKET_SHIFT = 8 - BUCKET_BITS;
31
+ const BUCKET_COUNT = 1 << (BUCKET_BITS * 3);
32
+ /** The most codes LZW may use (12-bit codes). */
33
+ const MAX_CODES = 4096;
34
+
35
+ /** An image as a palette and one palette index per pixel. */
36
+ export interface IndexedImage {
37
+ width: number;
38
+ height: number;
39
+ /** Red, green, blue for each color, in that order: 3 bytes a color */
40
+ palette: Uint8Array;
41
+ /** One palette index per pixel, top row first */
42
+ indices: Uint8Array;
43
+ /** The palette index that is see-through, or null when nothing is */
44
+ transparentIndex: number | null;
45
+ }
46
+
47
+ export interface QuantizedImage extends IndexedImage {
48
+ /** How many palette entries are used (the transparent one included) */
49
+ colors: number;
50
+ /**
51
+ * True when every pixel keeps its color and its opacity exactly: the
52
+ * image had no more than 256 colors and no half-transparent pixel.
53
+ */
54
+ lossless: boolean;
55
+ }
56
+
57
+ const validateSize = (width: number, height: number): void => {
58
+ if (
59
+ !(Number.isInteger(width) && Number.isInteger(height)) ||
60
+ width < 1 ||
61
+ height < 1 ||
62
+ width > GIF_MAX_DIMENSION ||
63
+ height > GIF_MAX_DIMENSION
64
+ ) {
65
+ throw new RangeError(
66
+ `GIF width and height must be whole numbers from 1 to ${GIF_MAX_DIMENSION}, got ${width} x ${height}`
67
+ );
68
+ }
69
+ };
70
+
71
+ /** A box of color buckets, for median cut. */
72
+ interface Box {
73
+ /** The bucket keys inside, sorted along no particular axis until split */
74
+ keys: number[];
75
+ pixels: number;
76
+ }
77
+
78
+ const channelOf = (key: number, channel: 0 | 1 | 2): number =>
79
+ (key >> (BUCKET_BITS * (2 - channel))) & ((1 << BUCKET_BITS) - 1);
80
+
81
+ /**
82
+ * RGBA pixels (as a canvas's getImageData or sharp's raw output returns them:
83
+ * `width * height * 4` bytes, top row first, not premultiplied) reduced to a
84
+ * GIF palette. A pixel with alpha under 128 becomes the one transparent
85
+ * color, and any other becomes opaque. The image's own colors are kept
86
+ * when they fit in 256 (255 plus the transparent one); otherwise a
87
+ * median-cut palette stands in for them. Throws a RangeError for a size
88
+ * outside 1 to GIF_MAX_DIMENSION, or pixels that don't match it.
89
+ */
90
+ export function quantizeRGBA(
91
+ rgba: ArrayLike<number>,
92
+ width: number,
93
+ height: number
94
+ ): QuantizedImage {
95
+ validateSize(width, height);
96
+ const count = width * height;
97
+ if (rgba.length !== count * 4) {
98
+ throw new RangeError(
99
+ `Expected ${count * 4} RGBA bytes for ${width} x ${height}, got ${rgba.length}`
100
+ );
101
+ }
102
+
103
+ // Pass 1: which colors are there, and is anything see-through
104
+ const exactColors = new Map<number, number>();
105
+ let transparent = false;
106
+ let partial = false;
107
+ let tooMany = false;
108
+ for (let pixel = 0; pixel < count; pixel++) {
109
+ const at = pixel * 4;
110
+ const alpha = rgba[at + 3] as number;
111
+ if (alpha < GIF_ALPHA_THRESHOLD) {
112
+ transparent = true;
113
+ partial ||= alpha > 0;
114
+ continue;
115
+ }
116
+ partial ||= alpha < OPAQUE;
117
+ if (!tooMany) {
118
+ const key =
119
+ ((rgba[at] as number) << 16) |
120
+ ((rgba[at + 1] as number) << 8) |
121
+ (rgba[at + 2] as number);
122
+ if (!exactColors.has(key)) {
123
+ exactColors.set(key, exactColors.size);
124
+ // 256 opaque colors fit only when nothing is transparent; the
125
+ // check is repeated below, once the transparency is known
126
+ tooMany = exactColors.size > GIF_MAX_COLORS;
127
+ }
128
+ }
129
+ }
130
+ const room = transparent ? GIF_MAX_COLORS - 1 : GIF_MAX_COLORS;
131
+ const exact = !tooMany && exactColors.size <= room;
132
+
133
+ const indices = new Uint8Array(count);
134
+ let opaqueColors: number;
135
+ let paletteRGB: number[];
136
+ let lookup: (red: number, green: number, blue: number) => number;
137
+
138
+ if (exact) {
139
+ // The image's own colors, in the order they first appear
140
+ paletteRGB = [];
141
+ for (const key of exactColors.keys()) {
142
+ paletteRGB.push((key >> 16) & 255, (key >> 8) & 255, key & 255);
143
+ }
144
+ opaqueColors = exactColors.size;
145
+ lookup = (red, green, blue) =>
146
+ exactColors.get((red << 16) | (green << 8) | blue) as number;
147
+ } else {
148
+ const built = medianCut(rgba, count, room);
149
+ paletteRGB = built.palette;
150
+ opaqueColors = built.palette.length / 3;
151
+ lookup = (red, green, blue) =>
152
+ built.bucketIndex[bucketKey(red, green, blue)] as number;
153
+ }
154
+
155
+ const transparentIndex = transparent ? opaqueColors : null;
156
+ for (let pixel = 0; pixel < count; pixel++) {
157
+ const at = pixel * 4;
158
+ if ((rgba[at + 3] as number) < GIF_ALPHA_THRESHOLD) {
159
+ indices[pixel] = transparentIndex as number;
160
+ } else {
161
+ indices[pixel] = lookup(
162
+ rgba[at] as number,
163
+ rgba[at + 1] as number,
164
+ rgba[at + 2] as number
165
+ );
166
+ }
167
+ }
168
+
169
+ const colors = opaqueColors + (transparent ? 1 : 0);
170
+ const palette = new Uint8Array(colors * 3);
171
+ palette.set(paletteRGB);
172
+ if (transparent) {
173
+ // The color behind the see-through entry, for a reader that ignores it
174
+ palette.fill(255, opaqueColors * 3);
175
+ }
176
+ return {
177
+ width,
178
+ height,
179
+ palette,
180
+ indices,
181
+ transparentIndex,
182
+ colors,
183
+ lossless: exact && !partial,
184
+ };
185
+ }
186
+
187
+ const bucketKey = (red: number, green: number, blue: number): number =>
188
+ ((red >> BUCKET_SHIFT) << (BUCKET_BITS * 2)) |
189
+ ((green >> BUCKET_SHIFT) << BUCKET_BITS) |
190
+ (blue >> BUCKET_SHIFT);
191
+
192
+ /**
193
+ * At most `limit` colors that stand for the opaque pixels, by median cut:
194
+ * the pixels are counted into 6-bit-a-channel buckets, the box with the most
195
+ * pixels is split at its weighted median along its widest channel until there
196
+ * are `limit` boxes, and each box becomes its pixels' mean color. Every
197
+ * bucket is mapped to the nearest of those colors.
198
+ */
199
+ function medianCut(
200
+ rgba: ArrayLike<number>,
201
+ count: number,
202
+ limit: number
203
+ ): { palette: number[]; bucketIndex: Uint8Array } {
204
+ const population = new Uint32Array(BUCKET_COUNT);
205
+ const sumRed = new Float64Array(BUCKET_COUNT);
206
+ const sumGreen = new Float64Array(BUCKET_COUNT);
207
+ const sumBlue = new Float64Array(BUCKET_COUNT);
208
+ for (let pixel = 0; pixel < count; pixel++) {
209
+ const at = pixel * 4;
210
+ if ((rgba[at + 3] as number) < GIF_ALPHA_THRESHOLD) {
211
+ continue;
212
+ }
213
+ const red = rgba[at] as number;
214
+ const green = rgba[at + 1] as number;
215
+ const blue = rgba[at + 2] as number;
216
+ const key = bucketKey(red, green, blue);
217
+ population[key] = (population[key] as number) + 1;
218
+ sumRed[key] = (sumRed[key] as number) + red;
219
+ sumGreen[key] = (sumGreen[key] as number) + green;
220
+ sumBlue[key] = (sumBlue[key] as number) + blue;
221
+ }
222
+
223
+ const keys: number[] = [];
224
+ for (let key = 0; key < BUCKET_COUNT; key++) {
225
+ if ((population[key] as number) > 0) {
226
+ keys.push(key);
227
+ }
228
+ }
229
+ const boxes: Box[] = [
230
+ {
231
+ keys,
232
+ pixels: keys.reduce((sum, key) => sum + (population[key] as number), 0),
233
+ },
234
+ ];
235
+
236
+ while (boxes.length < limit) {
237
+ // The splittable box holding the most pixels
238
+ let pick = -1;
239
+ for (let index = 0; index < boxes.length; index++) {
240
+ const box = boxes[index] as Box;
241
+ if (
242
+ box.keys.length > 1 &&
243
+ (pick === -1 || box.pixels > (boxes[pick] as Box).pixels)
244
+ ) {
245
+ pick = index;
246
+ }
247
+ }
248
+ if (pick === -1) {
249
+ break;
250
+ }
251
+ const box = boxes[pick] as Box;
252
+
253
+ // Widest channel in this box
254
+ let widest: 0 | 1 | 2 = 0;
255
+ let widestRange = -1;
256
+ for (const channel of [0, 1, 2] as const) {
257
+ let low = 255;
258
+ let high = 0;
259
+ for (const key of box.keys) {
260
+ const value = channelOf(key, channel);
261
+ low = Math.min(low, value);
262
+ high = Math.max(high, value);
263
+ }
264
+ if (high - low > widestRange) {
265
+ widestRange = high - low;
266
+ widest = channel;
267
+ }
268
+ }
269
+
270
+ // Split at the weighted median, keeping at least one bucket a side
271
+ const sorted = [...box.keys].sort(
272
+ (a, b) => channelOf(a, widest) - channelOf(b, widest) || a - b
273
+ );
274
+ const half = box.pixels / 2;
275
+ let running = 0;
276
+ let cut = 1;
277
+ for (let index = 0; index < sorted.length - 1; index++) {
278
+ running += population[sorted[index] as number] as number;
279
+ cut = index + 1;
280
+ if (running >= half) {
281
+ break;
282
+ }
283
+ }
284
+ const left = sorted.slice(0, cut);
285
+ const right = sorted.slice(cut);
286
+ const weigh = (list: number[]) =>
287
+ list.reduce((sum, key) => sum + (population[key] as number), 0);
288
+ boxes.splice(
289
+ pick,
290
+ 1,
291
+ { keys: left, pixels: weigh(left) },
292
+ { keys: right, pixels: weigh(right) }
293
+ );
294
+ }
295
+
296
+ const palette: number[] = [];
297
+ for (const box of boxes) {
298
+ let red = 0;
299
+ let green = 0;
300
+ let blue = 0;
301
+ for (const key of box.keys) {
302
+ red += sumRed[key] as number;
303
+ green += sumGreen[key] as number;
304
+ blue += sumBlue[key] as number;
305
+ }
306
+ palette.push(
307
+ Math.round(red / box.pixels),
308
+ Math.round(green / box.pixels),
309
+ Math.round(blue / box.pixels)
310
+ );
311
+ }
312
+
313
+ // Each bucket takes the nearest palette color to its own mean
314
+ const bucketIndex = new Uint8Array(BUCKET_COUNT);
315
+ const total = palette.length / 3;
316
+ for (const key of keys) {
317
+ const pop = population[key] as number;
318
+ const red = (sumRed[key] as number) / pop;
319
+ const green = (sumGreen[key] as number) / pop;
320
+ const blue = (sumBlue[key] as number) / pop;
321
+ let best = 0;
322
+ let bestDistance = Number.POSITIVE_INFINITY;
323
+ for (let index = 0; index < total; index++) {
324
+ const dr = red - (palette[index * 3] as number);
325
+ const dg = green - (palette[index * 3 + 1] as number);
326
+ const db = blue - (palette[index * 3 + 2] as number);
327
+ const distance = dr * dr + dg * dg + db * db;
328
+ if (distance < bestDistance) {
329
+ bestDistance = distance;
330
+ best = index;
331
+ }
332
+ }
333
+ bucketIndex[key] = best;
334
+ }
335
+ return { palette, bucketIndex };
336
+ }
337
+
338
+ /** Bits a palette of `colors` entries needs, from 1 (GIF tables hold 2 to 256). */
339
+ const tableBitsFor = (colors: number): number =>
340
+ Math.max(1, Math.ceil(Math.log2(colors)));
341
+
342
+ /** A growable list of bytes, so a big image doesn't cost a second copy. */
343
+ class ByteWriter {
344
+ private buffer = new Uint8Array(1024);
345
+ length = 0;
346
+
347
+ push(...bytes: number[]): void {
348
+ this.ensure(bytes.length);
349
+ for (const byte of bytes) {
350
+ this.buffer[this.length++] = byte;
351
+ }
352
+ }
353
+
354
+ u16(value: number): void {
355
+ this.push(value & 255, (value >> 8) & 255);
356
+ }
357
+
358
+ ascii(text: string): void {
359
+ for (let index = 0; index < text.length; index++) {
360
+ this.push(text.charCodeAt(index));
361
+ }
362
+ }
363
+
364
+ bytes(source: Uint8Array): void {
365
+ this.ensure(source.length);
366
+ this.buffer.set(source, this.length);
367
+ this.length += source.length;
368
+ }
369
+
370
+ private ensure(extra: number): void {
371
+ if (this.length + extra <= this.buffer.length) {
372
+ return;
373
+ }
374
+ let size = this.buffer.length;
375
+ while (size < this.length + extra) {
376
+ size *= 2;
377
+ }
378
+ const grown = new Uint8Array(size);
379
+ grown.set(this.buffer.subarray(0, this.length));
380
+ this.buffer = grown;
381
+ }
382
+
383
+ result(): Uint8Array {
384
+ return this.buffer.slice(0, this.length);
385
+ }
386
+ }
387
+
388
+ /** The LZW stream of GIF: variable-width codes, packed low bit first, in 255-byte blocks. */
389
+ function lzwEncode(indices: Uint8Array, minCodeSize: number): Uint8Array {
390
+ const out = new ByteWriter();
391
+ const clear = 1 << minCodeSize;
392
+ const end = clear + 1;
393
+
394
+ let block: number[] = [];
395
+ let bitBuffer = 0;
396
+ let bitCount = 0;
397
+ const flushBlock = () => {
398
+ if (block.length > 0) {
399
+ out.push(block.length, ...block);
400
+ block = [];
401
+ }
402
+ };
403
+ const writeByte = (byte: number) => {
404
+ block.push(byte);
405
+ if (block.length === 255) {
406
+ flushBlock();
407
+ }
408
+ };
409
+ const emit = (code: number, size: number) => {
410
+ bitBuffer |= code << bitCount;
411
+ bitCount += size;
412
+ while (bitCount >= 8) {
413
+ writeByte(bitBuffer & 255);
414
+ bitBuffer >>>= 8;
415
+ bitCount -= 8;
416
+ }
417
+ };
418
+
419
+ // table[(prefix << 8) | next] is the code of that string plus one, 0 for none
420
+ let table = new Int32Array(MAX_CODES << 8);
421
+ let codeSize = minCodeSize + 1;
422
+ let nextCode = end + 1;
423
+
424
+ emit(clear, codeSize);
425
+ let prefix = indices[0] as number;
426
+ for (let at = 1; at < indices.length; at++) {
427
+ const next = indices[at] as number;
428
+ const key = (prefix << 8) | next;
429
+ const known = table[key] as number;
430
+ if (known !== 0) {
431
+ prefix = known - 1;
432
+ continue;
433
+ }
434
+ emit(prefix, codeSize);
435
+ if (nextCode === MAX_CODES) {
436
+ // The table is full: start again
437
+ emit(clear, codeSize);
438
+ table = new Int32Array(MAX_CODES << 8);
439
+ nextCode = end + 1;
440
+ codeSize = minCodeSize + 1;
441
+ } else {
442
+ if (nextCode >= 1 << codeSize) {
443
+ codeSize++;
444
+ }
445
+ table[key] = nextCode + 1;
446
+ nextCode++;
447
+ }
448
+ prefix = next;
449
+ }
450
+ emit(prefix, codeSize);
451
+ emit(end, codeSize);
452
+ if (bitCount > 0) {
453
+ writeByte(bitBuffer & 255);
454
+ }
455
+ flushBlock();
456
+ return out.result();
457
+ }
458
+
459
+ /**
460
+ * An indexed image as a GIF89a file: one frame, a global color table, the
461
+ * transparent index (if any) in a graphic control extension, and LZW data.
462
+ * Throws a RangeError for a size outside 1 to GIF_MAX_DIMENSION, an empty or
463
+ * oversized palette, a transparent index outside it, or indices that don't
464
+ * match the size or point past the palette.
465
+ */
466
+ export function encodeGIF(image: IndexedImage): Uint8Array {
467
+ const { width, height, palette, indices, transparentIndex } = image;
468
+ validateSize(width, height);
469
+ const colors = palette.length / 3;
470
+ if (!Number.isInteger(colors) || colors < 1 || colors > GIF_MAX_COLORS) {
471
+ throw new RangeError(
472
+ `A GIF palette holds 1 to ${GIF_MAX_COLORS} colors, got ${palette.length} bytes`
473
+ );
474
+ }
475
+ if (indices.length !== width * height) {
476
+ throw new RangeError(
477
+ `Expected ${width * height} palette indices for ${width} x ${height}, got ${indices.length}`
478
+ );
479
+ }
480
+ if (
481
+ transparentIndex !== null &&
482
+ !(
483
+ Number.isInteger(transparentIndex) &&
484
+ transparentIndex >= 0 &&
485
+ transparentIndex < colors
486
+ )
487
+ ) {
488
+ throw new RangeError(
489
+ `The transparent index ${transparentIndex} isn't in a palette of ${colors} colors`
490
+ );
491
+ }
492
+ for (let at = 0; at < indices.length; at++) {
493
+ if ((indices[at] as number) >= colors) {
494
+ throw new RangeError(
495
+ `Pixel ${at} points at color ${indices[at]}, past the palette of ${colors}`
496
+ );
497
+ }
498
+ }
499
+
500
+ const tableBits = tableBitsFor(colors);
501
+ const tableSize = 1 << tableBits;
502
+ const minCodeSize = Math.max(2, tableBits);
503
+
504
+ const out = new ByteWriter();
505
+ out.ascii("GIF89a");
506
+ out.u16(width);
507
+ out.u16(height);
508
+ // Global color table present, 8 bits of color resolution, not sorted
509
+ out.push(0x80 | (7 << 4) | (tableBits - 1), 0, 0);
510
+ out.bytes(palette);
511
+ out.bytes(new Uint8Array((tableSize - colors) * 3)); // pad to a power of 2
512
+
513
+ if (transparentIndex !== null) {
514
+ // Graphic control extension: no delay, transparent color flag set
515
+ out.push(0x21, 0xf9, 4, 0x01, 0, 0, transparentIndex, 0);
516
+ }
517
+ out.push(0x2c);
518
+ out.u16(0);
519
+ out.u16(0);
520
+ out.u16(width);
521
+ out.u16(height);
522
+ out.push(0); // no local table, not interlaced
523
+ out.push(minCodeSize);
524
+ out.bytes(lzwEncode(indices, minCodeSize));
525
+ out.push(0); // end of the image data
526
+ out.push(0x3b); // trailer
527
+ return out.result();
528
+ }
529
+
530
+ /** Pixels as a GIF: the palette from `quantizeRGBA`, then `encodeGIF`. */
531
+ export function encodeGIFFromRGBA(
532
+ rgba: ArrayLike<number>,
533
+ width: number,
534
+ height: number
535
+ ): { file: Uint8Array; image: QuantizedImage } {
536
+ const image = quantizeRGBA(rgba, width, height);
537
+ return { file: encodeGIF(image), image };
538
+ }
539
+
540
+ /** An indexed image back to RGBA (see-through pixels get alpha 0). */
541
+ export function indexedToRGBA(image: IndexedImage): Uint8ClampedArray {
542
+ const { palette, indices, transparentIndex } = image;
543
+ const out = new Uint8ClampedArray(indices.length * 4);
544
+ for (let pixel = 0; pixel < indices.length; pixel++) {
545
+ const index = indices[pixel] as number;
546
+ const at = pixel * 4;
547
+ out[at] = palette[index * 3] as number;
548
+ out[at + 1] = palette[index * 3 + 1] as number;
549
+ out[at + 2] = palette[index * 3 + 2] as number;
550
+ out[at + 3] = index === transparentIndex ? 0 : OPAQUE;
551
+ }
552
+ return out;
553
+ }
554
+
555
+ const SIGNATURE = "GIF89a";
556
+
557
+ /**
558
+ * True when `bytes` is a GIF this writer would make: the GIF89a header, a
559
+ * color table that fits the file, one image of the size the header gives with
560
+ * well-formed data blocks, and the trailer. Used to check a file before it is
561
+ * saved, so nothing else is handed out as a GIF.
562
+ */
563
+ export function isGIFFile(bytes: Uint8Array): boolean {
564
+ if (bytes.length < 13 + 6 + 10 + 3) {
565
+ return false;
566
+ }
567
+ for (let index = 0; index < SIGNATURE.length; index++) {
568
+ if (bytes[index] !== SIGNATURE.charCodeAt(index)) {
569
+ return false;
570
+ }
571
+ }
572
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
573
+ const width = view.getUint16(6, true);
574
+ const height = view.getUint16(8, true);
575
+ const packed = bytes[10] as number;
576
+ if (width < 1 || height < 1 || !(packed & 0x80)) {
577
+ return false;
578
+ }
579
+ let at = 13 + 3 * (1 << ((packed & 7) + 1));
580
+ if (bytes.length < at) {
581
+ return false;
582
+ }
583
+
584
+ // The data sub-blocks that follow `at`: a run of length-prefixed blocks
585
+ // ending in a zero. Returns where the run ends, or -1 when it doesn't.
586
+ const skipBlocks = (from: number): number => {
587
+ let position = from;
588
+ while (position < bytes.length) {
589
+ const length = bytes[position] as number;
590
+ position += 1;
591
+ if (length === 0) {
592
+ return position;
593
+ }
594
+ position += length;
595
+ }
596
+ return -1;
597
+ };
598
+
599
+ let images = 0;
600
+ while (at < bytes.length) {
601
+ const marker = bytes[at] as number;
602
+ if (marker === 0x3b) {
603
+ return images === 1 && at === bytes.length - 1;
604
+ }
605
+ if (marker === 0x21) {
606
+ at = skipBlocks(at + 2);
607
+ } else if (marker === 0x2c) {
608
+ if (at + 10 > bytes.length) {
609
+ return false;
610
+ }
611
+ if (
612
+ view.getUint16(at + 5, true) !== width ||
613
+ view.getUint16(at + 7, true) !== height ||
614
+ (bytes[at + 9] as number) & 0x80 // no local color table here
615
+ ) {
616
+ return false;
617
+ }
618
+ const minCodeSize = bytes[at + 10] as number;
619
+ if (minCodeSize < 2 || minCodeSize > 8) {
620
+ return false;
621
+ }
622
+ images += 1;
623
+ at = skipBlocks(at + 11);
624
+ } else {
625
+ return false;
626
+ }
627
+ if (at === -1) {
628
+ return false;
629
+ }
630
+ }
631
+ return false;
632
+ }