decoder.js 35 KB

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