Filter.cpp 9.7 KB

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