Deflate.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Array.h>
  8. #include <AK/Assertions.h>
  9. #include <AK/BinaryHeap.h>
  10. #include <AK/BinarySearch.h>
  11. #include <AK/BitStream.h>
  12. #include <AK/MemoryStream.h>
  13. #include <string.h>
  14. #include <LibCompress/Deflate.h>
  15. namespace Compress {
  16. static constexpr u8 deflate_special_code_length_copy = 16;
  17. static constexpr u8 deflate_special_code_length_zeros = 17;
  18. static constexpr u8 deflate_special_code_length_long_zeros = 18;
  19. CanonicalCode const& CanonicalCode::fixed_literal_codes()
  20. {
  21. static CanonicalCode code;
  22. static bool initialized = false;
  23. if (initialized)
  24. return code;
  25. code = MUST(CanonicalCode::from_bytes(fixed_literal_bit_lengths));
  26. initialized = true;
  27. return code;
  28. }
  29. CanonicalCode const& CanonicalCode::fixed_distance_codes()
  30. {
  31. static CanonicalCode code;
  32. static bool initialized = false;
  33. if (initialized)
  34. return code;
  35. code = MUST(CanonicalCode::from_bytes(fixed_distance_bit_lengths));
  36. initialized = true;
  37. return code;
  38. }
  39. ErrorOr<CanonicalCode> CanonicalCode::from_bytes(ReadonlyBytes bytes)
  40. {
  41. // FIXME: I can't quite follow the algorithm here, but it seems to work.
  42. CanonicalCode code;
  43. auto non_zero_symbols = 0;
  44. auto last_non_zero = -1;
  45. for (size_t i = 0; i < bytes.size(); i++) {
  46. if (bytes[i] != 0) {
  47. non_zero_symbols++;
  48. last_non_zero = i;
  49. }
  50. }
  51. if (non_zero_symbols == 1) { // special case - only 1 symbol
  52. code.m_prefix_table[0] = PrefixTableEntry { static_cast<u16>(last_non_zero), 1u };
  53. code.m_prefix_table[1] = code.m_prefix_table[0];
  54. code.m_max_prefixed_code_length = 1;
  55. code.m_bit_codes[last_non_zero] = 0;
  56. code.m_bit_code_lengths[last_non_zero] = 1;
  57. return code;
  58. }
  59. struct PrefixCode {
  60. u16 symbol_code { 0 };
  61. u16 symbol_value { 0 };
  62. u16 code_length { 0 };
  63. };
  64. Array<PrefixCode, 1 << CanonicalCode::max_allowed_prefixed_code_length> prefix_codes;
  65. size_t number_of_prefix_codes = 0;
  66. auto next_code = 0;
  67. for (size_t code_length = 1; code_length <= 15; ++code_length) {
  68. next_code <<= 1;
  69. auto start_bit = 1 << code_length;
  70. for (size_t symbol = 0; symbol < bytes.size(); ++symbol) {
  71. if (bytes[symbol] != code_length)
  72. continue;
  73. if (next_code > start_bit)
  74. return Error::from_string_literal("Failed to decode code lengths");
  75. if (code_length <= CanonicalCode::max_allowed_prefixed_code_length) {
  76. auto& prefix_code = prefix_codes[number_of_prefix_codes++];
  77. prefix_code.symbol_code = next_code;
  78. prefix_code.symbol_value = symbol;
  79. prefix_code.code_length = code_length;
  80. code.m_max_prefixed_code_length = code_length;
  81. } else {
  82. code.m_symbol_codes.append(start_bit | next_code);
  83. code.m_symbol_values.append(symbol);
  84. }
  85. code.m_bit_codes[symbol] = fast_reverse16(start_bit | next_code, code_length); // DEFLATE writes huffman encoded symbols as lsb-first
  86. code.m_bit_code_lengths[symbol] = code_length;
  87. next_code++;
  88. }
  89. }
  90. if (next_code != (1 << 15))
  91. return Error::from_string_literal("Failed to decode code lengths");
  92. for (auto [symbol_code, symbol_value, code_length] : prefix_codes) {
  93. if (code_length == 0 || code_length > CanonicalCode::max_allowed_prefixed_code_length)
  94. break;
  95. auto shift = code.m_max_prefixed_code_length - code_length;
  96. symbol_code <<= shift;
  97. for (size_t j = 0; j < (1u << shift); ++j) {
  98. auto index = fast_reverse16(symbol_code + j, code.m_max_prefixed_code_length);
  99. code.m_prefix_table[index] = PrefixTableEntry { symbol_value, code_length };
  100. }
  101. }
  102. return code;
  103. }
  104. ErrorOr<u32> CanonicalCode::read_symbol(LittleEndianInputBitStream& stream) const
  105. {
  106. auto prefix = TRY(stream.peek_bits<size_t>(m_max_prefixed_code_length));
  107. if (auto [symbol_value, code_length] = m_prefix_table[prefix]; code_length != 0) {
  108. stream.discard_previously_peeked_bits(code_length);
  109. return symbol_value;
  110. }
  111. auto code_bits = TRY(stream.read_bits<u16>(m_max_prefixed_code_length));
  112. code_bits = fast_reverse16(code_bits, m_max_prefixed_code_length);
  113. code_bits |= 1 << m_max_prefixed_code_length;
  114. for (size_t i = m_max_prefixed_code_length; i < 16; ++i) {
  115. size_t index;
  116. if (binary_search(m_symbol_codes.span(), code_bits, &index))
  117. return m_symbol_values[index];
  118. code_bits = code_bits << 1 | TRY(stream.read_bit());
  119. }
  120. return Error::from_string_literal("Symbol exceeds maximum symbol number");
  121. }
  122. ErrorOr<void> CanonicalCode::write_symbol(LittleEndianOutputBitStream& stream, u32 symbol) const
  123. {
  124. TRY(stream.write_bits(m_bit_codes[symbol], m_bit_code_lengths[symbol]));
  125. return {};
  126. }
  127. DeflateDecompressor::CompressedBlock::CompressedBlock(DeflateDecompressor& decompressor, CanonicalCode literal_codes, Optional<CanonicalCode> distance_codes)
  128. : m_decompressor(decompressor)
  129. , m_literal_codes(literal_codes)
  130. , m_distance_codes(distance_codes)
  131. {
  132. }
  133. ErrorOr<bool> DeflateDecompressor::CompressedBlock::try_read_more()
  134. {
  135. if (m_eof == true)
  136. return false;
  137. auto const symbol = TRY(m_literal_codes.read_symbol(*m_decompressor.m_input_stream));
  138. if (symbol >= 286)
  139. return Error::from_string_literal("Invalid deflate literal/length symbol");
  140. if (symbol < 256) {
  141. u8 byte_symbol = symbol;
  142. m_decompressor.m_output_buffer.write({ &byte_symbol, sizeof(byte_symbol) });
  143. return true;
  144. }
  145. if (symbol == 256) {
  146. m_eof = true;
  147. return false;
  148. }
  149. if (!m_distance_codes.has_value())
  150. return Error::from_string_literal("Distance codes have not been initialized");
  151. auto const length = TRY(m_decompressor.decode_length(symbol));
  152. auto const distance_symbol = TRY(m_distance_codes.value().read_symbol(*m_decompressor.m_input_stream));
  153. if (distance_symbol >= 30)
  154. return Error::from_string_literal("Invalid deflate distance symbol");
  155. auto const distance = TRY(m_decompressor.decode_distance(distance_symbol));
  156. if (distance < length) {
  157. for (size_t idx = 0; idx < length; ++idx) {
  158. u8 byte = 0;
  159. TRY(m_decompressor.m_output_buffer.read_with_seekback({ &byte, sizeof(byte) }, distance));
  160. m_decompressor.m_output_buffer.write({ &byte, sizeof(byte) });
  161. }
  162. } else {
  163. auto copied_length = TRY(m_decompressor.m_output_buffer.copy_from_seekback(distance, length));
  164. // TODO: What should we do if the output buffer is full?
  165. VERIFY(copied_length == length);
  166. }
  167. return true;
  168. }
  169. DeflateDecompressor::UncompressedBlock::UncompressedBlock(DeflateDecompressor& decompressor, size_t length)
  170. : m_decompressor(decompressor)
  171. , m_bytes_remaining(length)
  172. {
  173. }
  174. ErrorOr<bool> DeflateDecompressor::UncompressedBlock::try_read_more()
  175. {
  176. if (m_bytes_remaining == 0)
  177. return false;
  178. Array<u8, 4096> temporary_buffer;
  179. auto readable_bytes = temporary_buffer.span().trim(min(m_bytes_remaining, m_decompressor.m_output_buffer.empty_space()));
  180. auto read_bytes = TRY(m_decompressor.m_input_stream->read_some(readable_bytes));
  181. auto written_bytes = m_decompressor.m_output_buffer.write(read_bytes);
  182. VERIFY(read_bytes.size() == written_bytes);
  183. m_bytes_remaining -= written_bytes;
  184. return true;
  185. }
  186. ErrorOr<NonnullOwnPtr<DeflateDecompressor>> DeflateDecompressor::construct(MaybeOwned<LittleEndianInputBitStream> stream)
  187. {
  188. auto output_buffer = TRY(CircularBuffer::create_empty(32 * KiB));
  189. return TRY(adopt_nonnull_own_or_enomem(new (nothrow) DeflateDecompressor(move(stream), move(output_buffer))));
  190. }
  191. DeflateDecompressor::DeflateDecompressor(MaybeOwned<LittleEndianInputBitStream> stream, CircularBuffer output_buffer)
  192. : m_input_stream(move(stream))
  193. , m_output_buffer(move(output_buffer))
  194. {
  195. }
  196. DeflateDecompressor::~DeflateDecompressor()
  197. {
  198. if (m_state == State::ReadingCompressedBlock)
  199. m_compressed_block.~CompressedBlock();
  200. if (m_state == State::ReadingUncompressedBlock)
  201. m_uncompressed_block.~UncompressedBlock();
  202. }
  203. ErrorOr<Bytes> DeflateDecompressor::read_some(Bytes bytes)
  204. {
  205. size_t total_read = 0;
  206. while (total_read < bytes.size()) {
  207. auto slice = bytes.slice(total_read);
  208. if (m_state == State::Idle) {
  209. if (m_read_final_bock)
  210. break;
  211. m_read_final_bock = TRY(m_input_stream->read_bit());
  212. auto const block_type = TRY(m_input_stream->read_bits(2));
  213. if (block_type == 0b00) {
  214. m_input_stream->align_to_byte_boundary();
  215. u16 length = TRY(m_input_stream->read_value<LittleEndian<u16>>());
  216. u16 negated_length = TRY(m_input_stream->read_value<LittleEndian<u16>>());
  217. if ((length ^ 0xffff) != negated_length)
  218. return Error::from_string_literal("Calculated negated length does not equal stored negated length");
  219. m_state = State::ReadingUncompressedBlock;
  220. new (&m_uncompressed_block) UncompressedBlock(*this, length);
  221. continue;
  222. }
  223. if (block_type == 0b01) {
  224. m_state = State::ReadingCompressedBlock;
  225. new (&m_compressed_block) CompressedBlock(*this, CanonicalCode::fixed_literal_codes(), CanonicalCode::fixed_distance_codes());
  226. continue;
  227. }
  228. if (block_type == 0b10) {
  229. CanonicalCode literal_codes;
  230. Optional<CanonicalCode> distance_codes;
  231. TRY(decode_codes(literal_codes, distance_codes));
  232. m_state = State::ReadingCompressedBlock;
  233. new (&m_compressed_block) CompressedBlock(*this, literal_codes, distance_codes);
  234. continue;
  235. }
  236. return Error::from_string_literal("Unhandled block type for Idle state");
  237. }
  238. if (m_state == State::ReadingCompressedBlock) {
  239. auto nread = m_output_buffer.read(slice).size();
  240. while (nread < slice.size() && TRY(m_compressed_block.try_read_more())) {
  241. nread += m_output_buffer.read(slice.slice(nread)).size();
  242. }
  243. total_read += nread;
  244. if (nread == slice.size())
  245. break;
  246. m_compressed_block.~CompressedBlock();
  247. m_state = State::Idle;
  248. continue;
  249. }
  250. if (m_state == State::ReadingUncompressedBlock) {
  251. auto nread = m_output_buffer.read(slice).size();
  252. while (nread < slice.size() && TRY(m_uncompressed_block.try_read_more())) {
  253. nread += m_output_buffer.read(slice.slice(nread)).size();
  254. }
  255. total_read += nread;
  256. if (nread == slice.size())
  257. break;
  258. m_uncompressed_block.~UncompressedBlock();
  259. m_state = State::Idle;
  260. continue;
  261. }
  262. VERIFY_NOT_REACHED();
  263. }
  264. return bytes.slice(0, total_read);
  265. }
  266. bool DeflateDecompressor::is_eof() const { return m_state == State::Idle && m_read_final_bock; }
  267. ErrorOr<size_t> DeflateDecompressor::write_some(ReadonlyBytes)
  268. {
  269. return Error::from_errno(EBADF);
  270. }
  271. bool DeflateDecompressor::is_open() const
  272. {
  273. return true;
  274. }
  275. void DeflateDecompressor::close()
  276. {
  277. }
  278. ErrorOr<ByteBuffer> DeflateDecompressor::decompress_all(ReadonlyBytes bytes)
  279. {
  280. FixedMemoryStream memory_stream { bytes };
  281. LittleEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream) };
  282. auto deflate_stream = TRY(DeflateDecompressor::construct(MaybeOwned<LittleEndianInputBitStream>(bit_stream)));
  283. AllocatingMemoryStream output_stream;
  284. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  285. while (!deflate_stream->is_eof()) {
  286. auto const slice = TRY(deflate_stream->read_some(buffer));
  287. TRY(output_stream.write_until_depleted(slice));
  288. }
  289. auto output_buffer = TRY(ByteBuffer::create_uninitialized(output_stream.used_buffer_size()));
  290. TRY(output_stream.read_until_filled(output_buffer));
  291. return output_buffer;
  292. }
  293. ErrorOr<u32> DeflateDecompressor::decode_length(u32 symbol)
  294. {
  295. // FIXME: I can't quite follow the algorithm here, but it seems to work.
  296. if (symbol <= 264)
  297. return symbol - 254;
  298. if (symbol <= 284) {
  299. auto extra_bits = (symbol - 261) / 4;
  300. return (((symbol - 265) % 4 + 4) << extra_bits) + 3 + TRY(m_input_stream->read_bits(extra_bits));
  301. }
  302. if (symbol == 285)
  303. return DeflateDecompressor::max_back_reference_length;
  304. VERIFY_NOT_REACHED();
  305. }
  306. ErrorOr<u32> DeflateDecompressor::decode_distance(u32 symbol)
  307. {
  308. // FIXME: I can't quite follow the algorithm here, but it seems to work.
  309. if (symbol <= 3)
  310. return symbol + 1;
  311. if (symbol <= 29) {
  312. auto extra_bits = (symbol / 2) - 1;
  313. return ((symbol % 2 + 2) << extra_bits) + 1 + TRY(m_input_stream->read_bits(extra_bits));
  314. }
  315. VERIFY_NOT_REACHED();
  316. }
  317. ErrorOr<void> DeflateDecompressor::decode_codes(CanonicalCode& literal_code, Optional<CanonicalCode>& distance_code)
  318. {
  319. auto literal_code_count = TRY(m_input_stream->read_bits(5)) + 257;
  320. auto distance_code_count = TRY(m_input_stream->read_bits(5)) + 1;
  321. auto code_length_count = TRY(m_input_stream->read_bits(4)) + 4;
  322. // First we have to extract the code lengths of the code that was used to encode the code lengths of
  323. // the code that was used to encode the block.
  324. u8 code_lengths_code_lengths[19] = { 0 };
  325. for (size_t i = 0; i < code_length_count; ++i) {
  326. code_lengths_code_lengths[code_lengths_code_lengths_order[i]] = TRY(m_input_stream->read_bits(3));
  327. }
  328. // Now we can extract the code that was used to encode the code lengths of the code that was used to
  329. // encode the block.
  330. auto const code_length_code = TRY(CanonicalCode::from_bytes({ code_lengths_code_lengths, sizeof(code_lengths_code_lengths) }));
  331. // Next we extract the code lengths of the code that was used to encode the block.
  332. Vector<u8, 286> code_lengths;
  333. while (code_lengths.size() < literal_code_count + distance_code_count) {
  334. auto symbol = TRY(code_length_code.read_symbol(*m_input_stream));
  335. if (symbol < deflate_special_code_length_copy) {
  336. code_lengths.append(static_cast<u8>(symbol));
  337. } else if (symbol == deflate_special_code_length_copy) {
  338. if (code_lengths.is_empty())
  339. return Error::from_string_literal("Found no codes to copy before a copy block");
  340. auto nrepeat = 3 + TRY(m_input_stream->read_bits(2));
  341. for (size_t j = 0; j < nrepeat; ++j)
  342. code_lengths.append(code_lengths.last());
  343. } else if (symbol == deflate_special_code_length_zeros) {
  344. auto nrepeat = 3 + TRY(m_input_stream->read_bits(3));
  345. for (size_t j = 0; j < nrepeat; ++j)
  346. code_lengths.append(0);
  347. } else {
  348. VERIFY(symbol == deflate_special_code_length_long_zeros);
  349. auto nrepeat = 11 + TRY(m_input_stream->read_bits(7));
  350. for (size_t j = 0; j < nrepeat; ++j)
  351. code_lengths.append(0);
  352. }
  353. }
  354. if (code_lengths.size() != literal_code_count + distance_code_count)
  355. return Error::from_string_literal("Number of code lengths does not match the sum of codes");
  356. // Now we extract the code that was used to encode literals and lengths in the block.
  357. literal_code = TRY(CanonicalCode::from_bytes(code_lengths.span().trim(literal_code_count)));
  358. // Now we extract the code that was used to encode distances in the block.
  359. if (distance_code_count == 1) {
  360. auto length = code_lengths[literal_code_count];
  361. if (length == 0)
  362. return {};
  363. else if (length != 1)
  364. return Error::from_string_literal("Length for a single distance code is longer than 1");
  365. }
  366. distance_code = TRY(CanonicalCode::from_bytes(code_lengths.span().slice(literal_code_count)));
  367. return {};
  368. }
  369. ErrorOr<NonnullOwnPtr<DeflateCompressor>> DeflateCompressor::construct(MaybeOwned<Stream> stream, CompressionLevel compression_level)
  370. {
  371. auto bit_stream = TRY(try_make<LittleEndianOutputBitStream>(move(stream)));
  372. auto deflate_compressor = TRY(adopt_nonnull_own_or_enomem(new (nothrow) DeflateCompressor(move(bit_stream), compression_level)));
  373. return deflate_compressor;
  374. }
  375. DeflateCompressor::DeflateCompressor(NonnullOwnPtr<LittleEndianOutputBitStream> stream, CompressionLevel compression_level)
  376. : m_compression_level(compression_level)
  377. , m_compression_constants(compression_constants[static_cast<int>(m_compression_level)])
  378. , m_output_stream(move(stream))
  379. {
  380. m_symbol_frequencies.fill(0);
  381. m_distance_frequencies.fill(0);
  382. }
  383. DeflateCompressor::~DeflateCompressor()
  384. {
  385. VERIFY(m_finished);
  386. }
  387. ErrorOr<Bytes> DeflateCompressor::read_some(Bytes)
  388. {
  389. return Error::from_errno(EBADF);
  390. }
  391. ErrorOr<size_t> DeflateCompressor::write_some(ReadonlyBytes bytes)
  392. {
  393. VERIFY(!m_finished);
  394. size_t total_written = 0;
  395. while (!bytes.is_empty()) {
  396. auto n_written = bytes.copy_trimmed_to(pending_block().slice(m_pending_block_size));
  397. m_pending_block_size += n_written;
  398. if (m_pending_block_size == block_size)
  399. TRY(flush());
  400. bytes = bytes.slice(n_written);
  401. total_written += n_written;
  402. }
  403. return total_written;
  404. }
  405. bool DeflateCompressor::is_eof() const
  406. {
  407. return true;
  408. }
  409. bool DeflateCompressor::is_open() const
  410. {
  411. return m_output_stream->is_open();
  412. }
  413. void DeflateCompressor::close()
  414. {
  415. }
  416. // Knuth's multiplicative hash on 4 bytes
  417. u16 DeflateCompressor::hash_sequence(u8 const* bytes)
  418. {
  419. constexpr const u32 knuth_constant = 2654435761; // shares no common factors with 2^32
  420. return ((bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24) * knuth_constant) >> (32 - hash_bits);
  421. }
  422. size_t DeflateCompressor::compare_match_candidate(size_t start, size_t candidate, size_t previous_match_length, size_t maximum_match_length)
  423. {
  424. VERIFY(previous_match_length < maximum_match_length);
  425. // We firstly check that the match is at least (prev_match_length + 1) long, we check backwards as there's a higher chance the end mismatches
  426. for (ssize_t i = previous_match_length; i >= 0; i--) {
  427. if (m_rolling_window[start + i] != m_rolling_window[candidate + i])
  428. return 0;
  429. }
  430. // Find the actual length
  431. auto match_length = previous_match_length + 1;
  432. while (match_length < maximum_match_length && m_rolling_window[start + match_length] == m_rolling_window[candidate + match_length]) {
  433. match_length++;
  434. }
  435. VERIFY(match_length > previous_match_length);
  436. VERIFY(match_length <= maximum_match_length);
  437. return match_length;
  438. }
  439. size_t DeflateCompressor::find_back_match(size_t start, u16 hash, size_t previous_match_length, size_t maximum_match_length, size_t& match_position)
  440. {
  441. auto max_chain_length = m_compression_constants.max_chain;
  442. if (previous_match_length == 0)
  443. previous_match_length = min_match_length - 1; // we only care about matches that are at least min_match_length long
  444. if (previous_match_length >= maximum_match_length)
  445. return 0; // we can't improve a maximum length match
  446. if (previous_match_length >= m_compression_constants.max_lazy_length)
  447. return 0; // the previous match is already pretty, we shouldn't waste another full search
  448. if (previous_match_length >= m_compression_constants.good_match_length)
  449. max_chain_length /= 4; // we already have a pretty good much, so do a shorter search
  450. auto candidate = m_hash_head[hash];
  451. auto match_found = false;
  452. while (max_chain_length--) {
  453. if (candidate == empty_slot)
  454. break; // no remaining candidates
  455. VERIFY(candidate < start);
  456. if (start - candidate > window_size)
  457. break; // outside the window
  458. auto match_length = compare_match_candidate(start, candidate, previous_match_length, maximum_match_length);
  459. if (match_length != 0) {
  460. match_found = true;
  461. match_position = candidate;
  462. previous_match_length = match_length;
  463. if (match_length == maximum_match_length)
  464. return match_length; // bail if we got the maximum possible length
  465. }
  466. candidate = m_hash_prev[candidate % window_size];
  467. }
  468. if (!match_found)
  469. return 0; // we didn't find any matches
  470. return previous_match_length; // we found matches, but they were at most previous_match_length long
  471. }
  472. ALWAYS_INLINE u8 DeflateCompressor::distance_to_base(u16 distance)
  473. {
  474. return (distance <= 256) ? distance_to_base_lo[distance - 1] : distance_to_base_hi[(distance - 1) >> 7];
  475. }
  476. template<size_t Size>
  477. void DeflateCompressor::generate_huffman_lengths(Array<u8, Size>& lengths, Array<u16, Size> const& frequencies, size_t max_bit_length, u16 frequency_cap)
  478. {
  479. VERIFY((1u << max_bit_length) >= Size);
  480. u16 heap_keys[Size]; // Used for O(n) heap construction
  481. u16 heap_values[Size];
  482. u16 huffman_links[Size * 2 + 1] = { 0 };
  483. size_t non_zero_freqs = 0;
  484. for (size_t i = 0; i < Size; i++) {
  485. auto frequency = frequencies[i];
  486. if (frequency == 0)
  487. continue;
  488. if (frequency > frequency_cap) {
  489. frequency = frequency_cap;
  490. }
  491. heap_keys[non_zero_freqs] = frequency; // sort symbols by frequency
  492. heap_values[non_zero_freqs] = Size + non_zero_freqs; // huffman_links "links"
  493. non_zero_freqs++;
  494. }
  495. // special case for only 1 used symbol
  496. if (non_zero_freqs < 2) {
  497. for (size_t i = 0; i < Size; i++)
  498. lengths[i] = (frequencies[i] == 0) ? 0 : 1;
  499. return;
  500. }
  501. BinaryHeap<u16, u16, Size> heap { heap_keys, heap_values, non_zero_freqs };
  502. // build the huffman tree - binary heap is used for efficient frequency comparisons
  503. while (heap.size() > 1) {
  504. u16 lowest_frequency = heap.peek_min_key();
  505. u16 lowest_link = heap.pop_min();
  506. u16 second_lowest_frequency = heap.peek_min_key();
  507. u16 second_lowest_link = heap.pop_min();
  508. u16 new_link = heap.size() + 2;
  509. heap.insert(lowest_frequency + second_lowest_frequency, new_link);
  510. huffman_links[lowest_link] = new_link;
  511. huffman_links[second_lowest_link] = new_link;
  512. }
  513. non_zero_freqs = 0;
  514. for (size_t i = 0; i < Size; i++) {
  515. if (frequencies[i] == 0) {
  516. lengths[i] = 0;
  517. continue;
  518. }
  519. u16 link = huffman_links[Size + non_zero_freqs];
  520. non_zero_freqs++;
  521. size_t bit_length = 1;
  522. while (link != 2) {
  523. bit_length++;
  524. link = huffman_links[link];
  525. }
  526. if (bit_length > max_bit_length) {
  527. VERIFY(frequency_cap != 1);
  528. return generate_huffman_lengths(lengths, frequencies, max_bit_length, frequency_cap / 2);
  529. }
  530. lengths[i] = bit_length;
  531. }
  532. }
  533. void DeflateCompressor::lz77_compress_block()
  534. {
  535. for (auto& slot : m_hash_head) { // initialize chained hash table
  536. slot = empty_slot;
  537. }
  538. auto insert_hash = [&](auto pos, auto hash) {
  539. auto window_pos = pos % window_size;
  540. m_hash_prev[window_pos] = m_hash_head[hash];
  541. m_hash_head[hash] = window_pos;
  542. };
  543. auto emit_literal = [&](auto literal) {
  544. VERIFY(m_pending_symbol_size <= block_size + 1);
  545. auto index = m_pending_symbol_size++;
  546. m_symbol_buffer[index].distance = 0;
  547. m_symbol_buffer[index].literal = literal;
  548. m_symbol_frequencies[literal]++;
  549. };
  550. auto emit_back_reference = [&](auto distance, auto length) {
  551. VERIFY(m_pending_symbol_size <= block_size + 1);
  552. auto index = m_pending_symbol_size++;
  553. m_symbol_buffer[index].distance = distance;
  554. m_symbol_buffer[index].length = length;
  555. m_symbol_frequencies[length_to_symbol[length]]++;
  556. m_distance_frequencies[distance_to_base(distance)]++;
  557. };
  558. size_t previous_match_length = 0;
  559. size_t previous_match_position = 0;
  560. VERIFY(m_compression_constants.great_match_length <= max_match_length);
  561. // our block starts at block_size and is m_pending_block_size in length
  562. auto block_end = block_size + m_pending_block_size;
  563. size_t current_position;
  564. for (current_position = block_size; current_position < block_end - min_match_length + 1; current_position++) {
  565. auto hash = hash_sequence(&m_rolling_window[current_position]);
  566. size_t match_position;
  567. auto match_length = find_back_match(current_position, hash, previous_match_length,
  568. min(m_compression_constants.great_match_length, block_end - current_position), match_position);
  569. insert_hash(current_position, hash);
  570. // if the previous match is as good as the new match, just use it
  571. if (previous_match_length != 0 && previous_match_length >= match_length) {
  572. emit_back_reference((current_position - 1) - previous_match_position, previous_match_length);
  573. // skip all the bytes that are included in this match
  574. for (size_t j = current_position + 1; j < min(current_position - 1 + previous_match_length, block_end - min_match_length + 1); j++) {
  575. insert_hash(j, hash_sequence(&m_rolling_window[j]));
  576. }
  577. current_position = (current_position - 1) + previous_match_length - 1;
  578. previous_match_length = 0;
  579. continue;
  580. }
  581. if (match_length == 0) {
  582. VERIFY(previous_match_length == 0);
  583. emit_literal(m_rolling_window[current_position]);
  584. continue;
  585. }
  586. // if this is a lazy match, and the new match is better than the old one, output previous as literal
  587. if (previous_match_length != 0) {
  588. emit_literal(m_rolling_window[current_position - 1]);
  589. }
  590. previous_match_length = match_length;
  591. previous_match_position = match_position;
  592. }
  593. // clean up leftover lazy match
  594. if (previous_match_length != 0) {
  595. emit_back_reference((current_position - 1) - previous_match_position, previous_match_length);
  596. current_position = (current_position - 1) + previous_match_length;
  597. }
  598. // output remaining literals
  599. while (current_position < block_end) {
  600. emit_literal(m_rolling_window[current_position++]);
  601. }
  602. }
  603. size_t DeflateCompressor::huffman_block_length(Array<u8, max_huffman_literals> const& literal_bit_lengths, Array<u8, max_huffman_distances> const& distance_bit_lengths)
  604. {
  605. size_t length = 0;
  606. for (size_t i = 0; i < 286; i++) {
  607. auto frequency = m_symbol_frequencies[i];
  608. length += literal_bit_lengths[i] * frequency;
  609. if (i >= 257) // back reference length symbols
  610. length += packed_length_symbols[i - 257].extra_bits * frequency;
  611. }
  612. for (size_t i = 0; i < 30; i++) {
  613. auto frequency = m_distance_frequencies[i];
  614. length += distance_bit_lengths[i] * frequency;
  615. length += packed_distances[i].extra_bits * frequency;
  616. }
  617. return length;
  618. }
  619. size_t DeflateCompressor::uncompressed_block_length()
  620. {
  621. auto padding = 8 - ((m_output_stream->bit_offset() + 3) % 8);
  622. // 3 bit block header + align to byte + 2 * 16 bit length fields + block contents
  623. return 3 + padding + (2 * 16) + m_pending_block_size * 8;
  624. }
  625. size_t DeflateCompressor::fixed_block_length()
  626. {
  627. // block header + fixed huffman encoded block contents
  628. return 3 + huffman_block_length(fixed_literal_bit_lengths, fixed_distance_bit_lengths);
  629. }
  630. size_t DeflateCompressor::dynamic_block_length(Array<u8, max_huffman_literals> const& literal_bit_lengths, Array<u8, max_huffman_distances> const& distance_bit_lengths, Array<u8, 19> const& code_lengths_bit_lengths, Array<u16, 19> const& code_lengths_frequencies, size_t code_lengths_count)
  631. {
  632. // block header + literal code count + distance code count + code length count
  633. auto length = 3 + 5 + 5 + 4;
  634. // 3 bits per code_length
  635. length += 3 * code_lengths_count;
  636. for (size_t i = 0; i < code_lengths_frequencies.size(); i++) {
  637. auto frequency = code_lengths_frequencies[i];
  638. length += code_lengths_bit_lengths[i] * frequency;
  639. if (i == deflate_special_code_length_copy) {
  640. length += 2 * frequency;
  641. } else if (i == deflate_special_code_length_zeros) {
  642. length += 3 * frequency;
  643. } else if (i == deflate_special_code_length_long_zeros) {
  644. length += 7 * frequency;
  645. }
  646. }
  647. return length + huffman_block_length(literal_bit_lengths, distance_bit_lengths);
  648. }
  649. ErrorOr<void> DeflateCompressor::write_huffman(CanonicalCode const& literal_code, Optional<CanonicalCode> const& distance_code)
  650. {
  651. auto has_distances = distance_code.has_value();
  652. for (size_t i = 0; i < m_pending_symbol_size; i++) {
  653. if (m_symbol_buffer[i].distance == 0) {
  654. TRY(literal_code.write_symbol(*m_output_stream, m_symbol_buffer[i].literal));
  655. continue;
  656. }
  657. VERIFY(has_distances);
  658. auto symbol = length_to_symbol[m_symbol_buffer[i].length];
  659. TRY(literal_code.write_symbol(*m_output_stream, symbol));
  660. // Emit extra bits if needed
  661. TRY(m_output_stream->write_bits<u16>(m_symbol_buffer[i].length - packed_length_symbols[symbol - 257].base_length, packed_length_symbols[symbol - 257].extra_bits));
  662. auto base_distance = distance_to_base(m_symbol_buffer[i].distance);
  663. TRY(distance_code.value().write_symbol(*m_output_stream, base_distance));
  664. // Emit extra bits if needed
  665. TRY(m_output_stream->write_bits<u16>(m_symbol_buffer[i].distance - packed_distances[base_distance].base_distance, packed_distances[base_distance].extra_bits));
  666. }
  667. return {};
  668. }
  669. size_t DeflateCompressor::encode_huffman_lengths(Array<u8, max_huffman_literals + max_huffman_distances> const& lengths, size_t lengths_count, Array<code_length_symbol, max_huffman_literals + max_huffman_distances>& encoded_lengths)
  670. {
  671. size_t encoded_count = 0;
  672. size_t i = 0;
  673. while (i < lengths_count) {
  674. if (lengths[i] == 0) {
  675. auto zero_count = 0;
  676. for (size_t j = i; j < min(lengths_count, i + 138) && lengths[j] == 0; j++)
  677. zero_count++;
  678. if (zero_count < 3) { // below minimum repeated zero count
  679. encoded_lengths[encoded_count++].symbol = 0;
  680. i++;
  681. continue;
  682. }
  683. if (zero_count <= 10) {
  684. encoded_lengths[encoded_count].symbol = deflate_special_code_length_zeros;
  685. encoded_lengths[encoded_count++].count = zero_count;
  686. } else {
  687. encoded_lengths[encoded_count].symbol = deflate_special_code_length_long_zeros;
  688. encoded_lengths[encoded_count++].count = zero_count;
  689. }
  690. i += zero_count;
  691. continue;
  692. }
  693. encoded_lengths[encoded_count++].symbol = lengths[i++];
  694. auto copy_count = 0;
  695. for (size_t j = i; j < min(lengths_count, i + 6) && lengths[j] == lengths[i - 1]; j++)
  696. copy_count++;
  697. if (copy_count >= 3) {
  698. encoded_lengths[encoded_count].symbol = deflate_special_code_length_copy;
  699. encoded_lengths[encoded_count++].count = copy_count;
  700. i += copy_count;
  701. continue;
  702. }
  703. }
  704. return encoded_count;
  705. }
  706. size_t DeflateCompressor::encode_block_lengths(Array<u8, max_huffman_literals> const& literal_bit_lengths, Array<u8, max_huffman_distances> const& distance_bit_lengths, Array<code_length_symbol, max_huffman_literals + max_huffman_distances>& encoded_lengths, size_t& literal_code_count, size_t& distance_code_count)
  707. {
  708. literal_code_count = max_huffman_literals;
  709. distance_code_count = max_huffman_distances;
  710. VERIFY(literal_bit_lengths[256] != 0); // Make sure at least the EndOfBlock marker is present
  711. while (literal_bit_lengths[literal_code_count - 1] == 0)
  712. literal_code_count--;
  713. // Drop trailing zero lengths, keeping at least one
  714. while (distance_bit_lengths[distance_code_count - 1] == 0 && distance_code_count > 1)
  715. distance_code_count--;
  716. Array<u8, max_huffman_literals + max_huffman_distances> all_lengths {};
  717. size_t lengths_count = 0;
  718. for (size_t i = 0; i < literal_code_count; i++) {
  719. all_lengths[lengths_count++] = literal_bit_lengths[i];
  720. }
  721. for (size_t i = 0; i < distance_code_count; i++) {
  722. all_lengths[lengths_count++] = distance_bit_lengths[i];
  723. }
  724. return encode_huffman_lengths(all_lengths, lengths_count, encoded_lengths);
  725. }
  726. ErrorOr<void> DeflateCompressor::write_dynamic_huffman(CanonicalCode const& literal_code, size_t literal_code_count, Optional<CanonicalCode> const& distance_code, size_t distance_code_count, Array<u8, 19> const& code_lengths_bit_lengths, size_t code_length_count, Array<code_length_symbol, max_huffman_literals + max_huffman_distances> const& encoded_lengths, size_t encoded_lengths_count)
  727. {
  728. TRY(m_output_stream->write_bits(literal_code_count - 257, 5));
  729. TRY(m_output_stream->write_bits(distance_code_count - 1, 5));
  730. TRY(m_output_stream->write_bits(code_length_count - 4, 4));
  731. for (size_t i = 0; i < code_length_count; i++) {
  732. TRY(m_output_stream->write_bits(code_lengths_bit_lengths[code_lengths_code_lengths_order[i]], 3));
  733. }
  734. auto code_lengths_code = MUST(CanonicalCode::from_bytes(code_lengths_bit_lengths));
  735. for (size_t i = 0; i < encoded_lengths_count; i++) {
  736. auto encoded_length = encoded_lengths[i];
  737. TRY(code_lengths_code.write_symbol(*m_output_stream, encoded_length.symbol));
  738. if (encoded_length.symbol == deflate_special_code_length_copy) {
  739. TRY(m_output_stream->write_bits<u8>(encoded_length.count - 3, 2));
  740. } else if (encoded_length.symbol == deflate_special_code_length_zeros) {
  741. TRY(m_output_stream->write_bits<u8>(encoded_length.count - 3, 3));
  742. } else if (encoded_length.symbol == deflate_special_code_length_long_zeros) {
  743. TRY(m_output_stream->write_bits<u8>(encoded_length.count - 11, 7));
  744. }
  745. }
  746. TRY(write_huffman(literal_code, distance_code));
  747. return {};
  748. }
  749. ErrorOr<void> DeflateCompressor::flush()
  750. {
  751. TRY(m_output_stream->write_bits(m_finished, 1));
  752. // if this is just an empty block to signify the end of the deflate stream use the smallest block possible (10 bits total)
  753. if (m_pending_block_size == 0) {
  754. VERIFY(m_finished); // we shouldn't be writing empty blocks unless this is the final one
  755. TRY(m_output_stream->write_bits(0b01u, 2)); // fixed huffman codes
  756. TRY(m_output_stream->write_bits(0b0000000u, 7)); // end of block symbol
  757. TRY(m_output_stream->align_to_byte_boundary());
  758. return {};
  759. }
  760. auto write_uncompressed = [&]() -> ErrorOr<void> {
  761. TRY(m_output_stream->write_bits(0b00u, 2)); // no compression
  762. TRY(m_output_stream->align_to_byte_boundary());
  763. LittleEndian<u16> len = m_pending_block_size;
  764. TRY(m_output_stream->write_until_depleted(len.bytes()));
  765. LittleEndian<u16> nlen = ~m_pending_block_size;
  766. TRY(m_output_stream->write_until_depleted(nlen.bytes()));
  767. TRY(m_output_stream->write_until_depleted(pending_block().slice(0, m_pending_block_size)));
  768. return {};
  769. };
  770. if (m_compression_level == CompressionLevel::STORE) { // disabled compression fast path
  771. TRY(write_uncompressed());
  772. m_pending_block_size = 0;
  773. return {};
  774. }
  775. // The following implementation of lz77 compression and huffman encoding is based on the reference implementation by Hans Wennborg https://www.hanshq.net/zip.html
  776. // this reads from the pending block and writes to m_symbol_buffer
  777. lz77_compress_block();
  778. // insert EndOfBlock marker to the symbol buffer
  779. m_symbol_buffer[m_pending_symbol_size].distance = 0;
  780. m_symbol_buffer[m_pending_symbol_size++].literal = 256;
  781. m_symbol_frequencies[256]++;
  782. // generate optimal dynamic huffman code lengths
  783. Array<u8, max_huffman_literals> dynamic_literal_bit_lengths {};
  784. Array<u8, max_huffman_distances> dynamic_distance_bit_lengths {};
  785. generate_huffman_lengths(dynamic_literal_bit_lengths, m_symbol_frequencies, 15); // deflate data huffman can use up to 15 bits per symbol
  786. generate_huffman_lengths(dynamic_distance_bit_lengths, m_distance_frequencies, 15);
  787. // encode literal and distance lengths together in deflate format
  788. Array<code_length_symbol, max_huffman_literals + max_huffman_distances> encoded_lengths {};
  789. size_t literal_code_count;
  790. size_t distance_code_count;
  791. auto encoded_lengths_count = encode_block_lengths(dynamic_literal_bit_lengths, dynamic_distance_bit_lengths, encoded_lengths, literal_code_count, distance_code_count);
  792. // count code length frequencies
  793. Array<u16, 19> code_lengths_frequencies { 0 };
  794. for (size_t i = 0; i < encoded_lengths_count; i++) {
  795. code_lengths_frequencies[encoded_lengths[i].symbol]++;
  796. }
  797. // generate optimal huffman code lengths code lengths
  798. Array<u8, 19> code_lengths_bit_lengths {};
  799. generate_huffman_lengths(code_lengths_bit_lengths, code_lengths_frequencies, 7); // deflate code length huffman can use up to 7 bits per symbol
  800. // calculate actual code length code lengths count (without trailing zeros)
  801. auto code_lengths_count = code_lengths_bit_lengths.size();
  802. while (code_lengths_bit_lengths[code_lengths_code_lengths_order[code_lengths_count - 1]] == 0)
  803. code_lengths_count--;
  804. auto uncompressed_size = uncompressed_block_length();
  805. auto fixed_huffman_size = fixed_block_length();
  806. auto dynamic_huffman_size = dynamic_block_length(dynamic_literal_bit_lengths, dynamic_distance_bit_lengths, code_lengths_bit_lengths, code_lengths_frequencies, code_lengths_count);
  807. // If the compression somehow didn't reduce the size enough, just write out the block uncompressed as it allows for much faster decompression
  808. if (uncompressed_size <= min(fixed_huffman_size, dynamic_huffman_size)) {
  809. TRY(write_uncompressed());
  810. } else if (fixed_huffman_size <= dynamic_huffman_size) {
  811. // If the fixed and dynamic huffman codes come out the same size, prefer the fixed version, as it takes less time to decode fixed huffman codes.
  812. TRY(m_output_stream->write_bits(0b01u, 2));
  813. TRY(write_huffman(CanonicalCode::fixed_literal_codes(), CanonicalCode::fixed_distance_codes()));
  814. } else {
  815. // dynamic huffman codes
  816. TRY(m_output_stream->write_bits(0b10u, 2));
  817. auto literal_code = MUST(CanonicalCode::from_bytes(dynamic_literal_bit_lengths));
  818. auto distance_code_or_error = CanonicalCode::from_bytes(dynamic_distance_bit_lengths);
  819. Optional<CanonicalCode> distance_code;
  820. if (!distance_code_or_error.is_error())
  821. distance_code = distance_code_or_error.release_value();
  822. TRY(write_dynamic_huffman(literal_code, literal_code_count, distance_code, distance_code_count, code_lengths_bit_lengths, code_lengths_count, encoded_lengths, encoded_lengths_count));
  823. }
  824. if (m_finished)
  825. TRY(m_output_stream->align_to_byte_boundary());
  826. // reset all block specific members
  827. m_pending_block_size = 0;
  828. m_pending_symbol_size = 0;
  829. m_symbol_frequencies.fill(0);
  830. m_distance_frequencies.fill(0);
  831. // On the final block this copy will potentially produce an invalid search window, but since its the final block we dont care
  832. pending_block().copy_trimmed_to({ m_rolling_window, block_size });
  833. return {};
  834. }
  835. ErrorOr<void> DeflateCompressor::final_flush()
  836. {
  837. VERIFY(!m_finished);
  838. m_finished = true;
  839. TRY(flush());
  840. TRY(m_output_stream->flush_buffer_to_stream());
  841. return {};
  842. }
  843. ErrorOr<ByteBuffer> DeflateCompressor::compress_all(ReadonlyBytes bytes, CompressionLevel compression_level)
  844. {
  845. auto output_stream = TRY(try_make<AllocatingMemoryStream>());
  846. auto deflate_stream = TRY(DeflateCompressor::construct(MaybeOwned<Stream>(*output_stream), compression_level));
  847. TRY(deflate_stream->write_until_depleted(bytes));
  848. TRY(deflate_stream->final_flush());
  849. auto buffer = TRY(ByteBuffer::create_uninitialized(output_stream->used_buffer_size()));
  850. TRY(output_stream->read_until_filled(buffer));
  851. return buffer;
  852. }
  853. }