TIFFLoader.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/String.h>
  10. #include <LibCompress/LZWDecoder.h>
  11. #include <LibGfx/ImageFormats/TIFFMetadata.h>
  12. namespace Gfx {
  13. namespace TIFF {
  14. class TIFFLoadingContext {
  15. public:
  16. enum class State {
  17. NotDecoded = 0,
  18. Error,
  19. HeaderDecoded,
  20. FrameDecoded,
  21. };
  22. TIFFLoadingContext(NonnullOwnPtr<FixedMemoryStream> stream)
  23. : m_stream(move(stream))
  24. {
  25. }
  26. ErrorOr<void> decode_image_header()
  27. {
  28. TRY(read_image_file_header());
  29. TRY(read_next_image_file_directory());
  30. m_state = State::HeaderDecoded;
  31. return {};
  32. }
  33. ErrorOr<void> decode_frame()
  34. {
  35. auto maybe_error = decode_frame_impl();
  36. if (maybe_error.is_error()) {
  37. m_state = State::Error;
  38. return maybe_error.release_error();
  39. }
  40. return {};
  41. }
  42. IntSize size() const
  43. {
  44. return { *m_metadata.image_width(), *m_metadata.image_height() };
  45. }
  46. Metadata const& metadata() const
  47. {
  48. return m_metadata;
  49. }
  50. State state() const
  51. {
  52. return m_state;
  53. }
  54. RefPtr<Bitmap> bitmap() const
  55. {
  56. return m_bitmap;
  57. }
  58. private:
  59. enum class ByteOrder {
  60. LittleEndian,
  61. BigEndian,
  62. };
  63. static ErrorOr<u8> read_component(BigEndianInputBitStream& stream, u8 bits)
  64. {
  65. // FIXME: This function truncates everything to 8-bits
  66. auto const value = TRY(stream.read_bits<u32>(bits));
  67. if (bits > 8)
  68. return value >> (bits - 8);
  69. return value << (8 - bits);
  70. }
  71. ErrorOr<Color> read_color(BigEndianInputBitStream& stream)
  72. {
  73. auto bits_per_sample = *m_metadata.bits_per_sample();
  74. if (m_metadata.samples_per_pixel().value_or(3) == 3) {
  75. auto const first_component = TRY(read_component(stream, bits_per_sample[0]));
  76. auto const second_component = TRY(read_component(stream, bits_per_sample[1]));
  77. auto const third_component = TRY(read_component(stream, bits_per_sample[2]));
  78. return Color(first_component, second_component, third_component);
  79. }
  80. if (*m_metadata.samples_per_pixel() == 1) {
  81. auto luminosity = TRY(read_component(stream, bits_per_sample[0]));
  82. if (m_metadata.photometric_interpretation() == PhotometricInterpretation::WhiteIsZero)
  83. luminosity = ~luminosity;
  84. return Color(luminosity, luminosity, luminosity);
  85. }
  86. return Error::from_string_literal("Unsupported number of sample per pixel");
  87. }
  88. template<CallableAs<ErrorOr<ReadonlyBytes>, u32> StripDecoder>
  89. ErrorOr<void> loop_over_pixels(StripDecoder&& strip_decoder)
  90. {
  91. auto const strips_offset = *m_metadata.strip_offsets();
  92. auto const strip_byte_counts = *m_metadata.strip_byte_counts();
  93. for (u32 strip_index = 0; strip_index < strips_offset.size(); ++strip_index) {
  94. TRY(m_stream->seek(strips_offset[strip_index]));
  95. auto const decoded_bytes = TRY(strip_decoder(strip_byte_counts[strip_index]));
  96. auto decoded_strip = make<FixedMemoryStream>(decoded_bytes);
  97. auto decoded_stream = make<BigEndianInputBitStream>(move(decoded_strip));
  98. for (u32 row = 0; row < *m_metadata.rows_per_strip(); row++) {
  99. auto const scanline = row + *m_metadata.rows_per_strip() * strip_index;
  100. if (scanline >= *m_metadata.image_height())
  101. break;
  102. Optional<Color> last_color {};
  103. for (u32 column = 0; column < *m_metadata.image_width(); ++column) {
  104. auto color = TRY(read_color(*decoded_stream));
  105. if (m_metadata.predictor() == Predictor::HorizontalDifferencing && last_color.has_value()) {
  106. color.set_red(last_color->red() + color.red());
  107. color.set_green(last_color->green() + color.green());
  108. color.set_blue(last_color->blue() + color.blue());
  109. }
  110. last_color = color;
  111. m_bitmap->set_pixel(column, scanline, color);
  112. }
  113. decoded_stream->align_to_byte_boundary();
  114. }
  115. }
  116. return {};
  117. }
  118. ErrorOr<void> decode_frame_impl()
  119. {
  120. m_bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, size()));
  121. switch (*m_metadata.compression()) {
  122. case Compression::NoCompression: {
  123. auto identity = [&](u32 num_bytes) {
  124. return m_stream->read_in_place<u8 const>(num_bytes);
  125. };
  126. TRY(loop_over_pixels(move(identity)));
  127. break;
  128. }
  129. case Compression::LZW: {
  130. ByteBuffer decoded_bytes {};
  131. auto decode_lzw_strip = [&](u32 num_bytes) -> ErrorOr<ReadonlyBytes> {
  132. auto const encoded_bytes = TRY(m_stream->read_in_place<u8 const>(num_bytes));
  133. if (encoded_bytes.is_empty())
  134. return Error::from_string_literal("TIFFImageDecoderPlugin: Unable to read from empty LZW strip");
  135. // Note: AFAIK, there are two common ways to use LZW compression:
  136. // - With a LittleEndian stream and no Early-Change, this is used in the GIF format
  137. // - With a BigEndian stream and an EarlyChange of 1, this is used in the PDF format
  138. // The fun begins when they decided to change from the former to the latter when moving
  139. // from TIFF 5.0 to 6.0, and without including a way for files to be identified.
  140. // Fortunately, as the first byte of a LZW stream is a constant we can guess the endianess
  141. // and deduce the version from it. The first code is 0x100 (9-bits).
  142. if (encoded_bytes[0] == 0x00)
  143. decoded_bytes = TRY(Compress::LZWDecoder<LittleEndianInputBitStream>::decode_all(encoded_bytes, 8, 0));
  144. else
  145. decoded_bytes = TRY(Compress::LZWDecoder<BigEndianInputBitStream>::decode_all(encoded_bytes, 8, -1));
  146. return decoded_bytes;
  147. };
  148. TRY(loop_over_pixels(move(decode_lzw_strip)));
  149. break;
  150. }
  151. case Compression::PackBits: {
  152. // Section 9: PackBits Compression
  153. ByteBuffer decoded_bytes {};
  154. auto decode_packbits_strip = [&](u32 num_bytes) -> ErrorOr<ReadonlyBytes> {
  155. auto strip_stream = make<FixedMemoryStream>(TRY(m_stream->read_in_place<u8 const>(num_bytes)));
  156. decoded_bytes.clear();
  157. Optional<i8> n {};
  158. Optional<u8> saved_byte {};
  159. while (strip_stream->remaining() > 0 || saved_byte.has_value()) {
  160. if (!n.has_value())
  161. n = TRY(strip_stream->read_value<i8>());
  162. if (n.value() >= 0 && !saved_byte.has_value()) {
  163. n.value() = n.value() - 1;
  164. if (n.value() == -1)
  165. n.clear();
  166. decoded_bytes.append(TRY(strip_stream->read_value<u8>()));
  167. continue;
  168. }
  169. if (n.value() == -128) {
  170. n.clear();
  171. continue;
  172. }
  173. if (!saved_byte.has_value())
  174. saved_byte = TRY(strip_stream->read_value<u8>());
  175. n.value() = n.value() + 1;
  176. decoded_bytes.append(*saved_byte);
  177. if (n == 1) {
  178. saved_byte.clear();
  179. n.clear();
  180. }
  181. }
  182. return decoded_bytes;
  183. };
  184. TRY(loop_over_pixels(move(decode_packbits_strip)));
  185. break;
  186. }
  187. default:
  188. return Error::from_string_literal("This compression type is not supported yet :^)");
  189. }
  190. return {};
  191. }
  192. template<typename T>
  193. ErrorOr<T> read_value()
  194. {
  195. if (m_byte_order == ByteOrder::LittleEndian)
  196. return TRY(m_stream->read_value<LittleEndian<T>>());
  197. if (m_byte_order == ByteOrder::BigEndian)
  198. return TRY(m_stream->read_value<BigEndian<T>>());
  199. VERIFY_NOT_REACHED();
  200. }
  201. ErrorOr<void> read_next_idf_offset()
  202. {
  203. auto const next_block_position = TRY(read_value<u32>());
  204. if (next_block_position != 0)
  205. m_next_ifd = Optional<u32> { next_block_position };
  206. else
  207. m_next_ifd = OptionalNone {};
  208. dbgln_if(TIFF_DEBUG, "Setting image file directory pointer to {}", m_next_ifd);
  209. return {};
  210. }
  211. ErrorOr<void> read_image_file_header()
  212. {
  213. // Section 2: TIFF Structure - Image File Header
  214. auto const byte_order = TRY(m_stream->read_value<u16>());
  215. switch (byte_order) {
  216. case 0x4949:
  217. m_byte_order = ByteOrder::LittleEndian;
  218. break;
  219. case 0x4D4D:
  220. m_byte_order = ByteOrder::BigEndian;
  221. break;
  222. default:
  223. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid byte order");
  224. }
  225. auto const magic_number = TRY(read_value<u16>());
  226. if (magic_number != 42)
  227. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid magic number");
  228. TRY(read_next_idf_offset());
  229. return {};
  230. }
  231. ErrorOr<void> read_next_image_file_directory()
  232. {
  233. // Section 2: TIFF Structure - Image File Directory
  234. if (!m_next_ifd.has_value())
  235. return Error::from_string_literal("TIFFImageDecoderPlugin: Missing an Image File Directory");
  236. TRY(m_stream->seek(m_next_ifd.value()));
  237. auto const number_of_field = TRY(read_value<u16>());
  238. for (u16 i = 0; i < number_of_field; ++i)
  239. TRY(read_tag());
  240. TRY(read_next_idf_offset());
  241. return {};
  242. }
  243. ErrorOr<Type> read_type()
  244. {
  245. switch (TRY(read_value<u16>())) {
  246. case to_underlying(Type::Byte):
  247. return Type::Byte;
  248. case to_underlying(Type::ASCII):
  249. return Type::ASCII;
  250. case to_underlying(Type::UnsignedShort):
  251. return Type::UnsignedShort;
  252. case to_underlying(Type::UnsignedLong):
  253. return Type::UnsignedLong;
  254. case to_underlying(Type::UnsignedRational):
  255. return Type::UnsignedRational;
  256. case to_underlying(Type::Undefined):
  257. return Type::Undefined;
  258. case to_underlying(Type::SignedLong):
  259. return Type::SignedLong;
  260. case to_underlying(Type::SignedRational):
  261. return Type::SignedRational;
  262. case to_underlying(Type::UTF8):
  263. return Type::UTF8;
  264. default:
  265. return Error::from_string_literal("TIFFImageDecoderPlugin: Unknown type");
  266. }
  267. }
  268. static constexpr u8 size_of_type(Type type)
  269. {
  270. switch (type) {
  271. case Type::Byte:
  272. return 1;
  273. case Type::ASCII:
  274. return 1;
  275. case Type::UnsignedShort:
  276. return 2;
  277. case Type::UnsignedLong:
  278. return 4;
  279. case Type::UnsignedRational:
  280. return 8;
  281. case Type::Undefined:
  282. return 1;
  283. case Type::SignedLong:
  284. return 4;
  285. case Type::SignedRational:
  286. return 8;
  287. case Type::Float:
  288. return 4;
  289. case Type::Double:
  290. return 8;
  291. case Type::UTF8:
  292. return 1;
  293. default:
  294. VERIFY_NOT_REACHED();
  295. }
  296. }
  297. ErrorOr<Vector<Value, 1>> read_tiff_value(Type type, u32 count, u32 offset)
  298. {
  299. auto const old_offset = TRY(m_stream->tell());
  300. ScopeGuard reset_offset { [this, old_offset]() { MUST(m_stream->seek(old_offset)); } };
  301. TRY(m_stream->seek(offset));
  302. if (size_of_type(type) * count > m_stream->remaining())
  303. return Error::from_string_literal("TIFFImageDecoderPlugin: Tag size claims to be bigger that remaining bytes");
  304. auto const read_every_values = [this, count]<typename T>() -> ErrorOr<Vector<Value>> {
  305. Vector<Value, 1> result {};
  306. TRY(result.try_ensure_capacity(count));
  307. if constexpr (IsSpecializationOf<T, Rational>) {
  308. for (u32 i = 0; i < count; ++i)
  309. result.empend(T { TRY(read_value<typename T::Type>()), TRY(read_value<typename T::Type>()) });
  310. } else {
  311. for (u32 i = 0; i < count; ++i)
  312. result.empend(typename TypePromoter<T>::Type(TRY(read_value<T>())));
  313. }
  314. return result;
  315. };
  316. switch (type) {
  317. case Type::Byte:
  318. case Type::Undefined: {
  319. Vector<Value, 1> result;
  320. auto buffer = TRY(ByteBuffer::create_uninitialized(count));
  321. TRY(m_stream->read_until_filled(buffer));
  322. result.append(move(buffer));
  323. return result;
  324. }
  325. case Type::ASCII:
  326. case Type::UTF8: {
  327. Vector<Value, 1> result;
  328. // NOTE: No need to include the null terminator
  329. if (count > 0)
  330. --count;
  331. auto string_data = TRY(ByteBuffer::create_uninitialized(count));
  332. TRY(m_stream->read_until_filled(string_data));
  333. result.empend(TRY(String::from_utf8(StringView { string_data.bytes() })));
  334. return result;
  335. }
  336. case Type::UnsignedShort:
  337. return read_every_values.template operator()<u16>();
  338. case Type::UnsignedLong:
  339. return read_every_values.template operator()<u32>();
  340. case Type::UnsignedRational:
  341. return read_every_values.template operator()<Rational<u32>>();
  342. case Type::SignedLong:
  343. return read_every_values.template operator()<i32>();
  344. ;
  345. case Type::SignedRational:
  346. return read_every_values.template operator()<Rational<i32>>();
  347. default:
  348. VERIFY_NOT_REACHED();
  349. }
  350. }
  351. ErrorOr<void> read_tag()
  352. {
  353. auto const tag = TRY(read_value<u16>());
  354. auto const type = TRY(read_type());
  355. auto const count = TRY(read_value<u32>());
  356. Checked<u32> checked_size = size_of_type(type);
  357. checked_size *= count;
  358. if (checked_size.has_overflow())
  359. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag with too large data");
  360. auto tiff_value = TRY(([=, this]() -> ErrorOr<Vector<Value>> {
  361. if (checked_size.value() <= 4) {
  362. auto value = TRY(read_tiff_value(type, count, TRY(m_stream->tell())));
  363. TRY(m_stream->discard(4));
  364. return value;
  365. }
  366. auto const offset = TRY(read_value<u32>());
  367. return read_tiff_value(type, count, offset);
  368. }()));
  369. TRY(handle_tag(m_metadata, tag, type, count, move(tiff_value)));
  370. return {};
  371. }
  372. NonnullOwnPtr<FixedMemoryStream> m_stream;
  373. State m_state {};
  374. RefPtr<Bitmap> m_bitmap {};
  375. ByteOrder m_byte_order {};
  376. Optional<u32> m_next_ifd {};
  377. Metadata m_metadata {};
  378. };
  379. }
  380. TIFFImageDecoderPlugin::TIFFImageDecoderPlugin(NonnullOwnPtr<FixedMemoryStream> stream)
  381. {
  382. m_context = make<TIFF::TIFFLoadingContext>(move(stream));
  383. }
  384. bool TIFFImageDecoderPlugin::sniff(ReadonlyBytes bytes)
  385. {
  386. if (bytes.size() < 4)
  387. return false;
  388. bool const valid_little_endian = bytes[0] == 0x49 && bytes[1] == 0x49 && bytes[2] == 0x2A && bytes[3] == 0x00;
  389. bool const valid_big_endian = bytes[0] == 0x4D && bytes[1] == 0x4D && bytes[2] == 0x00 && bytes[3] == 0x2A;
  390. return valid_little_endian || valid_big_endian;
  391. }
  392. IntSize TIFFImageDecoderPlugin::size()
  393. {
  394. return m_context->size();
  395. }
  396. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> TIFFImageDecoderPlugin::create(ReadonlyBytes data)
  397. {
  398. auto stream = TRY(try_make<FixedMemoryStream>(data));
  399. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TIFFImageDecoderPlugin(move(stream))));
  400. TRY(plugin->m_context->decode_image_header());
  401. return plugin;
  402. }
  403. ErrorOr<ImageFrameDescriptor> TIFFImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  404. {
  405. if (index > 0)
  406. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid frame index");
  407. if (m_context->state() == TIFF::TIFFLoadingContext::State::Error)
  408. return Error::from_string_literal("TIFFImageDecoderPlugin: Decoding failed");
  409. if (m_context->state() < TIFF::TIFFLoadingContext::State::FrameDecoded)
  410. TRY(m_context->decode_frame());
  411. return ImageFrameDescriptor { m_context->bitmap(), 0 };
  412. }
  413. ErrorOr<Optional<ReadonlyBytes>> TIFFImageDecoderPlugin::icc_data()
  414. {
  415. return m_context->metadata().icc_profile().map([](auto const& buffer) -> ReadonlyBytes { return buffer.bytes(); });
  416. }
  417. }