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