Deflate.cpp 39 KB

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