TIFFLoader.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. /*
  2. * Copyright (c) 2023, Lucas Chollet <lucas.chollet@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "TIFFLoader.h"
  7. #include <AK/ConstrainedStream.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Endian.h>
  10. #include <AK/String.h>
  11. #include <LibCompress/LZWDecoder.h>
  12. #include <LibCompress/PackBitsDecoder.h>
  13. #include <LibCompress/Zlib.h>
  14. #include <LibGfx/CMYKBitmap.h>
  15. #include <LibGfx/ImageFormats/CCITTDecoder.h>
  16. #include <LibGfx/ImageFormats/ExifOrientedBitmap.h>
  17. #include <LibGfx/ImageFormats/TIFFMetadata.h>
  18. namespace Gfx {
  19. namespace {
  20. CCITT::Group3Options parse_t4_options(u32 bit_field)
  21. {
  22. // Section 11: CCITT Bilevel Encodings
  23. CCITT::Group3Options options {};
  24. if (bit_field & 0b001)
  25. options.dimensions = CCITT::Group3Options::Mode::TwoDimensions;
  26. if (bit_field & 0b010)
  27. options.compression = CCITT::Group3Options::Compression::Uncompressed;
  28. if (bit_field & 0b100)
  29. options.use_fill_bits = CCITT::Group3Options::UseFillBits::Yes;
  30. return options;
  31. }
  32. }
  33. namespace TIFF {
  34. class TIFFLoadingContext {
  35. public:
  36. enum class State {
  37. NotDecoded = 0,
  38. Error,
  39. HeaderDecoded,
  40. FrameDecoded,
  41. };
  42. TIFFLoadingContext(NonnullOwnPtr<FixedMemoryStream> stream)
  43. : m_stream(move(stream))
  44. {
  45. }
  46. ErrorOr<void> decode_image_header()
  47. {
  48. TRY(read_image_file_header());
  49. TRY(read_next_image_file_directory());
  50. m_state = State::HeaderDecoded;
  51. return {};
  52. }
  53. ErrorOr<void> ensure_conditional_tags_are_correct() const
  54. {
  55. if (m_metadata.photometric_interpretation() == PhotometricInterpretation::RGBPalette && !m_metadata.color_map().has_value())
  56. return Error::from_string_literal("TIFFImageDecoderPlugin: RGBPalette image doesn't contain a color map");
  57. if (m_metadata.tile_width() == 0u || m_metadata.tile_length() == 0u)
  58. return Error::from_string_literal("TIFFImageDecoderPlugin: Null value in tile's dimensions");
  59. return {};
  60. }
  61. Optional<Vector<u32>> segment_offsets() const
  62. {
  63. return m_metadata.strip_offsets().has_value() ? m_metadata.strip_offsets() : m_metadata.tile_offsets();
  64. }
  65. Optional<Vector<u32>> segment_byte_counts() const
  66. {
  67. return m_metadata.strip_byte_counts().has_value() ? m_metadata.strip_byte_counts() : m_metadata.tile_byte_counts();
  68. }
  69. bool is_tiled() const
  70. {
  71. return m_metadata.tile_width().has_value() && m_metadata.tile_length().has_value();
  72. }
  73. ErrorOr<void> ensure_baseline_tags_are_correct() const
  74. {
  75. if (!segment_offsets().has_value())
  76. return Error::from_string_literal("TIFFImageDecoderPlugin: Missing Offsets tag");
  77. if (!segment_byte_counts().has_value())
  78. return Error::from_string_literal("TIFFImageDecoderPlugin: Missing ByteCounts tag");
  79. if (segment_offsets()->size() != segment_byte_counts()->size())
  80. return Error::from_string_literal("TIFFImageDecoderPlugin: StripsOffset and StripByteCount have different sizes");
  81. if (!m_metadata.rows_per_strip().has_value() && segment_byte_counts()->size() != 1 && !is_tiled())
  82. return Error::from_string_literal("TIFFImageDecoderPlugin: RowsPerStrip is not provided and impossible to deduce");
  83. if (!m_metadata.bits_per_sample().has_value())
  84. return Error::from_string_literal("TIFFImageDecoderPlugin: Tag BitsPerSample is missing");
  85. if (!m_metadata.samples_per_pixel().has_value())
  86. return Error::from_string_literal("TIFFImageDecoderPlugin: Tag SamplesPerPixel is missing");
  87. if (any_of(*m_metadata.bits_per_sample(), [](auto bit_depth) { return bit_depth == 0 || bit_depth > 32; }))
  88. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid value in BitsPerSample");
  89. if (m_metadata.bits_per_sample()->size() != m_metadata.samples_per_pixel())
  90. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid number of values in BitsPerSample");
  91. if (*m_metadata.samples_per_pixel() < samples_for_photometric_interpretation())
  92. return Error::from_string_literal("TIFFImageDecoderPlugin: Not enough values in BitsPerSample for given PhotometricInterpretation");
  93. return {};
  94. }
  95. void cache_values()
  96. {
  97. if (m_metadata.photometric_interpretation().has_value())
  98. m_photometric_interpretation = m_metadata.photometric_interpretation().value();
  99. if (m_metadata.bits_per_sample().has_value())
  100. m_bits_per_sample = m_metadata.bits_per_sample().value();
  101. if (m_metadata.image_width().has_value())
  102. m_image_width = m_metadata.image_width().value();
  103. if (m_metadata.predictor().has_value())
  104. m_predictor = m_metadata.predictor().value();
  105. m_alpha_channel_index = alpha_channel_index();
  106. }
  107. ErrorOr<void> decode_frame()
  108. {
  109. TRY(ensure_baseline_tags_are_present(m_metadata));
  110. TRY(ensure_baseline_tags_are_correct());
  111. TRY(ensure_conditional_tags_are_correct());
  112. cache_values();
  113. auto maybe_error = decode_frame_impl();
  114. if (maybe_error.is_error()) {
  115. m_state = State::Error;
  116. return maybe_error.release_error();
  117. }
  118. return {};
  119. }
  120. IntSize size() const
  121. {
  122. return ExifOrientedBitmap::oriented_size({ *m_metadata.image_width(), *m_metadata.image_length() }, *m_metadata.orientation());
  123. }
  124. ExifMetadata const& metadata() const
  125. {
  126. return m_metadata;
  127. }
  128. State state() const
  129. {
  130. return m_state;
  131. }
  132. RefPtr<CMYKBitmap> cmyk_bitmap() const
  133. {
  134. return m_cmyk_bitmap;
  135. }
  136. RefPtr<Bitmap> bitmap() const
  137. {
  138. return m_bitmap;
  139. }
  140. private:
  141. enum class ByteOrder {
  142. LittleEndian,
  143. BigEndian,
  144. };
  145. static ErrorOr<u8> read_component(BigEndianInputBitStream& stream, u8 bits)
  146. {
  147. // FIXME: This function truncates everything to 8-bits
  148. auto const value = TRY(stream.read_bits<u32>(bits));
  149. if (bits > 8)
  150. return value >> (bits - 8);
  151. return NumericLimits<u8>::max() * value / ((1 << bits) - 1);
  152. }
  153. u8 samples_for_photometric_interpretation() const
  154. {
  155. switch (m_photometric_interpretation) {
  156. case PhotometricInterpretation::WhiteIsZero:
  157. case PhotometricInterpretation::BlackIsZero:
  158. case PhotometricInterpretation::RGBPalette:
  159. return 1;
  160. case PhotometricInterpretation::RGB:
  161. return 3;
  162. case PhotometricInterpretation::CMYK:
  163. return 4;
  164. default:
  165. TODO();
  166. }
  167. }
  168. Optional<u8> alpha_channel_index() const
  169. {
  170. if (m_metadata.extra_samples().has_value()) {
  171. auto const extra_samples = m_metadata.extra_samples().value();
  172. for (u8 i = 0; i < extra_samples.size(); ++i) {
  173. if (extra_samples[i] == ExtraSample::UnassociatedAlpha)
  174. return i + samples_for_photometric_interpretation();
  175. }
  176. }
  177. return OptionalNone {};
  178. }
  179. ErrorOr<u8> manage_extra_channels(BigEndianInputBitStream& stream) const
  180. {
  181. // Section 7: Additional Baseline TIFF Requirements
  182. // Some TIFF files may have more components per pixel than you think. A Baseline TIFF reader must skip over
  183. // them gracefully, using the values of the SamplesPerPixel and BitsPerSample fields.
  184. // Both unknown and alpha channels are considered as extra channels, so let's iterate over
  185. // them, conserve the alpha value (if any) and discard everything else.
  186. auto const number_base_channels = samples_for_photometric_interpretation();
  187. Optional<u8> alpha {};
  188. for (u8 i = number_base_channels; i < m_bits_per_sample.size(); ++i) {
  189. if (m_alpha_channel_index == i)
  190. alpha = TRY(read_component(stream, m_bits_per_sample[i]));
  191. else
  192. TRY(read_component(stream, m_bits_per_sample[i]));
  193. }
  194. return alpha.value_or(NumericLimits<u8>::max());
  195. }
  196. ErrorOr<Color> read_color(BigEndianInputBitStream& stream)
  197. {
  198. if (m_photometric_interpretation == PhotometricInterpretation::RGB) {
  199. auto const first_component = TRY(read_component(stream, m_bits_per_sample[0]));
  200. auto const second_component = TRY(read_component(stream, m_bits_per_sample[1]));
  201. auto const third_component = TRY(read_component(stream, m_bits_per_sample[2]));
  202. auto const alpha = TRY(manage_extra_channels(stream));
  203. return Color(first_component, second_component, third_component, alpha);
  204. }
  205. if (m_photometric_interpretation == PhotometricInterpretation::RGBPalette) {
  206. auto const index = TRY(stream.read_bits<u16>(m_bits_per_sample[0]));
  207. auto const alpha = TRY(manage_extra_channels(stream));
  208. // SamplesPerPixel == 1 is a requirement for RGBPalette
  209. // From description of PhotometricInterpretation in Section 8: Baseline Field Reference Guide
  210. // "In a TIFF ColorMap, all the Red values come first, followed by the Green values,
  211. // then the Blue values."
  212. u64 const size = 1ul << m_bits_per_sample[0];
  213. u64 const red_offset = 0 * size;
  214. u64 const green_offset = 1 * size;
  215. u64 const blue_offset = 2 * size;
  216. auto const color_map = *m_metadata.color_map();
  217. if (blue_offset + index >= color_map.size())
  218. return Error::from_string_literal("TIFFImageDecoderPlugin: Color index is out of range");
  219. // FIXME: ColorMap's values are always 16-bits, stop truncating them when we support 16 bits bitmaps
  220. return Color(
  221. color_map[red_offset + index] >> 8,
  222. color_map[green_offset + index] >> 8,
  223. color_map[blue_offset + index] >> 8,
  224. alpha);
  225. }
  226. if (m_photometric_interpretation == PhotometricInterpretation::WhiteIsZero
  227. || m_photometric_interpretation == PhotometricInterpretation::BlackIsZero) {
  228. auto luminosity = TRY(read_component(stream, m_bits_per_sample[0]));
  229. if (m_photometric_interpretation == PhotometricInterpretation::WhiteIsZero)
  230. luminosity = ~luminosity;
  231. auto const alpha = TRY(manage_extra_channels(stream));
  232. return Color(luminosity, luminosity, luminosity, alpha);
  233. }
  234. return Error::from_string_literal("Unsupported value for PhotometricInterpretation");
  235. }
  236. ErrorOr<CMYK> read_color_cmyk(BigEndianInputBitStream& stream)
  237. {
  238. VERIFY(m_photometric_interpretation == PhotometricInterpretation::CMYK);
  239. auto const first_component = TRY(read_component(stream, m_bits_per_sample[0]));
  240. auto const second_component = TRY(read_component(stream, m_bits_per_sample[1]));
  241. auto const third_component = TRY(read_component(stream, m_bits_per_sample[2]));
  242. auto const fourth_component = TRY(read_component(stream, m_bits_per_sample[3]));
  243. // FIXME: We probably won't encounter CMYK images with an alpha channel, but if
  244. // we do: the first step to support them is not dropping the value here!
  245. [[maybe_unused]] auto const alpha = TRY(manage_extra_channels(stream));
  246. return CMYK { first_component, second_component, third_component, fourth_component };
  247. }
  248. template<CallableAs<ErrorOr<ReadonlyBytes>, u32, IntSize> SegmentDecoder>
  249. ErrorOr<void> loop_over_pixels(SegmentDecoder&& segment_decoder)
  250. {
  251. auto const offsets = *segment_offsets();
  252. auto const byte_counts = *segment_byte_counts();
  253. auto const segment_length = m_metadata.tile_length().value_or(m_metadata.rows_per_strip().value_or(*m_metadata.image_length()));
  254. auto const segment_width = m_metadata.tile_width().value_or(m_image_width);
  255. auto const segment_per_rows = m_metadata.tile_width().map([&](u32 w) { return ceil_div(m_image_width, w); }).value_or(1);
  256. Variant<ExifOrientedBitmap, ExifOrientedCMYKBitmap> oriented_bitmap = TRY(([&]() -> ErrorOr<Variant<ExifOrientedBitmap, ExifOrientedCMYKBitmap>> {
  257. if (m_photometric_interpretation == PhotometricInterpretation::CMYK)
  258. return ExifOrientedCMYKBitmap::create(*metadata().orientation(), { m_image_width, *metadata().image_length() });
  259. return ExifOrientedBitmap::create(*metadata().orientation(), { m_image_width, *metadata().image_length() }, BitmapFormat::BGRA8888);
  260. }()));
  261. for (u32 segment_index = 0; segment_index < offsets.size(); ++segment_index) {
  262. TRY(m_stream->seek(offsets[segment_index]));
  263. auto const rows_in_segment = segment_index < offsets.size() - 1 ? segment_length : *m_metadata.image_length() - segment_length * segment_index;
  264. auto const decoded_bytes = TRY(segment_decoder(byte_counts[segment_index], { segment_width, rows_in_segment }));
  265. auto decoded_segment = make<FixedMemoryStream>(decoded_bytes);
  266. auto decoded_stream = make<BigEndianInputBitStream>(move(decoded_segment));
  267. for (u32 row = 0; row < segment_length; row++) {
  268. auto const image_row = row + segment_length * (segment_index / segment_per_rows);
  269. if (image_row >= *m_metadata.image_length())
  270. break;
  271. Optional<Color> last_color {};
  272. for (u32 column = 0; column < segment_width; ++column) {
  273. // If image_length % segment_length != 0, the last tile will be padded.
  274. // This variable helps us to skip these last columns. Note that we still
  275. // need to read the sample from the stream.
  276. auto const image_column = column + segment_width * (segment_index % segment_per_rows);
  277. if (m_photometric_interpretation == PhotometricInterpretation::CMYK) {
  278. auto const cmyk = TRY(read_color_cmyk(*decoded_stream));
  279. if (image_column >= m_image_width)
  280. continue;
  281. oriented_bitmap.get<ExifOrientedCMYKBitmap>().set_pixel(image_column, image_row, cmyk);
  282. } else {
  283. auto color = TRY(read_color(*decoded_stream));
  284. // FIXME: We should do the differencing at the byte-stream level, that would make it
  285. // compatible with both LibPDF and all color formats.
  286. if (m_predictor == Predictor::HorizontalDifferencing && last_color.has_value()) {
  287. color.set_red(last_color->red() + color.red());
  288. color.set_green(last_color->green() + color.green());
  289. color.set_blue(last_color->blue() + color.blue());
  290. if (m_alpha_channel_index.has_value())
  291. color.set_alpha(last_color->alpha() + color.alpha());
  292. }
  293. last_color = color;
  294. if (image_column >= m_image_width)
  295. continue;
  296. oriented_bitmap.get<ExifOrientedBitmap>().set_pixel(image_column, image_row, color.value());
  297. }
  298. }
  299. decoded_stream->align_to_byte_boundary();
  300. }
  301. }
  302. if (m_photometric_interpretation == PhotometricInterpretation::CMYK)
  303. m_cmyk_bitmap = oriented_bitmap.get<ExifOrientedCMYKBitmap>().bitmap();
  304. else
  305. m_bitmap = oriented_bitmap.get<ExifOrientedBitmap>().bitmap();
  306. return {};
  307. }
  308. ErrorOr<void> ensure_tags_are_correct_for_ccitt() const
  309. {
  310. // Section 8: Baseline Field Reference Guide
  311. // BitsPerSample must be 1, since this type of compression is defined only for bilevel images.
  312. if (m_metadata.bits_per_sample()->size() > 1)
  313. return Error::from_string_literal("TIFFImageDecoderPlugin: CCITT image with BitsPerSample greater than one");
  314. if (m_metadata.photometric_interpretation() != PhotometricInterpretation::WhiteIsZero && m_metadata.photometric_interpretation() != PhotometricInterpretation::BlackIsZero)
  315. return Error::from_string_literal("TIFFImageDecoderPlugin: CCITT compression is used on a non bilevel image");
  316. return {};
  317. }
  318. ErrorOr<ByteBuffer> read_bytes_considering_fill_order(u32 bytes_to_read) const
  319. {
  320. auto const reverse_byte = [](u8 b) {
  321. b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
  322. b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
  323. b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
  324. return b;
  325. };
  326. auto const bytes = TRY(m_stream->read_in_place<u8 const>(bytes_to_read));
  327. auto copy = TRY(ByteBuffer::copy(bytes));
  328. if (m_metadata.fill_order() == FillOrder::RightToLeft) {
  329. for (auto& byte : copy.bytes())
  330. byte = reverse_byte(byte);
  331. }
  332. return copy;
  333. }
  334. ErrorOr<void> decode_frame_impl()
  335. {
  336. switch (*m_metadata.compression()) {
  337. case Compression::NoCompression: {
  338. auto identity = [&](u32 num_bytes, IntSize) {
  339. return m_stream->read_in_place<u8 const>(num_bytes);
  340. };
  341. TRY(loop_over_pixels(move(identity)));
  342. break;
  343. }
  344. case Compression::CCITTRLE: {
  345. TRY(ensure_tags_are_correct_for_ccitt());
  346. ByteBuffer decoded_bytes {};
  347. auto decode_ccitt_rle_segment = [&](u32 num_bytes, IntSize segment_size) -> ErrorOr<ReadonlyBytes> {
  348. auto const encoded_bytes = TRY(read_bytes_considering_fill_order(num_bytes));
  349. decoded_bytes = TRY(CCITT::decode_ccitt_rle(encoded_bytes, segment_size.width(), segment_size.height()));
  350. return decoded_bytes;
  351. };
  352. TRY(loop_over_pixels(move(decode_ccitt_rle_segment)));
  353. break;
  354. }
  355. case Compression::Group3Fax: {
  356. TRY(ensure_tags_are_correct_for_ccitt());
  357. auto const parameters = parse_t4_options(*m_metadata.t4_options());
  358. ByteBuffer decoded_bytes {};
  359. auto decode_group3_segment = [&](u32 num_bytes, IntSize segment_size) -> ErrorOr<ReadonlyBytes> {
  360. auto const encoded_bytes = TRY(read_bytes_considering_fill_order(num_bytes));
  361. decoded_bytes = TRY(CCITT::decode_ccitt_group3(encoded_bytes, segment_size.width(), segment_size.height(), parameters));
  362. return decoded_bytes;
  363. };
  364. TRY(loop_over_pixels(move(decode_group3_segment)));
  365. break;
  366. }
  367. case Compression::Group4Fax: {
  368. TRY(ensure_tags_are_correct_for_ccitt());
  369. // FIXME: We need to parse T6 options
  370. ByteBuffer decoded_bytes {};
  371. auto decode_group3_segment = [&](u32 num_bytes, IntSize segment_size) -> ErrorOr<ReadonlyBytes> {
  372. auto const encoded_bytes = TRY(read_bytes_considering_fill_order(num_bytes));
  373. decoded_bytes = TRY(CCITT::decode_ccitt_group4(encoded_bytes, segment_size.width(), segment_size.height()));
  374. return decoded_bytes;
  375. };
  376. TRY(loop_over_pixels(move(decode_group3_segment)));
  377. break;
  378. }
  379. case Compression::LZW: {
  380. ByteBuffer decoded_bytes {};
  381. auto decode_lzw_segment = [&](u32 num_bytes, IntSize) -> ErrorOr<ReadonlyBytes> {
  382. auto const encoded_bytes = TRY(m_stream->read_in_place<u8 const>(num_bytes));
  383. if (encoded_bytes.is_empty())
  384. return Error::from_string_literal("TIFFImageDecoderPlugin: Unable to read from empty LZW segment");
  385. // Note: AFAIK, there are two common ways to use LZW compression:
  386. // - With a LittleEndian stream and no Early-Change, this is used in the GIF format
  387. // - With a BigEndian stream and an EarlyChange of 1, this is used in the PDF format
  388. // The fun begins when they decided to change from the former to the latter when moving
  389. // from TIFF 5.0 to 6.0, and without including a way for files to be identified.
  390. // Fortunately, as the first byte of a LZW stream is a constant we can guess the endianess
  391. // and deduce the version from it. The first code is 0x100 (9-bits).
  392. if (encoded_bytes[0] == 0x00)
  393. decoded_bytes = TRY(Compress::LZWDecoder<LittleEndianInputBitStream>::decode_all(encoded_bytes, 8, 0));
  394. else
  395. decoded_bytes = TRY(Compress::LZWDecoder<BigEndianInputBitStream>::decode_all(encoded_bytes, 8, -1));
  396. return decoded_bytes;
  397. };
  398. TRY(loop_over_pixels(move(decode_lzw_segment)));
  399. break;
  400. }
  401. case Compression::AdobeDeflate:
  402. case Compression::PixarDeflate: {
  403. // This is an extension from the Technical Notes from 2002:
  404. // https://web.archive.org/web/20160305055905/http://partners.adobe.com/public/developer/en/tiff/TIFFphotoshop.pdf
  405. ByteBuffer decoded_bytes {};
  406. auto decode_zlib = [&](u32 num_bytes, IntSize) -> ErrorOr<ReadonlyBytes> {
  407. auto stream = make<ConstrainedStream>(MaybeOwned<Stream>(*m_stream), num_bytes);
  408. auto decompressed_stream = TRY(Compress::ZlibDecompressor::create(move(stream)));
  409. decoded_bytes = TRY(decompressed_stream->read_until_eof(4096));
  410. return decoded_bytes;
  411. };
  412. TRY(loop_over_pixels(move(decode_zlib)));
  413. break;
  414. }
  415. case Compression::PackBits: {
  416. // Section 9: PackBits Compression
  417. ByteBuffer decoded_bytes {};
  418. auto decode_packbits_segment = [&](u32 num_bytes, IntSize) -> ErrorOr<ReadonlyBytes> {
  419. auto const encoded_bytes = TRY(m_stream->read_in_place<u8 const>(num_bytes));
  420. decoded_bytes = TRY(Compress::PackBits::decode_all(encoded_bytes));
  421. return decoded_bytes;
  422. };
  423. TRY(loop_over_pixels(move(decode_packbits_segment)));
  424. break;
  425. }
  426. default:
  427. return Error::from_string_literal("This compression type is not supported yet :^)");
  428. }
  429. return {};
  430. }
  431. template<typename T>
  432. ErrorOr<T> read_value()
  433. {
  434. if (m_byte_order == ByteOrder::LittleEndian)
  435. return TRY(m_stream->read_value<LittleEndian<T>>());
  436. if (m_byte_order == ByteOrder::BigEndian)
  437. return TRY(m_stream->read_value<BigEndian<T>>());
  438. VERIFY_NOT_REACHED();
  439. }
  440. ErrorOr<void> set_next_ifd(u32 ifd_offset)
  441. {
  442. if (ifd_offset != 0) {
  443. if (ifd_offset < TRY(m_stream->tell()))
  444. return Error::from_string_literal("TIFFImageDecoderPlugin: Can not accept an IFD pointing to previous data");
  445. m_next_ifd = Optional<u32> { ifd_offset };
  446. } else {
  447. m_next_ifd = OptionalNone {};
  448. }
  449. return {};
  450. }
  451. ErrorOr<void> read_next_idf_offset()
  452. {
  453. auto const next_block_position = TRY(read_value<u32>());
  454. TRY(set_next_ifd(next_block_position));
  455. return {};
  456. }
  457. ErrorOr<void> read_image_file_header()
  458. {
  459. // Section 2: TIFF Structure - Image File Header
  460. auto const byte_order = TRY(m_stream->read_value<u16>());
  461. switch (byte_order) {
  462. case 0x4949:
  463. m_byte_order = ByteOrder::LittleEndian;
  464. break;
  465. case 0x4D4D:
  466. m_byte_order = ByteOrder::BigEndian;
  467. break;
  468. default:
  469. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid byte order");
  470. }
  471. auto const magic_number = TRY(read_value<u16>());
  472. if (magic_number != 42)
  473. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid magic number");
  474. TRY(read_next_idf_offset());
  475. return {};
  476. }
  477. ErrorOr<void> read_next_image_file_directory()
  478. {
  479. // Section 2: TIFF Structure - Image File Directory
  480. if (!m_next_ifd.has_value())
  481. return Error::from_string_literal("TIFFImageDecoderPlugin: Missing an Image File Directory");
  482. dbgln_if(TIFF_DEBUG, "Reading image file directory at offset {}", m_next_ifd);
  483. TRY(m_stream->seek(m_next_ifd.value()));
  484. auto const number_of_field = TRY(read_value<u16>());
  485. auto next_tag_offset = TRY(m_stream->tell());
  486. for (u16 i = 0; i < number_of_field; ++i) {
  487. if (auto maybe_error = read_tag(); maybe_error.is_error() && TIFF_DEBUG)
  488. dbgln("Unable to decode tag {}/{}", i + 1, number_of_field);
  489. // Section 2: TIFF Structure
  490. // IFD Entry
  491. // Size of tag(u16) + type(u16) + count(u32) + value_or_offset(u32) = 12
  492. next_tag_offset += 12;
  493. TRY(m_stream->seek(next_tag_offset));
  494. }
  495. TRY(read_next_idf_offset());
  496. return {};
  497. }
  498. ErrorOr<Vector<Value, 1>> read_tiff_value(Type type, u32 count, u32 offset)
  499. {
  500. auto const old_offset = TRY(m_stream->tell());
  501. ScopeGuard reset_offset { [this, old_offset]() { MUST(m_stream->seek(old_offset)); } };
  502. TRY(m_stream->seek(offset));
  503. if (size_of_type(type) * count > m_stream->remaining())
  504. return Error::from_string_literal("TIFFImageDecoderPlugin: Tag size claims to be bigger that remaining bytes");
  505. auto const read_every_values = [this, count]<typename T>() -> ErrorOr<Vector<Value>> {
  506. Vector<Value, 1> result {};
  507. TRY(result.try_ensure_capacity(count));
  508. if constexpr (IsSpecializationOf<T, Rational>) {
  509. for (u32 i = 0; i < count; ++i)
  510. result.empend(T { TRY(read_value<typename T::Type>()), TRY(read_value<typename T::Type>()) });
  511. } else {
  512. for (u32 i = 0; i < count; ++i)
  513. result.empend(typename TypePromoter<T>::Type(TRY(read_value<T>())));
  514. }
  515. return result;
  516. };
  517. switch (type) {
  518. case Type::Byte:
  519. case Type::Undefined: {
  520. Vector<Value, 1> result;
  521. auto buffer = TRY(ByteBuffer::create_uninitialized(count));
  522. TRY(m_stream->read_until_filled(buffer));
  523. result.append(move(buffer));
  524. return result;
  525. }
  526. case Type::ASCII:
  527. case Type::UTF8: {
  528. Vector<Value, 1> result;
  529. // NOTE: No need to include the null terminator
  530. if (count > 0)
  531. --count;
  532. auto string_data = TRY(ByteBuffer::create_uninitialized(count));
  533. TRY(m_stream->read_until_filled(string_data));
  534. result.empend(TRY(String::from_utf8(StringView { string_data.bytes() })));
  535. return result;
  536. }
  537. case Type::UnsignedShort:
  538. return read_every_values.template operator()<u16>();
  539. case Type::IFD:
  540. case Type::UnsignedLong:
  541. return read_every_values.template operator()<u32>();
  542. case Type::UnsignedRational:
  543. return read_every_values.template operator()<Rational<u32>>();
  544. case Type::SignedLong:
  545. return read_every_values.template operator()<i32>();
  546. case Type::SignedRational:
  547. return read_every_values.template operator()<Rational<i32>>();
  548. case Type::Float:
  549. return read_every_values.template operator()<float>();
  550. case Type::Double:
  551. return read_every_values.template operator()<double>();
  552. default:
  553. VERIFY_NOT_REACHED();
  554. }
  555. }
  556. ErrorOr<void> read_tag()
  557. {
  558. auto const tag = TRY(read_value<u16>());
  559. auto const raw_type = TRY(read_value<u16>());
  560. auto const type = TRY(tiff_type_from_u16(raw_type));
  561. auto const count = TRY(read_value<u32>());
  562. Checked<u32> checked_size = size_of_type(type);
  563. checked_size *= count;
  564. if (checked_size.has_overflow())
  565. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag with too large data");
  566. auto tiff_value = TRY(([=, this]() -> ErrorOr<Vector<Value>> {
  567. if (checked_size.value() <= 4) {
  568. auto value = TRY(read_tiff_value(type, count, TRY(m_stream->tell())));
  569. TRY(m_stream->discard(4));
  570. return value;
  571. }
  572. auto const offset = TRY(read_value<u32>());
  573. return read_tiff_value(type, count, offset);
  574. }()));
  575. auto subifd_handler = [&](u32 ifd_offset) -> ErrorOr<void> {
  576. if (auto result = set_next_ifd(ifd_offset); result.is_error()) {
  577. dbgln("{}", result.error());
  578. return {};
  579. }
  580. TRY(read_next_image_file_directory());
  581. return {};
  582. };
  583. TRY(handle_tag(move(subifd_handler), m_metadata, tag, type, count, move(tiff_value)));
  584. return {};
  585. }
  586. NonnullOwnPtr<FixedMemoryStream> m_stream;
  587. State m_state {};
  588. RefPtr<Bitmap> m_bitmap {};
  589. RefPtr<CMYKBitmap> m_cmyk_bitmap {};
  590. ByteOrder m_byte_order {};
  591. Optional<u32> m_next_ifd {};
  592. ExifMetadata m_metadata {};
  593. // These are caches for m_metadata values
  594. PhotometricInterpretation m_photometric_interpretation {};
  595. Vector<u32, 4> m_bits_per_sample {};
  596. u32 m_image_width {};
  597. Predictor m_predictor {};
  598. Optional<u8> m_alpha_channel_index {};
  599. };
  600. }
  601. TIFFImageDecoderPlugin::TIFFImageDecoderPlugin(NonnullOwnPtr<FixedMemoryStream> stream)
  602. {
  603. m_context = make<TIFF::TIFFLoadingContext>(move(stream));
  604. }
  605. bool TIFFImageDecoderPlugin::sniff(ReadonlyBytes bytes)
  606. {
  607. if (bytes.size() < 4)
  608. return false;
  609. bool const valid_little_endian = bytes[0] == 0x49 && bytes[1] == 0x49 && bytes[2] == 0x2A && bytes[3] == 0x00;
  610. bool const valid_big_endian = bytes[0] == 0x4D && bytes[1] == 0x4D && bytes[2] == 0x00 && bytes[3] == 0x2A;
  611. return valid_little_endian || valid_big_endian;
  612. }
  613. IntSize TIFFImageDecoderPlugin::size()
  614. {
  615. return m_context->size();
  616. }
  617. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> TIFFImageDecoderPlugin::create(ReadonlyBytes data)
  618. {
  619. auto stream = TRY(try_make<FixedMemoryStream>(data));
  620. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TIFFImageDecoderPlugin(move(stream))));
  621. TRY(plugin->m_context->decode_image_header());
  622. return plugin;
  623. }
  624. ErrorOr<ImageFrameDescriptor> TIFFImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  625. {
  626. if (index > 0)
  627. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid frame index");
  628. if (m_context->state() == TIFF::TIFFLoadingContext::State::Error)
  629. return Error::from_string_literal("TIFFImageDecoderPlugin: Decoding failed");
  630. if (m_context->state() < TIFF::TIFFLoadingContext::State::FrameDecoded)
  631. TRY(m_context->decode_frame());
  632. if (m_context->cmyk_bitmap())
  633. return ImageFrameDescriptor { TRY(m_context->cmyk_bitmap()->to_low_quality_rgb()), 0 };
  634. return ImageFrameDescriptor { m_context->bitmap(), 0 };
  635. }
  636. Optional<Metadata const&> TIFFImageDecoderPlugin::metadata()
  637. {
  638. return m_context->metadata();
  639. }
  640. ErrorOr<Optional<ReadonlyBytes>> TIFFImageDecoderPlugin::icc_data()
  641. {
  642. return m_context->metadata().icc_profile().map([](auto const& buffer) -> ReadonlyBytes { return buffer.bytes(); });
  643. }
  644. ErrorOr<NonnullOwnPtr<ExifMetadata>> TIFFImageDecoderPlugin::read_exif_metadata(ReadonlyBytes data)
  645. {
  646. auto stream = TRY(try_make<FixedMemoryStream>(data));
  647. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TIFFImageDecoderPlugin(move(stream))));
  648. TRY(plugin->m_context->decode_image_header());
  649. return try_make<ExifMetadata>(plugin->m_context->metadata());
  650. }
  651. }