JPEGLoader.cpp 77 KB

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