TIFFLoader.cpp 23 KB

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