JPGLoader.cpp 48 KB

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