Repository navigation
Expand file tree
/
Copy pathCompressionHelper.py
More file actions
509 lines (429 loc) · 16.3 KB
/
Copy pathCompressionHelper.py
File metadata and controls
509 lines (429 loc) · 16.3 KB
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import gzip
import lzma
import struct
import tempfile
from typing import Callable, Dict, Iterable, Tuple, Union
import brotli
import lz4.block
from ..enums.BundleFile import CompressionFlags
ByteString = Union[bytes, bytearray, memoryview]
GZIP_MAGIC: bytes = b"\x1f\x8b"
BROTLI_MAGIC: bytes = b"brotli"
LZMA_DICT_SIZE = 0x800000
LZMA_PROPERTIES = 0x5D
def create_lzma_decompressor(properties: ByteString) -> lzma.LZMADecompressor:
props, dict_size = struct.unpack("<BI", properties[:5])
lc = props % 9
remainder = props // 9
pb = remainder // 5
lp = remainder % 5
return lzma.LZMADecompressor(
format=lzma.FORMAT_RAW,
filters=[
{
"id": lzma.FILTER_LZMA1,
"dict_size": dict_size,
"lc": lc,
"lp": lp,
"pb": pb,
}
],
)
def create_lzma_compressor() -> lzma.LZMACompressor:
return lzma.LZMACompressor(
format=lzma.FORMAT_RAW,
filters=[
{
"id": lzma.FILTER_LZMA1,
"dict_size": LZMA_DICT_SIZE,
"lc": 3,
"lp": 0,
"pb": 2,
"mode": lzma.MODE_NORMAL,
"mf": lzma.MF_BT4,
"nice_len": 123,
}
],
)
# LZMA
def decompress_lzma(data: ByteString, read_decompressed_size: bool = False) -> bytes:
"""decompresses lzma-compressed data
:param data: compressed data
:type data: ByteString
:raises _lzma.LZMAError: Compressed data ended before the end-of-stream marker was reached
:return: uncompressed data
:rtype: bytes
"""
dec = create_lzma_decompressor(data)
data_offset = 13 if read_decompressed_size else 5
return dec.decompress(data[data_offset:])
def compress_lzma(data: ByteString, write_decompressed_size: bool = False) -> bytes:
"""compresses data via lzma (unity specific)
The current static settings may not be the best solution,
but they are the most commonly used values and should therefore be enough for the time being.
:param data: uncompressed data
:type data: ByteString
:return: compressed data
:rtype: bytes
"""
compressor = create_lzma_compressor()
compressed_data = compressor.compress(data) + compressor.flush()
cdl = len(compressed_data)
if write_decompressed_size:
return struct.pack(f"<BIQ{cdl}s", LZMA_PROPERTIES, LZMA_DICT_SIZE, len(data), compressed_data)
else:
return struct.pack(f"<BI{cdl}s", LZMA_PROPERTIES, LZMA_DICT_SIZE, compressed_data)
# LZ4
def decompress_lz4(data: ByteString, uncompressed_size: int) -> bytes: # LZ4M/LZ4HC
"""decompresses lz4-compressed data
:param data: compressed data
:type data: ByteString
:param uncompressed_size: size of the uncompressed data
:type uncompressed_size: int
:raises _block.LZ4BlockError: Decompression failed: corrupt input or insufficient space in destination buffer.
:return: uncompressed data
:rtype: bytes
"""
return lz4.block.decompress(data, uncompressed_size)
def compress_lz4(data: ByteString) -> bytes: # LZ4M/LZ4HC
"""compresses data via lz4.block
:param data: uncompressed data
:type data: ByteString
:return: compressed data
:rtype: bytes
"""
return lz4.block.compress(data, mode="high_compression", compression=9, store_size=False)
# Brotli
def decompress_brotli(data: ByteString) -> bytes:
"""decompresses brotli-compressed data
:param data: compressed data
:type data: ByteString
:raises brotli.error: BrotliDecompress failed
:return: uncompressed data
:rtype: bytes
"""
return brotli.decompress(data)
def compress_brotli(data: ByteString) -> bytes:
"""compresses data via brotli
:param data: uncompressed data
:type data: ByteString
:return: compressed data
:rtype: bytes
"""
return brotli.compress(data)
# GZIP
def decompress_gzip(data: ByteString) -> bytes:
"""decompresses gzip-compressed data
:param data: compressed data
:type data: ByteString
:raises OSError: Not a gzipped file
:return: uncompressed data
:rtype: bytes
"""
return gzip.decompress(data)
def compress_gzip(data: ByteString) -> bytes:
"""compresses data via gzip
The current static settings may not be the best solution,
but they are the most commonly used values and should therefore be enough for the time being.
:param data: uncompressed data
:type data: ByteString
:return: compressed data
:rtype: bytes
"""
return gzip.compress(data)
def chunk_based_compress(data: ByteString, block_info_flag: int) -> Tuple[ByteString, list]:
"""compresses AssetBundle data based on the block_info_flag
LZ4/LZ4HC will be chunk-based compression
:param data: uncompressed data
:type data: ByteString
:param block_info_flag: block info flag
:type block_info_flag: int
:return: compressed data and block info
:rtype: tuple
"""
switch = block_info_flag & 0x3F
chunk_size = None
compress_func = None
if switch == 0: # NONE
return data, [(len(data), len(data), block_info_flag)]
if switch in COMPRESSION_MAP:
compress_func = COMPRESSION_MAP[switch]
else:
raise NotImplementedError(f"No compression function in the CompressionHelper.COMPRESSION_MAP for {switch}")
if switch in COMPRESSION_CHUNK_SIZE_MAP:
chunk_size = COMPRESSION_CHUNK_SIZE_MAP[switch]
else:
raise NotImplementedError(f"No chunk size in the CompressionHelper.COMPRESSION_CHUNK_SIZE_MAP for {switch}")
block_info = []
uncompressed_data_size = len(data)
compressed_file_data = bytearray()
p = 0
while uncompressed_data_size > chunk_size:
compressed_data = compress_func(data[p : p + chunk_size])
if len(compressed_data) > chunk_size:
compressed_file_data.extend(data[p : p + chunk_size])
block_info.append(
(
chunk_size,
chunk_size,
block_info_flag ^ switch,
)
)
else:
compressed_file_data.extend(compressed_data)
block_info.append(
(
chunk_size,
len(compressed_data),
block_info_flag,
)
)
p += chunk_size
uncompressed_data_size -= chunk_size
if uncompressed_data_size > 0:
compressed_data = compress_func(data[p:])
if len(compressed_data) > uncompressed_data_size:
compressed_file_data.extend(data[p:])
block_info.append(
(
uncompressed_data_size,
uncompressed_data_size,
block_info_flag ^ switch,
)
)
else:
compressed_file_data.extend(compressed_data)
block_info.append(
(
uncompressed_data_size,
len(compressed_data),
block_info_flag,
)
)
return bytes(compressed_file_data), block_info
def chunk_based_compress_iter(chunks: Iterable[ByteString], block_info_flag: int) -> Tuple[ByteString, list]:
"""compresses AssetBundle data from an iterable of chunks.
This avoids creating one huge temporary uncompressed bytes blob before compression.
:param chunks: iterable of uncompressed data chunks
:type chunks: Iterable[ByteString]
:param block_info_flag: block info flag
:type block_info_flag: int
:return: compressed data and block info
:rtype: tuple
"""
switch = block_info_flag & 0x3F
if switch == 0: # NONE
raw_data = bytearray()
total_size = 0
for chunk in chunks:
if not chunk:
continue
raw_data.extend(chunk)
total_size += len(chunk)
return raw_data, [(total_size, total_size, block_info_flag)]
if switch in COMPRESSION_MAP:
compress_func = COMPRESSION_MAP[switch]
else:
raise NotImplementedError(f"No compression function in the CompressionHelper.COMPRESSION_MAP for {switch}")
if switch in COMPRESSION_CHUNK_SIZE_MAP:
chunk_size = COMPRESSION_CHUNK_SIZE_MAP[switch]
else:
raise NotImplementedError(f"No chunk size in the CompressionHelper.COMPRESSION_CHUNK_SIZE_MAP for {switch}")
block_info = []
compressed_file_data = bytearray()
pending = bytearray()
for chunk in chunks:
if not chunk:
continue
view = memoryview(chunk)
p = 0
while p < len(view):
to_copy = min(chunk_size - len(pending), len(view) - p)
pending.extend(view[p : p + to_copy])
p += to_copy
if len(pending) == chunk_size:
compressed_data = compress_func(pending)
if len(compressed_data) > chunk_size:
compressed_file_data.extend(pending)
block_info.append((chunk_size, chunk_size, block_info_flag ^ switch))
else:
compressed_file_data.extend(compressed_data)
block_info.append((chunk_size, len(compressed_data), block_info_flag))
pending.clear()
if pending:
pending_size = len(pending)
compressed_data = compress_func(pending)
if len(compressed_data) > pending_size:
compressed_file_data.extend(pending)
block_info.append((pending_size, pending_size, block_info_flag ^ switch))
else:
compressed_file_data.extend(compressed_data)
block_info.append((pending_size, len(compressed_data), block_info_flag))
return compressed_file_data, block_info
def _compress_lzma_iter_to_file(chunks: Iterable[ByteString], block_info_flag: int, out) -> list:
block_size_limit = COMPRESSION_CHUNK_SIZE_MAP[CompressionFlags.LZMA]
header = struct.pack("<BI", LZMA_PROPERTIES, LZMA_DICT_SIZE)
block_info = []
with tempfile.TemporaryFile() as raw_block:
compressor = None
block_start = 0
uncompressed_size = 0
def start_block():
nonlocal compressor, block_start, uncompressed_size
raw_block.seek(0)
raw_block.truncate()
block_start = out.tell()
out.write(header)
compressor = create_lzma_compressor()
uncompressed_size = 0
def finish_block():
nonlocal compressor, uncompressed_size
assert compressor is not None
out.write(compressor.flush())
compressed_size = out.tell() - block_start
if compressed_size > uncompressed_size:
out.seek(block_start)
out.truncate()
raw_block.seek(0)
while True:
data = raw_block.read(1024 * 1024)
if not data:
break
out.write(data)
block_info.append(
(
uncompressed_size,
uncompressed_size,
block_info_flag ^ int(CompressionFlags.LZMA),
)
)
else:
block_info.append((uncompressed_size, compressed_size, block_info_flag))
compressor = None
uncompressed_size = 0
for chunk in chunks:
if not chunk:
continue
view = memoryview(chunk)
position = 0
while position < len(view):
if compressor is None:
start_block()
copy_size = min(
block_size_limit - uncompressed_size,
len(view) - position,
1024 * 1024,
)
piece = view[position : position + copy_size]
raw_block.write(piece)
compressed = compressor.compress(piece)
if compressed:
out.write(compressed)
position += copy_size
uncompressed_size += copy_size
if uncompressed_size == block_size_limit:
finish_block()
if compressor is not None:
finish_block()
return block_info
def chunk_based_compress_iter_to_file(
chunks: Iterable[ByteString], block_info_flag: int, out_path: str
) -> list:
"""Like chunk_based_compress_iter but writes compressed output to
*out_path* instead of accumulating in an in-memory bytearray.
Returns *block_info* list only. The compressed payload is on disk.
"""
switch = block_info_flag & 0x3F
with open(out_path, "wb") as out:
if switch == 0: # NONE
total_size = 0
for chunk in chunks:
if not chunk:
continue
out.write(chunk)
total_size += len(chunk)
return [(total_size, total_size, block_info_flag)]
if switch == CompressionFlags.LZMA:
return _compress_lzma_iter_to_file(chunks, block_info_flag, out)
if switch in COMPRESSION_MAP:
compress_func = COMPRESSION_MAP[switch]
else:
raise NotImplementedError(
f"No compression function in the CompressionHelper.COMPRESSION_MAP for {switch}"
)
if switch in COMPRESSION_CHUNK_SIZE_MAP:
chunk_size = COMPRESSION_CHUNK_SIZE_MAP[switch]
else:
raise NotImplementedError(
f"No chunk size in the CompressionHelper.COMPRESSION_CHUNK_SIZE_MAP for {switch}"
)
block_info: list = []
pending = bytearray()
for chunk in chunks:
if not chunk:
continue
view = memoryview(chunk)
p = 0
while p < len(view):
to_copy = min(chunk_size - len(pending), len(view) - p)
pending.extend(view[p : p + to_copy])
p += to_copy
if len(pending) == chunk_size:
compressed_data = compress_func(pending)
if len(compressed_data) > chunk_size:
out.write(pending)
block_info.append((chunk_size, chunk_size, block_info_flag ^ switch))
else:
out.write(compressed_data)
block_info.append((chunk_size, len(compressed_data), block_info_flag))
pending.clear()
if pending:
pending_size = len(pending)
compressed_data = compress_func(pending)
if len(compressed_data) > pending_size:
out.write(pending)
block_info.append((pending_size, pending_size, block_info_flag ^ switch))
else:
out.write(compressed_data)
block_info.append((pending_size, len(compressed_data), block_info_flag))
return block_info
def decompress_lzham(data: ByteString, uncompressed_size: int) -> bytes:
raise NotImplementedError("Custom compression or unimplemented LZHAM (removed by Unity) encountered!")
DECOMPRESSION_MAP: Dict[Union[int, CompressionFlags], Callable[[ByteString, int], ByteString]] = {
CompressionFlags.NONE: lambda cd, _ucs: cd,
CompressionFlags.LZMA: lambda cd, _ucs: decompress_lzma(cd),
CompressionFlags.LZ4: decompress_lz4,
CompressionFlags.LZ4HC: decompress_lz4,
CompressionFlags.LZHAM: decompress_lzham,
}
COMPRESSION_MAP: Dict[Union[int, CompressionFlags], Callable[[ByteString], ByteString]] = {
CompressionFlags.NONE: lambda cd: cd,
CompressionFlags.LZMA: compress_lzma,
CompressionFlags.LZ4: compress_lz4,
CompressionFlags.LZ4HC: compress_lz4,
}
COMPRESSION_CHUNK_SIZE_MAP: Dict[Union[int, CompressionFlags], int] = {
CompressionFlags.NONE: 0xFFFFFFFF,
CompressionFlags.LZMA: 0xFFFFFFFF,
CompressionFlags.LZ4: 0x00020000,
CompressionFlags.LZ4HC: 0x00020000,
}
__all__ = (
"compress_brotli",
"compress_gzip",
"compress_lz4",
"compress_lzma",
"create_lzma_compressor",
"create_lzma_decompressor",
"decompress_brotli",
"decompress_gzip",
"decompress_lz4",
"decompress_lzma",
"decompress_lzham",
"chunk_based_compress",
"chunk_based_compress_iter",
"chunk_based_compress_iter_to_file",
"COMPRESSION_MAP",
"DECOMPRESSION_MAP",
"COMPRESSION_CHUNK_SIZE_MAP",
)