TIFFLoader.cpp 24 KB

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