Brian Silverman | f59fe3f | 2020-09-22 21:04:09 -0700 | [diff] [blame^] | 1 | #ifndef AOS_EVENTS_LOGGING_LZMA_ENCODER_H_ |
| 2 | #define AOS_EVENTS_LOGGING_LZMA_ENCODER_H_ |
| 3 | |
| 4 | #include "absl/types/span.h" |
| 5 | #include "flatbuffers/flatbuffers.h" |
| 6 | #include "lzma.h" |
| 7 | |
| 8 | #include "aos/containers/resizeable_buffer.h" |
| 9 | #include "aos/events/logging/buffer_encoder.h" |
| 10 | #include "aos/events/logging/logger_generated.h" |
| 11 | |
| 12 | namespace aos::logger { |
| 13 | |
| 14 | // Encodes buffers using liblzma. |
| 15 | class LzmaEncoder final : public DetachedBufferEncoder { |
| 16 | public: |
| 17 | // Initializes the LZMA stream and encoder. |
| 18 | explicit LzmaEncoder(uint32_t compression_preset); |
| 19 | // Gracefully shuts down the encoder. |
| 20 | ~LzmaEncoder() final; |
| 21 | |
| 22 | void Encode(flatbuffers::DetachedBuffer &&in) final; |
| 23 | void Finish() final; |
| 24 | void Clear(int n) final; |
| 25 | std::vector<absl::Span<const uint8_t>> queue() const final; |
| 26 | size_t queued_bytes() const final; |
| 27 | size_t total_bytes() const final { return total_bytes_; } |
| 28 | size_t queue_size() const final { return queue_.size(); } |
| 29 | |
| 30 | private: |
| 31 | static constexpr size_t kEncodedBufferSizeBytes{1024}; |
| 32 | |
| 33 | void RunLzmaCode(lzma_action action); |
| 34 | |
| 35 | lzma_stream stream_; |
| 36 | uint32_t compression_preset_; |
| 37 | std::vector<ResizeableBuffer> queue_; |
| 38 | bool finished_ = false; |
| 39 | // Total bytes that resulted from encoding raw data since the last call to |
| 40 | // Reset. |
| 41 | size_t total_bytes_ = 0; |
| 42 | }; |
| 43 | |
| 44 | // Decompresses data with liblzma. |
| 45 | class LzmaDecoder final : public DataDecoder { |
| 46 | public: |
| 47 | explicit LzmaDecoder(std::string_view filename); |
| 48 | ~LzmaDecoder(); |
| 49 | |
| 50 | size_t Read(uint8_t *begin, uint8_t *end) final; |
| 51 | |
| 52 | private: |
| 53 | // Size of temporary buffer to use. |
| 54 | static constexpr size_t kBufSize{256 * 1024}; |
| 55 | |
| 56 | // Temporary buffer for storing compressed data. |
| 57 | ResizeableBuffer compressed_data_; |
| 58 | // Used for reading data from the file. |
| 59 | DummyDecoder dummy_decoder_; |
| 60 | // Stream for decompression. |
| 61 | lzma_stream stream_; |
| 62 | // The current action. This is LZMA_RUN until we've run out of data to read |
| 63 | // from the file. |
| 64 | lzma_action action_ = LZMA_RUN; |
| 65 | // Flag that represents whether or not all the data from the file has been |
| 66 | // successfully decoded. |
| 67 | bool finished_ = false; |
| 68 | }; |
| 69 | |
| 70 | } // namespace aos::logger |
| 71 | |
| 72 | #endif // AOS_EVENTS_LOGGING_LZMA_ENCODER_H_ |