source: python/lib/gen_external.py @ 2719c54

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5pitchshiftsamplertimestretchyinfft+
Last change on this file since 2719c54 was 1bd8334, checked in by Paul Brossier <piem@piem.org>, 8 years ago

python/lib/gen_external.py: enable tss

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