JPEGLoader.cpp 61 KB

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