forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

gen_dts_tables.py334 lines, 16.0 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Generate crates/ec-dts/src/tables_data.rs from ETSI TS 102 114.
3
4Source: ETSI TS 102 114 V1.6.1 (2019-08), "DTS Coherent Acoustics; Core and
5Extensions with Additional Profiles", free from
6https://www.etsi.org/deliver/etsi_ts/102100_102199/102114/01.06.01_60/ts_102114v010601p.pdf
7
8Usage:
9 pdftotext -layout ts_102114v010601p.pdf ts102114.txt
10 python3 -I tools/gen_dts_tables.py ts102114.txt \
11 crates/ec-dts/src/tables_data.rs crates/ec-dts/tests/spec_ts102114_tables.txt
12
13The spec text (decimal commas, "1 926" style thousands separators) is parsed
14here; nothing is read from any other decoder. Two files are written:
15
16* tables_data.rs: the Rust statics, after the conversions listed below.
17* spec_ts102114_tables.txt: the raw numbers exactly as the spec prints them
18 (one line per table, with clause references). tests/spec_tables.rs applies
19 the same conversions independently in Rust and asserts equality with the
20 statics, so the committed numbers are checked against the committed text.
21
22Clauses used (all normative):
23 Table 5-26 Number of quantization levels per ABITS -> QUANT_LEVELS
24 Table 5-27 Scale factor adjustment index (ADJ) -> SCALE_FACTOR_ADJ
25 D.1.1, D.1.2 6-bit / 7-bit scale factor quantization -> SCALE_FACTOR_QUANT6/7
26 D.2.1, D.2.2 Lossy / lossless quantization step sizes -> LOSSY_QUANT, LOSSLESS_QUANT
27 D.5.x Huffman code books (A3 .. G129, SA129..SE129,
28 A12..E12, A4..D4) -> HUFF_SRC
29 D.8 (col. 5) 128x LFE interpolation FIR -> LFE_FIR_128
30 D.9 1024 tap FIR for X96 synthesis QMF -> FIR_64
31 D.11 Downmix scale factor look-up (DmixTable) -> DMIXTABLE
32
33Conversions (implementation layout choices, not spec content):
34 * invalid entries -> 0; tables are padded to their power-of-two length with 0.
35 * QUANT_LEVELS: ABITS 0 -> 1 (spec: 0, never used as a divisor here);
36 "33 or 32", "65 or 64", "129 or 128" -> the power of two.
37 * HUFF_SRC: codes sorted by left-aligned code value (the spec codes are
38 canonical), stored as (symbol, length) with symbol = level + offset where
39 offset is 1,2,3,4,6,8,12,16,32,64 for the 3..129 level books, ABITS-1 for
40 the 12 level books, level for the 4 level books, level+64 for SA..SE129.
41 Books are laid out in the order consumed by huff.rs.
42 * LFE_FIR_128: spec column (512 symmetric taps) read in the polyphase order
43 k = 4q+p -> index [q, 128+q, 255-q, 127-q][p].
44 * FIR_64: round-half-up(coef * 2^29), sign negated unless (index/32) % 4 == 0
45 (QMF cosine modulation sign), index 0-based (spec "Coef #" is 1-based).
46 * DMIXTABLE: a leading 0 then the 241 DmixTable entries.
47"""
48import re
49import sys
50from decimal import Decimal, ROUND_HALF_UP
51
52
53def D(s):
54 return Decimal(s.replace(',', '.'))
55
56
57def main():
58 spec_path, out_rs, out_spec = sys.argv[1:4]
59 with open(spec_path, encoding='utf-8') as f:
60 L = f.read().split('\n')
61 assert any('V1.6.1 (2019-08)' in l for l in L[:3000]), 'spec is not V1.6.1'
62
63 def find(pat, start=0):
64 for i in range(start, len(L)):
65 if re.match(pat, L[i]):
66 return i
67 raise SystemExit('not found: ' + pat)
68
69 # ---- section boundaries (annex D, after the table of contents)
70 a_d = find(r'^Annex D \(normative\):\s*$', 1000)
71 s = {}
72 for key, pat in [('d11', r'^D\.1\.1 '), ('d12', r'^D\.1\.2 '), ('d2', r'^D\.2 '),
73 ('d21', r'^D\.2\.1 '), ('d22', r'^D\.2\.2 '), ('d3', r'^D\.3 '),
74 ('d4', r'^D\.4 '), ('d5', r'^D\.5 '), ('d6', r'^D\.6 '),
75 ('d7', r'^D\.7 '), ('d8', r'^D\.8 '), ('d9', r'^D\.9 '),
76 ('d10', r'^D\.10 '), ('d11x', r'^D\.11 ')]:
77 s[key] = find(pat, a_d)
78
79 raw = [] # (name, clause, [strings])
80
81 # ---- Table 5-26 (quantization levels)
82 t526 = find(r'^\s*Table 5-26: Selection of Quantization Levels', 1000)
83 ql = {}
84 for l in L[t526:t526 + 40]:
85 m = re.match(r'^\s+(\d+)\s+(\d[\d ]*?)(?:\s+or\s+(\d+))?\s{2,}', l)
86 if m and int(m.group(1)) <= 26 and m.group(2).replace(' ', '').isdigit():
87 ql[int(m.group(1))] = (m.group(3) or m.group(2)).replace(' ', '')
88 assert sorted(ql) == list(range(27)), sorted(ql)
89 raw.append(('QUANT_LEVELS', 'Table 5-26', [ql[i] for i in range(27)]))
90
91 # ---- Table 5-27 (ADJ)
92 t527 = find(r'^\s*Table 5-27: Scale Factor Adjustment Index', 1000)
93 adj = []
94 for l in L[t527:t527 + 12]:
95 m = re.match(r'^\s+([0-3])\s+(\d,\d+)\s*$', l)
96 if m:
97 adj.append(m.group(2).replace(',', '.'))
98 assert len(adj) == 4
99 raw.append(('SCALE_FACTOR_ADJ', 'Table 5-27', adj))
100
101 # ---- D.1.1 / D.1.2 scale factor quantization (index, level, dB triples)
102 def triples(a, b, n):
103 d = {}
104 for l in L[a:b]:
105 t = l.split()
106 if len(t) % 3 or not t or not t[0].isdigit():
107 continue
108 for k in range(0, len(t), 3):
109 if t[k].isdigit() and (t[k + 1].isdigit() or t[k + 1] == 'invalid'):
110 d[int(t[k])] = t[k + 1]
111 assert sorted(d) == list(range(n)), (len(d), n)
112 return [d[i] for i in range(n)]
113 raw.append(('SCALE_FACTOR_QUANT6', 'D.1.1', triples(s['d11'], s['d12'], 64)))
114 raw.append(('SCALE_FACTOR_QUANT7', 'D.1.2', triples(s['d12'], s['d2'], 128)))
115
116 # ---- D.2.x step sizes (index, step x 2^22, nominal)
117 def steps(a, b):
118 d = {}
119 for l in L[a:b]:
120 m = re.match(r'^\s+(\d+)\s+(\d+|invalid)\s+(\S+)\s*$', l)
121 if m:
122 d[int(m.group(1))] = m.group(2)
123 assert sorted(d) == list(range(32)), len(d)
124 return [d[i] for i in range(32)]
125 raw.append(('LOSSY_QUANT', 'D.2.1', steps(s['d21'], s['d22'])))
126 raw.append(('LOSSLESS_QUANT', 'D.2.2', steps(s['d22'], s['d3'])))
127
128 # ---- D.5 Huffman code books
129 books = {} # table name -> [(level, length, code)]
130 names = [] # in document order
131 n_cols = 0
132 cur = []
133 fresh = False
134 for l in L[s['d5']:s['d6']]:
135 titles = re.findall(r'Table ([A-Z]{1,2}\d+)\b', l)
136 if titles:
137 # titles on consecutive lines (A33 / B33 C33) form one block
138 cur = cur + titles if fresh else titles
139 fresh = True
140 n_cols = len(cur)
141 for t in titles:
142 assert t not in books
143 books[t] = []
144 names.append(t)
145 continue
146 t = l.split()
147 if not t or not all(re.match(r'^-?\d+$', x) for x in t):
148 continue
149 row = []
150 k = 0
151 while k < len(t):
152 lv, ln, cd = t[k], t[k + 1], t[k + 2]
153 k += 3
154 while k < len(t) and re.match(r'^\d{3}$', t[k]):
155 cd += t[k]
156 k += 1
157 row.append((int(lv), int(ln), int(cd)))
158 # a ragged first row (table A33 starts one line before B33 and C33)
159 # (and its tail: the first column has ended, the others have one row left)
160 fresh = False
161 if n_cols == 1: # one table printed in several column segments
162 books[cur[0]].extend(row)
163 continue
164 assert len(row) == n_cols or (len(row) < n_cols and cur[0] == 'A33'), (l, n_cols, cur)
165 fresh = False
166 cols = cur[:len(row)] if not books[cur[0]] else cur[n_cols - len(row):]
167 for tname, e in zip(cols, row):
168 books[tname].append(e)
169 # The printed Table D65 (D.5.11) stops at level +-30: the rows for +-31 and
170 # +-32 are missing from the standard's text. They are the only symbols
171 # absent, so their codes are the unassigned part of the code space, which
172 # must be exactly four 15-bit words; following the printed pairs (the
173 # positive level has the code one above its negative, and a larger |level|
174 # has the lower code) they are -32, 32, -31, 31 in ascending order.
175 e = books['D65']
176 assert sorted(lv for lv, _, _ in e) == [x for x in range(-30, 31)], 'D65 layout changed'
177 used = set()
178 for _, ln, cd in e:
179 used.update(range(cd << (15 - ln), (cd + 1) << (15 - ln)))
180 free = [c for c in range(1 << 15) if c not in used]
181 assert free == [28848, 28849, 28850, 28851], free
182 for lv, c in zip([-32, 32, -31, 31], free):
183 e.append((lv, 15, c))
184 # Table D129 (D.5.12) prints level -37 as "37" (sign lost), so +37 appears
185 # twice; as in every other printed pair the negative level has the lower code.
186 e = books['D129']
187 dup = sorted((x for x in e if x[0] == 37), key=lambda x: x[2])
188 assert len(dup) == 2 and dup[0][1] == dup[1][1] and dup[1][2] == dup[0][2] + 1, dup
189 e[e.index(dup[0])] = (-37, dup[0][1], dup[0][2])
190 for tname in names:
191 e = books[tname]
192 kraft = sum(Decimal(2) ** -ln for _, ln, _ in e)
193 assert kraft == 1, (tname, kraft)
194 assert len(set(lv for lv, _, _ in e)) == len(e), (tname, len(e), sorted(lv for lv, _, _ in e))
195
196 def book(tname, nlev, offset):
197 e = books[tname]
198 assert len(e) == nlev, (tname, len(e), nlev)
199 return [(lv + offset, ln, cd) for lv, ln, cd in e]
200
201 order = [] # (table name, symbol offset) in huff.rs consumption order
202 for nlev, groups, off in [(3, 'A', 1), (5, 'ABC', 2), (7, 'ABC', 3), (9, 'ABC', 4),
203 (13, 'ABC', 6), (17, 'ABCDEFG', 8), (25, 'ABCDEFG', 12),
204 (33, 'ABCDEFG', 16), (65, 'ABCDEFG', 32), (129, 'ABCDEFG', 64)]:
205 for g in groups:
206 order.append((g + str(nlev), nlev, off))
207 for g in 'ABCDE':
208 order.append((g + '12', 12, 0)) # level column is ABITS 1..12 -> symbol ABITS-1
209 for g in 'ABCDE':
210 order.append(('S' + g + '129', 129, 64))
211 for g in 'ABCD':
212 order.append((g + '4', 4, 0))
213 assert sorted(n for n, _, _ in order) == sorted(names), set(names) ^ set(n for n, _, _ in order)
214 huff = []
215 huff_raw = []
216 for tname, nlev, off in order:
217 if nlev == 12:
218 e = [(lv - 1, ln, cd) for lv, ln, cd in books[tname]]
219 assert len(e) == 12
220 else:
221 e = book(tname, nlev, off)
222 e.sort(key=lambda x: x[2] << (32 - x[1]))
223 huff.extend((sym, ln) for sym, ln, _ in e)
224 huff_raw.append((tname, [(lv, ln, cd) for lv, ln, cd in books[tname]]))
225 if tname == 'D65':
226 huff_raw[-1] = (tname + ' [rows +-31,+-32 completed, see generator]', huff_raw[-1][1])
227 assert len(huff) == 2709, len(huff)
228
229 # ---- D.8 128x LFE FIR (last column) and D.9 FIR_64
230 lfe = []
231 for l in L[s['d8']:s['d9']]:
232 t = l.split()
233 if len(t) == 5 and t[0].isdigit() and 'e' in t[1]:
234 lfe.append(t[4].replace(',', '.'))
235 assert len(lfe) == 512
236 raw.append(('LFE_FIR_128', 'D.8 (128 x Interpolation column)', lfe))
237
238 fir = {}
239 for l in L[s['d9']:s['d10']]:
240 for m in re.finditer(r'(?<![\d,])(\d{1,3}(?: \d{3})?)\s+(-?\d,\d+e[-+]?\d+)', l):
241 fir[int(m.group(1).replace(' ', ''))] = m.group(2).replace(',', '.')
242 assert sorted(fir) == list(range(1, 1025))
243 raw.append(('FIR_64', 'D.9', [fir[i] for i in range(1, 1025)]))
244
245 # ---- D.11 downmix look-up
246 dm = {}
247 for l in L[s['d11x']:]:
248 m = re.match(r'^\s+(\d+)\s+(-?[\d,]+)\s+([\d,]+)\s+(\d+)\s+(\d+|N/A)\s+(\d+|N/A)\s*$', l)
249 if m:
250 dm[int(m.group(1))] = m.group(4)
251 assert sorted(dm) == list(range(241)), len(dm)
252 raw.append(('DMIXTABLE', 'D.11 (DmixTable column)', [dm[i] for i in range(241)]))
253
254 # ---- write the raw spec numbers
255 with open(out_spec, 'w') as f:
256 f.write('# Numbers exactly as printed in ETSI TS 102 114 V1.6.1 (2019-08), Annex D / clause 5.\n')
257 f.write('# Written by tools/gen_dts_tables.py; decimal commas written as points.\n')
258 f.write('# table NAME | clause | values... (invalid entries kept as the word "invalid")\n')
259 f.write('# huff TABLE | clause | level:length:code ... (code = value of the code word)\n')
260 for name, cl, vals in raw:
261 f.write('table %s | %s | %s\n' % (name, cl, ' '.join(vals)))
262 for tname, e in huff_raw:
263 tn, _, note = tname.partition(' ')
264 f.write('huff %s | D.5%s | %s\n' % (tn, ' ' + note if note else '',
265 ' '.join('%d:%d:%d' % x for x in e)))
266
267 # ---- convert and write the Rust file
268 out = []
269
270 def emit(rname, ty, vals, doc, per=12):
271 out.append('/// %s' % doc)
272 out.append('pub static %s: [%s; %d] = [' % (rname, ty, len(vals)))
273 for k in range(0, len(vals), per):
274 out.append(' ' + ', '.join(str(v) for v in vals[k:k + per]) + ',')
275 out.append('];')
276 out.append('')
277
278 def ints(vals, n):
279 v = [0 if x == 'invalid' else int(x.replace(' ', '')) for x in vals]
280 return v + [0] * (n - len(v))
281 R = {n: v for n, _, v in raw}
282 out.append('//! Constant tables for DTS Coherent Acoustics (ETSI TS 102 114).')
283 out.append('//!')
284 out.append('//! GENERATED by tools/gen_dts_tables.py from the numeric tables of')
285 out.append('//! ETSI TS 102 114 V1.6.1 (2019-08); the clause of each table is named on')
286 out.append('//! it. The raw printed numbers are committed in')
287 out.append('//! tests/spec_ts102114_tables.txt and tests/spec_tables.rs checks every')
288 out.append('//! table here against them. Do not edit by hand.')
289 out.append('//!')
290 out.append('//! The tables the standard does not print numerically (ADPCM and')
291 out.append('//! high-frequency VQ codebooks, which it says are too large to include) or')
292 out.append('//! prints at a precision that does not reproduce the fixed-point values')
293 out.append('//! used here live in `tables_residual.rs` and are re-exported below.')
294 out.append('')
295 out.append('pub use crate::tables_residual::*;')
296 out.append('')
297 emit('SCALE_FACTOR_QUANT6', 'u32', ints(R['SCALE_FACTOR_QUANT6'], 64),
298 '6-bit scale factor quantization levels, ETSI TS 102 114 D.1.1 (63 invalid = 0).')
299 emit('SCALE_FACTOR_QUANT7', 'u32', ints(R['SCALE_FACTOR_QUANT7'], 128),
300 '7-bit scale factor quantization levels, ETSI TS 102 114 D.1.2 (125..127 invalid = 0).')
301 emit('SCALE_FACTOR_ADJ', 'u32', [int(Decimal(a) * 2 ** 22) for a in adj],
302 'Scale factor adjustment values x 2^22, ETSI TS 102 114 Table 5-27.')
303 emit('QUANT_LEVELS', 'u32', [1] + [int(x) for x in R['QUANT_LEVELS'][1:]] + [0] * 5,
304 'Quantization levels by ABITS, ETSI TS 102 114 Table 5-26 (ABITS 0 = 1, 8..10 the power of two).')
305 emit('LOSSY_QUANT', 'u32', ints(R['LOSSY_QUANT'], 32),
306 'Lossy quantizer step size x 2^22, ETSI TS 102 114 D.2.1.')
307 emit('LOSSLESS_QUANT', 'u32', ints(R['LOSSLESS_QUANT'], 32),
308 'Lossless quantizer step size x 2^22, ETSI TS 102 114 D.2.2.')
309 f64 = [int((Decimal(x) * 2 ** 29).to_integral_value(ROUND_HALF_UP)) * (1 if (i // 32) % 4 == 0 else -1)
310 for i, x in enumerate(R['FIR_64'])]
311 emit('FIR_64', 'i32', f64,
312 '64-band QMF window for X96, x 2^29 with the cosine modulation sign, ETSI TS 102 114 D.9.', 8)
313 perm = [[q, 128 + q, 255 - q, 127 - q][p] for q in range(64) for p in range(4)]
314 out.append('/// LFE interpolation FIR for the 128x decimation, ETSI TS 102 114 D.8 (128 x column),')
315 out.append('/// in polyphase order.')
316 out.append('pub static LFE_FIR_128: [f32; 256] = [')
317 for k in range(0, 256, 4):
318 out.append(' ' + ', '.join(lfe[perm[j]] for j in range(k, k + 4)) + ',')
319 out.append('];')
320 out.append('')
321 emit('DMIXTABLE', 'u16', [0] + [int(dm[i]) for i in range(241)],
322 'Downmix scale factors, ETSI TS 102 114 D.11 (DmixTable, preceded by a 0 entry).')
323 out.append('/// Huffman code (symbol, length) pairs in canonical code order, from ETSI TS 102 114')
324 out.append('/// D.5: quantizer index books (10 books x group), bit allocation (5 x 12),')
325 out.append('/// scale factors (5 x 129), transition mode (4 x 4).')
326 out.append('pub static HUFF_SRC: [(u8, u8); %d] = [' % len(huff))
327 for k in range(0, len(huff), 8):
328 out.append(' ' + ', '.join('(%d, %d)' % p for p in huff[k:k + 8]) + ',')
329 out.append('];')
330 with open(out_rs, 'w') as f:
331 f.write('\n'.join(out) + '\n')
332
333
334main()