JPGLoader.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. /*
  2. * Copyright (c) 2020, The SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Bitmap.h>
  27. #include <AK/BufferStream.h>
  28. #include <AK/ByteBuffer.h>
  29. #include <AK/LexicalPath.h>
  30. #include <AK/MappedFile.h>
  31. #include <AK/String.h>
  32. #include <AK/Vector.h>
  33. #include <LibGfx/Bitmap.h>
  34. #include <LibGfx/JPGLoader.h>
  35. #include <Libraries/LibM/math.h>
  36. #define JPG_DBG 0
  37. #define jpg_dbg(x) \
  38. if (JPG_DBG) \
  39. dbg() << x
  40. #define JPG_INVALID 0X0000
  41. #define JPG_APPN0 0XFFE0
  42. #define JPG_APPN1 0XFFE1
  43. #define JPG_APPN2 0XFFE2
  44. #define JPG_APPN3 0XFFE3
  45. #define JPG_APPN4 0XFFE4
  46. #define JPG_APPN5 0XFFE5
  47. #define JPG_APPN6 0XFFE6
  48. #define JPG_APPN7 0XFFE7
  49. #define JPG_APPN8 0XFFE8
  50. #define JPG_APPN9 0XFFE9
  51. #define JPG_APPNA 0XFFEA
  52. #define JPG_APPNB 0XFFEB
  53. #define JPG_APPNC 0XFFEC
  54. #define JPG_APPND 0XFFED
  55. #define JPG_APPNE 0xFFEE
  56. #define JPG_APPNF 0xFFEF
  57. #define JPG_RESERVED1 0xFFF1
  58. #define JPG_RESERVED2 0xFFF2
  59. #define JPG_RESERVED3 0xFFF3
  60. #define JPG_RESERVED4 0xFFF4
  61. #define JPG_RESERVED5 0xFFF5
  62. #define JPG_RESERVED6 0xFFF6
  63. #define JPG_RESERVED7 0xFFF7
  64. #define JPG_RESERVED8 0xFFF8
  65. #define JPG_RESERVED9 0xFFF9
  66. #define JPG_RESERVEDA 0xFFFA
  67. #define JPG_RESERVEDB 0xFFFB
  68. #define JPG_RESERVEDC 0xFFFC
  69. #define JPG_RESERVEDD 0xFFFD
  70. #define JPG_RST0 0xFFD0
  71. #define JPG_RST1 0xFFD1
  72. #define JPG_RST2 0xFFD2
  73. #define JPG_RST3 0xFFD3
  74. #define JPG_RST4 0xFFD4
  75. #define JPG_RST5 0xFFD5
  76. #define JPG_RST6 0xFFD6
  77. #define JPG_RST7 0xFFD7
  78. #define JPG_DHP 0xFFDE
  79. #define JPG_EXP 0xFFDF
  80. #define JPG_DHT 0XFFC4
  81. #define JPG_DQT 0XFFDB
  82. #define JPG_EOI 0xFFD9
  83. #define JPG_RST 0XFFDD
  84. #define JPG_SOF0 0XFFC0
  85. #define JPG_SOF2 0xFFC2
  86. #define JPG_SOI 0XFFD8
  87. #define JPG_SOS 0XFFDA
  88. #define JPG_COM 0xFFFE
  89. namespace Gfx {
  90. constexpr static u8 zigzag_map[64] {
  91. 0, 1, 8, 16, 9, 2, 3, 10,
  92. 17, 24, 32, 25, 18, 11, 4, 5,
  93. 12, 19, 26, 33, 40, 48, 41, 34,
  94. 27, 20, 13, 6, 7, 14, 21, 28,
  95. 35, 42, 49, 56, 57, 50, 43, 36,
  96. 29, 22, 15, 23, 30, 37, 44, 51,
  97. 58, 59, 52, 45, 38, 31, 39, 46,
  98. 53, 60, 61, 54, 47, 55, 62, 63
  99. };
  100. using Marker = u16;
  101. /**
  102. * MCU means group of data units that are coded together. A data unit is an 8x8
  103. * block of component data. In interleaved scans, number of non-interleaved data
  104. * units of a component C is Ch * Cv, where Ch and Cv represent the horizontal &
  105. * vertical subsampling factors of the component, respectively. A MacroBlock is
  106. * an 8x8 block of RGB values before encoding, and 8x8 block of YCbCr values when
  107. * we're done decoding the huffman stream.
  108. */
  109. struct Macroblock {
  110. union {
  111. i32 y[64] = { 0 };
  112. i32 r[64];
  113. };
  114. union {
  115. i32 cb[64] = { 0 };
  116. i32 g[64];
  117. };
  118. union {
  119. i32 cr[64] = { 0 };
  120. i32 b[64];
  121. };
  122. };
  123. struct MacroblockMeta {
  124. u32 total { 0 };
  125. u32 padded_total { 0 };
  126. u32 hcount { 0 };
  127. u32 vcount { 0 };
  128. u32 hpadded_count { 0 };
  129. u32 vpadded_count { 0 };
  130. };
  131. struct ComponentSpec {
  132. i8 id { -1 };
  133. u8 hsample_factor { 1 }; // Horizontal sampling factor.
  134. u8 vsample_factor { 1 }; // Vertical sampling factor.
  135. u8 ac_destination_id { 0 };
  136. u8 dc_destination_id { 0 };
  137. u8 qtable_id { 0 }; // Quantization table id.
  138. };
  139. struct StartOfFrame {
  140. // Of these, only the first 3 are in mainstream use, and refers to SOF0-2.
  141. enum class FrameType {
  142. Baseline_DCT = 0,
  143. Extended_Sequential_DCT = 1,
  144. Progressive_DCT = 2,
  145. Sequential_Lossless = 3,
  146. Differential_Sequential_DCT = 5,
  147. Differential_Progressive_DCT = 6,
  148. Differential_Sequential_Lossless = 7,
  149. Extended_Sequential_DCT_Arithmetic = 9,
  150. Progressive_DCT_Arithmetic = 10,
  151. Sequential_Lossless_Arithmetic = 11,
  152. Differential_Sequential_DCT_Arithmetic = 13,
  153. Differential_Progressive_DCT_Arithmetic = 14,
  154. Differential_Sequential_Lossless_Arithmetic = 15,
  155. };
  156. FrameType type { FrameType::Baseline_DCT };
  157. u8 precision { 0 };
  158. u16 height { 0 };
  159. u16 width { 0 };
  160. };
  161. struct HuffmanTableSpec {
  162. u8 type { 0 };
  163. u8 destination_id { 0 };
  164. u8 code_counts[16] = { 0 };
  165. Vector<u8> symbols;
  166. Vector<u16> codes;
  167. };
  168. struct HuffmanStreamState {
  169. Vector<u8> stream;
  170. u8 bit_offset { 0 };
  171. size_t byte_offset { 0 };
  172. };
  173. struct JPGLoadingContext {
  174. enum State {
  175. NotDecoded = 0,
  176. Error,
  177. FrameDecoded,
  178. BitmapDecoded
  179. };
  180. State state { State::NotDecoded };
  181. const u8* data { nullptr };
  182. size_t data_size { 0 };
  183. u32 luma_table[64] = { 0 };
  184. u32 chroma_table[64] = { 0 };
  185. StartOfFrame frame;
  186. u8 hsample_factor { 0 };
  187. u8 vsample_factor { 0 };
  188. bool has_zero_based_ids { false };
  189. u8 component_count { 0 };
  190. ComponentSpec components[3];
  191. RefPtr<Gfx::Bitmap> bitmap;
  192. u16 dc_reset_interval { 0 };
  193. Vector<HuffmanTableSpec> dc_tables;
  194. Vector<HuffmanTableSpec> ac_tables;
  195. HuffmanStreamState huffman_stream;
  196. i32 previous_dc_values[3] = { 0 };
  197. MacroblockMeta mblock_meta;
  198. };
  199. void generate_huffman_codes(HuffmanTableSpec& table)
  200. {
  201. unsigned code = 0;
  202. for (auto number_of_codes : table.code_counts) {
  203. for (int i = 0; i < number_of_codes; i++)
  204. table.codes.append(code++);
  205. code <<= 1;
  206. }
  207. }
  208. Optional<size_t> read_huffman_bits(HuffmanStreamState& hstream, size_t count = 1)
  209. {
  210. if (count > (8 * sizeof(size_t))) {
  211. dbg() << String::format("Can't read %i bits at once!", count);
  212. return {};
  213. }
  214. size_t value = 0;
  215. while (count--) {
  216. if (hstream.byte_offset >= hstream.stream.size()) {
  217. dbg() << String::format("Huffman stream exhausted. This could be an error!");
  218. return {};
  219. }
  220. u8 current_byte = hstream.stream[hstream.byte_offset];
  221. u8 current_bit = 1u & (u32)(current_byte >> (7 - hstream.bit_offset)); // MSB first.
  222. hstream.bit_offset++;
  223. value = (value << 1) | (size_t)current_bit;
  224. if (hstream.bit_offset == 8) {
  225. hstream.byte_offset++;
  226. hstream.bit_offset = 0;
  227. }
  228. }
  229. return value;
  230. }
  231. Optional<u8> get_next_symbol(HuffmanStreamState& hstream, const HuffmanTableSpec& table)
  232. {
  233. unsigned code = 0;
  234. size_t code_cursor = 0;
  235. for (int i = 0; i < 16; i++) { // Codes can't be longer than 16 bits.
  236. auto result = read_huffman_bits(hstream);
  237. if (!result.has_value())
  238. return {};
  239. code = (code << 1) | (i32)result.release_value();
  240. for (int j = 0; j < table.code_counts[i]; j++) {
  241. if (code == table.codes[code_cursor])
  242. return table.symbols[code_cursor];
  243. code_cursor++;
  244. }
  245. }
  246. dbg() << "If you're seeing this...the jpeg decoder needs to support more kinds of JPEGs!";
  247. return {};
  248. }
  249. /**
  250. * Build the macroblocks possible by reading single (MCU) subsampled pair of CbCr.
  251. * Depending on the sampling factors, we may not see triples of y, cb, cr in that
  252. * order. If sample factors differ from one, we'll read more than one block of y-
  253. * coefficients before we get to read a cb-cr block.
  254. * In the function below, `hcursor` and `vcursor` denote the location of the block
  255. * we're building in the macroblock matrix. `vfactor_i` and `hfactor_i` are cursors
  256. * that iterate over the vertical and horizontal subsampling factors, respectively.
  257. * When we finish one iteration of the innermost loop, we'll have the coefficients
  258. * of one of the components of block at position `mb_index`. When the outermost loop
  259. * finishes first iteration, we'll have all the luminance coefficients for all the
  260. * macroblocks that share the chrominance data. Next two iterations (assuming that
  261. * we are dealing with three components) will fill up the blocks with chroma data.
  262. */
  263. bool build_macroblocks(JPGLoadingContext& context, Vector<Macroblock>& macroblocks, u8 hcursor, u8 vcursor)
  264. {
  265. for (u32 cindex = 0; cindex < context.component_count; cindex++) {
  266. auto& component = context.components[cindex];
  267. for (u8 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) {
  268. for (u8 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) {
  269. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  270. Macroblock& block = macroblocks[mb_index];
  271. auto& dc_table = context.dc_tables[component.dc_destination_id];
  272. auto& ac_table = context.ac_tables[component.ac_destination_id];
  273. auto symbol_or_error = get_next_symbol(context.huffman_stream, dc_table);
  274. if (!symbol_or_error.has_value())
  275. return false;
  276. // For DC coefficients, symbol encodes the length of the coefficient.
  277. auto dc_length = symbol_or_error.release_value();
  278. if (dc_length > 11) {
  279. dbg() << String::format("DC coefficient too long: %i!", dc_length);
  280. return false;
  281. }
  282. auto coeff_or_error = read_huffman_bits(context.huffman_stream, dc_length);
  283. if (!coeff_or_error.has_value())
  284. return false;
  285. // DC coefficients are encoded as the difference between previous and current DC values.
  286. i32 dc_diff = coeff_or_error.release_value();
  287. // If MSB in diff is 0, the difference is -ve. Otherwise +ve.
  288. if (dc_length != 0 && dc_diff < (1 << (dc_length - 1)))
  289. dc_diff -= (1 << dc_length) - 1;
  290. i32* select_component = component.id == 1 ? block.y : (component.id == 2 ? block.cb : block.cr);
  291. auto& previous_dc = context.previous_dc_values[cindex];
  292. select_component[0] = previous_dc += dc_diff;
  293. // Compute the AC coefficients.
  294. for (int j = 1; j < 64;) {
  295. symbol_or_error = get_next_symbol(context.huffman_stream, ac_table);
  296. if (!symbol_or_error.has_value())
  297. return false;
  298. // AC symbols encode 2 pieces of information, the high 4 bits represent
  299. // number of zeroes to be stuffed before reading the coefficient. Low 4
  300. // bits represent the magnitude of the coefficient.
  301. auto ac_symbol = symbol_or_error.release_value();
  302. if (ac_symbol == 0)
  303. break;
  304. // ac_symbol = 0xF0 means we need to skip 16 zeroes.
  305. u8 run_length = ac_symbol == 0xF0 ? 16 : ac_symbol >> 4;
  306. j += run_length;
  307. if (j >= 64) {
  308. dbg() << String::format("Run-length exceeded boundaries. Cursor: %i, Skipping: %i!", j, run_length);
  309. return false;
  310. }
  311. u8 coeff_length = ac_symbol & 0x0F;
  312. if (coeff_length > 10) {
  313. dbg() << String::format("AC coefficient too long: %i!", coeff_length);
  314. return false;
  315. }
  316. if (coeff_length != 0) {
  317. coeff_or_error = read_huffman_bits(context.huffman_stream, coeff_length);
  318. if (!coeff_or_error.has_value())
  319. return false;
  320. i32 ac_coefficient = coeff_or_error.release_value();
  321. if (ac_coefficient < (1 << (coeff_length - 1)))
  322. ac_coefficient -= (1 << coeff_length) - 1;
  323. select_component[zigzag_map[j++]] = ac_coefficient;
  324. }
  325. }
  326. }
  327. }
  328. }
  329. return true;
  330. }
  331. Optional<Vector<Macroblock>> decode_huffman_stream(JPGLoadingContext& context)
  332. {
  333. Vector<Macroblock> macroblocks;
  334. macroblocks.resize(context.mblock_meta.padded_total);
  335. jpg_dbg("Image width: " << context.frame.width);
  336. jpg_dbg("Image height: " << context.frame.height);
  337. jpg_dbg("Macroblocks in a row: " << context.mblock_meta.hpadded_count);
  338. jpg_dbg("Macroblocks in a column: " << context.mblock_meta.vpadded_count);
  339. // Compute huffman codes for DC and AC tables.
  340. for (auto& dc_table : context.dc_tables)
  341. generate_huffman_codes(dc_table);
  342. for (auto& ac_table : context.ac_tables)
  343. generate_huffman_codes(ac_table);
  344. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  345. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  346. u32 i = vcursor * context.mblock_meta.hpadded_count + hcursor;
  347. if (context.dc_reset_interval > 0) {
  348. if (i % context.dc_reset_interval == 0) {
  349. context.previous_dc_values[0] = 0;
  350. context.previous_dc_values[1] = 0;
  351. context.previous_dc_values[2] = 0;
  352. // Restart markers are stored in byte boundaries. Advance the huffman stream cursor to
  353. // the 0th bit of the next byte.
  354. if (context.huffman_stream.byte_offset < context.huffman_stream.stream.size()) {
  355. if (context.huffman_stream.bit_offset > 0) {
  356. context.huffman_stream.bit_offset = 0;
  357. context.huffman_stream.byte_offset++;
  358. }
  359. // Skip the restart marker (RSTn).
  360. context.huffman_stream.byte_offset++;
  361. }
  362. }
  363. }
  364. if (!build_macroblocks(context, macroblocks, hcursor, vcursor)) {
  365. dbg() << "Failed to build Macroblock " << i;
  366. dbg() << "Huffman stream byte offset " << context.huffman_stream.byte_offset;
  367. dbg() << "Huffman stream bit offset " << context.huffman_stream.bit_offset;
  368. return {};
  369. }
  370. }
  371. }
  372. return macroblocks;
  373. }
  374. static inline bool bounds_okay(const size_t cursor, const size_t delta, const size_t bound)
  375. {
  376. return (delta + cursor) < bound;
  377. }
  378. static inline bool is_valid_marker(const Marker marker)
  379. {
  380. if (marker >= JPG_APPN0 && marker <= JPG_APPNF) {
  381. if (marker != JPG_APPN0)
  382. dbg() << String::format("%04x not supported yet. The decoder may fail!", marker);
  383. return true;
  384. }
  385. if (marker >= JPG_RESERVED1 && marker <= JPG_RESERVEDD)
  386. return true;
  387. if (marker >= JPG_RST0 && marker <= JPG_RST7)
  388. return true;
  389. switch (marker) {
  390. case JPG_COM:
  391. case JPG_DHP:
  392. case JPG_EXP:
  393. case JPG_DHT:
  394. case JPG_DQT:
  395. case JPG_RST:
  396. case JPG_SOF0:
  397. case JPG_SOI:
  398. case JPG_SOS:
  399. return true;
  400. }
  401. if (marker >= 0xFFC0 && marker <= 0xFFCF) {
  402. if (marker != 0xFFC4 && marker != 0xFFC8 && marker != 0xFFCC) {
  403. dbg() << "Decoding this frame-type (SOF" << (marker & 0xf) << ") is not currently supported. Decoder will fail!";
  404. return false;
  405. }
  406. }
  407. return false;
  408. }
  409. static inline u16 read_be_word(BufferStream& stream)
  410. {
  411. u8 tmp1 = 0, tmp2 = 0;
  412. stream >> tmp1 >> tmp2;
  413. return ((u16)tmp1 << 8) | ((u16)tmp2);
  414. }
  415. static inline Marker read_marker_at_cursor(BufferStream& stream)
  416. {
  417. u16 marker = read_be_word(stream);
  418. if (stream.handle_read_failure())
  419. return JPG_INVALID;
  420. if (is_valid_marker(marker))
  421. return marker;
  422. if (marker != 0xFFFF)
  423. return JPG_INVALID;
  424. u8 next;
  425. do {
  426. stream >> next;
  427. if (stream.handle_read_failure() || next == 0x00)
  428. return JPG_INVALID;
  429. } while (next == 0xFF);
  430. marker = 0xFF00 | (u16)next;
  431. return is_valid_marker(marker) ? marker : JPG_INVALID;
  432. }
  433. static bool read_start_of_scan(BufferStream& stream, JPGLoadingContext& context)
  434. {
  435. if (context.state < JPGLoadingContext::State::FrameDecoded) {
  436. dbg() << stream.offset() << ": SOS found before reading a SOF!";
  437. return false;
  438. }
  439. u16 bytes_to_read = read_be_word(stream);
  440. if (stream.handle_read_failure())
  441. return false;
  442. bytes_to_read -= 2;
  443. if (!bounds_okay(stream.offset(), bytes_to_read, context.data_size))
  444. return false;
  445. u8 component_count;
  446. stream >> component_count;
  447. if (stream.handle_read_failure())
  448. return false;
  449. if (component_count != context.component_count) {
  450. dbg() << stream.offset()
  451. << String::format(": Unsupported number of components: %i!", component_count);
  452. return false;
  453. }
  454. for (int i = 0; i < component_count; i++) {
  455. ComponentSpec* component = nullptr;
  456. u8 component_id;
  457. stream >> component_id;
  458. if (stream.handle_read_failure())
  459. return false;
  460. component_id += context.has_zero_based_ids ? 1 : 0;
  461. if (component_id == context.components[0].id)
  462. component = &context.components[0];
  463. else if (component_id == context.components[1].id)
  464. component = &context.components[1];
  465. else if (component_id == context.components[2].id)
  466. component = &context.components[2];
  467. else {
  468. dbg() << stream.offset() << String::format(": Unsupported component id: %i!", component_id);
  469. return false;
  470. }
  471. u8 table_ids;
  472. stream >> table_ids;
  473. if (stream.handle_read_failure())
  474. return false;
  475. component->dc_destination_id = table_ids >> 4;
  476. component->ac_destination_id = table_ids & 0x0F;
  477. }
  478. u8 spectral_selection_start;
  479. stream >> spectral_selection_start;
  480. if (stream.handle_read_failure())
  481. return false;
  482. u8 spectral_selection_end;
  483. stream >> spectral_selection_end;
  484. if (stream.handle_read_failure())
  485. return false;
  486. u8 successive_approximation;
  487. stream >> successive_approximation;
  488. if (stream.handle_read_failure())
  489. return false;
  490. // The three values should be fixed for baseline JPEGs utilizing sequential DCT.
  491. if (spectral_selection_start != 0 || spectral_selection_end != 63 || successive_approximation != 0) {
  492. dbg() << stream.offset() << ": ERROR! Start of Selection: " << spectral_selection_start
  493. << ", End of Selection: " << spectral_selection_end
  494. << ", Successive Approximation: " << successive_approximation << "!";
  495. return false;
  496. }
  497. return true;
  498. }
  499. static bool read_reset_marker(BufferStream& stream, JPGLoadingContext& context)
  500. {
  501. u16 bytes_to_read = read_be_word(stream);
  502. if (stream.handle_read_failure())
  503. return false;
  504. bytes_to_read -= 2;
  505. if (bytes_to_read != 2) {
  506. dbg() << stream.offset() << ": Malformed reset marker found!";
  507. return false;
  508. }
  509. context.dc_reset_interval = read_be_word(stream);
  510. return true;
  511. }
  512. static bool read_huffman_table(BufferStream& stream, JPGLoadingContext& context)
  513. {
  514. i32 bytes_to_read = read_be_word(stream);
  515. if (!bounds_okay(stream.offset(), bytes_to_read, context.data_size))
  516. return false;
  517. bytes_to_read -= 2;
  518. while (bytes_to_read > 0) {
  519. HuffmanTableSpec table;
  520. u8 table_info;
  521. stream >> table_info;
  522. if (stream.handle_read_failure())
  523. return false;
  524. u8 table_type = table_info >> 4;
  525. u8 table_destination_id = table_info & 0x0F;
  526. if (table_type > 1) {
  527. dbg() << stream.offset() << String::format(": Unrecognized huffman table: %i!", table_type);
  528. return false;
  529. }
  530. if (table_destination_id > 3) {
  531. dbg() << stream.offset()
  532. << String::format(": Invalid huffman table destination id: %i!", table_destination_id);
  533. return false;
  534. }
  535. table.type = table_type;
  536. table.destination_id = table_destination_id;
  537. u32 total_codes = 0;
  538. // Read code counts. At each index K, the value represents the number of K+1 bit codes in this header.
  539. for (int i = 0; i < 16; i++) {
  540. u8 count;
  541. stream >> count;
  542. if (stream.handle_read_failure())
  543. return false;
  544. total_codes += count;
  545. table.code_counts[i] = count;
  546. }
  547. table.codes.ensure_capacity(total_codes);
  548. // Read symbols. Read X bytes, where X is the sum of the counts of codes read in the previous step.
  549. for (u32 i = 0; i < total_codes; i++) {
  550. u8 symbol = 0;
  551. stream >> symbol;
  552. table.symbols.append(symbol);
  553. }
  554. if (stream.handle_read_failure())
  555. return false;
  556. if (table_type == 0)
  557. context.dc_tables.append(move(table));
  558. else
  559. context.ac_tables.append(move(table));
  560. bytes_to_read -= 1 + 16 + total_codes;
  561. }
  562. if (bytes_to_read != 0) {
  563. dbg() << stream.offset() << ": Extra bytes detected in huffman header!";
  564. return false;
  565. }
  566. return true;
  567. }
  568. static inline bool validate_luma_and_modify_context(const ComponentSpec& luma, JPGLoadingContext& context)
  569. {
  570. if ((luma.hsample_factor == 1 || luma.hsample_factor == 2) && (luma.vsample_factor == 1 || luma.vsample_factor == 2)) {
  571. context.mblock_meta.hpadded_count += luma.hsample_factor == 1 ? 0 : context.mblock_meta.hcount % 2;
  572. context.mblock_meta.vpadded_count += luma.vsample_factor == 1 ? 0 : context.mblock_meta.vcount % 2;
  573. context.mblock_meta.padded_total = context.mblock_meta.hpadded_count * context.mblock_meta.vpadded_count;
  574. // For easy reference to relevant sample factors.
  575. context.hsample_factor = luma.hsample_factor;
  576. context.vsample_factor = luma.vsample_factor;
  577. jpg_dbg(String::format("Horizontal Subsampling Factor: %i", luma.hsample_factor));
  578. jpg_dbg(String::format("Vertical Subsampling Factor: %i", luma.vsample_factor));
  579. return true;
  580. }
  581. return false;
  582. }
  583. static inline void set_macroblock_metadata(JPGLoadingContext& context)
  584. {
  585. context.mblock_meta.hcount = (context.frame.width + 7) / 8;
  586. context.mblock_meta.vcount = (context.frame.height + 7) / 8;
  587. context.mblock_meta.hpadded_count = context.mblock_meta.hcount;
  588. context.mblock_meta.vpadded_count = context.mblock_meta.vcount;
  589. context.mblock_meta.total = context.mblock_meta.hcount * context.mblock_meta.vcount;
  590. }
  591. static bool read_start_of_frame(BufferStream& stream, JPGLoadingContext& context)
  592. {
  593. if (context.state == JPGLoadingContext::FrameDecoded) {
  594. dbg() << stream.offset() << ": SOF repeated!";
  595. return false;
  596. }
  597. i32 bytes_to_read = read_be_word(stream);
  598. if (stream.handle_read_failure())
  599. return false;
  600. bytes_to_read -= 2;
  601. if (!bounds_okay(stream.offset(), bytes_to_read, context.data_size))
  602. return false;
  603. stream >> context.frame.precision;
  604. if (context.frame.precision != 8) {
  605. dbg() << stream.offset() << ": SOF precision != 8!";
  606. return false;
  607. }
  608. context.frame.height = read_be_word(stream);
  609. context.frame.width = read_be_word(stream);
  610. if (!context.frame.width || !context.frame.height) {
  611. dbg() << stream.offset() << ": ERROR! Image height: " << context.frame.height << ", Image width: "
  612. << context.frame.width << "!";
  613. return false;
  614. }
  615. set_macroblock_metadata(context);
  616. stream >> context.component_count;
  617. if (context.component_count != 1 && context.component_count != 3) {
  618. dbg() << stream.offset() << ": Unsupported number of components in SOF: "
  619. << context.component_count << "!";
  620. return false;
  621. }
  622. for (int i = 0; i < context.component_count; i++) {
  623. ComponentSpec& component = context.components[i];
  624. stream >> component.id;
  625. if (i == 0)
  626. context.has_zero_based_ids = component.id == 0;
  627. component.id += context.has_zero_based_ids ? 1 : 0;
  628. u8 subsample_factors = 0;
  629. stream >> subsample_factors;
  630. if (stream.handle_read_failure())
  631. return false;
  632. component.hsample_factor = subsample_factors >> 4;
  633. component.vsample_factor = subsample_factors & 0x0F;
  634. if (component.id == 1) {
  635. // By convention, downsampling is applied only on chroma components. So we should
  636. // hope to see the maximum sampling factor in the luma component.
  637. if (!validate_luma_and_modify_context(component, context)) {
  638. dbg() << stream.offset() << ": Unsupported luma subsampling factors: "
  639. << "horizontal: " << component.hsample_factor << ", vertical: " << component.vsample_factor;
  640. return false;
  641. }
  642. } else {
  643. if (component.hsample_factor != 1 || component.vsample_factor != 1) {
  644. dbg() << stream.offset() << ": Unsupported chroma subsampling factors: "
  645. << "horizontal: " << component.hsample_factor << ", vertical: " << component.vsample_factor;
  646. return false;
  647. }
  648. }
  649. stream >> component.qtable_id;
  650. if (component.qtable_id > 1) {
  651. dbg() << stream.offset() << ": Unsupported quantization table id: "
  652. << component.qtable_id << "!";
  653. return false;
  654. }
  655. }
  656. return true;
  657. }
  658. static bool read_quantization_table(BufferStream& stream, JPGLoadingContext& context)
  659. {
  660. i32 bytes_to_read = read_be_word(stream);
  661. if (stream.handle_read_failure())
  662. return false;
  663. bytes_to_read -= 2;
  664. if (!bounds_okay(stream.offset(), bytes_to_read, context.data_size))
  665. return false;
  666. while (bytes_to_read > 0) {
  667. u8 info_byte;
  668. stream >> info_byte;
  669. if (stream.handle_read_failure())
  670. return false;
  671. u8 element_unit_hint = info_byte >> 4;
  672. if (element_unit_hint > 1) {
  673. dbg() << stream.offset()
  674. << String::format(": Unsupported unit hint in quantization table: %i!", element_unit_hint);
  675. return false;
  676. }
  677. u8 table_id = info_byte & 0x0F;
  678. if (table_id > 1) {
  679. dbg() << stream.offset() << String::format(": Unsupported quantization table id: %i!", table_id);
  680. return false;
  681. }
  682. u32* table = table_id == 0 ? context.luma_table : context.chroma_table;
  683. for (int i = 0; i < 64; i++) {
  684. if (element_unit_hint == 0) {
  685. u8 tmp = 0;
  686. stream >> tmp;
  687. table[zigzag_map[i]] = tmp;
  688. } else
  689. table[zigzag_map[i]] = read_be_word(stream);
  690. }
  691. if (stream.handle_read_failure())
  692. return false;
  693. bytes_to_read -= 1 + (element_unit_hint == 0 ? 64 : 128);
  694. }
  695. if (bytes_to_read != 0) {
  696. dbg() << stream.offset() << ": Invalid length for one or more quantization tables!";
  697. return false;
  698. }
  699. return true;
  700. }
  701. static bool skip_marker_with_length(BufferStream& stream)
  702. {
  703. u16 bytes_to_skip = read_be_word(stream);
  704. bytes_to_skip -= 2;
  705. if (stream.handle_read_failure())
  706. return false;
  707. stream.advance(bytes_to_skip);
  708. return !stream.handle_read_failure();
  709. }
  710. void dequantize(JPGLoadingContext& context, Vector<Macroblock>& macroblocks)
  711. {
  712. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  713. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  714. for (u8 cindex = 0; cindex < context.component_count; cindex++) {
  715. auto& component = context.components[cindex];
  716. const u32* table = component.qtable_id == 0 ? context.luma_table : context.chroma_table;
  717. for (u32 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) {
  718. for (u32 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) {
  719. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  720. Macroblock& block = macroblocks[mb_index];
  721. int* block_component = cindex == 0 ? block.y : (cindex == 1 ? block.cb : block.cr);
  722. for (u32 k = 0; k < 64; k++)
  723. block_component[k] *= table[k];
  724. }
  725. }
  726. }
  727. }
  728. }
  729. }
  730. void inverse_dct(const JPGLoadingContext& context, Vector<Macroblock>& macroblocks)
  731. {
  732. static const float m0 = 2.0 * cos(1.0 / 16.0 * 2.0 * M_PI);
  733. static const float m1 = 2.0 * cos(2.0 / 16.0 * 2.0 * M_PI);
  734. static const float m3 = 2.0 * cos(2.0 / 16.0 * 2.0 * M_PI);
  735. static const float m5 = 2.0 * cos(3.0 / 16.0 * 2.0 * M_PI);
  736. static const float m2 = m0 - m5;
  737. static const float m4 = m0 + m5;
  738. static const float s0 = cos(0.0 / 16.0 * M_PI) / sqrt(8);
  739. static const float s1 = cos(1.0 / 16.0 * M_PI) / 2.0;
  740. static const float s2 = cos(2.0 / 16.0 * M_PI) / 2.0;
  741. static const float s3 = cos(3.0 / 16.0 * M_PI) / 2.0;
  742. static const float s4 = cos(4.0 / 16.0 * M_PI) / 2.0;
  743. static const float s5 = cos(5.0 / 16.0 * M_PI) / 2.0;
  744. static const float s6 = cos(6.0 / 16.0 * M_PI) / 2.0;
  745. static const float s7 = cos(7.0 / 16.0 * M_PI) / 2.0;
  746. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  747. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  748. for (u8 cindex = 0; cindex < context.component_count; cindex++) {
  749. auto& component = context.components[cindex];
  750. for (u8 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) {
  751. for (u8 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) {
  752. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  753. Macroblock& block = macroblocks[mb_index];
  754. i32* block_component = cindex == 0 ? block.y : (cindex == 1 ? block.cb : block.cr);
  755. for (u32 k = 0; k < 8; ++k) {
  756. const float g0 = block_component[0 * 8 + k] * s0;
  757. const float g1 = block_component[4 * 8 + k] * s4;
  758. const float g2 = block_component[2 * 8 + k] * s2;
  759. const float g3 = block_component[6 * 8 + k] * s6;
  760. const float g4 = block_component[5 * 8 + k] * s5;
  761. const float g5 = block_component[1 * 8 + k] * s1;
  762. const float g6 = block_component[7 * 8 + k] * s7;
  763. const float g7 = block_component[3 * 8 + k] * s3;
  764. const float f0 = g0;
  765. const float f1 = g1;
  766. const float f2 = g2;
  767. const float f3 = g3;
  768. const float f4 = g4 - g7;
  769. const float f5 = g5 + g6;
  770. const float f6 = g5 - g6;
  771. const float f7 = g4 + g7;
  772. const float e0 = f0;
  773. const float e1 = f1;
  774. const float e2 = f2 - f3;
  775. const float e3 = f2 + f3;
  776. const float e4 = f4;
  777. const float e5 = f5 - f7;
  778. const float e6 = f6;
  779. const float e7 = f5 + f7;
  780. const float e8 = f4 + f6;
  781. const float d0 = e0;
  782. const float d1 = e1;
  783. const float d2 = e2 * m1;
  784. const float d3 = e3;
  785. const float d4 = e4 * m2;
  786. const float d5 = e5 * m3;
  787. const float d6 = e6 * m4;
  788. const float d7 = e7;
  789. const float d8 = e8 * m5;
  790. const float c0 = d0 + d1;
  791. const float c1 = d0 - d1;
  792. const float c2 = d2 - d3;
  793. const float c3 = d3;
  794. const float c4 = d4 + d8;
  795. const float c5 = d5 + d7;
  796. const float c6 = d6 - d8;
  797. const float c7 = d7;
  798. const float c8 = c5 - c6;
  799. const float b0 = c0 + c3;
  800. const float b1 = c1 + c2;
  801. const float b2 = c1 - c2;
  802. const float b3 = c0 - c3;
  803. const float b4 = c4 - c8;
  804. const float b5 = c8;
  805. const float b6 = c6 - c7;
  806. const float b7 = c7;
  807. block_component[0 * 8 + k] = b0 + b7;
  808. block_component[1 * 8 + k] = b1 + b6;
  809. block_component[2 * 8 + k] = b2 + b5;
  810. block_component[3 * 8 + k] = b3 + b4;
  811. block_component[4 * 8 + k] = b3 - b4;
  812. block_component[5 * 8 + k] = b2 - b5;
  813. block_component[6 * 8 + k] = b1 - b6;
  814. block_component[7 * 8 + k] = b0 - b7;
  815. }
  816. for (u32 l = 0; l < 8; ++l) {
  817. const float g0 = block_component[l * 8 + 0] * s0;
  818. const float g1 = block_component[l * 8 + 4] * s4;
  819. const float g2 = block_component[l * 8 + 2] * s2;
  820. const float g3 = block_component[l * 8 + 6] * s6;
  821. const float g4 = block_component[l * 8 + 5] * s5;
  822. const float g5 = block_component[l * 8 + 1] * s1;
  823. const float g6 = block_component[l * 8 + 7] * s7;
  824. const float g7 = block_component[l * 8 + 3] * s3;
  825. const float f0 = g0;
  826. const float f1 = g1;
  827. const float f2 = g2;
  828. const float f3 = g3;
  829. const float f4 = g4 - g7;
  830. const float f5 = g5 + g6;
  831. const float f6 = g5 - g6;
  832. const float f7 = g4 + g7;
  833. const float e0 = f0;
  834. const float e1 = f1;
  835. const float e2 = f2 - f3;
  836. const float e3 = f2 + f3;
  837. const float e4 = f4;
  838. const float e5 = f5 - f7;
  839. const float e6 = f6;
  840. const float e7 = f5 + f7;
  841. const float e8 = f4 + f6;
  842. const float d0 = e0;
  843. const float d1 = e1;
  844. const float d2 = e2 * m1;
  845. const float d3 = e3;
  846. const float d4 = e4 * m2;
  847. const float d5 = e5 * m3;
  848. const float d6 = e6 * m4;
  849. const float d7 = e7;
  850. const float d8 = e8 * m5;
  851. const float c0 = d0 + d1;
  852. const float c1 = d0 - d1;
  853. const float c2 = d2 - d3;
  854. const float c3 = d3;
  855. const float c4 = d4 + d8;
  856. const float c5 = d5 + d7;
  857. const float c6 = d6 - d8;
  858. const float c7 = d7;
  859. const float c8 = c5 - c6;
  860. const float b0 = c0 + c3;
  861. const float b1 = c1 + c2;
  862. const float b2 = c1 - c2;
  863. const float b3 = c0 - c3;
  864. const float b4 = c4 - c8;
  865. const float b5 = c8;
  866. const float b6 = c6 - c7;
  867. const float b7 = c7;
  868. block_component[l * 8 + 0] = b0 + b7;
  869. block_component[l * 8 + 1] = b1 + b6;
  870. block_component[l * 8 + 2] = b2 + b5;
  871. block_component[l * 8 + 3] = b3 + b4;
  872. block_component[l * 8 + 4] = b3 - b4;
  873. block_component[l * 8 + 5] = b2 - b5;
  874. block_component[l * 8 + 6] = b1 - b6;
  875. block_component[l * 8 + 7] = b0 - b7;
  876. }
  877. }
  878. }
  879. }
  880. }
  881. }
  882. }
  883. void ycbcr_to_rgb(const JPGLoadingContext& context, Vector<Macroblock>& macroblocks)
  884. {
  885. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  886. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  887. const u32 chroma_block_index = vcursor * context.mblock_meta.hpadded_count + hcursor;
  888. const Macroblock& chroma = macroblocks[chroma_block_index];
  889. // Overflows are intentional.
  890. for (u8 vfactor_i = context.vsample_factor - 1; vfactor_i < context.vsample_factor; --vfactor_i) {
  891. for (u8 hfactor_i = context.hsample_factor - 1; hfactor_i < context.hsample_factor; --hfactor_i) {
  892. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  893. i32* y = macroblocks[mb_index].y;
  894. i32* cb = macroblocks[mb_index].cb;
  895. i32* cr = macroblocks[mb_index].cr;
  896. for (u8 i = 7; i < 8; --i) {
  897. for (u8 j = 7; j < 8; --j) {
  898. const u8 pixel = i * 8 + j;
  899. const u32 chroma_pxrow = (i / context.vsample_factor) + 4 * vfactor_i;
  900. const u32 chroma_pxcol = (j / context.hsample_factor) + 4 * hfactor_i;
  901. const u32 chroma_pixel = chroma_pxrow * 8 + chroma_pxcol;
  902. int r = y[pixel] + 1.402f * chroma.cr[chroma_pixel] + 128;
  903. int g = y[pixel] - 0.344f * chroma.cb[chroma_pixel] - 0.714f * chroma.cr[chroma_pixel] + 128;
  904. int b = y[pixel] + 1.772f * chroma.cb[chroma_pixel] + 128;
  905. y[pixel] = r < 0 ? 0 : (r > 255 ? 255 : r);
  906. cb[pixel] = g < 0 ? 0 : (g > 255 ? 255 : g);
  907. cr[pixel] = b < 0 ? 0 : (b > 255 ? 255 : b);
  908. }
  909. }
  910. }
  911. }
  912. }
  913. }
  914. }
  915. static void compose_bitmap(JPGLoadingContext& context, const Vector<Macroblock>& macroblocks)
  916. {
  917. context.bitmap = Bitmap::create_purgeable(BitmapFormat::RGB32, { context.frame.width, context.frame.height });
  918. for (u32 y = context.frame.height - 1; y < context.frame.height; y--) {
  919. const u32 block_row = y / 8;
  920. const u32 pixel_row = y % 8;
  921. for (u32 x = 0; x < context.frame.width; x++) {
  922. const u32 block_column = x / 8;
  923. auto& block = macroblocks[block_row * context.mblock_meta.hpadded_count + block_column];
  924. const u32 pixel_column = x % 8;
  925. const u32 pixel_index = pixel_row * 8 + pixel_column;
  926. const Color color { (u8)block.y[pixel_index], (u8)block.cb[pixel_index], (u8)block.cr[pixel_index] };
  927. context.bitmap->set_pixel(x, y, color);
  928. }
  929. }
  930. }
  931. static bool parse_header(BufferStream& stream, JPGLoadingContext& context)
  932. {
  933. auto marker = read_marker_at_cursor(stream);
  934. if (stream.handle_read_failure())
  935. return false;
  936. if (marker != JPG_SOI) {
  937. dbg() << stream.offset() << String::format(": SOI not found: %x!", marker);
  938. return false;
  939. }
  940. for (;;) {
  941. marker = read_marker_at_cursor(stream);
  942. // Set frame type if the marker marks a new frame.
  943. if (marker >= 0xFFC0 && marker <= 0xFFCF) {
  944. // Ignore interleaved markers.
  945. if (marker != 0xFFC4 && marker != 0xFFC8 && marker != 0xFFCC) {
  946. context.frame.type = static_cast<StartOfFrame::FrameType>(marker & 0xF);
  947. }
  948. }
  949. switch (marker) {
  950. case JPG_INVALID:
  951. case JPG_RST0:
  952. case JPG_RST1:
  953. case JPG_RST2:
  954. case JPG_RST3:
  955. case JPG_RST4:
  956. case JPG_RST5:
  957. case JPG_RST6:
  958. case JPG_RST7:
  959. case JPG_SOI:
  960. case JPG_EOI:
  961. dbg() << stream.offset() << String::format(": Unexpected marker %x!", marker);
  962. return false;
  963. case JPG_SOF0:
  964. if (!read_start_of_frame(stream, context))
  965. return false;
  966. context.state = JPGLoadingContext::FrameDecoded;
  967. break;
  968. case JPG_DQT:
  969. if (!read_quantization_table(stream, context))
  970. return false;
  971. break;
  972. case JPG_RST:
  973. if (!read_reset_marker(stream, context))
  974. return false;
  975. break;
  976. case JPG_DHT:
  977. if (!read_huffman_table(stream, context))
  978. return false;
  979. break;
  980. case JPG_SOS:
  981. return read_start_of_scan(stream, context);
  982. default:
  983. if (!skip_marker_with_length(stream)) {
  984. dbg() << stream.offset() << String::format(": Error skipping marker: %x!", marker);
  985. return false;
  986. }
  987. break;
  988. }
  989. }
  990. ASSERT_NOT_REACHED();
  991. }
  992. static bool scan_huffman_stream(BufferStream& stream, JPGLoadingContext& context)
  993. {
  994. u8 last_byte;
  995. u8 current_byte;
  996. stream >> current_byte;
  997. if (stream.handle_read_failure())
  998. return false;
  999. for (;;) {
  1000. last_byte = current_byte;
  1001. stream >> current_byte;
  1002. if (stream.handle_read_failure()) {
  1003. dbg() << stream.offset() << ": EOI not found!";
  1004. return false;
  1005. }
  1006. if (last_byte == 0xFF) {
  1007. if (current_byte == 0xFF)
  1008. continue;
  1009. if (current_byte == 0x00) {
  1010. stream >> current_byte;
  1011. context.huffman_stream.stream.append(last_byte);
  1012. continue;
  1013. }
  1014. Marker marker = 0xFF00 | current_byte;
  1015. if (marker == JPG_EOI)
  1016. return true;
  1017. if (marker >= JPG_RST0 && marker <= JPG_RST7) {
  1018. context.huffman_stream.stream.append(marker);
  1019. stream >> current_byte;
  1020. continue;
  1021. }
  1022. dbg() << stream.offset() << String::format(": Invalid marker: %x!", marker);
  1023. return false;
  1024. } else {
  1025. context.huffman_stream.stream.append(last_byte);
  1026. }
  1027. }
  1028. ASSERT_NOT_REACHED();
  1029. }
  1030. static bool decode_jpg(JPGLoadingContext& context)
  1031. {
  1032. ByteBuffer buffer = ByteBuffer::wrap(context.data, context.data_size);
  1033. BufferStream stream(buffer);
  1034. if (!parse_header(stream, context))
  1035. return false;
  1036. if (!scan_huffman_stream(stream, context))
  1037. return false;
  1038. auto result = decode_huffman_stream(context);
  1039. if (!result.has_value()) {
  1040. dbg() << stream.offset() << ": Failed to decode Macroblocks!";
  1041. return false;
  1042. }
  1043. auto macroblocks = result.release_value();
  1044. dbg() << String::format("%i macroblocks decoded successfully :^)", macroblocks.size());
  1045. dequantize(context, macroblocks);
  1046. inverse_dct(context, macroblocks);
  1047. ycbcr_to_rgb(context, macroblocks);
  1048. compose_bitmap(context, macroblocks);
  1049. return true;
  1050. }
  1051. static RefPtr<Gfx::Bitmap> load_jpg_impl(const u8* data, size_t data_size)
  1052. {
  1053. JPGLoadingContext context;
  1054. context.data = data;
  1055. context.data_size = data_size;
  1056. if (!decode_jpg(context))
  1057. return nullptr;
  1058. return context.bitmap;
  1059. }
  1060. RefPtr<Gfx::Bitmap> load_jpg(const StringView& path)
  1061. {
  1062. MappedFile mapped_file(path);
  1063. if (!mapped_file.is_valid()) {
  1064. return nullptr;
  1065. }
  1066. auto bitmap = load_jpg_impl((const u8*)mapped_file.data(), mapped_file.size());
  1067. if (bitmap)
  1068. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded JPG: %s", bitmap->width(), bitmap->height(), LexicalPath::canonicalized_path(path).characters()));
  1069. return bitmap;
  1070. }
  1071. RefPtr<Gfx::Bitmap> load_jpg_from_memory(const u8* data, size_t length)
  1072. {
  1073. auto bitmap = load_jpg_impl(data, length);
  1074. if (bitmap)
  1075. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded jpg: <memory>", bitmap->width(), bitmap->height()));
  1076. return bitmap;
  1077. }
  1078. JPGImageDecoderPlugin::JPGImageDecoderPlugin(const u8* data, size_t size)
  1079. {
  1080. m_context = make<JPGLoadingContext>();
  1081. m_context->data = data;
  1082. m_context->data_size = size;
  1083. m_context->huffman_stream.stream.ensure_capacity(50 * KB);
  1084. }
  1085. JPGImageDecoderPlugin::~JPGImageDecoderPlugin()
  1086. {
  1087. }
  1088. IntSize JPGImageDecoderPlugin::size()
  1089. {
  1090. if (m_context->state == JPGLoadingContext::State::Error)
  1091. return {};
  1092. if (m_context->state >= JPGLoadingContext::State::FrameDecoded)
  1093. return { m_context->frame.width, m_context->frame.height };
  1094. return {};
  1095. }
  1096. RefPtr<Gfx::Bitmap> JPGImageDecoderPlugin::bitmap()
  1097. {
  1098. if (m_context->state == JPGLoadingContext::State::Error)
  1099. return nullptr;
  1100. if (m_context->state < JPGLoadingContext::State::BitmapDecoded) {
  1101. if (!decode_jpg(*m_context)) {
  1102. m_context->state = JPGLoadingContext::State::Error;
  1103. return nullptr;
  1104. }
  1105. m_context->state = JPGLoadingContext::State::BitmapDecoded;
  1106. }
  1107. return m_context->bitmap;
  1108. }
  1109. void JPGImageDecoderPlugin::set_volatile()
  1110. {
  1111. if (m_context->bitmap)
  1112. m_context->bitmap->set_volatile();
  1113. }
  1114. bool JPGImageDecoderPlugin::set_nonvolatile()
  1115. {
  1116. if (!m_context->bitmap)
  1117. return false;
  1118. return m_context->bitmap->set_nonvolatile();
  1119. }
  1120. bool JPGImageDecoderPlugin::sniff()
  1121. {
  1122. return m_context->data_size > 3
  1123. && m_context->data[0] == 0xFF
  1124. && m_context->data[1] == 0xD8
  1125. && m_context->data[2] == 0xFF;
  1126. }
  1127. bool JPGImageDecoderPlugin::is_animated()
  1128. {
  1129. return false;
  1130. }
  1131. size_t JPGImageDecoderPlugin::loop_count()
  1132. {
  1133. return 0;
  1134. }
  1135. size_t JPGImageDecoderPlugin::frame_count()
  1136. {
  1137. return 1;
  1138. }
  1139. ImageFrameDescriptor JPGImageDecoderPlugin::frame(size_t i)
  1140. {
  1141. if (i > 0) {
  1142. return { bitmap(), 0 };
  1143. }
  1144. return {};
  1145. }
  1146. }