JPEGLoader.cpp 77 KB

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