source: python/lib/gen_external.py @ ac971a51

sampler
Last change on this file since ac971a51 was ac971a51, checked in by Paul Brossier <piem@piem.org>, 7 years ago

setup.py, python/lib/: use sorted glob.glob to improve reproducibility

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