jpeg.js 26 KB

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