JPEGLoader.cpp 71 KB

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