#!/usr/bin/env python3 """Generates crates/ec-aac/src/ps_huff.rs from the Parametric Stereo Huffman code-length tables as tabulated in FFmpeg's libavcodec/aacpsdata.c (the `aacps_huff_tabs` array: one (symbol, code length) pair per codeword, in the order ISO/IEC 14496-3 subpart 8 lists them). Usage: gen-ps-huff.py """ import re import sys src, out = sys.argv[1], sys.argv[2] text = open(src).read() sizes = [int(x) for x in re.search(r"huff_sizes\[\] = \{([^}]*)\}", text).group(1).split(",")] body = re.search(r"aacps_huff_tabs\[\]\[2\] = \{(.*?)\n\};", text, re.S).group(1) pairs = [(int(a), int(b)) for a, b in re.findall(r"\{\s*(\d+),\s*(\d+)\s*\}", body)] offsets = [int(x) for x in re.search(r"huff_offset\[\] = \{([^}]*)\}", text).group(1).replace("\n", " ").split(",") if x.strip()] assert len(sizes) == 10 and len(offsets) == 10, (sizes, offsets) assert sum(sizes) == len(pairs), (sum(sizes), len(pairs)) names = [ "IID_DF1", "IID_DT1", "IID_DF0", "IID_DT0", "ICC_DF", "ICC_DT", "IPD_DF", "IPD_DT", "OPD_DF", "OPD_DT", ] lines = [ "//! Parametric Stereo Huffman code-length tables (ISO/IEC 14496-3 subpart 8).", "//!", "//! Generated by `scripts/aac-tables/gen-ps-huff.py` from the `aacps_huff_tabs`", "//! array of FFmpeg's `libavcodec/aacpsdata.c`: one `(symbol, code length)` pair", "//! per codeword, in table order. Codes are canonical: within each length they", "//! are assigned in table order (see `ps_data::build_codes`). Do not edit by hand.", "", "/// Added to a decoded symbol to give the parameter value, per table.", "pub const OFFSETS: [i32; 10] = [%s];" % ", ".join(str(o) for o in offsets), ] pos = 0 for i, (name, n) in enumerate(zip(names, sizes)): chunk = pairs[pos:pos + n] pos += n lines.append("/// `%s`: %d codewords." % (name, n)) lines.append("pub const T_%s: [(u8, u8); %d] = [" % (name, n)) for j in range(0, len(chunk), 6): lines.append(" " + " ".join("(%d, %d)," % p for p in chunk[j:j + 6])) lines.append("];") lines.append("/// The ten tables indexed by the `T_*` order above.") lines.append("pub const TABLES: [&[(u8, u8)]; 10] = [%s];" % ", ".join("&T_%s" % n for n in names)) open(out, "w").write("\n".join(lines) + "\n") print("wrote", out, "tables", len(sizes), "codewords", len(pairs)) # The two stereo-band index maps (ISO/IEC 14496-3 tables 8.48/8.49), from the same file. def kmap(name): m = re.search(r"%s\[\] = \{(.*?)\};" % name, text, re.S) return [int(x) for x in re.findall(r"-?\d+", m.group(1))] k20, k34 = kmap("ff_k_to_i_20"), kmap("ff_k_to_i_34") assert len(k20) == 71 and len(k34) == 91, (len(k20), len(k34)) extra = [ "/// Table 8.48: sub-subband `k` (0..71) to the 20-band parameter index.", "pub const K_TO_I_20: [u8; 71] = [%s];" % ", ".join(str(v) for v in k20), "/// Table 8.49: sub-subband `k` (0..91) to the 34-band parameter index.", "pub const K_TO_I_34: [u8; 91] = [%s];" % ", ".join(str(v) for v in k34), ] open(out, "a").write("\n".join(extra) + "\n")