python/lib/gen_external.py: use os.path.join
[aubio.git] / python / lib / gen_external.py
1 import os, glob
2
3 header = os.path.join('src', 'aubio.h')
4 output_path = os.path.join('python', 'gen')
5
6 source_header = """// this file is generated! do not modify
7 #include "aubio-types.h"
8 """
9
10 skip_objects = [
11   # already in ext/
12   'fft',
13   'pvoc',
14   'filter',
15   'filterbank',
16   #'resampler',
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   'tss',
44   ]
45
46
47 def get_cpp_objects(header=header):
48
49     cpp_output = [l.strip() for l in os.popen('cpp -DAUBIO_UNSTABLE=1 {:s}'.format(header)).readlines()]
50     #cpp_output = [l.strip() for l in os.popen('cpp -DAUBIO_UNSTABLE=0 -I../build/src ../src/onset/onset.h').readlines()]
51     #cpp_output = [l.strip() for l in os.popen('cpp -DAUBIO_UNSTABLE=0 -I../build/src ../src/pitch/pitch.h').readlines()]
52
53     cpp_output = filter(lambda y: len(y) > 1, cpp_output)
54     cpp_output = filter(lambda y: not y.startswith('#'), cpp_output)
55     cpp_output = list(cpp_output)
56
57     i = 1
58     while 1:
59         if i >= len(cpp_output): break
60         if cpp_output[i-1].endswith(',') or cpp_output[i-1].endswith('{') or cpp_output[i].startswith('}'):
61             cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
62             cpp_output.pop(i-1)
63         else:
64             i += 1
65
66     typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
67
68     cpp_objects = [a.split()[3][:-1] for a in typedefs]
69
70     return cpp_output, cpp_objects
71
72 def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
73     if not os.path.isdir(output_path): os.mkdir(output_path)
74     elif overwrite == False: return glob.glob(os.path.join(output_path, '*.c'))
75     sources_list = []
76     cpp_output, cpp_objects = get_cpp_objects(header)
77     lib = {}
78
79     for o in cpp_objects:
80         if o[:6] != 'aubio_':
81             continue
82         shortname = o[6:-2]
83         if shortname in skip_objects:
84             continue
85         lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
86         lib[shortname]['longname'] = o
87         lib[shortname]['shortname'] = shortname
88         for fn in cpp_output:
89             if o[:-1] in fn:
90                 #print "found", o[:-1], "in", fn
91                 if 'typedef struct ' in fn:
92                     lib[shortname]['struct'].append(fn)
93                 elif '_do' in fn:
94                     lib[shortname]['do'].append(fn)
95                 elif 'new_' in fn:
96                     lib[shortname]['new'].append(fn)
97                 elif 'del_' in fn:
98                     lib[shortname]['del'].append(fn)
99                 elif '_get_' in fn:
100                     lib[shortname]['get'].append(fn)
101                 elif '_set_' in fn:
102                     lib[shortname]['set'].append(fn)
103                 else:
104                     #print "no idea what to do about", fn
105                     lib[shortname]['other'].append(fn)
106
107     """
108     for fn in cpp_output:
109         found = 0
110         for o in lib:
111             for family in lib[o]:
112                 if fn in lib[o][family]:
113                     found = 1
114         if found == 0:
115             print "missing", fn
116
117     for o in lib:
118         for family in lib[o]:
119             if type(lib[o][family]) == str:
120                 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
121             elif len(lib[o][family]) == 1:
122                 print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
123             else:
124                 print ( "{:15s} {:10s} {:d}".format(o, family, len(lib[o][family]) ) )
125     """
126
127     try:
128         from .gen_code import MappedObject
129     except (SystemError, ValueError) as e:
130         from gen_code import MappedObject
131     for o in lib:
132         out = source_header
133         mapped = MappedObject(lib[o], usedouble = usedouble)
134         out += mapped.gen_code()
135         output_file = os.path.join(output_path, 'gen-%s.c' % o)
136         with open(output_file, 'w') as f:
137             f.write(out)
138             print ("wrote %s" % output_file )
139             sources_list.append(output_file)
140
141     out = source_header
142     out += "#include \"aubio-generated.h\""
143     check_types = "\n     ||  ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
144     out += """
145
146 int generated_types_ready (void)
147 {{
148   return ({pycheck_types});
149 }}
150 """.format(pycheck_types = check_types)
151
152     add_types = "".join(["""
153   Py_INCREF (&Py_{name}Type);
154   PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
155     out += """
156
157 void add_generated_objects ( PyObject *m )
158 {{
159 {add_types}
160 }}
161 """.format(add_types = add_types)
162
163     output_file = os.path.join(output_path, 'aubio-generated.c')
164     with open(output_file, 'w') as f:
165         f.write(out)
166         print ("wrote %s" % output_file )
167         sources_list.append(output_file)
168
169     objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
170     out = """// generated list of objects created with gen_external.py
171
172 #include <Python.h>
173 """
174     if usedouble:
175         out += """
176 #ifndef HAVE_AUBIO_DOUBLE
177 #define HAVE_AUBIO_DOUBLE 1
178 #endif
179 """
180     out += """
181 {objlist}
182 int generated_objects ( void );
183 void add_generated_objects( PyObject *m );
184 """.format(objlist = objlist)
185
186     output_file = os.path.join(output_path, 'aubio-generated.h')
187     with open(output_file, 'w') as f:
188         f.write(out)
189         print ("wrote %s" % output_file )
190         # no need to add header to list of sources
191
192     return sources_list
193
194 if __name__ == '__main__':
195     import sys
196     if len(sys.argv) > 1: header = sys.argv[1]
197     if len(sys.argv) > 2: output_path = sys.argv[2]
198     generate_external(header, output_path)