TIFFLoader.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. namespace Gfx {
  11. class TIFFLoadingContext {
  12. public:
  13. enum class State {
  14. NotDecoded = 0,
  15. Error,
  16. HeaderDecoded,
  17. FrameDecoded,
  18. };
  19. template<OneOf<u32, i32> x32>
  20. struct Rational {
  21. using Type = x32;
  22. x32 numerator;
  23. x32 denominator;
  24. };
  25. TIFFLoadingContext(NonnullOwnPtr<FixedMemoryStream> stream)
  26. : m_stream(move(stream))
  27. {
  28. }
  29. ErrorOr<void> decode_image_header()
  30. {
  31. TRY(read_image_file_header());
  32. TRY(read_next_image_file_directory());
  33. m_state = State::HeaderDecoded;
  34. return {};
  35. }
  36. ErrorOr<void> decode_frame()
  37. {
  38. auto maybe_error = decode_frame_impl();
  39. if (maybe_error.is_error()) {
  40. m_state = State::Error;
  41. return maybe_error.release_error();
  42. }
  43. return {};
  44. }
  45. IntSize size() const
  46. {
  47. return m_size;
  48. }
  49. State state() const
  50. {
  51. return m_state;
  52. }
  53. RefPtr<Bitmap> bitmap() const
  54. {
  55. return m_bitmap;
  56. }
  57. private:
  58. enum class ByteOrder {
  59. LittleEndian,
  60. BigEndian,
  61. };
  62. enum class Type {
  63. Byte = 1,
  64. ASCII = 2,
  65. UnsignedShort = 3,
  66. UnsignedLong = 4,
  67. UnsignedRational = 5,
  68. Undefined = 7,
  69. SignedLong = 9,
  70. SignedRational = 10,
  71. Float = 11,
  72. Double = 12,
  73. UTF8 = 129,
  74. };
  75. using Value = Variant<u8, String, u16, u32, Rational<u32>, i32, Rational<i32>>;
  76. // This enum is progessively defined across sections but summarized in:
  77. // Appendix A: TIFF Tags Sorted by Number
  78. enum class Compression {
  79. NoCompression = 1,
  80. CCITT = 2,
  81. Group3Fax = 3,
  82. Group4Fax = 4,
  83. LZW = 5,
  84. JPEG = 6,
  85. PackBits = 32773,
  86. };
  87. ErrorOr<void> decode_frame_impl()
  88. {
  89. if (m_compression != Compression::NoCompression)
  90. return Error::from_string_literal("Compressed TIFF are not supported yet :^)");
  91. m_bitmap = TRY(Bitmap::create(BitmapFormat::BGRA8888, m_size));
  92. for (u32 strip_index = 0; strip_index < m_strip_offsets.size(); ++strip_index) {
  93. TRY(m_stream->seek(m_strip_offsets[strip_index]));
  94. for (u32 row = 0; row < m_rows_per_strip; row++) {
  95. auto const scanline = row + m_rows_per_strip * strip_index;
  96. if (scanline >= static_cast<u32>(m_size.height()))
  97. break;
  98. for (u32 column = 0; column < static_cast<u32>(m_size.width()); ++column) {
  99. Color const color { TRY(read_value<u8>()), TRY(read_value<u8>()), TRY(read_value<u8>()) };
  100. m_bitmap->set_pixel(column, scanline, color);
  101. }
  102. }
  103. }
  104. return {};
  105. }
  106. template<typename T>
  107. ErrorOr<T> read_value()
  108. {
  109. if (m_byte_order == ByteOrder::LittleEndian)
  110. return TRY(m_stream->read_value<LittleEndian<T>>());
  111. if (m_byte_order == ByteOrder::BigEndian)
  112. return TRY(m_stream->read_value<BigEndian<T>>());
  113. VERIFY_NOT_REACHED();
  114. }
  115. ErrorOr<void> read_next_idf_offset()
  116. {
  117. auto const next_block_position = TRY(read_value<u32>());
  118. if (next_block_position != 0)
  119. m_next_ifd = Optional<u32> { next_block_position };
  120. else
  121. m_next_ifd = OptionalNone {};
  122. dbgln_if(TIFF_DEBUG, "Setting image file directory pointer to {}", m_next_ifd);
  123. return {};
  124. }
  125. ErrorOr<void> read_image_file_header()
  126. {
  127. // Section 2: TIFF Structure - Image File Header
  128. auto const byte_order = TRY(m_stream->read_value<u16>());
  129. switch (byte_order) {
  130. case 0x4949:
  131. m_byte_order = ByteOrder::LittleEndian;
  132. break;
  133. case 0x4D4D:
  134. m_byte_order = ByteOrder::BigEndian;
  135. break;
  136. default:
  137. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid byte order");
  138. }
  139. auto const magic_number = TRY(read_value<u16>());
  140. if (magic_number != 42)
  141. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid magic number");
  142. TRY(read_next_idf_offset());
  143. return {};
  144. }
  145. ErrorOr<void> read_next_image_file_directory()
  146. {
  147. // Section 2: TIFF Structure - Image File Directory
  148. if (!m_next_ifd.has_value())
  149. return Error::from_string_literal("TIFFImageDecoderPlugin: Missing an Image File Directory");
  150. TRY(m_stream->seek(m_next_ifd.value()));
  151. auto const number_of_field = TRY(read_value<u16>());
  152. for (u16 i = 0; i < number_of_field; ++i)
  153. TRY(read_tag());
  154. TRY(read_next_idf_offset());
  155. return {};
  156. }
  157. ErrorOr<Type> read_type()
  158. {
  159. switch (TRY(read_value<u16>())) {
  160. case to_underlying(Type::Byte):
  161. return Type::Byte;
  162. case to_underlying(Type::ASCII):
  163. return Type::ASCII;
  164. case to_underlying(Type::UnsignedShort):
  165. return Type::UnsignedShort;
  166. case to_underlying(Type::UnsignedLong):
  167. return Type::UnsignedLong;
  168. case to_underlying(Type::UnsignedRational):
  169. return Type::UnsignedRational;
  170. case to_underlying(Type::Undefined):
  171. return Type::Undefined;
  172. case to_underlying(Type::SignedLong):
  173. return Type::SignedLong;
  174. case to_underlying(Type::SignedRational):
  175. return Type::SignedRational;
  176. case to_underlying(Type::UTF8):
  177. return Type::UTF8;
  178. default:
  179. return Error::from_string_literal("TIFFImageDecoderPlugin: Unknown type");
  180. }
  181. }
  182. static constexpr u8 size_of_type(Type type)
  183. {
  184. switch (type) {
  185. case Type::Byte:
  186. return 1;
  187. case Type::ASCII:
  188. return 1;
  189. case Type::UnsignedShort:
  190. return 2;
  191. case Type::UnsignedLong:
  192. return 4;
  193. case Type::UnsignedRational:
  194. return 8;
  195. case Type::Undefined:
  196. return 1;
  197. case Type::SignedLong:
  198. return 4;
  199. case Type::SignedRational:
  200. return 8;
  201. case Type::Float:
  202. return 4;
  203. case Type::Double:
  204. return 8;
  205. case Type::UTF8:
  206. return 1;
  207. default:
  208. VERIFY_NOT_REACHED();
  209. }
  210. }
  211. ErrorOr<Vector<Value, 1>> read_tiff_value(Type type, u32 count, u32 offset)
  212. {
  213. auto const old_offset = TRY(m_stream->tell());
  214. ScopeGuard reset_offset { [this, old_offset]() { MUST(m_stream->seek(old_offset)); } };
  215. TRY(m_stream->seek(offset));
  216. if (size_of_type(type) * count > m_stream->remaining())
  217. return Error::from_string_literal("TIFFImageDecoderPlugin: Tag size claims to be bigger that remaining bytes");
  218. auto const read_every_values = [this, count]<typename T>() -> ErrorOr<Vector<Value>> {
  219. Vector<Value, 1> result {};
  220. TRY(result.try_ensure_capacity(count));
  221. if constexpr (IsSpecializationOf<T, Rational>) {
  222. for (u32 i = 0; i < count; ++i)
  223. result.empend(T { TRY(read_value<typename T::Type>()), TRY(read_value<typename T::Type>()) });
  224. } else {
  225. for (u32 i = 0; i < count; ++i)
  226. result.empend(TRY(read_value<T>()));
  227. }
  228. return result;
  229. };
  230. switch (type) {
  231. case Type::Byte:
  232. case Type::Undefined:
  233. return read_every_values.template operator()<u8>();
  234. case Type::ASCII:
  235. case Type::UTF8: {
  236. Vector<Value, 1> result;
  237. auto string_data = TRY(ByteBuffer::create_uninitialized(count));
  238. TRY(m_stream->read_until_filled(string_data));
  239. result.empend(TRY(String::from_utf8(StringView { string_data.bytes() })));
  240. return result;
  241. }
  242. case Type::UnsignedShort:
  243. return read_every_values.template operator()<u16>();
  244. case Type::UnsignedLong:
  245. return read_every_values.template operator()<u32>();
  246. case Type::UnsignedRational:
  247. return read_every_values.template operator()<Rational<u32>>();
  248. case Type::SignedLong:
  249. return read_every_values.template operator()<i32>();
  250. ;
  251. case Type::SignedRational:
  252. return read_every_values.template operator()<Rational<i32>>();
  253. default:
  254. VERIFY_NOT_REACHED();
  255. }
  256. }
  257. ErrorOr<void> read_tag()
  258. {
  259. auto const tag = TRY(read_value<u16>());
  260. auto const type = TRY(read_type());
  261. auto const count = TRY(read_value<u32>());
  262. Checked<u32> checked_size = size_of_type(type);
  263. checked_size *= count;
  264. if (checked_size.has_overflow())
  265. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag with too large data");
  266. auto const tiff_value = TRY(([=, this]() -> ErrorOr<Vector<Value>> {
  267. if (checked_size.value() <= 4) {
  268. auto value = TRY(read_tiff_value(type, count, TRY(m_stream->tell())));
  269. TRY(m_stream->discard(4));
  270. return value;
  271. }
  272. auto const offset = TRY(read_value<u32>());
  273. return read_tiff_value(type, count, offset);
  274. }()));
  275. if constexpr (TIFF_DEBUG) {
  276. if (tiff_value.size() == 1) {
  277. tiff_value[0].visit(
  278. [&](auto const& value) {
  279. dbgln("Read tag({}), type({}): {}", tag, to_underlying(type), value);
  280. });
  281. } else {
  282. dbg("Read tag({}), type({}): [", tag, to_underlying(type));
  283. for (u32 i = 0; i < tiff_value.size(); ++i) {
  284. tiff_value[i].visit(
  285. [&](auto const& value) {
  286. dbg("{}", value);
  287. });
  288. if (i != tiff_value.size() - 1)
  289. dbg(", ");
  290. }
  291. dbgln("]");
  292. }
  293. }
  294. TRY(handle_tag(tag, type, count, tiff_value));
  295. return {};
  296. }
  297. ErrorOr<void> handle_tag(u16 tag, Type type, u32 count, Vector<Value> const& value)
  298. {
  299. // FIXME: Make that easy to extend
  300. switch (tag) {
  301. case 256:
  302. // ImageWidth
  303. if ((type != Type::UnsignedShort && type != Type::UnsignedLong) || count != 1)
  304. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 256");
  305. value[0].visit(
  306. [this]<OneOf<u16, u32> T>(T const& width) {
  307. m_size.set_width(width);
  308. },
  309. [&](auto const&) {
  310. VERIFY_NOT_REACHED();
  311. });
  312. break;
  313. case 257:
  314. // ImageLength
  315. if ((type != Type::UnsignedShort && type != Type::UnsignedLong) || count != 1)
  316. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 257");
  317. value[0].visit(
  318. [this]<OneOf<u16, u32> T>(T const& width) {
  319. m_size.set_height(width);
  320. },
  321. [&](auto const&) {
  322. VERIFY_NOT_REACHED();
  323. });
  324. break;
  325. case 258:
  326. // BitsPerSample
  327. if (type != Type::UnsignedShort || count != 3)
  328. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 258");
  329. for (u8 i = 0; i < m_bits_per_sample.size(); ++i) {
  330. value[i].visit(
  331. [this, i](u16 const& bits_per_sample) {
  332. m_bits_per_sample[i] = bits_per_sample;
  333. },
  334. [&](auto const&) {
  335. VERIFY_NOT_REACHED();
  336. });
  337. }
  338. break;
  339. case 259:
  340. // Compression
  341. if (type != Type::UnsignedShort || count != 1)
  342. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 259");
  343. TRY(value[0].visit(
  344. [this](u16 const& compression) -> ErrorOr<void> {
  345. if (compression > 6 && compression != to_underlying(Compression::PackBits))
  346. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid compression value");
  347. m_compression = static_cast<Compression>(compression);
  348. return {};
  349. },
  350. [&](auto const&) -> ErrorOr<void> {
  351. VERIFY_NOT_REACHED();
  352. }));
  353. break;
  354. case 273:
  355. // StripOffsets
  356. if (type != Type::UnsignedShort && type != Type::UnsignedLong)
  357. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 273");
  358. TRY(m_strip_offsets.try_ensure_capacity(count));
  359. for (u32 i = 0; i < count; ++i) {
  360. value[i].visit(
  361. [this]<OneOf<u16, u32> T>(T const& offset) {
  362. m_strip_offsets.append(offset);
  363. },
  364. [&](auto const&) {
  365. VERIFY_NOT_REACHED();
  366. });
  367. }
  368. break;
  369. case 277:
  370. // SamplesPerPixel
  371. if (type != Type::UnsignedShort || count != 1)
  372. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 277");
  373. TRY(value[0].visit(
  374. [](u16 const& samples_per_pixels) -> ErrorOr<void> {
  375. if (samples_per_pixels != 3)
  376. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 277");
  377. return {};
  378. },
  379. [&](auto const&) -> ErrorOr<void> {
  380. VERIFY_NOT_REACHED();
  381. }));
  382. break;
  383. case 278:
  384. // RowsPerStrip
  385. if ((type != Type::UnsignedShort && type != Type::UnsignedLong) || count != 1)
  386. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 278");
  387. value[0].visit(
  388. [this]<OneOf<u16, u32> T>(T const& rows_per_strip) {
  389. m_rows_per_strip = rows_per_strip;
  390. },
  391. [&](auto const&) {
  392. VERIFY_NOT_REACHED();
  393. });
  394. break;
  395. case 279:
  396. // StripByteCounts
  397. if (type != Type::UnsignedShort && type != Type::UnsignedLong)
  398. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid tag 279");
  399. TRY(m_strip_bytes_count.try_ensure_capacity(count));
  400. for (u32 i = 0; i < count; ++i) {
  401. value[i].visit(
  402. [this]<OneOf<u16, u32> T>(T const& offset) {
  403. m_strip_bytes_count.append(offset);
  404. },
  405. [&](auto const&) {
  406. VERIFY_NOT_REACHED();
  407. });
  408. }
  409. break;
  410. default:
  411. dbgln_if(TIFF_DEBUG, "Unknown tag: {}", tag);
  412. }
  413. return {};
  414. }
  415. NonnullOwnPtr<FixedMemoryStream> m_stream;
  416. IntSize m_size {};
  417. State m_state {};
  418. RefPtr<Bitmap> m_bitmap {};
  419. ByteOrder m_byte_order {};
  420. Optional<u32> m_next_ifd {};
  421. Array<u16, 3> m_bits_per_sample {};
  422. Compression m_compression {};
  423. Vector<u32> m_strip_offsets {};
  424. u32 m_rows_per_strip {};
  425. Vector<u32> m_strip_bytes_count {};
  426. };
  427. TIFFImageDecoderPlugin::TIFFImageDecoderPlugin(NonnullOwnPtr<FixedMemoryStream> stream)
  428. {
  429. m_context = make<TIFFLoadingContext>(move(stream));
  430. }
  431. bool TIFFImageDecoderPlugin::sniff(ReadonlyBytes bytes)
  432. {
  433. if (bytes.size() < 4)
  434. return false;
  435. bool const valid_little_endian = bytes[0] == 0x49 && bytes[1] == 0x49 && bytes[2] == 0x2A && bytes[3] == 0x00;
  436. bool const valid_big_endian = bytes[0] == 0x4D && bytes[1] == 0x4D && bytes[2] == 0x00 && bytes[3] == 0x2A;
  437. return valid_little_endian || valid_big_endian;
  438. }
  439. IntSize TIFFImageDecoderPlugin::size()
  440. {
  441. return m_context->size();
  442. }
  443. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> TIFFImageDecoderPlugin::create(ReadonlyBytes data)
  444. {
  445. auto stream = TRY(try_make<FixedMemoryStream>(data));
  446. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) TIFFImageDecoderPlugin(move(stream))));
  447. TRY(plugin->m_context->decode_image_header());
  448. return plugin;
  449. }
  450. ErrorOr<ImageFrameDescriptor> TIFFImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  451. {
  452. if (index > 0)
  453. return Error::from_string_literal("TIFFImageDecoderPlugin: Invalid frame index");
  454. if (m_context->state() == TIFFLoadingContext::State::Error)
  455. return Error::from_string_literal("TIFFImageDecoderPlugin: Decoding failed");
  456. if (m_context->state() < TIFFLoadingContext::State::FrameDecoded)
  457. TRY(m_context->decode_frame());
  458. return ImageFrameDescriptor { m_context->bitmap(), 0 };
  459. }
  460. }
  461. template<typename T>
  462. struct AK::Formatter<Gfx::TIFFLoadingContext::Rational<T>> : Formatter<FormatString> {
  463. ErrorOr<void> format(FormatBuilder& builder, Gfx::TIFFLoadingContext::Rational<T> value)
  464. {
  465. return Formatter<FormatString>::format(builder, "{} ({}/{})"sv, static_cast<double>(value.numerator) / value.denominator, value.numerator, value.denominator);
  466. }
  467. };