TIFFLoader.cpp 32 KB

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