JPEGLoader.cpp 77 KB

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