JPEG2000Loader.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. /*
  2. * Copyright (c) 2024, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Enumerate.h>
  8. #include <AK/MemoryStream.h>
  9. #include <LibGfx/ImageFormats/ISOBMFF/JPEG2000Boxes.h>
  10. #include <LibGfx/ImageFormats/ISOBMFF/Reader.h>
  11. #include <LibGfx/ImageFormats/JPEG2000Loader.h>
  12. #include <LibTextCodec/Decoder.h>
  13. // Core coding system spec (.jp2 format): T-REC-T.800-201511-S!!PDF-E.pdf available here:
  14. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.800-201511-S!!PDF-E&type=items
  15. // Extensions (.jpx format): T-REC-T.801-202106-S!!PDF-E.pdf available here:
  16. // https://handle.itu.int/11.1002/1000/14666-en?locatt=format:pdf&auth
  17. // rfc3745 lists the MIME type. It only mentions the jp2_id_string as magic number.
  18. namespace Gfx {
  19. // A JPEG2000 image can be stored in a codestream with markers, similar to a JPEG image,
  20. // or in a JP2 file, which is a container format based on boxes similar to ISOBMFF.
  21. // This is the marker for the codestream version. We don't support this yet.
  22. // If we add support, add a second `"image/jp2"` line to MimeData.cpp for this magic number.
  23. // T.800 Annex A, Codestream syntax, A.2 Information in the marker segments and A.3 Construction of the codestream
  24. [[maybe_unused]] static constexpr u8 marker_id_string[] = { 0xFF, 0x4F, 0xFF, 0x51 };
  25. // This is the marker for the box version.
  26. // T.800 Annex I, JP2 file format syntax, I.5.1 JPEG 2000 Signature box
  27. static constexpr u8 jp2_id_string[] = { 0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A };
  28. // Table A.2 – List of markers and marker segments
  29. // "Delimiting markers and marker segments"
  30. #define J2K_SOC 0xFF4F // "Start of codestream"
  31. #define J2K_SOT 0xFF90 // "Start of tile-part"
  32. #define J2K_SOD 0xFF93 // "Start of data"
  33. #define J2K_EOC 0xFFD9 // "End of codestream"
  34. // "Fixed information marker segments"
  35. #define J2K_SIZ 0xFF51 // "Image and tile size"
  36. // "Functional marker segments"
  37. #define J2K_COD 0xFF52 // "Coding style default"
  38. #define J2K_COC 0xFF53 // "Coding style component"
  39. #define J2K_RGN 0xFF5E // "Region-of-interest"
  40. #define J2K_QCD 0xFF5C // "Quantization default"
  41. #define J2K_QCC 0xFF5D // "Quantization component"
  42. #define J2K_POC 0xFF5F // "Progression order change"
  43. // "Pointer marker segments"
  44. #define J2K_TLM 0xFF55 // "Tile-part lengths"
  45. #define J2K_PLM 0xFF57 // "Packet length, main header"
  46. #define J2K_PLT 0xFF58 // "Packet length, tile-part header"
  47. #define J2K_PPM 0xFF60 // "Packed packet headers, main header"
  48. #define J2K_PPT 0xFF61 // "Packed packet headers, tile-part header"
  49. // "In-bit-stream markers and marker segments"
  50. #define J2K_SOP 0xFF91 // "Start of packet"
  51. #define J2K_EPH 0xFF92 // "End of packet header"
  52. // "Informational marker segments"
  53. #define J2K_CRG 0xFF63 // "Component registration"
  54. #define J2K_COM 0xFF64 // "Comment"
  55. // A.4.2 Start of tile-part (SOT)
  56. struct StartOfTilePart {
  57. // "Tile index. This number refers to the tiles in raster order starting at the number 0."
  58. u16 tile_index { 0 }; // "Isot" in spec.
  59. // "Length, in bytes, from the beginning of the first byte of this SOT marker segment of the tile-part to
  60. // the end of the data of that tile-part. Figure A.16 shows this alignment. Only the last tile-part in the
  61. // codestream may contain a 0 for Psot. If the Psot is 0, this tile-part is assumed to contain all data until
  62. // the EOC marker."
  63. u32 tile_part_length { 0 }; // "Psot" in spec.
  64. // "Tile-part index. There is a specific order required for decoding tile-parts; this index denotes the order
  65. // from 0. If there is only one tile-part for a tile, then this value is zero. The tile-parts of this tile shall
  66. // appear in the codestream in this order, although not necessarily consecutively."
  67. u8 tile_part_index { 0 }; // "TPsot" in spec.
  68. // "Number of tile-parts of a tile in the codestream. Two values are allowed: the correct number of tile-
  69. // parts for that tile and zero. A zero value indicates that the number of tile-parts of this tile is not
  70. // specified in this tile-part.
  71. u8 number_of_tile_parts { 0 }; // "TNsot" in spec.
  72. };
  73. static ErrorOr<StartOfTilePart> read_start_of_tile_part(ReadonlyBytes data)
  74. {
  75. FixedMemoryStream stream { data };
  76. StartOfTilePart sot;
  77. sot.tile_index = TRY(stream.read_value<BigEndian<u16>>());
  78. sot.tile_part_length = TRY(stream.read_value<BigEndian<u32>>());
  79. sot.tile_part_index = TRY(stream.read_value<u8>());
  80. sot.number_of_tile_parts = TRY(stream.read_value<u8>());
  81. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: SOT marker segment: tile_index={}, tile_part_length={}, tile_part_index={}, number_of_tile_parts={}", sot.tile_index, sot.tile_part_length, sot.tile_part_index, sot.number_of_tile_parts);
  82. return sot;
  83. }
  84. // A.5.1 Image and tile size (SIZ)
  85. struct ImageAndTileSize {
  86. // "Denotes capabilities that a decoder needs to properly decode the codestream."
  87. u16 needed_decoder_capabilities { 0 }; // "Rsiz" in spec.
  88. // "Width of the reference grid."
  89. u32 width { 0 }; // "Xsiz" in spec.
  90. // "Height of the reference grid."
  91. u32 height { 0 }; // "Ysiz" in spec.
  92. // "Horizontal offset from the origin of the reference grid to the left side of the image area."
  93. u32 x_offset { 0 }; // "XOsiz" in spec.
  94. // "Vertical offset from the origin of the reference grid to the top side of the image area."
  95. u32 y_offset { 0 }; // "YOsiz" in spec.
  96. // "Width of one reference tile with respect to the reference grid."
  97. u32 tile_width { 0 }; // "XTsiz" in spec.
  98. // "Height of one reference tile with respect to the reference grid."
  99. u32 tile_height { 0 }; // "YTsiz" in spec.
  100. // "Horizontal offset from the origin of the reference grid to the left side of the first tile."
  101. u32 tile_x_offset { 0 }; // "XTOsiz" in spec.
  102. // "Vertical offset from the origin of the reference grid to the top side of the first tile."
  103. u32 tile_y_offset { 0 }; // "YTOsiz" in spec.
  104. // "Csiz" isn't stored in this struct. It corresponds to `components.size()`.
  105. struct ComponentInformation {
  106. // "Precision (depth) in bits and sign of the ith component samples."
  107. u8 depth_and_sign { 0 }; // "Ssiz" in spec.
  108. // Table A.11 – Component Ssiz parameter
  109. u8 bit_depth() const { return (depth_and_sign & 0x7F) + 1; }
  110. bool is_signed() const { return depth_and_sign & 0x80; }
  111. // "Horizontal separation of a sample of the ith component with respect to the reference grid."
  112. u8 horizontal_separation { 0 }; // "XRsiz" in spec.
  113. // "Vertical separation of a sample of the ith component with respect to the reference grid."
  114. u8 vertical_separation { 0 }; // "YRsiz" in spec.
  115. };
  116. Vector<ComponentInformation> components;
  117. };
  118. static ErrorOr<ImageAndTileSize> read_image_and_tile_size(ReadonlyBytes data)
  119. {
  120. FixedMemoryStream stream { data };
  121. ImageAndTileSize siz;
  122. siz.needed_decoder_capabilities = TRY(stream.read_value<BigEndian<u16>>());
  123. siz.width = TRY(stream.read_value<BigEndian<u32>>());
  124. siz.height = TRY(stream.read_value<BigEndian<u32>>());
  125. siz.x_offset = TRY(stream.read_value<BigEndian<u32>>());
  126. siz.y_offset = TRY(stream.read_value<BigEndian<u32>>());
  127. siz.tile_width = TRY(stream.read_value<BigEndian<u32>>());
  128. siz.tile_height = TRY(stream.read_value<BigEndian<u32>>());
  129. siz.tile_x_offset = TRY(stream.read_value<BigEndian<u32>>());
  130. siz.tile_y_offset = TRY(stream.read_value<BigEndian<u32>>());
  131. u16 component_count = TRY(stream.read_value<BigEndian<u16>>()); // "Csiz" in spec.
  132. for (size_t i = 0; i < component_count; ++i) {
  133. ImageAndTileSize::ComponentInformation component;
  134. component.depth_and_sign = TRY(stream.read_value<u8>());
  135. if (component.bit_depth() > 38)
  136. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid component depth");
  137. component.horizontal_separation = TRY(stream.read_value<u8>());
  138. component.vertical_separation = TRY(stream.read_value<u8>());
  139. siz.components.append(component);
  140. }
  141. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: SIZ marker segment: needed_decoder_capabilities={}, width={}, height={}, x_offset={}, y_offset={}, tile_width={}, tile_height={}, tile_x_offset={}, tile_y_offset={}", siz.needed_decoder_capabilities, siz.width, siz.height, siz.x_offset, siz.y_offset, siz.tile_width, siz.tile_height, siz.tile_x_offset, siz.tile_y_offset);
  142. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: SIZ marker segment: {} components:", component_count);
  143. for (auto [i, component] : enumerate(siz.components))
  144. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: SIZ marker segment: component[{}]: is_signed={}, bit_depth={}, horizontal_separation={}, vertical_separation={}", i, component.is_signed(), component.bit_depth(), component.horizontal_separation, component.vertical_separation);
  145. return siz;
  146. }
  147. // A.6.1 Coding style default (COD)
  148. struct CodingStyleDefault {
  149. // Table A.13 – Coding style parameter values for the Scod parameter
  150. bool has_explicit_precinct_size { false };
  151. bool may_use_SOP_marker { false };
  152. bool may_use_EPH_marker { false };
  153. // Table A.16 – Progression order for the SGcod, SPcoc, and Ppoc parameters
  154. enum ProgressionOrder {
  155. LayerResolutionComponentPosition = 0,
  156. ResolutionLayerComponentPosition = 1,
  157. ResolutionPositionComponentLayer = 2,
  158. PositionComponentResolutionLayer = 3,
  159. ComponentPositionResolutionLayer = 4,
  160. };
  161. // Table A.17 – Multiple component transformation for the SGcod parameters
  162. enum MultipleComponentTransformationType {
  163. None = 0,
  164. MultipleComponentTransformationUsed = 1, // See Annex G
  165. };
  166. // Table A.14 – Coding style parameter values of the SGcod parameter
  167. ProgressionOrder progression_order { LayerResolutionComponentPosition };
  168. u16 number_of_layers { 0 };
  169. MultipleComponentTransformationType multiple_component_transformation_type { None };
  170. // Table A.20 – Transformation for the SPcod and SPcoc parameters
  171. enum Transformation {
  172. Irreversible_9_7_Filter = 0,
  173. Reversible_5_3_Filter = 1,
  174. };
  175. // Table A.15 – Coding style parameter values of the SPcod and SPcoc parameters
  176. // "Number of decomposition levels, NL, Zero implies no transformation."
  177. u8 number_of_decomposition_levels { 0 };
  178. u8 code_block_width_exponent { 0 }; // "xcb" in spec; 2 already added.
  179. u8 code_block_height_exponent { 0 }; // "ycb" in spec; 2 already added.
  180. u8 code_block_style { 0 };
  181. Transformation transformation { Irreversible_9_7_Filter };
  182. // Table A.19 – Code-block style for the SPcod and SPcoc parameters
  183. bool uses_selective_arithmetic_coding_bypass() const { return code_block_style & 1; }
  184. bool reset_context_probabilities() const { return code_block_style & 2; }
  185. bool uses_termination_on_each_coding_pass() const { return code_block_style & 4; }
  186. bool uses_vertically_causal_context() const { return code_block_style & 8; }
  187. bool uses_predictable_termination() const { return code_block_style & 0x10; }
  188. bool uses_segmentation_symbols() const { return code_block_style & 0x20; }
  189. // If has_explicit_precinct_size is false, this contains the default { 15, 15 } number_of_decomposition_levels + 1 times.
  190. // If has_explicit_precinct_size is true, this contains number_of_decomposition_levels + 1 explicit values stored in the COD marker segment.
  191. struct PrecinctSize {
  192. u8 PPx { 0 };
  193. u8 PPy { 0 };
  194. };
  195. Vector<PrecinctSize> precinct_sizes;
  196. };
  197. static ErrorOr<CodingStyleDefault> read_coding_style_default(ReadonlyBytes data)
  198. {
  199. FixedMemoryStream stream { data };
  200. CodingStyleDefault cod;
  201. u8 Scod = TRY(stream.read_value<u8>());
  202. cod.has_explicit_precinct_size = Scod & 1;
  203. cod.may_use_SOP_marker = Scod & 2;
  204. cod.may_use_EPH_marker = Scod & 4;
  205. u32 SGcod = TRY(stream.read_value<BigEndian<u32>>());
  206. u8 progression_order = SGcod >> 24;
  207. if (progression_order > 4)
  208. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid progression order");
  209. cod.progression_order = static_cast<CodingStyleDefault::ProgressionOrder>(progression_order);
  210. cod.number_of_layers = (SGcod >> 8) & 0xFFFF;
  211. if (cod.number_of_layers == 0)
  212. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid number of layers");
  213. u8 multiple_component_transformation_type = SGcod & 0xFF;
  214. if (multiple_component_transformation_type > 1)
  215. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid multiple component transformation type");
  216. cod.multiple_component_transformation_type = static_cast<CodingStyleDefault::MultipleComponentTransformationType>(multiple_component_transformation_type);
  217. cod.number_of_decomposition_levels = TRY(stream.read_value<u8>());
  218. if (cod.number_of_decomposition_levels > 32)
  219. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid number of decomposition levels");
  220. // Table A.18 – Width or height exponent of the code-blocks for the SPcod and SPcoc parameters
  221. u8 xcb = (TRY(stream.read_value<u8>()) & 0xF) + 2;
  222. u8 ycb = (TRY(stream.read_value<u8>()) & 0xF) + 2;
  223. if (xcb > 10 || ycb > 10 || xcb + ycb > 12)
  224. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid code block size");
  225. cod.code_block_width_exponent = xcb;
  226. cod.code_block_height_exponent = ycb;
  227. cod.code_block_style = TRY(stream.read_value<u8>());
  228. u8 transformation = TRY(stream.read_value<u8>());
  229. if (transformation > 1)
  230. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid transformation");
  231. cod.transformation = static_cast<CodingStyleDefault::Transformation>(transformation);
  232. if (cod.has_explicit_precinct_size) {
  233. for (size_t i = 0; i < cod.number_of_decomposition_levels + 1u; ++i) {
  234. u8 b = TRY(stream.read_value<u8>());
  235. // Table A.21 – Precinct width and height for the SPcod and SPcoc parameters
  236. CodingStyleDefault::PrecinctSize precinct_size;
  237. precinct_size.PPx = b & 0xF;
  238. precinct_size.PPy = b >> 4;
  239. if ((precinct_size.PPx == 0 || precinct_size.PPy == 0) && i > 0)
  240. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid precinct size");
  241. cod.precinct_sizes.append(precinct_size);
  242. }
  243. } else {
  244. for (size_t i = 0; i < cod.number_of_decomposition_levels + 1u; ++i)
  245. cod.precinct_sizes.append({ 15, 15 });
  246. }
  247. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: COD marker segment: has_explicit_precinct_size={}, may_use_SOP_marker={}, may_use_EPH_marker={}, progression_order={}, number_of_layers={}", cod.has_explicit_precinct_size, cod.may_use_SOP_marker, cod.may_use_EPH_marker, (int)cod.progression_order, cod.number_of_layers);
  248. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: COD marker segment: multiple_component_transformation_type={}, number_of_decomposition_levels={}, code_block_width_exponent={}, code_block_height_exponent={}", (int)cod.multiple_component_transformation_type, cod.number_of_decomposition_levels, cod.code_block_width_exponent, cod.code_block_height_exponent);
  249. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: COD marker segment: code_block_style={}, transformation={}", cod.code_block_style, (int)cod.transformation);
  250. if (cod.has_explicit_precinct_size) {
  251. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: COD marker segment: {} explicit precinct sizes:", cod.precinct_sizes.size());
  252. for (auto [i, precinct_size] : enumerate(cod.precinct_sizes))
  253. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: COD marker segment: precinct_size[{}]: PPx={}, PPy={}", i, precinct_size.PPx, precinct_size.PPy);
  254. }
  255. return cod;
  256. }
  257. // A.6.4 Quantization default (QCD)
  258. struct QuantizationDefault {
  259. enum QuantizationStyle {
  260. NoQuantization = 0,
  261. ScalarDerived = 1,
  262. ScalarExpounded = 2,
  263. };
  264. QuantizationStyle quantization_style { NoQuantization };
  265. u8 number_of_guard_bits { 0 };
  266. struct ReversibleStepSize {
  267. u8 exponent { 0 };
  268. };
  269. struct IrreversibleStepSize {
  270. u16 mantissa { 0 };
  271. u8 exponent { 0 };
  272. };
  273. // Stores a Vector<ReversibleStepSize> if quantization_style is NoQuantization, and a Vector<IrreversibleStepSize> otherwise.
  274. // The size of the vector is >= 3*number_of_decomposition_levels + 1 if quantization_style is not ScalarDerived, and 1 otherwise.
  275. using StepSizeType = Variant<Empty, Vector<ReversibleStepSize>, Vector<IrreversibleStepSize>>;
  276. StepSizeType step_sizes;
  277. };
  278. static ErrorOr<QuantizationDefault> read_quantization_default(ReadonlyBytes data, StringView marker_name = "QCD"sv)
  279. {
  280. FixedMemoryStream stream { data };
  281. QuantizationDefault qcd;
  282. u8 sqcd = TRY(stream.read_value<u8>());
  283. u8 quantization_style = sqcd & 0x1F;
  284. if (quantization_style > 2)
  285. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid quantization style");
  286. qcd.quantization_style = static_cast<QuantizationDefault::QuantizationStyle>(quantization_style);
  287. qcd.number_of_guard_bits = sqcd >> 5;
  288. qcd.step_sizes = TRY([&]() -> ErrorOr<QuantizationDefault::StepSizeType> {
  289. if (quantization_style == QuantizationDefault::NoQuantization) {
  290. // Table A.29 – Reversible step size values for the SPqcd and SPqcc parameters (reversible transform only)
  291. if (data.size() < 2)
  292. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Not enough data for QCD marker segment");
  293. u8 number_of_decomposition_levels = (data.size() - 2) / 3;
  294. Vector<QuantizationDefault::ReversibleStepSize> reversible_step_sizes;
  295. for (size_t i = 0; i < 1u + 3u * number_of_decomposition_levels; ++i)
  296. reversible_step_sizes.append({ static_cast<u8>(TRY(stream.read_value<u8>()) >> 3) });
  297. return reversible_step_sizes;
  298. }
  299. // Table A.30 – Quantization values for the SPqcd and SPqcc parameters (irreversible transformation only)
  300. if (data.size() < 3)
  301. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Not enough data for QCD marker segment");
  302. u8 number_of_decomposition_levels = 0;
  303. if (quantization_style == QuantizationDefault::ScalarExpounded)
  304. number_of_decomposition_levels = (data.size() - 3) / 6;
  305. Vector<QuantizationDefault::IrreversibleStepSize> irreversible_step_sizes;
  306. for (size_t i = 0; i < 1u + 3u * number_of_decomposition_levels; ++i) {
  307. u16 value = TRY(stream.read_value<BigEndian<u16>>());
  308. QuantizationDefault::IrreversibleStepSize step_size;
  309. step_size.mantissa = value & 0x7FF;
  310. step_size.exponent = value >> 11;
  311. irreversible_step_sizes.append(step_size);
  312. }
  313. return irreversible_step_sizes;
  314. }());
  315. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: {} marker segment: quantization_style={}, number_of_guard_bits={}", marker_name, (int)qcd.quantization_style, qcd.number_of_guard_bits);
  316. qcd.step_sizes.visit(
  317. [](Empty) { VERIFY_NOT_REACHED(); },
  318. [&](Vector<QuantizationDefault::ReversibleStepSize> const& step_sizes) {
  319. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: {} marker segment: {} step sizes:", marker_name, step_sizes.size());
  320. for (auto [i, step_size] : enumerate(step_sizes)) {
  321. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: {} marker segment: step_size[{}]: exponent={}", marker_name, i, step_size.exponent);
  322. }
  323. },
  324. [&](Vector<QuantizationDefault::IrreversibleStepSize> const& step_sizes) {
  325. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: {} marker segment: {} step sizes:", marker_name, step_sizes.size());
  326. for (auto [i, step_size] : enumerate(step_sizes)) {
  327. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: {} marker segment: step_size[{}]: mantissa={}, exponent={}", marker_name, i, step_size.mantissa, step_size.exponent);
  328. }
  329. });
  330. return qcd;
  331. }
  332. // A.6.5 Quantization component (QCC)
  333. struct QuantizationComponent {
  334. u16 component_index { 0 }; // "Cqcc" in spec.
  335. QuantizationDefault qcd;
  336. };
  337. static ErrorOr<QuantizationComponent> read_quantization_component(ReadonlyBytes data, size_t number_of_components)
  338. {
  339. FixedMemoryStream stream { data };
  340. QuantizationComponent qcc;
  341. if (number_of_components < 257)
  342. qcc.component_index = TRY(stream.read_value<u8>());
  343. else
  344. qcc.component_index = TRY(stream.read_value<BigEndian<u16>>());
  345. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: QCC marker segment: component_index={}", qcc.component_index);
  346. qcc.qcd = TRY(read_quantization_default(data.slice(TRY(stream.tell())), "QCC"sv));
  347. return qcc;
  348. }
  349. // A.9.2 Comment (COM)
  350. struct Comment {
  351. enum CommentType {
  352. Binary = 0,
  353. ISO_IEC_8859_15 = 1,
  354. };
  355. CommentType type { Binary }; // "Rcom" in spec.
  356. ReadonlyBytes data;
  357. };
  358. static ErrorOr<Comment> read_comment(ReadonlyBytes data)
  359. {
  360. FixedMemoryStream stream { data };
  361. Comment com;
  362. u16 comment_type = TRY(stream.read_value<BigEndian<u16>>());
  363. if (comment_type > 1)
  364. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid comment type");
  365. com.type = static_cast<Comment::CommentType>(comment_type);
  366. com.data = data.slice(TRY(stream.tell()));
  367. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: COM marker segment: comment_type={}, size()={}", (int)com.type, com.data.size());
  368. if (com.type == Comment::ISO_IEC_8859_15)
  369. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: COM marker segment, ISO/IEC 8859-15 text: '{}'", TRY(TextCodec::decoder_for("ISO-8859-1"sv)->to_utf8(StringView { com.data })));
  370. return com;
  371. }
  372. struct TilePartData {
  373. StartOfTilePart sot;
  374. Vector<Comment> coms;
  375. ReadonlyBytes data;
  376. };
  377. struct TileData {
  378. Optional<QuantizationDefault> qcd;
  379. Vector<QuantizationComponent> qccs;
  380. Vector<TilePartData> tile_parts;
  381. };
  382. struct JPEG2000LoadingContext {
  383. enum class State {
  384. NotDecoded = 0,
  385. DecodedTileHeaders,
  386. Error,
  387. };
  388. State state { State::NotDecoded };
  389. ReadonlyBytes codestream_data;
  390. size_t codestream_cursor { 0 };
  391. Optional<ReadonlyBytes> icc_data;
  392. IntSize size;
  393. ISOBMFF::BoxList boxes;
  394. // Data from marker segments:
  395. ImageAndTileSize siz;
  396. CodingStyleDefault cod;
  397. QuantizationDefault qcd;
  398. Vector<QuantizationComponent> qccs;
  399. Vector<Comment> coms;
  400. Vector<TileData> tiles;
  401. };
  402. struct MarkerSegment {
  403. u16 marker;
  404. // OptionalNone for markers that don't have data.
  405. // For markers that do have data, this does not include the marker length data. (`data.size() + 2` is the value of the marker length field.)
  406. Optional<ReadonlyBytes> data;
  407. };
  408. static ErrorOr<u16> peek_marker(JPEG2000LoadingContext& context)
  409. {
  410. if (context.codestream_cursor + 2 > context.codestream_data.size())
  411. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Not enough data for marker");
  412. return *reinterpret_cast<BigEndian<u16> const*>(context.codestream_data.data() + context.codestream_cursor);
  413. }
  414. static ErrorOr<MarkerSegment> read_marker_at_cursor(JPEG2000LoadingContext& context)
  415. {
  416. u16 marker = TRY(peek_marker(context));
  417. // "All markers with the marker code between 0xFF30 and 0xFF3F have no marker segment parameters. They shall be skipped by the decoder."
  418. // "The SOC, SOD and EOC are delimiting markers not marker segments, and have no explicit length information or other parameters."
  419. bool is_marker_segment = !(marker >= 0xFF30 && marker <= 0xFF3F) && marker != J2K_SOC && marker != J2K_SOD && marker != J2K_EOC;
  420. MarkerSegment marker_segment;
  421. marker_segment.marker = marker;
  422. if (is_marker_segment) {
  423. if (context.codestream_cursor + 4 > context.codestream_data.size())
  424. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Not enough data for marker segment length");
  425. u16 marker_length = *reinterpret_cast<BigEndian<u16> const*>(context.codestream_data.data() + context.codestream_cursor + 2);
  426. if (marker_length < 2)
  427. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Marker segment length too small");
  428. if (context.codestream_cursor + 2 + marker_length > context.codestream_data.size())
  429. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Not enough data for marker segment data");
  430. marker_segment.data = ReadonlyBytes { context.codestream_data.data() + context.codestream_cursor + 4, marker_length - 2u };
  431. }
  432. context.codestream_cursor += 2;
  433. if (is_marker_segment)
  434. context.codestream_cursor += 2 + marker_segment.data->size();
  435. return marker_segment;
  436. }
  437. static ErrorOr<void> parse_codestream_main_header(JPEG2000LoadingContext& context)
  438. {
  439. // Figure A.3 – Construction of the main header
  440. // "Required as the first marker"
  441. auto marker = TRY(read_marker_at_cursor(context));
  442. if (marker.marker != J2K_SOC)
  443. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected SOC marker");
  444. // "Required as the second marker segment"
  445. marker = TRY(read_marker_at_cursor(context));
  446. if (marker.marker != J2K_SIZ)
  447. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected SIZ marker");
  448. context.siz = TRY(read_image_and_tile_size(marker.data.value()));
  449. bool saw_COD_marker = false;
  450. bool saw_QCD_marker = false;
  451. while (true) {
  452. u16 marker = TRY(peek_marker(context));
  453. switch (marker) {
  454. case J2K_COD:
  455. case J2K_COC:
  456. case J2K_QCD:
  457. case J2K_QCC:
  458. case J2K_RGN:
  459. case J2K_POC:
  460. case J2K_PPM:
  461. case J2K_TLM:
  462. case J2K_PLM:
  463. case J2K_CRG:
  464. case J2K_COM: {
  465. auto marker = TRY(read_marker_at_cursor(context));
  466. if (marker.marker == J2K_COD) {
  467. if (saw_COD_marker)
  468. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Multiple COD markers in main header");
  469. context.cod = TRY(read_coding_style_default(marker.data.value()));
  470. saw_COD_marker = true;
  471. } else if (marker.marker == J2K_QCD) {
  472. if (saw_QCD_marker)
  473. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Multiple QCD markers in main header");
  474. context.qcd = TRY(read_quantization_default(marker.data.value()));
  475. saw_QCD_marker = true;
  476. } else if (marker.marker == J2K_QCC) {
  477. context.qccs.append(TRY(read_quantization_component(marker.data.value(), context.siz.components.size())));
  478. } else if (marker.marker == J2K_COM) {
  479. context.coms.append(TRY(read_comment(marker.data.value())));
  480. } else {
  481. // FIXME: These are valid main header markers. Parse contents.
  482. dbgln("JPEG2000ImageDecoderPlugin: marker {:#04x} not yet implemented", marker.marker);
  483. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: marker not yet implemented");
  484. }
  485. break;
  486. }
  487. case J2K_SOT: {
  488. // SOT terminates the main header.
  489. // A.4.2: "There shall be at least one SOT in a codestream."
  490. if (!saw_COD_marker)
  491. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Required COD marker not present in main header");
  492. if (!saw_QCD_marker)
  493. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Required QCD marker not present in main header");
  494. // A.6.4: "there is not necessarily a correspondence with the number of sub-bands present because the sub-bands
  495. // can be truncated with no requirement to correct [the QCD] marker segment."
  496. size_t step_sizes_count = context.qcd.step_sizes.visit(
  497. [](Empty) -> size_t { VERIFY_NOT_REACHED(); },
  498. [](Vector<QuantizationDefault::ReversibleStepSize> const& step_sizes) { return step_sizes.size(); },
  499. [](Vector<QuantizationDefault::IrreversibleStepSize> const& step_sizes) { return step_sizes.size(); });
  500. if (context.qcd.quantization_style != QuantizationDefault::ScalarDerived && step_sizes_count < context.cod.number_of_decomposition_levels * 3u + 1u)
  501. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Not enough step sizes for number of decomposition levels");
  502. return {};
  503. }
  504. default:
  505. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Unexpected marker in main header");
  506. }
  507. }
  508. }
  509. static ErrorOr<void> parse_codestream_tile_header(JPEG2000LoadingContext& context)
  510. {
  511. // Figure A.4 – Construction of the first tile-part header of a given tile
  512. // Figure A.5 – Construction of a non-first tile-part header
  513. // "Required as the first marker segment of every tile-part header"
  514. auto tile_start = context.codestream_cursor;
  515. auto marker = TRY(read_marker_at_cursor(context));
  516. if (marker.marker != J2K_SOT)
  517. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected SOT marker");
  518. auto start_of_tile = TRY(read_start_of_tile_part(marker.data.value()));
  519. // FIXME: Store start_of_tile on context somewhere.
  520. context.tiles.resize(max(context.tiles.size(), (size_t)start_of_tile.tile_index + 1));
  521. auto& tile = context.tiles[start_of_tile.tile_index];
  522. if (tile.tile_parts.size() != start_of_tile.tile_part_index)
  523. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Tile part index out of order");
  524. tile.tile_parts.append({});
  525. auto& tile_part = tile.tile_parts.last();
  526. tile_part.sot = start_of_tile;
  527. bool found_start_of_data = false;
  528. while (!found_start_of_data) {
  529. u16 marker = TRY(peek_marker(context));
  530. switch (marker) {
  531. case J2K_SOD:
  532. // "Required as the last marker segment of every tile-part header"
  533. context.codestream_cursor += 2;
  534. found_start_of_data = true;
  535. break;
  536. case J2K_COD:
  537. case J2K_COC:
  538. case J2K_QCD:
  539. case J2K_QCC:
  540. case J2K_RGN:
  541. if (start_of_tile.tile_part_index != 0)
  542. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: COD, COC, QCD, QCC, RGN markers are only valid in the first tile-part header");
  543. [[fallthrough]];
  544. case J2K_POC:
  545. case J2K_PPT:
  546. case J2K_PLT:
  547. case J2K_COM: {
  548. auto marker = TRY(read_marker_at_cursor(context));
  549. if (marker.marker == J2K_QCD) {
  550. if (tile.qcd.has_value())
  551. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Multiple QCD markers in tile header");
  552. tile.qcd = TRY(read_quantization_default(marker.data.value()));
  553. } else if (marker.marker == J2K_QCC) {
  554. tile.qccs.append(TRY(read_quantization_component(marker.data.value(), context.siz.components.size())));
  555. } else if (marker.marker == J2K_COM) {
  556. tile_part.coms.append(TRY(read_comment(marker.data.value())));
  557. } else {
  558. // FIXME: These are valid main header markers. Parse contents.
  559. dbgln("JPEG2000ImageDecoderPlugin: marker {:#04x} not yet implemented in tile header", marker.marker);
  560. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: marker not yet implemented in tile header");
  561. }
  562. break;
  563. }
  564. default:
  565. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Unexpected marker in tile header");
  566. }
  567. }
  568. u32 tile_bitstream_length;
  569. if (start_of_tile.tile_part_length == 0) {
  570. // Leave room for EOC marker.
  571. if (context.codestream_data.size() - context.codestream_cursor < 2)
  572. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Not enough data for EOC marker");
  573. tile_bitstream_length = context.codestream_data.size() - context.codestream_cursor - 2;
  574. } else {
  575. u32 tile_header_length = context.codestream_cursor - tile_start;
  576. if (start_of_tile.tile_part_length < tile_header_length)
  577. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid tile part length");
  578. tile_bitstream_length = start_of_tile.tile_part_length - tile_header_length;
  579. }
  580. if (context.codestream_cursor + tile_bitstream_length > context.codestream_data.size())
  581. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Not enough data for tile bitstream");
  582. tile_part.data = context.codestream_data.slice(context.codestream_cursor, tile_bitstream_length);
  583. context.codestream_cursor += tile_bitstream_length;
  584. dbgln_if(JPEG2000_DEBUG, "JPEG2000ImageDecoderPlugin: Tile bitstream length: {}", tile_bitstream_length);
  585. return {};
  586. }
  587. static ErrorOr<void> parse_codestream_tile_headers(JPEG2000LoadingContext& context)
  588. {
  589. while (true) {
  590. auto marker = TRY(peek_marker(context));
  591. if (marker == J2K_EOC) {
  592. context.codestream_cursor += 2;
  593. break;
  594. }
  595. TRY(parse_codestream_tile_header(context));
  596. }
  597. if (context.codestream_cursor < context.codestream_data.size())
  598. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Unexpected data after EOC marker");
  599. return {};
  600. }
  601. static ErrorOr<void> decode_jpeg2000_header(JPEG2000LoadingContext& context, ReadonlyBytes data)
  602. {
  603. if (!JPEG2000ImageDecoderPlugin::sniff(data))
  604. return Error::from_string_literal("JPEG2000LoadingContext: Invalid JPEG2000 header");
  605. auto reader = TRY(Gfx::ISOBMFF::Reader::create(TRY(try_make<FixedMemoryStream>(data))));
  606. context.boxes = TRY(reader.read_entire_file());
  607. // I.2.2 File organization
  608. // "A particular order of those boxes in the file is not generally implied. However, the JPEG 2000 Signature box
  609. // shall be the first box in a JP2 file, the File Type box shall immediately follow the JPEG 2000 Signature box
  610. // and the JP2 Header box shall fall before the Contiguous Codestream box."
  611. if (context.boxes.size() < 4)
  612. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected at least four boxes");
  613. // Required toplevel boxes: signature box, file type box, jp2 header box, contiguous codestream box.
  614. if (context.boxes[0]->box_type() != ISOBMFF::BoxType::JPEG2000SignatureBox)
  615. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected JPEG2000SignatureBox as first box");
  616. if (context.boxes[1]->box_type() != ISOBMFF::BoxType::FileTypeBox)
  617. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected FileTypeBox as second box");
  618. Optional<size_t> jp2_header_box_index;
  619. Optional<size_t> contiguous_codestream_box_index;
  620. for (size_t i = 2; i < context.boxes.size(); ++i) {
  621. if (context.boxes[i]->box_type() == ISOBMFF::BoxType::JPEG2000HeaderBox) {
  622. // "Within a JP2 file, there shall be one and only one JP2 Header box."
  623. if (jp2_header_box_index.has_value())
  624. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Multiple JP2 Header boxes");
  625. jp2_header_box_index = i;
  626. }
  627. if (context.boxes[i]->box_type() == ISOBMFF::BoxType::JPEG2000ContiguousCodestreamBox && !contiguous_codestream_box_index.has_value()) {
  628. // "a conforming reader shall ignore all codestreams after the first codestream found in the file.
  629. // Contiguous Codestream boxes may be found anywhere in the file except before the JP2 Header box."
  630. contiguous_codestream_box_index = i;
  631. if (!jp2_header_box_index.has_value() || contiguous_codestream_box_index.value() < jp2_header_box_index.value())
  632. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: JP2 Header box must come before Contiguous Codestream box");
  633. }
  634. }
  635. if (!jp2_header_box_index.has_value())
  636. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected JP2 Header box");
  637. if (!contiguous_codestream_box_index.has_value())
  638. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected Contiguous Codestream box");
  639. // FIXME: JPEG2000ContiguousCodestreamBox makes a copy of the codestream data. That's too heavy for header scanning.
  640. // Add a mode to ISOBMFF::Reader where it only stores offsets for the codestream data and the ICC profile.
  641. auto const& codestream_box = static_cast<ISOBMFF::JPEG2000ContiguousCodestreamBox const&>(*context.boxes[contiguous_codestream_box_index.value()]);
  642. context.codestream_data = codestream_box.codestream.bytes();
  643. // Required child boxes of the jp2 header box: image header box, color box.
  644. Optional<size_t> image_header_box_index;
  645. Optional<size_t> color_header_box_index;
  646. auto const& header_box = static_cast<ISOBMFF::JPEG2000HeaderBox const&>(*context.boxes[jp2_header_box_index.value()]);
  647. for (size_t i = 0; i < header_box.child_boxes().size(); ++i) {
  648. auto const& subbox = header_box.child_boxes()[i];
  649. if (subbox->box_type() == ISOBMFF::BoxType::JPEG2000ImageHeaderBox) {
  650. if (image_header_box_index.has_value())
  651. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Multiple Image Header boxes");
  652. image_header_box_index = i;
  653. }
  654. if (subbox->box_type() == ISOBMFF::BoxType::JPEG2000ColorSpecificationBox) {
  655. // T.800 says there should be just one 'colr' box, but T.801 allows several and says to pick the one with highest precedence.
  656. bool use_this_color_box;
  657. if (!color_header_box_index.has_value()) {
  658. use_this_color_box = true;
  659. } else {
  660. auto const& new_header_box = static_cast<ISOBMFF::JPEG2000ColorSpecificationBox const&>(*header_box.child_boxes()[i]);
  661. auto const& current_color_box = static_cast<ISOBMFF::JPEG2000ColorSpecificationBox const&>(*header_box.child_boxes()[color_header_box_index.value()]);
  662. use_this_color_box = new_header_box.precedence > current_color_box.precedence;
  663. }
  664. if (use_this_color_box)
  665. color_header_box_index = i;
  666. }
  667. }
  668. if (!image_header_box_index.has_value())
  669. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected Image Header box");
  670. if (!color_header_box_index.has_value())
  671. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Expected Color Specification box");
  672. auto const& image_header_box = static_cast<ISOBMFF::JPEG2000ImageHeaderBox const&>(*header_box.child_boxes()[image_header_box_index.value()]);
  673. context.size = { image_header_box.width, image_header_box.height };
  674. auto const& color_header_box = static_cast<ISOBMFF::JPEG2000ColorSpecificationBox const&>(*header_box.child_boxes()[color_header_box_index.value()]);
  675. if (color_header_box.method == 2 || color_header_box.method == 3)
  676. context.icc_data = color_header_box.icc_data.bytes();
  677. TRY(parse_codestream_main_header(context));
  678. auto size_from_siz = IntSize { context.siz.width, context.siz.height };
  679. if (size_from_siz != context.size) {
  680. // FIXME: If this is common, warn and use size from SIZ marker.
  681. dbgln("JPEG2000ImageDecoderPlugin: Image size from SIZ marker ({}) does not match image size from JP2 header ({})", size_from_siz, context.size);
  682. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Image size from SIZ marker does not match image size from JP2 header");
  683. }
  684. return {};
  685. }
  686. namespace JPEG2000 {
  687. // Tag trees are used to store the code-block inclusion bits and the zero bit-plane information.
  688. // B.10.2 Tag trees
  689. // "At every node of this tree the minimum integer of the (up to four) nodes below it is recorded. [...]
  690. // Level 0 is the lowest level of the tag tree; it contains the top node. [...]
  691. // Each node has a [...] current value, [...] initialized to zero. A 0 bit in the tag tree means that the minimum
  692. // (or the value in the case of the highest level) is larger than the current value and a 1 bit means that the minimum
  693. // (or the value in the case of the highest level) is equal to the current value.
  694. // For each contiguous 0 bit in the tag tree the current value is incremented by one.
  695. // Nodes at higher levels cannot be coded until lower level node values are fixed (i.e, a 1 bit is coded). [...]
  696. // Only the information needed for the current code-block is stored at the current point in the packet header."
  697. // The example in Figure B.13 / Table B.5 is useful to understand what exactly "only the information needed" means.
  698. struct TagTreeNode {
  699. u32 value { 0 };
  700. enum State {
  701. Pending,
  702. Final,
  703. };
  704. State state { Pending };
  705. Array<OwnPtr<TagTreeNode>, 4> children {};
  706. u32 level { 0 }; // 0 for leaf nodes, 1 for the next level, etc.
  707. bool is_leaf() const { return level == 0; }
  708. ErrorOr<u32> read_value(u32 x, u32 y, Function<ErrorOr<bool>()> const& read_bit, u32 start_value, Optional<u32> stop_at = {})
  709. {
  710. value = max(value, start_value);
  711. while (true) {
  712. if (stop_at.has_value() && value == stop_at.value())
  713. return value;
  714. if (state == Final) {
  715. if (is_leaf())
  716. return value;
  717. u32 x_index = (x >> (level - 1)) & 1;
  718. u32 y_index = (y >> (level - 1)) & 1;
  719. return children[y_index * 2 + x_index]->read_value(x, y, read_bit, value, stop_at);
  720. }
  721. bool bit = TRY(read_bit());
  722. if (!bit)
  723. value++;
  724. else
  725. state = Final;
  726. }
  727. }
  728. static ErrorOr<NonnullOwnPtr<TagTreeNode>> create(u32 x_count, u32 y_count, u32 level)
  729. {
  730. VERIFY(x_count > 0);
  731. VERIFY(y_count > 0);
  732. auto node = TRY(try_make<TagTreeNode>());
  733. node->level = level;
  734. if (node->is_leaf()) {
  735. VERIFY(x_count == 1);
  736. VERIFY(y_count == 1);
  737. return node;
  738. }
  739. VERIFY(x_count > 1 || y_count > 1);
  740. u32 top_left_x_child_count = min(x_count, 1u << (max(level, 1) - 1));
  741. u32 top_left_y_child_count = min(y_count, 1u << (max(level, 1) - 1));
  742. for (u32 y = 0; y < 2; ++y) {
  743. for (u32 x = 0; x < 2; ++x) {
  744. u32 child_x_count = x == 1 ? x_count - top_left_x_child_count : top_left_x_child_count;
  745. u32 child_y_count = y == 1 ? y_count - top_left_y_child_count : top_left_y_child_count;
  746. if (child_x_count == 0 || child_y_count == 0)
  747. continue;
  748. node->children[y * 2 + x] = TRY(create(child_x_count, child_y_count, level - 1));
  749. }
  750. }
  751. return node;
  752. }
  753. };
  754. TagTree::TagTree(NonnullOwnPtr<TagTreeNode> root)
  755. : m_root(move(root))
  756. {
  757. }
  758. TagTree::TagTree(TagTree&&) = default;
  759. TagTree::~TagTree() = default;
  760. ErrorOr<TagTree> TagTree::create(u32 x_count, u32 y_count)
  761. {
  762. auto level = ceil(log2(max(x_count, y_count)));
  763. return TagTree { TRY(TagTreeNode::create(x_count, y_count, level)) };
  764. }
  765. ErrorOr<u32> TagTree::read_value(u32 x, u32 y, Function<ErrorOr<bool>()> const& read_bit, Optional<u32> stop_at) const
  766. {
  767. return m_root->read_value(x, y, read_bit, m_root->value, stop_at);
  768. }
  769. }
  770. bool JPEG2000ImageDecoderPlugin::sniff(ReadonlyBytes data)
  771. {
  772. return data.starts_with(jp2_id_string);
  773. }
  774. JPEG2000ImageDecoderPlugin::JPEG2000ImageDecoderPlugin()
  775. {
  776. m_context = make<JPEG2000LoadingContext>();
  777. }
  778. IntSize JPEG2000ImageDecoderPlugin::size()
  779. {
  780. return m_context->size;
  781. }
  782. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEG2000ImageDecoderPlugin::create(ReadonlyBytes data)
  783. {
  784. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JPEG2000ImageDecoderPlugin()));
  785. TRY(decode_jpeg2000_header(*plugin->m_context, data));
  786. return plugin;
  787. }
  788. ErrorOr<ImageFrameDescriptor> JPEG2000ImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  789. {
  790. if (index != 0)
  791. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Invalid frame index");
  792. if (m_context->state == JPEG2000LoadingContext::State::Error)
  793. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Decoding failed");
  794. if (m_context->state < JPEG2000LoadingContext::State::DecodedTileHeaders) {
  795. TRY(parse_codestream_tile_headers(*m_context));
  796. m_context->state = JPEG2000LoadingContext::State::DecodedTileHeaders;
  797. }
  798. return Error::from_string_literal("JPEG2000ImageDecoderPlugin: Draw the rest of the owl");
  799. }
  800. ErrorOr<Optional<ReadonlyBytes>> JPEG2000ImageDecoderPlugin::icc_data()
  801. {
  802. return m_context->icc_data;
  803. }
  804. }