d2115b5b587799b51acaf4c7b1e78d7bd7c2d13b
[aubio.git] / python / lib / gen_external.py
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   ]
43
44 def get_preprocessor():
45     # findout which compiler to use
46     from distutils.sysconfig import customize_compiler
47     compiler_name = distutils.ccompiler.get_default_compiler()
48     compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
49     try:
50         customize_compiler(compiler)
51     except AttributeError as e:
52         print("Warning: failed customizing compiler ({:s})".format(repr(e)))
53
54     if hasattr(compiler, 'initialize'):
55         try:
56             compiler.initialize()
57         except ValueError as e:
58             print("Warning: failed initializing compiler ({:s})".format(repr(e)))
59
60     cpp_cmd = None
61     if hasattr(compiler, 'preprocessor'): # for unixccompiler
62         cpp_cmd = compiler.preprocessor
63     elif hasattr(compiler, 'compiler'): # for ccompiler
64         cpp_cmd = compiler.compiler.split()
65         cpp_cmd += ['-E']
66     elif hasattr(compiler, 'cc'): # for msvccompiler
67         cpp_cmd = compiler.cc.split()
68         cpp_cmd += ['-E']
69
70     if not cpp_cmd:
71         print("Warning: could not guess preprocessor, using env's CC")
72         cpp_cmd = os.environ.get('CC', 'cc').split()
73         cpp_cmd += ['-E']
74
75     return cpp_cmd
76
77 def get_cpp_objects(header=header, usedouble=False):
78     cpp_cmd = get_preprocessor()
79
80     macros = [('AUBIO_UNSTABLE', 1)]
81     if usedouble:
82         macros += [('HAVE_AUBIO_DOUBLE', 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
124 def 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
156 def 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
176 def 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, usedouble=usedouble)
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
205 int 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
216 void 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}
241 int generated_objects ( void );
242 void 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
253 if __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)