Filter.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. if (bytes.size() % 2 == 0)
  53. return TRY(decode_hex(bytes));
  54. // FIXME: Integrate this padding into AK/Hex?
  55. auto output = TRY(ByteBuffer::create_zeroed(bytes.size() / 2 + 1));
  56. for (size_t i = 0; i < bytes.size() / 2; ++i) {
  57. auto const c1 = decode_hex_digit(static_cast<char>(bytes[i * 2]));
  58. if (c1 >= 16)
  59. return AK::Error::from_string_literal("Hex string contains invalid digit");
  60. auto const c2 = decode_hex_digit(static_cast<char>(bytes[i * 2 + 1]));
  61. if (c2 >= 16)
  62. return AK::Error::from_string_literal("Hex string contains invalid digit");
  63. output[i] = (c1 << 4) + c2;
  64. }
  65. // Process last byte with a padded zero
  66. output[output.size() - 1] = decode_hex_digit(static_cast<char>(bytes[bytes.size() - 1])) * 16;
  67. return { move(output) };
  68. };
  69. PDFErrorOr<ByteBuffer> Filter::decode_ascii85(ReadonlyBytes bytes)
  70. {
  71. Vector<u8> buff;
  72. buff.ensure_capacity(bytes.size());
  73. size_t byte_index = 0;
  74. while (byte_index < bytes.size()) {
  75. if (bytes[byte_index] == ' ') {
  76. byte_index++;
  77. continue;
  78. }
  79. if (bytes[byte_index] == 'z') {
  80. byte_index++;
  81. for (int i = 0; i < 4; i++)
  82. buff.append(0);
  83. continue;
  84. }
  85. u32 number = 0;
  86. if (byte_index + 5 >= bytes.size()) {
  87. auto to_write = bytes.size() - byte_index;
  88. for (int i = 0; i < 5; i++) {
  89. auto byte = byte_index >= bytes.size() ? 'u' : bytes[byte_index++];
  90. if (byte == ' ') {
  91. i--;
  92. continue;
  93. }
  94. number = number * 85 + byte - 33;
  95. }
  96. for (size_t i = 0; i < to_write - 1; i++)
  97. buff.append(reinterpret_cast<u8*>(&number)[3 - i]);
  98. break;
  99. } else {
  100. for (int i = 0; i < 5; i++) {
  101. auto byte = bytes[byte_index++];
  102. if (byte == ' ') {
  103. i--;
  104. continue;
  105. }
  106. number = number * 85 + byte - 33;
  107. }
  108. }
  109. for (int i = 0; i < 4; i++)
  110. buff.append(reinterpret_cast<u8*>(&number)[3 - i]);
  111. }
  112. return TRY(ByteBuffer::copy(buff.span()));
  113. };
  114. PDFErrorOr<ByteBuffer> Filter::decode_png_prediction(Bytes bytes, int bytes_per_row)
  115. {
  116. int number_of_rows = bytes.size() / bytes_per_row;
  117. ByteBuffer decoded;
  118. decoded.ensure_capacity(bytes.size() - number_of_rows);
  119. auto empty_row = TRY(ByteBuffer::create_zeroed(bytes_per_row));
  120. auto previous_row = empty_row.data();
  121. for (int row_index = 0; row_index < number_of_rows; ++row_index) {
  122. auto row = bytes.data() + row_index * bytes_per_row;
  123. u8 algorithm_tag = row[0];
  124. switch (algorithm_tag) {
  125. case 0:
  126. break;
  127. case 1:
  128. for (int i = 2; i < bytes_per_row; ++i)
  129. row[i] += row[i - 1];
  130. break;
  131. case 2:
  132. for (int i = 1; i < bytes_per_row; ++i)
  133. row[i] += previous_row[i];
  134. break;
  135. case 3:
  136. for (int i = 1; i < bytes_per_row; ++i) {
  137. u8 left = 0;
  138. if (i > 1)
  139. left = row[i - 1];
  140. u8 above = previous_row[i];
  141. row[i] += (left + above) / 2;
  142. }
  143. break;
  144. case 4:
  145. for (int i = 1; i < bytes_per_row; ++i) {
  146. u8 left = 0;
  147. u8 upper_left = 0;
  148. if (i > 1) {
  149. left = row[i - 1];
  150. upper_left = previous_row[i - 1];
  151. }
  152. u8 above = previous_row[i];
  153. u8 p = left + above - upper_left;
  154. int left_distance = abs(p - left);
  155. int above_distance = abs(p - above);
  156. int upper_left_distance = abs(p - upper_left);
  157. u8 paeth = min(left_distance, min(above_distance, upper_left_distance));
  158. row[i] += paeth;
  159. }
  160. break;
  161. default:
  162. return AK::Error::from_string_literal("Unknown PNG algorithm tag");
  163. }
  164. previous_row = row;
  165. decoded.append(row + 1, bytes_per_row - 1);
  166. }
  167. return decoded;
  168. }
  169. PDFErrorOr<ByteBuffer> Filter::decode_lzw(ReadonlyBytes)
  170. {
  171. return Error::rendering_unsupported_error("LZW Filter is not supported");
  172. };
  173. PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component)
  174. {
  175. auto buff = Compress::DeflateDecompressor::decompress_all(bytes.slice(2)).value();
  176. if (predictor == 1)
  177. return buff;
  178. // Check if we are dealing with a PNG prediction
  179. if (predictor == 2)
  180. return AK::Error::from_string_literal("The TIFF predictor is not supported");
  181. if (predictor < 10 || predictor > 15)
  182. return AK::Error::from_string_literal("Invalid predictor value");
  183. // Rows are always a whole number of bytes long, starting with an algorithm tag
  184. int bytes_per_row = AK::ceil_div(columns * colors * bits_per_component, 8) + 1;
  185. if (buff.size() % bytes_per_row)
  186. return AK::Error::from_string_literal("Flate input data is not divisible into columns");
  187. return decode_png_prediction(buff, bytes_per_row);
  188. };
  189. PDFErrorOr<ByteBuffer> Filter::decode_run_length(ReadonlyBytes bytes)
  190. {
  191. constexpr size_t END_OF_DECODING = 128;
  192. ByteBuffer buffer {};
  193. while (true) {
  194. VERIFY(bytes.size() > 0);
  195. auto length = bytes[0];
  196. bytes = bytes.slice(1);
  197. if (length == END_OF_DECODING) {
  198. VERIFY(bytes.is_empty());
  199. break;
  200. }
  201. if (length < 128) {
  202. TRY(buffer.try_append(bytes.slice(0, length + 1)));
  203. bytes = bytes.slice(length + 1);
  204. } else {
  205. VERIFY(bytes.size() > 1);
  206. auto byte_to_append = bytes[0];
  207. bytes = bytes.slice(1);
  208. size_t n_chars = 257 - length;
  209. for (size_t i = 0; i < n_chars; ++i) {
  210. TRY(buffer.try_append(byte_to_append));
  211. }
  212. }
  213. }
  214. return buffer;
  215. };
  216. PDFErrorOr<ByteBuffer> Filter::decode_ccitt(ReadonlyBytes)
  217. {
  218. return Error::rendering_unsupported_error("CCITTFaxDecode Filter is unsupported");
  219. };
  220. PDFErrorOr<ByteBuffer> Filter::decode_jbig2(ReadonlyBytes)
  221. {
  222. return Error::rendering_unsupported_error("JBIG2 Filter is unsupported");
  223. };
  224. PDFErrorOr<ByteBuffer> Filter::decode_dct(ReadonlyBytes bytes)
  225. {
  226. if (Gfx::JPEGImageDecoderPlugin::sniff({ bytes.data(), bytes.size() })) {
  227. auto decoder = Gfx::JPEGImageDecoderPlugin::create({ bytes.data(), bytes.size() }).release_value_but_fixme_should_propagate_errors();
  228. if (decoder->initialize()) {
  229. auto frame = TRY(decoder->frame(0));
  230. return TRY(frame.image->serialize_to_byte_buffer());
  231. }
  232. }
  233. return AK::Error::from_string_literal("Not a JPEG image!");
  234. };
  235. PDFErrorOr<ByteBuffer> Filter::decode_jpx(ReadonlyBytes)
  236. {
  237. return Error::rendering_unsupported_error("JPX Filter is not supported");
  238. };
  239. PDFErrorOr<ByteBuffer> Filter::decode_crypt(ReadonlyBytes)
  240. {
  241. return Error::rendering_unsupported_error("Crypt Filter is not supported");
  242. };
  243. }