JPEGLoader.cpp 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  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. RefPtr<Gfx::CMYKBitmap> cmyk_bitmap;
  361. u16 dc_restart_interval { 0 };
  362. HashMap<u8, HuffmanTable> dc_tables;
  363. HashMap<u8, HuffmanTable> ac_tables;
  364. Array<i16, 4> previous_dc_values {};
  365. MacroblockMeta mblock_meta;
  366. JPEGStream stream;
  367. JPEGDecoderOptions options;
  368. Optional<ColorTransform> color_transform {};
  369. Optional<ICCMultiChunkState> icc_multi_chunk_state;
  370. Optional<ByteBuffer> icc_data;
  371. };
  372. static inline auto* get_component(Macroblock& block, unsigned component)
  373. {
  374. switch (component) {
  375. case 0:
  376. return block.y;
  377. case 1:
  378. return block.cb;
  379. case 2:
  380. return block.cr;
  381. case 3:
  382. return block.k;
  383. default:
  384. VERIFY_NOT_REACHED();
  385. }
  386. }
  387. static ErrorOr<void> refine_coefficient(Scan& scan, auto& coefficient)
  388. {
  389. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  390. // See the correction bit from rule b.
  391. u8 const bit = TRY(scan.huffman_stream.read_bits(1));
  392. if (bit == 1)
  393. coefficient |= 1 << scan.successive_approximation_low;
  394. return {};
  395. }
  396. enum class JPEGDecodingMode {
  397. Sequential,
  398. Progressive
  399. };
  400. template<JPEGDecodingMode DecodingMode>
  401. static ErrorOr<void> add_dc(JPEGLoadingContext& context, Macroblock& macroblock, ScanComponent const& scan_component)
  402. {
  403. auto maybe_table = context.dc_tables.get(scan_component.dc_destination_id);
  404. if (!maybe_table.has_value()) {
  405. dbgln_if(JPEG_DEBUG, "Unable to find a DC table with id: {}", scan_component.dc_destination_id);
  406. return Error::from_string_literal("Unable to find corresponding DC table");
  407. }
  408. auto& dc_table = maybe_table.value();
  409. auto& scan = *context.current_scan;
  410. auto* select_component = get_component(macroblock, scan_component.component.index);
  411. auto& coefficient = select_component[0];
  412. if (DecodingMode == JPEGDecodingMode::Progressive && scan.successive_approximation_high > 0) {
  413. TRY(refine_coefficient(scan, coefficient));
  414. return {};
  415. }
  416. // For DC coefficients, symbol encodes the length of the coefficient.
  417. auto dc_length = TRY(scan.huffman_stream.next_symbol(dc_table));
  418. // F.1.2.1.2 - Defining Huffman tables for the DC coefficients
  419. // F.1.5.1 - Structure of DC code table for 12-bit sample precision
  420. if ((context.frame.precision == 8 && dc_length > 11)
  421. || (context.frame.precision == 12 && dc_length > 15)) {
  422. dbgln_if(JPEG_DEBUG, "DC coefficient too long: {}!", dc_length);
  423. return Error::from_string_literal("DC coefficient too long");
  424. }
  425. // DC coefficients are encoded as the difference between previous and current DC values.
  426. i16 dc_diff = TRY(scan.huffman_stream.read_bits(dc_length));
  427. // If MSB in diff is 0, the difference is -ve. Otherwise +ve.
  428. if (dc_length != 0 && dc_diff < (1 << (dc_length - 1)))
  429. dc_diff -= (1 << dc_length) - 1;
  430. auto& previous_dc = context.previous_dc_values[scan_component.component.index];
  431. previous_dc += dc_diff;
  432. coefficient = previous_dc << scan.successive_approximation_low;
  433. return {};
  434. }
  435. template<JPEGDecodingMode DecodingMode>
  436. static ALWAYS_INLINE ErrorOr<bool> read_eob(Scan& scan, u32 symbol)
  437. {
  438. // OPTIMIZATION: This is a fast path for sequential JPEGs, these
  439. // only supports EOB with a value of one block.
  440. if constexpr (DecodingMode == JPEGDecodingMode::Sequential)
  441. return symbol == 0x00;
  442. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  443. // Note: We also use it for non-progressive encoding as it supports both EOB and ZRL
  444. if (auto const eob = symbol & 0x0F; eob == 0 && symbol != JPEG_ZRL) {
  445. // We encountered an EOB marker
  446. auto const eob_base = symbol >> 4;
  447. auto const additional_value = TRY(scan.huffman_stream.read_bits(eob_base));
  448. scan.end_of_bands_run_count = additional_value + (1 << eob_base) - 1;
  449. // end_of_bands_run_count is decremented at the end of `build_macroblocks`.
  450. // And we need to now that we reached End of Block in `add_ac`.
  451. ++scan.end_of_bands_run_count;
  452. return true;
  453. }
  454. return false;
  455. }
  456. static bool is_progressive(StartOfFrame::FrameType frame_type)
  457. {
  458. return frame_type == StartOfFrame::FrameType::Progressive_DCT
  459. || frame_type == StartOfFrame::FrameType::Progressive_DCT_Arithmetic
  460. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT
  461. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT_Arithmetic;
  462. }
  463. template<JPEGDecodingMode DecodingMode>
  464. static ErrorOr<void> add_ac(JPEGLoadingContext& context, Macroblock& macroblock, ScanComponent const& scan_component)
  465. {
  466. auto maybe_table = context.ac_tables.get(scan_component.ac_destination_id);
  467. if (!maybe_table.has_value()) {
  468. dbgln_if(JPEG_DEBUG, "Unable to find a AC table with id: {}", scan_component.ac_destination_id);
  469. return Error::from_string_literal("Unable to find corresponding AC table");
  470. }
  471. auto& ac_table = maybe_table.value();
  472. auto* select_component = get_component(macroblock, scan_component.component.index);
  473. auto& scan = *context.current_scan;
  474. // Compute the AC coefficients.
  475. // 0th coefficient is the dc, which is already handled
  476. auto first_coefficient = max(1, scan.spectral_selection_start);
  477. u32 to_skip = 0;
  478. Optional<u8> saved_symbol;
  479. Optional<u8> saved_bit_for_rule_a;
  480. bool in_zrl = false;
  481. for (int j = first_coefficient; j <= scan.spectral_selection_end; ++j) {
  482. auto& coefficient = select_component[zigzag_map[j]];
  483. // AC symbols encode 2 pieces of information, the high 4 bits represent
  484. // number of zeroes to be stuffed before reading the coefficient. Low 4
  485. // bits represent the magnitude of the coefficient.
  486. if (!in_zrl && scan.end_of_bands_run_count == 0 && !saved_symbol.has_value()) {
  487. saved_symbol = TRY(scan.huffman_stream.next_symbol(ac_table));
  488. if (!TRY(read_eob<DecodingMode>(scan, *saved_symbol))) {
  489. to_skip = *saved_symbol >> 4;
  490. in_zrl = *saved_symbol == JPEG_ZRL;
  491. if (in_zrl) {
  492. to_skip++;
  493. saved_symbol.clear();
  494. }
  495. if constexpr (DecodingMode == JPEGDecodingMode::Sequential) {
  496. j += to_skip - 1;
  497. to_skip = 0;
  498. in_zrl = false;
  499. continue;
  500. }
  501. if constexpr (DecodingMode == JPEGDecodingMode::Progressive) {
  502. if (!in_zrl && scan.successive_approximation_high != 0) {
  503. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  504. // Bit sign from rule a
  505. saved_bit_for_rule_a = TRY(scan.huffman_stream.read_bits(1));
  506. }
  507. }
  508. } else if constexpr (DecodingMode == JPEGDecodingMode::Sequential) {
  509. break;
  510. }
  511. }
  512. if constexpr (DecodingMode == JPEGDecodingMode::Progressive) {
  513. if (coefficient != 0) {
  514. TRY(refine_coefficient(scan, coefficient));
  515. continue;
  516. }
  517. }
  518. if (to_skip > 0) {
  519. --to_skip;
  520. if (to_skip == 0)
  521. in_zrl = false;
  522. continue;
  523. }
  524. if (scan.end_of_bands_run_count > 0)
  525. continue;
  526. if (DecodingMode == JPEGDecodingMode::Progressive && scan.successive_approximation_high != 0) {
  527. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  528. if (auto const low_bits = *saved_symbol & 0x0F; low_bits != 1) {
  529. dbgln_if(JPEG_DEBUG, "AC coefficient low bits isn't equal to 1: {}!", low_bits);
  530. return Error::from_string_literal("AC coefficient low bits isn't equal to 1");
  531. }
  532. coefficient = (*saved_bit_for_rule_a == 0 ? -1 : 1) << scan.successive_approximation_low;
  533. saved_bit_for_rule_a.clear();
  534. } else {
  535. // F.1.2.2 - Huffman encoding of AC coefficients
  536. u8 const coeff_length = *saved_symbol & 0x0F;
  537. // F.1.2.2.1 - Structure of AC code table
  538. // F.1.5.2 - Structure of AC code table for 12-bit sample precision
  539. if ((context.frame.precision == 8 && coeff_length > 10)
  540. || (context.frame.precision == 12 && coeff_length > 14)) {
  541. dbgln_if(JPEG_DEBUG, "AC coefficient too long: {}!", coeff_length);
  542. return Error::from_string_literal("AC coefficient too long");
  543. }
  544. if (coeff_length != 0) {
  545. i32 ac_coefficient = TRY(scan.huffman_stream.read_bits(coeff_length));
  546. if (ac_coefficient < (1 << (coeff_length - 1)))
  547. ac_coefficient -= (1 << coeff_length) - 1;
  548. coefficient = ac_coefficient * (1 << scan.successive_approximation_low);
  549. }
  550. }
  551. saved_symbol.clear();
  552. }
  553. if (to_skip > 0) {
  554. dbgln_if(JPEG_DEBUG, "Run-length exceeded boundaries. Cursor: {}, Skipping: {}!", scan.spectral_selection_end + to_skip, to_skip);
  555. return Error::from_string_literal("Run-length exceeded boundaries");
  556. }
  557. return {};
  558. }
  559. /**
  560. * Build the macroblocks possible by reading single (MCU) subsampled pair of CbCr.
  561. * Depending on the sampling factors, we may not see triples of y, cb, cr in that
  562. * order. If sample factors differ from one, we'll read more than one block of y-
  563. * coefficients before we get to read a cb-cr block.
  564. * In the function below, `hcursor` and `vcursor` denote the location of the block
  565. * we're building in the macroblock matrix. `vfactor_i` and `hfactor_i` are cursors
  566. * that iterate over the vertical and horizontal subsampling factors, respectively.
  567. * When we finish one iteration of the innermost loop, we'll have the coefficients
  568. * of one of the components of block at position `macroblock_index`. When the outermost
  569. * loop finishes first iteration, we'll have all the luminance coefficients for all the
  570. * macroblocks that share the chrominance data. Next two iterations (assuming that
  571. * we are dealing with three components) will fill up the blocks with chroma data.
  572. */
  573. template<JPEGDecodingMode DecodingMode>
  574. static ErrorOr<void> build_macroblocks(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks, u32 hcursor, u32 vcursor)
  575. {
  576. for (auto const& scan_component : context.current_scan->components) {
  577. for (u8 vfactor_i = 0; vfactor_i < scan_component.component.sampling_factors.vertical; vfactor_i++) {
  578. for (u8 hfactor_i = 0; hfactor_i < scan_component.component.sampling_factors.horizontal; hfactor_i++) {
  579. // A.2.3 - Interleaved order
  580. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  581. if (!context.current_scan->are_components_interleaved()) {
  582. 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));
  583. // A.2.4 Completion of partial MCU
  584. // If the component is [and only if!] to be interleaved, the encoding process
  585. // shall also extend the number of samples by one or more additional blocks.
  586. // Horizontally
  587. if (macroblock_index >= context.mblock_meta.hcount && macroblock_index % context.mblock_meta.hpadded_count >= context.mblock_meta.hcount)
  588. continue;
  589. // Vertically
  590. if (macroblock_index >= context.mblock_meta.hpadded_count * context.mblock_meta.vcount)
  591. continue;
  592. }
  593. Macroblock& block = macroblocks[macroblock_index];
  594. if constexpr (DecodingMode == JPEGDecodingMode::Sequential) {
  595. TRY(add_dc<DecodingMode>(context, block, scan_component));
  596. TRY(add_ac<DecodingMode>(context, block, scan_component));
  597. } else {
  598. if (context.current_scan->spectral_selection_start == 0)
  599. TRY(add_dc<DecodingMode>(context, block, scan_component));
  600. if (context.current_scan->spectral_selection_end != 0)
  601. TRY(add_ac<DecodingMode>(context, block, scan_component));
  602. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  603. if (context.current_scan->end_of_bands_run_count > 0) {
  604. --context.current_scan->end_of_bands_run_count;
  605. continue;
  606. }
  607. }
  608. }
  609. }
  610. }
  611. return {};
  612. }
  613. static bool is_dct_based(StartOfFrame::FrameType frame_type)
  614. {
  615. return frame_type == StartOfFrame::FrameType::Baseline_DCT
  616. || frame_type == StartOfFrame::FrameType::Extended_Sequential_DCT
  617. || frame_type == StartOfFrame::FrameType::Progressive_DCT
  618. || frame_type == StartOfFrame::FrameType::Differential_Sequential_DCT
  619. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT
  620. || frame_type == StartOfFrame::FrameType::Progressive_DCT_Arithmetic
  621. || frame_type == StartOfFrame::FrameType::Differential_Sequential_DCT_Arithmetic
  622. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT_Arithmetic;
  623. }
  624. static void reset_decoder(JPEGLoadingContext& context)
  625. {
  626. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  627. context.current_scan->end_of_bands_run_count = 0;
  628. // E.2.4 Control procedure for decoding a restart interval
  629. if (is_dct_based(context.frame.type)) {
  630. context.previous_dc_values = {};
  631. return;
  632. }
  633. VERIFY_NOT_REACHED();
  634. }
  635. static ErrorOr<void> decode_huffman_stream(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks)
  636. {
  637. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  638. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  639. u32 i = vcursor * context.mblock_meta.hpadded_count + hcursor;
  640. auto& huffman_stream = context.current_scan->huffman_stream;
  641. if (context.dc_restart_interval > 0) {
  642. if (i != 0 && i % (context.dc_restart_interval * context.sampling_factors.vertical * context.sampling_factors.horizontal) == 0) {
  643. reset_decoder(context);
  644. // Restart markers are stored in byte boundaries. Advance the huffman stream cursor to
  645. // the 0th bit of the next byte.
  646. TRY(huffman_stream.advance_to_byte_boundary());
  647. // Skip the restart marker (RSTn).
  648. TRY(huffman_stream.discard_bits(8));
  649. }
  650. }
  651. auto result = [&]() {
  652. if (is_progressive(context.frame.type))
  653. return build_macroblocks<JPEGDecodingMode::Progressive>(context, macroblocks, hcursor, vcursor);
  654. return build_macroblocks<JPEGDecodingMode::Sequential>(context, macroblocks, hcursor, vcursor);
  655. }();
  656. if (result.is_error()) {
  657. if constexpr (JPEG_DEBUG) {
  658. dbgln("Failed to build Macroblock {}: {}", i, result.error());
  659. dbgln("Huffman stream byte offset {}", context.stream.byte_offset());
  660. }
  661. return result.release_error();
  662. }
  663. }
  664. }
  665. return {};
  666. }
  667. static bool is_frame_marker(Marker const marker)
  668. {
  669. // B.1.1.3 - Marker assignments
  670. bool const is_sof_marker = marker >= JPEG_SOF0 && marker <= JPEG_SOF15;
  671. // Start of frame markers are valid for JPEG_SOF0 to JPEG_SOF15 except number 4, 8 (reserved) and 12.
  672. bool const is_defined_marker = marker != JPEG_DHT && marker != 0xFFC8 && marker != JPEG_DAC;
  673. return is_sof_marker && is_defined_marker;
  674. }
  675. static inline bool is_supported_marker(Marker const marker)
  676. {
  677. if (marker >= JPEG_APPN0 && marker <= JPEG_APPN15) {
  678. if (marker != JPEG_APPN0 && marker != JPEG_APPN14)
  679. dbgln_if(JPEG_DEBUG, "{:#04x} not supported yet. The decoder may fail!", marker);
  680. return true;
  681. }
  682. if (marker >= JPEG_RESERVED1 && marker <= JPEG_RESERVEDD)
  683. return true;
  684. if (marker >= JPEG_RST0 && marker <= JPEG_RST7)
  685. return true;
  686. switch (marker) {
  687. case JPEG_COM:
  688. case JPEG_DHP:
  689. case JPEG_EXP:
  690. case JPEG_DHT:
  691. case JPEG_DQT:
  692. case JPEG_DRI:
  693. case JPEG_EOI:
  694. case JPEG_SOF0:
  695. case JPEG_SOF1:
  696. case JPEG_SOF2:
  697. case JPEG_SOI:
  698. case JPEG_SOS:
  699. return true;
  700. }
  701. if (is_frame_marker(marker))
  702. dbgln_if(JPEG_DEBUG, "Decoding this frame-type (SOF{}) is not currently supported. Decoder will fail!", marker & 0xf);
  703. return false;
  704. }
  705. static inline ErrorOr<Marker> read_marker_at_cursor(JPEGStream& stream)
  706. {
  707. u16 marker = TRY(stream.read_u16());
  708. if (marker == 0xFFFF) {
  709. u8 next { 0xFF };
  710. while (next == 0xFF)
  711. next = TRY(stream.read_u8());
  712. marker = 0xFF00 | next;
  713. }
  714. if (is_supported_marker(marker))
  715. return marker;
  716. return Error::from_string_literal("Reached an unsupported marker");
  717. }
  718. static ErrorOr<u16> read_effective_chunk_size(JPEGStream& stream)
  719. {
  720. // The stored chunk size includes the size of `stored_size` itself.
  721. u16 const stored_size = TRY(stream.read_u16());
  722. if (stored_size < 2)
  723. return Error::from_string_literal("Stored chunk size is too small");
  724. return stored_size - 2;
  725. }
  726. static ErrorOr<void> read_start_of_scan(JPEGStream& stream, JPEGLoadingContext& context)
  727. {
  728. // B.2.3 - Scan header syntax
  729. if (context.state < JPEGLoadingContext::State::FrameDecoded)
  730. return Error::from_string_literal("SOS found before reading a SOF");
  731. [[maybe_unused]] u16 const bytes_to_read = TRY(read_effective_chunk_size(stream));
  732. u8 const component_count = TRY(stream.read_u8());
  733. Scan current_scan(HuffmanStream { context.stream });
  734. Optional<u8> last_read;
  735. u8 component_read = 0;
  736. for (auto& component : context.components) {
  737. // See the Csj paragraph:
  738. // [...] the ordering in the scan header shall follow the ordering in the frame header.
  739. if (component_read == component_count)
  740. break;
  741. if (!last_read.has_value())
  742. last_read = TRY(stream.read_u8());
  743. if (component.id != *last_read)
  744. continue;
  745. u8 const table_ids = TRY(stream.read_u8());
  746. current_scan.components.empend(component, static_cast<u8>(table_ids >> 4), static_cast<u8>(table_ids & 0x0F));
  747. component_read++;
  748. last_read.clear();
  749. }
  750. if constexpr (JPEG_DEBUG) {
  751. StringBuilder builder;
  752. TRY(builder.try_append("Components in scan: "sv));
  753. for (auto const& scan_component : current_scan.components) {
  754. TRY(builder.try_append(TRY(String::number(scan_component.component.id))));
  755. TRY(builder.try_append(' '));
  756. }
  757. dbgln(builder.string_view());
  758. }
  759. current_scan.spectral_selection_start = TRY(stream.read_u8());
  760. current_scan.spectral_selection_end = TRY(stream.read_u8());
  761. auto const successive_approximation = TRY(stream.read_u8());
  762. current_scan.successive_approximation_high = successive_approximation >> 4;
  763. current_scan.successive_approximation_low = successive_approximation & 0x0F;
  764. dbgln_if(JPEG_DEBUG, "Start of Selection: {}, End of Selection: {}, Successive Approximation High: {}, Successive Approximation Low: {}",
  765. current_scan.spectral_selection_start,
  766. current_scan.spectral_selection_end,
  767. current_scan.successive_approximation_high,
  768. current_scan.successive_approximation_low);
  769. 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) {
  770. dbgln_if(JPEG_DEBUG, "ERROR! Start of Selection: {}, End of Selection: {}, Successive Approximation High: {}, Successive Approximation Low: {}!",
  771. current_scan.spectral_selection_start,
  772. current_scan.spectral_selection_end,
  773. current_scan.successive_approximation_high,
  774. current_scan.successive_approximation_low);
  775. return Error::from_string_literal("Spectral selection is not [0,63] or successive approximation is not null");
  776. }
  777. context.current_scan = move(current_scan);
  778. return {};
  779. }
  780. static ErrorOr<void> read_restart_interval(JPEGStream& stream, JPEGLoadingContext& context)
  781. {
  782. // B.2.4.4 - Restart interval definition syntax
  783. u16 bytes_to_read = TRY(read_effective_chunk_size(stream));
  784. if (bytes_to_read != 2) {
  785. dbgln_if(JPEG_DEBUG, "Malformed DRI marker found!");
  786. return Error::from_string_literal("Malformed DRI marker found");
  787. }
  788. context.dc_restart_interval = TRY(stream.read_u16());
  789. dbgln_if(JPEG_DEBUG, "Restart marker: {}", context.dc_restart_interval);
  790. return {};
  791. }
  792. static ErrorOr<void> read_huffman_table(JPEGStream& stream, JPEGLoadingContext& context)
  793. {
  794. // B.2.4.2 - Huffman table-specification syntax
  795. u16 bytes_to_read = TRY(read_effective_chunk_size(stream));
  796. while (bytes_to_read > 0) {
  797. HuffmanTable table;
  798. u8 const table_info = TRY(stream.read_u8());
  799. u8 const table_type = table_info >> 4;
  800. u8 const table_destination_id = table_info & 0x0F;
  801. if (table_type > 1) {
  802. dbgln_if(JPEG_DEBUG, "Unrecognized huffman table: {}!", table_type);
  803. return Error::from_string_literal("Unrecognized huffman table");
  804. }
  805. if ((context.frame.type == StartOfFrame::FrameType::Baseline_DCT && table_destination_id > 1)
  806. || (context.frame.type != StartOfFrame::FrameType::Baseline_DCT && table_destination_id > 3)) {
  807. dbgln_if(JPEG_DEBUG, "Invalid huffman table destination id: {}!", table_destination_id);
  808. return Error::from_string_literal("Invalid huffman table destination id");
  809. }
  810. table.type = table_type;
  811. table.destination_id = table_destination_id;
  812. u32 total_codes = 0;
  813. // Read code counts. At each index K, the value represents the number of K+1 bit codes in this header.
  814. for (int i = 0; i < 16; i++) {
  815. if (i == HuffmanTable::bits_per_cached_code)
  816. table.first_non_cached_code_index = total_codes;
  817. u8 const count = TRY(stream.read_u8());
  818. total_codes += count;
  819. table.code_counts[i] = count;
  820. }
  821. table.codes.ensure_capacity(total_codes);
  822. table.symbols.ensure_capacity(total_codes);
  823. // Read symbols. Read X bytes, where X is the sum of the counts of codes read in the previous step.
  824. for (u32 i = 0; i < total_codes; i++) {
  825. u8 symbol = TRY(stream.read_u8());
  826. table.symbols.append(symbol);
  827. }
  828. TRY(table.generate_codes());
  829. auto& huffman_table = table.type == 0 ? context.dc_tables : context.ac_tables;
  830. huffman_table.set(table.destination_id, table);
  831. bytes_to_read -= 1 + 16 + total_codes;
  832. }
  833. if (bytes_to_read != 0) {
  834. dbgln_if(JPEG_DEBUG, "Extra bytes detected in huffman header!");
  835. return Error::from_string_literal("Extra bytes detected in huffman header");
  836. }
  837. return {};
  838. }
  839. static ErrorOr<void> read_icc_profile(JPEGStream& stream, JPEGLoadingContext& context, int bytes_to_read)
  840. {
  841. // https://www.color.org/technotes/ICC-Technote-ProfileEmbedding.pdf, page 5, "JFIF".
  842. if (bytes_to_read <= 2) {
  843. dbgln_if(JPEG_DEBUG, "icc marker too small");
  844. TRY(stream.discard(bytes_to_read));
  845. return {};
  846. }
  847. auto chunk_sequence_number = TRY(stream.read_u8()); // 1-based
  848. auto number_of_chunks = TRY(stream.read_u8());
  849. bytes_to_read -= 2;
  850. if (!context.icc_multi_chunk_state.has_value())
  851. context.icc_multi_chunk_state.emplace(ICCMultiChunkState { 0, TRY(FixedArray<ByteBuffer>::create(number_of_chunks)) });
  852. auto& chunk_state = context.icc_multi_chunk_state;
  853. u8 index {};
  854. auto const ensure_correctness = [&]() -> ErrorOr<void> {
  855. if (chunk_state->seen_number_of_icc_chunks >= number_of_chunks)
  856. return Error::from_string_literal("Too many ICC chunks");
  857. if (chunk_state->chunks.size() != number_of_chunks)
  858. return Error::from_string_literal("Inconsistent number of total ICC chunks");
  859. if (chunk_sequence_number == 0)
  860. return Error::from_string_literal("ICC chunk sequence number not 1 based");
  861. index = chunk_sequence_number - 1;
  862. if (index >= chunk_state->chunks.size())
  863. return Error::from_string_literal("ICC chunk sequence number larger than number of chunks");
  864. if (!chunk_state->chunks[index].is_empty())
  865. return Error::from_string_literal("Duplicate ICC chunk at sequence number");
  866. return {};
  867. };
  868. if (auto result = ensure_correctness(); result.is_error()) {
  869. dbgln_if(JPEG_DEBUG, "JPEG: {}", result.release_error());
  870. TRY(stream.discard(bytes_to_read));
  871. return {};
  872. }
  873. chunk_state->chunks[index] = TRY(ByteBuffer::create_zeroed(bytes_to_read));
  874. TRY(stream.read_until_filled(chunk_state->chunks[index]));
  875. chunk_state->seen_number_of_icc_chunks++;
  876. if (chunk_state->seen_number_of_icc_chunks != chunk_state->chunks.size())
  877. return {};
  878. if (number_of_chunks == 1) {
  879. context.icc_data = move(chunk_state->chunks[0]);
  880. return {};
  881. }
  882. size_t total_size = 0;
  883. for (auto const& chunk : chunk_state->chunks)
  884. total_size += chunk.size();
  885. auto icc_bytes = TRY(ByteBuffer::create_zeroed(total_size));
  886. size_t start = 0;
  887. for (auto const& chunk : chunk_state->chunks) {
  888. memcpy(icc_bytes.data() + start, chunk.data(), chunk.size());
  889. start += chunk.size();
  890. }
  891. context.icc_data = move(icc_bytes);
  892. return {};
  893. }
  894. static ErrorOr<void> read_colour_encoding(JPEGStream& stream, [[maybe_unused]] JPEGLoadingContext& context, int bytes_to_read)
  895. {
  896. // The App 14 segment is application specific in the first JPEG standard.
  897. // However, the Adobe implementation is globally accepted and the value of the color transform
  898. // was latter standardized as a JPEG-1 extension.
  899. // For the structure of the App 14 segment, see:
  900. // https://www.pdfa.org/norm-refs/5116.DCT_Filter.pdf
  901. // 18 Adobe Application-Specific JPEG Marker
  902. // For the value of color_transform, see:
  903. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.872-201206-I!!PDF-E&type=items
  904. // 6.5.3 - APP14 marker segment for colour encoding
  905. if (bytes_to_read < 6)
  906. return Error::from_string_literal("App14 segment too small");
  907. [[maybe_unused]] auto const version = TRY(stream.read_u8());
  908. [[maybe_unused]] u16 const flag0 = TRY(stream.read_u16());
  909. [[maybe_unused]] u16 const flag1 = TRY(stream.read_u16());
  910. auto const color_transform = TRY(stream.read_u8());
  911. if (bytes_to_read > 6) {
  912. dbgln_if(JPEG_DEBUG, "Unread bytes in App14 segment: {}", bytes_to_read - 6);
  913. TRY(stream.discard(bytes_to_read - 6));
  914. }
  915. switch (color_transform) {
  916. case 0:
  917. context.color_transform = ColorTransform::CmykOrRgb;
  918. break;
  919. case 1:
  920. context.color_transform = ColorTransform::YCbCr;
  921. break;
  922. case 2:
  923. context.color_transform = ColorTransform::YCCK;
  924. break;
  925. default:
  926. dbgln("0x{:x} is not a specified transform flag value, ignoring", color_transform);
  927. }
  928. return {};
  929. }
  930. static ErrorOr<void> read_app_marker(JPEGStream& stream, JPEGLoadingContext& context, int app_marker_number)
  931. {
  932. // B.2.4.6 - Application data syntax
  933. u16 bytes_to_read = TRY(read_effective_chunk_size(stream));
  934. StringBuilder builder;
  935. for (;;) {
  936. if (bytes_to_read == 0) {
  937. dbgln_if(JPEG_DEBUG, "app marker {} does not start with zero-terminated string", app_marker_number);
  938. return {};
  939. }
  940. auto c = TRY(stream.read_u8());
  941. bytes_to_read--;
  942. if (c == '\0')
  943. break;
  944. TRY(builder.try_append(c));
  945. }
  946. auto app_id = TRY(builder.to_string());
  947. if (app_marker_number == 2 && app_id == "ICC_PROFILE"sv)
  948. return read_icc_profile(stream, context, bytes_to_read);
  949. if (app_marker_number == 14 && app_id == "Adobe"sv)
  950. return read_colour_encoding(stream, context, bytes_to_read);
  951. return stream.discard(bytes_to_read);
  952. }
  953. static inline bool validate_luma_and_modify_context(Component const& luma, JPEGLoadingContext& context)
  954. {
  955. if ((luma.sampling_factors.horizontal == 1 || luma.sampling_factors.horizontal == 2) && (luma.sampling_factors.vertical == 1 || luma.sampling_factors.vertical == 2)) {
  956. context.mblock_meta.hpadded_count += luma.sampling_factors.horizontal == 1 ? 0 : context.mblock_meta.hcount % 2;
  957. context.mblock_meta.vpadded_count += luma.sampling_factors.vertical == 1 ? 0 : context.mblock_meta.vcount % 2;
  958. context.mblock_meta.padded_total = context.mblock_meta.hpadded_count * context.mblock_meta.vpadded_count;
  959. // For easy reference to relevant sample factors.
  960. context.sampling_factors = luma.sampling_factors;
  961. return true;
  962. }
  963. return false;
  964. }
  965. static inline void set_macroblock_metadata(JPEGLoadingContext& context)
  966. {
  967. context.mblock_meta.hcount = (context.frame.width + 7) / 8;
  968. context.mblock_meta.vcount = (context.frame.height + 7) / 8;
  969. context.mblock_meta.hpadded_count = context.mblock_meta.hcount;
  970. context.mblock_meta.vpadded_count = context.mblock_meta.vcount;
  971. context.mblock_meta.total = context.mblock_meta.hcount * context.mblock_meta.vcount;
  972. }
  973. static ErrorOr<void> ensure_standard_precision(StartOfFrame const& frame)
  974. {
  975. // B.2.2 - Frame header syntax
  976. // Table B.2 - Frame header parameter sizes and values
  977. if (frame.precision == 8)
  978. return {};
  979. if (frame.type == StartOfFrame::FrameType::Extended_Sequential_DCT && frame.precision == 12)
  980. return {};
  981. if (frame.type == StartOfFrame::FrameType::Progressive_DCT && frame.precision == 12)
  982. return {};
  983. dbgln_if(JPEG_DEBUG, "Unsupported precision: {}, for SOF type: {}!", frame.precision, static_cast<int>(frame.type));
  984. return Error::from_string_literal("Unsupported SOF precision.");
  985. }
  986. static ErrorOr<void> read_start_of_frame(JPEGStream& stream, JPEGLoadingContext& context)
  987. {
  988. if (context.state == JPEGLoadingContext::FrameDecoded) {
  989. dbgln_if(JPEG_DEBUG, "SOF repeated!");
  990. return Error::from_string_literal("SOF repeated");
  991. }
  992. // B.2.2 Frame header syntax
  993. [[maybe_unused]] u16 const bytes_to_read = TRY(read_effective_chunk_size(stream));
  994. context.frame.precision = TRY(stream.read_u8());
  995. TRY(ensure_standard_precision(context.frame));
  996. context.frame.height = TRY(stream.read_u16());
  997. context.frame.width = TRY(stream.read_u16());
  998. if (!context.frame.width || !context.frame.height) {
  999. dbgln_if(JPEG_DEBUG, "ERROR! Image height: {}, Image width: {}!", context.frame.height, context.frame.width);
  1000. return Error::from_string_literal("Image frame height of width null");
  1001. }
  1002. set_macroblock_metadata(context);
  1003. auto component_count = TRY(stream.read_u8());
  1004. if (component_count != 1 && component_count != 3 && component_count != 4) {
  1005. dbgln_if(JPEG_DEBUG, "Unsupported number of components in SOF: {}!", component_count);
  1006. return Error::from_string_literal("Unsupported number of components in SOF");
  1007. }
  1008. for (u8 i = 0; i < component_count; i++) {
  1009. Component component;
  1010. component.id = TRY(stream.read_u8());
  1011. component.index = i;
  1012. u8 subsample_factors = TRY(stream.read_u8());
  1013. component.sampling_factors.horizontal = subsample_factors >> 4;
  1014. component.sampling_factors.vertical = subsample_factors & 0x0F;
  1015. dbgln_if(JPEG_DEBUG, "Component subsampling: {}, {}", component.sampling_factors.horizontal, component.sampling_factors.vertical);
  1016. if (i == 0) {
  1017. // By convention, downsampling is applied only on chroma components. So we should
  1018. // hope to see the maximum sampling factor in the luma component.
  1019. if (!validate_luma_and_modify_context(component, context)) {
  1020. dbgln_if(JPEG_DEBUG, "Unsupported luma subsampling factors: horizontal: {}, vertical: {}",
  1021. component.sampling_factors.horizontal,
  1022. component.sampling_factors.vertical);
  1023. return Error::from_string_literal("Unsupported luma subsampling factors");
  1024. }
  1025. } else {
  1026. // YCCK with just CC subsampled and K matching Y is fine.
  1027. auto const& y_component = context.components[0];
  1028. bool channel_matches_y_factor = component.sampling_factors == y_component.sampling_factors;
  1029. bool k_channel_matches_y = context.color_transform == ColorTransform::YCCK && i == 3 && channel_matches_y_factor;
  1030. if (((component.sampling_factors != SamplingFactors { 1, 1 }) && !k_channel_matches_y) || (i == 3 && !channel_matches_y_factor)) {
  1031. dbgln_if(JPEG_DEBUG, "Unsupported chroma subsampling factors: horizontal: {}, vertical: {}",
  1032. component.sampling_factors.horizontal,
  1033. component.sampling_factors.vertical);
  1034. return Error::from_string_literal("Unsupported chroma subsampling factors");
  1035. }
  1036. }
  1037. component.quantization_table_id = TRY(stream.read_u8());
  1038. context.components.append(move(component));
  1039. }
  1040. return {};
  1041. }
  1042. static ErrorOr<void> read_quantization_table(JPEGStream& stream, JPEGLoadingContext& context)
  1043. {
  1044. // B.2.4.1 - Quantization table-specification syntax
  1045. u16 bytes_to_read = TRY(read_effective_chunk_size(stream));
  1046. while (bytes_to_read > 0) {
  1047. u8 const info_byte = TRY(stream.read_u8());
  1048. u8 const element_unit_hint = info_byte >> 4;
  1049. if (element_unit_hint > 1) {
  1050. dbgln_if(JPEG_DEBUG, "Unsupported unit hint in quantization table: {}!", element_unit_hint);
  1051. return Error::from_string_literal("Unsupported unit hint in quantization table");
  1052. }
  1053. u8 const table_id = info_byte & 0x0F;
  1054. if (table_id > 3) {
  1055. dbgln_if(JPEG_DEBUG, "Unsupported quantization table id: {}!", table_id);
  1056. return Error::from_string_literal("Unsupported quantization table id");
  1057. }
  1058. auto& maybe_table = context.quantization_tables[table_id];
  1059. if (!maybe_table.has_value())
  1060. maybe_table = Array<u16, 64> {};
  1061. auto& table = maybe_table.value();
  1062. for (int i = 0; i < 64; i++) {
  1063. if (element_unit_hint == 0)
  1064. table[zigzag_map[i]] = TRY(stream.read_u8());
  1065. else
  1066. table[zigzag_map[i]] = TRY(stream.read_u16());
  1067. }
  1068. bytes_to_read -= 1 + (element_unit_hint == 0 ? 64 : 128);
  1069. }
  1070. if (bytes_to_read != 0) {
  1071. dbgln_if(JPEG_DEBUG, "Invalid length for one or more quantization tables!");
  1072. return Error::from_string_literal("Invalid length for one or more quantization tables");
  1073. }
  1074. return {};
  1075. }
  1076. static ErrorOr<void> skip_segment(JPEGStream& stream)
  1077. {
  1078. u16 bytes_to_skip = TRY(stream.read_u16()) - 2;
  1079. TRY(stream.discard(bytes_to_skip));
  1080. return {};
  1081. }
  1082. static ErrorOr<void> dequantize(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks)
  1083. {
  1084. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1085. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1086. for (u32 i = 0; i < context.components.size(); i++) {
  1087. auto const& component = context.components[i];
  1088. if (!context.quantization_tables[component.quantization_table_id].has_value()) {
  1089. dbgln_if(JPEG_DEBUG, "Unknown quantization table id: {}!", component.quantization_table_id);
  1090. return Error::from_string_literal("Unknown quantization table id");
  1091. }
  1092. auto const& table = context.quantization_tables[component.quantization_table_id].value();
  1093. for (u32 vfactor_i = 0; vfactor_i < component.sampling_factors.vertical; vfactor_i++) {
  1094. for (u32 hfactor_i = 0; hfactor_i < component.sampling_factors.horizontal; hfactor_i++) {
  1095. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  1096. Macroblock& block = macroblocks[macroblock_index];
  1097. auto* block_component = get_component(block, i);
  1098. for (u32 k = 0; k < 64; k++)
  1099. block_component[k] *= table[k];
  1100. }
  1101. }
  1102. }
  1103. }
  1104. }
  1105. return {};
  1106. }
  1107. static void inverse_dct(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1108. {
  1109. static float const m0 = 2.0f * AK::cos(1.0f / 16.0f * 2.0f * AK::Pi<float>);
  1110. static float const m1 = 2.0f * AK::cos(2.0f / 16.0f * 2.0f * AK::Pi<float>);
  1111. static float const m3 = 2.0f * AK::cos(2.0f / 16.0f * 2.0f * AK::Pi<float>);
  1112. static float const m5 = 2.0f * AK::cos(3.0f / 16.0f * 2.0f * AK::Pi<float>);
  1113. static float const m2 = m0 - m5;
  1114. static float const m4 = m0 + m5;
  1115. static float const s0 = AK::cos(0.0f / 16.0f * AK::Pi<float>) * AK::rsqrt(8.0f);
  1116. static float const s1 = AK::cos(1.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1117. static float const s2 = AK::cos(2.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1118. static float const s3 = AK::cos(3.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1119. static float const s4 = AK::cos(4.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1120. static float const s5 = AK::cos(5.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1121. static float const s6 = AK::cos(6.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1122. static float const s7 = AK::cos(7.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1123. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1124. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1125. for (u32 component_i = 0; component_i < context.components.size(); component_i++) {
  1126. auto& component = context.components[component_i];
  1127. for (u8 vfactor_i = 0; vfactor_i < component.sampling_factors.vertical; vfactor_i++) {
  1128. for (u8 hfactor_i = 0; hfactor_i < component.sampling_factors.horizontal; hfactor_i++) {
  1129. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  1130. Macroblock& block = macroblocks[macroblock_index];
  1131. auto* block_component = get_component(block, component_i);
  1132. for (u32 k = 0; k < 8; ++k) {
  1133. float const g0 = block_component[0 * 8 + k] * s0;
  1134. float const g1 = block_component[4 * 8 + k] * s4;
  1135. float const g2 = block_component[2 * 8 + k] * s2;
  1136. float const g3 = block_component[6 * 8 + k] * s6;
  1137. float const g4 = block_component[5 * 8 + k] * s5;
  1138. float const g5 = block_component[1 * 8 + k] * s1;
  1139. float const g6 = block_component[7 * 8 + k] * s7;
  1140. float const g7 = block_component[3 * 8 + k] * s3;
  1141. float const f0 = g0;
  1142. float const f1 = g1;
  1143. float const f2 = g2;
  1144. float const f3 = g3;
  1145. float const f4 = g4 - g7;
  1146. float const f5 = g5 + g6;
  1147. float const f6 = g5 - g6;
  1148. float const f7 = g4 + g7;
  1149. float const e0 = f0;
  1150. float const e1 = f1;
  1151. float const e2 = f2 - f3;
  1152. float const e3 = f2 + f3;
  1153. float const e4 = f4;
  1154. float const e5 = f5 - f7;
  1155. float const e6 = f6;
  1156. float const e7 = f5 + f7;
  1157. float const e8 = f4 + f6;
  1158. float const d0 = e0;
  1159. float const d1 = e1;
  1160. float const d2 = e2 * m1;
  1161. float const d3 = e3;
  1162. float const d4 = e4 * m2;
  1163. float const d5 = e5 * m3;
  1164. float const d6 = e6 * m4;
  1165. float const d7 = e7;
  1166. float const d8 = e8 * m5;
  1167. float const c0 = d0 + d1;
  1168. float const c1 = d0 - d1;
  1169. float const c2 = d2 - d3;
  1170. float const c3 = d3;
  1171. float const c4 = d4 + d8;
  1172. float const c5 = d5 + d7;
  1173. float const c6 = d6 - d8;
  1174. float const c7 = d7;
  1175. float const c8 = c5 - c6;
  1176. float const b0 = c0 + c3;
  1177. float const b1 = c1 + c2;
  1178. float const b2 = c1 - c2;
  1179. float const b3 = c0 - c3;
  1180. float const b4 = c4 - c8;
  1181. float const b5 = c8;
  1182. float const b6 = c6 - c7;
  1183. float const b7 = c7;
  1184. block_component[0 * 8 + k] = b0 + b7;
  1185. block_component[1 * 8 + k] = b1 + b6;
  1186. block_component[2 * 8 + k] = b2 + b5;
  1187. block_component[3 * 8 + k] = b3 + b4;
  1188. block_component[4 * 8 + k] = b3 - b4;
  1189. block_component[5 * 8 + k] = b2 - b5;
  1190. block_component[6 * 8 + k] = b1 - b6;
  1191. block_component[7 * 8 + k] = b0 - b7;
  1192. }
  1193. for (u32 l = 0; l < 8; ++l) {
  1194. float const g0 = block_component[l * 8 + 0] * s0;
  1195. float const g1 = block_component[l * 8 + 4] * s4;
  1196. float const g2 = block_component[l * 8 + 2] * s2;
  1197. float const g3 = block_component[l * 8 + 6] * s6;
  1198. float const g4 = block_component[l * 8 + 5] * s5;
  1199. float const g5 = block_component[l * 8 + 1] * s1;
  1200. float const g6 = block_component[l * 8 + 7] * s7;
  1201. float const g7 = block_component[l * 8 + 3] * s3;
  1202. float const f0 = g0;
  1203. float const f1 = g1;
  1204. float const f2 = g2;
  1205. float const f3 = g3;
  1206. float const f4 = g4 - g7;
  1207. float const f5 = g5 + g6;
  1208. float const f6 = g5 - g6;
  1209. float const f7 = g4 + g7;
  1210. float const e0 = f0;
  1211. float const e1 = f1;
  1212. float const e2 = f2 - f3;
  1213. float const e3 = f2 + f3;
  1214. float const e4 = f4;
  1215. float const e5 = f5 - f7;
  1216. float const e6 = f6;
  1217. float const e7 = f5 + f7;
  1218. float const e8 = f4 + f6;
  1219. float const d0 = e0;
  1220. float const d1 = e1;
  1221. float const d2 = e2 * m1;
  1222. float const d3 = e3;
  1223. float const d4 = e4 * m2;
  1224. float const d5 = e5 * m3;
  1225. float const d6 = e6 * m4;
  1226. float const d7 = e7;
  1227. float const d8 = e8 * m5;
  1228. float const c0 = d0 + d1;
  1229. float const c1 = d0 - d1;
  1230. float const c2 = d2 - d3;
  1231. float const c3 = d3;
  1232. float const c4 = d4 + d8;
  1233. float const c5 = d5 + d7;
  1234. float const c6 = d6 - d8;
  1235. float const c7 = d7;
  1236. float const c8 = c5 - c6;
  1237. float const b0 = c0 + c3;
  1238. float const b1 = c1 + c2;
  1239. float const b2 = c1 - c2;
  1240. float const b3 = c0 - c3;
  1241. float const b4 = c4 - c8;
  1242. float const b5 = c8;
  1243. float const b6 = c6 - c7;
  1244. float const b7 = c7;
  1245. block_component[l * 8 + 0] = b0 + b7;
  1246. block_component[l * 8 + 1] = b1 + b6;
  1247. block_component[l * 8 + 2] = b2 + b5;
  1248. block_component[l * 8 + 3] = b3 + b4;
  1249. block_component[l * 8 + 4] = b3 - b4;
  1250. block_component[l * 8 + 5] = b2 - b5;
  1251. block_component[l * 8 + 6] = b1 - b6;
  1252. block_component[l * 8 + 7] = b0 - b7;
  1253. }
  1254. }
  1255. }
  1256. }
  1257. }
  1258. }
  1259. // F.2.1.5 - Inverse DCT (IDCT)
  1260. auto const level_shift = 1 << (context.frame.precision - 1);
  1261. auto const max_value = (1 << context.frame.precision) - 1;
  1262. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1263. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1264. for (u8 vfactor_i = 0; vfactor_i < context.sampling_factors.vertical; ++vfactor_i) {
  1265. for (u8 hfactor_i = 0; hfactor_i < context.sampling_factors.horizontal; ++hfactor_i) {
  1266. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1267. for (u8 i = 0; i < 8; ++i) {
  1268. for (u8 j = 0; j < 8; ++j) {
  1269. // FIXME: This just truncate all coefficients, it's an easy way to support (read hack)
  1270. // 12 bits JPEGs without rewriting all color transformations.
  1271. auto const clamp_to_8_bits = [&](u16 color) -> u8 {
  1272. if (context.frame.precision == 8)
  1273. return static_cast<u8>(color);
  1274. return static_cast<u8>(color >> 4);
  1275. };
  1276. macroblocks[mb_index].r[i * 8 + j] = clamp_to_8_bits(clamp(macroblocks[mb_index].r[i * 8 + j] + level_shift, 0, max_value));
  1277. macroblocks[mb_index].g[i * 8 + j] = clamp_to_8_bits(clamp(macroblocks[mb_index].g[i * 8 + j] + level_shift, 0, max_value));
  1278. macroblocks[mb_index].b[i * 8 + j] = clamp_to_8_bits(clamp(macroblocks[mb_index].b[i * 8 + j] + level_shift, 0, max_value));
  1279. macroblocks[mb_index].k[i * 8 + j] = clamp_to_8_bits(clamp(macroblocks[mb_index].k[i * 8 + j] + level_shift, 0, max_value));
  1280. }
  1281. }
  1282. }
  1283. }
  1284. }
  1285. }
  1286. }
  1287. static void ycbcr_to_rgb(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1288. {
  1289. // Conversion from YCbCr to RGB isn't specified in the first JPEG specification but in the JFIF extension:
  1290. // See: https://www.itu.int/rec/dologin_pub.asp?lang=f&id=T-REC-T.871-201105-I!!PDF-E&type=items
  1291. // 7 - Conversion to and from RGB
  1292. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1293. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1294. u32 const chroma_block_index = vcursor * context.mblock_meta.hpadded_count + hcursor;
  1295. Macroblock const& chroma = macroblocks[chroma_block_index];
  1296. // Overflows are intentional.
  1297. for (u8 vfactor_i = context.sampling_factors.vertical - 1; vfactor_i < context.sampling_factors.vertical; --vfactor_i) {
  1298. for (u8 hfactor_i = context.sampling_factors.horizontal - 1; hfactor_i < context.sampling_factors.horizontal; --hfactor_i) {
  1299. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1300. auto* y = macroblocks[macroblock_index].y;
  1301. auto* cb = macroblocks[macroblock_index].cb;
  1302. auto* cr = macroblocks[macroblock_index].cr;
  1303. for (u8 i = 7; i < 8; --i) {
  1304. for (u8 j = 7; j < 8; --j) {
  1305. u8 const pixel = i * 8 + j;
  1306. u32 const chroma_pxrow = (i / context.sampling_factors.vertical) + 4 * vfactor_i;
  1307. u32 const chroma_pxcol = (j / context.sampling_factors.horizontal) + 4 * hfactor_i;
  1308. u32 const chroma_pixel = chroma_pxrow * 8 + chroma_pxcol;
  1309. int r = y[pixel] + 1.402f * (chroma.cr[chroma_pixel] - 128);
  1310. int g = y[pixel] - 0.3441f * (chroma.cb[chroma_pixel] - 128) - 0.7141f * (chroma.cr[chroma_pixel] - 128);
  1311. int b = y[pixel] + 1.772f * (chroma.cb[chroma_pixel] - 128);
  1312. y[pixel] = clamp(r, 0, 255);
  1313. cb[pixel] = clamp(g, 0, 255);
  1314. cr[pixel] = clamp(b, 0, 255);
  1315. }
  1316. }
  1317. }
  1318. }
  1319. }
  1320. }
  1321. }
  1322. static void invert_colors_for_adobe_images(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1323. {
  1324. if (!context.color_transform.has_value())
  1325. return;
  1326. // From libjpeg-turbo's libjpeg.txt:
  1327. // https://github.com/libjpeg-turbo/libjpeg-turbo/blob/main/libjpeg.txt
  1328. // CAUTION: it appears that Adobe Photoshop writes inverted data in CMYK JPEG
  1329. // files: 0 represents 100% ink coverage, rather than 0% ink as you'd expect.
  1330. // This is arguably a bug in Photoshop, but if you need to work with Photoshop
  1331. // CMYK files, you will have to deal with it in your application.
  1332. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1333. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1334. for (u8 vfactor_i = 0; vfactor_i < context.sampling_factors.vertical; ++vfactor_i) {
  1335. for (u8 hfactor_i = 0; hfactor_i < context.sampling_factors.horizontal; ++hfactor_i) {
  1336. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1337. for (u8 i = 0; i < 8; ++i) {
  1338. for (u8 j = 0; j < 8; ++j) {
  1339. macroblocks[mb_index].r[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].r[i * 8 + j];
  1340. macroblocks[mb_index].g[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].g[i * 8 + j];
  1341. macroblocks[mb_index].b[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].b[i * 8 + j];
  1342. macroblocks[mb_index].k[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].k[i * 8 + j];
  1343. }
  1344. }
  1345. }
  1346. }
  1347. }
  1348. }
  1349. }
  1350. static ErrorOr<void> cmyk_to_rgb(JPEGLoadingContext& context)
  1351. {
  1352. VERIFY(context.cmyk_bitmap);
  1353. VERIFY(!context.bitmap);
  1354. context.bitmap = TRY(Bitmap::create(BitmapFormat::BGRx8888, { context.frame.width, context.frame.height }));
  1355. for (int y = 0; y < context.frame.height; ++y) {
  1356. for (int x = 0; x < context.frame.width; ++x) {
  1357. auto const& cmyk = context.cmyk_bitmap->scanline(y)[x];
  1358. u8 k = 255 - cmyk.k;
  1359. context.bitmap->scanline(y)[x] = Color((255 - cmyk.c) * k / 255, (255 - cmyk.m) * k / 255, (255 - cmyk.y) * k / 255).value();
  1360. }
  1361. }
  1362. context.cmyk_bitmap = nullptr;
  1363. return {};
  1364. }
  1365. static void ycck_to_cmyk(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1366. {
  1367. // 7 - Conversions between colour encodings
  1368. // YCCK is obtained from CMYK by converting the CMY channels to YCC channel.
  1369. // To convert back into RGB, we only need the 3 first components, which are baseline YCbCr
  1370. ycbcr_to_rgb(context, macroblocks);
  1371. // 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
  1372. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1373. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1374. for (u8 vfactor_i = 0; vfactor_i < context.sampling_factors.vertical; ++vfactor_i) {
  1375. for (u8 hfactor_i = 0; hfactor_i < context.sampling_factors.horizontal; ++hfactor_i) {
  1376. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1377. for (u8 i = 0; i < 8; ++i) {
  1378. for (u8 j = 0; j < 8; ++j) {
  1379. macroblocks[mb_index].r[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].r[i * 8 + j];
  1380. macroblocks[mb_index].g[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].g[i * 8 + j];
  1381. macroblocks[mb_index].b[i * 8 + j] = NumericLimits<u8>::max() - macroblocks[mb_index].b[i * 8 + j];
  1382. }
  1383. }
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }
  1389. static ErrorOr<void> handle_color_transform(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1390. {
  1391. // Note: This is non-standard but some encoder still add the App14 segment for grayscale images.
  1392. // So let's ignore the color transform value if we only have one component.
  1393. if (context.color_transform.has_value() && context.components.size() != 1) {
  1394. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.872-201206-I!!PDF-E&type=items
  1395. // 6.5.3 - APP14 marker segment for colour encoding
  1396. switch (*context.color_transform) {
  1397. case ColorTransform::CmykOrRgb:
  1398. if (context.components.size() == 4) {
  1399. // Nothing to do here.
  1400. } else if (context.components.size() == 3) {
  1401. // Note: components.size() == 3 means that we have an RGB image, so no color transformation is needed.
  1402. } else {
  1403. return Error::from_string_literal("Wrong number of components for CMYK or RGB, aborting.");
  1404. }
  1405. break;
  1406. case ColorTransform::YCbCr:
  1407. ycbcr_to_rgb(context, macroblocks);
  1408. break;
  1409. case ColorTransform::YCCK:
  1410. ycck_to_cmyk(context, macroblocks);
  1411. break;
  1412. }
  1413. return {};
  1414. }
  1415. // No App14 segment is present, assuming :
  1416. // - 1 components means grayscale
  1417. // - 3 components means YCbCr
  1418. // - 4 components means CMYK (Nothing to do here).
  1419. if (context.components.size() == 3)
  1420. ycbcr_to_rgb(context, macroblocks);
  1421. if (context.components.size() == 1) {
  1422. // With Cb and Cr being equal to zero, this function assign the Y
  1423. // value (luminosity) to R, G and B. Providing a proper conversion
  1424. // from grayscale to RGB.
  1425. ycbcr_to_rgb(context, macroblocks);
  1426. }
  1427. return {};
  1428. }
  1429. static ErrorOr<void> compose_bitmap(JPEGLoadingContext& context, Vector<Macroblock> const& macroblocks)
  1430. {
  1431. context.bitmap = TRY(Bitmap::create(BitmapFormat::BGRx8888, { context.frame.width, context.frame.height }));
  1432. for (u32 y = context.frame.height - 1; y < context.frame.height; y--) {
  1433. u32 const block_row = y / 8;
  1434. u32 const pixel_row = y % 8;
  1435. for (u32 x = 0; x < context.frame.width; x++) {
  1436. u32 const block_column = x / 8;
  1437. auto& block = macroblocks[block_row * context.mblock_meta.hpadded_count + block_column];
  1438. u32 const pixel_column = x % 8;
  1439. u32 const pixel_index = pixel_row * 8 + pixel_column;
  1440. Color const color { (u8)block.y[pixel_index], (u8)block.cb[pixel_index], (u8)block.cr[pixel_index] };
  1441. context.bitmap->set_pixel(x, y, color);
  1442. }
  1443. }
  1444. return {};
  1445. }
  1446. static ErrorOr<void> compose_cmyk_bitmap(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks)
  1447. {
  1448. if (context.options.cmyk == JPEGDecoderOptions::CMYK::Normal)
  1449. invert_colors_for_adobe_images(context, macroblocks);
  1450. context.cmyk_bitmap = TRY(Gfx::CMYKBitmap::create_with_size({ context.frame.width, context.frame.height }));
  1451. for (u32 y = context.frame.height - 1; y < context.frame.height; y--) {
  1452. u32 const block_row = y / 8;
  1453. u32 const pixel_row = y % 8;
  1454. for (u32 x = 0; x < context.frame.width; x++) {
  1455. u32 const block_column = x / 8;
  1456. auto& block = macroblocks[block_row * context.mblock_meta.hpadded_count + block_column];
  1457. u32 const pixel_column = x % 8;
  1458. u32 const pixel_index = pixel_row * 8 + pixel_column;
  1459. 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] };
  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. if (context.components.size() == 4)
  1595. TRY(compose_cmyk_bitmap(context, macroblocks));
  1596. else
  1597. TRY(compose_bitmap(context, macroblocks));
  1598. return {};
  1599. }
  1600. JPEGImageDecoderPlugin::JPEGImageDecoderPlugin(NonnullOwnPtr<JPEGLoadingContext> context)
  1601. : m_context(move(context))
  1602. {
  1603. }
  1604. JPEGImageDecoderPlugin::~JPEGImageDecoderPlugin() = default;
  1605. IntSize JPEGImageDecoderPlugin::size()
  1606. {
  1607. return { m_context->frame.width, m_context->frame.height };
  1608. }
  1609. bool JPEGImageDecoderPlugin::sniff(ReadonlyBytes data)
  1610. {
  1611. return data.size() > 3
  1612. && data.data()[0] == 0xFF
  1613. && data.data()[1] == 0xD8
  1614. && data.data()[2] == 0xFF;
  1615. }
  1616. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGImageDecoderPlugin::create(ReadonlyBytes data)
  1617. {
  1618. return create_with_options(data, {});
  1619. }
  1620. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGImageDecoderPlugin::create_with_options(ReadonlyBytes data, JPEGDecoderOptions options)
  1621. {
  1622. auto stream = TRY(try_make<FixedMemoryStream>(data));
  1623. auto context = TRY(JPEGLoadingContext::create(move(stream), options));
  1624. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JPEGImageDecoderPlugin(move(context))));
  1625. TRY(decode_header(*plugin->m_context));
  1626. return plugin;
  1627. }
  1628. ErrorOr<ImageFrameDescriptor> JPEGImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1629. {
  1630. if (index > 0)
  1631. return Error::from_string_literal("JPEGImageDecoderPlugin: Invalid frame index");
  1632. if (m_context->state == JPEGLoadingContext::State::Error)
  1633. return Error::from_string_literal("JPEGImageDecoderPlugin: Decoding failed");
  1634. if (m_context->state < JPEGLoadingContext::State::BitmapDecoded) {
  1635. if (auto result = decode_jpeg(*m_context); result.is_error()) {
  1636. m_context->state = JPEGLoadingContext::State::Error;
  1637. return result.release_error();
  1638. }
  1639. m_context->state = JPEGLoadingContext::State::BitmapDecoded;
  1640. }
  1641. if (m_context->cmyk_bitmap)
  1642. TRY(cmyk_to_rgb(*m_context));
  1643. return ImageFrameDescriptor { m_context->bitmap, 0 };
  1644. }
  1645. ErrorOr<Optional<ReadonlyBytes>> JPEGImageDecoderPlugin::icc_data()
  1646. {
  1647. if (m_context->icc_data.has_value())
  1648. return *m_context->icc_data;
  1649. return OptionalNone {};
  1650. }
  1651. NaturalFrameFormat JPEGImageDecoderPlugin::natural_frame_format() const
  1652. {
  1653. if (m_context->state == JPEGLoadingContext::State::Error)
  1654. return NaturalFrameFormat::RGB;
  1655. VERIFY(m_context->state >= JPEGLoadingContext::State::HeaderDecoded);
  1656. if (m_context->components.size() == 1)
  1657. return NaturalFrameFormat::Grayscale;
  1658. if (m_context->components.size() == 4)
  1659. return NaturalFrameFormat::CMYK;
  1660. return NaturalFrameFormat::RGB;
  1661. }
  1662. ErrorOr<NonnullRefPtr<CMYKBitmap>> JPEGImageDecoderPlugin::cmyk_frame()
  1663. {
  1664. VERIFY(natural_frame_format() == NaturalFrameFormat::CMYK);
  1665. if (m_context->state < JPEGLoadingContext::State::BitmapDecoded) {
  1666. if (auto result = decode_jpeg(*m_context); result.is_error()) {
  1667. m_context->state = JPEGLoadingContext::State::Error;
  1668. return result.release_error();
  1669. }
  1670. m_context->state = JPEGLoadingContext::State::BitmapDecoded;
  1671. }
  1672. return *m_context->cmyk_bitmap;
  1673. }
  1674. }