Deflate.cpp 39 KB

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