source: python/lib/gen_external.py @ 15a43e0

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5
Last change on this file since 15a43e0 was 15a43e0, checked in by Martin Hermant <martin.hermant@gmail.com>, 7 years ago

gen_external.py : relax a bit parsing of preprocessor code -> one line per {} block no matter if they are actually at end of line (conflict with structs)

  • Property mode set to 100644
File size: 8.0 KB
Line 
1import distutils.ccompiler
2import sys, os, subprocess, glob
3
4header = os.path.join('src', 'aubio.h')
5output_path = os.path.join('python', 'gen')
6
7source_header = """// this file is generated! do not modify
8#include "aubio-types.h"
9"""
10
11skip_objects = [
12  # already in ext/
13  'fft',
14  'pvoc',
15  'filter',
16  'filterbank',
17  # AUBIO_UNSTABLE
18  'hist',
19  'parameter',
20  'scale',
21  'beattracking',
22  'resampler',
23  'peakpicker',
24  'pitchfcomb',
25  'pitchmcomb',
26  'pitchschmitt',
27  'pitchspecacf',
28  'pitchyin',
29  'pitchyinfft',
30  'sink',
31  'sink_apple_audio',
32  'sink_sndfile',
33  'sink_wavwrite',
34  #'mfcc',
35  'source',
36  'source_apple_audio',
37  'source_sndfile',
38  'source_avcodec',
39  'source_wavread',
40  #'sampler',
41  'audio_unit',
42  'spectral_whitening',
43  ]
44
45def get_preprocessor():
46    # findout which compiler to use
47    from distutils.sysconfig import customize_compiler
48    compiler_name = distutils.ccompiler.get_default_compiler()
49    compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
50    try:
51        customize_compiler(compiler)
52    except AttributeError as e:
53        print("Warning: failed customizing compiler ({:s})".format(repr(e)))
54
55    if hasattr(compiler, 'initialize'):
56        try:
57            compiler.initialize()
58        except ValueError as e:
59            print("Warning: failed initializing compiler ({:s})".format(repr(e)))
60
61    cpp_cmd = None
62    if hasattr(compiler, 'preprocessor'): # for unixccompiler
63        cpp_cmd = compiler.preprocessor
64    elif hasattr(compiler, 'compiler'): # for ccompiler
65        cpp_cmd = compiler.compiler.split()
66        cpp_cmd += ['-E']
67    elif hasattr(compiler, 'cc'): # for msvccompiler
68        cpp_cmd = compiler.cc.split()
69        cpp_cmd += ['-E']
70
71    if not cpp_cmd:
72        print("Warning: could not guess preprocessor, using env's CC")
73        cpp_cmd = os.environ.get('CC', 'cc').split()
74        cpp_cmd += ['-E']
75    cpp_cmd += ['-x', 'c']  # force C language (emcc defaults to c++)
76    return cpp_cmd
77
78def get_cpp_objects(header=header, usedouble=False):
79    cpp_cmd = get_preprocessor()
80
81    macros = [('AUBIO_UNSTABLE', 1)]
82    if usedouble:
83        macros += [('HAVE_AUBIO_DOUBLE', 1)]
84
85    if not os.path.isfile(header):
86        raise Exception("could not find include file " + header)
87
88    includes = [os.path.dirname(header)]
89    cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes)
90    cpp_cmd += [header]
91
92    print("Running command: {:s}".format(" ".join(cpp_cmd)))
93    proc = subprocess.Popen(cpp_cmd,
94            stderr=subprocess.PIPE,
95            stdout=subprocess.PIPE)
96    assert proc, 'Proc was none'
97    cpp_output = proc.stdout.read()
98    err_output = proc.stderr.read()
99    if not cpp_output:
100        raise Exception("preprocessor output is empty:\n%s" % err_output)
101    elif err_output:
102        print ("Warning: preprocessor produced warnings:\n%s" % err_output)
103    if not isinstance(cpp_output, list):
104        cpp_output = [l.strip() for l in cpp_output.decode('utf8').split('\n')]
105
106    cpp_output = filter(lambda y: len(y) > 1, cpp_output)
107    cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output))
108
109    i = 1
110    while 1:
111        if i >= len(cpp_output):break
112        if ('{' in cpp_output[i - 1]) and (not '}' in cpp_output[i - 1]) or (not ';' in cpp_output[i - 1]):
113            cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
114            cpp_output.pop(i-1)
115        elif ('}' in cpp_output[i]):
116            cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i]
117            cpp_output.pop(i - 1)
118        else:
119            i += 1
120
121    typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
122
123    cpp_objects = [a.split()[3][:-1] for a in typedefs]
124
125    return cpp_output, cpp_objects
126
127
128def analyze_cpp_output(cpp_objects, cpp_output):
129    lib = {}
130
131    for o in cpp_objects:
132        if o[:6] != 'aubio_':
133            continue
134        shortname = o[6:-2]
135        if shortname in skip_objects:
136            continue
137        lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
138        lib[shortname]['longname'] = o
139        lib[shortname]['shortname'] = shortname
140        for fn in cpp_output:
141            if o[:-1] in fn:
142                #print "found", o[:-1], "in", fn
143                if 'typedef struct ' in fn:
144                    lib[shortname]['struct'].append(fn)
145                elif '_do' in fn:
146                    lib[shortname]['do'].append(fn)
147                elif 'new_' in fn:
148                    lib[shortname]['new'].append(fn)
149                elif 'del_' in fn:
150                    lib[shortname]['del'].append(fn)
151                elif '_get_' in fn:
152                    lib[shortname]['get'].append(fn)
153                elif '_set_' in fn:
154                    lib[shortname]['set'].append(fn)
155                else:
156                    #print "no idea what to do about", fn
157                    lib[shortname]['other'].append(fn)
158    return lib
159
160def print_cpp_output_results(lib, cpp_output):
161    for fn in cpp_output:
162        found = 0
163        for o in lib:
164            for family in lib[o]:
165                if fn in lib[o][family]:
166                    found = 1
167        if found == 0:
168            print ("missing", fn)
169
170    for o in lib:
171        for family in lib[o]:
172            if type(lib[o][family]) == str:
173                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
174            elif len(lib[o][family]) == 1:
175                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
176            else:
177                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
178
179
180def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
181    if not os.path.isdir(output_path): os.mkdir(output_path)
182    elif not overwrite: return sorted(glob.glob(os.path.join(output_path, '*.c')))
183
184    cpp_output, cpp_objects = get_cpp_objects(header, usedouble=usedouble)
185
186    lib = analyze_cpp_output(cpp_objects, cpp_output)
187    # print_cpp_output_results(lib, cpp_output)
188
189    sources_list = []
190    try:
191        from .gen_code import MappedObject
192    except (SystemError, ValueError):
193        from gen_code import MappedObject
194    for o in lib:
195        out = source_header
196        mapped = MappedObject(lib[o], usedouble = usedouble)
197        out += mapped.gen_code()
198        output_file = os.path.join(output_path, 'gen-%s.c' % o)
199        with open(output_file, 'w') as f:
200            f.write(out)
201            print ("wrote %s" % output_file )
202            sources_list.append(output_file)
203
204    out = source_header
205    out += "#include \"aubio-generated.h\""
206    check_types = "\n     ||  ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
207    out += """
208
209int generated_types_ready (void)
210{{
211  return ({pycheck_types});
212}}
213""".format(pycheck_types = check_types)
214
215    add_types = "".join(["""
216  Py_INCREF (&Py_{name}Type);
217  PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
218    out += """
219
220void add_generated_objects ( PyObject *m )
221{{
222{add_types}
223}}
224""".format(add_types = add_types)
225
226    output_file = os.path.join(output_path, 'aubio-generated.c')
227    with open(output_file, 'w') as f:
228        f.write(out)
229        print ("wrote %s" % output_file )
230        sources_list.append(output_file)
231
232    objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
233    out = """// generated list of objects created with gen_external.py
234
235#include <Python.h>
236"""
237    if usedouble:
238        out += """
239#ifndef HAVE_AUBIO_DOUBLE
240#define HAVE_AUBIO_DOUBLE 1
241#endif
242"""
243    out += """
244{objlist}
245int generated_objects ( void );
246void add_generated_objects( PyObject *m );
247""".format(objlist = objlist)
248
249    output_file = os.path.join(output_path, 'aubio-generated.h')
250    with open(output_file, 'w') as f:
251        f.write(out)
252        print ("wrote %s" % output_file )
253        # no need to add header to list of sources
254
255    return sorted(sources_list)
256
257if __name__ == '__main__':
258    if len(sys.argv) > 1: header = sys.argv[1]
259    if len(sys.argv) > 2: output_path = sys.argv[2]
260    generate_external(header, output_path)
Note: See TracBrowser for help on using the repository browser.