Deflate.cpp 37 KB

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