Merge branch 'master' into dct
[aubio.git] / python / lib / gen_code.py
1 aubiodefvalue = {
2     # we have some clean up to do
3     'buf_size': 'Py_default_vector_length',
4     'win_s': 'Py_default_vector_length',
5     'size': 'Py_default_vector_length',
6     # and here too
7     'hop_size': 'Py_default_vector_length / 2',
8     'hop_s': 'Py_default_vector_length / 2',
9     # these should be alright
10     'samplerate': 'Py_aubio_default_samplerate',
11     # now for the non obvious ones
12     'n_filters': '40',
13     'n_coeffs': '13',
14     'nelems': '10',
15     'flow': '0.',
16     'fhig': '1.',
17     'ilow': '0.',
18     'ihig': '1.',
19     'thrs': '0.5',
20     'ratio': '0.5',
21     'method': '"default"',
22     'uri': '"none"',
23     }
24
25 member_types = {
26         'name': 'type',
27         'char_t*': 'T_STRING',
28         'uint_t': 'T_INT',
29         'smpl_t': 'AUBIO_NPY_SMPL',
30         }
31
32 pyfromtype_fn = {
33         'smpl_t': 'PyFloat_FromDouble',
34         'uint_t': 'PyLong_FromLong', # was: 'PyInt_FromLong',
35         'fvec_t*': 'PyAubio_CFvecToArray',
36         'fmat_t*': 'PyAubio_CFmatToArray',
37         }
38
39 pytoaubio_fn = {
40         'fvec_t*': 'PyAubio_ArrayToCFvec',
41         'cvec_t*': 'PyAubio_PyCvecToCCvec',
42         #'fmat_t*': 'PyAubio_ArrayToCFmat',
43         }
44
45 newfromtype_fn = {
46         'fvec_t*': 'new_py_fvec',
47         'fmat_t*': 'new_py_fmat',
48         'cvec_t*': 'new_py_cvec',
49         }
50
51 delfromtype_fn = {
52         'fvec_t*': 'Py_DECREF',
53         'fmat_t*': 'Py_DECREF',
54         'cvec_t*': 'Py_DECREF',
55         }
56
57 param_init = {
58         'char_t*': 'NULL',
59         'uint_t': '0',
60         'sint_t': 0,
61         'smpl_t': 0.,
62         'lsmp_t': 0.,
63         }
64
65 pyargparse_chars = {
66         'smpl_t': 'f', # if not usedouble else 'd',
67         'uint_t': 'I',
68         'sint_t': 'I',
69         'char_t*': 's',
70         'fmat_t*': 'O',
71         'fvec_t*': 'O',
72         'cvec_t*': 'O',
73         }
74
75 objoutsize = {
76         'onset': '1',
77         'pitch': '1',
78         'notes': '3',
79         'wavetable': 'self->hop_size',
80         'sampler': 'self->hop_size',
81         'mfcc': 'self->n_coeffs',
82         'specdesc': '1',
83         'tempo': '1',
84         'filterbank': 'self->n_filters',
85         'tss': 'self->buf_size',
86         'dct': 'self->size',
87         }
88
89 objinputsize = {
90         'mfcc': 'self->buf_size / 2 + 1',
91         'notes': 'self->hop_size',
92         'onset': 'self->hop_size',
93         'pitch': 'self->hop_size',
94         'sampler': 'self->hop_size',
95         'specdesc': 'self->buf_size / 2 + 1',
96         'tempo': 'self->hop_size',
97         'wavetable': 'self->hop_size',
98         'tss': 'self->buf_size / 2 + 1',
99         }
100
101 def get_name(proto):
102     name = proto.replace(' *', '* ').split()[1].split('(')[0]
103     name = name.replace('*','')
104     if name == '': raise ValueError(proto + "gave empty name")
105     return name
106
107 def get_return_type(proto):
108     import re
109     paramregex = re.compile('(\w+ ?\*?).*')
110     outputs = paramregex.findall(proto)
111     assert len(outputs) == 1
112     return outputs[0].replace(' ', '')
113
114 def split_type(arg):
115     """ arg = 'foo *name' 
116         return ['foo*', 'name'] """
117     l = arg.split()
118     type_arg = {} #'type': l[0], 'name': l[1]}
119     type_arg['type'] = " ".join(l[:-1])
120     type_arg['name'] = l[-1]
121     # fix up type / name
122     if type_arg['name'].startswith('*'):
123         # ['foo', '*name'] -> ['foo*', 'name']
124         type_arg['type'] += '*'
125         type_arg['name'] = type_arg['name'][1:]
126     if type_arg['type'].endswith(' *'):
127         # ['foo *', 'name'] -> ['foo*', 'name']
128         type_arg['type'] = type_arg['type'].replace(' *','*')
129     if type_arg['type'].startswith('const '):
130         # ['foo *', 'name'] -> ['foo*', 'name']
131         type_arg['type'] = type_arg['type'].replace('const ','')
132     return type_arg
133
134 def get_params(proto):
135     """ get the list of parameters from a function prototype
136     example: proto = "int main (int argc, char ** argv)"
137     returns: ['int argc', 'char ** argv']
138     """
139     import re
140     paramregex = re.compile('.*\((.*)\);')
141     a = paramregex.findall(proto)[0].split(', ')
142     #a = [i.replace('const ', '') for i in a]
143     return a
144
145 def get_input_params(proto):
146     a = get_params(proto)
147     return [i.replace('const ', '') for i in a if (i.startswith('const ') or i.startswith('uint_t ') or i.startswith('smpl_t '))]
148
149 def get_output_params(proto):
150     a = get_params(proto)
151     return [i for i in a if not i.startswith('const ')][1:]
152
153 def get_params_types_names(proto):
154     """ get the list of parameters from a function prototype
155     example: proto = "int main (int argc, char ** argv)"
156     returns: [['int', 'argc'], ['char **','argv']]
157     """
158     a = list(map(split_type, get_params(proto)))
159     #print proto, a
160     #import sys; sys.exit(1)
161     return a
162
163 class MappedObject(object):
164
165     def __init__(self, prototypes, usedouble = False):
166         if usedouble:
167             pyargparse_chars['smpl_t'] = 'd'
168         self.prototypes = prototypes
169
170         self.shortname = prototypes['shortname']
171         self.longname = prototypes['longname']
172         self.new_proto = prototypes['new'][0]
173         self.del_proto = prototypes['del'][0]
174         self.do_proto = prototypes['do'][0]
175         self.input_params = get_params_types_names(self.new_proto)
176         self.input_params_list = "; ".join(get_input_params(self.new_proto))
177         self.outputs = get_params_types_names(self.do_proto)[2:]
178         self.do_inputs = [get_params_types_names(self.do_proto)[1]]
179         self.do_outputs = get_params_types_names(self.do_proto)[2:]
180         struct_output_str = ["PyObject *{0[name]}; {1} c_{0[name]}".format(i, i['type'][:-1]) for i in self.do_outputs]
181         self.struct_outputs = ";\n    ".join(struct_output_str)
182
183         #print ("input_params: ", map(split_type, get_input_params(self.do_proto)))
184         #print ("output_params", map(split_type, get_output_params(self.do_proto)))
185
186     def gen_code(self):
187         out = ""
188         try:
189             out += self.gen_struct()
190             out += self.gen_doc()
191             out += self.gen_new()
192             out += self.gen_init()
193             out += self.gen_del()
194             out += self.gen_do()
195             if len(self.prototypes['rdo']):
196                 self.do_proto = self.prototypes['rdo'][0]
197                 self.do_inputs = [get_params_types_names(self.do_proto)[1]]
198                 self.do_outputs = get_params_types_names(self.do_proto)[2:]
199                 out += self.gen_do(method='rdo')
200             out += self.gen_memberdef()
201             out += self.gen_set()
202             out += self.gen_get()
203             out += self.gen_methodef()
204             out += self.gen_typeobject()
205         except Exception as e:
206             print ("Failed generating code for", self.shortname)
207             raise
208         return out
209
210     def gen_struct(self):
211         out = """
212 // {shortname} structure
213 typedef struct{{
214     PyObject_HEAD
215     // pointer to aubio object
216     {longname} *o;
217     // input parameters
218     {input_params_list};
219     // do input vectors
220     {do_inputs_list};
221     // output results
222     {struct_outputs};
223 }} Py_{shortname};
224 """
225         # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
226         do_inputs_list = "; ".join(get_input_params(self.do_proto)).replace('fvec_t *','fvec_t').replace('fmat_t *', 'fmat_t').replace('cvec_t *', 'cvec_t')
227         return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
228
229     def gen_doc(self):
230         out = """
231 // TODO: add documentation
232 static char Py_{shortname}_doc[] = \"undefined\";
233 """
234         return out.format(**self.__dict__)
235
236     def gen_new(self):
237         out = """
238 // new {shortname}
239 static PyObject *
240 Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
241 {{
242     Py_{shortname} *self;
243 """.format(**self.__dict__)
244         params = self.input_params
245         for p in params:
246             out += """
247     {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
248         plist = ", ".join(["\"%s\"" % p['name'] for p in params])
249         out += """
250     static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
251         argchars = "".join([pyargparse_chars[p['type']] for p in params])
252         arglist = ", ".join(["&%s" % p['name'] for p in params])
253         out += """
254     if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
255               {arglist})) {{
256         return NULL;
257     }}
258 """.format(argchars = argchars, arglist = arglist)
259         out += """
260     self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
261     if (self == NULL) {{
262         return NULL;
263     }}
264 """.format(**self.__dict__)
265         params = self.input_params
266         for p in params:
267             out += self.check_valid(p)
268         out += """
269     return (PyObject *)self;
270 }
271 """
272         return out
273
274     def check_valid(self, p):
275         if p['type'] == 'uint_t':
276             return self.check_valid_uint(p)
277         if p['type'] == 'char_t*':
278             return self.check_valid_char(p)
279         else:
280             print ("ERROR, no idea how to check %s for validity" % p['type'])
281
282     def check_valid_uint(self, p):
283         name = p['name']
284         return """
285     self->{name} = {defval};
286     if ((sint_t){name} > 0) {{
287         self->{name} = {name};
288     }} else if ((sint_t){name} < 0) {{
289         PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
290         return NULL;
291     }}
292 """.format(defval = aubiodefvalue[name], name = name)
293
294     def check_valid_char(self, p):
295         name = p['name']
296         return """
297     self->{name} = {defval};
298     if ({name} != NULL) {{
299         self->{name} = {name};
300     }}
301 """.format(defval = aubiodefvalue[name], name = name)
302
303     def gen_init(self):
304         out = """
305 // init {shortname}
306 static int
307 Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
308 {{
309 """.format(**self.__dict__)
310         new_name = get_name(self.new_proto)
311         new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
312         out += """
313   self->o = {new_name}({new_params});
314 """.format(new_name = new_name, new_params = new_params)
315         paramchars = "%s"
316         paramvals = "self->method"
317         out += """
318   // return -1 and set error string on failure
319   if (self->o == NULL) {{
320     PyErr_Format (PyExc_RuntimeError, "failed creating {shortname}");
321     return -1;
322   }}
323 """.format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
324         output_create = ""
325         for o in self.outputs:
326             output_create += """
327   self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
328         out += """
329   // TODO get internal params after actual object creation?
330 """
331         out += """
332   // create outputs{output_create}
333 """.format(output_create = output_create)
334         out += """
335   return 0;
336 }
337 """
338         return out
339
340     def gen_memberdef(self):
341         out = """
342 static PyMemberDef Py_{shortname}_members[] = {{
343 """.format(**self.__dict__)
344         for p in get_params_types_names(self.new_proto):
345             tmp = "  {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
346             pytype = member_types[p['type']]
347             out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
348         out += """  {NULL}, // sentinel
349 };
350 """
351         return out
352
353     def gen_del(self):
354         out = """
355 // del {shortname}
356 static void
357 Py_{shortname}_del  (Py_{shortname} * self, PyObject * unused)
358 {{""".format(**self.__dict__)
359         for input_param in self.do_inputs:
360             if input_param['type'] == 'fmat_t *':
361                 out += """
362   free(self->{0[name]}.data);""".format(input_param)
363         for o in self.outputs:
364             name = o['name']
365             del_out = delfromtype_fn[o['type']]
366             out += """
367   if (self->{name}) {{
368     {del_out}(self->{name});
369   }}""".format(del_out = del_out, name = name)
370         del_fn = get_name(self.del_proto)
371         out += """
372   if (self->o) {{
373     {del_fn}(self->o);
374   }}
375   Py_TYPE(self)->tp_free((PyObject *) self);
376 }}
377 """.format(del_fn = del_fn)
378         return out
379
380     def gen_do(self, method = 'do'):
381         out = """
382 // do {shortname}
383 static PyObject*
384 Pyaubio_{shortname}_{method}  (Py_{shortname} * self, PyObject * args)
385 {{""".format(**self.__dict__, method = method)
386         input_params = self.do_inputs
387         output_params = self.do_outputs
388         #print input_params
389         #print output_params
390         out += """
391     PyObject *outputs;"""
392         for input_param in input_params:
393             out += """
394     PyObject *py_{0};""".format(input_param['name'])
395         refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
396         pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
397         out += """
398     if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
399         return NULL;
400     }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
401         for input_param in input_params:
402             out += """
403
404     if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
405         return NULL;
406     }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
407         if self.shortname in objinputsize:
408             out += """
409
410     if (self->{0[name]}.length != {expected_size}) {{
411         PyErr_Format (PyExc_ValueError,
412             "input size of {shortname} should be %d, not %d",
413             {expected_size}, self->{0[name]}.length);
414         return NULL;
415     }}""".format(input_param, expected_size = objinputsize[self.shortname], **self.__dict__)
416         else:
417             out += """
418
419     // TODO: check input sizes"""
420         for output_param in output_params:
421             out += """
422
423     Py_INCREF(self->{0[name]});
424     if (!{pytoaubio}(self->{0[name]}, &(self->c_{0[name]}))) {{
425         return NULL;
426     }}""".format(output_param, pytoaubio = pytoaubio_fn[output_param['type']])
427         do_fn = get_name(self.do_proto)
428         inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
429         c_outputs = ", ".join(["&(self->c_%s)" % p['name'] for p in self.do_outputs])
430         outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
431         out += """
432
433     {do_fn}(self->o, {inputs}, {c_outputs});
434 """.format(
435         do_fn = do_fn,
436         inputs = inputs, c_outputs = c_outputs,
437         )
438         if len(self.do_outputs) > 1:
439             out += """
440     outputs = PyTuple_New({:d});""".format(len(self.do_outputs))
441             for i, p in enumerate(self.do_outputs):
442                 out += """
443     PyTuple_SetItem( outputs, {i}, self->{p[name]});""".format(i = i, p = p)
444         else:
445             out += """
446     outputs = self->{p[name]};""".format(p = self.do_outputs[0])
447         out += """
448
449     return outputs;
450 }}
451 """.format(
452         outputs = outputs,
453         )
454         return out
455
456     def gen_set(self):
457         out = """
458 // {shortname} setters
459 """.format(**self.__dict__)
460         for set_param in self.prototypes['set']:
461             params = get_params_types_names(set_param)[1]
462             paramtype = params['type']
463             method_name = get_name(set_param)
464             param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
465             pyparamtype = pyargparse_chars[paramtype]
466             out += """
467 static PyObject *
468 Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
469 {{
470   uint_t err = 0;
471   {paramtype} {param};
472
473   if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
474     return NULL;
475   }}
476   err = aubio_{shortname}_set_{param} (self->o, {param});
477
478   if (err > 0) {{
479     PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
480     return NULL;
481   }}
482   Py_RETURN_NONE;
483 }}
484 """.format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
485         return out
486
487     def gen_get(self):
488         out = """
489 // {shortname} getters
490 """.format(**self.__dict__)
491         for method in self.prototypes['get']:
492             params = get_params_types_names(method)
493             method_name = get_name(method)
494             assert len(params) == 1, \
495                 "get method has more than one parameter %s" % params
496             param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
497             paramtype = get_return_type(method)
498             ptypeconv = pyfromtype_fn[paramtype]
499             out += """
500 static PyObject *
501 Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
502 {{
503   {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
504   return (PyObject *){ptypeconv} ({param});
505 }}
506 """.format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
507         **self.__dict__)
508         return out
509
510     def gen_methodef(self):
511         out = """
512 static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
513         for m in self.prototypes['set']:
514             name = get_name(m)
515             shortname = name.replace('aubio_%s_' % self.shortname, '')
516             out += """
517   {{"{shortname}", (PyCFunction) Py{name},
518     METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
519         for m in self.prototypes['get']:
520             name = get_name(m)
521             shortname = name.replace('aubio_%s_' % self.shortname, '')
522             out += """
523   {{"{shortname}", (PyCFunction) Py{name},
524     METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
525         for m in self.prototypes['rdo']:
526             name = get_name(m)
527             shortname = name.replace('aubio_%s_' % self.shortname, '')
528             out += """
529   {{"{shortname}", (PyCFunction) Py{name},
530     METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
531         out += """
532   {NULL} /* sentinel */
533 };
534 """
535         return out
536
537     def gen_typeobject(self):
538         return """
539 PyTypeObject Py_{shortname}Type = {{
540   //PyObject_HEAD_INIT (NULL)
541   //0,
542   PyVarObject_HEAD_INIT (NULL, 0)
543   "aubio.{shortname}",
544   sizeof (Py_{shortname}),
545   0,
546   (destructor) Py_{shortname}_del,
547   0,
548   0,
549   0,
550   0,
551   0,
552   0,
553   0,
554   0,
555   0,
556   (ternaryfunc)Pyaubio_{shortname}_do,
557   0,
558   0,
559   0,
560   0,
561   Py_TPFLAGS_DEFAULT,
562   Py_{shortname}_doc,
563   0,
564   0,
565   0,
566   0,
567   0,
568   0,
569   Py_{shortname}_methods,
570   Py_{shortname}_members,
571   0,
572   0,
573   0,
574   0,
575   0,
576   0,
577   (initproc) Py_{shortname}_init,
578   0,
579   Py_{shortname}_new,
580   0,
581   0,
582   0,
583   0,
584   0,
585   0,
586   0,
587   0,
588   0,
589 }};
590 """.format(**self.__dict__)