pico_compress
Functions for compressing/decompressing the pico8 source
1"""Functions for compressing/decompressing the pico8 source""" 2 3from utils import * 4from pico_defs import * 5 6def print_size(name, size, limit, prefix=None, handler=None): 7 if handler and handler != True: 8 handler(prefix, name, size, limit) 9 else: 10 percent = size / limit * 100 11 fmt = "%.2f%%" if percent >= 95 else "%.0f%%" 12 if prefix: 13 name = f"{prefix} {name}" 14 name += ":" 15 print(name, size, fmt % percent) 16 17def print_code_size(size, **kwargs): 18 print_size("chars", size, 0xffff, **kwargs) 19 20def print_compressed_size(size, **kwargs): 21 print_size("compressed", size, k_code_size, **kwargs) 22 23def write_code_size(cart, handler=None, input=False): 24 print_code_size(len(cart.code), prefix="input" if input else None, handler=handler) 25 26def write_compressed_size(cart, handler=True, debug_handler=None, **opts): 27 compress_code(BinaryWriter(BytesIO()), cart.code, size_handler=handler, debug_handler=debug_handler, 28 force_compress=True, fail_on_error=False, **opts) 29 30k_old_code_table = [ 31 None, '\n', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', # 00 32 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', # 0d 33 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', # 1a 34 '!', '#', '%', '(', ')', '{', '}', '[', ']', '<', '>', # 27 35 '+', '=', '/', '*', ':', ';', '.', ',', '~', '_' # 32 36] 37 38k_old_inv_code_table = {ch: i for i, ch in enumerate(k_old_code_table)} 39 40k_old_compressed_code_header = b":c:\0" 41k_new_compressed_code_header = b"\0pxa" 42 43def update_mtf(mtf, idx, ch): 44 for ii in range(idx, 0, -1): 45 mtf[ii] = mtf[ii - 1] 46 mtf[0] = ch 47 48def uncompress_code(r: BinaryReader, max_code_size=k_code_size, size_handler=None, debug_handler=None, **_) -> str: 49 """Uncompress the code read from `r`""" 50 51 start_pos = r.pos() 52 header = r.bytes(4, allow_eof=True) 53 54 if header == k_new_compressed_code_header: 55 # the new compression format - uses bit encoding & mtf (move-to-front) 56 unc_size = r.u16() 57 com_size = r.u16() 58 59 if size_handler: 60 print_compressed_size(com_size, prefix="input", handler=size_handler) 61 62 mtf = [chr(i) for i in range(0x100)] 63 br = BinaryBitReader(r.f) 64 if debug_handler: debug_handler.init(br, str) 65 66 code = [] 67 while len(code) < unc_size: 68 if br.bit(): 69 extra = 0 70 while br.bit(): 71 extra += 1 72 idx = br.bits(4 + extra) + make_mask(4, extra) 73 74 if debug_handler: debug_handler.update(mtf[idx]) 75 code.append(mtf[idx]) 76 77 update_mtf(mtf, idx, code[-1]) 78 else: 79 offlen = (5 if br.bit() else 10) if br.bit() else 15 80 offset = br.bits(offlen) + 1 81 82 if offset == 1 and offlen != 5: 83 assert offlen == 10 84 startlen = len(code) 85 while True: 86 ch = br.bits(8) 87 if ch != 0: 88 code.append(chr(ch)) 89 else: 90 break 91 92 if debug_handler: debug_handler.update("".join(code[startlen:])) 93 else: 94 count = 3 95 while True: 96 part = br.bits(3) 97 count += part 98 if part != 7: 99 break 100 101 if debug_handler: debug_handler.update(Lz77Entry(offset, count)) 102 for _ in range(count): 103 code.append(code[-offset]) 104 105 if debug_handler: debug_handler.end() 106 assert r.pos() == start_pos + com_size 107 assert len(code) == unc_size 108 109 elif header == k_old_compressed_code_header: 110 # the old compression format - byte-based and allows very limited matching 111 unc_size = r.u16() 112 assert r.u16() == 0 # ? 113 if debug_handler: debug_handler.init(r, str) 114 115 code = [] 116 while True: 117 ch = r.u8() 118 if ch == 0x00: 119 ch2 = r.u8() 120 if ch2 == 0x00: 121 break 122 code.append(chr(ch2)) 123 if debug_handler: debug_handler.update(code[-1]) 124 125 elif ch <= 0x3b: 126 code.append(k_old_code_table[ch]) 127 if debug_handler: debug_handler.update(code[-1]) 128 129 else: 130 ch2 = r.u8() 131 count = (ch2 >> 4) + 2 132 offset = ((ch - 0x3c) << 4) + (ch2 & 0xf) 133 assert count <= offset 134 if debug_handler: debug_handler.update(Lz77Entry(offset, count)) 135 for _ in range(count): 136 code.append(code[-offset]) 137 138 if size_handler: 139 print_compressed_size(r.pos() - start_pos, prefix="input", handler=size_handler) 140 141 if debug_handler: debug_handler.end() 142 assert len(code) in (unc_size, unc_size - 1) # extra null at the end dropped? 143 144 else: 145 r.subpos(len(header)) 146 code = [chr(c) for c in r.zbytes(max_code_size, allow_eof=True)] 147 148 return "".join(code) 149 150def get_compressed_size(r, max_code_size=k_code_size): 151 start_pos = r.pos() 152 header = r.bytes(4, allow_eof=True) 153 154 if header == k_new_compressed_code_header: 155 r.u16() 156 return r.u16() # compressed size 157 158 elif header == k_old_compressed_code_header: 159 r.u16() 160 r.u16() 161 162 while True: 163 ch = r.u8() 164 if ch == 0: 165 if r.u8() == 0: 166 break 167 elif ch > 0x3b: 168 r.u8() 169 170 return r.pos() - start_pos 171 172 else: 173 r.subpos(len(header)) 174 return len(r.zbytes(max_code_size, allow_eof=True)) 175 176class Lz77Entry(Tuple): 177 """A copy of 'count' bytes starting from an 'offset' to the left of the current position.""" 178 offset = count = ... 179 180class Lz77Advance(Tuple): 181 """A strategy that advances from 'i' to 'next_i' using 'item' (a literal/lz77/etc) with cost 'cost', 182 it was preceded by Lz77Advance 'prev'. (so Lz77Advance-s form a linked list) 183 ('ctxt' is the opaque context for measure)""" 184 i = next_i = cost = ctxt = item = prev = ... 185 186class SubMatchDict(Struct): 187 """When the list of previous matches gets too long, a SubMatchDict can be used as a perf optimization, 188 grouping the list by an extra code character""" 189 dict = best_j = ... 190 191def get_lz77(code, min_c=3, max_c=0x7fff, max_o=0x7fff, measure=None, min_cost=None, 192 get_cheaper_c=None, max_o_steps=None, fast_c=None, no_repeat=False, litblock_idxs=None): 193 """a generic helper that transforms code (either bytes or str) into a sequence of items: 194 literals (bytes/chars), Lz77Entry-ies, and literal blocks. 195 min_c/max_c - min/max allowed counts in Lz77Entry-ies 196 max_o - max allowed offsets (distances) in Lz77Entry-ies 197 measure - measures the cost of a particular item. (any cost unit can be used) 198 also returns a context, an opaque value passed when measuring subsequent items 199 min_cost - the absolute minimum cost that the given number of bytes can correspond to 200 anywhere for any code. (used for perf. optimization) 201 get_cheaper_c - given a count, return a smaller count that results in less cost 202 (but may be a better choice if the next match catches up without increasing cost) 203 max_o_steps - (turn this to get_shorter_o?) - offset values that may be shorter but 204 result in less cost. 205 litblock_idxs - indices of where to enter or exit a literal block (should be precomputed) 206 """ 207 min_matches = defaultdict(list) # for each min_c-sized sequence in the code - its previous matches 208 # as either a list or a SubMatchDict 209 next_litblock = litblock_idxs.popleft() if litblock_idxs else len(code) 210 empty_code = type(code)() # e.g. "" if code is an str 211 212 def get_match_length(left, left_i, right, right_i, min_c): 213 c = min_c 214 limit = min(len(left) - left_i, len(right) - right_i) 215 while c < limit and left[left_i + c] == right[right_i + c]: 216 c += 1 217 return c 218 219 def find_match(i, min_c=min_c, max_o=max_o, matches_dict=min_matches): 220 """find the longest lz77 match at a given position""" 221 matches = matches_dict[code[i:i+min_c]] 222 223 if isinstance(matches, SubMatchDict): 224 best_c, best_j = find_match(i, min_c + 1, max_o, matches.dict) 225 if not best_c: 226 c, j = min_c, matches.best_j 227 if j >= 0: 228 if max_c != None: 229 c = min(c, max_c) 230 if no_repeat: 231 c = min(c, i - j) 232 233 if not (max_o != None and j < i - max_o): 234 best_c, best_j = c, j 235 236 return best_c, best_j 237 238 best_c, best_j = 0, -1 239 best_slice = empty_code 240 241 for j in reversed(matches): 242 if best_slice == code[j:j+best_c]: # some speed-up, esp. for cpython 243 c = get_match_length(code, i, code, j, best_c if best_c > 0 else min_c) 244 else: 245 continue 246 247 if max_c != None: 248 c = min(c, max_c) 249 if no_repeat: 250 c = min(c, i - j) 251 252 if max_o != None and j < i - max_o: 253 break 254 255 if c > best_c and c >= min_c or c == best_c and j > best_j: 256 best_c, best_j = c, j 257 best_slice = code[i:i+best_c] 258 259 return best_c, best_j 260 261 def convert_to_matches_dict(matches, min_i, c): 262 """list -> SubMatchDict""" 263 matches_dict = defaultdict(list) 264 best_j = -1 265 266 for j in matches: 267 if max_o != None and j < min_i - max_o: 268 continue 269 270 matches_dict[code[j:j+c]].append(j) 271 best_j = j 272 273 return SubMatchDict(matches_dict, best_j) 274 275 i = 0 # current position in the code 276 prev_i = 0 # previous position in the code 277 advances = deque() if measure else None # potentially worthwhile ways to go from the current or past positions 278 curr_adv = None 279 280 def add_advance(cost, ctxt, c, item): 281 """add an Lz77Advance if it's worthwhile compared to existing ones""" 282 next_i = i + c 283 adv_idx = 0 284 insert_idx = None 285 do_replace = False 286 for adv in advances: 287 if insert_idx is None: 288 if next_i == adv.next_i: 289 insert_idx, do_replace = adv_idx, True 290 elif next_i < adv.next_i: 291 insert_idx = adv_idx 292 293 if insert_idx != None: 294 adv_cost = adv.cost 295 if min_cost: 296 adv_cost -= min_cost(adv.next_i - next_i) 297 298 if cost >= adv_cost: 299 return 300 adv_idx += 1 301 302 next_adv = Lz77Advance(i, next_i, cost, ctxt, item, curr_adv) 303 if do_replace: 304 advances[insert_idx] = next_adv 305 elif insert_idx != None: 306 advances.insert(insert_idx, next_adv) 307 else: 308 advances.append(next_adv) 309 310 def add_lz77_advance(j, c): 311 item = Lz77Entry(i - j, c) 312 cost, ctxt = measure(curr_ctxt, item) 313 add_advance(curr_cost + cost, ctxt, c, item) 314 315 def get_advance_items(adv): 316 while adv: 317 yield adv.i, adv.item 318 adv = adv.prev 319 320 while i < len(code): 321 if i >= next_litblock: 322 if curr_adv: # get rid of any advances 323 yield from reversed(tuple(get_advance_items(curr_adv))) 324 curr_adv = None 325 advances.clear() 326 327 best_c = sys.maxsize 328 end_litblock = litblock_idxs.popleft() if litblock_idxs else len(code) 329 330 yield i, code[i:end_litblock] 331 i = end_litblock 332 333 next_litblock = litblock_idxs.popleft() if litblock_idxs else len(code) 334 335 else: 336 if measure: 337 curr_ctxt = curr_adv.ctxt if curr_adv else None 338 curr_cost = curr_adv.cost if curr_adv else 0 339 340 # try using a literal 341 ch_cost, ch_ctxt = measure(curr_ctxt, code[i]) 342 add_advance(curr_cost + ch_cost, ch_ctxt, 1, code[i]) 343 344 # try using a match 345 best_c, best_j = find_match(i) 346 if best_c > 0: 347 add_lz77_advance(best_j, best_c) 348 349 if get_cheaper_c: 350 # try a shorter yet cheaper match 351 cheap_c = get_cheaper_c(best_c) 352 if best_c > cheap_c >= min_c: 353 add_lz77_advance(best_j, cheap_c) 354 355 if max_o_steps: 356 # try a shorter yet closer match 357 for step in max_o_steps: 358 if i - best_j <= step: 359 break 360 361 sh_best_c, sh_best_j = find_match(i, max_o=step) 362 if sh_best_c > 0: 363 add_lz77_advance(sh_best_j, sh_best_c) 364 365 if get_cheaper_c: 366 # try a shorter yet cheaper match 367 sh_cheap_c = get_cheaper_c(sh_best_c) 368 if sh_best_c > sh_cheap_c >= min_c: 369 add_lz77_advance(sh_best_j, sh_cheap_c) 370 371 curr_adv = advances.popleft() 372 i = curr_adv.next_i 373 374 if not advances: 375 # have a best choice, flush it 376 yield from reversed(tuple(get_advance_items(curr_adv))) 377 curr_adv = None 378 379 else: # case when no 'measure' is provided - result is far less optimal 380 best_c, best_j = find_match(i) 381 if best_c > 0: 382 # check for obvious wins of not using matches 383 skip_best_c, skip_best_j = find_match(i+1) 384 if skip_best_c > best_c: 385 yield i, code[i] 386 i += 1 387 else: 388 yield i, Lz77Entry(i - best_j, best_c) 389 i += best_c 390 else: 391 yield i, code[i] 392 i += 1 393 394 if fast_c is None or best_c < fast_c: 395 # add the matches we just passed through to min_matches 396 397 for j in range(prev_i, i): 398 matches_dict = min_matches 399 c = min_c 400 matches = matches_dict[code[j:j+c]] 401 402 while isinstance(matches, SubMatchDict): 403 matches.best_j = j 404 matches_dict = matches.dict 405 c += 1 406 matches = matches_dict[code[j:j+c]] 407 408 matches.append(j) 409 410 if len(matches) > 200 and len(matches_dict) > 5 and c < min_c * 6: # shaky perf. heuristic 411 matches_dict[code[j:j+c]] = convert_to_matches_dict(matches, i, c + 1) 412 413 prev_i = i 414 415 assert not curr_adv 416 417def compress_code(w: BinaryWriter, code: str, size_handler=None, debug_handler=None, force_compress=False, 418 fail_on_error=True, fast_compress=False, old_compress=False, **_): 419 """Compress code into `w`""" 420 421 is_new = not old_compress 422 min_c = 3 423 424 if len(code) >= k_code_size or force_compress: # (>= due to null) 425 start_pos = w.pos() 426 w.bytes(k_new_compressed_code_header if is_new else k_old_compressed_code_header) 427 w.u16(len(code) & 0xffff) # only throw under fail_on_error below 428 len_pos = w.pos() 429 w.u16(0) # revised below 430 431 if is_new: 432 # the new compression scheme, measured cost is in bits 433 bw = BinaryBitWriter(w.f) 434 if debug_handler: debug_handler.init(bw, str) 435 mtf = [chr(i) for i in range(0x100)] 436 437 def mtf_cost_heuristic(ch_i): 438 mask = 1 << 4 439 count = 6 440 while ch_i >= mask: 441 mask = (mask << 1) | (1 << 4) 442 count += 2 443 if ch_i >= 16: 444 count -= 1 # heuristic, since mtf generally pays forward 445 return count 446 447 def measure(ctxt_mtf, item): 448 if isinstance(item, Lz77Entry): 449 offset_bits = max(round_up(count_significant_bits(item.offset - 1), 5), 5) 450 count_bits = (((item.count - min_c) // 7) + 1) * 3 451 cost = 2 + (offset_bits < 15) + offset_bits + count_bits 452 453 else: 454 ctxt_mtf = ctxt_mtf or mtf 455 ch_i = ctxt_mtf.index(item) 456 cost = mtf_cost_heuristic(ch_i) 457 458 ctxt_mtf = ctxt_mtf[:] # a bit wasteful, but doesn't impact perf in practice 459 update_mtf(ctxt_mtf, ch_i, item) 460 461 return cost, ctxt_mtf 462 463 def min_cost(dist): 464 # assume dist can be covered by an Lz77Entry without any overhead 465 # plus subtract possible overhead *savings* of an Lz77Entry (due to diff. in offset_bits) 466 return max((((dist - min_c) // 7) + 1) * 3 - 11, 0) 467 468 # heuristicly find at which indices we should enter/leave literal blocks 469 def preprocess_litblock_idxs(): 470 premtf = [chr(i) for i in range(0x100)] 471 pre_min_c = 4 # ignore questionable lz77s 472 last_cost_len = 0x20 473 last_cost_mask = last_cost_len - 1 474 last_costs = [0 for i in range(last_cost_len)] # cost deltas of using compression vs literal blocks 475 sum_costs = 0 476 litblock_idxs = deque() 477 478 in_litblock = False 479 def add_last_cost(i, cost): 480 nonlocal sum_costs, in_litblock 481 482 cost_i = i & last_cost_mask 483 sum_costs -= last_costs[cost_i] 484 last_costs[cost_i] = cost 485 sum_costs += cost 486 487 if i >= last_cost_len and (not in_litblock and sum_costs > 19) or (in_litblock and sum_costs < 0): 488 in_litblock = not in_litblock 489 490 ordered_costs = last_costs[cost_i + 1:] + last_costs[:cost_i + 1] 491 best_func = max if in_litblock else min 492 best_j = best_func(range(last_cost_len), key=lambda j: sum(ordered_costs[-j-1:])) 493 494 litblock_idxs.append(i - best_j) 495 496 for i, item in get_lz77(code, min_c=pre_min_c, fast_c=1): 497 if isinstance(item, Lz77Entry): 498 cost = (20 - item.count * 8) // item.count 499 for j in range(item.count): 500 add_last_cost(i + j, cost) 501 else: 502 ch_i = premtf.index(item) 503 update_mtf(premtf, ch_i, item) 504 cost = mtf_cost_heuristic(ch_i) 505 add_last_cost(i, cost - 8) 506 507 for i in range(last_cost_len): # flush litblock 508 add_last_cost(len(code) + i, 0) 509 510 return litblock_idxs 511 512 def write_match(item): 513 bw.bit(0) 514 offset_val = item.offset - 1 515 count_val = item.count - min_c 516 517 offset_bits = max(round_up(count_significant_bits(offset_val), 5), 5) 518 assert offset_bits in (5, 10, 15) 519 bw.bit(offset_bits < 15) 520 if offset_bits < 15: 521 bw.bit(offset_bits < 10) 522 bw.bits(offset_bits, offset_val) 523 524 while count_val >= 7: 525 bw.bits(3, 7) 526 count_val -= 7 527 bw.bits(3, count_val) 528 529 def write_literal(ch): 530 bw.bit(1) 531 ch_i = mtf.index(ch) 532 533 i_val = ch_i 534 i_bits = 4 535 while i_val >= (1 << i_bits): 536 bw.bit(1) 537 i_val -= 1 << i_bits 538 i_bits += 1 539 540 bw.bit(0) 541 bw.bits(i_bits, i_val) 542 543 update_mtf(mtf, ch_i, ch) 544 545 def write_litblock(str): 546 bw.bit(0); bw.bit(1); bw.bit(0) 547 bw.bits(10, 0) 548 549 for ch in str: 550 bw.bits(8, ord(ch)) 551 bw.bits(8, 0) 552 553 def get_cheaper_c(c): 554 return round_down(c - min_c, 7) - 1 + min_c 555 556 if fast_compress: 557 items = get_lz77(code, min_c=min_c, max_c=None, fast_c=16) 558 else: 559 items = get_lz77(code, min_c=min_c, max_c=None, measure=measure, min_cost=min_cost, 560 get_cheaper_c=get_cheaper_c, max_o_steps=(0x20, 0x400), litblock_idxs=preprocess_litblock_idxs()) 561 562 for i, item in items: 563 if isinstance(item, Lz77Entry): 564 write_match(item) 565 elif len(item) == 1: 566 write_literal(item) 567 else: 568 write_litblock(item) 569 if debug_handler: debug_handler.update(item) 570 571 if debug_handler: debug_handler.end() 572 bw.flush() 573 574 else: 575 # the old compression scheme, measured cost is in bytes 576 if debug_handler: debug_handler.init(w, str) 577 578 def measure(ctxt, item): 579 if isinstance(item, Lz77Entry): 580 return 2, ctxt 581 elif item in k_old_inv_code_table: 582 return 1, ctxt 583 else: 584 return 2, ctxt 585 586 def write_match(item): 587 offset_val = item.offset 588 count_val = item.count - 2 589 w.u8(0x3c + (offset_val >> 4)) 590 w.u8((offset_val & 0xf) + (count_val << 4)) 591 592 def write_literal(ch): 593 ch_i = k_old_inv_code_table.get(ch, 0) 594 595 if ch_i > 0: 596 w.u8(ch_i) 597 598 else: 599 w.u8(0) 600 w.u8(ord(ch)) 601 602 for i, item in get_lz77(code, min_c=min_c, max_c=0x11, max_o=0xc3f, no_repeat=True, 603 measure=None if fast_compress else measure): 604 if isinstance(item, Lz77Entry): 605 write_match(item) 606 else: 607 write_literal(item) 608 if debug_handler: debug_handler.update(item) 609 610 if debug_handler: debug_handler.end() 611 612 size = w.pos() - start_pos 613 if size_handler: 614 print_compressed_size(size, handler=size_handler) 615 616 if fail_on_error: 617 check(len(code) < 0x10000, "cart has too many characters!") 618 check(size <= k_code_size, "cart takes too much compressed space!") 619 620 if is_new: 621 w.setpos(len_pos) 622 w.u16(size & 0xffff) # only throw under fail_on_error above 623 624 else: 625 w.bytes(encode_p8str(code)) 626 627class CompressionTracer: 628 """a debug_handler that traces compression to a file""" 629 def __init__(m, path, lang): 630 m.file = file_create_maybe_text(path) 631 m.lang = lang 632 633 def init(m, reader, type): 634 m.reader = reader 635 m.old_pos = m.curr_pos() 636 m.code = [] 637 m.type = type 638 639 def curr_pos(m): 640 if isinstance(m.reader, (BinaryBitReader, BinaryBitWriter)): 641 return m.reader.bit_position 642 elif isinstance(m.reader, (BinaryReader, BinaryWriter)): 643 return m.reader.position 644 fail() 645 646 def escape(m, value): 647 if not isinstance(value, str): 648 value = value.decode(errors="backslashreplace") # we don't pre-escape \\, so the result isn't properly parsable 649 return '"%s"' % from_langstr(value, m.lang).replace('"', '""') # let \n/etc go unescaped, good for excel/etc 650 651 def update(m, item): 652 pos = m.curr_pos() 653 size = pos - m.old_pos 654 655 if isinstance(item, Lz77Entry): 656 for _ in range(item.count): 657 m.code.append(m.code[-item.offset]) 658 659 if m.type is str: 660 old_code = "".join(m.code[-item.count:]) 661 else: 662 old_code = bytes(m.code[-item.count:]) 663 664 m.file.write(f"{size},{m.escape(old_code)},{item.offset}:{item.count}\n") 665 666 else: 667 for ch in item: 668 m.code.append(ch) 669 m.file.write(f"{size},{m.escape(item)}\n") 670 671 m.old_pos = pos 672 673 def end(m): 674 m.file.close()
7def print_size(name, size, limit, prefix=None, handler=None): 8 if handler and handler != True: 9 handler(prefix, name, size, limit) 10 else: 11 percent = size / limit * 100 12 fmt = "%.2f%%" if percent >= 95 else "%.0f%%" 13 if prefix: 14 name = f"{prefix} {name}" 15 name += ":" 16 print(name, size, fmt % percent)
49def uncompress_code(r: BinaryReader, max_code_size=k_code_size, size_handler=None, debug_handler=None, **_) -> str: 50 """Uncompress the code read from `r`""" 51 52 start_pos = r.pos() 53 header = r.bytes(4, allow_eof=True) 54 55 if header == k_new_compressed_code_header: 56 # the new compression format - uses bit encoding & mtf (move-to-front) 57 unc_size = r.u16() 58 com_size = r.u16() 59 60 if size_handler: 61 print_compressed_size(com_size, prefix="input", handler=size_handler) 62 63 mtf = [chr(i) for i in range(0x100)] 64 br = BinaryBitReader(r.f) 65 if debug_handler: debug_handler.init(br, str) 66 67 code = [] 68 while len(code) < unc_size: 69 if br.bit(): 70 extra = 0 71 while br.bit(): 72 extra += 1 73 idx = br.bits(4 + extra) + make_mask(4, extra) 74 75 if debug_handler: debug_handler.update(mtf[idx]) 76 code.append(mtf[idx]) 77 78 update_mtf(mtf, idx, code[-1]) 79 else: 80 offlen = (5 if br.bit() else 10) if br.bit() else 15 81 offset = br.bits(offlen) + 1 82 83 if offset == 1 and offlen != 5: 84 assert offlen == 10 85 startlen = len(code) 86 while True: 87 ch = br.bits(8) 88 if ch != 0: 89 code.append(chr(ch)) 90 else: 91 break 92 93 if debug_handler: debug_handler.update("".join(code[startlen:])) 94 else: 95 count = 3 96 while True: 97 part = br.bits(3) 98 count += part 99 if part != 7: 100 break 101 102 if debug_handler: debug_handler.update(Lz77Entry(offset, count)) 103 for _ in range(count): 104 code.append(code[-offset]) 105 106 if debug_handler: debug_handler.end() 107 assert r.pos() == start_pos + com_size 108 assert len(code) == unc_size 109 110 elif header == k_old_compressed_code_header: 111 # the old compression format - byte-based and allows very limited matching 112 unc_size = r.u16() 113 assert r.u16() == 0 # ? 114 if debug_handler: debug_handler.init(r, str) 115 116 code = [] 117 while True: 118 ch = r.u8() 119 if ch == 0x00: 120 ch2 = r.u8() 121 if ch2 == 0x00: 122 break 123 code.append(chr(ch2)) 124 if debug_handler: debug_handler.update(code[-1]) 125 126 elif ch <= 0x3b: 127 code.append(k_old_code_table[ch]) 128 if debug_handler: debug_handler.update(code[-1]) 129 130 else: 131 ch2 = r.u8() 132 count = (ch2 >> 4) + 2 133 offset = ((ch - 0x3c) << 4) + (ch2 & 0xf) 134 assert count <= offset 135 if debug_handler: debug_handler.update(Lz77Entry(offset, count)) 136 for _ in range(count): 137 code.append(code[-offset]) 138 139 if size_handler: 140 print_compressed_size(r.pos() - start_pos, prefix="input", handler=size_handler) 141 142 if debug_handler: debug_handler.end() 143 assert len(code) in (unc_size, unc_size - 1) # extra null at the end dropped? 144 145 else: 146 r.subpos(len(header)) 147 code = [chr(c) for c in r.zbytes(max_code_size, allow_eof=True)] 148 149 return "".join(code)
Uncompress the code read from r
151def get_compressed_size(r, max_code_size=k_code_size): 152 start_pos = r.pos() 153 header = r.bytes(4, allow_eof=True) 154 155 if header == k_new_compressed_code_header: 156 r.u16() 157 return r.u16() # compressed size 158 159 elif header == k_old_compressed_code_header: 160 r.u16() 161 r.u16() 162 163 while True: 164 ch = r.u8() 165 if ch == 0: 166 if r.u8() == 0: 167 break 168 elif ch > 0x3b: 169 r.u8() 170 171 return r.pos() - start_pos 172 173 else: 174 r.subpos(len(header)) 175 return len(r.zbytes(max_code_size, allow_eof=True))
177class Lz77Entry(Tuple): 178 """A copy of 'count' bytes starting from an 'offset' to the left of the current position.""" 179 offset = count = ...
A copy of 'count' bytes starting from an 'offset' to the left of the current position.
181class Lz77Advance(Tuple): 182 """A strategy that advances from 'i' to 'next_i' using 'item' (a literal/lz77/etc) with cost 'cost', 183 it was preceded by Lz77Advance 'prev'. (so Lz77Advance-s form a linked list) 184 ('ctxt' is the opaque context for measure)""" 185 i = next_i = cost = ctxt = item = prev = ...
A strategy that advances from 'i' to 'next_i' using 'item' (a literal/lz77/etc) with cost 'cost', it was preceded by Lz77Advance 'prev'. (so Lz77Advance-s form a linked list) ('ctxt' is the opaque context for measure)
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])
187class SubMatchDict(Struct): 188 """When the list of previous matches gets too long, a SubMatchDict can be used as a perf optimization, 189 grouping the list by an extra code character""" 190 dict = best_j = ...
When the list of previous matches gets too long, a SubMatchDict can be used as a perf optimization, grouping the list by an extra code character
192def get_lz77(code, min_c=3, max_c=0x7fff, max_o=0x7fff, measure=None, min_cost=None, 193 get_cheaper_c=None, max_o_steps=None, fast_c=None, no_repeat=False, litblock_idxs=None): 194 """a generic helper that transforms code (either bytes or str) into a sequence of items: 195 literals (bytes/chars), Lz77Entry-ies, and literal blocks. 196 min_c/max_c - min/max allowed counts in Lz77Entry-ies 197 max_o - max allowed offsets (distances) in Lz77Entry-ies 198 measure - measures the cost of a particular item. (any cost unit can be used) 199 also returns a context, an opaque value passed when measuring subsequent items 200 min_cost - the absolute minimum cost that the given number of bytes can correspond to 201 anywhere for any code. (used for perf. optimization) 202 get_cheaper_c - given a count, return a smaller count that results in less cost 203 (but may be a better choice if the next match catches up without increasing cost) 204 max_o_steps - (turn this to get_shorter_o?) - offset values that may be shorter but 205 result in less cost. 206 litblock_idxs - indices of where to enter or exit a literal block (should be precomputed) 207 """ 208 min_matches = defaultdict(list) # for each min_c-sized sequence in the code - its previous matches 209 # as either a list or a SubMatchDict 210 next_litblock = litblock_idxs.popleft() if litblock_idxs else len(code) 211 empty_code = type(code)() # e.g. "" if code is an str 212 213 def get_match_length(left, left_i, right, right_i, min_c): 214 c = min_c 215 limit = min(len(left) - left_i, len(right) - right_i) 216 while c < limit and left[left_i + c] == right[right_i + c]: 217 c += 1 218 return c 219 220 def find_match(i, min_c=min_c, max_o=max_o, matches_dict=min_matches): 221 """find the longest lz77 match at a given position""" 222 matches = matches_dict[code[i:i+min_c]] 223 224 if isinstance(matches, SubMatchDict): 225 best_c, best_j = find_match(i, min_c + 1, max_o, matches.dict) 226 if not best_c: 227 c, j = min_c, matches.best_j 228 if j >= 0: 229 if max_c != None: 230 c = min(c, max_c) 231 if no_repeat: 232 c = min(c, i - j) 233 234 if not (max_o != None and j < i - max_o): 235 best_c, best_j = c, j 236 237 return best_c, best_j 238 239 best_c, best_j = 0, -1 240 best_slice = empty_code 241 242 for j in reversed(matches): 243 if best_slice == code[j:j+best_c]: # some speed-up, esp. for cpython 244 c = get_match_length(code, i, code, j, best_c if best_c > 0 else min_c) 245 else: 246 continue 247 248 if max_c != None: 249 c = min(c, max_c) 250 if no_repeat: 251 c = min(c, i - j) 252 253 if max_o != None and j < i - max_o: 254 break 255 256 if c > best_c and c >= min_c or c == best_c and j > best_j: 257 best_c, best_j = c, j 258 best_slice = code[i:i+best_c] 259 260 return best_c, best_j 261 262 def convert_to_matches_dict(matches, min_i, c): 263 """list -> SubMatchDict""" 264 matches_dict = defaultdict(list) 265 best_j = -1 266 267 for j in matches: 268 if max_o != None and j < min_i - max_o: 269 continue 270 271 matches_dict[code[j:j+c]].append(j) 272 best_j = j 273 274 return SubMatchDict(matches_dict, best_j) 275 276 i = 0 # current position in the code 277 prev_i = 0 # previous position in the code 278 advances = deque() if measure else None # potentially worthwhile ways to go from the current or past positions 279 curr_adv = None 280 281 def add_advance(cost, ctxt, c, item): 282 """add an Lz77Advance if it's worthwhile compared to existing ones""" 283 next_i = i + c 284 adv_idx = 0 285 insert_idx = None 286 do_replace = False 287 for adv in advances: 288 if insert_idx is None: 289 if next_i == adv.next_i: 290 insert_idx, do_replace = adv_idx, True 291 elif next_i < adv.next_i: 292 insert_idx = adv_idx 293 294 if insert_idx != None: 295 adv_cost = adv.cost 296 if min_cost: 297 adv_cost -= min_cost(adv.next_i - next_i) 298 299 if cost >= adv_cost: 300 return 301 adv_idx += 1 302 303 next_adv = Lz77Advance(i, next_i, cost, ctxt, item, curr_adv) 304 if do_replace: 305 advances[insert_idx] = next_adv 306 elif insert_idx != None: 307 advances.insert(insert_idx, next_adv) 308 else: 309 advances.append(next_adv) 310 311 def add_lz77_advance(j, c): 312 item = Lz77Entry(i - j, c) 313 cost, ctxt = measure(curr_ctxt, item) 314 add_advance(curr_cost + cost, ctxt, c, item) 315 316 def get_advance_items(adv): 317 while adv: 318 yield adv.i, adv.item 319 adv = adv.prev 320 321 while i < len(code): 322 if i >= next_litblock: 323 if curr_adv: # get rid of any advances 324 yield from reversed(tuple(get_advance_items(curr_adv))) 325 curr_adv = None 326 advances.clear() 327 328 best_c = sys.maxsize 329 end_litblock = litblock_idxs.popleft() if litblock_idxs else len(code) 330 331 yield i, code[i:end_litblock] 332 i = end_litblock 333 334 next_litblock = litblock_idxs.popleft() if litblock_idxs else len(code) 335 336 else: 337 if measure: 338 curr_ctxt = curr_adv.ctxt if curr_adv else None 339 curr_cost = curr_adv.cost if curr_adv else 0 340 341 # try using a literal 342 ch_cost, ch_ctxt = measure(curr_ctxt, code[i]) 343 add_advance(curr_cost + ch_cost, ch_ctxt, 1, code[i]) 344 345 # try using a match 346 best_c, best_j = find_match(i) 347 if best_c > 0: 348 add_lz77_advance(best_j, best_c) 349 350 if get_cheaper_c: 351 # try a shorter yet cheaper match 352 cheap_c = get_cheaper_c(best_c) 353 if best_c > cheap_c >= min_c: 354 add_lz77_advance(best_j, cheap_c) 355 356 if max_o_steps: 357 # try a shorter yet closer match 358 for step in max_o_steps: 359 if i - best_j <= step: 360 break 361 362 sh_best_c, sh_best_j = find_match(i, max_o=step) 363 if sh_best_c > 0: 364 add_lz77_advance(sh_best_j, sh_best_c) 365 366 if get_cheaper_c: 367 # try a shorter yet cheaper match 368 sh_cheap_c = get_cheaper_c(sh_best_c) 369 if sh_best_c > sh_cheap_c >= min_c: 370 add_lz77_advance(sh_best_j, sh_cheap_c) 371 372 curr_adv = advances.popleft() 373 i = curr_adv.next_i 374 375 if not advances: 376 # have a best choice, flush it 377 yield from reversed(tuple(get_advance_items(curr_adv))) 378 curr_adv = None 379 380 else: # case when no 'measure' is provided - result is far less optimal 381 best_c, best_j = find_match(i) 382 if best_c > 0: 383 # check for obvious wins of not using matches 384 skip_best_c, skip_best_j = find_match(i+1) 385 if skip_best_c > best_c: 386 yield i, code[i] 387 i += 1 388 else: 389 yield i, Lz77Entry(i - best_j, best_c) 390 i += best_c 391 else: 392 yield i, code[i] 393 i += 1 394 395 if fast_c is None or best_c < fast_c: 396 # add the matches we just passed through to min_matches 397 398 for j in range(prev_i, i): 399 matches_dict = min_matches 400 c = min_c 401 matches = matches_dict[code[j:j+c]] 402 403 while isinstance(matches, SubMatchDict): 404 matches.best_j = j 405 matches_dict = matches.dict 406 c += 1 407 matches = matches_dict[code[j:j+c]] 408 409 matches.append(j) 410 411 if len(matches) > 200 and len(matches_dict) > 5 and c < min_c * 6: # shaky perf. heuristic 412 matches_dict[code[j:j+c]] = convert_to_matches_dict(matches, i, c + 1) 413 414 prev_i = i 415 416 assert not curr_adv
a generic helper that transforms code (either bytes or str) into a sequence of items: literals (bytes/chars), Lz77Entry-ies, and literal blocks. min_c/max_c - min/max allowed counts in Lz77Entry-ies max_o - max allowed offsets (distances) in Lz77Entry-ies measure - measures the cost of a particular item. (any cost unit can be used) also returns a context, an opaque value passed when measuring subsequent items min_cost - the absolute minimum cost that the given number of bytes can correspond to anywhere for any code. (used for perf. optimization) get_cheaper_c - given a count, return a smaller count that results in less cost (but may be a better choice if the next match catches up without increasing cost) max_o_steps - (turn this to get_shorter_o?) - offset values that may be shorter but result in less cost. litblock_idxs - indices of where to enter or exit a literal block (should be precomputed)
418def compress_code(w: BinaryWriter, code: str, size_handler=None, debug_handler=None, force_compress=False, 419 fail_on_error=True, fast_compress=False, old_compress=False, **_): 420 """Compress code into `w`""" 421 422 is_new = not old_compress 423 min_c = 3 424 425 if len(code) >= k_code_size or force_compress: # (>= due to null) 426 start_pos = w.pos() 427 w.bytes(k_new_compressed_code_header if is_new else k_old_compressed_code_header) 428 w.u16(len(code) & 0xffff) # only throw under fail_on_error below 429 len_pos = w.pos() 430 w.u16(0) # revised below 431 432 if is_new: 433 # the new compression scheme, measured cost is in bits 434 bw = BinaryBitWriter(w.f) 435 if debug_handler: debug_handler.init(bw, str) 436 mtf = [chr(i) for i in range(0x100)] 437 438 def mtf_cost_heuristic(ch_i): 439 mask = 1 << 4 440 count = 6 441 while ch_i >= mask: 442 mask = (mask << 1) | (1 << 4) 443 count += 2 444 if ch_i >= 16: 445 count -= 1 # heuristic, since mtf generally pays forward 446 return count 447 448 def measure(ctxt_mtf, item): 449 if isinstance(item, Lz77Entry): 450 offset_bits = max(round_up(count_significant_bits(item.offset - 1), 5), 5) 451 count_bits = (((item.count - min_c) // 7) + 1) * 3 452 cost = 2 + (offset_bits < 15) + offset_bits + count_bits 453 454 else: 455 ctxt_mtf = ctxt_mtf or mtf 456 ch_i = ctxt_mtf.index(item) 457 cost = mtf_cost_heuristic(ch_i) 458 459 ctxt_mtf = ctxt_mtf[:] # a bit wasteful, but doesn't impact perf in practice 460 update_mtf(ctxt_mtf, ch_i, item) 461 462 return cost, ctxt_mtf 463 464 def min_cost(dist): 465 # assume dist can be covered by an Lz77Entry without any overhead 466 # plus subtract possible overhead *savings* of an Lz77Entry (due to diff. in offset_bits) 467 return max((((dist - min_c) // 7) + 1) * 3 - 11, 0) 468 469 # heuristicly find at which indices we should enter/leave literal blocks 470 def preprocess_litblock_idxs(): 471 premtf = [chr(i) for i in range(0x100)] 472 pre_min_c = 4 # ignore questionable lz77s 473 last_cost_len = 0x20 474 last_cost_mask = last_cost_len - 1 475 last_costs = [0 for i in range(last_cost_len)] # cost deltas of using compression vs literal blocks 476 sum_costs = 0 477 litblock_idxs = deque() 478 479 in_litblock = False 480 def add_last_cost(i, cost): 481 nonlocal sum_costs, in_litblock 482 483 cost_i = i & last_cost_mask 484 sum_costs -= last_costs[cost_i] 485 last_costs[cost_i] = cost 486 sum_costs += cost 487 488 if i >= last_cost_len and (not in_litblock and sum_costs > 19) or (in_litblock and sum_costs < 0): 489 in_litblock = not in_litblock 490 491 ordered_costs = last_costs[cost_i + 1:] + last_costs[:cost_i + 1] 492 best_func = max if in_litblock else min 493 best_j = best_func(range(last_cost_len), key=lambda j: sum(ordered_costs[-j-1:])) 494 495 litblock_idxs.append(i - best_j) 496 497 for i, item in get_lz77(code, min_c=pre_min_c, fast_c=1): 498 if isinstance(item, Lz77Entry): 499 cost = (20 - item.count * 8) // item.count 500 for j in range(item.count): 501 add_last_cost(i + j, cost) 502 else: 503 ch_i = premtf.index(item) 504 update_mtf(premtf, ch_i, item) 505 cost = mtf_cost_heuristic(ch_i) 506 add_last_cost(i, cost - 8) 507 508 for i in range(last_cost_len): # flush litblock 509 add_last_cost(len(code) + i, 0) 510 511 return litblock_idxs 512 513 def write_match(item): 514 bw.bit(0) 515 offset_val = item.offset - 1 516 count_val = item.count - min_c 517 518 offset_bits = max(round_up(count_significant_bits(offset_val), 5), 5) 519 assert offset_bits in (5, 10, 15) 520 bw.bit(offset_bits < 15) 521 if offset_bits < 15: 522 bw.bit(offset_bits < 10) 523 bw.bits(offset_bits, offset_val) 524 525 while count_val >= 7: 526 bw.bits(3, 7) 527 count_val -= 7 528 bw.bits(3, count_val) 529 530 def write_literal(ch): 531 bw.bit(1) 532 ch_i = mtf.index(ch) 533 534 i_val = ch_i 535 i_bits = 4 536 while i_val >= (1 << i_bits): 537 bw.bit(1) 538 i_val -= 1 << i_bits 539 i_bits += 1 540 541 bw.bit(0) 542 bw.bits(i_bits, i_val) 543 544 update_mtf(mtf, ch_i, ch) 545 546 def write_litblock(str): 547 bw.bit(0); bw.bit(1); bw.bit(0) 548 bw.bits(10, 0) 549 550 for ch in str: 551 bw.bits(8, ord(ch)) 552 bw.bits(8, 0) 553 554 def get_cheaper_c(c): 555 return round_down(c - min_c, 7) - 1 + min_c 556 557 if fast_compress: 558 items = get_lz77(code, min_c=min_c, max_c=None, fast_c=16) 559 else: 560 items = get_lz77(code, min_c=min_c, max_c=None, measure=measure, min_cost=min_cost, 561 get_cheaper_c=get_cheaper_c, max_o_steps=(0x20, 0x400), litblock_idxs=preprocess_litblock_idxs()) 562 563 for i, item in items: 564 if isinstance(item, Lz77Entry): 565 write_match(item) 566 elif len(item) == 1: 567 write_literal(item) 568 else: 569 write_litblock(item) 570 if debug_handler: debug_handler.update(item) 571 572 if debug_handler: debug_handler.end() 573 bw.flush() 574 575 else: 576 # the old compression scheme, measured cost is in bytes 577 if debug_handler: debug_handler.init(w, str) 578 579 def measure(ctxt, item): 580 if isinstance(item, Lz77Entry): 581 return 2, ctxt 582 elif item in k_old_inv_code_table: 583 return 1, ctxt 584 else: 585 return 2, ctxt 586 587 def write_match(item): 588 offset_val = item.offset 589 count_val = item.count - 2 590 w.u8(0x3c + (offset_val >> 4)) 591 w.u8((offset_val & 0xf) + (count_val << 4)) 592 593 def write_literal(ch): 594 ch_i = k_old_inv_code_table.get(ch, 0) 595 596 if ch_i > 0: 597 w.u8(ch_i) 598 599 else: 600 w.u8(0) 601 w.u8(ord(ch)) 602 603 for i, item in get_lz77(code, min_c=min_c, max_c=0x11, max_o=0xc3f, no_repeat=True, 604 measure=None if fast_compress else measure): 605 if isinstance(item, Lz77Entry): 606 write_match(item) 607 else: 608 write_literal(item) 609 if debug_handler: debug_handler.update(item) 610 611 if debug_handler: debug_handler.end() 612 613 size = w.pos() - start_pos 614 if size_handler: 615 print_compressed_size(size, handler=size_handler) 616 617 if fail_on_error: 618 check(len(code) < 0x10000, "cart has too many characters!") 619 check(size <= k_code_size, "cart takes too much compressed space!") 620 621 if is_new: 622 w.setpos(len_pos) 623 w.u16(size & 0xffff) # only throw under fail_on_error above 624 625 else: 626 w.bytes(encode_p8str(code))
Compress code into w
628class CompressionTracer: 629 """a debug_handler that traces compression to a file""" 630 def __init__(m, path, lang): 631 m.file = file_create_maybe_text(path) 632 m.lang = lang 633 634 def init(m, reader, type): 635 m.reader = reader 636 m.old_pos = m.curr_pos() 637 m.code = [] 638 m.type = type 639 640 def curr_pos(m): 641 if isinstance(m.reader, (BinaryBitReader, BinaryBitWriter)): 642 return m.reader.bit_position 643 elif isinstance(m.reader, (BinaryReader, BinaryWriter)): 644 return m.reader.position 645 fail() 646 647 def escape(m, value): 648 if not isinstance(value, str): 649 value = value.decode(errors="backslashreplace") # we don't pre-escape \\, so the result isn't properly parsable 650 return '"%s"' % from_langstr(value, m.lang).replace('"', '""') # let \n/etc go unescaped, good for excel/etc 651 652 def update(m, item): 653 pos = m.curr_pos() 654 size = pos - m.old_pos 655 656 if isinstance(item, Lz77Entry): 657 for _ in range(item.count): 658 m.code.append(m.code[-item.offset]) 659 660 if m.type is str: 661 old_code = "".join(m.code[-item.count:]) 662 else: 663 old_code = bytes(m.code[-item.count:]) 664 665 m.file.write(f"{size},{m.escape(old_code)},{item.offset}:{item.count}\n") 666 667 else: 668 for ch in item: 669 m.code.append(ch) 670 m.file.write(f"{size},{m.escape(item)}\n") 671 672 m.old_pos = pos 673 674 def end(m): 675 m.file.close()
a debug_handler that traces compression to a file
652 def update(m, item): 653 pos = m.curr_pos() 654 size = pos - m.old_pos 655 656 if isinstance(item, Lz77Entry): 657 for _ in range(item.count): 658 m.code.append(m.code[-item.offset]) 659 660 if m.type is str: 661 old_code = "".join(m.code[-item.count:]) 662 else: 663 old_code = bytes(m.code[-item.count:]) 664 665 m.file.write(f"{size},{m.escape(old_code)},{item.offset}:{item.count}\n") 666 667 else: 668 for ch in item: 669 m.code.append(ch) 670 m.file.write(f"{size},{m.escape(item)}\n") 671 672 m.old_pos = pos