JPEGLoader.cpp 62 KB

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