Deflate.cpp 38 KB

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