Filter.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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, int 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));
  133. auto previous_row = empty_row.data();
  134. for (int row_index = 0; row_index < number_of_rows; ++row_index) {
  135. auto row = bytes.data() + row_index * bytes_per_row;
  136. auto filter = TRY(Gfx::PNG::filter_type(row[0]));
  137. switch (filter) {
  138. case Gfx::PNG::FilterType::None:
  139. break;
  140. case Gfx::PNG::FilterType::Sub:
  141. for (int i = 2; i < bytes_per_row; ++i)
  142. row[i] += row[i - 1];
  143. break;
  144. case Gfx::PNG::FilterType::Up:
  145. for (int i = 1; i < bytes_per_row; ++i)
  146. row[i] += previous_row[i];
  147. break;
  148. case Gfx::PNG::FilterType::Average:
  149. for (int i = 1; i < bytes_per_row; ++i) {
  150. u8 left = 0;
  151. if (i > 1)
  152. left = row[i - 1];
  153. u8 above = previous_row[i];
  154. row[i] += (left + above) / 2;
  155. }
  156. break;
  157. case Gfx::PNG::FilterType::Paeth:
  158. for (int i = 1; i < bytes_per_row; ++i) {
  159. u8 left = 0;
  160. u8 upper_left = 0;
  161. if (i > 1) {
  162. left = row[i - 1];
  163. upper_left = previous_row[i - 1];
  164. }
  165. u8 above = previous_row[i];
  166. row[i] += Gfx::PNG::paeth_predictor(left, above, upper_left);
  167. }
  168. break;
  169. }
  170. previous_row = row;
  171. decoded.append(row + 1, bytes_per_row - 1);
  172. }
  173. return decoded;
  174. }
  175. PDFErrorOr<ByteBuffer> Filter::handle_lzw_and_flate_parameters(ByteBuffer buffer, int predictor, int columns, int colors, int bits_per_component)
  176. {
  177. // Table 3.7 Optional parameters for LZWDecode and FlateDecode filters
  178. if (predictor == 1)
  179. return buffer;
  180. // Check if we are dealing with a PNG prediction
  181. if (predictor == 2)
  182. return AK::Error::from_string_literal("The TIFF predictor is not supported");
  183. if (predictor < 10 || predictor > 15)
  184. return AK::Error::from_string_literal("Invalid predictor value");
  185. // Rows are always a whole number of bytes long, starting with an algorithm tag
  186. int const bytes_per_row = AK::ceil_div(columns * colors * bits_per_component, 8) + 1;
  187. if (buffer.size() % bytes_per_row)
  188. return AK::Error::from_string_literal("Flate input data is not divisible into columns");
  189. return decode_png_prediction(buffer, bytes_per_row);
  190. }
  191. PDFErrorOr<ByteBuffer> Filter::decode_lzw(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component, int early_change)
  192. {
  193. auto memory_stream = make<FixedMemoryStream>(bytes);
  194. auto lzw_stream = make<BigEndianInputBitStream>(MaybeOwned<Stream>(move(memory_stream)));
  195. Compress::LZWDecoder lzw_decoder { MaybeOwned<BigEndianInputBitStream> { move(lzw_stream) }, 8, -early_change };
  196. ByteBuffer decoded;
  197. u16 const clear_code = lzw_decoder.add_control_code();
  198. u16 const end_of_data_code = lzw_decoder.add_control_code();
  199. while (true) {
  200. auto const code = TRY(lzw_decoder.next_code());
  201. if (code == clear_code) {
  202. lzw_decoder.reset();
  203. continue;
  204. }
  205. if (code == end_of_data_code)
  206. break;
  207. TRY(decoded.try_append(lzw_decoder.get_output()));
  208. }
  209. return handle_lzw_and_flate_parameters(move(decoded), predictor, columns, colors, bits_per_component);
  210. }
  211. PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component)
  212. {
  213. auto buff = TRY(Compress::DeflateDecompressor::decompress_all(bytes.slice(2)));
  214. return handle_lzw_and_flate_parameters(move(buff), predictor, columns, colors, bits_per_component);
  215. }
  216. PDFErrorOr<ByteBuffer> Filter::decode_run_length(ReadonlyBytes bytes)
  217. {
  218. constexpr size_t END_OF_DECODING = 128;
  219. ByteBuffer buffer {};
  220. while (true) {
  221. VERIFY(bytes.size() > 0);
  222. auto length = bytes[0];
  223. bytes = bytes.slice(1);
  224. if (length == END_OF_DECODING) {
  225. VERIFY(bytes.is_empty());
  226. break;
  227. }
  228. if (length < 128) {
  229. TRY(buffer.try_append(bytes.slice(0, length + 1)));
  230. bytes = bytes.slice(length + 1);
  231. } else {
  232. VERIFY(bytes.size() > 1);
  233. auto byte_to_append = bytes[0];
  234. bytes = bytes.slice(1);
  235. size_t n_chars = 257 - length;
  236. for (size_t i = 0; i < n_chars; ++i) {
  237. TRY(buffer.try_append(byte_to_append));
  238. }
  239. }
  240. }
  241. return buffer;
  242. }
  243. PDFErrorOr<ByteBuffer> Filter::decode_ccitt(ReadonlyBytes)
  244. {
  245. return Error::rendering_unsupported_error("CCITTFaxDecode Filter is unsupported");
  246. }
  247. PDFErrorOr<ByteBuffer> Filter::decode_jbig2(ReadonlyBytes)
  248. {
  249. return Error::rendering_unsupported_error("JBIG2 Filter is unsupported");
  250. }
  251. PDFErrorOr<ByteBuffer> Filter::decode_dct(ReadonlyBytes bytes)
  252. {
  253. if (Gfx::JPEGImageDecoderPlugin::sniff({ bytes.data(), bytes.size() })) {
  254. auto decoder = TRY(Gfx::JPEGImageDecoderPlugin::create({ bytes.data(), bytes.size() }));
  255. auto frame = TRY(decoder->frame(0));
  256. return TRY(frame.image->serialize_to_byte_buffer());
  257. }
  258. return AK::Error::from_string_literal("Not a JPEG image!");
  259. }
  260. PDFErrorOr<ByteBuffer> Filter::decode_jpx(ReadonlyBytes)
  261. {
  262. return Error::rendering_unsupported_error("JPX Filter is not supported");
  263. }
  264. PDFErrorOr<ByteBuffer> Filter::decode_crypt(ReadonlyBytes)
  265. {
  266. return Error::rendering_unsupported_error("Crypt Filter is not supported");
  267. }
  268. }