Filter.cpp 11 KB

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