blob: d2eda152711df18577b9fc14619458cb8ea42dff [file] [log] [blame]
Oliver Smitha47d37c2019-12-11 08:46:41 +01001#!/usr/bin/env python3
Harald Welteeea18a62016-04-29 15:18:35 +02002
3mod_license = """
4/*
5 * Copyright (C) 2011-2016 Sylvain Munaut <tnt@246tNt.com>
6 * Copyright (C) 2016 sysmocom s.f.m.c. GmbH
7 *
8 * All Rights Reserved
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 */
24"""
25
Vadim Yanitskiy2c717942017-01-13 02:23:01 +070026import sys, os, math, argparse
Vadim Yanitskiyf9c2c562016-11-01 22:19:28 +070027from functools import reduce
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +070028import conv_codes_gsm
Harald Welteeea18a62016-04-29 15:18:35 +020029
30class ConvolutionalCode(object):
31
Vadim Yanitskiye31cf802016-09-07 21:51:25 +070032 def __init__(self, block_len, polys, name,
Vadim Yanitskiye9a90ee2017-01-13 03:43:58 +070033 description = None, puncture = [], term_type = None,
34 vec_in = None, vec_out = None):
Harald Welteeea18a62016-04-29 15:18:35 +020035 # Save simple params
36 self.block_len = block_len
37 self.k = 1
38 self.puncture = puncture
39 self.rate_inv = len(polys)
Vadim Yanitskiya6b52162016-09-08 22:06:07 +070040 self.term_type = term_type
Vadim Yanitskiye9a90ee2017-01-13 03:43:58 +070041 self.vec_in = vec_in
42 self.vec_out = vec_out
Harald Welteeea18a62016-04-29 15:18:35 +020043
44 # Infos
45 self.name = name
46 self.description = description
47
Vadim Yanitskiy84fc2ce2016-09-08 20:30:36 +070048 # Handle polynomials (and check for recursion)
Harald Welteeea18a62016-04-29 15:18:35 +020049 self.polys = [(1, 1) if x[0] == x[1] else x for x in polys]
50
51 # Determine the polynomial degree
52 for (x, y) in polys:
53 self.k = max(self.k, int(math.floor(math.log(max(x, y), 2))))
54 self.k = self.k + 1
55
56 self.poly_divider = 1
57 rp = [x[1] for x in self.polys if x[1] != 1]
58 if rp:
59 if not all([x == rp[0] for x in rp]):
Vadim Yanitskiy84fc2ce2016-09-08 20:30:36 +070060 raise ValueError("Bad polynomials: "
61 "Can't have multiple different divider polynomials!")
Vadim Yanitskiye31cf802016-09-07 21:51:25 +070062
Harald Welteeea18a62016-04-29 15:18:35 +020063 if not all([x[0] == 1 for x in polys if x[1] == 1]):
Vadim Yanitskiy84fc2ce2016-09-08 20:30:36 +070064 raise ValueError("Bad polynomials: "
Vadim Yanitskiye31cf802016-09-07 21:51:25 +070065 "Can't have a '1' divider with a non '1' dividend "
66 "in a recursive code")
67
Harald Welteeea18a62016-04-29 15:18:35 +020068 self.poly_divider = rp[0]
69
70 @property
71 def recursive(self):
72 return self.poly_divider != 1
73
74 @property
75 def _state_mask(self):
76 return (1 << (self.k - 1)) - 1
77
78 def next_state(self, state, bit):
79 nb = combine(
80 (state << 1) | bit,
81 self.poly_divider,
82 self.k,
83 )
84 return ((state << 1) | nb) & self._state_mask
85
86 def next_term_state(self, state):
87 return (state << 1) & self._state_mask
88
89 def next_output(self, state, bit, ns = None):
90 # Next state bit
91 if ns is None:
92 ns = self.next_state(state, bit)
93
94 src = (ns & 1) | (state << 1)
95
Vadim Yanitskiy84fc2ce2016-09-08 20:30:36 +070096 # Scan polynomials
Harald Welteeea18a62016-04-29 15:18:35 +020097 rv = []
98 for p_n, p_d in self.polys:
99 if self.recursive and p_d == 1:
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700100 # No choice ... (systematic output in recursive case)
101 o = bit
Harald Welteeea18a62016-04-29 15:18:35 +0200102 else:
103 o = combine(src, p_n, self.k)
104 rv.append(o)
105
106 return rv
107
108 def next_term_output(self, state, ns = None):
109 # Next state bit
110 if ns is None:
111 ns = self.next_term_state(state)
112
113 src = (ns & 1) | (state << 1)
114
Vadim Yanitskiy84fc2ce2016-09-08 20:30:36 +0700115 # Scan polynomials
Harald Welteeea18a62016-04-29 15:18:35 +0200116 rv = []
117 for p_n, p_d in self.polys:
118 if self.recursive and p_d == 1:
119 # Systematic output are replaced when in 'termination' mode
120 o = combine(src, self.poly_divider, self.k)
121 else:
122 o = combine(src, p_n, self.k)
123 rv.append(o)
124
125 return rv
126
127 def next(self, state, bit):
128 ns = self.next_state(state, bit)
129 nb = self.next_output(state, bit, ns = ns)
130 return ns, nb
131
132 def next_term(self, state):
133 ns = self.next_term_state(state)
134 nb = self.next_term_output(state, ns = ns)
135 return ns, nb
136
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700137 def _print_term(self, fi, num_states, pack = False):
Vadim Yanitskiy6908fa72016-09-07 22:34:53 +0700138 items = []
139
Harald Welteeea18a62016-04-29 15:18:35 +0200140 for state in range(num_states):
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700141 if pack:
142 x = pack(self.next_term_output(state))
143 else:
144 x = self.next_term_state(state)
145
Vadim Yanitskiy6908fa72016-09-07 22:34:53 +0700146 items.append(x)
147
148 # Up to 12 numbers should be placed per line
149 print_formatted(items, "%3d, ", 12, fi)
Harald Welteeea18a62016-04-29 15:18:35 +0200150
151 def _print_x(self, fi, num_states, pack = False):
Vadim Yanitskiy6908fa72016-09-07 22:34:53 +0700152 items = []
153
Harald Welteeea18a62016-04-29 15:18:35 +0200154 for state in range(num_states):
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700155 if pack:
156 x0 = pack(self.next_output(state, 0))
157 x1 = pack(self.next_output(state, 1))
158 else:
159 x0 = self.next_state(state, 0)
160 x1 = self.next_state(state, 1)
161
Vadim Yanitskiy6908fa72016-09-07 22:34:53 +0700162 items.append((x0, x1))
163
164 # Up to 4 blocks should be placed per line
165 print_formatted(items, "{ %2d, %2d }, ", 4, fi)
166
167 def _print_puncture(self, fi):
168 # Up to 12 numbers should be placed per line
169 print_formatted(self.puncture, "%3d, ", 12, fi)
Harald Welteeea18a62016-04-29 15:18:35 +0200170
Vadim Yanitskiy804c4c72017-01-13 15:04:37 +0700171 def print_description(self, fi, brief = False):
172 if brief is True:
Neels Hofmeyr87e45502017-06-20 00:17:59 +0200173 fi.write("/*! structure describing %s.\n"
Vadim Yanitskiy804c4c72017-01-13 15:04:37 +0700174 % self.description[0])
175 for line in self.description[1:]:
176 fi.write(" * %s\n" % line)
177 else:
178 fi.write("/**\n")
179 for line in self.description:
180 fi.write(" * %s\n" % line)
181
182 fi.write(" */\n")
183
Vadim Yanitskiy6431add2016-10-29 00:00:57 +0700184 def print_state_and_output(self, fi):
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700185 pack = lambda n: \
186 sum([x << (self.rate_inv - i - 1) for i, x in enumerate(n)])
Harald Welteeea18a62016-04-29 15:18:35 +0200187 num_states = 1 << (self.k - 1)
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700188
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700189 fi.write("static const uint8_t %s_state[][2] = {\n" % self.name)
Harald Welteeea18a62016-04-29 15:18:35 +0200190 self._print_x(fi, num_states)
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700191 fi.write("};\n\n")
192
193 fi.write("static const uint8_t %s_output[][2] = {\n" % self.name)
Harald Welteeea18a62016-04-29 15:18:35 +0200194 self._print_x(fi, num_states, pack)
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700195 fi.write("};\n\n")
Harald Welteeea18a62016-04-29 15:18:35 +0200196
197 if self.recursive:
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700198 fi.write("static const uint8_t %s_term_state[] = {\n" % self.name)
Harald Welteeea18a62016-04-29 15:18:35 +0200199 self._print_term(fi, num_states)
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700200 fi.write("};\n\n")
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700201
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700202 fi.write("static const uint8_t %s_term_output[] = {\n" % self.name)
Harald Welteeea18a62016-04-29 15:18:35 +0200203 self._print_term(fi, num_states, pack)
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700204 fi.write("};\n\n")
Harald Welteeea18a62016-04-29 15:18:35 +0200205
Vadim Yanitskiy6431add2016-10-29 00:00:57 +0700206 def gen_tables(self, pref, fi, shared_tables = None):
207 # Do not print shared tables
208 if shared_tables is None:
209 self.print_state_and_output(fi)
210 table_pref = self.name
211 else:
212 table_pref = shared_tables
213
Harald Welteeea18a62016-04-29 15:18:35 +0200214 if len(self.puncture):
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700215 fi.write("static const int %s_puncture[] = {\n" % self.name)
Vadim Yanitskiy6908fa72016-09-07 22:34:53 +0700216 self._print_puncture(fi)
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700217 fi.write("};\n\n")
Harald Welteeea18a62016-04-29 15:18:35 +0200218
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700219 # Write description as a multi-line comment
220 if self.description is not None:
Vadim Yanitskiy804c4c72017-01-13 15:04:37 +0700221 self.print_description(fi)
Vadim Yanitskiye31cf802016-09-07 21:51:25 +0700222
223 # Print a final convolutional code definition
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700224 fi.write("const struct osmo_conv_code %s_%s = {\n" % (pref, self.name))
225 fi.write("\t.N = %d,\n" % self.rate_inv)
226 fi.write("\t.K = %d,\n" % self.k)
227 fi.write("\t.len = %d,\n" % self.block_len)
Vadim Yanitskiy6431add2016-10-29 00:00:57 +0700228 fi.write("\t.next_output = %s_output,\n" % table_pref)
229 fi.write("\t.next_state = %s_state,\n" % table_pref)
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700230
Vadim Yanitskiya6b52162016-09-08 22:06:07 +0700231 if self.term_type is not None:
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700232 fi.write("\t.term = %s,\n" % self.term_type)
233
Harald Welteeea18a62016-04-29 15:18:35 +0200234 if self.recursive:
Vadim Yanitskiy6431add2016-10-29 00:00:57 +0700235 fi.write("\t.next_term_output = %s_term_output,\n" % table_pref)
236 fi.write("\t.next_term_state = %s_term_state,\n" % table_pref)
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700237
Harald Welteeea18a62016-04-29 15:18:35 +0200238 if len(self.puncture):
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700239 fi.write("\t.puncture = %s_puncture,\n" % self.name)
240 fi.write("};\n\n")
Harald Welteeea18a62016-04-29 15:18:35 +0200241
Vadim Yanitskiye9a90ee2017-01-13 03:43:58 +0700242 def calc_out_len(self):
243 out_len = self.block_len * self.rate_inv
244
245 # By default CONV_TERM_FLUSH
246 if self.term_type is None:
247 out_len += self.rate_inv * (self.k - 1)
248
249 if len(self.puncture):
250 out_len -= len(self.puncture) - 1
251
252 return out_len
253
254 def gen_test_vector(self, fi, prefix):
255 code_name = "%s_%s" % (prefix, self.name)
256
257 fi.write("\t{\n")
258 fi.write("\t\t.name = \"%s\",\n" % code_name)
259 fi.write("\t\t.code = &%s,\n" % code_name)
260
261 fi.write("\t\t.in_len = %d,\n" % self.block_len)
262 fi.write("\t\t.out_len = %d,\n" % self.calc_out_len())
263
264 # Print pre computed vectors if preset
265 if self.vec_in is not None and self.vec_out is not None:
266 fi.write("\t\t.has_vec = 1,\n")
267 fi.write("\t\t.vec_in = {\n")
268 print_formatted(self.vec_in, "0x%02x, ", 8, fi, indent = "\t\t\t")
269 fi.write("\t\t},\n")
270 fi.write("\t\t.vec_out = {\n")
271 print_formatted(self.vec_out, "0x%02x, ", 8, fi, indent = "\t\t\t")
272 fi.write("\t\t},\n")
273 else:
274 fi.write("\t\t.has_vec = 0,\n")
275 fi.write("\t\t.vec_in = { },\n")
276 fi.write("\t\t.vec_out = { },\n")
277
278 fi.write("\t},\n")
279
Harald Welteeea18a62016-04-29 15:18:35 +0200280poly = lambda *args: sum([(1 << x) for x in args])
281
282def combine(src, sel, nb):
283 x = src & sel
284 fn_xor = lambda x, y: x ^ y
285 return reduce(fn_xor, [(x >> n) & 1 for n in range(nb)])
286
Vadim Yanitskiy6908fa72016-09-07 22:34:53 +0700287def print_formatted(items, format, count, fi):
288 counter = 0
289
290 # Print initial indent
291 fi.write("\t")
292
293 for item in items:
294 if counter > 0 and counter % count == 0:
295 fi.write("\n\t")
296
297 fi.write(format % item)
298 counter += 1
299
300 fi.write("\n")
301
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700302def print_shared(fi, shared_polys):
Vadim Yanitskiy6431add2016-10-29 00:00:57 +0700303 for (name, polys) in shared_polys.items():
304 # HACK
305 code = ConvolutionalCode(0, polys, name = name)
306 code.print_state_and_output(fi)
307
Neels Hofmeyrd1537e02017-03-13 14:14:17 +0100308def open_for_writing(parent_dir, base_name):
309 path = os.path.join(parent_dir, base_name)
310 if not os.path.isdir(parent_dir):
311 os.makedirs(parent_dir)
312 return open(path, 'w')
313
Vadim Yanitskiy2c717942017-01-13 02:23:01 +0700314def generate_codes(codes, path, prefix, name):
Vadim Yanitskiyd2d97602016-09-07 22:18:10 +0700315 # Open a new file for writing
Neels Hofmeyrd1537e02017-03-13 14:14:17 +0100316 f = open_for_writing(path, name)
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700317 f.write(mod_license + "\n")
318 f.write("#include <stdint.h>\n")
319 f.write("#include <osmocom/core/conv.h>\n\n")
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700320
Vadim Yanitskiy2c717942017-01-13 02:23:01 +0700321 sys.stderr.write("Generating convolutional codes...\n")
322
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700323 # Print shared tables first
324 if hasattr(codes, "shared_polys"):
325 print_shared(f, codes.shared_polys)
Harald Welteeea18a62016-04-29 15:18:35 +0200326
Vadim Yanitskiyd2d97602016-09-07 22:18:10 +0700327 # Generate the tables one by one
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700328 for code in codes.conv_codes:
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700329 sys.stderr.write("Generate '%s' definition\n" % code.name)
Vadim Yanitskiy6431add2016-10-29 00:00:57 +0700330
331 # Check whether shared polynomials are used
332 shared = None
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700333 if hasattr(codes, "shared_polys"):
334 for (name, polys) in codes.shared_polys.items():
335 if code.polys == polys:
336 shared = name
337 break
Vadim Yanitskiy6431add2016-10-29 00:00:57 +0700338
339 code.gen_tables(prefix, f, shared_tables = shared)
Vadim Yanitskiyd2d97602016-09-07 22:18:10 +0700340
Vadim Yanitskiye9a90ee2017-01-13 03:43:58 +0700341def generate_vectors(codes, path, prefix, name, inc = None):
342 # Open a new file for writing
Neels Hofmeyrd1537e02017-03-13 14:14:17 +0100343 f = open_for_writing(path, name)
Vadim Yanitskiye9a90ee2017-01-13 03:43:58 +0700344 f.write(mod_license + "\n")
345
346 # Print includes
347 if inc is not None:
348 for item in inc:
349 f.write("%s\n" % item)
350 f.write("#include <osmocom/core/conv.h>\n")
351 f.write("#include \"conv.h\"\n\n")
352
353 sys.stderr.write("Generating test vectors...\n")
354
355 vec_count = len(codes.conv_codes)
356 f.write("const int %s_vectors_len = %d;\n\n"
357 % (prefix, vec_count))
358
359 f.write("const struct conv_test_vector %s_vectors[%d] = {\n"
360 % (prefix, vec_count))
361
362 # Generate the vectors one by one
363 for code in codes.conv_codes:
364 sys.stderr.write("Generate '%s' test vector\n" % code.name)
365 code.gen_test_vector(f, prefix)
366
367 f.write("};\n")
368
Vadim Yanitskiy804c4c72017-01-13 15:04:37 +0700369def generate_header(codes, path, prefix, name, description = None):
370 # Open a new file for writing
Neels Hofmeyrd1537e02017-03-13 14:14:17 +0100371 f = open_for_writing(path, name)
Vadim Yanitskiy804c4c72017-01-13 15:04:37 +0700372
373 # Print license and includes
374 f.write(mod_license + "\n")
375 f.write("#pragma once\n\n")
376 f.write("#include <stdint.h>\n")
377 f.write("#include <osmocom/core/conv.h>\n\n")
378
379 # Print general file description if preset
380 if description is not None:
381 f.write("/*! \\file %s.h\n" % prefix)
382 f.write(" * %s\n" % description)
383 f.write(" */\n\n")
384
385 sys.stderr.write("Generating header file...\n")
386
387 # Generate declarations one by one
388 for code in codes.conv_codes:
389 sys.stderr.write("Generate '%s' declaration\n" % code.name)
390 code.print_description(f, True)
391 f.write("extern const struct osmo_conv_code %s_%s;\n\n"
392 % (prefix, code.name))
393
Vadim Yanitskiy2c717942017-01-13 02:23:01 +0700394def parse_argv():
395 parser = argparse.ArgumentParser()
396
397 # Positional arguments
398 parser.add_argument("action",
399 help = "what to generate",
Vadim Yanitskiy804c4c72017-01-13 15:04:37 +0700400 choices = ["gen_codes", "gen_vectors", "gen_header"])
Vadim Yanitskiy2c717942017-01-13 02:23:01 +0700401 parser.add_argument("family",
402 help = "convolutional code family",
403 choices = ["gsm"])
404
405 # Optional arguments
406 parser.add_argument("-p", "--prefix",
407 help = "internal naming prefix")
408 parser.add_argument("-n", "--target-name",
409 help = "target name for generated file")
410 parser.add_argument("-P", "--target-path",
411 help = "target path for generated file")
412
413 return parser.parse_args()
414
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700415if __name__ == '__main__':
Vadim Yanitskiy2c717942017-01-13 02:23:01 +0700416 # Parse and verify arguments
417 argv = parse_argv()
418 path = argv.target_path or os.getcwd()
Vadim Yanitskiye9a90ee2017-01-13 03:43:58 +0700419 inc = None
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700420
Vadim Yanitskiy2c717942017-01-13 02:23:01 +0700421 # Determine convolutional code family
422 if argv.family == "gsm":
423 codes = conv_codes_gsm
424 prefix = argv.prefix or "gsm0503"
Vadim Yanitskiye9a90ee2017-01-13 03:43:58 +0700425 inc = [ "#include <osmocom/gsm/gsm0503.h>" ]
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700426
Vadim Yanitskiy2c717942017-01-13 02:23:01 +0700427 # What to generate?
428 if argv.action == "gen_codes":
429 name = argv.target_name or prefix + "_conv.c"
430 generate_codes(codes, path, prefix, name)
Vadim Yanitskiye9a90ee2017-01-13 03:43:58 +0700431 elif argv.action == "gen_vectors":
432 name = argv.target_name or prefix + "_test_vectors.c"
433 generate_vectors(codes, path, prefix, name, inc)
Vadim Yanitskiy804c4c72017-01-13 15:04:37 +0700434 elif argv.action == "gen_header":
435 name = argv.target_name or prefix + ".h"
436 generate_header(codes, path, prefix, name)
Vadim Yanitskiy15492bc2016-11-10 17:10:42 +0700437
Vadim Yanitskiy45ebc522016-10-27 02:19:37 +0700438 sys.stderr.write("Generation complete.\n")