JPEGLoader.cpp 78 KB

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