Deflate.cpp 38 KB

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