This repository has been archived by the owner on May 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
lzss.js
393 lines (320 loc) · 13 KB
/
lzss.js
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
* YI Mirrorless Firmware Tools
* Author: Mario Guggenberger <[email protected]>
* Licensed under the GPLv3
*/
'use strict';
const S = require('string');
const LOOKUP_BUFFER_SIZE = 0x1000;
const LOOKUP_DATA_MAX_INDEX = 0x0FFF;
const LOOKUP_DATA_MAX_LENGTH = 0x0F;
const LOOKUP_MIN_LENGTH = 3;
const LOOKUP_MAX_LENGTH = LOOKUP_DATA_MAX_LENGTH + LOOKUP_MIN_LENGTH;
class RingBuffer {
constructor(size, initialIndex = 0) {
this.buffer = Buffer.alloc(size);
this.bufferIndex = initialIndex;
this.bufferLevel = 0;
}
get length() {
return this.buffer.length;
}
get innerBuffer() {
return this.buffer;
}
get index() {
return this.bufferIndex;
}
readUInt8(index) {
let wrappedIndex = index;
if (this.bufferLevel < this.buffer.length) {
// Wrap offset around fillLevel
const shift = this.bufferIndex - this.bufferLevel;
wrappedIndex = ((index - shift) % this.buffer.length % this.bufferLevel) + shift + this.buffer.length;
}
return this.buffer.readUInt8(wrappedIndex % this.buffer.length);
}
appendUInt8(value) {
this.buffer.writeUInt8(value, this.bufferIndex);
this.bufferIndex = ++this.bufferIndex % this.buffer.length;
if (this.bufferLevel < this.buffer.length) {
this.bufferLevel++;
}
}
toString(encoding) {
return this.buffer.toString(encoding, this.bufferIndex, this.buffer.length)
+ this.buffer.toString(encoding, 0, this.bufferIndex);
}
getSequentialBuffer() {
return Buffer.concat([
this.buffer.slice(this.bufferIndex, this.buffer.length),
this.buffer.slice(0, this.bufferIndex),
]);
}
find(byteArray, length) {
if (length === undefined) {
length = byteArray.length;
}
const check = (x) => {
for (let y = 1; y < length; y++) {
if (this.readUInt8((x + y) % this.buffer.length) !== byteArray[y]) {
return y - 1;
}
}
return length - 1;
};
let maxLength = 0;
let maxLengthIndex = -1;
for (let x = 2; x < this.bufferLevel; x++) {
// Search backwards from the most recently written byte
const searchIndex = (this.bufferIndex - x + this.buffer.length) % this.buffer.length;
// Check the first value and if it matched, check all remaining ones
if (this.readUInt8(searchIndex) === byteArray[0]) {
const length = check(searchIndex) + 1;
if (length > maxLength) {
maxLength = length;
maxLengthIndex = searchIndex;
}
}
}
return [maxLength, maxLengthIndex];
}
}
const decodeFlagByte = (flagByte) => {
const flags = [];
for (let bitIndex = 0; bitIndex < 8; bitIndex++) {
const copyByte = (flagByte >> bitIndex) & 1 === 1;
flags.push(copyByte);
}
return flags;
};
const encodeFlagByte = (flags) => {
let flagByte = 0;
if (flags.length !== 8) {
throw `invalid flags array`;
}
flags.forEach((flag, index) => {
if (flag) {
flagByte |= 1 << index;
}
});
return flagByte;
};
const toBitString = (value, bits) => {
return S(value.toString(2)).padLeft(bits, '0');
};
const toHexString = (value, bytes) => {
return S(value.toString(16)).padLeft(bytes * 2, '0').toString().toUpperCase();
};
const logFlags = (position, flagByte, flags) => {
const flagsByteBinaryString = toBitString(flagByte, 8);
const flagsString = flags.map((flag) => flag ? 'C' : 'L').reduce((a, b) => a + b);
console.log(`${position} flag: 0x${toHexString(flagByte, 1)}/${flagsByteBinaryString} => ${flagsString}`);
};
const logByteCopy = (position, byte) => {
console.log(`${position} copy: 0x${byte.toString(16)}`);
};
const logLookup = (position, lookupByte1, lookupByte2, index, length) => {
const lookup = lookupByte1 << 8 | lookupByte2;
console.log(`${position} lookup: 0x${toHexString(lookup, 2)}/${toBitString(lookup, 16)}`
+ ` => ${toBitString(index, 12)} ${toBitString(length - 3, 4)}`
+ ` => ${length}@${index}`);
};
/**
* Decompresses compressed data in section 0 of the firmware.
* @param buffer
* @returns {Buffer}
*/
function decompress(buffer, options) {
const VERBOSE = false;
if (options === undefined) {
options = {};
}
let bufferByteIndex = 0;
const lookupBuffer = new RingBuffer(LOOKUP_BUFFER_SIZE, LOOKUP_BUFFER_SIZE - LOOKUP_MAX_LENGTH);
const outputBuffer = Buffer.alloc(buffer.length * 10); // the compression is probably way less effective so lets just hope this size is enough (else we have to implement dynamic resizing)
let outputBufferByteIndex = 0;
const readNextByte = () => {
return buffer.readUInt8(bufferByteIndex++);
};
const writeNextByte = (value) => {
if (outputBufferByteIndex === outputBuffer.length) {
throw 'Output buffer is full, cannot write more data';
}
outputBuffer.writeUInt8(value, outputBufferByteIndex++);
};
while (bufferByteIndex < buffer.length) {
// Read the flag byte, whose bits are flags that tell which bytes are to be copied directly, and which bytes
// are lookup information.
const flagByte = readNextByte();
// Detect end of section
// All sections are padded to 2048 byte chunks with 0x00
// A 0x00 flag byte with 8 zero lookups is highly unlikely, so we use that for now to detect the section end
// If a section fits better into the 2048 byte alignment, this detection fails
// TODO find out how we can determine the actual end (where the length of a section is stored)
if (flagByte === 0x00) {
const oldBufferByteIndex = bufferByteIndex;
let zeroCount = 0;
for (let x = 0; x < 16; x++) {
if (readNextByte() === 0x00) {
zeroCount++;
} else {
break;
}
}
if (zeroCount === 16) {
console.log(`Section end detected at ${bufferByteIndex - 9}`);
break;
}
// End has not been detected, so restore the old buffer index and continue processing the data
bufferByteIndex = oldBufferByteIndex;
}
// Parse the flag byte into a boolean flag array
const flags = decodeFlagByte(flagByte);
if (VERBOSE) {
logFlags(bufferByteIndex - 1, flagByte, flags);
}
for (let copyByte of flags) {
if (copyByte) {
// Just copy the byte into the output
const byte = readNextByte();
if (VERBOSE) {
logByteCopy(bufferByteIndex - 1, byte);
}
// Write byte into output and lookup buffer
writeNextByte(byte);
lookupBuffer.appendUInt8(byte);
} else {
// Read lookup data bytes (2 bytes)
const lookup1 = readNextByte();
const lookup2 = readNextByte();
// length is 4 bits, index 12 bits
// The bytes are ordered big endian
const lookupIndex = lookup1 | ((lookup2 & 0xF0) << 4);
const lookupLength = (lookup2 & 0x0F) + LOOKUP_MIN_LENGTH;
if (VERBOSE) {
logLookup(bufferByteIndex - 2, lookup1, lookup2, lookupIndex, lookupLength);
}
// Read bytes from lookup buffer
const lookupBytes = [];
for (let x = 0; x < lookupLength; x++) {
let bufferByte = lookupBuffer.readUInt8(lookupIndex + x);
lookupBytes.push(bufferByte);
}
if (options.lookupCallback) {
options.lookupCallback([bufferByteIndex - 2, outputBufferByteIndex, lookupIndex, lookupLength, lookupBuffer.bufferIndex]);
}
lookupBytes.forEach(byte => {
lookupBuffer.appendUInt8(byte);
writeNextByte(byte);
});
}
}
}
return outputBuffer.slice(0, outputBufferByteIndex);
}
function compress(buffer, options) {
const VERBOSE = false;
if (options === undefined) {
options = {};
}
let bufferByteIndex = 0;
const lookupBuffer = new RingBuffer(LOOKUP_BUFFER_SIZE, LOOKUP_BUFFER_SIZE - LOOKUP_MAX_LENGTH);
const outputBuffer = Buffer.alloc(buffer.length * 2); // compressed data should never be larger than the uncompressed data but just to be save we use a larger buffer
let outputBufferByteIndex = 0;
const readNextByte = () => {
return buffer.readUInt8(bufferByteIndex++);
};
const writeNextByte = (value) => {
if (outputBufferByteIndex === outputBuffer.length) {
throw 'Output buffer is full, cannot write more data';
}
outputBuffer.writeUInt8(value, outputBufferByteIndex++);
};
let lastPercent = 0;
while (bufferByteIndex < buffer.length) {
const flags = [];
// A temporary output buffer that holds all bytes while the flags byte is built
const outputBuffer = [];
// Calculate progress
const percent = Math.round(bufferByteIndex / buffer.length * 100);
if (percent > lastPercent) {
lastPercent = percent;
if (percent > 1) {
process.stdout.write(`\r`);
}
process.stdout.write(`${percent}%`);
if (percent === 100) {
console.log(); // add line break
}
}
// Every 8 flags we write the flag byte and the output buffer to the output
while (flags.length < 8) {
const remainingInputBytes = buffer.length - bufferByteIndex;
if (remainingInputBytes === 0) {
// Fill up flags & write buffer and exit compression loop
console.log(`early end detected`);
while (flags.length < 8) {
flags.push(true);
outputBuffer.push(0);
}
break;
}
// Read 18 bytes (the max number of bytes we can lookup)
const lookup = [];
for (let i = 0; i < Math.min(LOOKUP_MAX_LENGTH, remainingInputBytes); i++) {
const byte = readNextByte();
lookup.push(byte);
}
// Reset the read index, the previous reads were just lookaheads
bufferByteIndex -= lookup.length;
// Check if we find the lookup data in the lookup buffer
// We start with the longest sequence and decrease the length step by step until we have a match or
// in the worst case no match at all
const [length, index] = lookupBuffer.find(lookup);
if (index === -1 || length < LOOKUP_MIN_LENGTH) {
// Lookup was unsuccessful, we just copy the byte into the output
flags.push(true); // true === copy byte
const nextByte = readNextByte();
outputBuffer.push(nextByte);
lookupBuffer.appendUInt8(nextByte);
if (VERBOSE) {
logByteCopy(outputBufferByteIndex + outputBuffer.length, nextByte);
}
} else {
// Lookup success
flags.push(false); // false === lookup bytes
if (index > LOOKUP_DATA_MAX_INDEX) {
throw `invalid lookup index size ${index}`;
}
if (length > LOOKUP_MAX_LENGTH) {
throw `invalid lookup length ${length}`;
}
const lookup1 = index & 0xFF;
const lookup2 = ((index & 0xF00) >> 4) | ((length - LOOKUP_MIN_LENGTH) & 0x0F);
outputBuffer.push(lookup1);
outputBuffer.push(lookup2);
if (VERBOSE) {
logLookup(outputBufferByteIndex + outputBuffer.length - 1, lookup1, lookup2, index, length);
}
if (options.lookupCallback) {
options.lookupCallback([outputBufferByteIndex + outputBuffer.length - 1, bufferByteIndex, index, length, lookupBuffer.bufferIndex]);
}
for (let i = 0; i < length; i++) {
lookupBuffer.appendUInt8(readNextByte());
}
}
}
// We have 8 flags, so we can now write the flags byte...
const flagByte = encodeFlagByte(flags);
if (VERBOSE) {
logFlags(outputBufferByteIndex, flagByte, flags);
}
writeNextByte(flagByte);
// ... and the pertaining data (data & lookup)
outputBuffer.forEach(byte => writeNextByte(byte));
}
return outputBuffer.slice(0, outputBufferByteIndex);
}
exports.decompress = decompress;
exports.compress = compress;