TIFFLoader.cpp 31 KB

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