blob: f5838180b0c373c16a70b52607868e167fb7c262 [file] [log] [blame]
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07001#include "aos/events/logging/lzma_encoder.h"
2
3#include "glog/logging.h"
4
Austin Schuhbe91b342022-06-27 00:53:45 -07005DEFINE_int32(lzma_threads, 1, "Number of threads to use for encoding");
6
Brian Silvermanf59fe3f2020-09-22 21:04:09 -07007namespace aos::logger {
8namespace {
9
Austin Schuh3bd4c402020-11-06 18:19:06 -080010// Returns true if `status` is not an error code, false if it is recoverable, or
11// otherwise logs the appropriate error message and crashes.
Austin Schuhed292dc2020-12-22 22:32:59 -080012bool LzmaCodeIsOk(lzma_ret status, std::string_view filename = "") {
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070013 switch (status) {
14 case LZMA_OK:
15 case LZMA_STREAM_END:
Austin Schuh3bd4c402020-11-06 18:19:06 -080016 return true;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070017 case LZMA_MEM_ERROR:
18 LOG(FATAL) << "Memory allocation failed:" << status;
19 case LZMA_OPTIONS_ERROR:
20 LOG(FATAL) << "The given compression preset or decompression options are "
21 "not supported: "
22 << status;
23 case LZMA_UNSUPPORTED_CHECK:
24 LOG(FATAL) << "The given check type is not supported: " << status;
25 case LZMA_PROG_ERROR:
26 LOG(FATAL) << "One or more of the parameters have values that will never "
27 "be valid: "
28 << status;
29 case LZMA_MEMLIMIT_ERROR:
30 LOG(FATAL) << "Decoder needs more memory than allowed by the specified "
31 "memory usage limit: "
32 << status;
33 case LZMA_FORMAT_ERROR:
Austin Schuhed292dc2020-12-22 22:32:59 -080034 if (filename.empty()) {
35 LOG(FATAL) << "File format not recognized: " << status;
36 } else {
37 LOG(FATAL) << "File format of " << filename
38 << " not recognized: " << status;
39 }
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070040 case LZMA_DATA_ERROR:
Brian Silverman517431e2021-11-10 12:48:58 -080041 VLOG(1) << "Compressed file is corrupt: " << status;
Austin Schuh3bd4c402020-11-06 18:19:06 -080042 return false;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070043 case LZMA_BUF_ERROR:
Brian Silverman517431e2021-11-10 12:48:58 -080044 VLOG(1) << "Compressed file is truncated or corrupt: " << status;
Austin Schuh3bd4c402020-11-06 18:19:06 -080045 return false;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070046 default:
47 LOG(FATAL) << "Unexpected return value: " << status;
48 }
49}
50
51} // namespace
52
Austin Schuh48d10d62022-10-16 22:19:23 -070053LzmaEncoder::LzmaEncoder(size_t max_message_size,
54 const uint32_t compression_preset, size_t block_size)
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070055 : stream_(LZMA_STREAM_INIT), compression_preset_(compression_preset) {
56 CHECK_GE(compression_preset_, 0u)
57 << ": Compression preset must be in the range [0, 9].";
58 CHECK_LE(compression_preset_, 9u)
59 << ": Compression preset must be in the range [0, 9].";
60
Austin Schuhbe91b342022-06-27 00:53:45 -070061 if (FLAGS_lzma_threads <= 1) {
62 lzma_ret status =
63 lzma_easy_encoder(&stream_, compression_preset_, LZMA_CHECK_CRC64);
64 CHECK(LzmaCodeIsOk(status));
65 } else {
66 lzma_mt mt_options;
67 memset(&mt_options, 0, sizeof(mt_options));
68 mt_options.threads = FLAGS_lzma_threads;
69 mt_options.block_size = block_size;
70 // Compress for at most 100 ms before relinquishing control back to the main
71 // thread.
72 mt_options.timeout = 100;
73 mt_options.preset = compression_preset_;
74 mt_options.filters = nullptr;
75 mt_options.check = LZMA_CHECK_CRC64;
76 lzma_ret status = lzma_stream_encoder_mt(&stream_, &mt_options);
77 CHECK(LzmaCodeIsOk(status));
78 }
79
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070080 stream_.avail_out = 0;
81 VLOG(2) << "LzmaEncoder: Initialization succeeded.";
Austin Schuh48d10d62022-10-16 22:19:23 -070082
83 // TODO(austin): We don't write the biggest messages very often. Is it more
84 // efficient to allocate if we go over a threshold to keep the static memory
85 // in use smaller, or just allocate the worst case like we are doing here?
86 input_buffer_.resize(max_message_size);
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070087}
88
89LzmaEncoder::~LzmaEncoder() { lzma_end(&stream_); }
90
Austin Schuh48d10d62022-10-16 22:19:23 -070091void LzmaEncoder::Encode(Copier *copy) {
92 const size_t copy_size = copy->size();
93 // LZMA compresses the data as it goes along, copying the compressed results
94 // into another buffer. So, there's no need to store more than one message
95 // since lzma is going to take it from here.
96 CHECK_LE(copy_size, input_buffer_.size());
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070097
Austin Schuh48d10d62022-10-16 22:19:23 -070098 CHECK_EQ(copy->Copy(input_buffer_.data()), copy_size);
99
100 stream_.next_in = input_buffer_.data();
101 stream_.avail_in = copy_size;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700102
103 RunLzmaCode(LZMA_RUN);
104}
105
106void LzmaEncoder::Finish() { RunLzmaCode(LZMA_FINISH); }
107
108void LzmaEncoder::Clear(const int n) {
109 CHECK_GE(n, 0);
110 CHECK_LE(static_cast<size_t>(n), queue_size());
111 queue_.erase(queue_.begin(), queue_.begin() + n);
112 if (queue_.empty()) {
113 stream_.next_out = nullptr;
114 stream_.avail_out = 0;
115 }
116}
117
Austin Schuh48d10d62022-10-16 22:19:23 -0700118absl::Span<const absl::Span<const uint8_t>> LzmaEncoder::queue() {
119 return_queue_.clear();
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700120 if (queue_.empty()) {
Austin Schuh48d10d62022-10-16 22:19:23 -0700121 return return_queue_;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700122 }
Austin Schuh48d10d62022-10-16 22:19:23 -0700123 return_queue_.reserve(queue_.size());
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700124 for (size_t i = 0; i < queue_.size() - 1; ++i) {
Austin Schuh48d10d62022-10-16 22:19:23 -0700125 return_queue_.emplace_back(
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700126 absl::MakeConstSpan(queue_.at(i).data(), queue_.at(i).size()));
127 }
128 // For the last buffer in the queue, we must account for the possibility that
129 // the buffer isn't full yet.
Austin Schuh48d10d62022-10-16 22:19:23 -0700130 return_queue_.emplace_back(absl::MakeConstSpan(
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700131 queue_.back().data(), queue_.back().size() - stream_.avail_out));
Austin Schuh48d10d62022-10-16 22:19:23 -0700132 return return_queue_;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700133}
134
135size_t LzmaEncoder::queued_bytes() const {
136 size_t bytes = queue_size() * kEncodedBufferSizeBytes;
137 // Subtract the bytes that the encoder hasn't filled yet.
138 bytes -= stream_.avail_out;
139 return bytes;
140}
141
142void LzmaEncoder::RunLzmaCode(lzma_action action) {
143 CHECK(!finished_);
144
145 // This is to keep track of how many bytes resulted from encoding this input
146 // buffer.
147 size_t last_avail_out = stream_.avail_out;
148
149 while (stream_.avail_in > 0 || action == LZMA_FINISH) {
150 // If output buffer is full, create a new one, queue it up, and resume
151 // encoding. This could happen in the first call to Encode after
152 // construction or a Reset, or when an input buffer is large enough to fill
153 // more than one output buffer.
154 if (stream_.avail_out == 0) {
155 queue_.emplace_back();
156 queue_.back().resize(kEncodedBufferSizeBytes);
157 stream_.next_out = queue_.back().data();
158 stream_.avail_out = kEncodedBufferSizeBytes;
159 // Update the byte count.
160 total_bytes_ += last_avail_out;
161 last_avail_out = stream_.avail_out;
162 }
163
164 // Encode the data.
165 lzma_ret status = lzma_code(&stream_, action);
Austin Schuh3bd4c402020-11-06 18:19:06 -0800166 CHECK(LzmaCodeIsOk(status));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700167 if (action == LZMA_FINISH) {
168 if (status == LZMA_STREAM_END) {
169 // This is returned when lzma_code is all done.
170 finished_ = true;
171 break;
172 }
173 } else {
174 CHECK(status != LZMA_STREAM_END);
175 }
176 VLOG(2) << "LzmaEncoder: Encoded chunk.";
177 }
178
179 // Update the number of resulting encoded bytes.
180 total_bytes_ += last_avail_out - stream_.avail_out;
181}
182
Austin Schuhcd368422021-11-22 21:23:29 -0800183LzmaDecoder::LzmaDecoder(std::unique_ptr<DataDecoder> underlying_decoder,
184 bool quiet)
Tyler Chatow2015bc62021-08-04 21:15:09 -0700185 : underlying_decoder_(std::move(underlying_decoder)),
Austin Schuhcd368422021-11-22 21:23:29 -0800186 stream_(LZMA_STREAM_INIT),
187 quiet_(quiet) {
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700188 compressed_data_.resize(kBufSize);
189
190 lzma_ret status =
191 lzma_stream_decoder(&stream_, UINT64_MAX, LZMA_CONCATENATED);
Austin Schuh3bd4c402020-11-06 18:19:06 -0800192 CHECK(LzmaCodeIsOk(status)) << "Failed initializing LZMA stream decoder.";
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700193 stream_.avail_out = 0;
194 VLOG(2) << "LzmaDecoder: Initialization succeeded.";
195}
196
197LzmaDecoder::~LzmaDecoder() { lzma_end(&stream_); }
198
199size_t LzmaDecoder::Read(uint8_t *begin, uint8_t *end) {
200 if (finished_) {
201 return 0;
202 }
203
204 // Write into the given range.
205 stream_.next_out = begin;
206 stream_.avail_out = end - begin;
207 // Keep decompressing until we run out of buffer space.
208 while (stream_.avail_out > 0) {
209 if (action_ == LZMA_RUN && stream_.avail_in == 0) {
210 // Read more bytes from the file if we're all out.
Tyler Chatow2015bc62021-08-04 21:15:09 -0700211 const size_t count = underlying_decoder_->Read(compressed_data_.begin(),
212 compressed_data_.end());
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700213 if (count == 0) {
214 // No more data to read in the file, begin the finishing operation.
215 action_ = LZMA_FINISH;
216 } else {
217 stream_.next_in = compressed_data_.data();
218 stream_.avail_in = count;
219 }
220 }
221 // Decompress the data.
222 const lzma_ret status = lzma_code(&stream_, action_);
223 // Return if we're done.
224 if (status == LZMA_STREAM_END) {
225 CHECK_EQ(action_, LZMA_FINISH)
226 << ": Got LZMA_STREAM_END when action wasn't LZMA_FINISH";
227 finished_ = true;
228 return (end - begin) - stream_.avail_out;
229 }
Austin Schuh3bd4c402020-11-06 18:19:06 -0800230
231 // If we fail to decompress, give up. Return everything that has been
232 // produced so far.
Tyler Chatow2015bc62021-08-04 21:15:09 -0700233 if (!LzmaCodeIsOk(status, filename())) {
Austin Schuh3bd4c402020-11-06 18:19:06 -0800234 finished_ = true;
Brian Silverman517431e2021-11-10 12:48:58 -0800235 if (status == LZMA_DATA_ERROR) {
Austin Schuhcd368422021-11-22 21:23:29 -0800236 if (!quiet_ || VLOG_IS_ON(1)) {
237 LOG(WARNING) << filename() << " is corrupted.";
238 }
Brian Silverman517431e2021-11-10 12:48:58 -0800239 } else if (status == LZMA_BUF_ERROR) {
Austin Schuhcd368422021-11-22 21:23:29 -0800240 if (!quiet_ || VLOG_IS_ON(1)) {
241 LOG(WARNING) << filename() << " is truncated or corrupted.";
242 }
Brian Silverman517431e2021-11-10 12:48:58 -0800243 } else {
244 LOG(FATAL) << "Unknown error " << status << " when reading "
245 << filename();
246 }
Austin Schuh3bd4c402020-11-06 18:19:06 -0800247 return (end - begin) - stream_.avail_out;
248 }
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700249 }
250 return end - begin;
251}
252
Tyler Chatow2015bc62021-08-04 21:15:09 -0700253ThreadedLzmaDecoder::ThreadedLzmaDecoder(
Austin Schuhcd368422021-11-22 21:23:29 -0800254 std::unique_ptr<DataDecoder> underlying_decoder, bool quiet)
255 : decoder_(std::move(underlying_decoder), quiet), decode_thread_([this] {
Tyler Chatow7df60832021-07-15 21:18:36 -0700256 std::unique_lock lock(decode_mutex_);
257 while (true) {
258 // Wake if the queue is too small or we are finished.
259 continue_decoding_.wait(lock, [this] {
260 return decoded_queue_.size() < kQueueSize || finished_;
261 });
262
263 if (finished_) {
264 return;
265 }
266
267 while (true) {
268 CHECK(!finished_);
269 // Release our lock on the queue before doing decompression work.
270 lock.unlock();
271
272 ResizeableBuffer buffer;
273 buffer.resize(kBufSize);
274
275 const size_t bytes_read =
276 decoder_.Read(buffer.begin(), buffer.end());
277 buffer.resize(bytes_read);
278
279 // Relock the queue and move the new buffer to the end. This should
280 // be fast. We also need to stay locked when we wait().
281 lock.lock();
282 if (bytes_read > 0) {
283 decoded_queue_.emplace_back(std::move(buffer));
284 } else {
285 finished_ = true;
286 }
287
288 // If we've filled the queue or are out of data, go back to sleep.
289 if (decoded_queue_.size() >= kQueueSize || finished_) {
290 break;
291 }
292 }
293
294 // Notify main thread in case it was waiting for us to queue more
295 // data.
296 queue_filled_.notify_one();
297 }
298 }) {}
299
300ThreadedLzmaDecoder::~ThreadedLzmaDecoder() {
301 // Wake up decode thread so it can return.
302 {
303 std::scoped_lock lock(decode_mutex_);
304 finished_ = true;
305 }
306 continue_decoding_.notify_one();
307 decode_thread_.join();
308}
309
310size_t ThreadedLzmaDecoder::Read(uint8_t *begin, uint8_t *end) {
311 std::unique_lock lock(decode_mutex_);
312
313 // Strip any empty buffers
314 for (auto iter = decoded_queue_.begin(); iter != decoded_queue_.end();) {
315 if (iter->size() == 0) {
316 iter = decoded_queue_.erase(iter);
317 } else {
318 ++iter;
319 }
320 }
321
322 // If the queue is empty, sleep until the decoder thread has produced another
323 // buffer.
324 if (decoded_queue_.empty()) {
325 continue_decoding_.notify_one();
326 queue_filled_.wait(lock,
327 [this] { return finished_ || !decoded_queue_.empty(); });
328 if (finished_ && decoded_queue_.empty()) {
329 return 0;
330 }
331 }
332 // Sanity check if the queue is empty and we're not finished.
333 CHECK(!decoded_queue_.empty()) << "Decoded queue unexpectedly empty";
334
335 ResizeableBuffer &front_buffer = decoded_queue_.front();
336
337 // Copy some data from our working buffer to the requested destination.
338 const std::size_t bytes_requested = end - begin;
339 const std::size_t bytes_to_copy =
340 std::min(bytes_requested, front_buffer.size());
341 memcpy(begin, front_buffer.data(), bytes_to_copy);
342 front_buffer.erase_front(bytes_to_copy);
343
344 // Ensure the decoding thread wakes up if the queue isn't full.
345 if (!finished_ && decoded_queue_.size() < kQueueSize) {
346 continue_decoding_.notify_one();
347 }
348
349 return bytes_to_copy;
350}
351
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700352} // namespace aos::logger