TIFFLoader.cpp 17 KB

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