blob: 60a203ed99dfc433f75f0847b3b89d99ae3c854e [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:
Austin Schuh3bd4c402020-11-06 18:19:06 -080039 LOG(WARNING) << "Compressed file is corrupt: " << status;
40 return false;
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070041 case LZMA_BUF_ERROR:
Austin Schuh3bd4c402020-11-06 18:19:06 -080042 LOG(WARNING) << "Compressed file is truncated or corrupt: " << status;
43 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
152LzmaDecoder::LzmaDecoder(std::string_view filename)
Austin Schuh3bd4c402020-11-06 18:19:06 -0800153 : dummy_decoder_(filename), stream_(LZMA_STREAM_INIT), filename_(filename) {
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700154 compressed_data_.resize(kBufSize);
155
156 lzma_ret status =
157 lzma_stream_decoder(&stream_, UINT64_MAX, LZMA_CONCATENATED);
Austin Schuh3bd4c402020-11-06 18:19:06 -0800158 CHECK(LzmaCodeIsOk(status)) << "Failed initializing LZMA stream decoder.";
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700159 stream_.avail_out = 0;
160 VLOG(2) << "LzmaDecoder: Initialization succeeded.";
161}
162
163LzmaDecoder::~LzmaDecoder() { lzma_end(&stream_); }
164
165size_t LzmaDecoder::Read(uint8_t *begin, uint8_t *end) {
166 if (finished_) {
167 return 0;
168 }
169
170 // Write into the given range.
171 stream_.next_out = begin;
172 stream_.avail_out = end - begin;
173 // Keep decompressing until we run out of buffer space.
174 while (stream_.avail_out > 0) {
175 if (action_ == LZMA_RUN && stream_.avail_in == 0) {
176 // Read more bytes from the file if we're all out.
177 const size_t count =
178 dummy_decoder_.Read(compressed_data_.begin(), compressed_data_.end());
179 if (count == 0) {
180 // No more data to read in the file, begin the finishing operation.
181 action_ = LZMA_FINISH;
182 } else {
183 stream_.next_in = compressed_data_.data();
184 stream_.avail_in = count;
185 }
186 }
187 // Decompress the data.
188 const lzma_ret status = lzma_code(&stream_, action_);
189 // Return if we're done.
190 if (status == LZMA_STREAM_END) {
191 CHECK_EQ(action_, LZMA_FINISH)
192 << ": Got LZMA_STREAM_END when action wasn't LZMA_FINISH";
193 finished_ = true;
194 return (end - begin) - stream_.avail_out;
195 }
Austin Schuh3bd4c402020-11-06 18:19:06 -0800196
197 // If we fail to decompress, give up. Return everything that has been
198 // produced so far.
Austin Schuhed292dc2020-12-22 22:32:59 -0800199 if (!LzmaCodeIsOk(status, filename_)) {
Austin Schuh3bd4c402020-11-06 18:19:06 -0800200 finished_ = true;
201 LOG(WARNING) << filename_ << " is truncated or corrupted.";
202 return (end - begin) - stream_.avail_out;
203 }
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700204 }
205 return end - begin;
206}
207
Tyler Chatow7df60832021-07-15 21:18:36 -0700208ThreadedLzmaDecoder::ThreadedLzmaDecoder(std::string_view filename)
209 : decoder_(filename), decode_thread_([this] {
210 std::unique_lock lock(decode_mutex_);
211 while (true) {
212 // Wake if the queue is too small or we are finished.
213 continue_decoding_.wait(lock, [this] {
214 return decoded_queue_.size() < kQueueSize || finished_;
215 });
216
217 if (finished_) {
218 return;
219 }
220
221 while (true) {
222 CHECK(!finished_);
223 // Release our lock on the queue before doing decompression work.
224 lock.unlock();
225
226 ResizeableBuffer buffer;
227 buffer.resize(kBufSize);
228
229 const size_t bytes_read =
230 decoder_.Read(buffer.begin(), buffer.end());
231 buffer.resize(bytes_read);
232
233 // Relock the queue and move the new buffer to the end. This should
234 // be fast. We also need to stay locked when we wait().
235 lock.lock();
236 if (bytes_read > 0) {
237 decoded_queue_.emplace_back(std::move(buffer));
238 } else {
239 finished_ = true;
240 }
241
242 // If we've filled the queue or are out of data, go back to sleep.
243 if (decoded_queue_.size() >= kQueueSize || finished_) {
244 break;
245 }
246 }
247
248 // Notify main thread in case it was waiting for us to queue more
249 // data.
250 queue_filled_.notify_one();
251 }
252 }) {}
253
254ThreadedLzmaDecoder::~ThreadedLzmaDecoder() {
255 // Wake up decode thread so it can return.
256 {
257 std::scoped_lock lock(decode_mutex_);
258 finished_ = true;
259 }
260 continue_decoding_.notify_one();
261 decode_thread_.join();
262}
263
264size_t ThreadedLzmaDecoder::Read(uint8_t *begin, uint8_t *end) {
265 std::unique_lock lock(decode_mutex_);
266
267 // Strip any empty buffers
268 for (auto iter = decoded_queue_.begin(); iter != decoded_queue_.end();) {
269 if (iter->size() == 0) {
270 iter = decoded_queue_.erase(iter);
271 } else {
272 ++iter;
273 }
274 }
275
276 // If the queue is empty, sleep until the decoder thread has produced another
277 // buffer.
278 if (decoded_queue_.empty()) {
279 continue_decoding_.notify_one();
280 queue_filled_.wait(lock,
281 [this] { return finished_ || !decoded_queue_.empty(); });
282 if (finished_ && decoded_queue_.empty()) {
283 return 0;
284 }
285 }
286 // Sanity check if the queue is empty and we're not finished.
287 CHECK(!decoded_queue_.empty()) << "Decoded queue unexpectedly empty";
288
289 ResizeableBuffer &front_buffer = decoded_queue_.front();
290
291 // Copy some data from our working buffer to the requested destination.
292 const std::size_t bytes_requested = end - begin;
293 const std::size_t bytes_to_copy =
294 std::min(bytes_requested, front_buffer.size());
295 memcpy(begin, front_buffer.data(), bytes_to_copy);
296 front_buffer.erase_front(bytes_to_copy);
297
298 // Ensure the decoding thread wakes up if the queue isn't full.
299 if (!finished_ && decoded_queue_.size() < kQueueSize) {
300 continue_decoding_.notify_one();
301 }
302
303 return bytes_to_copy;
304}
305
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700306} // namespace aos::logger