Deflate.cpp 37 KB

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