JPGLoader.cpp 48 KB

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