Lzma.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  1. /*
  2. * Copyright (c) 2023, Tim Schumacher <timschumi@gmx.de>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/IntegralMath.h>
  8. #include <LibCompress/Lzma.h>
  9. namespace Compress {
  10. u32 LzmaHeader::dictionary_size() const
  11. {
  12. // "If the value of dictionary size in properties is smaller than (1 << 12),
  13. // the LZMA decoder must set the dictionary size variable to (1 << 12)."
  14. constexpr u32 minimum_dictionary_size = (1 << 12);
  15. if (unchecked_dictionary_size < minimum_dictionary_size)
  16. return minimum_dictionary_size;
  17. return unchecked_dictionary_size;
  18. }
  19. Optional<u64> LzmaHeader::uncompressed_size() const
  20. {
  21. // We are making a copy of the packed field here because we would otherwise
  22. // pass an unaligned reference to the constructor of Optional, which is
  23. // undefined behavior.
  24. auto uncompressed_size = encoded_uncompressed_size;
  25. // "If "Uncompressed size" field contains ones in all 64 bits, it means that
  26. // uncompressed size is unknown and there is the "end marker" in stream,
  27. // that indicates the end of decoding point."
  28. if (uncompressed_size == placeholder_for_unknown_uncompressed_size)
  29. return {};
  30. // "In opposite case, if the value from "Uncompressed size" field is not
  31. // equal to ((2^64) - 1), the LZMA stream decoding must be finished after
  32. // specified number of bytes (Uncompressed size) is decoded. And if there
  33. // is the "end marker", the LZMA decoder must read that marker also."
  34. return uncompressed_size;
  35. }
  36. ErrorOr<LzmaModelProperties> LzmaHeader::decode_model_properties(u8 input_bits)
  37. {
  38. // "Decodes the following values from the encoded model properties field:
  39. //
  40. // name Range Description
  41. // lc [0, 8] the number of "literal context" bits
  42. // lp [0, 4] the number of "literal pos" bits
  43. // pb [0, 4] the number of "pos" bits
  44. //
  45. // Encoded using `((pb * 5 + lp) * 9 + lc)`."
  46. if (input_bits >= (9 * 5 * 5))
  47. return Error::from_string_literal("Encoded model properties value is larger than the highest possible value");
  48. u8 literal_context_bits = input_bits % 9;
  49. input_bits /= 9;
  50. VERIFY(literal_context_bits >= 0 && literal_context_bits <= 8);
  51. u8 literal_position_bits = input_bits % 5;
  52. input_bits /= 5;
  53. VERIFY(literal_position_bits >= 0 && literal_position_bits <= 4);
  54. u8 position_bits = input_bits;
  55. VERIFY(position_bits >= 0 && position_bits <= 4);
  56. return LzmaModelProperties {
  57. .literal_context_bits = literal_context_bits,
  58. .literal_position_bits = literal_position_bits,
  59. .position_bits = position_bits,
  60. };
  61. }
  62. ErrorOr<u8> LzmaHeader::encode_model_properties(LzmaModelProperties const& model_properties)
  63. {
  64. if (model_properties.literal_context_bits > 8)
  65. return Error::from_string_literal("LZMA literal context bits are too large to encode");
  66. if (model_properties.literal_position_bits > 4)
  67. return Error::from_string_literal("LZMA literal position bits are too large to encode");
  68. if (model_properties.position_bits > 4)
  69. return Error::from_string_literal("LZMA position bits are too large to encode");
  70. return (model_properties.position_bits * 5 + model_properties.literal_position_bits) * 9 + model_properties.literal_context_bits;
  71. }
  72. ErrorOr<LzmaDecompressorOptions> LzmaHeader::as_decompressor_options() const
  73. {
  74. auto model_properties = TRY(decode_model_properties(encoded_model_properties));
  75. return Compress::LzmaDecompressorOptions {
  76. .literal_context_bits = model_properties.literal_context_bits,
  77. .literal_position_bits = model_properties.literal_position_bits,
  78. .position_bits = model_properties.position_bits,
  79. .dictionary_size = dictionary_size(),
  80. .uncompressed_size = uncompressed_size(),
  81. .reject_end_of_stream_marker = false,
  82. };
  83. }
  84. ErrorOr<LzmaHeader> LzmaHeader::from_compressor_options(LzmaCompressorOptions const& options)
  85. {
  86. auto encoded_model_properties = TRY(encode_model_properties({
  87. .literal_context_bits = options.literal_context_bits,
  88. .literal_position_bits = options.literal_position_bits,
  89. .position_bits = options.position_bits,
  90. }));
  91. return LzmaHeader {
  92. .encoded_model_properties = encoded_model_properties,
  93. .unchecked_dictionary_size = options.dictionary_size,
  94. .encoded_uncompressed_size = options.uncompressed_size.value_or(placeholder_for_unknown_uncompressed_size),
  95. };
  96. }
  97. void LzmaState::initialize_to_default_probability(Span<Probability> span)
  98. {
  99. for (auto& entry : span)
  100. entry = default_probability;
  101. }
  102. ErrorOr<NonnullOwnPtr<LzmaDecompressor>> LzmaDecompressor::create_from_container(MaybeOwned<Stream> stream, Optional<MaybeOwned<CircularBuffer>> dictionary)
  103. {
  104. auto header = TRY(stream->read_value<LzmaHeader>());
  105. return TRY(LzmaDecompressor::create_from_raw_stream(move(stream), TRY(header.as_decompressor_options()), move(dictionary)));
  106. }
  107. ErrorOr<NonnullOwnPtr<LzmaDecompressor>> LzmaDecompressor::create_from_raw_stream(MaybeOwned<Stream> stream, LzmaDecompressorOptions const& options, Optional<MaybeOwned<CircularBuffer>> dictionary)
  108. {
  109. if (!dictionary.has_value()) {
  110. auto new_dictionary = TRY(CircularBuffer::create_empty(options.dictionary_size));
  111. dictionary = TRY(try_make<CircularBuffer>(move(new_dictionary)));
  112. }
  113. VERIFY((*dictionary)->capacity() >= options.dictionary_size);
  114. // "The LZMA Decoder uses (1 << (lc + lp)) tables with CProb values, where each table contains 0x300 CProb values."
  115. auto literal_probabilities = TRY(FixedArray<Probability>::create(literal_probability_table_size * (1 << (options.literal_context_bits + options.literal_position_bits))));
  116. auto decompressor = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LzmaDecompressor(move(stream), options, dictionary.release_value(), move(literal_probabilities))));
  117. TRY(decompressor->initialize_range_decoder());
  118. return decompressor;
  119. }
  120. LzmaState::LzmaState(FixedArray<Probability> literal_probabilities)
  121. : m_literal_probabilities(move(literal_probabilities))
  122. {
  123. initialize_to_default_probability(m_literal_probabilities.span());
  124. for (auto& array : m_length_to_position_states)
  125. initialize_to_default_probability(array);
  126. for (auto& array : m_binary_tree_distance_probabilities)
  127. initialize_to_default_probability(array);
  128. initialize_to_default_probability(m_alignment_bit_probabilities);
  129. initialize_to_default_probability(m_is_match_probabilities);
  130. initialize_to_default_probability(m_is_rep_probabilities);
  131. initialize_to_default_probability(m_is_rep_g0_probabilities);
  132. initialize_to_default_probability(m_is_rep_g1_probabilities);
  133. initialize_to_default_probability(m_is_rep_g2_probabilities);
  134. initialize_to_default_probability(m_is_rep0_long_probabilities);
  135. }
  136. LzmaDecompressor::LzmaDecompressor(MaybeOwned<Stream> stream, LzmaDecompressorOptions options, MaybeOwned<CircularBuffer> dictionary, FixedArray<Probability> literal_probabilities)
  137. : LzmaState(move(literal_probabilities))
  138. , m_stream(move(stream))
  139. , m_options(move(options))
  140. , m_dictionary(move(dictionary))
  141. {
  142. }
  143. bool LzmaDecompressor::is_range_decoder_in_clean_state() const
  144. {
  145. return m_range_decoder_code == 0;
  146. }
  147. bool LzmaDecompressor::has_reached_expected_data_size() const
  148. {
  149. if (!m_options.uncompressed_size.has_value())
  150. return false;
  151. return m_total_processed_bytes >= m_options.uncompressed_size.value();
  152. }
  153. ErrorOr<void> LzmaDecompressor::initialize_range_decoder()
  154. {
  155. // "The LZMA Encoder always writes ZERO in initial byte of compressed stream.
  156. // That scheme allows to simplify the code of the Range Encoder in the
  157. // LZMA Encoder. If initial byte is not equal to ZERO, the LZMA Decoder must
  158. // stop decoding and report error."
  159. {
  160. auto byte = TRY(m_stream->read_value<u8>());
  161. if (byte != 0)
  162. return Error::from_string_literal("Initial byte of data stream is not zero");
  163. }
  164. // Read the initial bytes into the range decoder.
  165. m_range_decoder_code = 0;
  166. for (size_t i = 0; i < 4; i++) {
  167. auto byte = TRY(m_stream->read_value<u8>());
  168. m_range_decoder_code = m_range_decoder_code << 8 | byte;
  169. }
  170. m_range_decoder_range = 0xFFFFFFFF;
  171. return {};
  172. }
  173. ErrorOr<void> LzmaDecompressor::append_input_stream(MaybeOwned<Stream> stream, Optional<u64> uncompressed_size)
  174. {
  175. m_stream = move(stream);
  176. TRY(initialize_range_decoder());
  177. if (m_options.uncompressed_size.has_value() != uncompressed_size.has_value())
  178. return Error::from_string_literal("Appending LZMA streams with mismatching uncompressed size status");
  179. if (uncompressed_size.has_value())
  180. *m_options.uncompressed_size += *uncompressed_size;
  181. return {};
  182. }
  183. ErrorOr<void> LzmaDecompressor::normalize_range_decoder()
  184. {
  185. // "The Normalize() function keeps the "Range" value in described range."
  186. if (m_range_decoder_range >= minimum_range_value)
  187. return {};
  188. m_range_decoder_range <<= 8;
  189. m_range_decoder_code <<= 8;
  190. m_range_decoder_code |= TRY(m_stream->read_value<u8>());
  191. VERIFY(m_range_decoder_range >= minimum_range_value);
  192. return {};
  193. }
  194. ErrorOr<void> LzmaCompressor::shift_range_encoder()
  195. {
  196. if ((m_range_encoder_code >> 32) == 0x01) {
  197. // If there is an overflow, we can finalize the chain we were previously building.
  198. // This includes incrementing both the cached byte and all the 0xFF bytes that we generate.
  199. VERIFY(m_range_encoder_cached_byte != 0xFF);
  200. TRY(m_stream->write_value<u8>(m_range_encoder_cached_byte + 1));
  201. for (size_t i = 0; i < m_range_encoder_ff_chain_length; i++)
  202. TRY(m_stream->write_value<u8>(0x00));
  203. m_range_encoder_ff_chain_length = 0;
  204. m_range_encoder_cached_byte = (m_range_encoder_code >> 24);
  205. } else if ((m_range_encoder_code >> 24) == 0xFF) {
  206. // If the byte to flush is 0xFF, it can potentially propagate an overflow and needs to be added to the chain.
  207. m_range_encoder_ff_chain_length++;
  208. } else {
  209. // If the byte to flush isn't 0xFF, any future overflows will not be propagated beyond this point,
  210. // so we can be sure that the built chain doesn't change anymore.
  211. TRY(m_stream->write_value<u8>(m_range_encoder_cached_byte));
  212. for (size_t i = 0; i < m_range_encoder_ff_chain_length; i++)
  213. TRY(m_stream->write_value<u8>(0xFF));
  214. m_range_encoder_ff_chain_length = 0;
  215. m_range_encoder_cached_byte = (m_range_encoder_code >> 24);
  216. }
  217. // In all three cases we now recorded the highest byte in some way, so we can shift it away and shift in a null byte as the lowest byte.
  218. m_range_encoder_range <<= 8;
  219. m_range_encoder_code <<= 8;
  220. // Since we are working with a 64-bit code, we need to limit it to 32 bits artificially.
  221. m_range_encoder_code &= 0xFFFFFFFF;
  222. return {};
  223. }
  224. ErrorOr<void> LzmaCompressor::normalize_range_encoder()
  225. {
  226. u64 const maximum_range_value = m_range_encoder_code + m_range_encoder_range;
  227. // Logically, we should only ever build up an overflow that is smaller than or equal to 0x01.
  228. VERIFY((maximum_range_value >> 32) <= 0x01);
  229. if (m_range_encoder_range >= minimum_range_value)
  230. return {};
  231. TRY(shift_range_encoder());
  232. VERIFY(m_range_encoder_range >= minimum_range_value);
  233. return {};
  234. }
  235. ErrorOr<u8> LzmaDecompressor::decode_direct_bit()
  236. {
  237. dbgln_if(LZMA_DEBUG, "Decoding direct bit {} with code = {:#x}, range = {:#x}", 1 - ((m_range_decoder_code - (m_range_decoder_range >> 1)) >> 31), m_range_decoder_code, m_range_decoder_range);
  238. m_range_decoder_range >>= 1;
  239. m_range_decoder_code -= m_range_decoder_range;
  240. u32 temp = 0 - (m_range_decoder_code >> 31);
  241. m_range_decoder_code += m_range_decoder_range & temp;
  242. if (m_range_decoder_code == m_range_decoder_range)
  243. return Error::from_string_literal("Reached an invalid state while decoding LZMA stream");
  244. TRY(normalize_range_decoder());
  245. return temp + 1;
  246. }
  247. ErrorOr<void> LzmaCompressor::encode_direct_bit(u8 value)
  248. {
  249. dbgln_if(LZMA_DEBUG, "Encoding direct bit {} with code = {:#x}, range = {:#x}", value, m_range_encoder_code, m_range_encoder_range);
  250. m_range_encoder_range >>= 1;
  251. if (value != 0)
  252. m_range_encoder_code += m_range_encoder_range;
  253. TRY(normalize_range_encoder());
  254. return {};
  255. }
  256. ErrorOr<u8> LzmaDecompressor::decode_bit_with_probability(Probability& probability)
  257. {
  258. // "The LZMA decoder provides the pointer to CProb variable that contains
  259. // information about estimated probability for symbol 0 and the Range Decoder
  260. // updates that CProb variable after decoding."
  261. u32 bound = (m_range_decoder_range >> probability_bit_count) * probability;
  262. dbgln_if(LZMA_DEBUG, "Decoding bit {} with probability = {:#x}, bound = {:#x}, code = {:#x}, range = {:#x}", m_range_decoder_code < bound ? 0 : 1, probability, bound, m_range_decoder_code, m_range_decoder_range);
  263. if (m_range_decoder_code < bound) {
  264. probability += ((1 << probability_bit_count) - probability) >> probability_shift_width;
  265. m_range_decoder_range = bound;
  266. TRY(normalize_range_decoder());
  267. return 0;
  268. } else {
  269. probability -= probability >> probability_shift_width;
  270. m_range_decoder_code -= bound;
  271. m_range_decoder_range -= bound;
  272. TRY(normalize_range_decoder());
  273. return 1;
  274. }
  275. }
  276. ErrorOr<void> LzmaCompressor::encode_bit_with_probability(Probability& probability, u8 value)
  277. {
  278. u32 bound = (m_range_encoder_range >> probability_bit_count) * probability;
  279. dbgln_if(LZMA_DEBUG, "Encoding bit {} with probability = {:#x}, bound = {:#x}, code = {:#x}, range = {:#x}", value, probability, bound, m_range_encoder_code, m_range_encoder_range);
  280. if (value == 0) {
  281. probability += ((1 << probability_bit_count) - probability) >> probability_shift_width;
  282. m_range_encoder_range = bound;
  283. } else {
  284. probability -= probability >> probability_shift_width;
  285. m_range_encoder_code += bound;
  286. m_range_encoder_range -= bound;
  287. }
  288. TRY(normalize_range_encoder());
  289. return {};
  290. }
  291. ErrorOr<u16> LzmaDecompressor::decode_symbol_using_bit_tree(size_t bit_count, Span<Probability> probability_tree)
  292. {
  293. VERIFY(bit_count <= sizeof(u16) * 8);
  294. VERIFY(probability_tree.size() >= 1ul << bit_count);
  295. // This has been modified from the reference implementation to unlink the result and the tree index,
  296. // which should allow for better readability.
  297. u16 result = 0;
  298. size_t tree_index = 1;
  299. for (size_t i = 0; i < bit_count; i++) {
  300. u16 next_bit = TRY(decode_bit_with_probability(probability_tree[tree_index]));
  301. result = (result << 1) | next_bit;
  302. tree_index = (tree_index << 1) | next_bit;
  303. }
  304. dbgln_if(LZMA_DEBUG, "Decoded value {:#x} with {} bits using bit tree", result, bit_count);
  305. return result;
  306. }
  307. ErrorOr<void> LzmaCompressor::encode_symbol_using_bit_tree(size_t bit_count, Span<Probability> probability_tree, u16 value)
  308. {
  309. VERIFY(bit_count <= sizeof(u16) * 8);
  310. VERIFY(probability_tree.size() >= 1ul << bit_count);
  311. VERIFY(value <= (1 << bit_count) - 1);
  312. auto original_value = value;
  313. // Shift value to make the first sent byte the most significant bit. This makes the shifting logic a lot easier to read.
  314. value <<= sizeof(u16) * 8 - bit_count;
  315. size_t tree_index = 1;
  316. for (size_t i = 0; i < bit_count; i++) {
  317. u8 const next_bit = (value & 0x8000) >> (sizeof(u16) * 8 - 1);
  318. value <<= 1;
  319. TRY(encode_bit_with_probability(probability_tree[tree_index], next_bit));
  320. tree_index = (tree_index << 1) | next_bit;
  321. }
  322. dbgln_if(LZMA_DEBUG, "Encoded value {:#x} with {} bits using bit tree", original_value, bit_count);
  323. return {};
  324. }
  325. ErrorOr<u16> LzmaDecompressor::decode_symbol_using_reverse_bit_tree(size_t bit_count, Span<Probability> probability_tree)
  326. {
  327. VERIFY(bit_count <= sizeof(u16) * 8);
  328. VERIFY(probability_tree.size() >= 1ul << bit_count);
  329. u16 result = 0;
  330. size_t tree_index = 1;
  331. for (size_t i = 0; i < bit_count; i++) {
  332. u16 next_bit = TRY(decode_bit_with_probability(probability_tree[tree_index]));
  333. result |= next_bit << i;
  334. tree_index = (tree_index << 1) | next_bit;
  335. }
  336. dbgln_if(LZMA_DEBUG, "Decoded value {:#x} with {} bits using reverse bit tree", result, bit_count);
  337. return result;
  338. }
  339. ErrorOr<void> LzmaCompressor::encode_symbol_using_reverse_bit_tree(size_t bit_count, Span<Probability> probability_tree, u16 value)
  340. {
  341. VERIFY(bit_count <= sizeof(u16) * 8);
  342. VERIFY(probability_tree.size() >= 1ul << bit_count);
  343. VERIFY(value <= (1 << bit_count) - 1);
  344. auto original_value = value;
  345. size_t tree_index = 1;
  346. for (size_t i = 0; i < bit_count; i++) {
  347. u8 const next_bit = value & 1;
  348. value >>= 1;
  349. TRY(encode_bit_with_probability(probability_tree[tree_index], next_bit));
  350. tree_index = (tree_index << 1) | next_bit;
  351. }
  352. dbgln_if(LZMA_DEBUG, "Encoded value {:#x} with {} bits using reverse bit tree", original_value, bit_count);
  353. return {};
  354. }
  355. ErrorOr<void> LzmaDecompressor::decode_literal_to_output_buffer()
  356. {
  357. u8 previous_byte = 0;
  358. if (m_dictionary->seekback_limit() > 0) {
  359. auto read_bytes = MUST(m_dictionary->read_with_seekback({ &previous_byte, sizeof(previous_byte) }, 1));
  360. VERIFY(read_bytes.size() == sizeof(previous_byte));
  361. }
  362. // "To select the table for decoding it uses the context that consists of
  363. // (lc) high bits from previous literal and (lp) low bits from value that
  364. // represents current position in outputStream."
  365. u16 literal_state_bits_from_position = m_total_processed_bytes & ((1 << m_options.literal_position_bits) - 1);
  366. u16 literal_state_bits_from_output = previous_byte >> (8 - m_options.literal_context_bits);
  367. u16 literal_state = literal_state_bits_from_position << m_options.literal_context_bits | literal_state_bits_from_output;
  368. Span<Probability> selected_probability_table = m_literal_probabilities.span().slice(literal_probability_table_size * literal_state, literal_probability_table_size);
  369. // The result is defined as u16 here and initialized to 1, but we will cut off the top bits before queueing them into the output buffer.
  370. // The top bit is only used to track how much we have decoded already, and to select the correct probability table.
  371. u16 result = 1;
  372. // "If (State > 7), the Literal Decoder also uses "matchByte" that represents
  373. // the byte in OutputStream at position the is the DISTANCE bytes before
  374. // current position, where the DISTANCE is the distance in DISTANCE-LENGTH pair
  375. // of latest decoded match."
  376. // Note: The specification says `(State > 7)`, but the reference implementation does `(State >= 7)`, which is a mismatch.
  377. // Testing `(State > 7)` with actual test files yields errors, so the reference implementation appears to be the correct one.
  378. if (m_state >= 7) {
  379. u8 matched_byte = 0;
  380. auto read_bytes = TRY(m_dictionary->read_with_seekback({ &matched_byte, sizeof(matched_byte) }, current_repetition_offset()));
  381. VERIFY(read_bytes.size() == sizeof(matched_byte));
  382. dbgln_if(LZMA_DEBUG, "Decoding literal using match byte {:#x}", matched_byte);
  383. do {
  384. u8 match_bit = (matched_byte >> 7) & 1;
  385. matched_byte <<= 1;
  386. u8 decoded_bit = TRY(decode_bit_with_probability(selected_probability_table[((1 + match_bit) << 8) + result]));
  387. result = result << 1 | decoded_bit;
  388. if (match_bit != decoded_bit)
  389. break;
  390. } while (result < 0x100);
  391. }
  392. while (result < 0x100)
  393. result = (result << 1) | TRY(decode_bit_with_probability(selected_probability_table[result]));
  394. u8 actual_result = result - 0x100;
  395. size_t written_bytes = m_dictionary->write({ &actual_result, sizeof(actual_result) });
  396. VERIFY(written_bytes == sizeof(actual_result));
  397. m_total_processed_bytes += sizeof(actual_result);
  398. dbgln_if(LZMA_DEBUG, "Decoded literal {:#x} in state {} using literal state {:#x} (previous byte is {:#x})", actual_result, m_state, literal_state, previous_byte);
  399. return {};
  400. }
  401. ErrorOr<void> LzmaCompressor::encode_literal(u8 literal)
  402. {
  403. // This function largely mirrors `decode_literal_to_output_buffer`, so specification comments have been omitted.
  404. TRY(encode_match_type(MatchType::Literal));
  405. // Note: We have already read the next byte from the input buffer, so it's now in the seekback buffer, shifting all seekback offsets by one.
  406. u8 previous_byte = 0;
  407. if (m_dictionary->seekback_limit() - m_dictionary->used_space() > 1) {
  408. auto read_bytes = MUST(m_dictionary->read_with_seekback({ &previous_byte, sizeof(previous_byte) }, 2 + m_dictionary->used_space()));
  409. VERIFY(read_bytes.size() == sizeof(previous_byte));
  410. }
  411. u16 const literal_state_bits_from_position = m_total_processed_bytes & ((1 << m_options.literal_position_bits) - 1);
  412. u16 const literal_state_bits_from_output = previous_byte >> (8 - m_options.literal_context_bits);
  413. u16 const literal_state = literal_state_bits_from_position << m_options.literal_context_bits | literal_state_bits_from_output;
  414. Span<Probability> selected_probability_table = m_literal_probabilities.span().slice(literal_probability_table_size * literal_state, literal_probability_table_size);
  415. auto original_literal = literal;
  416. u16 result = 1;
  417. if (m_state >= 7) {
  418. u8 matched_byte = 0;
  419. auto read_bytes = TRY(m_dictionary->read_with_seekback({ &matched_byte, sizeof(matched_byte) }, current_repetition_offset() + m_dictionary->used_space() + 1));
  420. VERIFY(read_bytes.size() == sizeof(matched_byte));
  421. dbgln_if(LZMA_DEBUG, "Encoding literal using match byte {:#x}", matched_byte);
  422. do {
  423. u8 const match_bit = (matched_byte >> 7) & 1;
  424. matched_byte <<= 1;
  425. u8 const encoded_bit = (literal & 0x80) >> 7;
  426. literal <<= 1;
  427. TRY(encode_bit_with_probability(selected_probability_table[((1 + match_bit) << 8) + result], encoded_bit));
  428. result = result << 1 | encoded_bit;
  429. if (match_bit != encoded_bit)
  430. break;
  431. } while (result < 0x100);
  432. }
  433. while (result < 0x100) {
  434. u8 const encoded_bit = (literal & 0x80) >> 7;
  435. literal <<= 1;
  436. TRY(encode_bit_with_probability(selected_probability_table[result], encoded_bit));
  437. result = (result << 1) | encoded_bit;
  438. }
  439. m_total_processed_bytes += sizeof(literal);
  440. dbgln_if(LZMA_DEBUG, "Encoded literal {:#x} in state {} using literal state {:#x} (previous byte is {:#x})", original_literal, m_state, literal_state, previous_byte);
  441. update_state_after_literal();
  442. return {};
  443. }
  444. ErrorOr<void> LzmaCompressor::encode_existing_match(size_t real_distance, size_t real_length)
  445. {
  446. VERIFY(real_distance >= normalized_to_real_match_distance_offset);
  447. u32 const normalized_distance = real_distance - normalized_to_real_match_distance_offset;
  448. VERIFY(real_length >= normalized_to_real_match_length_offset);
  449. u16 const normalized_length = real_length - normalized_to_real_match_length_offset;
  450. if (normalized_distance == m_rep0) {
  451. TRY(encode_match_type(MatchType::RepMatch0));
  452. } else if (normalized_distance == m_rep1) {
  453. TRY(encode_match_type(MatchType::RepMatch1));
  454. u32 const distance = m_rep1;
  455. m_rep1 = m_rep0;
  456. m_rep0 = distance;
  457. } else if (normalized_distance == m_rep2) {
  458. TRY(encode_match_type(MatchType::RepMatch2));
  459. u32 const distance = m_rep2;
  460. m_rep2 = m_rep1;
  461. m_rep1 = m_rep0;
  462. m_rep0 = distance;
  463. } else if (normalized_distance == m_rep3) {
  464. TRY(encode_match_type(MatchType::RepMatch3));
  465. u32 const distance = m_rep3;
  466. m_rep3 = m_rep2;
  467. m_rep2 = m_rep1;
  468. m_rep1 = m_rep0;
  469. m_rep0 = distance;
  470. } else {
  471. VERIFY_NOT_REACHED();
  472. }
  473. TRY(encode_normalized_match_length(m_rep_length_coder, normalized_length));
  474. update_state_after_rep();
  475. MUST(m_dictionary->discard(real_length));
  476. m_total_processed_bytes += real_length;
  477. return {};
  478. }
  479. ErrorOr<void> LzmaCompressor::encode_new_match(size_t real_distance, size_t real_length)
  480. {
  481. VERIFY(real_distance >= normalized_to_real_match_distance_offset);
  482. u32 const normalized_distance = real_distance - normalized_to_real_match_distance_offset;
  483. VERIFY(real_length >= normalized_to_real_match_length_offset);
  484. u16 const normalized_length = real_length - normalized_to_real_match_length_offset;
  485. TRY(encode_normalized_simple_match(normalized_distance, normalized_length));
  486. MUST(m_dictionary->discard(real_length));
  487. m_total_processed_bytes += real_length;
  488. return {};
  489. }
  490. ErrorOr<void> LzmaCompressor::encode_normalized_simple_match(u32 normalized_distance, u16 normalized_length)
  491. {
  492. TRY(encode_match_type(MatchType::SimpleMatch));
  493. m_rep3 = m_rep2;
  494. m_rep2 = m_rep1;
  495. m_rep1 = m_rep0;
  496. TRY(encode_normalized_match_length(m_length_coder, normalized_length));
  497. update_state_after_match();
  498. TRY(encode_normalized_match_distance(normalized_length, normalized_distance));
  499. m_rep0 = normalized_distance;
  500. return {};
  501. }
  502. LzmaState::LzmaLengthCoderState::LzmaLengthCoderState()
  503. {
  504. for (auto& array : m_low_length_probabilities)
  505. initialize_to_default_probability(array);
  506. for (auto& array : m_medium_length_probabilities)
  507. initialize_to_default_probability(array);
  508. initialize_to_default_probability(m_high_length_probabilities);
  509. }
  510. ErrorOr<u16> LzmaDecompressor::decode_normalized_match_length(LzmaLengthCoderState& length_decoder_state)
  511. {
  512. // "LZMA uses "posState" value as context to select the binary tree
  513. // from LowCoder and MidCoder binary tree arrays:"
  514. u16 position_state = m_total_processed_bytes & ((1 << m_options.position_bits) - 1);
  515. // "The following scheme is used for the match length encoding:
  516. //
  517. // Binary encoding Binary Tree structure Zero-based match length
  518. // sequence (binary + decimal):
  519. //
  520. // 0 xxx LowCoder[posState] xxx
  521. if (TRY(decode_bit_with_probability(length_decoder_state.m_first_choice_probability)) == 0)
  522. return TRY(decode_symbol_using_bit_tree(3, length_decoder_state.m_low_length_probabilities[position_state].span()));
  523. // 1 0 yyy MidCoder[posState] yyy + 8
  524. if (TRY(decode_bit_with_probability(length_decoder_state.m_second_choice_probability)) == 0)
  525. return TRY(decode_symbol_using_bit_tree(3, length_decoder_state.m_medium_length_probabilities[position_state].span())) + 8;
  526. // 1 1 zzzzzzzz HighCoder zzzzzzzz + 16"
  527. return TRY(decode_symbol_using_bit_tree(8, length_decoder_state.m_high_length_probabilities.span())) + 16;
  528. }
  529. ErrorOr<void> LzmaCompressor::encode_normalized_match_length(LzmaLengthCoderState& length_coder_state, u16 normalized_length)
  530. {
  531. u16 const position_state = m_total_processed_bytes & ((1 << m_options.position_bits) - 1);
  532. if (normalized_length < 8) {
  533. TRY(encode_bit_with_probability(length_coder_state.m_first_choice_probability, 0));
  534. TRY(encode_symbol_using_bit_tree(3, length_coder_state.m_low_length_probabilities[position_state].span(), normalized_length));
  535. return {};
  536. }
  537. TRY(encode_bit_with_probability(length_coder_state.m_first_choice_probability, 1));
  538. if (normalized_length < 16) {
  539. TRY(encode_bit_with_probability(length_coder_state.m_second_choice_probability, 0));
  540. TRY(encode_symbol_using_bit_tree(3, length_coder_state.m_medium_length_probabilities[position_state].span(), normalized_length - 8));
  541. return {};
  542. }
  543. TRY(encode_bit_with_probability(length_coder_state.m_second_choice_probability, 1));
  544. TRY(encode_symbol_using_bit_tree(8, length_coder_state.m_high_length_probabilities.span(), normalized_length - 16));
  545. return {};
  546. }
  547. ErrorOr<u32> LzmaDecompressor::decode_normalized_match_distance(u16 normalized_match_length)
  548. {
  549. // "LZMA uses normalized match length (zero-based length)
  550. // to calculate the context state "lenState" do decode the distance value."
  551. u16 length_state = min(normalized_match_length, number_of_length_to_position_states - 1);
  552. // "At first stage the distance decoder decodes 6-bit "posSlot" value with bit
  553. // tree decoder from PosSlotDecoder array."
  554. u16 position_slot = TRY(decode_symbol_using_bit_tree(6, m_length_to_position_states[length_state].span()));
  555. // "The encoding scheme for distance value is shown in the following table:
  556. //
  557. // posSlot (decimal) /
  558. // zero-based distance (binary)
  559. // 0 0
  560. // 1 1
  561. // 2 10
  562. // 3 11
  563. //
  564. // 4 10 x
  565. // 5 11 x
  566. // 6 10 xx
  567. // 7 11 xx
  568. // 8 10 xxx
  569. // 9 11 xxx
  570. // 10 10 xxxx
  571. // 11 11 xxxx
  572. // 12 10 xxxxx
  573. // 13 11 xxxxx
  574. //
  575. // 14 10 yy zzzz
  576. // 15 11 yy zzzz
  577. // 16 10 yyy zzzz
  578. // 17 11 yyy zzzz
  579. // ...
  580. // 62 10 yyyyyyyyyyyyyyyyyyyyyyyyyy zzzz
  581. // 63 11 yyyyyyyyyyyyyyyyyyyyyyyyyy zzzz
  582. //
  583. // where
  584. // "x ... x" means the sequence of binary symbols encoded with binary tree and
  585. // "Reverse" scheme. It uses separated binary tree for each posSlot from 4 to 13.
  586. // "y" means direct bit encoded with range coder.
  587. // "zzzz" means the sequence of four binary symbols encoded with binary
  588. // tree with "Reverse" scheme, where one common binary tree "AlignDecoder"
  589. // is used for all posSlot values."
  590. // "If (posSlot < 4), the "dist" value is equal to posSlot value."
  591. if (position_slot < first_position_slot_with_binary_tree_bits)
  592. return position_slot;
  593. // From here on, the first bit of the distance is always set and the second bit is set if the last bit of the position slot is set.
  594. u32 distance_prefix = ((1 << 1) | ((position_slot & 1) << 0));
  595. // "If (posSlot >= 4), the decoder uses "posSlot" value to calculate the value of
  596. // the high bits of "dist" value and the number of the low bits.
  597. // If (4 <= posSlot < kEndPosModelIndex), the decoder uses bit tree decoders.
  598. // (one separated bit tree decoder per one posSlot value) and "Reverse" scheme."
  599. if (position_slot < first_position_slot_with_direct_encoded_bits) {
  600. size_t number_of_bits_to_decode = (position_slot / 2) - 1;
  601. auto& selected_probability_tree = m_binary_tree_distance_probabilities[position_slot - first_position_slot_with_binary_tree_bits];
  602. return (distance_prefix << number_of_bits_to_decode) | TRY(decode_symbol_using_reverse_bit_tree(number_of_bits_to_decode, selected_probability_tree));
  603. }
  604. // " if (posSlot >= kEndPosModelIndex), the middle bits are decoded as direct
  605. // bits from RangeDecoder and the low 4 bits are decoded with a bit tree
  606. // decoder "AlignDecoder" with "Reverse" scheme."
  607. size_t number_of_direct_bits_to_decode = ((position_slot - first_position_slot_with_direct_encoded_bits) / 2) + 2;
  608. for (size_t i = 0; i < number_of_direct_bits_to_decode; i++) {
  609. distance_prefix = (distance_prefix << 1) | TRY(decode_direct_bit());
  610. }
  611. return (distance_prefix << number_of_alignment_bits) | TRY(decode_symbol_using_reverse_bit_tree(number_of_alignment_bits, m_alignment_bit_probabilities));
  612. }
  613. ErrorOr<void> LzmaCompressor::encode_normalized_match_distance(u16 normalized_match_length, u32 normalized_match_distance)
  614. {
  615. u16 const length_state = min(normalized_match_length, number_of_length_to_position_states - 1);
  616. if (normalized_match_distance < first_position_slot_with_binary_tree_bits) {
  617. // The normalized distance gets encoded as the position slot.
  618. TRY(encode_symbol_using_bit_tree(6, m_length_to_position_states[length_state].span(), normalized_match_distance));
  619. return {};
  620. }
  621. // Note: This has been deduced, there is no immediate relation to the decoding function.
  622. u16 const distance_log2 = AK::log2(normalized_match_distance);
  623. u16 number_of_distance_bits = count_required_bits(normalized_match_distance);
  624. u16 const position_slot = (distance_log2 << 1) + ((normalized_match_distance >> (distance_log2 - 1)) & 1);
  625. TRY(encode_symbol_using_bit_tree(6, m_length_to_position_states[length_state].span(), position_slot));
  626. // Mask off the top two bits of the value, those are already encoded by the position slot.
  627. normalized_match_distance &= (1 << (number_of_distance_bits - 2)) - 1;
  628. number_of_distance_bits -= 2;
  629. if (position_slot < first_position_slot_with_direct_encoded_bits) {
  630. // The value gets encoded using only a reverse bit tree coder.
  631. auto& selected_probability_tree = m_binary_tree_distance_probabilities[position_slot - first_position_slot_with_binary_tree_bits];
  632. TRY(encode_symbol_using_reverse_bit_tree(number_of_distance_bits, selected_probability_tree, normalized_match_distance));
  633. return {};
  634. }
  635. // The value is split into direct bits (everything except the last four bits) and alignment bits (last four bits).
  636. auto direct_bits = normalized_match_distance & ~((1 << number_of_alignment_bits) - 1);
  637. auto const alignment_bits = normalized_match_distance & ((1 << number_of_alignment_bits) - 1);
  638. // Shift to-be-written direct bits to the most significant position for easier access.
  639. direct_bits <<= sizeof(direct_bits) * 8 - number_of_distance_bits;
  640. for (auto i = 0u; i < number_of_distance_bits - number_of_alignment_bits; i++) {
  641. TRY(encode_direct_bit((direct_bits & 0x80000000) ? 1 : 0));
  642. direct_bits <<= 1;
  643. }
  644. TRY(encode_symbol_using_reverse_bit_tree(number_of_alignment_bits, m_alignment_bit_probabilities, alignment_bits));
  645. return {};
  646. }
  647. u32 LzmaState::current_repetition_offset() const
  648. {
  649. // LZMA never needs to read at offset 0 (i.e. the actual read head of the buffer).
  650. // Instead, the values are remapped so that the rep-value n starts reading n + 1 bytes back.
  651. // The special rep-value 0xFFFFFFFF is reserved for marking the end of the stream,
  652. // so this should never overflow.
  653. VERIFY(m_rep0 <= NumericLimits<u32>::max() - normalized_to_real_match_distance_offset);
  654. return m_rep0 + normalized_to_real_match_distance_offset;
  655. }
  656. void LzmaState::update_state_after_literal()
  657. {
  658. if (m_state < 4)
  659. m_state = 0;
  660. else if (m_state < 10)
  661. m_state -= 3;
  662. else
  663. m_state -= 6;
  664. }
  665. void LzmaState::update_state_after_match()
  666. {
  667. if (m_state < 7)
  668. m_state = 7;
  669. else
  670. m_state = 10;
  671. }
  672. void LzmaState::update_state_after_rep()
  673. {
  674. if (m_state < 7)
  675. m_state = 8;
  676. else
  677. m_state = 11;
  678. }
  679. void LzmaState::update_state_after_short_rep()
  680. {
  681. if (m_state < 7)
  682. m_state = 9;
  683. else
  684. m_state = 11;
  685. }
  686. ErrorOr<LzmaDecompressor::MatchType> LzmaDecompressor::decode_match_type()
  687. {
  688. // "The decoder calculates "state2" variable value to select exact variable from
  689. // "IsMatch" and "IsRep0Long" arrays."
  690. u16 position_state = m_total_processed_bytes & ((1 << m_options.position_bits) - 1);
  691. u16 state2 = (m_state << maximum_number_of_position_bits) + position_state;
  692. // "The decoder uses the following code flow scheme to select exact
  693. // type of LITERAL or MATCH:
  694. //
  695. // IsMatch[state2] decode
  696. // 0 - the Literal"
  697. if (TRY(decode_bit_with_probability(m_is_match_probabilities[state2])) == 0) {
  698. dbgln_if(LZMA_DEBUG, "Decoded match type 'Literal'");
  699. return MatchType::Literal;
  700. }
  701. // " 1 - the Match
  702. // IsRep[state] decode
  703. // 0 - Simple Match"
  704. if (TRY(decode_bit_with_probability(m_is_rep_probabilities[m_state])) == 0) {
  705. dbgln_if(LZMA_DEBUG, "Decoded match type 'SimpleMatch'");
  706. return MatchType::SimpleMatch;
  707. }
  708. // " 1 - Rep Match
  709. // IsRepG0[state] decode
  710. // 0 - the distance is rep0"
  711. if (TRY(decode_bit_with_probability(m_is_rep_g0_probabilities[m_state])) == 0) {
  712. // " IsRep0Long[state2] decode
  713. // 0 - Short Rep Match"
  714. if (TRY(decode_bit_with_probability(m_is_rep0_long_probabilities[state2])) == 0) {
  715. dbgln_if(LZMA_DEBUG, "Decoded match type 'ShortRepMatch'");
  716. return MatchType::ShortRepMatch;
  717. }
  718. // " 1 - Rep Match 0"
  719. dbgln_if(LZMA_DEBUG, "Decoded match type 'RepMatch0'");
  720. return MatchType::RepMatch0;
  721. }
  722. // " 1 -
  723. // IsRepG1[state] decode
  724. // 0 - Rep Match 1"
  725. if (TRY(decode_bit_with_probability(m_is_rep_g1_probabilities[m_state])) == 0) {
  726. dbgln_if(LZMA_DEBUG, "Decoded match type 'RepMatch1'");
  727. return MatchType::RepMatch1;
  728. }
  729. // " 1 -
  730. // IsRepG2[state] decode
  731. // 0 - Rep Match 2"
  732. if (TRY(decode_bit_with_probability(m_is_rep_g2_probabilities[m_state])) == 0) {
  733. dbgln_if(LZMA_DEBUG, "Decoded match type 'RepMatch2'");
  734. return MatchType::RepMatch2;
  735. }
  736. // " 1 - Rep Match 3"
  737. dbgln_if(LZMA_DEBUG, "Decoded match type 'RepMatch3'");
  738. return MatchType::RepMatch3;
  739. }
  740. ErrorOr<void> LzmaCompressor::encode_match_type(MatchType match_type)
  741. {
  742. u16 position_state = m_total_processed_bytes & ((1 << m_options.position_bits) - 1);
  743. u16 state2 = (m_state << maximum_number_of_position_bits) + position_state;
  744. if (match_type == MatchType::Literal) {
  745. TRY(encode_bit_with_probability(m_is_match_probabilities[state2], 0));
  746. dbgln_if(LZMA_DEBUG, "Encoded match type 'Literal'");
  747. return {};
  748. }
  749. TRY(encode_bit_with_probability(m_is_match_probabilities[state2], 1));
  750. if (match_type == MatchType::SimpleMatch) {
  751. TRY(encode_bit_with_probability(m_is_rep_probabilities[m_state], 0));
  752. dbgln_if(LZMA_DEBUG, "Encoded match type 'SimpleMatch'");
  753. return {};
  754. }
  755. TRY(encode_bit_with_probability(m_is_rep_probabilities[m_state], 1));
  756. if (match_type == MatchType::ShortRepMatch || match_type == MatchType::RepMatch0) {
  757. TRY(encode_bit_with_probability(m_is_rep_g0_probabilities[m_state], 0));
  758. TRY(encode_bit_with_probability(m_is_rep0_long_probabilities[state2], match_type == MatchType::RepMatch0));
  759. if constexpr (LZMA_DEBUG) {
  760. if (match_type == RepMatch0)
  761. dbgln("Encoded match type 'RepMatch0'");
  762. else
  763. dbgln("Encoded match type 'ShortRepMatch'");
  764. }
  765. return {};
  766. }
  767. TRY(encode_bit_with_probability(m_is_rep_g0_probabilities[m_state], 1));
  768. if (match_type == MatchType::RepMatch1) {
  769. TRY(encode_bit_with_probability(m_is_rep_g1_probabilities[m_state], 0));
  770. dbgln_if(LZMA_DEBUG, "Encoded match type 'RepMatch1'");
  771. return {};
  772. }
  773. TRY(encode_bit_with_probability(m_is_rep_g1_probabilities[m_state], 1));
  774. if (match_type == MatchType::RepMatch2) {
  775. TRY(encode_bit_with_probability(m_is_rep_g2_probabilities[m_state], 0));
  776. dbgln_if(LZMA_DEBUG, "Encoded match type 'RepMatch2'");
  777. return {};
  778. }
  779. TRY(encode_bit_with_probability(m_is_rep_g2_probabilities[m_state], 1));
  780. dbgln_if(LZMA_DEBUG, "Encoded match type 'RepMatch3'");
  781. return {};
  782. }
  783. ErrorOr<void> LzmaCompressor::encode_once()
  784. {
  785. // Check if any of our existing match distances are currently usable.
  786. Vector<size_t> const existing_distances {
  787. m_rep0 + normalized_to_real_match_distance_offset,
  788. m_rep1 + normalized_to_real_match_distance_offset,
  789. m_rep2 + normalized_to_real_match_distance_offset,
  790. m_rep3 + normalized_to_real_match_distance_offset,
  791. };
  792. auto existing_distance_result = m_dictionary->find_copy_in_seekback(existing_distances, m_dictionary->used_space(), normalized_to_real_match_length_offset);
  793. if (existing_distance_result.has_value()) {
  794. auto selected_match = existing_distance_result.release_value();
  795. TRY(encode_existing_match(selected_match.distance, selected_match.length));
  796. return {};
  797. }
  798. // If we weren't able to find any viable existing offsets, we now have to search the rest of the dictionary for possible new offsets.
  799. auto new_distance_result = m_dictionary->find_copy_in_seekback(m_dictionary->used_space(), normalized_to_real_match_length_offset);
  800. if (new_distance_result.has_value()) {
  801. auto selected_match = new_distance_result.release_value();
  802. TRY(encode_new_match(selected_match.distance, selected_match.length));
  803. return {};
  804. }
  805. // If we weren't able to find any matches, we don't have any other choice than to encode the next byte as a literal.
  806. u8 next_byte { 0 };
  807. TRY(m_dictionary->read({ &next_byte, sizeof(next_byte) }));
  808. TRY(encode_literal(next_byte));
  809. return {};
  810. }
  811. ErrorOr<Bytes> LzmaDecompressor::read_some(Bytes bytes)
  812. {
  813. while (m_dictionary->used_space() < bytes.size() && m_dictionary->empty_space() != 0) {
  814. if (m_found_end_of_stream_marker)
  815. break;
  816. if (has_reached_expected_data_size()) {
  817. // If the decoder is in a clean state, we assume that this is fine.
  818. if (is_range_decoder_in_clean_state())
  819. break;
  820. // Otherwise, we give it one last try to find the end marker in the remaining data.
  821. }
  822. auto copy_match_to_buffer = [&](u16 real_length) -> ErrorOr<void> {
  823. VERIFY(!m_leftover_match_length.has_value());
  824. if (m_options.uncompressed_size.has_value() && m_options.uncompressed_size.value() < m_total_processed_bytes + real_length)
  825. return Error::from_string_literal("Tried to copy match beyond expected uncompressed file size");
  826. auto copied_length = TRY(m_dictionary->copy_from_seekback(current_repetition_offset(), real_length));
  827. m_total_processed_bytes += copied_length;
  828. real_length -= copied_length;
  829. if (real_length > 0)
  830. m_leftover_match_length = real_length;
  831. return {};
  832. };
  833. // If we have a leftover part of a repeating match, we should finish that first.
  834. if (m_leftover_match_length.has_value()) {
  835. TRY(copy_match_to_buffer(m_leftover_match_length.release_value()));
  836. continue;
  837. }
  838. auto const match_type = TRY(decode_match_type());
  839. // If we are looking for EOS, but find another match type, the stream is also corrupted.
  840. if (has_reached_expected_data_size() && match_type != MatchType::SimpleMatch)
  841. return Error::from_string_literal("First match type after the expected uncompressed size is not a simple match");
  842. if (match_type == MatchType::Literal) {
  843. // "At first the LZMA decoder must check that it doesn't exceed
  844. // specified uncompressed size."
  845. // This is already checked for at the beginning of the loop.
  846. // "Then it decodes literal value and puts it to sliding window."
  847. TRY(decode_literal_to_output_buffer());
  848. // "Then the decoder must update the "state" value."
  849. update_state_after_literal();
  850. continue;
  851. }
  852. if (match_type == MatchType::SimpleMatch) {
  853. // "The distance history table is updated with the following scheme:"
  854. m_rep3 = m_rep2;
  855. m_rep2 = m_rep1;
  856. m_rep1 = m_rep0;
  857. // "The zero-based length is decoded with "LenDecoder"."
  858. u16 normalized_length = TRY(decode_normalized_match_length(m_length_coder));
  859. // "The state is update with UpdateState_Match function."
  860. update_state_after_match();
  861. // "and the new "rep0" value is decoded with DecodeDistance."
  862. m_rep0 = TRY(decode_normalized_match_distance(normalized_length));
  863. // "If the value of "rep0" is equal to 0xFFFFFFFF, it means that we have
  864. // "End of stream" marker, so we can stop decoding and check finishing
  865. // condition in Range Decoder"
  866. if (m_rep0 == end_of_stream_marker) {
  867. // If we should reject end-of-stream markers, do so now.
  868. // Note that this is not part of LZMA, as LZMA allows end-of-stream markers in all contexts, so pure LZMA should never set this option.
  869. if (m_options.reject_end_of_stream_marker)
  870. return Error::from_string_literal("An end-of-stream marker was found, but the LZMA stream is configured to reject them");
  871. // The range decoder condition is checked after breaking out of the loop.
  872. m_found_end_of_stream_marker = true;
  873. continue;
  874. }
  875. // If we are looking for EOS, but haven't found it here, the stream is corrupted.
  876. if (has_reached_expected_data_size())
  877. return Error::from_string_literal("First simple match after the expected uncompressed size is not the EOS marker");
  878. // "If uncompressed size is defined, LZMA decoder must check that it doesn't
  879. // exceed that specified uncompressed size."
  880. // This is being checked for in the common "copy to buffer" implementation.
  881. // "Also the decoder must check that "rep0" value is not larger than dictionary size
  882. // and is not larger than the number of already decoded bytes."
  883. if (current_repetition_offset() > m_dictionary->seekback_limit())
  884. return Error::from_string_literal("rep0 value is larger than the possible lookback size");
  885. // "Then the decoder must copy match bytes as described in
  886. // "The match symbols copying" section."
  887. TRY(copy_match_to_buffer(normalized_length + normalized_to_real_match_length_offset));
  888. continue;
  889. }
  890. if (match_type == MatchType::ShortRepMatch) {
  891. // "LZMA doesn't update the distance history."
  892. // "If the subtype is "Short Rep Match", the decoder updates the state, puts
  893. // the one byte from window to current position in window and goes to next
  894. // MATCH/LITERAL symbol."
  895. update_state_after_short_rep();
  896. TRY(copy_match_to_buffer(1));
  897. continue;
  898. }
  899. // Note: We don't need to do anything specific for "Rep Match 0", we just need to make sure to not
  900. // run the detection for other match types and to not switch around the distance history.
  901. if (match_type == MatchType::RepMatch1) {
  902. u32 distance = m_rep1;
  903. m_rep1 = m_rep0;
  904. m_rep0 = distance;
  905. }
  906. if (match_type == MatchType::RepMatch2) {
  907. u32 distance = m_rep2;
  908. m_rep2 = m_rep1;
  909. m_rep1 = m_rep0;
  910. m_rep0 = distance;
  911. }
  912. if (match_type == MatchType::RepMatch3) {
  913. u32 distance = m_rep3;
  914. m_rep3 = m_rep2;
  915. m_rep2 = m_rep1;
  916. m_rep1 = m_rep0;
  917. m_rep0 = distance;
  918. }
  919. // "In other cases (Rep Match 0/1/2/3), it decodes the zero-based
  920. // length of match with "RepLenDecoder" decoder."
  921. u16 normalized_length = TRY(decode_normalized_match_length(m_rep_length_coder));
  922. // "Then it updates the state."
  923. update_state_after_rep();
  924. // "Then the decoder must copy match bytes as described in
  925. // "The Match symbols copying" section."
  926. TRY(copy_match_to_buffer(normalized_length + normalized_to_real_match_length_offset));
  927. }
  928. if (m_found_end_of_stream_marker || has_reached_expected_data_size()) {
  929. if (m_options.uncompressed_size.has_value() && m_total_processed_bytes < m_options.uncompressed_size.value())
  930. return Error::from_string_literal("Found end-of-stream marker earlier than expected");
  931. if (!is_range_decoder_in_clean_state())
  932. return Error::from_string_literal("LZMA stream ends in an unclean state");
  933. }
  934. return m_dictionary->read(bytes);
  935. }
  936. ErrorOr<size_t> LzmaDecompressor::write_some(ReadonlyBytes)
  937. {
  938. return Error::from_errno(EBADF);
  939. }
  940. bool LzmaDecompressor::is_eof() const
  941. {
  942. if (m_dictionary->used_space() > 0)
  943. return false;
  944. if (has_reached_expected_data_size())
  945. return true;
  946. return m_found_end_of_stream_marker;
  947. }
  948. bool LzmaDecompressor::is_open() const
  949. {
  950. return true;
  951. }
  952. void LzmaDecompressor::close()
  953. {
  954. }
  955. ErrorOr<NonnullOwnPtr<LzmaCompressor>> LzmaCompressor::create_container(MaybeOwned<Stream> stream, LzmaCompressorOptions const& options)
  956. {
  957. auto dictionary = TRY(try_make<SearchableCircularBuffer>(TRY(SearchableCircularBuffer::create_empty(options.dictionary_size + largest_real_match_length))));
  958. // "The LZMA Decoder uses (1 << (lc + lp)) tables with CProb values, where each table contains 0x300 CProb values."
  959. auto literal_probabilities = TRY(FixedArray<Probability>::create(literal_probability_table_size * (1 << (options.literal_context_bits + options.literal_position_bits))));
  960. auto header = TRY(LzmaHeader::from_compressor_options(options));
  961. TRY(stream->write_value(header));
  962. auto compressor = TRY(adopt_nonnull_own_or_enomem(new (nothrow) LzmaCompressor(move(stream), options, move(dictionary), move(literal_probabilities))));
  963. return compressor;
  964. }
  965. LzmaCompressor::LzmaCompressor(MaybeOwned<AK::Stream> stream, Compress::LzmaCompressorOptions options, MaybeOwned<SearchableCircularBuffer> dictionary, FixedArray<Compress::LzmaState::Probability> literal_probabilities)
  966. : LzmaState(move(literal_probabilities))
  967. , m_stream(move(stream))
  968. , m_options(move(options))
  969. , m_dictionary(move(dictionary))
  970. {
  971. }
  972. ErrorOr<Bytes> LzmaCompressor::read_some(Bytes)
  973. {
  974. return Error::from_errno(EBADF);
  975. }
  976. ErrorOr<size_t> LzmaCompressor::write_some(ReadonlyBytes bytes)
  977. {
  978. // Fill the input buffer until it's full or until we can't read any more data.
  979. size_t processed_bytes = min(bytes.size(), largest_real_match_length - m_dictionary->used_space());
  980. bytes = bytes.trim(processed_bytes);
  981. while (bytes.size() > 0) {
  982. auto const written_bytes = m_dictionary->write(bytes);
  983. bytes = bytes.slice(written_bytes);
  984. }
  985. VERIFY(m_dictionary->used_space() <= largest_real_match_length);
  986. if (m_options.uncompressed_size.has_value() && m_total_processed_bytes + m_dictionary->used_space() > m_options.uncompressed_size.value())
  987. return Error::from_string_literal("Tried to compress more LZMA data than announced");
  988. TRY(encode_once());
  989. // If we read enough data to reach the final uncompressed size, flush automatically.
  990. // Flushing will handle encoding the remaining data for us and finalize the stream.
  991. if (m_options.uncompressed_size.has_value() && m_total_processed_bytes + m_dictionary->used_space() >= m_options.uncompressed_size.value())
  992. TRY(flush());
  993. return processed_bytes;
  994. }
  995. ErrorOr<void> LzmaCompressor::flush()
  996. {
  997. if (m_has_flushed_data)
  998. return Error::from_string_literal("Flushed an LZMA stream twice");
  999. while (m_dictionary->used_space() > 0)
  1000. TRY(encode_once());
  1001. if (m_options.uncompressed_size.has_value() && m_total_processed_bytes < m_options.uncompressed_size.value())
  1002. return Error::from_string_literal("Flushing LZMA data with known but unreached uncompressed size");
  1003. // The LZMA specification technically also allows both a known size and an end-of-stream marker simultaneously,
  1004. // but LZMA2 rejects them, so skip emitting the end-of-stream marker if we know the uncompressed size.
  1005. if (!m_options.uncompressed_size.has_value())
  1006. TRY(encode_normalized_simple_match(end_of_stream_marker, 0));
  1007. // Shifting the range encoder using the normal operation handles any pending overflows.
  1008. TRY(shift_range_encoder());
  1009. // Now, the remaining bytes are the cached byte, the chain of 0xFF, and the upper 3 bytes of the current `code`.
  1010. // Incrementing the values does not have to be considered as no overflows are pending. The fourth byte is the
  1011. // null byte that we just shifted in, which should not be flushed as it would be extraneous junk data.
  1012. TRY(m_stream->write_value<u8>(m_range_encoder_cached_byte));
  1013. for (size_t i = 0; i < m_range_encoder_ff_chain_length; i++)
  1014. TRY(m_stream->write_value<u8>(0xFF));
  1015. TRY(m_stream->write_value<u8>(m_range_encoder_code >> 24));
  1016. TRY(m_stream->write_value<u8>(m_range_encoder_code >> 16));
  1017. TRY(m_stream->write_value<u8>(m_range_encoder_code >> 8));
  1018. m_has_flushed_data = true;
  1019. return {};
  1020. }
  1021. bool LzmaCompressor::is_eof() const
  1022. {
  1023. return true;
  1024. }
  1025. bool LzmaCompressor::is_open() const
  1026. {
  1027. return !m_has_flushed_data;
  1028. }
  1029. void LzmaCompressor::close()
  1030. {
  1031. if (!m_has_flushed_data) {
  1032. // Note: We need a better API for specifying things like this.
  1033. flush().release_value_but_fixme_should_propagate_errors();
  1034. }
  1035. }
  1036. LzmaCompressor::~LzmaCompressor()
  1037. {
  1038. if (!m_has_flushed_data) {
  1039. // Note: We need a better API for specifying things like this.
  1040. flush().release_value_but_fixme_should_propagate_errors();
  1041. }
  1042. }
  1043. }