Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 77 additions & 47 deletions py/maketranslationdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,8 +517,6 @@ def compute_huffman_coding(qstrs, translation_name, translations, f, compression
if any(ord(c) >= RARE_IDX_BASE for c in text):
raise ValueError(f"Translation contains private-use character: {text!r}")

max_translation_encoded_length = max(len(t.encode("utf-8")) for t in original_texts)
encoded_length_bits = max_translation_encoded_length.bit_length()
use_qstrs = compression_level > 3

# Non-ASCII characters by decreasing frequency. The most frequent ones are
Expand Down Expand Up @@ -615,11 +613,8 @@ def table_bytes(class_map, counts, used_words):
used_symbols = set().union(*counts.values())
used_words = sorted((w for w in words if w in used_symbols), key=len)
size = table_bytes(class_map, counts, used_words) + sum(
(
encoded_length_bits
+ encoded_bits(t, tokens[t], lens, class_map, est_qstr_bits, rare_index_bits)
+ 7
)
1 # the blob's size byte
+ (encoded_bits(t, tokens[t], lens, class_map, est_qstr_bits, rare_index_bits) + 7)
// 8
for t in texts
)
Expand Down Expand Up @@ -656,7 +651,8 @@ def table_bytes(class_map, counts, used_words):
for tok in toks:
if is_qstr(tok):
used_qstr = max(used_qstr, qstrs[tok[1]])
translation_qstr_bits = used_qstr.bit_length()
# At least 8 bits, so that a qstr escape can always pad a message's last byte.
translation_qstr_bits = max(used_qstr.bit_length(), 8)

word_end = word_start + len(words) - 1
word_code = {w: chr(word_start + i) for i, w in enumerate(words)}
Expand All @@ -665,6 +661,27 @@ def symbol_value(sym):
return ord(word_code.get(sym, sym))

nclasses = max(class_map) + 1

# compress() pads the last byte of a message (up to 7 bits) with the start
# of a longer code, so every table needs a code longer than 7 bits. A qstr
# escape counts its index bits too. If a table has no such code, split its
# longest code in two and give one half to a qstr escape.
def padding_bits(sym, length):
return length + (translation_qstr_bits if sym == SYMBOL_QSTR else 0)

for cls in range(nclasses):
table = lens.setdefault(cls, {})
if any(padding_bits(s, l) > 7 for s, l in table.items()):
continue
assert SYMBOL_QSTR not in table
if len(table) > 1:
longest = max(table, key=lambda s: table[s])
table[longest] += 1
table[SYMBOL_QSTR] = table[longest]
else:
# A lone symbol has a 1-bit code; the escape takes the other one.
table[SYMBOL_QSTR] = 1

values = []
lengths_rows = []
canonical = []
Expand Down Expand Up @@ -695,7 +712,6 @@ def symbol_value(sym):
minlen = len(words[0]) if words else 0
wlencount = [len([None for w in words if len(w) == l]) for l in range(minlen, maxlen + 1)]

f.write("#define compress_max_length_bits ({})\n".format(encoded_length_bits))
f.write("#define TRANSLATION_CLASSES {}\n".format(nclasses))
f.write("#define LENGTHS_ROW {}\n".format(lengths_row))
f.write(
Expand Down Expand Up @@ -763,18 +779,21 @@ def symbol_value(sym):
)


def decompress(encoding_table, encoded, encoded_length_bits):
def decompress(encoding_table, encoded):
"""Decode as the C decoder does (translate.c). Returns the original text."""
et = encoding_table
alphabet_size = len(et.alphabet)
word_end = et.word_start + len(et.words) - 1
end = len(encoded) * 8
pos = 0

def bititer():
for byte in encoded:
for bit in (0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1):
yield bool(byte & bit)

nextbit = bititer().__next__
def nextbit():
nonlocal pos
# Bits past the data only finish the padding symbol, which is dropped.
bit = bool(encoded[pos >> 3] & (0x80 >> (pos & 7))) if pos < end else True
pos += 1
assert pos < end + 64, "runaway decode"
return bit

def getnbits(n):
bits = 0
Expand All @@ -784,13 +803,10 @@ def getnbits(n):

dec = []
last = None
length = getnbits(encoded_length_bits)
decoded = 0

def emit_char(c):
nonlocal last, decoded
nonlocal last
dec.append(c)
decoded += len(c.encode("utf-8"))
last = c[-1]

def emit(u):
Expand All @@ -799,7 +815,7 @@ def emit(u):
else:
emit_char(chr(u))

while decoded < length:
while pos < end:
cls = et.class_map[base_class(last)]
lengths = et.lengths[cls]
bits = 0
Expand All @@ -814,13 +830,21 @@ def emit(u):
max_code = (max_code << 1) + lengths[bit_length]
searched_length += lengths[bit_length]
v = et.values[cls][searched_length + bits - max_code]
extra = 0
if v == 1:
extra = getnbits(et.translation_qstr_bits)
elif v == 2:
extra = getnbits(et.rare_index_bits)
elif v == 3:
extra = getnbits(16)
if pos > end:
break
if v == 1:
qstr_idx = getnbits(et.translation_qstr_bits)
emit_char(et.qstrs_inv[qstr_idx])
emit_char(et.qstrs_inv[extra])
elif v == 2:
emit_char(et.rare_idx_chars[getnbits(et.rare_index_bits)])
emit_char(et.rare_idx_chars[extra])
elif v == 3:
emit_char(chr(getnbits(16)))
emit_char(chr(extra))
elif et.word_start <= v <= word_end:
for c in et.words[v - et.word_start]:
emit(ord(c))
Expand All @@ -829,7 +853,7 @@ def emit(u):
return "".join(dec)


def compress(encoding_table, decompressed, encoded_length_bits, len_translation_encoded):
def compress(encoding_table, decompressed):
"""Encode a translation using the tokenization chosen in compute_huffman_coding()."""
if not isinstance(decompressed, str):
raise TypeError()
Expand All @@ -853,8 +877,6 @@ def put_code(enc, cls, sym):
enc = put_bit(enc, b == "1")
return enc

enc = put_bits(enc, len_translation_encoded, encoded_length_bits)

pos = 0
for tok in tokens:
cls = et.class_map[base_class(text[pos - 1] if pos else None)]
Expand All @@ -868,8 +890,20 @@ def put_code(enc, cls, sym):
enc = put_bits(enc, ord(tok) - RARE_IDX_BASE, et.rare_index_bits)
pos += token_len(tok)

while enc.bit_length() % 8 != 1:
enc = put_bit(enc, 0)
# Mark the end of the message: pad the last byte with the start of a code
# longer than the padding, from the table the decoder uses next. The
# decoder then reads a symbol that runs past the data and stops. Zero
# padding could decode as one more character.
pad = -(enc.bit_length() - 1) % 8
if pad:
cls = et.class_map[base_class(text[pos - 1] if pos else None)]
canon = et.canonical[cls]
longest = max(canon.values(), key=len)
if len(longest) <= pad:
longest = canon[SYMBOL_QSTR] + "0" * et.translation_qstr_bits
assert len(longest) > pad, "no code is long enough to pad with"
for b in longest[:pad]:
enc = put_bit(enc, b == "1")

r = enc.to_bytes((enc.bit_length() + 7) // 8, "big")
return r[1:]
Expand Down Expand Up @@ -955,31 +989,27 @@ def output_translation_data(encoding_table, i18ns, out):

total_text_size = 0
total_text_compressed_size = 0
max_translation_encoded_length = max(
len(translation.encode("utf-8")) for original, translation in i18ns
)
encoded_length_bits = max_translation_encoded_length.bit_length()
# Messages are referenced by index (see MP_COMPRESSED_ROM_TEXT), not by address.
# Each entry is the length of the compressed string in bytes, followed by the string.
out.write("const uint8_t translation_blob[] = {\n")
for i, translation in enumerate(i18ns):
original, translation = translation
translation_encoded = translation.encode("utf-8")
compressed = compress(
encoding_table, translation, encoded_length_bits, len(translation_encoded)
)
# The blob stores the compressed size in one byte.
assert len(compressed) < 256, ("compressed translation too long", translation)
total_text_compressed_size += 1 + len(compressed)
decompressed = decompress(encoding_table, compressed, encoded_length_bits)
compressed = compress(encoding_table, translation)
total_text_compressed_size += len(compressed) + 1
decompressed = decompress(encoding_table, compressed)
assert decompressed == translation, (decompressed, translation)
for c, replacement in C_ESCAPES.items():
decompressed = decompressed.replace(c, replacement)
formatted = ["{:d}".format(x) for x in compressed]
out.write(" {}, {}, // {}\n".format(len(compressed), ", ".join(formatted), original))
# The blob stores the compressed size in one byte.
assert len(compressed) < 256
if i == 0:
out.write("const uint8_t translation_blob[] = {\n")
out.write(
" {}, // {}\n".format(", ".join([str(len(compressed))] + formatted), original)
)
total_text_size += len(translation.encode("utf-8"))

out.write("};\n\n")
# The decoder may read one code and its fixed bits past the end of the last message.
longest = max(len(c) for table in encoding_table.canonical for c in table.values())
out.write(" {}\n}};\n\n".format(", ".join(["0"] * ((longest + 16 + 7) // 8))))
out.write("// {} bytes worth of translations\n".format(total_text_size))
out.write("// {} bytes worth of translations compressed\n".format(total_text_compressed_size))
out.write("// {} bytes saved\n".format(total_text_size - total_text_compressed_size))
Expand Down
32 changes: 6 additions & 26 deletions supervisor/shared/translate/compressed_string.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,9 @@
#include <string.h>

// The format of the compressed data is:
// - the size of the uncompressed string in UTF-8 bytes, encoded as a
// (compress_max_length_bits)-bit number. compress_max_length_bits is
// computed during dictionary generation time, and is 8 for all
// current translations except ru, which needs 9. This length excludes
// the trailing NUL, though notably decompress_length includes it.
//
// - followed by the huffman encoding of the symbols that make up the
// string. The trailing "\0" is not represented by a huffman code, but
// is implied by the length.
// - the huffman encoding of the symbols that make up the string. The last
// byte is padded with the start of a code longer than the padding, so the
// symbol that runs past the end of the data marks the end of the string.
//
// - Each symbol is coded with one of TRANSLATION_CLASSES canonical Huffman
// tables, chosen by the class of the previously decoded byte: start of
Expand Down Expand Up @@ -65,23 +59,9 @@
// parser, which picks the tokenization of each string that takes the
// fewest bits.)
//
// The "data" / "tail" construct is so that the struct's last member is a
// "flexible array". However, the _only_ member is not permitted to be
// a flexible member, so we have to declare the first byte as a separate
// member of the structure.
//
// For translations where length needs 8 bits, this saves about 1.5
// bytes per string on average compared to a structure of {uint16_t,
// flexible array}, but is also future-proofed against strings with
// UTF-8 length above 256, with a savings of about 1.375 bytes per
// string.
//
// MP_ERROR_TEXT() returns a 1-based message index cast to this pointer type;
// find_message() in translate.c turns it into a pointer.
typedef struct compressed_string {
uint8_t data;
const uint8_t tail[];
} const *mp_rom_error_text_t;
// MP_ERROR_TEXT() returns a 1-based message index cast to this pointer type.
// It is never dereferenced.
typedef const struct compressed_string *mp_rom_error_text_t;

// Class of the previously decoded byte, which selects the Huffman table for
// the next symbol. Must match base_class() in py/maketranslationdata.py.
Expand Down
Loading
Loading