TIFFLoader.cpp 29 KB

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