TIFFLoader.cpp 30 KB

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