source: python/lib/gen_external.py @ a89ed31

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

python/setup.py: add command 'generate' with option '--enable-double'

  • Property mode set to 100644
File size: 5.5 KB
Line 
1import os, glob
2
3header = """// this file is generated! do not modify
4#include "aubio-types.h"
5"""
6
7skip_objects = [
8  # already in ext/
9  'fft',
10  'pvoc',
11  'filter',
12  'filterbank',
13  #'resampler',
14  # AUBIO_UNSTABLE
15  'hist',
16  'parameter',
17  'scale',
18  'beattracking',
19  'resampler',
20  'peakpicker',
21  'pitchfcomb',
22  'pitchmcomb',
23  'pitchschmitt',
24  'pitchspecacf',
25  'pitchyin',
26  'pitchyinfft',
27  'sink',
28  'sink_apple_audio',
29  'sink_sndfile',
30  'sink_wavwrite',
31  #'mfcc',
32  'source',
33  'source_apple_audio',
34  'source_sndfile',
35  'source_avcodec',
36  'source_wavread',
37  #'sampler',
38  'audio_unit',
39
40  'tss',
41  ]
42
43
44def get_cpp_objects():
45
46    cpp_output = [l.strip() for l in os.popen('cpp -DAUBIO_UNSTABLE=1 -I../build/src ../src/aubio.h').readlines()]
47    #cpp_output = [l.strip() for l in os.popen('cpp -DAUBIO_UNSTABLE=0 -I../build/src ../src/onset/onset.h').readlines()]
48    #cpp_output = [l.strip() for l in os.popen('cpp -DAUBIO_UNSTABLE=0 -I../build/src ../src/pitch/pitch.h').readlines()]
49
50    cpp_output = filter(lambda y: len(y) > 1, cpp_output)
51    cpp_output = filter(lambda y: not y.startswith('#'), cpp_output)
52    cpp_output = list(cpp_output)
53
54    i = 1
55    while 1:
56        if i >= len(cpp_output): break
57        if cpp_output[i-1].endswith(',') or cpp_output[i-1].endswith('{') or cpp_output[i].startswith('}'):
58            cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
59            cpp_output.pop(i-1)
60        else:
61            i += 1
62
63    typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
64
65    cpp_objects = [a.split()[3][:-1] for a in typedefs]
66
67    return cpp_output, cpp_objects
68
69def generate_external(output_path, usedouble = False, overwrite = True):
70    if not os.path.isdir(output_path): os.mkdir(output_path)
71    elif overwrite == False: return glob.glob(os.path.join(output_path, '*.c'))
72    sources_list = []
73    cpp_output, cpp_objects = get_cpp_objects()
74    lib = {}
75
76    for o in cpp_objects:
77        if o[:6] != 'aubio_':
78            continue
79        shortname = o[6:-2]
80        if shortname in skip_objects:
81            continue
82        lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
83        lib[shortname]['longname'] = o
84        lib[shortname]['shortname'] = shortname
85        for fn in cpp_output:
86            if o[:-1] in fn:
87                #print "found", o[:-1], "in", fn
88                if 'typedef struct ' in fn:
89                    lib[shortname]['struct'].append(fn)
90                elif '_do' in fn:
91                    lib[shortname]['do'].append(fn)
92                elif 'new_' in fn:
93                    lib[shortname]['new'].append(fn)
94                elif 'del_' in fn:
95                    lib[shortname]['del'].append(fn)
96                elif '_get_' in fn:
97                    lib[shortname]['get'].append(fn)
98                elif '_set_' in fn:
99                    lib[shortname]['set'].append(fn)
100                else:
101                    #print "no idea what to do about", fn
102                    lib[shortname]['other'].append(fn)
103
104    """
105    for fn in cpp_output:
106        found = 0
107        for o in lib:
108            for family in lib[o]:
109                if fn in lib[o][family]:
110                    found = 1
111        if found == 0:
112            print "missing", fn
113
114    for o in lib:
115        for family in lib[o]:
116            if type(lib[o][family]) == str:
117                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
118            elif len(lib[o][family]) == 1:
119                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
120            else:
121                print ( "{:15s} {:10s} {:d}".format(o, family, len(lib[o][family]) ) )
122    """
123
124    from .gen_code import MappedObject
125    for o in lib:
126        out = header
127        mapped = MappedObject(lib[o], usedouble = usedouble)
128        out += mapped.gen_code()
129        output_file = os.path.join(output_path, 'gen-%s.c' % o)
130        with open(output_file, 'w') as f:
131            f.write(out)
132            print ("wrote %s" % output_file )
133            sources_list.append(output_file)
134
135    out = header
136    out += "#include \"aubio-generated.h\""
137    check_types = "\n     ||  ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
138    out += """
139
140int generated_types_ready (void)
141{{
142  return ({pycheck_types});
143}}
144""".format(pycheck_types = check_types)
145
146    add_types = "".join(["""
147  Py_INCREF (&Py_{name}Type);
148  PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
149    out += """
150
151void add_generated_objects ( PyObject *m )
152{{
153{add_types}
154}}
155""".format(add_types = add_types)
156
157    output_file = os.path.join(output_path, 'aubio-generated.c')
158    with open(output_file, 'w') as f:
159        f.write(out)
160        print ("wrote %s" % output_file )
161        sources_list.append(output_file)
162
163    objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
164    out = """// generated list of objects created with gen_external.py
165
166#include <Python.h>
167"""
168    if usedouble:
169        out += """
170#ifndef HAVE_AUBIO_DOUBLE
171#define HAVE_AUBIO_DOUBLE 1
172#endif
173"""
174    out += """
175{objlist}
176int generated_objects ( void );
177void add_generated_objects( PyObject *m );
178""".format(objlist = objlist)
179
180    output_file = os.path.join(output_path, 'aubio-generated.h')
181    with open(output_file, 'w') as f:
182        f.write(out)
183        print ("wrote %s" % output_file )
184        # no need to add header to list of sources
185
186    return sources_list
187
188if __name__ == '__main__':
189    output_path = 'gen'
190    generate_external(output_path)
Note: See TracBrowser for help on using the repository browser.