-
Notifications
You must be signed in to change notification settings - Fork 9
/
gff.cpp
130 lines (111 loc) · 2.58 KB
/
gff.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include "gff.h"
class CBitStream {
public:
CBitStream(uint8_t* data_ptr, uint32_t data_len)
: mask_(0x80),
data_ptr_(data_ptr),
data_len_(data_len) {}
bool HasData() const { return mask_ != 0 || data_len_ != 0; }
uint32_t DataSize() const { return data_len_; }
bool ReadBit() {
if (!mask_) {
NextMask();
}
bool result = (*data_ptr_ & mask_) != 0;
mask_ >>= 1;
return result;
}
private:
void NextMask() {
if (data_len_) {
mask_ = 0x80;
data_ptr_++;
data_len_--;
}
}
uint8_t mask_;
uint8_t* data_ptr_;
uint32_t data_len_;
};
static uint8_t gff_decode_nibble(CBitStream* bit_stream) {
uint8_t zero_cnt = 0;
bool bit;
do {
if (!bit_stream->HasData()) return 0xf0;
bit = bit_stream->ReadBit();
if (bit) break;
zero_cnt++;
} while (zero_cnt < 6);
if (zero_cnt > 5) {
if (bit_stream->DataSize() == 1) {
return 0xf0;
}
return 0xff;
}
switch (zero_cnt) {
case 0:
return 0;
case 1:
bit = bit_stream->ReadBit();
return (bit) ? 0xf : 1;
case 2:
bit = bit_stream->ReadBit();
return (bit) ? 8 : 2;
case 3:
bit = bit_stream->ReadBit();
return (bit) ? 7 : 0xc;
case 4:
bit = bit_stream->ReadBit();
if (bit) {
bit = bit_stream->ReadBit();
return (bit) ? 9 : 4;
} else {
bit = bit_stream->ReadBit();
if (bit) {
bit = bit_stream->ReadBit();
return (bit) ? 5 : 0xa;
} else {
bit = bit_stream->ReadBit();
return (bit) ? 0xb : 3;
}
}
break;
case 5:
bit = bit_stream->ReadBit();
if (bit) {
bit = bit_stream->ReadBit();
return (bit) ? 0xd : 0xe;
} else {
bit = bit_stream->ReadBit();
return (bit) ? 6 : 0xff;
}
break;
}
return 0xff;
}
uint32_t ComputeGffDecodedSize(uint8_t* data_ptr, uint32_t data_len) {
CBitStream bs(data_ptr, data_len);
uint32_t cnt = 0;
while (bs.HasData()) {
uint8_t b = gff_decode_nibble(&bs);
if (b == 0xff) return 0;
if (b == 0xf0) return cnt; // End of file
b = gff_decode_nibble(&bs);
if (b > 0xf) return 0; // Error or odd number of nibbles
cnt++;
}
return cnt;
}
bool DecodeGff(uint8_t* data_ptr, uint32_t data_len, uint8_t* dest) {
CBitStream bs(data_ptr, data_len);
while (bs.HasData()) {
uint8_t n1 = gff_decode_nibble(&bs);
if (n1 == 0xf0) return true; // End of file
if (n1 == 0xff) return false;
uint8_t n2 = gff_decode_nibble(&bs);
if (n2 > 0xf) return false;
uint8_t byte = (n1 << 4) | n2;
*dest++ = byte;
}
return true;
}