comparison 3rdparty/compressor/fpaq0.h @ 0:a4671277546c tip

created the repository for the thymian project
author ferencd
date Tue, 17 Aug 2021 11:19:54 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:a4671277546c
1 #ifndef FPAQ0
2 #define FPAQ0
3
4 #include <vector>
5 #include <string>
6 #include <stdint.h>
7
8 #include <string.h>
9
10 class Archive
11 {
12 public:
13
14 Archive(const std::vector<unsigned char>& s) : content(s.begin(), s.end()), it(content.begin()) {}
15 Archive() : content(), it(content.begin()) {}
16
17 int getc() const
18 {
19 if(it == content.end())
20 {
21 return EOF;
22 }
23 int v = static_cast<int> (*it);
24 ++ it;
25 return v;
26 }
27
28 void putc(char c)
29 {
30 content.push_back(c);
31 }
32
33 std::vector<unsigned char> data() const
34 {
35 return content;
36 }
37
38 private:
39 std::vector<unsigned char> content; // Compressed data file
40 mutable std::vector<unsigned char>::iterator it;
41 };
42
43 //////////////////////////// Predictor /////////////////////////
44
45 /* A Predictor estimates the probability that the next bit of
46 uncompressed data is 1. Methods:
47 p() returns P(1) as a 12 bit number (0-4095).
48 update(y) trains the predictor with the actual bit (0 or 1).
49 */
50
51 class Predictor
52 {
53 int cxt; // Context: last 0-8 bits with a leading 1
54 int ct[512][2]; // 0 and 1 counts in context cxt
55 public:
56 Predictor(): cxt(1)
57 {
58 memset(ct, 0, sizeof(ct));
59 }
60
61 // Assume a stationary order 0 stream of 9-bit symbols
62 int p() const;
63
64 void update(int y);
65 };
66
67
68 //////////////////////////// Encoder ////////////////////////////
69
70 /* An Encoder does arithmetic encoding. Methods:
71 Encoder(COMPRESS, f) creates encoder for compression to archive f, which
72 must be open past any header for writing in binary mode
73 Encoder(DECOMPRESS, f) creates encoder for decompression from archive f,
74 which must be open past any header for reading in binary mode
75 encode(bit) in COMPRESS mode compresses bit to file f.
76 decode() in DECOMPRESS mode returns the next decompressed bit from file f.
77 flush() should be called when there is no more to compress.
78 */
79
80 typedef enum {COMPRESS, DECOMPRESS} Mode;
81 class Encoder
82 {
83 public:
84 Encoder(Mode m, Archive& archive);
85 void encode(int y); // Compress bit y
86 int decode(); // Uncompress and return bit y
87 void flush(); // Call when done compressing
88 private:
89 Predictor predictor;
90 const Mode mode; // Compress or decompress?
91 Archive& archive;
92 uint32_t x1, x2; // Range, initially [0, 1), scaled by 2^32
93 uint32_t x; // Last 4 input bytes of archive.
94 };
95
96 std::vector<unsigned char> compress(const std::string& s);
97
98 std::string decompress(const std::vector<unsigned char>& v);
99
100 #endif // FPAQ0
101