JPGLoader.cpp 48 KB

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