JPEGLoader.cpp 65 KB

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