Filter.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. return Error::malformed_error("Unrecognized filter encoding {}", encoding_type);
  49. }
  50. PDFErrorOr<ByteBuffer> Filter::decode_ascii_hex(ReadonlyBytes bytes)
  51. {
  52. ByteBuffer output;
  53. bool have_read_high_nibble = false;
  54. u8 high_nibble = 0;
  55. for (u8 byte : bytes) {
  56. // 3.3.1 ASCIIHexDecode Filter
  57. // All white-space characters [...] are ignored.
  58. // FIXME: Any other characters cause an error.
  59. if (is_ascii_hex_digit(byte)) {
  60. u8 hex_digit = decode_hex_digit(byte);
  61. if (have_read_high_nibble) {
  62. u8 full_byte = (high_nibble << 4) | hex_digit;
  63. TRY(output.try_append(full_byte));
  64. have_read_high_nibble = false;
  65. } else {
  66. high_nibble = hex_digit;
  67. have_read_high_nibble = true;
  68. }
  69. }
  70. }
  71. // If the filter encounters the EOD marker after reading an odd number
  72. // of hexadecimal digits, it behaves as if a 0 followed the last digit.
  73. if (have_read_high_nibble)
  74. TRY(output.try_append(high_nibble << 4));
  75. return output;
  76. };
  77. PDFErrorOr<ByteBuffer> Filter::decode_ascii85(ReadonlyBytes bytes)
  78. {
  79. Vector<u8> buff;
  80. buff.ensure_capacity(bytes.size());
  81. size_t byte_index = 0;
  82. while (byte_index < bytes.size()) {
  83. if (bytes[byte_index] == ' ') {
  84. byte_index++;
  85. continue;
  86. }
  87. if (bytes[byte_index] == 'z') {
  88. byte_index++;
  89. for (int i = 0; i < 4; i++)
  90. buff.append(0);
  91. continue;
  92. }
  93. u32 number = 0;
  94. if (byte_index + 5 >= bytes.size()) {
  95. auto to_write = bytes.size() - byte_index;
  96. for (int i = 0; i < 5; i++) {
  97. auto byte = byte_index >= bytes.size() ? 'u' : bytes[byte_index++];
  98. if (byte == ' ') {
  99. i--;
  100. continue;
  101. }
  102. number = number * 85 + byte - 33;
  103. }
  104. for (size_t i = 0; i < to_write - 1; i++)
  105. buff.append(reinterpret_cast<u8*>(&number)[3 - i]);
  106. break;
  107. } else {
  108. for (int i = 0; i < 5; i++) {
  109. auto byte = bytes[byte_index++];
  110. if (byte == ' ') {
  111. i--;
  112. continue;
  113. }
  114. number = number * 85 + byte - 33;
  115. }
  116. }
  117. for (int i = 0; i < 4; i++)
  118. buff.append(reinterpret_cast<u8*>(&number)[3 - i]);
  119. }
  120. return TRY(ByteBuffer::copy(buff.span()));
  121. };
  122. PDFErrorOr<ByteBuffer> Filter::decode_png_prediction(Bytes bytes, int bytes_per_row)
  123. {
  124. int number_of_rows = bytes.size() / bytes_per_row;
  125. ByteBuffer decoded;
  126. decoded.ensure_capacity(bytes.size() - number_of_rows);
  127. auto empty_row = TRY(ByteBuffer::create_zeroed(bytes_per_row));
  128. auto previous_row = empty_row.data();
  129. for (int row_index = 0; row_index < number_of_rows; ++row_index) {
  130. auto row = bytes.data() + row_index * bytes_per_row;
  131. u8 algorithm_tag = row[0];
  132. switch (algorithm_tag) {
  133. case 0:
  134. break;
  135. case 1:
  136. for (int i = 2; i < bytes_per_row; ++i)
  137. row[i] += row[i - 1];
  138. break;
  139. case 2:
  140. for (int i = 1; i < bytes_per_row; ++i)
  141. row[i] += previous_row[i];
  142. break;
  143. case 3:
  144. for (int i = 1; i < bytes_per_row; ++i) {
  145. u8 left = 0;
  146. if (i > 1)
  147. left = row[i - 1];
  148. u8 above = previous_row[i];
  149. row[i] += (left + above) / 2;
  150. }
  151. break;
  152. case 4:
  153. for (int i = 1; i < bytes_per_row; ++i) {
  154. u8 left = 0;
  155. u8 upper_left = 0;
  156. if (i > 1) {
  157. left = row[i - 1];
  158. upper_left = previous_row[i - 1];
  159. }
  160. u8 above = previous_row[i];
  161. u8 p = left + above - upper_left;
  162. int left_distance = abs(p - left);
  163. int above_distance = abs(p - above);
  164. int upper_left_distance = abs(p - upper_left);
  165. u8 paeth = min(left_distance, min(above_distance, upper_left_distance));
  166. row[i] += paeth;
  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::decode_lzw(ReadonlyBytes)
  178. {
  179. return Error::rendering_unsupported_error("LZW Filter is not supported");
  180. };
  181. PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component)
  182. {
  183. auto buff = Compress::DeflateDecompressor::decompress_all(bytes.slice(2)).value();
  184. if (predictor == 1)
  185. return buff;
  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 bytes_per_row = AK::ceil_div(columns * colors * bits_per_component, 8) + 1;
  193. if (buff.size() % bytes_per_row)
  194. return AK::Error::from_string_literal("Flate input data is not divisible into columns");
  195. return decode_png_prediction(buff, bytes_per_row);
  196. };
  197. PDFErrorOr<ByteBuffer> Filter::decode_run_length(ReadonlyBytes bytes)
  198. {
  199. constexpr size_t END_OF_DECODING = 128;
  200. ByteBuffer buffer {};
  201. while (true) {
  202. VERIFY(bytes.size() > 0);
  203. auto length = bytes[0];
  204. bytes = bytes.slice(1);
  205. if (length == END_OF_DECODING) {
  206. VERIFY(bytes.is_empty());
  207. break;
  208. }
  209. if (length < 128) {
  210. TRY(buffer.try_append(bytes.slice(0, length + 1)));
  211. bytes = bytes.slice(length + 1);
  212. } else {
  213. VERIFY(bytes.size() > 1);
  214. auto byte_to_append = bytes[0];
  215. bytes = bytes.slice(1);
  216. size_t n_chars = 257 - length;
  217. for (size_t i = 0; i < n_chars; ++i) {
  218. TRY(buffer.try_append(byte_to_append));
  219. }
  220. }
  221. }
  222. return buffer;
  223. };
  224. PDFErrorOr<ByteBuffer> Filter::decode_ccitt(ReadonlyBytes)
  225. {
  226. return Error::rendering_unsupported_error("CCITTFaxDecode Filter is unsupported");
  227. };
  228. PDFErrorOr<ByteBuffer> Filter::decode_jbig2(ReadonlyBytes)
  229. {
  230. return Error::rendering_unsupported_error("JBIG2 Filter is unsupported");
  231. };
  232. PDFErrorOr<ByteBuffer> Filter::decode_dct(ReadonlyBytes bytes)
  233. {
  234. if (Gfx::JPEGImageDecoderPlugin::sniff({ bytes.data(), bytes.size() })) {
  235. auto decoder = Gfx::JPEGImageDecoderPlugin::create({ bytes.data(), bytes.size() }).release_value_but_fixme_should_propagate_errors();
  236. if (decoder->initialize()) {
  237. auto frame = TRY(decoder->frame(0));
  238. return TRY(frame.image->serialize_to_byte_buffer());
  239. }
  240. }
  241. return AK::Error::from_string_literal("Not a JPEG image!");
  242. };
  243. PDFErrorOr<ByteBuffer> Filter::decode_jpx(ReadonlyBytes)
  244. {
  245. return Error::rendering_unsupported_error("JPX Filter is not supported");
  246. };
  247. PDFErrorOr<ByteBuffer> Filter::decode_crypt(ReadonlyBytes)
  248. {
  249. return Error::rendering_unsupported_error("Crypt Filter is not supported");
  250. };
  251. }