blob: e9915af7b45fe749c2bc1fb10c49db9539803d30 [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
5namespace aos::logger {
6namespace {
7
Austin Schuh3bd4c402020-11-06 18:19:06 -08008// Returns true if `status` is not an error code, false if it is recoverable, or
9// otherwise logs the appropriate error message and crashes.
Austin Schuhed292dc2020-12-22 22:32:59 -080010bool LzmaCodeIsOk(lzma_ret status, std::string_view filename = "") {
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070011 switch (status) {
12 case LZMA_OK:
13 case LZMA_STREAM_END:
Austin Schuh3bd4c402020-11-06 18:19:06 -080014 return true;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070015 case LZMA_MEM_ERROR:
16 LOG(FATAL) << "Memory allocation failed:" << status;
17 case LZMA_OPTIONS_ERROR:
18 LOG(FATAL) << "The given compression preset or decompression options are "
19 "not supported: "
20 << status;
21 case LZMA_UNSUPPORTED_CHECK:
22 LOG(FATAL) << "The given check type is not supported: " << status;
23 case LZMA_PROG_ERROR:
24 LOG(FATAL) << "One or more of the parameters have values that will never "
25 "be valid: "
26 << status;
27 case LZMA_MEMLIMIT_ERROR:
28 LOG(FATAL) << "Decoder needs more memory than allowed by the specified "
29 "memory usage limit: "
30 << status;
31 case LZMA_FORMAT_ERROR:
Austin Schuhed292dc2020-12-22 22:32:59 -080032 if (filename.empty()) {
33 LOG(FATAL) << "File format not recognized: " << status;
34 } else {
35 LOG(FATAL) << "File format of " << filename
36 << " not recognized: " << status;
37 }
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070038 case LZMA_DATA_ERROR:
Brian Silverman517431e2021-11-10 12:48:58 -080039 VLOG(1) << "Compressed file is corrupt: " << status;
Austin Schuh3bd4c402020-11-06 18:19:06 -080040 return false;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070041 case LZMA_BUF_ERROR:
Brian Silverman517431e2021-11-10 12:48:58 -080042 VLOG(1) << "Compressed file is truncated or corrupt: " << status;
Austin Schuh3bd4c402020-11-06 18:19:06 -080043 return false;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070044 default:
45 LOG(FATAL) << "Unexpected return value: " << status;
46 }
47}
48
49} // namespace
50
51LzmaEncoder::LzmaEncoder(const uint32_t compression_preset)
52 : stream_(LZMA_STREAM_INIT), compression_preset_(compression_preset) {
53 CHECK_GE(compression_preset_, 0u)
54 << ": Compression preset must be in the range [0, 9].";
55 CHECK_LE(compression_preset_, 9u)
56 << ": Compression preset must be in the range [0, 9].";
57
58 lzma_ret status =
59 lzma_easy_encoder(&stream_, compression_preset_, LZMA_CHECK_CRC64);
Austin Schuh3bd4c402020-11-06 18:19:06 -080060 CHECK(LzmaCodeIsOk(status));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070061 stream_.avail_out = 0;
62 VLOG(2) << "LzmaEncoder: Initialization succeeded.";
63}
64
65LzmaEncoder::~LzmaEncoder() { lzma_end(&stream_); }
66
67void LzmaEncoder::Encode(flatbuffers::DetachedBuffer &&in) {
68 CHECK(in.data()) << ": Encode called with nullptr.";
69
70 stream_.next_in = in.data();
71 stream_.avail_in = in.size();
72
73 RunLzmaCode(LZMA_RUN);
74}
75
76void LzmaEncoder::Finish() { RunLzmaCode(LZMA_FINISH); }
77
78void LzmaEncoder::Clear(const int n) {
79 CHECK_GE(n, 0);
80 CHECK_LE(static_cast<size_t>(n), queue_size());
81 queue_.erase(queue_.begin(), queue_.begin() + n);
82 if (queue_.empty()) {
83 stream_.next_out = nullptr;
84 stream_.avail_out = 0;
85 }
86}
87
88std::vector<absl::Span<const uint8_t>> LzmaEncoder::queue() const {
89 std::vector<absl::Span<const uint8_t>> queue;
90 if (queue_.empty()) {
91 return queue;
92 }
93 for (size_t i = 0; i < queue_.size() - 1; ++i) {
94 queue.emplace_back(
95 absl::MakeConstSpan(queue_.at(i).data(), queue_.at(i).size()));
96 }
97 // For the last buffer in the queue, we must account for the possibility that
98 // the buffer isn't full yet.
99 queue.emplace_back(absl::MakeConstSpan(
100 queue_.back().data(), queue_.back().size() - stream_.avail_out));
101 return queue;
102}
103
104size_t LzmaEncoder::queued_bytes() const {
105 size_t bytes = queue_size() * kEncodedBufferSizeBytes;
106 // Subtract the bytes that the encoder hasn't filled yet.
107 bytes -= stream_.avail_out;
108 return bytes;
109}
110
111void LzmaEncoder::RunLzmaCode(lzma_action action) {
112 CHECK(!finished_);
113
114 // This is to keep track of how many bytes resulted from encoding this input
115 // buffer.
116 size_t last_avail_out = stream_.avail_out;
117
118 while (stream_.avail_in > 0 || action == LZMA_FINISH) {
119 // If output buffer is full, create a new one, queue it up, and resume
120 // encoding. This could happen in the first call to Encode after
121 // construction or a Reset, or when an input buffer is large enough to fill
122 // more than one output buffer.
123 if (stream_.avail_out == 0) {
124 queue_.emplace_back();
125 queue_.back().resize(kEncodedBufferSizeBytes);
126 stream_.next_out = queue_.back().data();
127 stream_.avail_out = kEncodedBufferSizeBytes;
128 // Update the byte count.
129 total_bytes_ += last_avail_out;
130 last_avail_out = stream_.avail_out;
131 }
132
133 // Encode the data.
134 lzma_ret status = lzma_code(&stream_, action);
Austin Schuh3bd4c402020-11-06 18:19:06 -0800135 CHECK(LzmaCodeIsOk(status));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700136 if (action == LZMA_FINISH) {
137 if (status == LZMA_STREAM_END) {
138 // This is returned when lzma_code is all done.
139 finished_ = true;
140 break;
141 }
142 } else {
143 CHECK(status != LZMA_STREAM_END);
144 }
145 VLOG(2) << "LzmaEncoder: Encoded chunk.";
146 }
147
148 // Update the number of resulting encoded bytes.
149 total_bytes_ += last_avail_out - stream_.avail_out;
150}
151
Tyler Chatow2015bc62021-08-04 21:15:09 -0700152LzmaDecoder::LzmaDecoder(std::unique_ptr<DataDecoder> underlying_decoder)
153 : underlying_decoder_(std::move(underlying_decoder)),
154 stream_(LZMA_STREAM_INIT) {
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700155 compressed_data_.resize(kBufSize);
156
157 lzma_ret status =
158 lzma_stream_decoder(&stream_, UINT64_MAX, LZMA_CONCATENATED);
Austin Schuh3bd4c402020-11-06 18:19:06 -0800159 CHECK(LzmaCodeIsOk(status)) << "Failed initializing LZMA stream decoder.";
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700160 stream_.avail_out = 0;
161 VLOG(2) << "LzmaDecoder: Initialization succeeded.";
162}
163
164LzmaDecoder::~LzmaDecoder() { lzma_end(&stream_); }
165
166size_t LzmaDecoder::Read(uint8_t *begin, uint8_t *end) {
167 if (finished_) {
168 return 0;
169 }
170
171 // Write into the given range.
172 stream_.next_out = begin;
173 stream_.avail_out = end - begin;
174 // Keep decompressing until we run out of buffer space.
175 while (stream_.avail_out > 0) {
176 if (action_ == LZMA_RUN && stream_.avail_in == 0) {
177 // Read more bytes from the file if we're all out.
Tyler Chatow2015bc62021-08-04 21:15:09 -0700178 const size_t count = underlying_decoder_->Read(compressed_data_.begin(),
179 compressed_data_.end());
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700180 if (count == 0) {
181 // No more data to read in the file, begin the finishing operation.
182 action_ = LZMA_FINISH;
183 } else {
184 stream_.next_in = compressed_data_.data();
185 stream_.avail_in = count;
186 }
187 }
188 // Decompress the data.
189 const lzma_ret status = lzma_code(&stream_, action_);
190 // Return if we're done.
191 if (status == LZMA_STREAM_END) {
192 CHECK_EQ(action_, LZMA_FINISH)
193 << ": Got LZMA_STREAM_END when action wasn't LZMA_FINISH";
194 finished_ = true;
195 return (end - begin) - stream_.avail_out;
196 }
Austin Schuh3bd4c402020-11-06 18:19:06 -0800197
198 // If we fail to decompress, give up. Return everything that has been
199 // produced so far.
Tyler Chatow2015bc62021-08-04 21:15:09 -0700200 if (!LzmaCodeIsOk(status, filename())) {
Austin Schuh3bd4c402020-11-06 18:19:06 -0800201 finished_ = true;
Brian Silverman517431e2021-11-10 12:48:58 -0800202 if (status == LZMA_DATA_ERROR) {
203 LOG(WARNING) << filename() << " is corrupted.";
204 } else if (status == LZMA_BUF_ERROR) {
205 LOG(WARNING) << filename() << " is truncated or corrupted.";
206 } else {
207 LOG(FATAL) << "Unknown error " << status << " when reading "
208 << filename();
209 }
Austin Schuh3bd4c402020-11-06 18:19:06 -0800210 return (end - begin) - stream_.avail_out;
211 }
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700212 }
213 return end - begin;
214}
215
Tyler Chatow2015bc62021-08-04 21:15:09 -0700216ThreadedLzmaDecoder::ThreadedLzmaDecoder(
217 std::unique_ptr<DataDecoder> underlying_decoder)
218 : decoder_(std::move(underlying_decoder)), decode_thread_([this] {
Tyler Chatow7df60832021-07-15 21:18:36 -0700219 std::unique_lock lock(decode_mutex_);
220 while (true) {
221 // Wake if the queue is too small or we are finished.
222 continue_decoding_.wait(lock, [this] {
223 return decoded_queue_.size() < kQueueSize || finished_;
224 });
225
226 if (finished_) {
227 return;
228 }
229
230 while (true) {
231 CHECK(!finished_);
232 // Release our lock on the queue before doing decompression work.
233 lock.unlock();
234
235 ResizeableBuffer buffer;
236 buffer.resize(kBufSize);
237
238 const size_t bytes_read =
239 decoder_.Read(buffer.begin(), buffer.end());
240 buffer.resize(bytes_read);
241
242 // Relock the queue and move the new buffer to the end. This should
243 // be fast. We also need to stay locked when we wait().
244 lock.lock();
245 if (bytes_read > 0) {
246 decoded_queue_.emplace_back(std::move(buffer));
247 } else {
248 finished_ = true;
249 }
250
251 // If we've filled the queue or are out of data, go back to sleep.
252 if (decoded_queue_.size() >= kQueueSize || finished_) {
253 break;
254 }
255 }
256
257 // Notify main thread in case it was waiting for us to queue more
258 // data.
259 queue_filled_.notify_one();
260 }
261 }) {}
262
263ThreadedLzmaDecoder::~ThreadedLzmaDecoder() {
264 // Wake up decode thread so it can return.
265 {
266 std::scoped_lock lock(decode_mutex_);
267 finished_ = true;
268 }
269 continue_decoding_.notify_one();
270 decode_thread_.join();
271}
272
273size_t ThreadedLzmaDecoder::Read(uint8_t *begin, uint8_t *end) {
274 std::unique_lock lock(decode_mutex_);
275
276 // Strip any empty buffers
277 for (auto iter = decoded_queue_.begin(); iter != decoded_queue_.end();) {
278 if (iter->size() == 0) {
279 iter = decoded_queue_.erase(iter);
280 } else {
281 ++iter;
282 }
283 }
284
285 // If the queue is empty, sleep until the decoder thread has produced another
286 // buffer.
287 if (decoded_queue_.empty()) {
288 continue_decoding_.notify_one();
289 queue_filled_.wait(lock,
290 [this] { return finished_ || !decoded_queue_.empty(); });
291 if (finished_ && decoded_queue_.empty()) {
292 return 0;
293 }
294 }
295 // Sanity check if the queue is empty and we're not finished.
296 CHECK(!decoded_queue_.empty()) << "Decoded queue unexpectedly empty";
297
298 ResizeableBuffer &front_buffer = decoded_queue_.front();
299
300 // Copy some data from our working buffer to the requested destination.
301 const std::size_t bytes_requested = end - begin;
302 const std::size_t bytes_to_copy =
303 std::min(bytes_requested, front_buffer.size());
304 memcpy(begin, front_buffer.data(), bytes_to_copy);
305 front_buffer.erase_front(bytes_to_copy);
306
307 // Ensure the decoding thread wakes up if the queue isn't full.
308 if (!finished_ && decoded_queue_.size() < kQueueSize) {
309 continue_decoding_.notify_one();
310 }
311
312 return bytes_to_copy;
313}
314
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700315} // namespace aos::logger