TIFFLoader.cpp 30 KB

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