Filter.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. * Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/BitStream.h>
  7. #include <AK/Hex.h>
  8. #include <LibCompress/Deflate.h>
  9. #include <LibCompress/LZWDecoder.h>
  10. #include <LibGfx/ImageFormats/JPEGLoader.h>
  11. #include <LibGfx/ImageFormats/PNGShared.h>
  12. #include <LibPDF/CommonNames.h>
  13. #include <LibPDF/Filter.h>
  14. #include <LibPDF/Reader.h>
  15. namespace PDF {
  16. PDFErrorOr<ByteBuffer> Filter::decode(ReadonlyBytes bytes, DeprecatedFlyString const& encoding_type, RefPtr<DictObject> decode_parms)
  17. {
  18. int predictor = 1;
  19. int columns = 1;
  20. int colors = 1;
  21. int bits_per_component = 8;
  22. int early_change = 1;
  23. if (decode_parms) {
  24. if (decode_parms->contains(CommonNames::Predictor))
  25. predictor = decode_parms->get_value(CommonNames::Predictor).get<int>();
  26. if (decode_parms->contains(CommonNames::Columns))
  27. columns = decode_parms->get_value(CommonNames::Columns).get<int>();
  28. if (decode_parms->contains(CommonNames::Colors))
  29. colors = decode_parms->get_value(CommonNames::Colors).get<int>();
  30. if (decode_parms->contains(CommonNames::BitsPerComponent))
  31. bits_per_component = decode_parms->get_value(CommonNames::BitsPerComponent).get<int>();
  32. if (decode_parms->contains(CommonNames::EarlyChange))
  33. early_change = decode_parms->get_value(CommonNames::EarlyChange).get<int>();
  34. }
  35. if (encoding_type == CommonNames::ASCIIHexDecode)
  36. return decode_ascii_hex(bytes);
  37. if (encoding_type == CommonNames::ASCII85Decode)
  38. return decode_ascii85(bytes);
  39. if (encoding_type == CommonNames::LZWDecode)
  40. return decode_lzw(bytes, predictor, columns, colors, bits_per_component, early_change);
  41. if (encoding_type == CommonNames::FlateDecode)
  42. return decode_flate(bytes, predictor, columns, colors, bits_per_component);
  43. if (encoding_type == CommonNames::RunLengthDecode)
  44. return decode_run_length(bytes);
  45. if (encoding_type == CommonNames::CCITTFaxDecode)
  46. return decode_ccitt(bytes);
  47. if (encoding_type == CommonNames::JBIG2Decode)
  48. return decode_jbig2(bytes);
  49. if (encoding_type == CommonNames::DCTDecode)
  50. return decode_dct(bytes);
  51. if (encoding_type == CommonNames::JPXDecode)
  52. return decode_jpx(bytes);
  53. if (encoding_type == CommonNames::Crypt)
  54. return decode_crypt(bytes);
  55. dbgln_if(PDF_DEBUG, "Unrecognized filter encoding {}", encoding_type);
  56. return Error::malformed_error("Unrecognized filter encoding");
  57. }
  58. PDFErrorOr<ByteBuffer> Filter::decode_ascii_hex(ReadonlyBytes bytes)
  59. {
  60. ByteBuffer output;
  61. bool have_read_high_nibble = false;
  62. u8 high_nibble = 0;
  63. for (u8 byte : bytes) {
  64. // 3.3.1 ASCIIHexDecode Filter
  65. // All white-space characters [...] are ignored.
  66. // FIXME: Any other characters cause an error.
  67. if (is_ascii_hex_digit(byte)) {
  68. u8 hex_digit = decode_hex_digit(byte);
  69. if (have_read_high_nibble) {
  70. u8 full_byte = (high_nibble << 4) | hex_digit;
  71. TRY(output.try_append(full_byte));
  72. have_read_high_nibble = false;
  73. } else {
  74. high_nibble = hex_digit;
  75. have_read_high_nibble = true;
  76. }
  77. }
  78. }
  79. // If the filter encounters the EOD marker after reading an odd number
  80. // of hexadecimal digits, it behaves as if a 0 followed the last digit.
  81. if (have_read_high_nibble)
  82. TRY(output.try_append(high_nibble << 4));
  83. return output;
  84. }
  85. PDFErrorOr<ByteBuffer> Filter::decode_ascii85(ReadonlyBytes bytes)
  86. {
  87. // 3.3.2 ASCII85Decode Filter
  88. ByteBuffer buffer;
  89. TRY(buffer.try_ensure_capacity(bytes.size()));
  90. size_t byte_index = 0;
  91. while (byte_index < bytes.size()) {
  92. if (Reader::is_whitespace(bytes[byte_index])) {
  93. byte_index++;
  94. continue;
  95. }
  96. if (bytes[byte_index] == 'z') {
  97. byte_index++;
  98. for (int i = 0; i < 4; i++)
  99. buffer.append(0);
  100. continue;
  101. }
  102. u32 number = 0;
  103. auto to_write = byte_index + 5 >= bytes.size() ? bytes.size() - byte_index : 5;
  104. Optional<u32> end_of_data_index {};
  105. for (int i = 0; i < 5; i++) {
  106. // We check for the EOD sequence '~>', but as '~' can only appear in
  107. // this sequence, there is no need to check for '>'.
  108. if (!end_of_data_index.has_value() && bytes[byte_index] == '~') {
  109. end_of_data_index = i;
  110. to_write = i + 1;
  111. }
  112. bool const should_fake_end = byte_index >= bytes.size() || end_of_data_index.has_value();
  113. auto const byte = should_fake_end ? 'u' : bytes[byte_index++];
  114. if (Reader::is_whitespace(byte)) {
  115. i--;
  116. continue;
  117. }
  118. number = number * 85 + byte - 33;
  119. }
  120. for (size_t i = 0; i < to_write - 1; i++)
  121. buffer.append(reinterpret_cast<u8*>(&number)[3 - i]);
  122. if (end_of_data_index.has_value())
  123. break;
  124. }
  125. return buffer;
  126. }
  127. PDFErrorOr<ByteBuffer> Filter::decode_png_prediction(Bytes bytes, size_t bytes_per_row)
  128. {
  129. int number_of_rows = bytes.size() / bytes_per_row;
  130. ByteBuffer decoded;
  131. decoded.ensure_capacity(bytes.size() - number_of_rows);
  132. auto empty_row = TRY(ByteBuffer::create_zeroed(bytes_per_row - 1));
  133. auto previous_row = empty_row.bytes();
  134. for (int row_index = 0; row_index < number_of_rows; ++row_index) {
  135. auto row = Bytes { bytes.data() + row_index * bytes_per_row, bytes_per_row };
  136. auto filter = TRY(Gfx::PNG::filter_type(row[0]));
  137. row = row.slice(1);
  138. switch (filter) {
  139. case Gfx::PNG::FilterType::None:
  140. break;
  141. case Gfx::PNG::FilterType::Sub:
  142. for (size_t i = 1; i < row.size(); ++i)
  143. row[i] += row[i - 1];
  144. break;
  145. case Gfx::PNG::FilterType::Up:
  146. for (size_t i = 0; i < row.size(); ++i)
  147. row[i] += previous_row[i];
  148. break;
  149. case Gfx::PNG::FilterType::Average:
  150. for (size_t i = 0; i < row.size(); ++i) {
  151. u8 left = 0;
  152. if (i > 0)
  153. left = row[i - 1];
  154. u8 above = previous_row[i];
  155. row[i] += (left + above) / 2;
  156. }
  157. break;
  158. case Gfx::PNG::FilterType::Paeth:
  159. for (size_t i = 0; i < row.size(); ++i) {
  160. u8 left = 0;
  161. u8 upper_left = 0;
  162. if (i > 0) {
  163. left = row[i - 1];
  164. upper_left = previous_row[i - 1];
  165. }
  166. u8 above = previous_row[i];
  167. row[i] += Gfx::PNG::paeth_predictor(left, above, upper_left);
  168. }
  169. break;
  170. }
  171. previous_row = row;
  172. decoded.append(row);
  173. }
  174. return decoded;
  175. }
  176. PDFErrorOr<ByteBuffer> Filter::handle_lzw_and_flate_parameters(ByteBuffer buffer, int predictor, int columns, int colors, int bits_per_component)
  177. {
  178. // Table 3.7 Optional parameters for LZWDecode and FlateDecode filters
  179. if (predictor == 1)
  180. return buffer;
  181. // Check if we are dealing with a PNG prediction
  182. if (predictor == 2)
  183. return AK::Error::from_string_literal("The TIFF predictor is not supported");
  184. if (predictor < 10 || predictor > 15)
  185. return AK::Error::from_string_literal("Invalid predictor value");
  186. // Rows are always a whole number of bytes long, starting with an algorithm tag
  187. size_t const bytes_per_row = ceil_div(columns * colors * bits_per_component, 8) + 1;
  188. if (buffer.size() % bytes_per_row)
  189. return AK::Error::from_string_literal("Flate input data is not divisible into columns");
  190. return decode_png_prediction(buffer, bytes_per_row);
  191. }
  192. PDFErrorOr<ByteBuffer> Filter::decode_lzw(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component, int early_change)
  193. {
  194. auto memory_stream = make<FixedMemoryStream>(bytes);
  195. auto lzw_stream = make<BigEndianInputBitStream>(MaybeOwned<Stream>(move(memory_stream)));
  196. Compress::LZWDecoder lzw_decoder { MaybeOwned<BigEndianInputBitStream> { move(lzw_stream) }, 8, -early_change };
  197. ByteBuffer decoded;
  198. u16 const clear_code = lzw_decoder.add_control_code();
  199. u16 const end_of_data_code = lzw_decoder.add_control_code();
  200. while (true) {
  201. auto const code = TRY(lzw_decoder.next_code());
  202. if (code == clear_code) {
  203. lzw_decoder.reset();
  204. continue;
  205. }
  206. if (code == end_of_data_code)
  207. break;
  208. TRY(decoded.try_append(lzw_decoder.get_output()));
  209. }
  210. return handle_lzw_and_flate_parameters(move(decoded), predictor, columns, colors, bits_per_component);
  211. }
  212. PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component)
  213. {
  214. auto buff = TRY(Compress::DeflateDecompressor::decompress_all(bytes.slice(2)));
  215. return handle_lzw_and_flate_parameters(move(buff), predictor, columns, colors, bits_per_component);
  216. }
  217. PDFErrorOr<ByteBuffer> Filter::decode_run_length(ReadonlyBytes bytes)
  218. {
  219. constexpr size_t END_OF_DECODING = 128;
  220. ByteBuffer buffer {};
  221. while (true) {
  222. VERIFY(bytes.size() > 0);
  223. auto length = bytes[0];
  224. bytes = bytes.slice(1);
  225. if (length == END_OF_DECODING) {
  226. VERIFY(bytes.is_empty());
  227. break;
  228. }
  229. if (length < 128) {
  230. TRY(buffer.try_append(bytes.slice(0, length + 1)));
  231. bytes = bytes.slice(length + 1);
  232. } else {
  233. VERIFY(bytes.size() > 1);
  234. auto byte_to_append = bytes[0];
  235. bytes = bytes.slice(1);
  236. size_t n_chars = 257 - length;
  237. for (size_t i = 0; i < n_chars; ++i) {
  238. TRY(buffer.try_append(byte_to_append));
  239. }
  240. }
  241. }
  242. return buffer;
  243. }
  244. PDFErrorOr<ByteBuffer> Filter::decode_ccitt(ReadonlyBytes)
  245. {
  246. return Error::rendering_unsupported_error("CCITTFaxDecode Filter is unsupported");
  247. }
  248. PDFErrorOr<ByteBuffer> Filter::decode_jbig2(ReadonlyBytes)
  249. {
  250. return Error::rendering_unsupported_error("JBIG2 Filter is unsupported");
  251. }
  252. PDFErrorOr<ByteBuffer> Filter::decode_dct(ReadonlyBytes bytes)
  253. {
  254. if (Gfx::JPEGImageDecoderPlugin::sniff({ bytes.data(), bytes.size() })) {
  255. auto decoder = TRY(Gfx::JPEGImageDecoderPlugin::create({ bytes.data(), bytes.size() }));
  256. auto frame = TRY(decoder->frame(0));
  257. return TRY(frame.image->serialize_to_byte_buffer());
  258. }
  259. return AK::Error::from_string_literal("Not a JPEG image!");
  260. }
  261. PDFErrorOr<ByteBuffer> Filter::decode_jpx(ReadonlyBytes)
  262. {
  263. return Error::rendering_unsupported_error("JPX Filter is not supported");
  264. }
  265. PDFErrorOr<ByteBuffer> Filter::decode_crypt(ReadonlyBytes)
  266. {
  267. return Error::rendering_unsupported_error("Crypt Filter is not supported");
  268. }
  269. }