jpeg.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. const basedecoder_js_1 = __importDefault(require("./basedecoder.js"));
  7. /* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
  8. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  9. /*
  10. Copyright 2011 notmasteryet
  11. Licensed under the Apache License, Version 2.0 (the "License");
  12. you may not use this file except in compliance with the License.
  13. You may obtain a copy of the License at
  14. http://www.apache.org/licenses/LICENSE-2.0
  15. Unless required by applicable law or agreed to in writing, software
  16. distributed under the License is distributed on an "AS IS" BASIS,
  17. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. See the License for the specific language governing permissions and
  19. limitations under the License.
  20. */
  21. // - The JPEG specification can be found in the ITU CCITT Recommendation T.81
  22. // (www.w3.org/Graphics/JPEG/itu-t81.pdf)
  23. // - The JFIF specification can be found in the JPEG File Interchange Format
  24. // (www.w3.org/Graphics/JPEG/jfif3.pdf)
  25. // - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters
  26. // in PostScript Level 2, Technical Note #5116
  27. // (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)
  28. const dctZigZag = new Int32Array([
  29. 0,
  30. 1, 8,
  31. 16, 9, 2,
  32. 3, 10, 17, 24,
  33. 32, 25, 18, 11, 4,
  34. 5, 12, 19, 26, 33, 40,
  35. 48, 41, 34, 27, 20, 13, 6,
  36. 7, 14, 21, 28, 35, 42, 49, 56,
  37. 57, 50, 43, 36, 29, 22, 15,
  38. 23, 30, 37, 44, 51, 58,
  39. 59, 52, 45, 38, 31,
  40. 39, 46, 53, 60,
  41. 61, 54, 47,
  42. 55, 62,
  43. 63,
  44. ]);
  45. const dctCos1 = 4017; // cos(pi/16)
  46. const dctSin1 = 799; // sin(pi/16)
  47. const dctCos3 = 3406; // cos(3*pi/16)
  48. const dctSin3 = 2276; // sin(3*pi/16)
  49. const dctCos6 = 1567; // cos(6*pi/16)
  50. const dctSin6 = 3784; // sin(6*pi/16)
  51. const dctSqrt2 = 5793; // sqrt(2)
  52. const dctSqrt1d2 = 2896; // sqrt(2) / 2
  53. function buildHuffmanTable(codeLengths, values) {
  54. let k = 0;
  55. const code = [];
  56. let length = 16;
  57. while (length > 0 && !codeLengths[length - 1]) {
  58. --length;
  59. }
  60. code.push({ children: [], index: 0 });
  61. let p = code[0];
  62. let q;
  63. for (let i = 0; i < length; i++) {
  64. for (let j = 0; j < codeLengths[i]; j++) {
  65. p = code.pop();
  66. p.children[p.index] = values[k];
  67. while (p.index > 0) {
  68. p = code.pop();
  69. }
  70. p.index++;
  71. code.push(p);
  72. while (code.length <= i) {
  73. code.push(q = { children: [], index: 0 });
  74. p.children[p.index] = q.children;
  75. p = q;
  76. }
  77. k++;
  78. }
  79. if (i + 1 < length) {
  80. // p here points to last code
  81. code.push(q = { children: [], index: 0 });
  82. p.children[p.index] = q.children;
  83. p = q;
  84. }
  85. }
  86. return code[0].children;
  87. }
  88. function decodeScan(data, initialOffset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive) {
  89. const { mcusPerLine, progressive } = frame;
  90. const startOffset = initialOffset;
  91. let offset = initialOffset;
  92. let bitsData = 0;
  93. let bitsCount = 0;
  94. function readBit() {
  95. if (bitsCount > 0) {
  96. bitsCount--;
  97. return (bitsData >> bitsCount) & 1;
  98. }
  99. bitsData = data[offset++];
  100. if (bitsData === 0xFF) {
  101. const nextByte = data[offset++];
  102. if (nextByte) {
  103. throw new Error(`unexpected marker: ${((bitsData << 8) | nextByte).toString(16)}`);
  104. }
  105. // unstuff 0
  106. }
  107. bitsCount = 7;
  108. return bitsData >>> 7;
  109. }
  110. function decodeHuffman(tree) {
  111. let node = tree;
  112. let bit;
  113. while ((bit = readBit()) !== null) { // eslint-disable-line no-cond-assign
  114. node = node[bit];
  115. if (typeof node === 'number') {
  116. return node;
  117. }
  118. if (typeof node !== 'object') {
  119. throw new Error('invalid huffman sequence');
  120. }
  121. }
  122. return null;
  123. }
  124. function receive(initialLength) {
  125. let length = initialLength;
  126. let n = 0;
  127. while (length > 0) {
  128. const bit = readBit();
  129. if (bit === null) {
  130. return undefined;
  131. }
  132. n = (n << 1) | bit;
  133. --length;
  134. }
  135. return n;
  136. }
  137. function receiveAndExtend(length) {
  138. const n = receive(length);
  139. if (n >= 1 << (length - 1)) {
  140. return n;
  141. }
  142. return n + (-1 << length) + 1;
  143. }
  144. function decodeBaseline(component, zz) {
  145. const t = decodeHuffman(component.huffmanTableDC);
  146. const diff = t === 0 ? 0 : receiveAndExtend(t);
  147. component.pred += diff;
  148. zz[0] = component.pred;
  149. let k = 1;
  150. while (k < 64) {
  151. const rs = decodeHuffman(component.huffmanTableAC);
  152. const s = rs & 15;
  153. const r = rs >> 4;
  154. if (s === 0) {
  155. if (r < 15) {
  156. break;
  157. }
  158. k += 16;
  159. }
  160. else {
  161. k += r;
  162. const z = dctZigZag[k];
  163. zz[z] = receiveAndExtend(s);
  164. k++;
  165. }
  166. }
  167. }
  168. function decodeDCFirst(component, zz) {
  169. const t = decodeHuffman(component.huffmanTableDC);
  170. const diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
  171. component.pred += diff;
  172. zz[0] = component.pred;
  173. }
  174. function decodeDCSuccessive(component, zz) {
  175. zz[0] |= readBit() << successive;
  176. }
  177. let eobrun = 0;
  178. function decodeACFirst(component, zz) {
  179. if (eobrun > 0) {
  180. eobrun--;
  181. return;
  182. }
  183. let k = spectralStart;
  184. const e = spectralEnd;
  185. while (k <= e) {
  186. const rs = decodeHuffman(component.huffmanTableAC);
  187. const s = rs & 15;
  188. const r = rs >> 4;
  189. if (s === 0) {
  190. if (r < 15) {
  191. eobrun = receive(r) + (1 << r) - 1;
  192. break;
  193. }
  194. k += 16;
  195. }
  196. else {
  197. k += r;
  198. const z = dctZigZag[k];
  199. zz[z] = receiveAndExtend(s) * (1 << successive);
  200. k++;
  201. }
  202. }
  203. }
  204. let successiveACState = 0;
  205. let successiveACNextValue;
  206. function decodeACSuccessive(component, zz) {
  207. let k = spectralStart;
  208. const e = spectralEnd;
  209. let r = 0;
  210. while (k <= e) {
  211. const z = dctZigZag[k];
  212. const direction = zz[z] < 0 ? -1 : 1;
  213. switch (successiveACState) {
  214. case 0: { // initial state
  215. const rs = decodeHuffman(component.huffmanTableAC);
  216. const s = rs & 15;
  217. r = rs >> 4;
  218. if (s === 0) {
  219. if (r < 15) {
  220. eobrun = receive(r) + (1 << r);
  221. successiveACState = 4;
  222. }
  223. else {
  224. r = 16;
  225. successiveACState = 1;
  226. }
  227. }
  228. else {
  229. if (s !== 1) {
  230. throw new Error('invalid ACn encoding');
  231. }
  232. successiveACNextValue = receiveAndExtend(s);
  233. successiveACState = r ? 2 : 3;
  234. }
  235. continue; // eslint-disable-line no-continue
  236. }
  237. case 1: // skipping r zero items
  238. case 2:
  239. if (zz[z]) {
  240. zz[z] += (readBit() << successive) * direction;
  241. }
  242. else {
  243. r--;
  244. if (r === 0) {
  245. successiveACState = successiveACState === 2 ? 3 : 0;
  246. }
  247. }
  248. break;
  249. case 3: // set value for a zero item
  250. if (zz[z]) {
  251. zz[z] += (readBit() << successive) * direction;
  252. }
  253. else {
  254. zz[z] = successiveACNextValue << successive;
  255. successiveACState = 0;
  256. }
  257. break;
  258. case 4: // eob
  259. if (zz[z]) {
  260. zz[z] += (readBit() << successive) * direction;
  261. }
  262. break;
  263. default:
  264. break;
  265. }
  266. k++;
  267. }
  268. if (successiveACState === 4) {
  269. eobrun--;
  270. if (eobrun === 0) {
  271. successiveACState = 0;
  272. }
  273. }
  274. }
  275. function decodeMcu(component, decodeFunction, mcu, row, col) {
  276. const mcuRow = (mcu / mcusPerLine) | 0;
  277. const mcuCol = mcu % mcusPerLine;
  278. const blockRow = (mcuRow * component.v) + row;
  279. const blockCol = (mcuCol * component.h) + col;
  280. decodeFunction(component, component.blocks[blockRow][blockCol]);
  281. }
  282. function decodeBlock(component, decodeFunction, mcu) {
  283. const blockRow = (mcu / component.blocksPerLine) | 0;
  284. const blockCol = mcu % component.blocksPerLine;
  285. decodeFunction(component, component.blocks[blockRow][blockCol]);
  286. }
  287. const componentsLength = components.length;
  288. let component;
  289. let i;
  290. let j;
  291. let k;
  292. let n;
  293. let decodeFn;
  294. if (progressive) {
  295. if (spectralStart === 0) {
  296. decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
  297. }
  298. else {
  299. decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
  300. }
  301. }
  302. else {
  303. decodeFn = decodeBaseline;
  304. }
  305. let mcu = 0;
  306. let marker;
  307. let mcuExpected;
  308. if (componentsLength === 1) {
  309. mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
  310. }
  311. else {
  312. mcuExpected = mcusPerLine * frame.mcusPerColumn;
  313. }
  314. const usedResetInterval = resetInterval || mcuExpected;
  315. while (mcu < mcuExpected) {
  316. // reset interval stuff
  317. for (i = 0; i < componentsLength; i++) {
  318. components[i].pred = 0;
  319. }
  320. eobrun = 0;
  321. if (componentsLength === 1) {
  322. component = components[0];
  323. for (n = 0; n < usedResetInterval; n++) {
  324. decodeBlock(component, decodeFn, mcu);
  325. mcu++;
  326. }
  327. }
  328. else {
  329. for (n = 0; n < usedResetInterval; n++) {
  330. for (i = 0; i < componentsLength; i++) {
  331. component = components[i];
  332. const { h, v } = component;
  333. for (j = 0; j < v; j++) {
  334. for (k = 0; k < h; k++) {
  335. decodeMcu(component, decodeFn, mcu, j, k);
  336. }
  337. }
  338. }
  339. mcu++;
  340. // If we've reached our expected MCU's, stop decoding
  341. if (mcu === mcuExpected) {
  342. break;
  343. }
  344. }
  345. }
  346. // find marker
  347. bitsCount = 0;
  348. marker = (data[offset] << 8) | data[offset + 1];
  349. if (marker < 0xFF00) {
  350. throw new Error('marker was not found');
  351. }
  352. if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
  353. offset += 2;
  354. }
  355. else {
  356. break;
  357. }
  358. }
  359. return offset - startOffset;
  360. }
  361. function buildComponentData(frame, component) {
  362. const lines = [];
  363. const { blocksPerLine, blocksPerColumn } = component;
  364. const samplesPerLine = blocksPerLine << 3;
  365. const R = new Int32Array(64);
  366. const r = new Uint8Array(64);
  367. // A port of poppler's IDCT method which in turn is taken from:
  368. // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
  369. // "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
  370. // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
  371. // 988-991.
  372. function quantizeAndInverse(zz, dataOut, dataIn) {
  373. const qt = component.quantizationTable;
  374. let v0;
  375. let v1;
  376. let v2;
  377. let v3;
  378. let v4;
  379. let v5;
  380. let v6;
  381. let v7;
  382. let t;
  383. const p = dataIn;
  384. let i;
  385. // dequant
  386. for (i = 0; i < 64; i++) {
  387. p[i] = zz[i] * qt[i];
  388. }
  389. // inverse DCT on rows
  390. for (i = 0; i < 8; ++i) {
  391. const row = 8 * i;
  392. // check for all-zero AC coefficients
  393. if (p[1 + row] === 0 && p[2 + row] === 0 && p[3 + row] === 0
  394. && p[4 + row] === 0 && p[5 + row] === 0 && p[6 + row] === 0
  395. && p[7 + row] === 0) {
  396. t = ((dctSqrt2 * p[0 + row]) + 512) >> 10;
  397. p[0 + row] = t;
  398. p[1 + row] = t;
  399. p[2 + row] = t;
  400. p[3 + row] = t;
  401. p[4 + row] = t;
  402. p[5 + row] = t;
  403. p[6 + row] = t;
  404. p[7 + row] = t;
  405. continue; // eslint-disable-line no-continue
  406. }
  407. // stage 4
  408. v0 = ((dctSqrt2 * p[0 + row]) + 128) >> 8;
  409. v1 = ((dctSqrt2 * p[4 + row]) + 128) >> 8;
  410. v2 = p[2 + row];
  411. v3 = p[6 + row];
  412. v4 = ((dctSqrt1d2 * (p[1 + row] - p[7 + row])) + 128) >> 8;
  413. v7 = ((dctSqrt1d2 * (p[1 + row] + p[7 + row])) + 128) >> 8;
  414. v5 = p[3 + row] << 4;
  415. v6 = p[5 + row] << 4;
  416. // stage 3
  417. t = (v0 - v1 + 1) >> 1;
  418. v0 = (v0 + v1 + 1) >> 1;
  419. v1 = t;
  420. t = ((v2 * dctSin6) + (v3 * dctCos6) + 128) >> 8;
  421. v2 = ((v2 * dctCos6) - (v3 * dctSin6) + 128) >> 8;
  422. v3 = t;
  423. t = (v4 - v6 + 1) >> 1;
  424. v4 = (v4 + v6 + 1) >> 1;
  425. v6 = t;
  426. t = (v7 + v5 + 1) >> 1;
  427. v5 = (v7 - v5 + 1) >> 1;
  428. v7 = t;
  429. // stage 2
  430. t = (v0 - v3 + 1) >> 1;
  431. v0 = (v0 + v3 + 1) >> 1;
  432. v3 = t;
  433. t = (v1 - v2 + 1) >> 1;
  434. v1 = (v1 + v2 + 1) >> 1;
  435. v2 = t;
  436. t = ((v4 * dctSin3) + (v7 * dctCos3) + 2048) >> 12;
  437. v4 = ((v4 * dctCos3) - (v7 * dctSin3) + 2048) >> 12;
  438. v7 = t;
  439. t = ((v5 * dctSin1) + (v6 * dctCos1) + 2048) >> 12;
  440. v5 = ((v5 * dctCos1) - (v6 * dctSin1) + 2048) >> 12;
  441. v6 = t;
  442. // stage 1
  443. p[0 + row] = v0 + v7;
  444. p[7 + row] = v0 - v7;
  445. p[1 + row] = v1 + v6;
  446. p[6 + row] = v1 - v6;
  447. p[2 + row] = v2 + v5;
  448. p[5 + row] = v2 - v5;
  449. p[3 + row] = v3 + v4;
  450. p[4 + row] = v3 - v4;
  451. }
  452. // inverse DCT on columns
  453. for (i = 0; i < 8; ++i) {
  454. const col = i;
  455. // check for all-zero AC coefficients
  456. if (p[(1 * 8) + col] === 0 && p[(2 * 8) + col] === 0 && p[(3 * 8) + col] === 0
  457. && p[(4 * 8) + col] === 0 && p[(5 * 8) + col] === 0 && p[(6 * 8) + col] === 0
  458. && p[(7 * 8) + col] === 0) {
  459. t = ((dctSqrt2 * dataIn[i + 0]) + 8192) >> 14;
  460. p[(0 * 8) + col] = t;
  461. p[(1 * 8) + col] = t;
  462. p[(2 * 8) + col] = t;
  463. p[(3 * 8) + col] = t;
  464. p[(4 * 8) + col] = t;
  465. p[(5 * 8) + col] = t;
  466. p[(6 * 8) + col] = t;
  467. p[(7 * 8) + col] = t;
  468. continue; // eslint-disable-line no-continue
  469. }
  470. // stage 4
  471. v0 = ((dctSqrt2 * p[(0 * 8) + col]) + 2048) >> 12;
  472. v1 = ((dctSqrt2 * p[(4 * 8) + col]) + 2048) >> 12;
  473. v2 = p[(2 * 8) + col];
  474. v3 = p[(6 * 8) + col];
  475. v4 = ((dctSqrt1d2 * (p[(1 * 8) + col] - p[(7 * 8) + col])) + 2048) >> 12;
  476. v7 = ((dctSqrt1d2 * (p[(1 * 8) + col] + p[(7 * 8) + col])) + 2048) >> 12;
  477. v5 = p[(3 * 8) + col];
  478. v6 = p[(5 * 8) + col];
  479. // stage 3
  480. t = (v0 - v1 + 1) >> 1;
  481. v0 = (v0 + v1 + 1) >> 1;
  482. v1 = t;
  483. t = ((v2 * dctSin6) + (v3 * dctCos6) + 2048) >> 12;
  484. v2 = ((v2 * dctCos6) - (v3 * dctSin6) + 2048) >> 12;
  485. v3 = t;
  486. t = (v4 - v6 + 1) >> 1;
  487. v4 = (v4 + v6 + 1) >> 1;
  488. v6 = t;
  489. t = (v7 + v5 + 1) >> 1;
  490. v5 = (v7 - v5 + 1) >> 1;
  491. v7 = t;
  492. // stage 2
  493. t = (v0 - v3 + 1) >> 1;
  494. v0 = (v0 + v3 + 1) >> 1;
  495. v3 = t;
  496. t = (v1 - v2 + 1) >> 1;
  497. v1 = (v1 + v2 + 1) >> 1;
  498. v2 = t;
  499. t = ((v4 * dctSin3) + (v7 * dctCos3) + 2048) >> 12;
  500. v4 = ((v4 * dctCos3) - (v7 * dctSin3) + 2048) >> 12;
  501. v7 = t;
  502. t = ((v5 * dctSin1) + (v6 * dctCos1) + 2048) >> 12;
  503. v5 = ((v5 * dctCos1) - (v6 * dctSin1) + 2048) >> 12;
  504. v6 = t;
  505. // stage 1
  506. p[(0 * 8) + col] = v0 + v7;
  507. p[(7 * 8) + col] = v0 - v7;
  508. p[(1 * 8) + col] = v1 + v6;
  509. p[(6 * 8) + col] = v1 - v6;
  510. p[(2 * 8) + col] = v2 + v5;
  511. p[(5 * 8) + col] = v2 - v5;
  512. p[(3 * 8) + col] = v3 + v4;
  513. p[(4 * 8) + col] = v3 - v4;
  514. }
  515. // convert to 8-bit integers
  516. for (i = 0; i < 64; ++i) {
  517. const sample = 128 + ((p[i] + 8) >> 4);
  518. if (sample < 0) {
  519. dataOut[i] = 0;
  520. }
  521. else if (sample > 0XFF) {
  522. dataOut[i] = 0xFF;
  523. }
  524. else {
  525. dataOut[i] = sample;
  526. }
  527. }
  528. }
  529. for (let blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
  530. const scanLine = blockRow << 3;
  531. for (let i = 0; i < 8; i++) {
  532. lines.push(new Uint8Array(samplesPerLine));
  533. }
  534. for (let blockCol = 0; blockCol < blocksPerLine; blockCol++) {
  535. quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
  536. let offset = 0;
  537. const sample = blockCol << 3;
  538. for (let j = 0; j < 8; j++) {
  539. const line = lines[scanLine + j];
  540. for (let i = 0; i < 8; i++) {
  541. line[sample + i] = r[offset++];
  542. }
  543. }
  544. }
  545. }
  546. return lines;
  547. }
  548. class JpegStreamReader {
  549. constructor() {
  550. this.jfif = null;
  551. this.adobe = null;
  552. this.quantizationTables = [];
  553. this.huffmanTablesAC = [];
  554. this.huffmanTablesDC = [];
  555. this.resetFrames();
  556. }
  557. resetFrames() {
  558. this.frames = [];
  559. }
  560. parse(data) {
  561. let offset = 0;
  562. // const { length } = data;
  563. function readUint16() {
  564. const value = (data[offset] << 8) | data[offset + 1];
  565. offset += 2;
  566. return value;
  567. }
  568. function readDataBlock() {
  569. const length = readUint16();
  570. const array = data.subarray(offset, offset + length - 2);
  571. offset += array.length;
  572. return array;
  573. }
  574. function prepareComponents(frame) {
  575. let maxH = 0;
  576. let maxV = 0;
  577. let component;
  578. let componentId;
  579. for (componentId in frame.components) {
  580. if (frame.components.hasOwnProperty(componentId)) {
  581. component = frame.components[componentId];
  582. if (maxH < component.h) {
  583. maxH = component.h;
  584. }
  585. if (maxV < component.v) {
  586. maxV = component.v;
  587. }
  588. }
  589. }
  590. const mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
  591. const mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
  592. for (componentId in frame.components) {
  593. if (frame.components.hasOwnProperty(componentId)) {
  594. component = frame.components[componentId];
  595. const blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
  596. const blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
  597. const blocksPerLineForMcu = mcusPerLine * component.h;
  598. const blocksPerColumnForMcu = mcusPerColumn * component.v;
  599. const blocks = [];
  600. for (let i = 0; i < blocksPerColumnForMcu; i++) {
  601. const row = [];
  602. for (let j = 0; j < blocksPerLineForMcu; j++) {
  603. row.push(new Int32Array(64));
  604. }
  605. blocks.push(row);
  606. }
  607. component.blocksPerLine = blocksPerLine;
  608. component.blocksPerColumn = blocksPerColumn;
  609. component.blocks = blocks;
  610. }
  611. }
  612. frame.maxH = maxH;
  613. frame.maxV = maxV;
  614. frame.mcusPerLine = mcusPerLine;
  615. frame.mcusPerColumn = mcusPerColumn;
  616. }
  617. let fileMarker = readUint16();
  618. if (fileMarker !== 0xFFD8) { // SOI (Start of Image)
  619. throw new Error('SOI not found');
  620. }
  621. fileMarker = readUint16();
  622. while (fileMarker !== 0xFFD9) { // EOI (End of image)
  623. switch (fileMarker) {
  624. case 0xFF00: break;
  625. case 0xFFE0: // APP0 (Application Specific)
  626. case 0xFFE1: // APP1
  627. case 0xFFE2: // APP2
  628. case 0xFFE3: // APP3
  629. case 0xFFE4: // APP4
  630. case 0xFFE5: // APP5
  631. case 0xFFE6: // APP6
  632. case 0xFFE7: // APP7
  633. case 0xFFE8: // APP8
  634. case 0xFFE9: // APP9
  635. case 0xFFEA: // APP10
  636. case 0xFFEB: // APP11
  637. case 0xFFEC: // APP12
  638. case 0xFFED: // APP13
  639. case 0xFFEE: // APP14
  640. case 0xFFEF: // APP15
  641. case 0xFFFE: { // COM (Comment)
  642. const appData = readDataBlock();
  643. if (fileMarker === 0xFFE0) {
  644. if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49
  645. && appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
  646. this.jfif = {
  647. version: { major: appData[5], minor: appData[6] },
  648. densityUnits: appData[7],
  649. xDensity: (appData[8] << 8) | appData[9],
  650. yDensity: (appData[10] << 8) | appData[11],
  651. thumbWidth: appData[12],
  652. thumbHeight: appData[13],
  653. thumbData: appData.subarray(14, 14 + (3 * appData[12] * appData[13])),
  654. };
  655. }
  656. }
  657. // TODO APP1 - Exif
  658. if (fileMarker === 0xFFEE) {
  659. if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F
  660. && appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
  661. this.adobe = {
  662. version: appData[6],
  663. flags0: (appData[7] << 8) | appData[8],
  664. flags1: (appData[9] << 8) | appData[10],
  665. transformCode: appData[11],
  666. };
  667. }
  668. }
  669. break;
  670. }
  671. case 0xFFDB: { // DQT (Define Quantization Tables)
  672. const quantizationTablesLength = readUint16();
  673. const quantizationTablesEnd = quantizationTablesLength + offset - 2;
  674. while (offset < quantizationTablesEnd) {
  675. const quantizationTableSpec = data[offset++];
  676. const tableData = new Int32Array(64);
  677. if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
  678. for (let j = 0; j < 64; j++) {
  679. const z = dctZigZag[j];
  680. tableData[z] = data[offset++];
  681. }
  682. }
  683. else if ((quantizationTableSpec >> 4) === 1) { // 16 bit
  684. for (let j = 0; j < 64; j++) {
  685. const z = dctZigZag[j];
  686. tableData[z] = readUint16();
  687. }
  688. }
  689. else {
  690. throw new Error('DQT: invalid table spec');
  691. }
  692. this.quantizationTables[quantizationTableSpec & 15] = tableData;
  693. }
  694. break;
  695. }
  696. case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
  697. case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
  698. case 0xFFC2: { // SOF2 (Start of Frame, Progressive DCT)
  699. readUint16(); // skip data length
  700. const frame = {
  701. extended: (fileMarker === 0xFFC1),
  702. progressive: (fileMarker === 0xFFC2),
  703. precision: data[offset++],
  704. scanLines: readUint16(),
  705. samplesPerLine: readUint16(),
  706. components: {},
  707. componentsOrder: [],
  708. };
  709. const componentsCount = data[offset++];
  710. let componentId;
  711. // let maxH = 0;
  712. // let maxV = 0;
  713. for (let i = 0; i < componentsCount; i++) {
  714. componentId = data[offset];
  715. const h = data[offset + 1] >> 4;
  716. const v = data[offset + 1] & 15;
  717. const qId = data[offset + 2];
  718. frame.componentsOrder.push(componentId);
  719. frame.components[componentId] = {
  720. h,
  721. v,
  722. quantizationIdx: qId,
  723. };
  724. offset += 3;
  725. }
  726. prepareComponents(frame);
  727. this.frames.push(frame);
  728. break;
  729. }
  730. case 0xFFC4: { // DHT (Define Huffman Tables)
  731. const huffmanLength = readUint16();
  732. for (let i = 2; i < huffmanLength;) {
  733. const huffmanTableSpec = data[offset++];
  734. const codeLengths = new Uint8Array(16);
  735. let codeLengthSum = 0;
  736. for (let j = 0; j < 16; j++, offset++) {
  737. codeLengths[j] = data[offset];
  738. codeLengthSum += codeLengths[j];
  739. }
  740. const huffmanValues = new Uint8Array(codeLengthSum);
  741. for (let j = 0; j < codeLengthSum; j++, offset++) {
  742. huffmanValues[j] = data[offset];
  743. }
  744. i += 17 + codeLengthSum;
  745. if ((huffmanTableSpec >> 4) === 0) {
  746. this.huffmanTablesDC[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues);
  747. }
  748. else {
  749. this.huffmanTablesAC[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues);
  750. }
  751. }
  752. break;
  753. }
  754. case 0xFFDD: // DRI (Define Restart Interval)
  755. readUint16(); // skip data length
  756. this.resetInterval = readUint16();
  757. break;
  758. case 0xFFDA: { // SOS (Start of Scan)
  759. readUint16(); // skip length
  760. const selectorsCount = data[offset++];
  761. const components = [];
  762. const frame = this.frames[0];
  763. for (let i = 0; i < selectorsCount; i++) {
  764. const component = frame.components[data[offset++]];
  765. const tableSpec = data[offset++];
  766. component.huffmanTableDC = this.huffmanTablesDC[tableSpec >> 4];
  767. component.huffmanTableAC = this.huffmanTablesAC[tableSpec & 15];
  768. components.push(component);
  769. }
  770. const spectralStart = data[offset++];
  771. const spectralEnd = data[offset++];
  772. const successiveApproximation = data[offset++];
  773. const processed = decodeScan(data, offset, frame, components, this.resetInterval, spectralStart, spectralEnd, successiveApproximation >> 4, successiveApproximation & 15);
  774. offset += processed;
  775. break;
  776. }
  777. case 0xFFFF: // Fill bytes
  778. if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
  779. offset--;
  780. }
  781. break;
  782. default:
  783. if (data[offset - 3] === 0xFF
  784. && data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
  785. // could be incorrect encoding -- last 0xFF byte of the previous
  786. // block was eaten by the encoder
  787. offset -= 3;
  788. break;
  789. }
  790. throw new Error(`unknown JPEG marker ${fileMarker.toString(16)}`);
  791. }
  792. fileMarker = readUint16();
  793. }
  794. }
  795. getResult() {
  796. const { frames } = this;
  797. if (this.frames.length === 0) {
  798. throw new Error('no frames were decoded');
  799. }
  800. else if (this.frames.length > 1) {
  801. console.warn('more than one frame is not supported');
  802. }
  803. // set each frame's components quantization table
  804. for (let i = 0; i < this.frames.length; i++) {
  805. const cp = this.frames[i].components;
  806. for (const j of Object.keys(cp)) {
  807. cp[j].quantizationTable = this.quantizationTables[cp[j].quantizationIdx];
  808. delete cp[j].quantizationIdx;
  809. }
  810. }
  811. const frame = frames[0];
  812. const { components, componentsOrder } = frame;
  813. const outComponents = [];
  814. const width = frame.samplesPerLine;
  815. const height = frame.scanLines;
  816. for (let i = 0; i < componentsOrder.length; i++) {
  817. const component = components[componentsOrder[i]];
  818. outComponents.push({
  819. lines: buildComponentData(frame, component),
  820. scaleX: component.h / frame.maxH,
  821. scaleY: component.v / frame.maxV,
  822. });
  823. }
  824. const out = new Uint8Array(width * height * outComponents.length);
  825. let oi = 0;
  826. for (let y = 0; y < height; ++y) {
  827. for (let x = 0; x < width; ++x) {
  828. for (let i = 0; i < outComponents.length; ++i) {
  829. const component = outComponents[i];
  830. out[oi] = component.lines[0 | y * component.scaleY][0 | x * component.scaleX];
  831. ++oi;
  832. }
  833. }
  834. }
  835. return out;
  836. }
  837. }
  838. class JpegDecoder extends basedecoder_js_1.default {
  839. constructor(fileDirectory) {
  840. super();
  841. this.reader = new JpegStreamReader();
  842. if (fileDirectory.JPEGTables) {
  843. this.reader.parse(fileDirectory.JPEGTables);
  844. }
  845. }
  846. decodeBlock(buffer) {
  847. this.reader.resetFrames();
  848. this.reader.parse(new Uint8Array(buffer));
  849. return this.reader.getResult().buffer;
  850. }
  851. }
  852. exports.default = JpegDecoder;
  853. //# sourceMappingURL=jpeg.js.map