Filter.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. if (encoding_type == CommonNames::ASCIIHexDecode)
  20. return decode_ascii_hex(bytes);
  21. if (encoding_type == CommonNames::ASCII85Decode)
  22. return decode_ascii85(bytes);
  23. if (encoding_type == CommonNames::LZWDecode)
  24. return decode_lzw(bytes, decode_parms);
  25. if (encoding_type == CommonNames::FlateDecode)
  26. return decode_flate(bytes, decode_parms);
  27. if (encoding_type == CommonNames::RunLengthDecode)
  28. return decode_run_length(bytes);
  29. if (encoding_type == CommonNames::CCITTFaxDecode)
  30. return decode_ccitt(bytes, decode_parms);
  31. if (encoding_type == CommonNames::JBIG2Decode)
  32. return decode_jbig2(bytes);
  33. if (encoding_type == CommonNames::DCTDecode)
  34. return decode_dct(bytes);
  35. if (encoding_type == CommonNames::JPXDecode)
  36. return decode_jpx(bytes);
  37. if (encoding_type == CommonNames::Crypt)
  38. return decode_crypt(bytes);
  39. dbgln_if(PDF_DEBUG, "Unrecognized filter encoding {}", encoding_type);
  40. return Error::malformed_error("Unrecognized filter encoding");
  41. }
  42. PDFErrorOr<ByteBuffer> Filter::decode_ascii_hex(ReadonlyBytes bytes)
  43. {
  44. ByteBuffer output;
  45. bool have_read_high_nibble = false;
  46. u8 high_nibble = 0;
  47. for (u8 byte : bytes) {
  48. // 3.3.1 ASCIIHexDecode Filter
  49. // All white-space characters [...] are ignored.
  50. // FIXME: Any other characters cause an error.
  51. if (is_ascii_hex_digit(byte)) {
  52. u8 hex_digit = decode_hex_digit(byte);
  53. if (have_read_high_nibble) {
  54. u8 full_byte = (high_nibble << 4) | hex_digit;
  55. TRY(output.try_append(full_byte));
  56. have_read_high_nibble = false;
  57. } else {
  58. high_nibble = hex_digit;
  59. have_read_high_nibble = true;
  60. }
  61. }
  62. }
  63. // If the filter encounters the EOD marker after reading an odd number
  64. // of hexadecimal digits, it behaves as if a 0 followed the last digit.
  65. if (have_read_high_nibble)
  66. TRY(output.try_append(high_nibble << 4));
  67. return output;
  68. }
  69. PDFErrorOr<ByteBuffer> Filter::decode_ascii85(ReadonlyBytes bytes)
  70. {
  71. // 3.3.2 ASCII85Decode Filter
  72. ByteBuffer buffer;
  73. TRY(buffer.try_ensure_capacity(bytes.size()));
  74. size_t byte_index = 0;
  75. while (byte_index < bytes.size()) {
  76. if (Reader::is_whitespace(bytes[byte_index])) {
  77. byte_index++;
  78. continue;
  79. }
  80. if (bytes[byte_index] == 'z') {
  81. byte_index++;
  82. for (int i = 0; i < 4; i++)
  83. buffer.append(0);
  84. continue;
  85. }
  86. u32 number = 0;
  87. auto to_write = byte_index + 5 >= bytes.size() ? bytes.size() - byte_index : 5;
  88. Optional<u32> end_of_data_index {};
  89. for (int i = 0; i < 5; i++) {
  90. // We check for the EOD sequence '~>', but as '~' can only appear in
  91. // this sequence, there is no need to check for '>'.
  92. if (!end_of_data_index.has_value() && bytes[byte_index] == '~') {
  93. end_of_data_index = i;
  94. to_write = i + 1;
  95. }
  96. bool const should_fake_end = byte_index >= bytes.size() || end_of_data_index.has_value();
  97. auto const byte = should_fake_end ? 'u' : bytes[byte_index++];
  98. if (Reader::is_whitespace(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. buffer.append(reinterpret_cast<u8*>(&number)[3 - i]);
  106. if (end_of_data_index.has_value())
  107. break;
  108. }
  109. return buffer;
  110. }
  111. PDFErrorOr<ByteBuffer> Filter::decode_png_prediction(Bytes bytes, size_t bytes_per_row, size_t bytes_per_pixel)
  112. {
  113. int number_of_rows = bytes.size() / bytes_per_row;
  114. ByteBuffer decoded;
  115. TRY(decoded.try_ensure_capacity(bytes.size() - number_of_rows));
  116. auto empty_row = TRY(ByteBuffer::create_zeroed(bytes_per_row - 1));
  117. auto previous_row = empty_row.bytes();
  118. for (int row_index = 0; row_index < number_of_rows; ++row_index) {
  119. auto row = Bytes { bytes.data() + row_index * bytes_per_row, bytes_per_row };
  120. auto filter = TRY(Gfx::PNG::filter_type(row[0]));
  121. row = row.slice(1);
  122. Gfx::PNGImageDecoderPlugin::unfilter_scanline(filter, row, previous_row, bytes_per_pixel);
  123. previous_row = row;
  124. decoded.append(row);
  125. }
  126. return decoded;
  127. }
  128. PDFErrorOr<ByteBuffer> Filter::decode_tiff_prediction(Bytes bytes, int columns, int colors, int bits_per_component)
  129. {
  130. // TIFF 6 spec, Section 14: Differencing Predictor.
  131. // "Assuming 8-bit grayscale pixels for the moment, a basic C implementation might look something like this:
  132. // char image[][]; int row, col;
  133. // /* take horizontal differences: */
  134. // for (row = 0; row < nrows; row++)
  135. // for (col = ncols - 1; col >= 1; col--)
  136. // image[row][col] -= image[row][col-1];
  137. // If we don’t have 8-bit components, we need to work a little harder [...]
  138. // Suppose we have 4-bit components packed two per byte in the normal TIFF uncompressed [...]
  139. // first expand each 4-bit component into an 8-bit byte, so that we have one component per byte, low-order justified.
  140. // We then perform the horizontal differencing [...] we then repack the 4-bit differences two to a byte [...]
  141. // If the components are greater than 8 bits deep, expanding the components into 16-bit words instead of 8-bit bytes
  142. // seems like the best way to perform the subtraction on most computers. [...]
  143. // An additional consideration arises in the case of color images. [...]
  144. // we will do our horizontal differences with an offset of SamplesPerPixel [...
  145. // In other words, we will subtract red from red, green from green, and blue from blue"
  146. //
  147. // The spec text describes the forward transform; this implements the inverse.
  148. //
  149. // Section 8: Baseline Field Reference Guide, entry for Compression:
  150. // "Each row is padded to the next BYTE/SHORT/LONG boundary, consistent with
  151. // the preceding BitsPerSample rule."
  152. //
  153. // That's consistent with PDF. PDF allows bits_per_component to be 1, 2, 4, 8, or 16.
  154. // FIXME: Support bits_per_component != 8.
  155. if (bits_per_component != 8)
  156. return AK::Error::from_string_literal("PDF: TIFF Predictor with bits per component != 8 not yet implemented");
  157. // Translate from PDF spec language to TIFF 6 spec language:
  158. int samples_per_pixel = colors;
  159. ByteBuffer decoded;
  160. TRY(decoded.try_ensure_capacity(bytes.size()));
  161. while (!bytes.is_empty()) {
  162. auto row = bytes.slice(0, columns * samples_per_pixel);
  163. for (int column = 1; column < columns; ++column) {
  164. for (int sample = 0; sample < samples_per_pixel; ++sample) {
  165. int index = column * samples_per_pixel + sample;
  166. row[index] += row[index - samples_per_pixel];
  167. }
  168. }
  169. decoded.append(row);
  170. bytes = bytes.slice(row.size());
  171. }
  172. return decoded;
  173. }
  174. PDFErrorOr<ByteBuffer> Filter::handle_lzw_and_flate_parameters(ByteBuffer buffer, RefPtr<DictObject> decode_parms)
  175. {
  176. // Table 3.7 Optional parameters for LZWDecode and FlateDecode filters
  177. int predictor = 1;
  178. int colors = 1;
  179. int bits_per_component = 8;
  180. int columns = 1;
  181. if (decode_parms) {
  182. if (decode_parms->contains(CommonNames::Predictor))
  183. predictor = decode_parms->get_value(CommonNames::Predictor).get<int>();
  184. if (decode_parms->contains(CommonNames::Colors))
  185. colors = decode_parms->get_value(CommonNames::Colors).get<int>();
  186. if (decode_parms->contains(CommonNames::BitsPerComponent))
  187. bits_per_component = decode_parms->get_value(CommonNames::BitsPerComponent).get<int>();
  188. if (decode_parms->contains(CommonNames::Columns))
  189. columns = decode_parms->get_value(CommonNames::Columns).get<int>();
  190. }
  191. if (predictor == 1)
  192. return buffer;
  193. // Check if we are dealing with a TIFF or PNG prediction.
  194. if (predictor != 2 && (predictor < 10 || predictor > 15))
  195. return AK::Error::from_string_literal("Invalid predictor value");
  196. // Rows are always a whole number of bytes long, for PNG starting with an algorithm tag.
  197. auto buffer_bytes = buffer.bytes();
  198. size_t bytes_per_row = ceil_div(columns * colors * bits_per_component, 8);
  199. if (predictor != 2)
  200. bytes_per_row++;
  201. if (buffer.size() % bytes_per_row) {
  202. // Rarely, there is some trailing data after the image data. Ignore the part of it that doesn't fit into a row.
  203. dbgln_if(PDF_DEBUG, "Predictor input data length {} is not divisible into columns {}, dropping {} bytes", buffer.size(), bytes_per_row, buffer.size() % bytes_per_row);
  204. buffer_bytes = buffer_bytes.slice(0, buffer.size() - buffer.size() % bytes_per_row);
  205. }
  206. if (predictor == 2)
  207. return decode_tiff_prediction(buffer_bytes, columns, colors, bits_per_component);
  208. size_t bytes_per_pixel = ceil_div(colors * bits_per_component, 8);
  209. return decode_png_prediction(buffer_bytes, bytes_per_row, bytes_per_pixel);
  210. }
  211. PDFErrorOr<ByteBuffer> Filter::decode_lzw(ReadonlyBytes bytes, RefPtr<DictObject> decode_parms)
  212. {
  213. // Table 3.7 Optional parameters for LZWDecode and FlateDecode filters
  214. int early_change = 1;
  215. if (decode_parms && decode_parms->contains(CommonNames::EarlyChange))
  216. early_change = decode_parms->get_value(CommonNames::EarlyChange).get<int>();
  217. auto decoded = TRY(Compress::LZWDecoder<BigEndianInputBitStream>::decode_all(bytes, 8, -early_change));
  218. return handle_lzw_and_flate_parameters(move(decoded), decode_parms);
  219. }
  220. PDFErrorOr<ByteBuffer> Filter::decode_flate(ReadonlyBytes bytes, RefPtr<DictObject> decode_parms)
  221. {
  222. auto buff = TRY(Compress::DeflateDecompressor::decompress_all(bytes.slice(2)));
  223. return handle_lzw_and_flate_parameters(move(buff), decode_parms);
  224. }
  225. PDFErrorOr<ByteBuffer> Filter::decode_run_length(ReadonlyBytes bytes)
  226. {
  227. return TRY(Compress::PackBits::decode_all(bytes, OptionalNone {}, Compress::PackBits::CompatibilityMode::PDF));
  228. }
  229. PDFErrorOr<ByteBuffer> Filter::decode_ccitt(ReadonlyBytes, RefPtr<DictObject> decode_parms)
  230. {
  231. // Table 3.9 Optional parameters for the CCITTFaxDecode filter
  232. int k = 0;
  233. bool require_end_of_line = false;
  234. bool encoded_byte_align = false;
  235. int columns = 1728;
  236. int rows = 0;
  237. bool end_of_block = true;
  238. bool black_is_1 = false;
  239. int damaged_rows_before_error = 0;
  240. if (decode_parms) {
  241. if (decode_parms->contains(CommonNames::K))
  242. k = decode_parms->get_value(CommonNames::K).get<int>();
  243. if (decode_parms->contains(CommonNames::EndOfLine))
  244. require_end_of_line = decode_parms->get_value(CommonNames::EndOfLine).get<bool>();
  245. if (decode_parms->contains(CommonNames::EncodedByteAlign))
  246. encoded_byte_align = decode_parms->get_value(CommonNames::EncodedByteAlign).get<bool>();
  247. if (decode_parms->contains(CommonNames::Columns))
  248. columns = decode_parms->get_value(CommonNames::Columns).get<int>();
  249. if (decode_parms->contains(CommonNames::Rows))
  250. rows = decode_parms->get_value(CommonNames::Rows).get<int>();
  251. if (decode_parms->contains(CommonNames::EndOfBlock))
  252. end_of_block = decode_parms->get_value(CommonNames::EndOfBlock).get<bool>();
  253. if (decode_parms->contains(CommonNames::BlackIs1))
  254. black_is_1 = decode_parms->get_value(CommonNames::BlackIs1).get<bool>();
  255. if (decode_parms->contains(CommonNames::DamagedRowsBeforeError))
  256. damaged_rows_before_error = decode_parms->get_value(CommonNames::DamagedRowsBeforeError).get<int>();
  257. }
  258. // FIXME: Do something with these.
  259. (void)require_end_of_line;
  260. (void)encoded_byte_align;
  261. (void)columns;
  262. (void)rows;
  263. (void)end_of_block;
  264. (void)black_is_1;
  265. (void)damaged_rows_before_error;
  266. if (k < 0)
  267. return Error::rendering_unsupported_error("CCITTFaxDecode Filter Group 4 is unsupported");
  268. if (k == 0)
  269. return Error::rendering_unsupported_error("CCITTFaxDecode Filter Group 3, 1-D is unsupported");
  270. return Error::rendering_unsupported_error("CCITTFaxDecode Filter Group 3, 2-D is unsupported");
  271. }
  272. PDFErrorOr<ByteBuffer> Filter::decode_jbig2(ReadonlyBytes)
  273. {
  274. return Error::rendering_unsupported_error("JBIG2 Filter is unsupported");
  275. }
  276. PDFErrorOr<ByteBuffer> Filter::decode_dct(ReadonlyBytes bytes)
  277. {
  278. if (!Gfx::JPEGImageDecoderPlugin::sniff({ bytes.data(), bytes.size() }))
  279. return AK::Error::from_string_literal("Not a JPEG image!");
  280. auto decoder = TRY(Gfx::JPEGImageDecoderPlugin::create_with_options({ bytes.data(), bytes.size() }, { .cmyk = Gfx::JPEGDecoderOptions::CMYK::PDF }));
  281. auto internal_format = decoder->natural_frame_format();
  282. if (internal_format == Gfx::NaturalFrameFormat::CMYK) {
  283. auto bitmap = TRY(decoder->cmyk_frame());
  284. // FIXME: Could give CMYKBitmap a method to steal its internal ByteBuffer.
  285. auto size = bitmap->size().width() * bitmap->size().height() * 4;
  286. auto buffer = TRY(ByteBuffer::create_uninitialized(size));
  287. buffer.overwrite(0, bitmap->scanline(0), size);
  288. return buffer;
  289. }
  290. auto bitmap = TRY(decoder->frame(0)).image;
  291. auto size = bitmap->size().width() * bitmap->size().height() * (internal_format == Gfx::NaturalFrameFormat::Grayscale ? 1 : 3);
  292. ByteBuffer buffer;
  293. TRY(buffer.try_ensure_capacity(size));
  294. for (auto& pixel : *bitmap) {
  295. Color color = Color::from_argb(pixel);
  296. if (internal_format == Gfx::NaturalFrameFormat::Grayscale) {
  297. // Either channel is fine, they're all the same.
  298. buffer.append(color.red());
  299. } else {
  300. buffer.append(color.red());
  301. buffer.append(color.green());
  302. buffer.append(color.blue());
  303. }
  304. }
  305. return buffer;
  306. }
  307. PDFErrorOr<ByteBuffer> Filter::decode_jpx(ReadonlyBytes)
  308. {
  309. return Error::rendering_unsupported_error("JPX Filter is not supported");
  310. }
  311. PDFErrorOr<ByteBuffer> Filter::decode_crypt(ReadonlyBytes)
  312. {
  313. return Error::rendering_unsupported_error("Crypt Filter is not supported");
  314. }
  315. }