Deflate.cpp 38 KB

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