JPEGLoader.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  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/Endian.h>
  8. #include <AK/Error.h>
  9. #include <AK/FixedArray.h>
  10. #include <AK/HashMap.h>
  11. #include <AK/Math.h>
  12. #include <AK/MemoryStream.h>
  13. #include <AK/String.h>
  14. #include <AK/Try.h>
  15. #include <AK/Vector.h>
  16. #include <LibGfx/ImageFormats/JPEGLoader.h>
  17. #define JPEG_INVALID 0X0000
  18. // These names are defined in B.1.1.3 - Marker assignments
  19. #define JPEG_APPN0 0XFFE0
  20. #define JPEG_APPN1 0XFFE1
  21. #define JPEG_APPN2 0XFFE2
  22. #define JPEG_APPN3 0XFFE3
  23. #define JPEG_APPN4 0XFFE4
  24. #define JPEG_APPN5 0XFFE5
  25. #define JPEG_APPN6 0XFFE6
  26. #define JPEG_APPN7 0XFFE7
  27. #define JPEG_APPN8 0XFFE8
  28. #define JPEG_APPN9 0XFFE9
  29. #define JPEG_APPN10 0XFFEA
  30. #define JPEG_APPN11 0XFFEB
  31. #define JPEG_APPN12 0XFFEC
  32. #define JPEG_APPN13 0XFFED
  33. #define JPEG_APPN14 0xFFEE
  34. #define JPEG_APPN15 0xFFEF
  35. #define JPEG_RESERVED1 0xFFF1
  36. #define JPEG_RESERVED2 0xFFF2
  37. #define JPEG_RESERVED3 0xFFF3
  38. #define JPEG_RESERVED4 0xFFF4
  39. #define JPEG_RESERVED5 0xFFF5
  40. #define JPEG_RESERVED6 0xFFF6
  41. #define JPEG_RESERVED7 0xFFF7
  42. #define JPEG_RESERVED8 0xFFF8
  43. #define JPEG_RESERVED9 0xFFF9
  44. #define JPEG_RESERVEDA 0xFFFA
  45. #define JPEG_RESERVEDB 0xFFFB
  46. #define JPEG_RESERVEDC 0xFFFC
  47. #define JPEG_RESERVEDD 0xFFFD
  48. #define JPEG_RST0 0xFFD0
  49. #define JPEG_RST1 0xFFD1
  50. #define JPEG_RST2 0xFFD2
  51. #define JPEG_RST3 0xFFD3
  52. #define JPEG_RST4 0xFFD4
  53. #define JPEG_RST5 0xFFD5
  54. #define JPEG_RST6 0xFFD6
  55. #define JPEG_RST7 0xFFD7
  56. #define JPEG_ZRL 0xF0
  57. #define JPEG_DHP 0xFFDE
  58. #define JPEG_EXP 0xFFDF
  59. #define JPEG_DAC 0XFFCC
  60. #define JPEG_DHT 0XFFC4
  61. #define JPEG_DQT 0XFFDB
  62. #define JPEG_EOI 0xFFD9
  63. #define JPEG_DRI 0XFFDD
  64. #define JPEG_SOF0 0XFFC0
  65. #define JPEG_SOF2 0xFFC2
  66. #define JPEG_SOF15 0xFFCF
  67. #define JPEG_SOI 0XFFD8
  68. #define JPEG_SOS 0XFFDA
  69. #define JPEG_COM 0xFFFE
  70. namespace Gfx {
  71. constexpr static u8 zigzag_map[64] {
  72. 0, 1, 8, 16, 9, 2, 3, 10,
  73. 17, 24, 32, 25, 18, 11, 4, 5,
  74. 12, 19, 26, 33, 40, 48, 41, 34,
  75. 27, 20, 13, 6, 7, 14, 21, 28,
  76. 35, 42, 49, 56, 57, 50, 43, 36,
  77. 29, 22, 15, 23, 30, 37, 44, 51,
  78. 58, 59, 52, 45, 38, 31, 39, 46,
  79. 53, 60, 61, 54, 47, 55, 62, 63
  80. };
  81. using Marker = u16;
  82. /**
  83. * MCU means group of data units that are coded together. A data unit is an 8x8
  84. * block of component data. In interleaved scans, number of non-interleaved data
  85. * units of a component C is Ch * Cv, where Ch and Cv represent the horizontal &
  86. * vertical subsampling factors of the component, respectively. A MacroBlock is
  87. * an 8x8 block of RGB values before encoding, and 8x8 block of YCbCr values when
  88. * we're done decoding the huffman stream.
  89. */
  90. struct Macroblock {
  91. union {
  92. i16 y[64] = { 0 };
  93. i16 r[64];
  94. };
  95. union {
  96. i16 cb[64] = { 0 };
  97. i16 g[64];
  98. };
  99. union {
  100. i16 cr[64] = { 0 };
  101. i16 b[64];
  102. };
  103. i16 k[64] = { 0 };
  104. };
  105. struct MacroblockMeta {
  106. u32 total { 0 };
  107. u32 padded_total { 0 };
  108. u32 hcount { 0 };
  109. u32 vcount { 0 };
  110. u32 hpadded_count { 0 };
  111. u32 vpadded_count { 0 };
  112. };
  113. // In the JPEG format, components are defined first at the frame level, then
  114. // referenced in each scan and aggregated with scan-specific information. The
  115. // two following structs mimic this hierarchy.
  116. struct Component {
  117. // B.2.2 - Frame header syntax
  118. u8 id { 0 }; // Ci, Component identifier
  119. u8 hsample_factor { 1 }; // Hi, Horizontal sampling factor
  120. u8 vsample_factor { 1 }; // Vi, Vertical sampling factor
  121. u8 qtable_id { 0 }; // Tqi, Quantization table destination selector
  122. // The JPEG specification does not specify which component corresponds to
  123. // Y, Cb or Cr. This field (actually the index in the parent Vector) will
  124. // act as an authority to determine the *real* component.
  125. // Please note that this is implementation specific.
  126. u8 index { 0 };
  127. };
  128. struct ScanComponent {
  129. // B.2.3 - Scan header syntax
  130. Component& component;
  131. u8 dc_destination_id { 0 }; // Tdj, DC entropy coding table destination selector
  132. u8 ac_destination_id { 0 }; // Taj, AC entropy coding table destination selector
  133. };
  134. struct StartOfFrame {
  135. // Of these, only the first 3 are in mainstream use, and refers to SOF0-2.
  136. enum class FrameType {
  137. Baseline_DCT = 0,
  138. Extended_Sequential_DCT = 1,
  139. Progressive_DCT = 2,
  140. Sequential_Lossless = 3,
  141. Differential_Sequential_DCT = 5,
  142. Differential_Progressive_DCT = 6,
  143. Differential_Sequential_Lossless = 7,
  144. Extended_Sequential_DCT_Arithmetic = 9,
  145. Progressive_DCT_Arithmetic = 10,
  146. Sequential_Lossless_Arithmetic = 11,
  147. Differential_Sequential_DCT_Arithmetic = 13,
  148. Differential_Progressive_DCT_Arithmetic = 14,
  149. Differential_Sequential_Lossless_Arithmetic = 15,
  150. };
  151. FrameType type { FrameType::Baseline_DCT };
  152. u8 precision { 0 };
  153. u16 height { 0 };
  154. u16 width { 0 };
  155. };
  156. struct HuffmanTableSpec {
  157. u8 type { 0 };
  158. u8 destination_id { 0 };
  159. u8 code_counts[16] = { 0 };
  160. Vector<u8> symbols;
  161. Vector<u16> codes;
  162. };
  163. struct HuffmanStreamState {
  164. Vector<u8> stream;
  165. u8 bit_offset { 0 };
  166. size_t byte_offset { 0 };
  167. };
  168. struct ICCMultiChunkState {
  169. u8 seen_number_of_icc_chunks { 0 };
  170. FixedArray<ByteBuffer> chunks;
  171. };
  172. struct Scan {
  173. // B.2.3 - Scan header syntax
  174. Vector<ScanComponent, 4> components;
  175. u8 spectral_selection_start {}; // Ss
  176. u8 spectral_selection_end {}; // Se
  177. u8 successive_approximation_high {}; // Ah
  178. u8 successive_approximation_low {}; // Al
  179. HuffmanStreamState huffman_stream;
  180. u64 end_of_bands_run_count { 0 };
  181. // See the note on Figure B.4 - Scan header syntax
  182. bool are_components_interleaved() const
  183. {
  184. return components.size() != 1;
  185. }
  186. };
  187. enum class ColorTransform {
  188. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.872-201206-I!!PDF-E&type=items
  189. // 6.5.3 - APP14 marker segment for colour encoding
  190. CmykOrRgb = 0,
  191. YCbCr = 1,
  192. YCCK = 2,
  193. };
  194. struct JPEGLoadingContext {
  195. enum State {
  196. NotDecoded = 0,
  197. Error,
  198. FrameDecoded,
  199. HeaderDecoded,
  200. BitmapDecoded
  201. };
  202. State state { State::NotDecoded };
  203. u32 luma_table[64] = { 0 };
  204. u32 chroma_table[64] = { 0 };
  205. StartOfFrame frame;
  206. u8 hsample_factor { 0 };
  207. u8 vsample_factor { 0 };
  208. Scan current_scan;
  209. Vector<Component, 4> components;
  210. RefPtr<Gfx::Bitmap> bitmap;
  211. u16 dc_restart_interval { 0 };
  212. HashMap<u8, HuffmanTableSpec> dc_tables;
  213. HashMap<u8, HuffmanTableSpec> ac_tables;
  214. Array<i32, 4> previous_dc_values {};
  215. MacroblockMeta mblock_meta;
  216. OwnPtr<FixedMemoryStream> stream;
  217. Optional<ColorTransform> color_transform {};
  218. Optional<ICCMultiChunkState> icc_multi_chunk_state;
  219. Optional<ByteBuffer> icc_data;
  220. };
  221. static void generate_huffman_codes(HuffmanTableSpec& table)
  222. {
  223. unsigned code = 0;
  224. for (auto number_of_codes : table.code_counts) {
  225. for (int i = 0; i < number_of_codes; i++)
  226. table.codes.append(code++);
  227. code <<= 1;
  228. }
  229. }
  230. static ErrorOr<size_t> read_huffman_bits(HuffmanStreamState& hstream, size_t count = 1)
  231. {
  232. if (count > (8 * sizeof(size_t))) {
  233. dbgln_if(JPEG_DEBUG, "Can't read {} bits at once!", count);
  234. return Error::from_string_literal("Reading too much huffman bits at once");
  235. }
  236. size_t value = 0;
  237. while (count--) {
  238. if (hstream.byte_offset >= hstream.stream.size()) {
  239. dbgln_if(JPEG_DEBUG, "Huffman stream exhausted. This could be an error!");
  240. return Error::from_string_literal("Huffman stream exhausted.");
  241. }
  242. u8 current_byte = hstream.stream[hstream.byte_offset];
  243. u8 current_bit = 1u & (u32)(current_byte >> (7 - hstream.bit_offset)); // MSB first.
  244. hstream.bit_offset++;
  245. value = (value << 1) | (size_t)current_bit;
  246. if (hstream.bit_offset == 8) {
  247. hstream.byte_offset++;
  248. hstream.bit_offset = 0;
  249. }
  250. }
  251. return value;
  252. }
  253. static ErrorOr<u8> get_next_symbol(HuffmanStreamState& hstream, HuffmanTableSpec const& table)
  254. {
  255. unsigned code = 0;
  256. size_t code_cursor = 0;
  257. for (int i = 0; i < 16; i++) { // Codes can't be longer than 16 bits.
  258. auto result = TRY(read_huffman_bits(hstream));
  259. code = (code << 1) | (i32)result;
  260. for (int j = 0; j < table.code_counts[i]; j++) {
  261. if (code == table.codes[code_cursor])
  262. return table.symbols[code_cursor];
  263. code_cursor++;
  264. }
  265. }
  266. dbgln_if(JPEG_DEBUG, "If you're seeing this...the jpeg decoder needs to support more kinds of JPEGs!");
  267. return Error::from_string_literal("This kind of JPEG is not yet supported by the decoder");
  268. }
  269. static inline auto* get_component(Macroblock& block, unsigned component)
  270. {
  271. switch (component) {
  272. case 0:
  273. return block.y;
  274. case 1:
  275. return block.cb;
  276. case 2:
  277. return block.cr;
  278. case 3:
  279. return block.k;
  280. default:
  281. VERIFY_NOT_REACHED();
  282. }
  283. }
  284. static ErrorOr<void> refine_coefficient(Scan& scan, auto& coefficient)
  285. {
  286. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  287. // See the correction bit from rule b.
  288. u8 const bit = TRY(read_huffman_bits(scan.huffman_stream, 1));
  289. if (bit == 1)
  290. coefficient |= 1 << scan.successive_approximation_low;
  291. return {};
  292. }
  293. static ErrorOr<void> add_dc(JPEGLoadingContext& context, Macroblock& macroblock, ScanComponent const& scan_component)
  294. {
  295. auto maybe_table = context.dc_tables.get(scan_component.dc_destination_id);
  296. if (!maybe_table.has_value()) {
  297. dbgln_if(JPEG_DEBUG, "Unable to find a DC table with id: {}", scan_component.dc_destination_id);
  298. return Error::from_string_literal("Unable to find corresponding DC table");
  299. }
  300. auto& dc_table = maybe_table.value();
  301. auto& scan = context.current_scan;
  302. auto* select_component = get_component(macroblock, scan_component.component.index);
  303. auto& coefficient = select_component[0];
  304. if (context.current_scan.successive_approximation_high > 0) {
  305. TRY(refine_coefficient(scan, coefficient));
  306. return {};
  307. }
  308. // For DC coefficients, symbol encodes the length of the coefficient.
  309. auto dc_length = TRY(get_next_symbol(scan.huffman_stream, dc_table));
  310. if (dc_length > 11) {
  311. dbgln_if(JPEG_DEBUG, "DC coefficient too long: {}!", dc_length);
  312. return Error::from_string_literal("DC coefficient too long");
  313. }
  314. // DC coefficients are encoded as the difference between previous and current DC values.
  315. i32 dc_diff = TRY(read_huffman_bits(scan.huffman_stream, dc_length));
  316. // If MSB in diff is 0, the difference is -ve. Otherwise +ve.
  317. if (dc_length != 0 && dc_diff < (1 << (dc_length - 1)))
  318. dc_diff -= (1 << dc_length) - 1;
  319. auto& previous_dc = context.previous_dc_values[scan_component.component.index];
  320. previous_dc += dc_diff;
  321. coefficient = previous_dc << scan.successive_approximation_low;
  322. return {};
  323. }
  324. static ErrorOr<bool> read_eob(Scan& scan, u32 symbol)
  325. {
  326. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  327. // Note: We also use it for non-progressive encoding as it supports both EOB and ZRL
  328. if (auto const eob = symbol & 0x0F; eob == 0 && symbol != JPEG_ZRL) {
  329. // We encountered an EOB marker
  330. auto const eob_base = symbol >> 4;
  331. auto const additional_value = TRY(read_huffman_bits(scan.huffman_stream, eob_base));
  332. scan.end_of_bands_run_count = additional_value + (1 << eob_base) - 1;
  333. // end_of_bands_run_count is decremented at the end of `build_macroblocks`.
  334. // And we need to now that we reached End of Block in `add_ac`.
  335. ++scan.end_of_bands_run_count;
  336. return true;
  337. }
  338. return false;
  339. }
  340. static bool is_progressive(StartOfFrame::FrameType frame_type)
  341. {
  342. return frame_type == StartOfFrame::FrameType::Progressive_DCT
  343. || frame_type == StartOfFrame::FrameType::Progressive_DCT_Arithmetic
  344. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT
  345. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT_Arithmetic;
  346. }
  347. static ErrorOr<void> add_ac(JPEGLoadingContext& context, Macroblock& macroblock, ScanComponent const& scan_component)
  348. {
  349. auto maybe_table = context.ac_tables.get(scan_component.ac_destination_id);
  350. if (!maybe_table.has_value()) {
  351. dbgln_if(JPEG_DEBUG, "Unable to find a AC table with id: {}", scan_component.ac_destination_id);
  352. return Error::from_string_literal("Unable to find corresponding AC table");
  353. }
  354. auto& ac_table = maybe_table.value();
  355. auto* select_component = get_component(macroblock, scan_component.component.index);
  356. auto& scan = context.current_scan;
  357. // Compute the AC coefficients.
  358. // 0th coefficient is the dc, which is already handled
  359. auto first_coefficient = max(1, scan.spectral_selection_start);
  360. u32 to_skip = 0;
  361. Optional<u8> saved_symbol;
  362. Optional<u8> saved_bit_for_rule_a;
  363. bool in_zrl = false;
  364. for (int j = first_coefficient; j <= scan.spectral_selection_end; ++j) {
  365. auto& coefficient = select_component[zigzag_map[j]];
  366. // AC symbols encode 2 pieces of information, the high 4 bits represent
  367. // number of zeroes to be stuffed before reading the coefficient. Low 4
  368. // bits represent the magnitude of the coefficient.
  369. if (!in_zrl && scan.end_of_bands_run_count == 0 && !saved_symbol.has_value()) {
  370. saved_symbol = TRY(get_next_symbol(scan.huffman_stream, ac_table));
  371. if (!TRY(read_eob(scan, *saved_symbol))) {
  372. to_skip = *saved_symbol >> 4;
  373. in_zrl = *saved_symbol == JPEG_ZRL;
  374. if (in_zrl) {
  375. to_skip++;
  376. saved_symbol.clear();
  377. }
  378. if (!in_zrl && is_progressive(context.frame.type) && scan.successive_approximation_high != 0) {
  379. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  380. // Bit sign from rule a
  381. saved_bit_for_rule_a = TRY(read_huffman_bits(scan.huffman_stream, 1));
  382. }
  383. }
  384. }
  385. if (coefficient != 0) {
  386. TRY(refine_coefficient(scan, coefficient));
  387. continue;
  388. }
  389. if (to_skip > 0) {
  390. --to_skip;
  391. if (to_skip == 0)
  392. in_zrl = false;
  393. continue;
  394. }
  395. if (scan.end_of_bands_run_count > 0)
  396. continue;
  397. if (is_progressive(context.frame.type) && scan.successive_approximation_high != 0) {
  398. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  399. if (auto const low_bits = *saved_symbol & 0x0F; low_bits != 1) {
  400. dbgln_if(JPEG_DEBUG, "AC coefficient low bits isn't equal to 1: {}!", low_bits);
  401. return Error::from_string_literal("AC coefficient low bits isn't equal to 1");
  402. }
  403. coefficient = (*saved_bit_for_rule_a == 0 ? -1 : 1) << scan.successive_approximation_low;
  404. saved_bit_for_rule_a.clear();
  405. } else {
  406. // F.1.2.2 - Huffman encoding of AC coefficients
  407. u8 const coeff_length = *saved_symbol & 0x0F;
  408. if (coeff_length > 10) {
  409. dbgln_if(JPEG_DEBUG, "AC coefficient too long: {}!", coeff_length);
  410. return Error::from_string_literal("AC coefficient too long");
  411. }
  412. if (coeff_length != 0) {
  413. i32 ac_coefficient = TRY(read_huffman_bits(scan.huffman_stream, coeff_length));
  414. if (ac_coefficient < (1 << (coeff_length - 1)))
  415. ac_coefficient -= (1 << coeff_length) - 1;
  416. coefficient = ac_coefficient * (1 << scan.successive_approximation_low);
  417. }
  418. }
  419. saved_symbol.clear();
  420. }
  421. if (to_skip > 0) {
  422. dbgln_if(JPEG_DEBUG, "Run-length exceeded boundaries. Cursor: {}, Skipping: {}!", scan.spectral_selection_end + to_skip, to_skip);
  423. return Error::from_string_literal("Run-length exceeded boundaries");
  424. }
  425. return {};
  426. }
  427. /**
  428. * Build the macroblocks possible by reading single (MCU) subsampled pair of CbCr.
  429. * Depending on the sampling factors, we may not see triples of y, cb, cr in that
  430. * order. If sample factors differ from one, we'll read more than one block of y-
  431. * coefficients before we get to read a cb-cr block.
  432. * In the function below, `hcursor` and `vcursor` denote the location of the block
  433. * we're building in the macroblock matrix. `vfactor_i` and `hfactor_i` are cursors
  434. * that iterate over the vertical and horizontal subsampling factors, respectively.
  435. * When we finish one iteration of the innermost loop, we'll have the coefficients
  436. * of one of the components of block at position `macroblock_index`. When the outermost
  437. * loop finishes first iteration, we'll have all the luminance coefficients for all the
  438. * macroblocks that share the chrominance data. Next two iterations (assuming that
  439. * we are dealing with three components) will fill up the blocks with chroma data.
  440. */
  441. static ErrorOr<void> build_macroblocks(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks, u32 hcursor, u32 vcursor)
  442. {
  443. for (auto const& scan_component : context.current_scan.components) {
  444. for (u8 vfactor_i = 0; vfactor_i < scan_component.component.vsample_factor; vfactor_i++) {
  445. for (u8 hfactor_i = 0; hfactor_i < scan_component.component.hsample_factor; hfactor_i++) {
  446. // A.2.3 - Interleaved order
  447. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  448. if (!context.current_scan.are_components_interleaved()) {
  449. macroblock_index = vcursor * context.mblock_meta.hpadded_count + (hfactor_i + (hcursor * scan_component.component.vsample_factor) + (vfactor_i * scan_component.component.hsample_factor));
  450. // A.2.4 Completion of partial MCU
  451. // If the component is [and only if!] to be interleaved, the encoding process
  452. // shall also extend the number of samples by one or more additional blocks.
  453. // Horizontally
  454. if (macroblock_index >= context.mblock_meta.hcount && macroblock_index % context.mblock_meta.hpadded_count >= context.mblock_meta.hcount)
  455. continue;
  456. // Vertically
  457. if (macroblock_index >= context.mblock_meta.hpadded_count * context.mblock_meta.vcount)
  458. continue;
  459. }
  460. Macroblock& block = macroblocks[macroblock_index];
  461. if (context.current_scan.spectral_selection_start == 0)
  462. TRY(add_dc(context, block, scan_component));
  463. if (context.current_scan.spectral_selection_end != 0)
  464. TRY(add_ac(context, block, scan_component));
  465. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  466. if (context.current_scan.end_of_bands_run_count > 0) {
  467. --context.current_scan.end_of_bands_run_count;
  468. continue;
  469. }
  470. }
  471. }
  472. }
  473. return {};
  474. }
  475. static bool is_dct_based(StartOfFrame::FrameType frame_type)
  476. {
  477. return frame_type == StartOfFrame::FrameType::Baseline_DCT
  478. || frame_type == StartOfFrame::FrameType::Extended_Sequential_DCT
  479. || frame_type == StartOfFrame::FrameType::Progressive_DCT
  480. || frame_type == StartOfFrame::FrameType::Differential_Sequential_DCT
  481. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT
  482. || frame_type == StartOfFrame::FrameType::Progressive_DCT_Arithmetic
  483. || frame_type == StartOfFrame::FrameType::Differential_Sequential_DCT_Arithmetic
  484. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT_Arithmetic;
  485. }
  486. static void reset_decoder(JPEGLoadingContext& context)
  487. {
  488. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  489. context.current_scan.end_of_bands_run_count = 0;
  490. // E.2.4 Control procedure for decoding a restart interval
  491. if (is_dct_based(context.frame.type)) {
  492. context.previous_dc_values = {};
  493. return;
  494. }
  495. VERIFY_NOT_REACHED();
  496. }
  497. static ErrorOr<void> decode_huffman_stream(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks)
  498. {
  499. // Compute huffman codes for DC and AC tables.
  500. for (auto it = context.dc_tables.begin(); it != context.dc_tables.end(); ++it)
  501. generate_huffman_codes(it->value);
  502. for (auto it = context.ac_tables.begin(); it != context.ac_tables.end(); ++it)
  503. generate_huffman_codes(it->value);
  504. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  505. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  506. u32 i = vcursor * context.mblock_meta.hpadded_count + hcursor;
  507. auto& huffman_stream = context.current_scan.huffman_stream;
  508. if (context.dc_restart_interval > 0) {
  509. if (i != 0 && i % (context.dc_restart_interval * context.vsample_factor * context.hsample_factor) == 0) {
  510. reset_decoder(context);
  511. // Restart markers are stored in byte boundaries. Advance the huffman stream cursor to
  512. // the 0th bit of the next byte.
  513. if (huffman_stream.byte_offset < huffman_stream.stream.size()) {
  514. if (huffman_stream.bit_offset > 0) {
  515. huffman_stream.bit_offset = 0;
  516. huffman_stream.byte_offset++;
  517. }
  518. // Skip the restart marker (RSTn).
  519. huffman_stream.byte_offset++;
  520. }
  521. }
  522. }
  523. if (auto result = build_macroblocks(context, macroblocks, hcursor, vcursor); result.is_error()) {
  524. if constexpr (JPEG_DEBUG) {
  525. dbgln("Failed to build Macroblock {}: {}", i, result.error());
  526. dbgln("Huffman stream byte offset {}", huffman_stream.byte_offset);
  527. dbgln("Huffman stream bit offset {}", huffman_stream.bit_offset);
  528. }
  529. return result.release_error();
  530. }
  531. }
  532. }
  533. return {};
  534. }
  535. static bool is_frame_marker(Marker const marker)
  536. {
  537. // B.1.1.3 - Marker assignments
  538. bool const is_sof_marker = marker >= JPEG_SOF0 && marker <= JPEG_SOF15;
  539. // Start of frame markers are valid for JPEG_SOF0 to JPEG_SOF15 except number 4, 8 (reserved) and 12.
  540. bool const is_defined_marker = marker != JPEG_DHT && marker != 0xFFC8 && marker != JPEG_DAC;
  541. return is_sof_marker && is_defined_marker;
  542. }
  543. static inline bool is_supported_marker(Marker const marker)
  544. {
  545. if (marker >= JPEG_APPN0 && marker <= JPEG_APPN15) {
  546. if (marker != JPEG_APPN0 && marker != JPEG_APPN14)
  547. dbgln_if(JPEG_DEBUG, "{:#04x} not supported yet. The decoder may fail!", marker);
  548. return true;
  549. }
  550. if (marker >= JPEG_RESERVED1 && marker <= JPEG_RESERVEDD)
  551. return true;
  552. if (marker >= JPEG_RST0 && marker <= JPEG_RST7)
  553. return true;
  554. switch (marker) {
  555. case JPEG_COM:
  556. case JPEG_DHP:
  557. case JPEG_EXP:
  558. case JPEG_DHT:
  559. case JPEG_DQT:
  560. case JPEG_DRI:
  561. case JPEG_EOI:
  562. case JPEG_SOF0:
  563. case JPEG_SOF2:
  564. case JPEG_SOI:
  565. case JPEG_SOS:
  566. return true;
  567. }
  568. if (is_frame_marker(marker))
  569. dbgln_if(JPEG_DEBUG, "Decoding this frame-type (SOF{}) is not currently supported. Decoder will fail!", marker & 0xf);
  570. return false;
  571. }
  572. static inline ErrorOr<Marker> read_marker_at_cursor(Stream& stream)
  573. {
  574. u16 marker = TRY(stream.read_value<BigEndian<u16>>());
  575. if (is_supported_marker(marker))
  576. return marker;
  577. if (marker != 0xFFFF)
  578. return JPEG_INVALID;
  579. u8 next;
  580. do {
  581. next = TRY(stream.read_value<u8>());
  582. if (next == 0x00)
  583. return JPEG_INVALID;
  584. } while (next == 0xFF);
  585. marker = 0xFF00 | (u16)next;
  586. return is_supported_marker(marker) ? marker : JPEG_INVALID;
  587. }
  588. static ErrorOr<void> read_start_of_scan(Stream& stream, JPEGLoadingContext& context)
  589. {
  590. // B.2.3 - Scan header syntax
  591. if (context.state < JPEGLoadingContext::State::FrameDecoded)
  592. return Error::from_string_literal("SOS found before reading a SOF");
  593. [[maybe_unused]] u16 const bytes_to_read = TRY(stream.read_value<BigEndian<u16>>()) - 2;
  594. u8 const component_count = TRY(stream.read_value<u8>());
  595. Scan current_scan;
  596. current_scan.huffman_stream.stream.ensure_capacity(50 * KiB);
  597. Optional<u8> last_read;
  598. u8 component_read = 0;
  599. for (auto& component : context.components) {
  600. // See the Csj paragraph:
  601. // [...] the ordering in the scan header shall follow the ordering in the frame header.
  602. if (component_read == component_count)
  603. break;
  604. if (!last_read.has_value())
  605. last_read = TRY(stream.read_value<u8>());
  606. if (component.id != *last_read)
  607. continue;
  608. u8 table_ids = TRY(stream.read_value<u8>());
  609. current_scan.components.empend(component, static_cast<u8>(table_ids >> 4), static_cast<u8>(table_ids & 0x0F));
  610. component_read++;
  611. last_read.clear();
  612. }
  613. if constexpr (JPEG_DEBUG) {
  614. StringBuilder builder;
  615. TRY(builder.try_append("Components in scan: "sv));
  616. for (auto const& scan_component : current_scan.components) {
  617. TRY(builder.try_append(TRY(String::number(scan_component.component.id))));
  618. TRY(builder.try_append(' '));
  619. }
  620. dbgln(builder.string_view());
  621. }
  622. current_scan.spectral_selection_start = TRY(stream.read_value<u8>());
  623. current_scan.spectral_selection_end = TRY(stream.read_value<u8>());
  624. auto const successive_approximation = TRY(stream.read_value<u8>());
  625. current_scan.successive_approximation_high = successive_approximation >> 4;
  626. current_scan.successive_approximation_low = successive_approximation & 0x0F;
  627. dbgln_if(JPEG_DEBUG, "Start of Selection: {}, End of Selection: {}, Successive Approximation High: {}, Successive Approximation Low: {}",
  628. current_scan.spectral_selection_start,
  629. current_scan.spectral_selection_end,
  630. current_scan.successive_approximation_high,
  631. current_scan.successive_approximation_low);
  632. if (current_scan.spectral_selection_start > 63 || current_scan.spectral_selection_end > 63 || current_scan.successive_approximation_high > 13 || current_scan.successive_approximation_low > 13) {
  633. dbgln_if(JPEG_DEBUG, "ERROR! Start of Selection: {}, End of Selection: {}, Successive Approximation High: {}, Successive Approximation Low: {}!",
  634. current_scan.spectral_selection_start,
  635. current_scan.spectral_selection_end,
  636. current_scan.successive_approximation_high,
  637. current_scan.successive_approximation_low);
  638. return Error::from_string_literal("Spectral selection is not [0,63] or successive approximation is not null");
  639. }
  640. context.current_scan = move(current_scan);
  641. return {};
  642. }
  643. static ErrorOr<void> read_restart_interval(Stream& stream, JPEGLoadingContext& context)
  644. {
  645. // B.2.4.4 - Restart interval definition syntax
  646. u16 bytes_to_read = TRY(stream.read_value<BigEndian<u16>>()) - 2;
  647. if (bytes_to_read != 2) {
  648. dbgln_if(JPEG_DEBUG, "Malformed DRI marker found!");
  649. return Error::from_string_literal("Malformed DRI marker found");
  650. }
  651. context.dc_restart_interval = TRY(stream.read_value<BigEndian<u16>>());
  652. return {};
  653. }
  654. static ErrorOr<void> read_huffman_table(Stream& stream, JPEGLoadingContext& context)
  655. {
  656. i32 bytes_to_read = TRY(stream.read_value<BigEndian<u16>>());
  657. bytes_to_read -= 2;
  658. while (bytes_to_read > 0) {
  659. HuffmanTableSpec table;
  660. u8 table_info = TRY(stream.read_value<u8>());
  661. u8 table_type = table_info >> 4;
  662. u8 table_destination_id = table_info & 0x0F;
  663. if (table_type > 1) {
  664. dbgln_if(JPEG_DEBUG, "Unrecognized huffman table: {}!", table_type);
  665. return Error::from_string_literal("Unrecognized huffman table");
  666. }
  667. if (table_destination_id > 1) {
  668. dbgln_if(JPEG_DEBUG, "Invalid huffman table destination id: {}!", table_destination_id);
  669. return Error::from_string_literal("Invalid huffman table destination id");
  670. }
  671. table.type = table_type;
  672. table.destination_id = table_destination_id;
  673. u32 total_codes = 0;
  674. // Read code counts. At each index K, the value represents the number of K+1 bit codes in this header.
  675. for (int i = 0; i < 16; i++) {
  676. u8 count = TRY(stream.read_value<u8>());
  677. total_codes += count;
  678. table.code_counts[i] = count;
  679. }
  680. table.codes.ensure_capacity(total_codes);
  681. // Read symbols. Read X bytes, where X is the sum of the counts of codes read in the previous step.
  682. for (u32 i = 0; i < total_codes; i++) {
  683. u8 symbol = TRY(stream.read_value<u8>());
  684. table.symbols.append(symbol);
  685. }
  686. auto& huffman_table = table.type == 0 ? context.dc_tables : context.ac_tables;
  687. huffman_table.set(table.destination_id, table);
  688. VERIFY(huffman_table.size() <= 2);
  689. bytes_to_read -= 1 + 16 + total_codes;
  690. }
  691. if (bytes_to_read != 0) {
  692. dbgln_if(JPEG_DEBUG, "Extra bytes detected in huffman header!");
  693. return Error::from_string_literal("Extra bytes detected in huffman header");
  694. }
  695. return {};
  696. }
  697. static ErrorOr<void> read_icc_profile(Stream& stream, JPEGLoadingContext& context, int bytes_to_read)
  698. {
  699. // https://www.color.org/technotes/ICC-Technote-ProfileEmbedding.pdf, page 5, "JFIF".
  700. if (bytes_to_read <= 2)
  701. return Error::from_string_literal("icc marker too small");
  702. auto chunk_sequence_number = TRY(stream.read_value<u8>()); // 1-based
  703. auto number_of_chunks = TRY(stream.read_value<u8>());
  704. bytes_to_read -= 2;
  705. if (!context.icc_multi_chunk_state.has_value())
  706. context.icc_multi_chunk_state.emplace(ICCMultiChunkState { 0, TRY(FixedArray<ByteBuffer>::create(number_of_chunks)) });
  707. auto& chunk_state = context.icc_multi_chunk_state;
  708. if (chunk_state->seen_number_of_icc_chunks >= number_of_chunks)
  709. return Error::from_string_literal("Too many ICC chunks");
  710. if (chunk_state->chunks.size() != number_of_chunks)
  711. return Error::from_string_literal("Inconsistent number of total ICC chunks");
  712. if (chunk_sequence_number == 0)
  713. return Error::from_string_literal("ICC chunk sequence number not 1 based");
  714. u8 index = chunk_sequence_number - 1;
  715. if (index >= chunk_state->chunks.size())
  716. return Error::from_string_literal("ICC chunk sequence number larger than number of chunks");
  717. if (!chunk_state->chunks[index].is_empty())
  718. return Error::from_string_literal("Duplicate ICC chunk at sequence number");
  719. chunk_state->chunks[index] = TRY(ByteBuffer::create_zeroed(bytes_to_read));
  720. TRY(stream.read_until_filled(chunk_state->chunks[index]));
  721. chunk_state->seen_number_of_icc_chunks++;
  722. if (chunk_state->seen_number_of_icc_chunks != chunk_state->chunks.size())
  723. return {};
  724. if (number_of_chunks == 1) {
  725. context.icc_data = move(chunk_state->chunks[0]);
  726. return {};
  727. }
  728. size_t total_size = 0;
  729. for (auto const& chunk : chunk_state->chunks)
  730. total_size += chunk.size();
  731. auto icc_bytes = TRY(ByteBuffer::create_zeroed(total_size));
  732. size_t start = 0;
  733. for (auto const& chunk : chunk_state->chunks) {
  734. memcpy(icc_bytes.data() + start, chunk.data(), chunk.size());
  735. start += chunk.size();
  736. }
  737. context.icc_data = move(icc_bytes);
  738. return {};
  739. }
  740. static ErrorOr<void> read_colour_encoding(Stream& stream, [[maybe_unused]] JPEGLoadingContext& context, int bytes_to_read)
  741. {
  742. // The App 14 segment is application specific in the first JPEG standard.
  743. // However, the Adobe implementation is globally accepted and the value of the color transform
  744. // was latter standardized as a JPEG-1 extension.
  745. // For the structure of the App 14 segment, see:
  746. // https://www.pdfa.org/norm-refs/5116.DCT_Filter.pdf
  747. // 18 Adobe Application-Specific JPEG Marker
  748. // For the value of color_transform, see:
  749. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.872-201206-I!!PDF-E&type=items
  750. // 6.5.3 - APP14 marker segment for colour encoding
  751. if (bytes_to_read < 6)
  752. return Error::from_string_literal("App14 segment too small");
  753. [[maybe_unused]] auto const version = TRY(stream.read_value<u8>());
  754. [[maybe_unused]] u16 const flag0 = TRY(stream.read_value<BigEndian<u16>>());
  755. [[maybe_unused]] u16 const flag1 = TRY(stream.read_value<BigEndian<u16>>());
  756. auto const color_transform = TRY(stream.read_value<u8>());
  757. if (bytes_to_read > 6) {
  758. dbgln_if(JPEG_DEBUG, "Unread bytes in App14 segment: {}", bytes_to_read - 1);
  759. TRY(stream.discard(bytes_to_read - 1));
  760. }
  761. switch (color_transform) {
  762. case 0:
  763. context.color_transform = ColorTransform::CmykOrRgb;
  764. break;
  765. case 1:
  766. context.color_transform = ColorTransform::YCbCr;
  767. break;
  768. case 2:
  769. context.color_transform = ColorTransform::YCCK;
  770. break;
  771. default:
  772. dbgln("0x{:x} is not a specified transform flag value, ignoring", color_transform);
  773. }
  774. return {};
  775. }
  776. static ErrorOr<void> read_app_marker(Stream& stream, JPEGLoadingContext& context, int app_marker_number)
  777. {
  778. // B.2.4.6 - Application data syntax
  779. i32 bytes_to_read = TRY(stream.read_value<BigEndian<u16>>());
  780. if (bytes_to_read <= 2)
  781. return Error::from_string_literal("app marker size too small");
  782. bytes_to_read -= 2;
  783. StringBuilder builder;
  784. for (;;) {
  785. if (bytes_to_read == 0) {
  786. dbgln_if(JPEG_DEBUG, "app marker {} does not start with zero-terminated string", app_marker_number);
  787. return {};
  788. }
  789. auto c = TRY(stream.read_value<char>());
  790. bytes_to_read--;
  791. if (c == '\0')
  792. break;
  793. TRY(builder.try_append(c));
  794. }
  795. auto app_id = TRY(builder.to_string());
  796. if (app_marker_number == 2 && app_id == "ICC_PROFILE"sv)
  797. return read_icc_profile(stream, context, bytes_to_read);
  798. if (app_marker_number == 14 && app_id == "Adobe"sv)
  799. return read_colour_encoding(stream, context, bytes_to_read);
  800. return stream.discard(bytes_to_read);
  801. }
  802. static inline bool validate_luma_and_modify_context(Component const& luma, JPEGLoadingContext& context)
  803. {
  804. if ((luma.hsample_factor == 1 || luma.hsample_factor == 2) && (luma.vsample_factor == 1 || luma.vsample_factor == 2)) {
  805. context.mblock_meta.hpadded_count += luma.hsample_factor == 1 ? 0 : context.mblock_meta.hcount % 2;
  806. context.mblock_meta.vpadded_count += luma.vsample_factor == 1 ? 0 : context.mblock_meta.vcount % 2;
  807. context.mblock_meta.padded_total = context.mblock_meta.hpadded_count * context.mblock_meta.vpadded_count;
  808. // For easy reference to relevant sample factors.
  809. context.hsample_factor = luma.hsample_factor;
  810. context.vsample_factor = luma.vsample_factor;
  811. if constexpr (JPEG_DEBUG) {
  812. dbgln("Horizontal Subsampling Factor: {}", luma.hsample_factor);
  813. dbgln("Vertical Subsampling Factor: {}", luma.vsample_factor);
  814. }
  815. return true;
  816. }
  817. return false;
  818. }
  819. static inline void set_macroblock_metadata(JPEGLoadingContext& context)
  820. {
  821. context.mblock_meta.hcount = (context.frame.width + 7) / 8;
  822. context.mblock_meta.vcount = (context.frame.height + 7) / 8;
  823. context.mblock_meta.hpadded_count = context.mblock_meta.hcount;
  824. context.mblock_meta.vpadded_count = context.mblock_meta.vcount;
  825. context.mblock_meta.total = context.mblock_meta.hcount * context.mblock_meta.vcount;
  826. }
  827. static ErrorOr<void> read_start_of_frame(Stream& stream, JPEGLoadingContext& context)
  828. {
  829. if (context.state == JPEGLoadingContext::FrameDecoded) {
  830. dbgln_if(JPEG_DEBUG, "SOF repeated!");
  831. return Error::from_string_literal("SOF repeated");
  832. }
  833. [[maybe_unused]] u16 const bytes_to_read = TRY(stream.read_value<BigEndian<u16>>());
  834. context.frame.precision = TRY(stream.read_value<u8>());
  835. if (context.frame.precision != 8) {
  836. dbgln_if(JPEG_DEBUG, "SOF precision != 8!");
  837. return Error::from_string_literal("SOF precision != 8");
  838. }
  839. context.frame.height = TRY(stream.read_value<BigEndian<u16>>());
  840. context.frame.width = TRY(stream.read_value<BigEndian<u16>>());
  841. if (!context.frame.width || !context.frame.height) {
  842. dbgln_if(JPEG_DEBUG, "ERROR! Image height: {}, Image width: {}!", context.frame.height, context.frame.width);
  843. return Error::from_string_literal("Image frame height of width null");
  844. }
  845. if (context.frame.width > maximum_width_for_decoded_images || context.frame.height > maximum_height_for_decoded_images) {
  846. dbgln("This JPEG is too large for comfort: {}x{}", context.frame.width, context.frame.height);
  847. return Error::from_string_literal("JPEG too large for comfort");
  848. }
  849. set_macroblock_metadata(context);
  850. auto component_count = TRY(stream.read_value<u8>());
  851. if (component_count != 1 && component_count != 3 && component_count != 4) {
  852. dbgln_if(JPEG_DEBUG, "Unsupported number of components in SOF: {}!", component_count);
  853. return Error::from_string_literal("Unsupported number of components in SOF");
  854. }
  855. for (u8 i = 0; i < component_count; i++) {
  856. Component component;
  857. component.id = TRY(stream.read_value<u8>());
  858. component.index = i;
  859. u8 subsample_factors = TRY(stream.read_value<u8>());
  860. component.hsample_factor = subsample_factors >> 4;
  861. component.vsample_factor = subsample_factors & 0x0F;
  862. if (i == 0) {
  863. // By convention, downsampling is applied only on chroma components. So we should
  864. // hope to see the maximum sampling factor in the luma component.
  865. if (!validate_luma_and_modify_context(component, context)) {
  866. dbgln_if(JPEG_DEBUG, "Unsupported luma subsampling factors: horizontal: {}, vertical: {}",
  867. component.hsample_factor,
  868. component.vsample_factor);
  869. return Error::from_string_literal("Unsupported luma subsampling factors");
  870. }
  871. } else {
  872. if (component.hsample_factor != 1 || component.vsample_factor != 1) {
  873. dbgln_if(JPEG_DEBUG, "Unsupported chroma subsampling factors: horizontal: {}, vertical: {}",
  874. component.hsample_factor,
  875. component.vsample_factor);
  876. return Error::from_string_literal("Unsupported chroma subsampling factors");
  877. }
  878. }
  879. component.qtable_id = TRY(stream.read_value<u8>());
  880. if (component.qtable_id > 1) {
  881. dbgln_if(JPEG_DEBUG, "Unsupported quantization table id: {}!", component.qtable_id);
  882. return Error::from_string_literal("Unsupported quantization table id");
  883. }
  884. context.components.append(move(component));
  885. }
  886. return {};
  887. }
  888. static ErrorOr<void> read_quantization_table(Stream& stream, JPEGLoadingContext& context)
  889. {
  890. u16 bytes_to_read = TRY(stream.read_value<BigEndian<u16>>()) - 2;
  891. while (bytes_to_read > 0) {
  892. u8 const info_byte = TRY(stream.read_value<u8>());
  893. u8 const element_unit_hint = info_byte >> 4;
  894. if (element_unit_hint > 1) {
  895. dbgln_if(JPEG_DEBUG, "Unsupported unit hint in quantization table: {}!", element_unit_hint);
  896. return Error::from_string_literal("Unsupported unit hint in quantization table");
  897. }
  898. u8 const table_id = info_byte & 0x0F;
  899. if (table_id > 1) {
  900. dbgln_if(JPEG_DEBUG, "Unsupported quantization table id: {}!", table_id);
  901. return Error::from_string_literal("Unsupported quantization table id");
  902. }
  903. u32* const table = table_id == 0 ? context.luma_table : context.chroma_table;
  904. for (int i = 0; i < 64; i++) {
  905. if (element_unit_hint == 0)
  906. table[zigzag_map[i]] = TRY(stream.read_value<u8>());
  907. else
  908. table[zigzag_map[i]] = TRY(stream.read_value<BigEndian<u16>>());
  909. }
  910. bytes_to_read -= 1 + (element_unit_hint == 0 ? 64 : 128);
  911. }
  912. if (bytes_to_read != 0) {
  913. dbgln_if(JPEG_DEBUG, "Invalid length for one or more quantization tables!");
  914. return Error::from_string_literal("Invalid length for one or more quantization tables");
  915. }
  916. return {};
  917. }
  918. static ErrorOr<void> skip_segment(Stream& stream)
  919. {
  920. u16 bytes_to_skip = TRY(stream.read_value<BigEndian<u16>>()) - 2;
  921. TRY(stream.discard(bytes_to_skip));
  922. return {};
  923. }
  924. static void dequantize(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks)
  925. {
  926. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  927. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  928. for (u32 i = 0; i < context.components.size(); i++) {
  929. auto& component = context.components[i];
  930. u32 const* table = component.qtable_id == 0 ? context.luma_table : context.chroma_table;
  931. for (u32 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) {
  932. for (u32 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) {
  933. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  934. Macroblock& block = macroblocks[macroblock_index];
  935. auto* block_component = get_component(block, i);
  936. for (u32 k = 0; k < 64; k++)
  937. block_component[k] *= table[k];
  938. }
  939. }
  940. }
  941. }
  942. }
  943. }
  944. static void inverse_dct(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  945. {
  946. static float const m0 = 2.0f * AK::cos(1.0f / 16.0f * 2.0f * AK::Pi<float>);
  947. static float const m1 = 2.0f * AK::cos(2.0f / 16.0f * 2.0f * AK::Pi<float>);
  948. static float const m3 = 2.0f * AK::cos(2.0f / 16.0f * 2.0f * AK::Pi<float>);
  949. static float const m5 = 2.0f * AK::cos(3.0f / 16.0f * 2.0f * AK::Pi<float>);
  950. static float const m2 = m0 - m5;
  951. static float const m4 = m0 + m5;
  952. static float const s0 = AK::cos(0.0f / 16.0f * AK::Pi<float>) * AK::rsqrt(8.0f);
  953. static float const s1 = AK::cos(1.0f / 16.0f * AK::Pi<float>) / 2.0f;
  954. static float const s2 = AK::cos(2.0f / 16.0f * AK::Pi<float>) / 2.0f;
  955. static float const s3 = AK::cos(3.0f / 16.0f * AK::Pi<float>) / 2.0f;
  956. static float const s4 = AK::cos(4.0f / 16.0f * AK::Pi<float>) / 2.0f;
  957. static float const s5 = AK::cos(5.0f / 16.0f * AK::Pi<float>) / 2.0f;
  958. static float const s6 = AK::cos(6.0f / 16.0f * AK::Pi<float>) / 2.0f;
  959. static float const s7 = AK::cos(7.0f / 16.0f * AK::Pi<float>) / 2.0f;
  960. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  961. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  962. for (u32 component_i = 0; component_i < context.components.size(); component_i++) {
  963. auto& component = context.components[component_i];
  964. for (u8 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) {
  965. for (u8 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) {
  966. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  967. Macroblock& block = macroblocks[macroblock_index];
  968. auto* block_component = get_component(block, component_i);
  969. for (u32 k = 0; k < 8; ++k) {
  970. float const g0 = block_component[0 * 8 + k] * s0;
  971. float const g1 = block_component[4 * 8 + k] * s4;
  972. float const g2 = block_component[2 * 8 + k] * s2;
  973. float const g3 = block_component[6 * 8 + k] * s6;
  974. float const g4 = block_component[5 * 8 + k] * s5;
  975. float const g5 = block_component[1 * 8 + k] * s1;
  976. float const g6 = block_component[7 * 8 + k] * s7;
  977. float const g7 = block_component[3 * 8 + k] * s3;
  978. float const f0 = g0;
  979. float const f1 = g1;
  980. float const f2 = g2;
  981. float const f3 = g3;
  982. float const f4 = g4 - g7;
  983. float const f5 = g5 + g6;
  984. float const f6 = g5 - g6;
  985. float const f7 = g4 + g7;
  986. float const e0 = f0;
  987. float const e1 = f1;
  988. float const e2 = f2 - f3;
  989. float const e3 = f2 + f3;
  990. float const e4 = f4;
  991. float const e5 = f5 - f7;
  992. float const e6 = f6;
  993. float const e7 = f5 + f7;
  994. float const e8 = f4 + f6;
  995. float const d0 = e0;
  996. float const d1 = e1;
  997. float const d2 = e2 * m1;
  998. float const d3 = e3;
  999. float const d4 = e4 * m2;
  1000. float const d5 = e5 * m3;
  1001. float const d6 = e6 * m4;
  1002. float const d7 = e7;
  1003. float const d8 = e8 * m5;
  1004. float const c0 = d0 + d1;
  1005. float const c1 = d0 - d1;
  1006. float const c2 = d2 - d3;
  1007. float const c3 = d3;
  1008. float const c4 = d4 + d8;
  1009. float const c5 = d5 + d7;
  1010. float const c6 = d6 - d8;
  1011. float const c7 = d7;
  1012. float const c8 = c5 - c6;
  1013. float const b0 = c0 + c3;
  1014. float const b1 = c1 + c2;
  1015. float const b2 = c1 - c2;
  1016. float const b3 = c0 - c3;
  1017. float const b4 = c4 - c8;
  1018. float const b5 = c8;
  1019. float const b6 = c6 - c7;
  1020. float const b7 = c7;
  1021. block_component[0 * 8 + k] = b0 + b7;
  1022. block_component[1 * 8 + k] = b1 + b6;
  1023. block_component[2 * 8 + k] = b2 + b5;
  1024. block_component[3 * 8 + k] = b3 + b4;
  1025. block_component[4 * 8 + k] = b3 - b4;
  1026. block_component[5 * 8 + k] = b2 - b5;
  1027. block_component[6 * 8 + k] = b1 - b6;
  1028. block_component[7 * 8 + k] = b0 - b7;
  1029. }
  1030. for (u32 l = 0; l < 8; ++l) {
  1031. float const g0 = block_component[l * 8 + 0] * s0;
  1032. float const g1 = block_component[l * 8 + 4] * s4;
  1033. float const g2 = block_component[l * 8 + 2] * s2;
  1034. float const g3 = block_component[l * 8 + 6] * s6;
  1035. float const g4 = block_component[l * 8 + 5] * s5;
  1036. float const g5 = block_component[l * 8 + 1] * s1;
  1037. float const g6 = block_component[l * 8 + 7] * s7;
  1038. float const g7 = block_component[l * 8 + 3] * s3;
  1039. float const f0 = g0;
  1040. float const f1 = g1;
  1041. float const f2 = g2;
  1042. float const f3 = g3;
  1043. float const f4 = g4 - g7;
  1044. float const f5 = g5 + g6;
  1045. float const f6 = g5 - g6;
  1046. float const f7 = g4 + g7;
  1047. float const e0 = f0;
  1048. float const e1 = f1;
  1049. float const e2 = f2 - f3;
  1050. float const e3 = f2 + f3;
  1051. float const e4 = f4;
  1052. float const e5 = f5 - f7;
  1053. float const e6 = f6;
  1054. float const e7 = f5 + f7;
  1055. float const e8 = f4 + f6;
  1056. float const d0 = e0;
  1057. float const d1 = e1;
  1058. float const d2 = e2 * m1;
  1059. float const d3 = e3;
  1060. float const d4 = e4 * m2;
  1061. float const d5 = e5 * m3;
  1062. float const d6 = e6 * m4;
  1063. float const d7 = e7;
  1064. float const d8 = e8 * m5;
  1065. float const c0 = d0 + d1;
  1066. float const c1 = d0 - d1;
  1067. float const c2 = d2 - d3;
  1068. float const c3 = d3;
  1069. float const c4 = d4 + d8;
  1070. float const c5 = d5 + d7;
  1071. float const c6 = d6 - d8;
  1072. float const c7 = d7;
  1073. float const c8 = c5 - c6;
  1074. float const b0 = c0 + c3;
  1075. float const b1 = c1 + c2;
  1076. float const b2 = c1 - c2;
  1077. float const b3 = c0 - c3;
  1078. float const b4 = c4 - c8;
  1079. float const b5 = c8;
  1080. float const b6 = c6 - c7;
  1081. float const b7 = c7;
  1082. block_component[l * 8 + 0] = b0 + b7;
  1083. block_component[l * 8 + 1] = b1 + b6;
  1084. block_component[l * 8 + 2] = b2 + b5;
  1085. block_component[l * 8 + 3] = b3 + b4;
  1086. block_component[l * 8 + 4] = b3 - b4;
  1087. block_component[l * 8 + 5] = b2 - b5;
  1088. block_component[l * 8 + 6] = b1 - b6;
  1089. block_component[l * 8 + 7] = b0 - b7;
  1090. }
  1091. }
  1092. }
  1093. }
  1094. }
  1095. }
  1096. // F.2.1.5 - Inverse DCT (IDCT)
  1097. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  1098. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  1099. for (u8 vfactor_i = 0; vfactor_i < context.vsample_factor; ++vfactor_i) {
  1100. for (u8 hfactor_i = 0; hfactor_i < context.hsample_factor; ++hfactor_i) {
  1101. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1102. for (u8 i = 0; i < 8; ++i) {
  1103. for (u8 j = 0; j < 8; ++j) {
  1104. macroblocks[mb_index].r[i * 8 + j] = clamp(macroblocks[mb_index].r[i * 8 + j] + 128, 0, 255);
  1105. macroblocks[mb_index].g[i * 8 + j] = clamp(macroblocks[mb_index].g[i * 8 + j] + 128, 0, 255);
  1106. macroblocks[mb_index].b[i * 8 + j] = clamp(macroblocks[mb_index].b[i * 8 + j] + 128, 0, 255);
  1107. macroblocks[mb_index].k[i * 8 + j] = clamp(macroblocks[mb_index].b[i * 8 + j] + 128, 0, 255);
  1108. }
  1109. }
  1110. }
  1111. }
  1112. }
  1113. }
  1114. }
  1115. static void ycbcr_to_rgb(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1116. {
  1117. // Conversion from YCbCr to RGB isn't specified in the first JPEG specification but in the JFIF extension:
  1118. // See: https://www.itu.int/rec/dologin_pub.asp?lang=f&id=T-REC-T.871-201105-I!!PDF-E&type=items
  1119. // 7 - Conversion to and from RGB
  1120. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  1121. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  1122. const u32 chroma_block_index = vcursor * context.mblock_meta.hpadded_count + hcursor;
  1123. Macroblock const& chroma = macroblocks[chroma_block_index];
  1124. // Overflows are intentional.
  1125. for (u8 vfactor_i = context.vsample_factor - 1; vfactor_i < context.vsample_factor; --vfactor_i) {
  1126. for (u8 hfactor_i = context.hsample_factor - 1; hfactor_i < context.hsample_factor; --hfactor_i) {
  1127. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1128. auto* y = macroblocks[macroblock_index].y;
  1129. auto* cb = macroblocks[macroblock_index].cb;
  1130. auto* cr = macroblocks[macroblock_index].cr;
  1131. for (u8 i = 7; i < 8; --i) {
  1132. for (u8 j = 7; j < 8; --j) {
  1133. const u8 pixel = i * 8 + j;
  1134. const u32 chroma_pxrow = (i / context.vsample_factor) + 4 * vfactor_i;
  1135. const u32 chroma_pxcol = (j / context.hsample_factor) + 4 * hfactor_i;
  1136. const u32 chroma_pixel = chroma_pxrow * 8 + chroma_pxcol;
  1137. int r = y[pixel] + 1.402f * (chroma.cr[chroma_pixel] - 128);
  1138. int g = y[pixel] - 0.3441f * (chroma.cb[chroma_pixel] - 128) - 0.7141f * (chroma.cr[chroma_pixel] - 128);
  1139. int b = y[pixel] + 1.772f * (chroma.cb[chroma_pixel] - 128);
  1140. y[pixel] = clamp(r, 0, 255);
  1141. cb[pixel] = clamp(g, 0, 255);
  1142. cr[pixel] = clamp(b, 0, 255);
  1143. }
  1144. }
  1145. }
  1146. }
  1147. }
  1148. }
  1149. }
  1150. static void invert_colors_for_adobe_images(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1151. {
  1152. if (!context.color_transform.has_value())
  1153. return;
  1154. // From libjpeg-turbo's libjpeg.txt:
  1155. // https://github.com/libjpeg-turbo/libjpeg-turbo/blob/main/libjpeg.txt
  1156. // CAUTION: it appears that Adobe Photoshop writes inverted data in CMYK JPEG
  1157. // files: 0 represents 100% ink coverage, rather than 0% ink as you'd expect.
  1158. // This is arguably a bug in Photoshop, but if you need to work with Photoshop
  1159. // CMYK files, you will have to deal with it in your application.
  1160. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  1161. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  1162. for (u8 vfactor_i = 0; vfactor_i < context.vsample_factor; ++vfactor_i) {
  1163. for (u8 hfactor_i = 0; hfactor_i < context.hsample_factor; ++hfactor_i) {
  1164. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1165. for (u8 i = 0; i < 8; ++i) {
  1166. for (u8 j = 0; j < 8; ++j) {
  1167. macroblocks[mb_index].r[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].r[i * 8 + j];
  1168. macroblocks[mb_index].g[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].g[i * 8 + j];
  1169. macroblocks[mb_index].b[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].b[i * 8 + j];
  1170. macroblocks[mb_index].k[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].k[i * 8 + j];
  1171. }
  1172. }
  1173. }
  1174. }
  1175. }
  1176. }
  1177. }
  1178. static void cmyk_to_rgb(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1179. {
  1180. invert_colors_for_adobe_images(context, macroblocks);
  1181. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  1182. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  1183. for (u8 vfactor_i = context.vsample_factor - 1; vfactor_i < context.vsample_factor; --vfactor_i) {
  1184. for (u8 hfactor_i = context.hsample_factor - 1; hfactor_i < context.hsample_factor; --hfactor_i) {
  1185. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1186. auto* c = macroblocks[mb_index].y;
  1187. auto* m = macroblocks[mb_index].cb;
  1188. auto* y = macroblocks[mb_index].cr;
  1189. auto* k = macroblocks[mb_index].k;
  1190. for (u8 i = 0; i < 8; ++i) {
  1191. for (u8 j = 0; j < 8; ++j) {
  1192. u8 const pixel = i * 8 + j;
  1193. static constexpr auto max_value = NumericLimits<u8>::max();
  1194. auto const black_component = max_value - k[pixel];
  1195. int const r = ((max_value - c[pixel]) * black_component) / max_value;
  1196. int const g = ((max_value - m[pixel]) * black_component) / max_value;
  1197. int const b = ((max_value - y[pixel]) * black_component) / max_value;
  1198. c[pixel] = clamp(r, 0, max_value);
  1199. m[pixel] = clamp(g, 0, max_value);
  1200. y[pixel] = clamp(b, 0, max_value);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. }
  1206. }
  1207. }
  1208. static void ycck_to_rgb(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1209. {
  1210. // 7 - Conversions between colour encodings
  1211. // YCCK is obtained from CMYK by converting the CMY channels to YCC channel.
  1212. // To convert back into RGB, we only need the 3 first components, which are baseline YCbCr
  1213. ycbcr_to_rgb(context, macroblocks);
  1214. // RGB to CMYK, as mentioned in https://www.smcm.iqfr.csic.es/docs/intel/ipp/ipp_manual/IPPI/ippi_ch15/functn_YCCKToCMYK_JPEG.htm#functn_YCCKToCMYK_JPEG
  1215. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  1216. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  1217. for (u8 vfactor_i = 0; vfactor_i < context.vsample_factor; ++vfactor_i) {
  1218. for (u8 hfactor_i = 0; hfactor_i < context.hsample_factor; ++hfactor_i) {
  1219. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1220. for (u8 i = 0; i < 8; ++i) {
  1221. for (u8 j = 0; j < 8; ++j) {
  1222. macroblocks[mb_index].r[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].r[i * 8 + j];
  1223. macroblocks[mb_index].g[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].g[i * 8 + j];
  1224. macroblocks[mb_index].b[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].b[i * 8 + j];
  1225. }
  1226. }
  1227. }
  1228. }
  1229. }
  1230. }
  1231. cmyk_to_rgb(context, macroblocks);
  1232. }
  1233. static ErrorOr<void> handle_color_transform(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1234. {
  1235. if (context.color_transform.has_value()) {
  1236. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.872-201206-I!!PDF-E&type=items
  1237. // 6.5.3 - APP14 marker segment for colour encoding
  1238. switch (*context.color_transform) {
  1239. case ColorTransform::CmykOrRgb:
  1240. if (context.components.size() == 4) {
  1241. cmyk_to_rgb(context, macroblocks);
  1242. } else if (context.components.size() == 3) {
  1243. // Note: components.size() == 3 means that we have an RGB image, so no color transformation is needed.
  1244. } else {
  1245. return Error::from_string_literal("Wrong number of components for CMYK or RGB, aborting.");
  1246. }
  1247. break;
  1248. case ColorTransform::YCbCr:
  1249. ycbcr_to_rgb(context, macroblocks);
  1250. break;
  1251. case ColorTransform::YCCK:
  1252. ycck_to_rgb(context, macroblocks);
  1253. break;
  1254. }
  1255. return {};
  1256. }
  1257. // No App14 segment is present, assuming :
  1258. // - 1 components means grayscale
  1259. // - 3 components means YCbCr
  1260. // - 4 components means CMYK
  1261. if (context.components.size() == 4)
  1262. cmyk_to_rgb(context, macroblocks);
  1263. if (context.components.size() == 3)
  1264. ycbcr_to_rgb(context, macroblocks);
  1265. if (context.components.size() == 1) {
  1266. // With Cb and Cr being equal to zero, this function assign the Y
  1267. // value (luminosity) to R, G and B. Providing a proper conversion
  1268. // from grayscale to RGB.
  1269. ycbcr_to_rgb(context, macroblocks);
  1270. }
  1271. return {};
  1272. }
  1273. static ErrorOr<void> compose_bitmap(JPEGLoadingContext& context, Vector<Macroblock> const& macroblocks)
  1274. {
  1275. context.bitmap = TRY(Bitmap::create(BitmapFormat::BGRx8888, { context.frame.width, context.frame.height }));
  1276. for (u32 y = context.frame.height - 1; y < context.frame.height; y--) {
  1277. const u32 block_row = y / 8;
  1278. const u32 pixel_row = y % 8;
  1279. for (u32 x = 0; x < context.frame.width; x++) {
  1280. const u32 block_column = x / 8;
  1281. auto& block = macroblocks[block_row * context.mblock_meta.hpadded_count + block_column];
  1282. const u32 pixel_column = x % 8;
  1283. const u32 pixel_index = pixel_row * 8 + pixel_column;
  1284. const Color color { (u8)block.y[pixel_index], (u8)block.cb[pixel_index], (u8)block.cr[pixel_index] };
  1285. context.bitmap->set_pixel(x, y, color);
  1286. }
  1287. }
  1288. return {};
  1289. }
  1290. static bool is_app_marker(Marker const marker)
  1291. {
  1292. return marker >= JPEG_APPN0 && marker <= JPEG_APPN15;
  1293. }
  1294. static bool is_miscellaneous_or_table_marker(Marker const marker)
  1295. {
  1296. // B.2.4 - Table-specification and miscellaneous marker segment syntax
  1297. // See also B.6 - Summary: Figure B.17 – Flow of marker segment
  1298. bool const is_misc = marker == JPEG_COM || marker == JPEG_DRI || is_app_marker(marker);
  1299. bool const is_table = marker == JPEG_DQT || marker == JPEG_DAC || marker == JPEG_DHT;
  1300. return is_misc || is_table;
  1301. }
  1302. static ErrorOr<void> handle_miscellaneous_or_table(Stream& stream, JPEGLoadingContext& context, Marker const marker)
  1303. {
  1304. if (is_app_marker(marker)) {
  1305. TRY(read_app_marker(stream, context, marker - JPEG_APPN0));
  1306. return {};
  1307. }
  1308. switch (marker) {
  1309. case JPEG_COM:
  1310. case JPEG_DAC:
  1311. dbgln_if(JPEG_DEBUG, "TODO: implement marker \"{:x}\"", marker);
  1312. if (auto result = skip_segment(stream); result.is_error()) {
  1313. dbgln_if(JPEG_DEBUG, "Error skipping marker: {:x}!", marker);
  1314. return result.release_error();
  1315. }
  1316. break;
  1317. case JPEG_DHT:
  1318. TRY(read_huffman_table(stream, context));
  1319. break;
  1320. case JPEG_DQT:
  1321. TRY(read_quantization_table(stream, context));
  1322. break;
  1323. case JPEG_DRI:
  1324. TRY(read_restart_interval(stream, context));
  1325. break;
  1326. default:
  1327. dbgln("Unexpected marker: {:x}", marker);
  1328. VERIFY_NOT_REACHED();
  1329. }
  1330. return {};
  1331. }
  1332. static ErrorOr<void> parse_header(Stream& stream, JPEGLoadingContext& context)
  1333. {
  1334. auto marker = TRY(read_marker_at_cursor(stream));
  1335. if (marker != JPEG_SOI) {
  1336. dbgln_if(JPEG_DEBUG, "SOI not found: {:x}!", marker);
  1337. return Error::from_string_literal("SOI not found");
  1338. }
  1339. for (;;) {
  1340. marker = TRY(read_marker_at_cursor(stream));
  1341. if (is_miscellaneous_or_table_marker(marker)) {
  1342. TRY(handle_miscellaneous_or_table(stream, context, marker));
  1343. continue;
  1344. }
  1345. // Set frame type if the marker marks a new frame.
  1346. if (is_frame_marker(marker))
  1347. context.frame.type = static_cast<StartOfFrame::FrameType>(marker & 0xF);
  1348. switch (marker) {
  1349. case JPEG_INVALID:
  1350. case JPEG_RST0:
  1351. case JPEG_RST1:
  1352. case JPEG_RST2:
  1353. case JPEG_RST3:
  1354. case JPEG_RST4:
  1355. case JPEG_RST5:
  1356. case JPEG_RST6:
  1357. case JPEG_RST7:
  1358. case JPEG_SOI:
  1359. case JPEG_EOI:
  1360. dbgln_if(JPEG_DEBUG, "Unexpected marker {:x}!", marker);
  1361. return Error::from_string_literal("Unexpected marker");
  1362. case JPEG_SOF0:
  1363. case JPEG_SOF2:
  1364. TRY(read_start_of_frame(stream, context));
  1365. context.state = JPEGLoadingContext::FrameDecoded;
  1366. return {};
  1367. default:
  1368. if (auto result = skip_segment(stream); result.is_error()) {
  1369. dbgln_if(JPEG_DEBUG, "Error skipping marker: {:x}!", marker);
  1370. return result.release_error();
  1371. }
  1372. break;
  1373. }
  1374. }
  1375. VERIFY_NOT_REACHED();
  1376. }
  1377. static ErrorOr<void> scan_huffman_stream(AK::SeekableStream& stream, HuffmanStreamState& huffman_stream)
  1378. {
  1379. u8 last_byte;
  1380. u8 current_byte = TRY(stream.read_value<u8>());
  1381. for (;;) {
  1382. last_byte = current_byte;
  1383. current_byte = TRY(stream.read_value<u8>());
  1384. if (last_byte == 0xFF) {
  1385. if (current_byte == 0xFF)
  1386. continue;
  1387. if (current_byte == 0x00) {
  1388. current_byte = TRY(stream.read_value<u8>());
  1389. huffman_stream.stream.append(last_byte);
  1390. continue;
  1391. }
  1392. Marker marker = 0xFF00 | current_byte;
  1393. if (marker >= JPEG_RST0 && marker <= JPEG_RST7) {
  1394. huffman_stream.stream.append(marker);
  1395. current_byte = TRY(stream.read_value<u8>());
  1396. continue;
  1397. }
  1398. // Rollback the marker we just read
  1399. TRY(stream.seek(-2, AK::SeekMode::FromCurrentPosition));
  1400. return {};
  1401. } else {
  1402. huffman_stream.stream.append(last_byte);
  1403. }
  1404. }
  1405. VERIFY_NOT_REACHED();
  1406. }
  1407. static ErrorOr<void> decode_header(JPEGLoadingContext& context)
  1408. {
  1409. if (context.state < JPEGLoadingContext::State::HeaderDecoded) {
  1410. if (auto result = parse_header(*context.stream, context); result.is_error()) {
  1411. context.state = JPEGLoadingContext::State::Error;
  1412. return result.release_error();
  1413. }
  1414. if constexpr (JPEG_DEBUG) {
  1415. dbgln("Image width: {}", context.frame.width);
  1416. dbgln("Image height: {}", context.frame.height);
  1417. dbgln("Macroblocks in a row: {}", context.mblock_meta.hpadded_count);
  1418. dbgln("Macroblocks in a column: {}", context.mblock_meta.vpadded_count);
  1419. dbgln("Macroblock meta padded total: {}", context.mblock_meta.padded_total);
  1420. }
  1421. context.state = JPEGLoadingContext::State::HeaderDecoded;
  1422. }
  1423. return {};
  1424. }
  1425. static ErrorOr<Vector<Macroblock>> construct_macroblocks(JPEGLoadingContext& context)
  1426. {
  1427. // B.6 - Summary
  1428. // See: Figure B.16 – Flow of compressed data syntax
  1429. // This function handles the "Multi-scan" loop.
  1430. Vector<Macroblock> macroblocks;
  1431. TRY(macroblocks.try_resize(context.mblock_meta.padded_total));
  1432. Marker marker = TRY(read_marker_at_cursor(*context.stream));
  1433. while (true) {
  1434. if (is_miscellaneous_or_table_marker(marker)) {
  1435. TRY(handle_miscellaneous_or_table(*context.stream, context, marker));
  1436. } else if (marker == JPEG_SOS) {
  1437. TRY(read_start_of_scan(*context.stream, context));
  1438. TRY(scan_huffman_stream(*context.stream, context.current_scan.huffman_stream));
  1439. TRY(decode_huffman_stream(context, macroblocks));
  1440. } else if (marker == JPEG_EOI) {
  1441. return macroblocks;
  1442. } else {
  1443. dbgln_if(JPEG_DEBUG, "Unexpected marker {:x}!", marker);
  1444. return Error::from_string_literal("Unexpected marker");
  1445. }
  1446. marker = TRY(read_marker_at_cursor(*context.stream));
  1447. }
  1448. }
  1449. static ErrorOr<void> decode_jpeg(JPEGLoadingContext& context)
  1450. {
  1451. TRY(decode_header(context));
  1452. auto macroblocks = TRY(construct_macroblocks(context));
  1453. dequantize(context, macroblocks);
  1454. inverse_dct(context, macroblocks);
  1455. TRY(handle_color_transform(context, macroblocks));
  1456. TRY(compose_bitmap(context, macroblocks));
  1457. context.stream.clear();
  1458. return {};
  1459. }
  1460. JPEGImageDecoderPlugin::JPEGImageDecoderPlugin(NonnullOwnPtr<FixedMemoryStream> stream)
  1461. {
  1462. m_context = make<JPEGLoadingContext>();
  1463. m_context->stream = move(stream);
  1464. }
  1465. JPEGImageDecoderPlugin::~JPEGImageDecoderPlugin() = default;
  1466. IntSize JPEGImageDecoderPlugin::size()
  1467. {
  1468. if (m_context->state == JPEGLoadingContext::State::Error)
  1469. return {};
  1470. if (m_context->state >= JPEGLoadingContext::State::FrameDecoded)
  1471. return { m_context->frame.width, m_context->frame.height };
  1472. return {};
  1473. }
  1474. void JPEGImageDecoderPlugin::set_volatile()
  1475. {
  1476. if (m_context->bitmap)
  1477. m_context->bitmap->set_volatile();
  1478. }
  1479. bool JPEGImageDecoderPlugin::set_nonvolatile(bool& was_purged)
  1480. {
  1481. if (!m_context->bitmap)
  1482. return false;
  1483. return m_context->bitmap->set_nonvolatile(was_purged);
  1484. }
  1485. bool JPEGImageDecoderPlugin::initialize()
  1486. {
  1487. return true;
  1488. }
  1489. bool JPEGImageDecoderPlugin::sniff(ReadonlyBytes data)
  1490. {
  1491. return data.size() > 3
  1492. && data.data()[0] == 0xFF
  1493. && data.data()[1] == 0xD8
  1494. && data.data()[2] == 0xFF;
  1495. }
  1496. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGImageDecoderPlugin::create(ReadonlyBytes data)
  1497. {
  1498. auto stream = TRY(try_make<FixedMemoryStream>(data));
  1499. return adopt_nonnull_own_or_enomem(new (nothrow) JPEGImageDecoderPlugin(move(stream)));
  1500. }
  1501. bool JPEGImageDecoderPlugin::is_animated()
  1502. {
  1503. return false;
  1504. }
  1505. size_t JPEGImageDecoderPlugin::loop_count()
  1506. {
  1507. return 0;
  1508. }
  1509. size_t JPEGImageDecoderPlugin::frame_count()
  1510. {
  1511. return 1;
  1512. }
  1513. ErrorOr<ImageFrameDescriptor> JPEGImageDecoderPlugin::frame(size_t index)
  1514. {
  1515. if (index > 0)
  1516. return Error::from_string_literal("JPEGImageDecoderPlugin: Invalid frame index");
  1517. if (m_context->state == JPEGLoadingContext::State::Error)
  1518. return Error::from_string_literal("JPEGImageDecoderPlugin: Decoding failed");
  1519. if (m_context->state < JPEGLoadingContext::State::BitmapDecoded) {
  1520. if (auto result = decode_jpeg(*m_context); result.is_error()) {
  1521. m_context->state = JPEGLoadingContext::State::Error;
  1522. return result.release_error();
  1523. }
  1524. m_context->state = JPEGLoadingContext::State::BitmapDecoded;
  1525. }
  1526. return ImageFrameDescriptor { m_context->bitmap, 0 };
  1527. }
  1528. ErrorOr<Optional<ReadonlyBytes>> JPEGImageDecoderPlugin::icc_data()
  1529. {
  1530. TRY(decode_header(*m_context));
  1531. if (m_context->icc_data.has_value())
  1532. return *m_context->icc_data;
  1533. return OptionalNone {};
  1534. }
  1535. }