JPEGLoader.cpp 71 KB

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