diff --git a/py/maketranslationdata.py b/py/maketranslationdata.py index 3d1a7959a87..79dc4b5cd52 100644 --- a/py/maketranslationdata.py +++ b/py/maketranslationdata.py @@ -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 @@ -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 ) @@ -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)} @@ -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 = [] @@ -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( @@ -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 @@ -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): @@ -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 @@ -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)) @@ -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() @@ -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)] @@ -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:] @@ -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)) diff --git a/supervisor/shared/translate/compressed_string.h b/supervisor/shared/translate/compressed_string.h index 2fdf5503ae3..c8071e29239 100644 --- a/supervisor/shared/translate/compressed_string.h +++ b/supervisor/shared/translate/compressed_string.h @@ -11,15 +11,9 @@ #include // 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 @@ -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. diff --git a/supervisor/shared/translate/translate.c b/supervisor/shared/translate/translate.c index 314a1a4e7f4..9188132070a 100644 --- a/supervisor/shared/translate/translate.c +++ b/supervisor/shared/translate/translate.c @@ -25,16 +25,6 @@ void serial_write_compressed(mp_rom_error_text_t compressed) { extern const uint8_t translation_blob[]; -// MP_ERROR_TEXT() is a 1-based index into translation_blob. Each entry is a -// length byte followed by the compressed string. -static mp_rom_error_text_t find_message(mp_rom_error_text_t compressed) { - const uint8_t *p = translation_blob; - for (uintptr_t n = (uintptr_t)compressed - 1; n > 0; n--) { - p += *p + 1; - } - return (mp_rom_error_text_t)(p + 1); -} - static void get_word(int n, const uint8_t **pos, const uint8_t **end) { int len = minlen; int i = 0; @@ -49,15 +39,43 @@ static void get_word(int n, const uint8_t **pos, const uint8_t **end) { *end = *pos + len; } -static void put_utf8(vstr_t *vstr, unsigned u) { +// Where the decoded bytes go. With out == NULL they are only counted. +typedef struct { + char *out; + size_t len; + uint8_t last; +} sink_t; + +static void put_byte(sink_t *s, unsigned c) { + if (s->out) { + s->out[s->len] = c; + } + s->len++; + s->last = c; +} + +// UTF-8 encode a code point up to U+FFFF. +static void put_char(sink_t *s, unsigned u) { + if (u >= 0x80) { + if (u >= 0x800) { + put_byte(s, 0xe0 | (u >> 12)); + put_byte(s, 0x80 | ((u >> 6) & 0x3f)); + } else { + put_byte(s, 0xc0 | (u >> 6)); + } + u = 0x80 | (u & 0x3f); + } + put_byte(s, u); +} + +static void put_symbol(sink_t *s, unsigned u) { if (word_start <= u && u <= word_end) { const uint8_t *pos, *end; get_word(u - word_start, &pos, &end); - // note that at present, entries in the words table are - // guaranteed not to represent words themselves, so this adds - // at most 1 level of recursive call + // entries in the words table do not contain words themselves, so + // this adds at most 1 level of recursive call for (; pos < end; pos++) { - put_utf8(vstr, *pos); + put_symbol(s, *pos); } return; } @@ -65,7 +83,7 @@ static void put_utf8(vstr_t *vstr, unsigned u) { if (alphabet_size > 0 && u >= 0x80 && u < 0x80 + alphabet_size) { u = alphabet[u - 0x80]; } - vstr_add_char(vstr, u); + put_char(s, u); } // The Huffman table used for the next symbol depends on the class of the last @@ -94,21 +112,6 @@ static translation_class_t base_class(uint8_t last) { return CLASS_OTHER; } -// Takes a pointer from find_message(). Includes the trailing NUL. -static uint16_t message_length(mp_rom_error_text_t message) { - #ifndef NO_QSTR - #if (compress_max_length_bits <= 8) - return 1 + (message->data >> (8 - compress_max_length_bits)); - #else - return 1 + ((message->data * 256 + message->tail[0]) >> (16 - compress_max_length_bits)); - #endif - #endif -} - -uint16_t decompress_length(mp_rom_error_text_t compressed) { - return message_length(find_message(compressed)); -} - typedef struct { const uint8_t *ptr; uint8_t bit; @@ -132,19 +135,28 @@ static int get_nbits(bitstream_state_t *st, int n) { return r; } -// note: the vstr must be a fixed-buffer vstr that matches the decompressed length of the string -static void decompress_vstr(mp_rom_error_text_t compressed, vstr_t *decompressed) { +// Decode message number `compressed` (1-based) into out, or only count its +// bytes when out is NULL. Returns the length without the trailing NUL. +// +// Each blob entry is a size byte, then the Huffman-coded message. The +// message length is not stored. Instead, the unused bits of the last byte +// hold the start of a code that is longer than them, so the symbol that +// would end past the data marks the end of the message. +static size_t decode(mp_rom_error_text_t compressed, char *out) { + const uint8_t *p = translation_blob; + for (size_t n = (uintptr_t)compressed; --n;) { + p += *p + 1; + } + const uint8_t *end = p + 1 + *p; bitstream_state_t b = { - .ptr = &(compressed->data) + (compress_max_length_bits >> 3), - .bit = 1 << (7 - ((compress_max_length_bits) & 0x7)), + .ptr = p + 1, + .bit = 0x80, }; + // The start of a string is classed like a space. + sink_t s = { .out = out, .len = 0, .last = ' ' }; - size_t alloc = decompressed->alloc - 1; - // Stop one early because the last byte is always NULL. - for (; decompressed->len < alloc;) { - // The start of a string is classed like a space. - uint8_t last = decompressed->len ? (uint8_t)decompressed->buf[decompressed->len - 1] : ' '; - uint8_t cls = class_map[base_class(last)]; + while (b.ptr < end) { + uint8_t cls = class_map[base_class(s.last)]; const uint8_t *len_row = lengths + cls * LENGTHS_ROW; uint32_t bits = 0; @@ -161,28 +173,48 @@ static void decompress_vstr(mp_rom_error_text_t compressed, vstr_t *decompressed searched_length += len_row[bit_length]; } unsigned v = values[values_offset[cls] + searched_length + bits - max_code]; + unsigned extra_bits = 0; + if (v == SYMBOL_QSTR) { + extra_bits = translation_qstr_bits; + } else if (rare_index_count > 0 && v == SYMBOL_RARE_INDEX) { + extra_bits = rare_index_bits; + } else if (rare_raw_count > 0 && v == SYMBOL_RARE_RAW) { + extra_bits = 16; + } + unsigned extra = get_nbits(&b, extra_bits); + if (b.ptr + (b.bit != 0x80) > end) { + // This symbol is the end-of-message padding. + break; + } if (v == SYMBOL_QSTR) { - qstr q = get_nbits(&b, translation_qstr_bits); - vstr_add_str(decompressed, qstr_str(q)); + size_t l; + const byte *d = qstr_data(extra, &l); + while (l--) { + put_byte(&s, *d++); + } } else if (rare_index_count > 0 && v == SYMBOL_RARE_INDEX) { // A non-ASCII character outside the dense alphabet, by table index. - vstr_add_char(decompressed, rare_chars[get_nbits(&b, rare_index_bits)]); + put_char(&s, rare_chars[extra]); } else if (rare_raw_count > 0 && v == SYMBOL_RARE_RAW) { // A non-ASCII character used only once, as a raw code point. - vstr_add_char(decompressed, get_nbits(&b, 16)); + put_char(&s, extra); } else { - put_utf8(decompressed, v); + put_symbol(&s, v); } } + if (out) { + out[s.len] = 0; + } + return s.len; } +uint16_t decompress_length(mp_rom_error_text_t compressed) { + return decode(compressed, NULL) + 1; +} char *decompress(mp_rom_error_text_t compressed, char *decompressed) { - mp_rom_error_text_t message = find_message(compressed); - vstr_t vstr; - vstr_init_fixed_buf(&vstr, message_length(message), decompressed); - decompress_vstr(message, &vstr); - return vstr_null_terminated_str(&vstr); + decode(compressed, decompressed); + return decompressed; } #if CIRCUITPY_TRANSLATE_OBJECT == 1