JPEGLoader.cpp 73 KB

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