[19c3d75] | 1 | import distutils.ccompiler |
---|
[541ea280] | 2 | import sys |
---|
| 3 | import os |
---|
| 4 | import subprocess |
---|
| 5 | import glob |
---|
[ccb9fb5] | 6 | |
---|
[89b04e8] | 7 | header = os.path.join('src', 'aubio.h') |
---|
| 8 | output_path = os.path.join('python', 'gen') |
---|
[1167631] | 9 | |
---|
| 10 | source_header = """// this file is generated! do not modify |
---|
[ccb9fb5] | 11 | #include "aubio-types.h" |
---|
| 12 | """ |
---|
| 13 | |
---|
[51ca615] | 14 | default_skip_objects = [ |
---|
[541ea280] | 15 | # already in ext/ |
---|
| 16 | 'fft', |
---|
| 17 | 'pvoc', |
---|
| 18 | 'filter', |
---|
| 19 | 'filterbank', |
---|
| 20 | # AUBIO_UNSTABLE |
---|
| 21 | 'hist', |
---|
| 22 | 'parameter', |
---|
| 23 | 'scale', |
---|
| 24 | 'beattracking', |
---|
| 25 | 'resampler', |
---|
| 26 | 'peakpicker', |
---|
| 27 | 'pitchfcomb', |
---|
| 28 | 'pitchmcomb', |
---|
| 29 | 'pitchschmitt', |
---|
| 30 | 'pitchspecacf', |
---|
| 31 | 'pitchyin', |
---|
| 32 | 'pitchyinfft', |
---|
[9fa0ed1] | 33 | 'pitchyinfast', |
---|
[541ea280] | 34 | 'sink', |
---|
| 35 | 'sink_apple_audio', |
---|
| 36 | 'sink_sndfile', |
---|
| 37 | 'sink_wavwrite', |
---|
| 38 | #'mfcc', |
---|
| 39 | 'source', |
---|
| 40 | 'source_apple_audio', |
---|
| 41 | 'source_sndfile', |
---|
| 42 | 'source_avcodec', |
---|
| 43 | 'source_wavread', |
---|
| 44 | #'sampler', |
---|
| 45 | 'audio_unit', |
---|
| 46 | 'spectral_whitening', |
---|
| 47 | ] |
---|
| 48 | |
---|
[ccb9fb5] | 49 | |
---|
[19c3d75] | 50 | def get_preprocessor(): |
---|
| 51 | # findout which compiler to use |
---|
| 52 | from distutils.sysconfig import customize_compiler |
---|
| 53 | compiler_name = distutils.ccompiler.get_default_compiler() |
---|
| 54 | compiler = distutils.ccompiler.new_compiler(compiler=compiler_name) |
---|
| 55 | try: |
---|
| 56 | customize_compiler(compiler) |
---|
| 57 | except AttributeError as e: |
---|
| 58 | print("Warning: failed customizing compiler ({:s})".format(repr(e))) |
---|
| 59 | |
---|
| 60 | if hasattr(compiler, 'initialize'): |
---|
| 61 | try: |
---|
| 62 | compiler.initialize() |
---|
| 63 | except ValueError as e: |
---|
| 64 | print("Warning: failed initializing compiler ({:s})".format(repr(e))) |
---|
| 65 | |
---|
| 66 | cpp_cmd = None |
---|
[541ea280] | 67 | if hasattr(compiler, 'preprocessor'): # for unixccompiler |
---|
[19c3d75] | 68 | cpp_cmd = compiler.preprocessor |
---|
[541ea280] | 69 | elif hasattr(compiler, 'compiler'): # for ccompiler |
---|
[19c3d75] | 70 | cpp_cmd = compiler.compiler.split() |
---|
| 71 | cpp_cmd += ['-E'] |
---|
[541ea280] | 72 | elif hasattr(compiler, 'cc'): # for msvccompiler |
---|
[19c3d75] | 73 | cpp_cmd = compiler.cc.split() |
---|
| 74 | cpp_cmd += ['-E'] |
---|
| 75 | |
---|
| 76 | if not cpp_cmd: |
---|
| 77 | print("Warning: could not guess preprocessor, using env's CC") |
---|
| 78 | cpp_cmd = os.environ.get('CC', 'cc').split() |
---|
| 79 | cpp_cmd += ['-E'] |
---|
[dbdb48a] | 80 | if 'emcc' in cpp_cmd: |
---|
| 81 | cpp_cmd += ['-x', 'c'] # emcc defaults to c++, force C language |
---|
[19c3d75] | 82 | return cpp_cmd |
---|
[ccb9fb5] | 83 | |
---|
[150ec2d] | 84 | |
---|
| 85 | def get_c_declarations(header=header, usedouble=False): |
---|
| 86 | ''' return a dense and preprocessed string of all c declarations implied by aubio.h |
---|
| 87 | ''' |
---|
[d214124] | 88 | cpp_output = get_cpp_output(header=header, usedouble=usedouble) |
---|
| 89 | return filter_cpp_output (cpp_output) |
---|
| 90 | |
---|
| 91 | |
---|
| 92 | def get_cpp_output(header=header, usedouble=False): |
---|
| 93 | ''' find and run a C pre-processor on aubio.h ''' |
---|
[19c3d75] | 94 | cpp_cmd = get_preprocessor() |
---|
| 95 | |
---|
| 96 | macros = [('AUBIO_UNSTABLE', 1)] |
---|
[3d14829] | 97 | if usedouble: |
---|
| 98 | macros += [('HAVE_AUBIO_DOUBLE', 1)] |
---|
[19c3d75] | 99 | |
---|
| 100 | if not os.path.isfile(header): |
---|
| 101 | raise Exception("could not find include file " + header) |
---|
| 102 | |
---|
| 103 | includes = [os.path.dirname(header)] |
---|
| 104 | cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes) |
---|
| 105 | cpp_cmd += [header] |
---|
| 106 | |
---|
| 107 | print("Running command: {:s}".format(" ".join(cpp_cmd))) |
---|
| 108 | proc = subprocess.Popen(cpp_cmd, |
---|
[541ea280] | 109 | stderr=subprocess.PIPE, |
---|
| 110 | stdout=subprocess.PIPE) |
---|
[19c3d75] | 111 | assert proc, 'Proc was none' |
---|
| 112 | cpp_output = proc.stdout.read() |
---|
| 113 | err_output = proc.stderr.read() |
---|
[31742b8] | 114 | if err_output: |
---|
[073b969] | 115 | print("Warning: preprocessor produced errors or warnings:\n%s" \ |
---|
| 116 | % err_output.decode('utf8')) |
---|
[19c3d75] | 117 | if not cpp_output: |
---|
[073b969] | 118 | raise_msg = "preprocessor output is empty! Running command " \ |
---|
| 119 | + "\"%s\" failed" % " ".join(cpp_cmd) |
---|
| 120 | if err_output: |
---|
| 121 | raise_msg += " with stderr: \"%s\"" % err_output.decode('utf8') |
---|
| 122 | else: |
---|
| 123 | raise_msg += " with no stdout or stderr" |
---|
| 124 | raise Exception(raise_msg) |
---|
[19c3d75] | 125 | if not isinstance(cpp_output, list): |
---|
| 126 | cpp_output = [l.strip() for l in cpp_output.decode('utf8').split('\n')] |
---|
[ccb9fb5] | 127 | |
---|
[d214124] | 128 | return cpp_output |
---|
| 129 | |
---|
| 130 | def filter_cpp_output(cpp_raw_output): |
---|
| 131 | ''' prepare cpp-output for parsing ''' |
---|
| 132 | cpp_output = filter(lambda y: len(y) > 1, cpp_raw_output) |
---|
[19c3d75] | 133 | cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output)) |
---|
[ccb9fb5] | 134 | |
---|
| 135 | i = 1 |
---|
| 136 | while 1: |
---|
[541ea280] | 137 | if i >= len(cpp_output): |
---|
| 138 | break |
---|
[50853b0] | 139 | if ('{' in cpp_output[i - 1]) and ('}' not in cpp_output[i - 1]) or (';' not in cpp_output[i - 1]): |
---|
[541ea280] | 140 | cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i] |
---|
| 141 | cpp_output.pop(i - 1) |
---|
[15a43e0] | 142 | elif ('}' in cpp_output[i]): |
---|
| 143 | cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i] |
---|
| 144 | cpp_output.pop(i - 1) |
---|
[ccb9fb5] | 145 | else: |
---|
| 146 | i += 1 |
---|
| 147 | |
---|
[eea6101] | 148 | # clean pointer notations |
---|
| 149 | tmp = [] |
---|
| 150 | for l in cpp_output: |
---|
[2f5f1e4] | 151 | tmp += [l.replace(' *', ' * ')] |
---|
[541ea280] | 152 | cpp_output = tmp |
---|
[ccb9fb5] | 153 | |
---|
[150ec2d] | 154 | return cpp_output |
---|
[ccb9fb5] | 155 | |
---|
[541ea280] | 156 | |
---|
[dad51ce] | 157 | def get_cpp_objects_from_c_declarations(c_declarations, skip_objects=None): |
---|
[50853b0] | 158 | if skip_objects is None: |
---|
[51ca615] | 159 | skip_objects = default_skip_objects |
---|
[541ea280] | 160 | typedefs = filter(lambda y: y.startswith('typedef struct _aubio'), c_declarations) |
---|
[ccb9fb5] | 161 | cpp_objects = [a.split()[3][:-1] for a in typedefs] |
---|
[51ca615] | 162 | cpp_objects_filtered = filter(lambda y: not y[6:-2] in skip_objects, cpp_objects) |
---|
| 163 | return cpp_objects_filtered |
---|
[ccb9fb5] | 164 | |
---|
[6cbf34b] | 165 | |
---|
[50853b0] | 166 | def get_all_func_names_from_lib(lib): |
---|
[6cbf34b] | 167 | ''' return flat string of all function used in lib |
---|
| 168 | ''' |
---|
| 169 | res = [] |
---|
[50853b0] | 170 | for _, v in lib.items(): |
---|
[6cbf34b] | 171 | if isinstance(v, dict): |
---|
[50853b0] | 172 | res += get_all_func_names_from_lib(v) |
---|
[6cbf34b] | 173 | elif isinstance(v, list): |
---|
| 174 | for elem in v: |
---|
| 175 | e = elem.split('(') |
---|
| 176 | if len(e) < 2: |
---|
| 177 | continue # not a function |
---|
| 178 | fname_part = e[0].strip().split(' ') |
---|
| 179 | fname = fname_part[-1] |
---|
| 180 | if fname: |
---|
| 181 | res += [fname] |
---|
| 182 | else: |
---|
| 183 | raise NameError('gen_lib : weird function: ' + str(e)) |
---|
[ccb9fb5] | 184 | |
---|
[6cbf34b] | 185 | return res |
---|
[ccb9fb5] | 186 | |
---|
[41fc24f] | 187 | |
---|
[6cbf34b] | 188 | def generate_lib_from_c_declarations(cpp_objects, c_declarations): |
---|
| 189 | ''' returns a lib from given cpp_object names |
---|
| 190 | |
---|
| 191 | a lib is a dict grouping functions by family (onset,pitch...) |
---|
| 192 | each eement is itself a dict of functions grouped by puposes as : |
---|
| 193 | struct, new, del, do, get, set and other |
---|
| 194 | ''' |
---|
[ccb9fb5] | 195 | lib = {} |
---|
| 196 | |
---|
| 197 | for o in cpp_objects: |
---|
[0b2643b] | 198 | shortname = o |
---|
[5674833] | 199 | if o[:6] == 'aubio_': |
---|
[0b2643b] | 200 | shortname = o[6:-2] # without aubio_ prefix and _t suffix |
---|
[541ea280] | 201 | |
---|
[c96e6c0] | 202 | lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'rdo': [], 'get': [], 'set': [], 'other': []} |
---|
[ccb9fb5] | 203 | lib[shortname]['longname'] = o |
---|
| 204 | lib[shortname]['shortname'] = shortname |
---|
[5674833] | 205 | |
---|
[0b2643b] | 206 | fullshortname = o[:-2] # name without _t suffix |
---|
| 207 | |
---|
[150ec2d] | 208 | for fn in c_declarations: |
---|
[0b2643b] | 209 | func_name = fn.split('(')[0].strip().split(' ')[-1] |
---|
| 210 | if func_name.startswith(fullshortname + '_') or func_name.endswith(fullshortname): |
---|
[5674833] | 211 | # print "found", shortname, "in", fn |
---|
[ccb9fb5] | 212 | if 'typedef struct ' in fn: |
---|
| 213 | lib[shortname]['struct'].append(fn) |
---|
| 214 | elif '_do' in fn: |
---|
| 215 | lib[shortname]['do'].append(fn) |
---|
[c96e6c0] | 216 | elif '_rdo' in fn: |
---|
| 217 | lib[shortname]['rdo'].append(fn) |
---|
[ccb9fb5] | 218 | elif 'new_' in fn: |
---|
| 219 | lib[shortname]['new'].append(fn) |
---|
| 220 | elif 'del_' in fn: |
---|
| 221 | lib[shortname]['del'].append(fn) |
---|
| 222 | elif '_get_' in fn: |
---|
| 223 | lib[shortname]['get'].append(fn) |
---|
| 224 | elif '_set_' in fn: |
---|
| 225 | lib[shortname]['set'].append(fn) |
---|
| 226 | else: |
---|
[541ea280] | 227 | # print "no idea what to do about", fn |
---|
[ccb9fb5] | 228 | lib[shortname]['other'].append(fn) |
---|
[41fc24f] | 229 | return lib |
---|
[ccb9fb5] | 230 | |
---|
[541ea280] | 231 | |
---|
[150ec2d] | 232 | def print_c_declarations_results(lib, c_declarations): |
---|
| 233 | for fn in c_declarations: |
---|
[ccb9fb5] | 234 | found = 0 |
---|
| 235 | for o in lib: |
---|
| 236 | for family in lib[o]: |
---|
| 237 | if fn in lib[o][family]: |
---|
| 238 | found = 1 |
---|
| 239 | if found == 0: |
---|
[541ea280] | 240 | print("missing", fn) |
---|
[ccb9fb5] | 241 | |
---|
| 242 | for o in lib: |
---|
| 243 | for family in lib[o]: |
---|
| 244 | if type(lib[o][family]) == str: |
---|
[541ea280] | 245 | print("{:15s} {:10s} {:s}".format(o, family, lib[o][family])) |
---|
[ccb9fb5] | 246 | elif len(lib[o][family]) == 1: |
---|
[541ea280] | 247 | print("{:15s} {:10s} {:s}".format(o, family, lib[o][family][0])) |
---|
[a7f398d] | 248 | else: |
---|
[541ea280] | 249 | print("{:15s} {:10s} {:s}".format(o, family, lib[o][family])) |
---|
[41fc24f] | 250 | |
---|
[ccb9fb5] | 251 | |
---|
[41fc24f] | 252 | def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True): |
---|
[541ea280] | 253 | if not os.path.isdir(output_path): |
---|
| 254 | os.mkdir(output_path) |
---|
| 255 | elif not overwrite: |
---|
| 256 | return sorted(glob.glob(os.path.join(output_path, '*.c'))) |
---|
[41fc24f] | 257 | |
---|
[150ec2d] | 258 | c_declarations = get_c_declarations(header, usedouble=usedouble) |
---|
| 259 | cpp_objects = get_cpp_objects_from_c_declarations(c_declarations) |
---|
[41fc24f] | 260 | |
---|
[6cbf34b] | 261 | lib = generate_lib_from_c_declarations(cpp_objects, c_declarations) |
---|
[150ec2d] | 262 | # print_c_declarations_results(lib, c_declarations) |
---|
[41fc24f] | 263 | |
---|
| 264 | sources_list = [] |
---|
[1167631] | 265 | try: |
---|
| 266 | from .gen_code import MappedObject |
---|
[19c3d75] | 267 | except (SystemError, ValueError): |
---|
[1167631] | 268 | from gen_code import MappedObject |
---|
[ccb9fb5] | 269 | for o in lib: |
---|
[1167631] | 270 | out = source_header |
---|
[541ea280] | 271 | mapped = MappedObject(lib[o], usedouble=usedouble) |
---|
[ccb9fb5] | 272 | out += mapped.gen_code() |
---|
| 273 | output_file = os.path.join(output_path, 'gen-%s.c' % o) |
---|
| 274 | with open(output_file, 'w') as f: |
---|
| 275 | f.write(out) |
---|
[541ea280] | 276 | print("wrote %s" % output_file) |
---|
[ccb9fb5] | 277 | sources_list.append(output_file) |
---|
| 278 | |
---|
[1167631] | 279 | out = source_header |
---|
[ccb9fb5] | 280 | out += "#include \"aubio-generated.h\"" |
---|
| 281 | check_types = "\n || ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib]) |
---|
| 282 | out += """ |
---|
| 283 | |
---|
| 284 | int generated_types_ready (void) |
---|
| 285 | {{ |
---|
| 286 | return ({pycheck_types}); |
---|
| 287 | }} |
---|
[541ea280] | 288 | """.format(pycheck_types=check_types) |
---|
[ccb9fb5] | 289 | |
---|
| 290 | add_types = "".join([""" |
---|
| 291 | Py_INCREF (&Py_{name}Type); |
---|
[541ea280] | 292 | PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name=o) for o in lib]) |
---|
[ccb9fb5] | 293 | out += """ |
---|
| 294 | |
---|
| 295 | void add_generated_objects ( PyObject *m ) |
---|
| 296 | {{ |
---|
| 297 | {add_types} |
---|
| 298 | }} |
---|
[541ea280] | 299 | """.format(add_types=add_types) |
---|
[ccb9fb5] | 300 | |
---|
| 301 | output_file = os.path.join(output_path, 'aubio-generated.c') |
---|
| 302 | with open(output_file, 'w') as f: |
---|
| 303 | f.write(out) |
---|
[541ea280] | 304 | print("wrote %s" % output_file) |
---|
[ccb9fb5] | 305 | sources_list.append(output_file) |
---|
[a7f398d] | 306 | |
---|
[b6230d8] | 307 | objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib]) |
---|
[a89ed31] | 308 | out = """// generated list of objects created with gen_external.py |
---|
[ccb9fb5] | 309 | |
---|
[a89ed31] | 310 | #include <Python.h> |
---|
| 311 | """ |
---|
| 312 | if usedouble: |
---|
| 313 | out += """ |
---|
| 314 | #ifndef HAVE_AUBIO_DOUBLE |
---|
| 315 | #define HAVE_AUBIO_DOUBLE 1 |
---|
| 316 | #endif |
---|
| 317 | """ |
---|
| 318 | out += """ |
---|
[ccb9fb5] | 319 | {objlist} |
---|
| 320 | int generated_objects ( void ); |
---|
| 321 | void add_generated_objects( PyObject *m ); |
---|
[541ea280] | 322 | """.format(objlist=objlist) |
---|
[ccb9fb5] | 323 | |
---|
| 324 | output_file = os.path.join(output_path, 'aubio-generated.h') |
---|
| 325 | with open(output_file, 'w') as f: |
---|
| 326 | f.write(out) |
---|
[541ea280] | 327 | print("wrote %s" % output_file) |
---|
[ccb9fb5] | 328 | # no need to add header to list of sources |
---|
| 329 | |
---|
[ee7e543] | 330 | return sorted(sources_list) |
---|
[ccb9fb5] | 331 | |
---|
| 332 | if __name__ == '__main__': |
---|
[541ea280] | 333 | if len(sys.argv) > 1: |
---|
| 334 | header = sys.argv[1] |
---|
| 335 | if len(sys.argv) > 2: |
---|
| 336 | output_path = sys.argv[2] |
---|
[1167631] | 337 | generate_external(header, output_path) |
---|