bbd7e5dbc552788781dae0be5bacb8bab988da69
[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   #'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
45 def 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
78 def get_cpp_objects(header=header, usedouble=False):
79     cpp_cmd = get_preprocessor()
80
81     macros = [('AUBIO_UNSTABLE', 1)]
82     if usedouble:
83         macros += [('HAVE_AUBIO_DOUBLE', 1)]
84
85     if not os.path.isfile(header):
86         raise Exception("could not find include file " + header)
87
88     includes = [os.path.dirname(header)]
89     cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes)
90     cpp_cmd += [header]
91
92     print("Running command: {:s}".format(" ".join(cpp_cmd)))
93     proc = subprocess.Popen(cpp_cmd,
94             stderr=subprocess.PIPE,
95             stdout=subprocess.PIPE)
96     assert proc, 'Proc was none'
97     cpp_output = proc.stdout.read()
98     err_output = proc.stderr.read()
99     if not cpp_output:
100         raise Exception("preprocessor output is empty:\n%s" % err_output)
101     elif err_output:
102         print ("Warning: preprocessor produced warnings:\n%s" % err_output)
103     if not isinstance(cpp_output, list):
104         cpp_output = [l.strip() for l in cpp_output.decode('utf8').split('\n')]
105
106     cpp_output = filter(lambda y: len(y) > 1, cpp_output)
107     cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output))
108
109     i = 1
110     while 1:
111         if i >= len(cpp_output): break
112         if cpp_output[i-1].endswith(',') or cpp_output[i-1].endswith('{') or cpp_output[i].startswith('}'):
113             cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
114             cpp_output.pop(i-1)
115         else:
116             i += 1
117
118     typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
119
120     cpp_objects = [a.split()[3][:-1] for a in typedefs]
121
122     return cpp_output, cpp_objects
123
124
125 def analyze_cpp_output(cpp_objects, cpp_output):
126     lib = {}
127
128     for o in cpp_objects:
129         if o[:6] != 'aubio_':
130             continue
131         shortname = o[6:-2]
132         if shortname in skip_objects:
133             continue
134         lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
135         lib[shortname]['longname'] = o
136         lib[shortname]['shortname'] = shortname
137         for fn in cpp_output:
138             if o[:-1] in fn:
139                 #print "found", o[:-1], "in", fn
140                 if 'typedef struct ' in fn:
141                     lib[shortname]['struct'].append(fn)
142                 elif '_do' in fn:
143                     lib[shortname]['do'].append(fn)
144                 elif 'new_' in fn:
145                     lib[shortname]['new'].append(fn)
146                 elif 'del_' in fn:
147                     lib[shortname]['del'].append(fn)
148                 elif '_get_' in fn:
149                     lib[shortname]['get'].append(fn)
150                 elif '_set_' in fn:
151                     lib[shortname]['set'].append(fn)
152                 else:
153                     #print "no idea what to do about", fn
154                     lib[shortname]['other'].append(fn)
155     return lib
156
157 def print_cpp_output_results(lib, cpp_output):
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} {:s}".format(o, family, lib[o][family] ) )
175
176
177 def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
178     if not os.path.isdir(output_path): os.mkdir(output_path)
179     elif not overwrite: return sorted(glob.glob(os.path.join(output_path, '*.c')))
180
181     cpp_output, cpp_objects = get_cpp_objects(header, usedouble=usedouble)
182
183     lib = analyze_cpp_output(cpp_objects, cpp_output)
184     # print_cpp_output_results(lib, cpp_output)
185
186     sources_list = []
187     try:
188         from .gen_code import MappedObject
189     except (SystemError, ValueError):
190         from gen_code import MappedObject
191     for o in lib:
192         out = source_header
193         mapped = MappedObject(lib[o], usedouble = usedouble)
194         out += mapped.gen_code()
195         output_file = os.path.join(output_path, 'gen-%s.c' % o)
196         with open(output_file, 'w') as f:
197             f.write(out)
198             print ("wrote %s" % output_file )
199             sources_list.append(output_file)
200
201     out = source_header
202     out += "#include \"aubio-generated.h\""
203     check_types = "\n     ||  ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
204     out += """
205
206 int generated_types_ready (void)
207 {{
208   return ({pycheck_types});
209 }}
210 """.format(pycheck_types = check_types)
211
212     add_types = "".join(["""
213   Py_INCREF (&Py_{name}Type);
214   PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
215     out += """
216
217 void add_generated_objects ( PyObject *m )
218 {{
219 {add_types}
220 }}
221 """.format(add_types = add_types)
222
223     output_file = os.path.join(output_path, 'aubio-generated.c')
224     with open(output_file, 'w') as f:
225         f.write(out)
226         print ("wrote %s" % output_file )
227         sources_list.append(output_file)
228
229     objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
230     out = """// generated list of objects created with gen_external.py
231
232 #include <Python.h>
233 """
234     if usedouble:
235         out += """
236 #ifndef HAVE_AUBIO_DOUBLE
237 #define HAVE_AUBIO_DOUBLE 1
238 #endif
239 """
240     out += """
241 {objlist}
242 int generated_objects ( void );
243 void add_generated_objects( PyObject *m );
244 """.format(objlist = objlist)
245
246     output_file = os.path.join(output_path, 'aubio-generated.h')
247     with open(output_file, 'w') as f:
248         f.write(out)
249         print ("wrote %s" % output_file )
250         # no need to add header to list of sources
251
252     return sources_list
253
254 if __name__ == '__main__':
255     if len(sys.argv) > 1: header = sys.argv[1]
256     if len(sys.argv) > 2: output_path = sys.argv[2]
257     generate_external(header, output_path)