Deflate.cpp 37 KB

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