Lzma.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /*
  2. * Copyright (c) 2023, Tim Schumacher <timschumi@gmx.de>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/CircularBuffer.h>
  8. #include <AK/FixedArray.h>
  9. #include <AK/MaybeOwned.h>
  10. #include <AK/NonnullOwnPtr.h>
  11. #include <AK/Stream.h>
  12. namespace Compress {
  13. // This implementation is mostly based on the LZMA specification contained in the 7-Zip SDK, which has been placed in the public domain.
  14. // LZMA Specification Draft (2015): https://www.7-zip.org/a/lzma-specification.7z
  15. struct LzmaModelProperties {
  16. u8 literal_context_bits;
  17. u8 literal_position_bits;
  18. u8 position_bits;
  19. };
  20. struct LzmaDecompressorOptions {
  21. u8 literal_context_bits { 0 };
  22. u8 literal_position_bits { 0 };
  23. u8 position_bits { 0 };
  24. u32 dictionary_size { 0 };
  25. Optional<u64> uncompressed_size;
  26. bool reject_end_of_stream_marker { false };
  27. };
  28. struct LzmaCompressorOptions {
  29. // Note: The default settings have been chosen based on the default settings of other LZMA compressors.
  30. u8 literal_context_bits { 3 };
  31. u8 literal_position_bits { 0 };
  32. u8 position_bits { 2 };
  33. u32 dictionary_size { 8 * MiB };
  34. Optional<u64> uncompressed_size {};
  35. };
  36. // Described in section "lzma file format".
  37. struct [[gnu::packed]] LzmaHeader {
  38. u32 dictionary_size() const;
  39. Optional<u64> uncompressed_size() const;
  40. ErrorOr<LzmaDecompressorOptions> as_decompressor_options() const;
  41. static ErrorOr<LzmaHeader> from_compressor_options(LzmaCompressorOptions const&);
  42. static ErrorOr<LzmaModelProperties> decode_model_properties(u8 input_bits);
  43. static ErrorOr<u8> encode_model_properties(LzmaModelProperties const&);
  44. u8 encoded_model_properties;
  45. u32 unchecked_dictionary_size;
  46. u64 encoded_uncompressed_size;
  47. static constexpr u64 placeholder_for_unknown_uncompressed_size = UINT64_MAX;
  48. };
  49. static_assert(sizeof(LzmaHeader) == 13);
  50. class LzmaState {
  51. protected:
  52. // LZMA uses 11-bit probability counters, but they are usually stored in 16-bit variables.
  53. // Therefore, we can model probabilities with a resolution of up to 1 / 2^11 (which is equal to 1 / 2048).
  54. // The default probability for most counters is 0.5.
  55. using Probability = u16;
  56. static constexpr size_t probability_bit_count = 11;
  57. static constexpr Probability default_probability = (1 << probability_bit_count) / 2;
  58. static void initialize_to_default_probability(Span<Probability>);
  59. // The significance of the shift width is not explained and appears to be a magic constant.
  60. static constexpr size_t probability_shift_width = 5;
  61. // "The value of the "Range" variable before each bit decoding can not be smaller than ((UInt32)1 << 24)."
  62. static constexpr u32 minimum_range_value = 1 << 24;
  63. LzmaState(FixedArray<Probability> literal_probabilities);
  64. u64 m_total_processed_bytes { 0 };
  65. static constexpr size_t literal_probability_table_size = 0x300;
  66. FixedArray<Probability> m_literal_probabilities;
  67. struct LzmaLengthCoderState {
  68. public:
  69. LzmaLengthCoderState();
  70. Probability m_first_choice_probability { default_probability };
  71. Probability m_second_choice_probability { default_probability };
  72. static constexpr size_t maximum_number_of_position_bits = 4;
  73. Array<Array<Probability, (1 << 3)>, (1 << maximum_number_of_position_bits)> m_low_length_probabilities;
  74. Array<Array<Probability, (1 << 3)>, (1 << maximum_number_of_position_bits)> m_medium_length_probabilities;
  75. Array<Probability, (1 << 8)> m_high_length_probabilities;
  76. };
  77. LzmaLengthCoderState m_length_coder;
  78. LzmaLengthCoderState m_rep_length_coder;
  79. static constexpr u16 normalized_to_real_match_length_offset = 2;
  80. static constexpr u32 normalized_to_real_match_distance_offset = 1;
  81. // According to the specification, the largest possible normalized match length is provided by the high coder,
  82. // which processes 8 bits (0 to 255) and adds a displacement of 16 on top.
  83. // This is the minimum size that our input buffer has to have to not miss any possible repetitions while encoding.
  84. static constexpr u16 largest_real_match_length = 255 + 16 + normalized_to_real_match_length_offset;
  85. static constexpr u32 end_of_stream_marker = 0xFFFFFFFF;
  86. static constexpr size_t number_of_length_to_position_states = 4;
  87. Array<Array<Probability, (1 << 6)>, number_of_length_to_position_states> m_length_to_position_states;
  88. static constexpr size_t first_position_slot_with_binary_tree_bits = 4;
  89. static constexpr size_t first_position_slot_with_direct_encoded_bits = 14;
  90. // This is a bit wasteful on memory and not in the specification, but it makes the math easier.
  91. static constexpr size_t number_of_binary_tree_distance_slots = first_position_slot_with_direct_encoded_bits - first_position_slot_with_binary_tree_bits;
  92. static constexpr size_t largest_number_of_binary_tree_distance_bits = 5;
  93. Array<Array<Probability, (1 << largest_number_of_binary_tree_distance_bits)>, number_of_binary_tree_distance_slots> m_binary_tree_distance_probabilities;
  94. static constexpr size_t number_of_alignment_bits = 4;
  95. Array<Probability, (1 << number_of_alignment_bits)> m_alignment_bit_probabilities;
  96. // LZ state tracking.
  97. u16 m_state { 0 };
  98. u32 m_rep0 { 0 };
  99. u32 m_rep1 { 0 };
  100. u32 m_rep2 { 0 };
  101. u32 m_rep3 { 0 };
  102. u32 current_repetition_offset() const;
  103. void update_state_after_literal();
  104. void update_state_after_match();
  105. void update_state_after_rep();
  106. void update_state_after_short_rep();
  107. static constexpr size_t maximum_number_of_position_bits = 4;
  108. static constexpr size_t number_of_states = 12;
  109. Array<Probability, (number_of_states << maximum_number_of_position_bits)> m_is_match_probabilities;
  110. Array<Probability, number_of_states> m_is_rep_probabilities;
  111. Array<Probability, number_of_states> m_is_rep_g0_probabilities;
  112. Array<Probability, number_of_states> m_is_rep_g1_probabilities;
  113. Array<Probability, number_of_states> m_is_rep_g2_probabilities;
  114. Array<Probability, (number_of_states << maximum_number_of_position_bits)> m_is_rep0_long_probabilities;
  115. enum MatchType {
  116. Literal,
  117. SimpleMatch,
  118. RepMatch0,
  119. ShortRepMatch,
  120. RepMatch1,
  121. RepMatch2,
  122. RepMatch3,
  123. };
  124. };
  125. class LzmaDecompressor : public Stream
  126. , LzmaState {
  127. public:
  128. /// Creates a decompressor from a standalone LZMA container (.lzma file extension, occasionally known as an LZMA 'archive').
  129. static ErrorOr<NonnullOwnPtr<LzmaDecompressor>> create_from_container(MaybeOwned<Stream>, Optional<MaybeOwned<CircularBuffer>> dictionary = {});
  130. /// Creates a decompressor from a raw stream of LZMA-compressed data (found inside an LZMA container or embedded in other file formats).
  131. static ErrorOr<NonnullOwnPtr<LzmaDecompressor>> create_from_raw_stream(MaybeOwned<Stream>, LzmaDecompressorOptions const&, Optional<MaybeOwned<CircularBuffer>> dictionary = {});
  132. ErrorOr<void> append_input_stream(MaybeOwned<Stream>, Optional<u64> uncompressed_size);
  133. virtual ErrorOr<Bytes> read_some(Bytes) override;
  134. virtual ErrorOr<size_t> write_some(ReadonlyBytes) override;
  135. virtual bool is_eof() const override;
  136. virtual bool is_open() const override;
  137. virtual void close() override;
  138. private:
  139. LzmaDecompressor(MaybeOwned<Stream>, LzmaDecompressorOptions, MaybeOwned<CircularBuffer>, FixedArray<Probability> literal_probabilities);
  140. MaybeOwned<Stream> m_stream;
  141. LzmaDecompressorOptions m_options;
  142. // This doubles as an output buffer, since we have to write all of our results into this anyways.
  143. MaybeOwned<CircularBuffer> m_dictionary;
  144. bool m_found_end_of_stream_marker { false };
  145. bool is_range_decoder_in_clean_state() const;
  146. bool has_reached_expected_data_size() const;
  147. Optional<u16> m_leftover_match_length;
  148. // Range decoder state (initialized with stream data in LzmaDecompressor::create).
  149. u32 m_range_decoder_range { 0xFFFFFFFF };
  150. u32 m_range_decoder_code { 0 };
  151. ErrorOr<void> initialize_range_decoder();
  152. ErrorOr<void> normalize_range_decoder();
  153. ErrorOr<u8> decode_direct_bit();
  154. ErrorOr<u8> decode_bit_with_probability(Probability& probability);
  155. ErrorOr<MatchType> decode_match_type();
  156. // Decodes a multi-bit symbol using a given probability tree (either in normal or in reverse order).
  157. // The specification states that "unsigned" is at least 16 bits in size, our implementation assumes this as the maximum symbol size.
  158. ErrorOr<u16> decode_symbol_using_bit_tree(size_t bit_count, Span<Probability> probability_tree);
  159. ErrorOr<u16> decode_symbol_using_reverse_bit_tree(size_t bit_count, Span<Probability> probability_tree);
  160. ErrorOr<void> decode_literal_to_output_buffer();
  161. ErrorOr<u16> decode_normalized_match_length(LzmaLengthCoderState&);
  162. // This deviates from the specification, which states that "unsigned" is at least 16-bit.
  163. // However, the match distance needs to be at least 32-bit, at the very least to hold the 0xFFFFFFFF end marker value.
  164. ErrorOr<u32> decode_normalized_match_distance(u16 normalized_match_length);
  165. };
  166. class LzmaCompressor : public Stream
  167. , LzmaState {
  168. public:
  169. /// Creates a compressor for a standalone LZMA container (.lzma file extension, occasionally known as an LZMA 'archive').
  170. static ErrorOr<NonnullOwnPtr<LzmaCompressor>> create_container(MaybeOwned<Stream>, LzmaCompressorOptions const&);
  171. /// Finishes the archive by writing out the remaining data from the range coder.
  172. ErrorOr<void> flush();
  173. virtual ErrorOr<Bytes> read_some(Bytes) override;
  174. virtual ErrorOr<size_t> write_some(ReadonlyBytes) override;
  175. virtual bool is_eof() const override;
  176. virtual bool is_open() const override;
  177. virtual void close() override;
  178. virtual ~LzmaCompressor();
  179. private:
  180. LzmaCompressor(MaybeOwned<Stream>, LzmaCompressorOptions, MaybeOwned<SearchableCircularBuffer>, FixedArray<Probability> literal_probabilities);
  181. ErrorOr<void> shift_range_encoder();
  182. ErrorOr<void> normalize_range_encoder();
  183. ErrorOr<void> encode_direct_bit(u8 value);
  184. ErrorOr<void> encode_bit_with_probability(Probability&, u8 value);
  185. ErrorOr<void> encode_symbol_using_bit_tree(size_t bit_count, Span<Probability> probability_tree, u16 value);
  186. ErrorOr<void> encode_symbol_using_reverse_bit_tree(size_t bit_count, Span<Probability> probability_tree, u16 value);
  187. ErrorOr<void> encode_normalized_match_length(LzmaLengthCoderState&, u16 normalized_length);
  188. ErrorOr<void> encode_normalized_match_distance(u16 normalized_match_length, u32 normalized_match_distance);
  189. ErrorOr<void> encode_match_type(MatchType);
  190. ErrorOr<void> encode_literal(u8 literal);
  191. ErrorOr<void> encode_existing_match(size_t real_distance, size_t real_length);
  192. ErrorOr<void> encode_new_match(size_t real_distance, size_t real_length);
  193. ErrorOr<void> encode_normalized_simple_match(u32 normalized_distance, u16 normalized_length);
  194. ErrorOr<void> encode_once();
  195. bool m_has_flushed_data { false };
  196. MaybeOwned<Stream> m_stream;
  197. LzmaCompressorOptions m_options;
  198. // This doubles as an input buffer, which is appended at the very front of the buffer.
  199. // Therefore, the size of this should at least be the dictionary size + the largest possible repetition length.
  200. MaybeOwned<SearchableCircularBuffer> m_dictionary;
  201. // Range encoder state.
  202. u32 m_range_encoder_range { 0xFFFFFFFF };
  203. u64 m_range_encoder_code { 0 };
  204. // Since the range is only 32-bits, we can overflow at most +1 into the next byte beyond the usual 32-bit code.
  205. // Therefore, it is sufficient to store the highest byte (which may still change due to that +1 overflow) and
  206. // the length of the chain of 0xFF bytes that may end up propagating that change.
  207. u8 m_range_encoder_cached_byte { 0x00 };
  208. size_t m_range_encoder_ff_chain_length { 0 };
  209. };
  210. }
  211. template<>
  212. struct AK::Traits<Compress::LzmaHeader> : public AK::DefaultTraits<Compress::LzmaHeader> {
  213. static constexpr bool is_trivially_serializable() { return true; }
  214. };