Filter.cpp 16 KB

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