TIFFLoader.cpp 28 KB

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