JPGLoader.cpp 48 KB

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