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