TIFFLoader.cpp 17 KB

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