JPEGLoader.cpp 76 KB

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