Filter.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 <LibCompress/PackBitsDecoder.h>
  11. #include <LibGfx/ImageFormats/JPEGLoader.h>
  12. #include <LibGfx/ImageFormats/PNGLoader.h>
  13. #include <LibPDF/CommonNames.h>
  14. #include <LibPDF/Filter.h>
  15. #include <LibPDF/Reader.h>
  16. namespace PDF {
  17. PDFErrorOr<ByteBuffer> Filter::decode(ReadonlyBytes bytes, DeprecatedFlyString const& encoding_type, RefPtr<DictObject> decode_parms)
  18. {
  19. int predictor = 1;
  20. int columns = 1;
  21. int colors = 1;
  22. int bits_per_component = 8;
  23. int early_change = 1;
  24. if (decode_parms) {
  25. if (decode_parms->contains(CommonNames::Predictor))
  26. predictor = decode_parms->get_value(CommonNames::Predictor).get<int>();
  27. if (decode_parms->contains(CommonNames::Columns))
  28. columns = decode_parms->get_value(CommonNames::Columns).get<int>();
  29. if (decode_parms->contains(CommonNames::Colors))
  30. colors = decode_parms->get_value(CommonNames::Colors).get<int>();
  31. if (decode_parms->contains(CommonNames::BitsPerComponent))
  32. bits_per_component = decode_parms->get_value(CommonNames::BitsPerComponent).get<int>();
  33. if (decode_parms->contains(CommonNames::EarlyChange))
  34. early_change = decode_parms->get_value(CommonNames::EarlyChange).get<int>();
  35. }
  36. if (encoding_type == CommonNames::ASCIIHexDecode)
  37. return decode_ascii_hex(bytes);
  38. if (encoding_type == CommonNames::ASCII85Decode)
  39. return decode_ascii85(bytes);
  40. if (encoding_type == CommonNames::LZWDecode)
  41. return decode_lzw(bytes, predictor, columns, colors, bits_per_component, early_change);
  42. if (encoding_type == CommonNames::FlateDecode)
  43. return decode_flate(bytes, predictor, columns, colors, bits_per_component);
  44. if (encoding_type == CommonNames::RunLengthDecode)
  45. return decode_run_length(bytes);
  46. if (encoding_type == CommonNames::CCITTFaxDecode)
  47. return decode_ccitt(bytes);
  48. if (encoding_type == CommonNames::JBIG2Decode)
  49. return decode_jbig2(bytes);
  50. if (encoding_type == CommonNames::DCTDecode)
  51. return decode_dct(bytes);
  52. if (encoding_type == CommonNames::JPXDecode)
  53. return decode_jpx(bytes);
  54. if (encoding_type == CommonNames::Crypt)
  55. return decode_crypt(bytes);
  56. dbgln_if(PDF_DEBUG, "Unrecognized filter encoding {}", encoding_type);
  57. return Error::malformed_error("Unrecognized filter encoding");
  58. }
  59. PDFErrorOr<ByteBuffer> Filter::decode_ascii_hex(ReadonlyBytes bytes)
  60. {
  61. ByteBuffer output;
  62. bool have_read_high_nibble = false;
  63. u8 high_nibble = 0;
  64. for (u8 byte : bytes) {
  65. // 3.3.1 ASCIIHexDecode Filter
  66. // All white-space characters [...] are ignored.
  67. // FIXME: Any other characters cause an error.
  68. if (is_ascii_hex_digit(byte)) {
  69. u8 hex_digit = decode_hex_digit(byte);
  70. if (have_read_high_nibble) {
  71. u8 full_byte = (high_nibble << 4) | hex_digit;
  72. TRY(output.try_append(full_byte));
  73. have_read_high_nibble = false;
  74. } else {
  75. high_nibble = hex_digit;
  76. have_read_high_nibble = true;
  77. }
  78. }
  79. }
  80. // If the filter encounters the EOD marker after reading an odd number
  81. // of hexadecimal digits, it behaves as if a 0 followed the last digit.
  82. if (have_read_high_nibble)
  83. TRY(output.try_append(high_nibble << 4));
  84. return output;
  85. }
  86. PDFErrorOr<ByteBuffer> Filter::decode_ascii85(ReadonlyBytes bytes)
  87. {
  88. // 3.3.2 ASCII85Decode Filter
  89. ByteBuffer buffer;
  90. TRY(buffer.try_ensure_capacity(bytes.size()));
  91. size_t byte_index = 0;
  92. while (byte_index < bytes.size()) {
  93. if (Reader::is_whitespace(bytes[byte_index])) {
  94. byte_index++;
  95. continue;
  96. }
  97. if (bytes[byte_index] == 'z') {
  98. byte_index++;
  99. for (int i = 0; i < 4; i++)
  100. buffer.append(0);
  101. continue;
  102. }
  103. u32 number = 0;
  104. auto to_write = byte_index + 5 >= bytes.size() ? bytes.size() - byte_index : 5;
  105. Optional<u32> end_of_data_index {};
  106. for (int i = 0; i < 5; i++) {
  107. // We check for the EOD sequence '~>', but as '~' can only appear in
  108. // this sequence, there is no need to check for '>'.
  109. if (!end_of_data_index.has_value() && bytes[byte_index] == '~') {
  110. end_of_data_index = i;
  111. to_write = i + 1;
  112. }
  113. bool const should_fake_end = byte_index >= bytes.size() || end_of_data_index.has_value();
  114. auto const byte = should_fake_end ? 'u' : bytes[byte_index++];
  115. if (Reader::is_whitespace(byte)) {
  116. i--;
  117. continue;
  118. }
  119. number = number * 85 + byte - 33;
  120. }
  121. for (size_t i = 0; i < to_write - 1; i++)
  122. buffer.append(reinterpret_cast<u8*>(&number)[3 - i]);
  123. if (end_of_data_index.has_value())
  124. break;
  125. }
  126. return buffer;
  127. }
  128. PDFErrorOr<ByteBuffer> Filter::decode_png_prediction(Bytes bytes, size_t bytes_per_row, size_t bytes_per_pixel)
  129. {
  130. int number_of_rows = bytes.size() / bytes_per_row;
  131. ByteBuffer decoded;
  132. decoded.ensure_capacity(bytes.size() - number_of_rows);
  133. auto empty_row = TRY(ByteBuffer::create_zeroed(bytes_per_row - 1));
  134. auto previous_row = empty_row.bytes();
  135. for (int row_index = 0; row_index < number_of_rows; ++row_index) {
  136. auto row = Bytes { bytes.data() + row_index * bytes_per_row, bytes_per_row };
  137. auto filter = TRY(Gfx::PNG::filter_type(row[0]));
  138. row = row.slice(1);
  139. Gfx::PNGImageDecoderPlugin::unfilter_scanline(filter, row, previous_row, bytes_per_pixel);
  140. previous_row = row;
  141. decoded.append(row);
  142. }
  143. return decoded;
  144. }
  145. PDFErrorOr<ByteBuffer> Filter::handle_lzw_and_flate_parameters(ByteBuffer buffer, int predictor, int columns, int colors, int bits_per_component)
  146. {
  147. // Table 3.7 Optional parameters for LZWDecode and FlateDecode filters
  148. if (predictor == 1)
  149. return buffer;
  150. // Check if we are dealing with a PNG prediction
  151. if (predictor == 2)
  152. return AK::Error::from_string_literal("The TIFF predictor is not supported");
  153. if (predictor < 10 || predictor > 15)
  154. return AK::Error::from_string_literal("Invalid predictor value");
  155. // Rows are always a whole number of bytes long, starting with an algorithm tag
  156. size_t const bytes_per_row = ceil_div(columns * colors * bits_per_component, 8) + 1;
  157. if (buffer.size() % bytes_per_row)
  158. return AK::Error::from_string_literal("Flate input data is not divisible into columns");
  159. size_t bytes_per_pixel = ceil_div(colors * bits_per_component, 8);
  160. return decode_png_prediction(buffer, bytes_per_row, bytes_per_pixel);
  161. }
  162. PDFErrorOr<ByteBuffer> Filter::decode_lzw(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component, int early_change)
  163. {
  164. auto decoded = TRY(Compress::LZWDecoder<BigEndianInputBitStream>::decode_all(bytes, 8, -early_change));
  165. return handle_lzw_and_flate_parameters(move(decoded), predictor, columns, colors, bits_per_component);
  166. }
  167. PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, int predictor, int columns, int colors, int bits_per_component)
  168. {
  169. auto buff = TRY(Compress::DeflateDecompressor::decompress_all(bytes.slice(2)));
  170. return handle_lzw_and_flate_parameters(move(buff), predictor, columns, colors, bits_per_component);
  171. }
  172. PDFErrorOr<ByteBuffer> Filter::decode_run_length(ReadonlyBytes bytes)
  173. {
  174. return TRY(Compress::PackBits::decode_all(bytes, OptionalNone {}, Compress::PackBits::CompatibilityMode::PDF));
  175. }
  176. PDFErrorOr<ByteBuffer> Filter::decode_ccitt(ReadonlyBytes)
  177. {
  178. return Error::rendering_unsupported_error("CCITTFaxDecode Filter is unsupported");
  179. }
  180. PDFErrorOr<ByteBuffer> Filter::decode_jbig2(ReadonlyBytes)
  181. {
  182. return Error::rendering_unsupported_error("JBIG2 Filter is unsupported");
  183. }
  184. PDFErrorOr<ByteBuffer> Filter::decode_dct(ReadonlyBytes bytes)
  185. {
  186. if (Gfx::JPEGImageDecoderPlugin::sniff({ bytes.data(), bytes.size() })) {
  187. auto decoder = TRY(Gfx::JPEGImageDecoderPlugin::create_with_options({ bytes.data(), bytes.size() }, { .cmyk = Gfx::JPEGDecoderOptions::CMYK::PDF }));
  188. auto frame = TRY(decoder->frame(0));
  189. return TRY(frame.image->serialize_to_byte_buffer());
  190. }
  191. return AK::Error::from_string_literal("Not a JPEG image!");
  192. }
  193. PDFErrorOr<ByteBuffer> Filter::decode_jpx(ReadonlyBytes)
  194. {
  195. return Error::rendering_unsupported_error("JPX Filter is not supported");
  196. }
  197. PDFErrorOr<ByteBuffer> Filter::decode_crypt(ReadonlyBytes)
  198. {
  199. return Error::rendering_unsupported_error("Crypt Filter is not supported");
  200. }
  201. }