2 # we have some clean up to do
3 'buf_size': 'Py_default_vector_length',
4 'win_s': 'Py_default_vector_length',
6 'hop_size': 'Py_default_vector_length / 2',
7 'hop_s': 'Py_default_vector_length / 2',
8 # these should be alright
9 'samplerate': 'Py_aubio_default_samplerate',
10 # now for the non obvious ones
20 'method': '"default"',
26 'char_t*': 'T_STRING',
28 'smpl_t': 'AUBIO_NPY_SMPL',
32 'smpl_t': 'PyFloat_FromDouble',
33 'uint_t': 'PyLong_FromLong', # was: 'PyInt_FromLong',
34 'fvec_t*': 'PyAubio_CFvecToArray',
35 'fmat_t*': 'PyAubio_CFmatToArray',
39 'fvec_t*': 'PyAubio_ArrayToCFvec',
40 'cvec_t*': 'PyAubio_PyCvecToCCvec',
41 #'fmat_t*': 'PyAubio_ArrayToCFmat',
45 'fvec_t*': 'new_py_fvec',
46 'fmat_t*': 'new_py_fmat',
47 'cvec_t*': 'new_py_cvec',
51 'fvec_t*': 'Py_DECREF',
52 'fmat_t*': 'Py_DECREF',
53 'cvec_t*': 'Py_DECREF',
65 'smpl_t': 'f', # if not usedouble else 'd',
78 'wavetable': 'self->hop_size',
79 'sampler': 'self->hop_size',
80 'mfcc': 'self->n_coeffs',
83 'filterbank': 'self->n_filters',
84 'tss': 'self->buf_size',
88 'mfcc': 'self->buf_size / 2 + 1',
89 'notes': 'self->hop_size',
90 'onset': 'self->hop_size',
91 'pitch': 'self->hop_size',
92 'sampler': 'self->hop_size',
93 'specdesc': 'self->buf_size / 2 + 1',
94 'tempo': 'self->hop_size',
95 'wavetable': 'self->hop_size',
96 'tss': 'self->buf_size / 2 + 1',
100 name = proto.replace(' *', '* ').split()[1].split('(')[0]
101 name = name.replace('*','')
102 if name == '': raise ValueError(proto + "gave empty name")
105 def get_return_type(proto):
107 paramregex = re.compile('(\w+ ?\*?).*')
108 outputs = paramregex.findall(proto)
109 assert len(outputs) == 1
110 return outputs[0].replace(' ', '')
113 """ arg = 'foo *name'
114 return ['foo*', 'name'] """
116 type_arg = {} #'type': l[0], 'name': l[1]}
117 type_arg['type'] = " ".join(l[:-1])
118 type_arg['name'] = l[-1]
120 if type_arg['name'].startswith('*'):
121 # ['foo', '*name'] -> ['foo*', 'name']
122 type_arg['type'] += '*'
123 type_arg['name'] = type_arg['name'][1:]
124 if type_arg['type'].endswith(' *'):
125 # ['foo *', 'name'] -> ['foo*', 'name']
126 type_arg['type'] = type_arg['type'].replace(' *','*')
127 if type_arg['type'].startswith('const '):
128 # ['foo *', 'name'] -> ['foo*', 'name']
129 type_arg['type'] = type_arg['type'].replace('const ','')
132 def get_params(proto):
133 """ get the list of parameters from a function prototype
134 example: proto = "int main (int argc, char ** argv)"
135 returns: ['int argc', 'char ** argv']
138 paramregex = re.compile('.*\((.*)\);')
139 a = paramregex.findall(proto)[0].split(', ')
140 #a = [i.replace('const ', '') for i in a]
143 def get_input_params(proto):
144 a = get_params(proto)
145 return [i.replace('const ', '') for i in a if (i.startswith('const ') or i.startswith('uint_t ') or i.startswith('smpl_t '))]
147 def get_output_params(proto):
148 a = get_params(proto)
149 return [i for i in a if not i.startswith('const ')][1:]
151 def get_params_types_names(proto):
152 """ get the list of parameters from a function prototype
153 example: proto = "int main (int argc, char ** argv)"
154 returns: [['int', 'argc'], ['char **','argv']]
156 a = list(map(split_type, get_params(proto)))
158 #import sys; sys.exit(1)
161 class MappedObject(object):
163 def __init__(self, prototypes, usedouble = False):
165 pyargparse_chars['smpl_t'] = 'd'
166 self.prototypes = prototypes
168 self.shortname = prototypes['shortname']
169 self.longname = prototypes['longname']
170 self.new_proto = prototypes['new'][0]
171 self.del_proto = prototypes['del'][0]
172 self.do_proto = prototypes['do'][0]
173 self.input_params = get_params_types_names(self.new_proto)
174 self.input_params_list = "; ".join(get_input_params(self.new_proto))
175 self.outputs = get_params_types_names(self.do_proto)[2:]
176 self.do_inputs = [get_params_types_names(self.do_proto)[1]]
177 self.do_outputs = get_params_types_names(self.do_proto)[2:]
178 struct_output_str = ["PyObject *{0[name]}; {1} c_{0[name]}".format(i, i['type'][:-1]) for i in self.do_outputs]
179 self.struct_outputs = ";\n ".join(struct_output_str)
181 #print ("input_params: ", map(split_type, get_input_params(self.do_proto)))
182 #print ("output_params", map(split_type, get_output_params(self.do_proto)))
187 out += self.gen_struct()
188 out += self.gen_doc()
189 out += self.gen_new()
190 out += self.gen_init()
191 out += self.gen_del()
193 out += self.gen_memberdef()
194 out += self.gen_set()
195 out += self.gen_get()
196 out += self.gen_methodef()
197 out += self.gen_typeobject()
198 except Exception as e:
199 print ("Failed generating code for", self.shortname)
203 def gen_struct(self):
205 // {shortname} structure
208 // pointer to aubio object
218 # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
219 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')
220 return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
224 // TODO: add documentation
225 static char Py_{shortname}_doc[] = \"undefined\";
227 return out.format(**self.__dict__)
233 Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
235 Py_{shortname} *self;
236 """.format(**self.__dict__)
237 params = self.input_params
240 {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
241 plist = ", ".join(["\"%s\"" % p['name'] for p in params])
243 static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
244 argchars = "".join([pyargparse_chars[p['type']] for p in params])
245 arglist = ", ".join(["&%s" % p['name'] for p in params])
247 if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
251 """.format(argchars = argchars, arglist = arglist)
253 self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
257 """.format(**self.__dict__)
258 params = self.input_params
260 out += self.check_valid(p)
262 return (PyObject *)self;
267 def check_valid(self, p):
268 if p['type'] == 'uint_t':
269 return self.check_valid_uint(p)
270 if p['type'] == 'char_t*':
271 return self.check_valid_char(p)
273 print ("ERROR, no idea how to check %s for validity" % p['type'])
275 def check_valid_uint(self, p):
278 self->{name} = {defval};
279 if ((sint_t){name} > 0) {{
280 self->{name} = {name};
281 }} else if ((sint_t){name} < 0) {{
282 PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
285 """.format(defval = aubiodefvalue[name], name = name)
287 def check_valid_char(self, p):
290 self->{name} = {defval};
291 if ({name} != NULL) {{
292 self->{name} = {name};
294 """.format(defval = aubiodefvalue[name], name = name)
300 Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
302 """.format(**self.__dict__)
303 new_name = get_name(self.new_proto)
304 new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
306 self->o = {new_name}({new_params});
307 """.format(new_name = new_name, new_params = new_params)
309 paramvals = "self->method"
311 // return -1 and set error string on failure
312 if (self->o == NULL) {{
313 PyErr_Format (PyExc_RuntimeError, "failed creating {shortname}");
316 """.format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
318 for o in self.outputs:
320 self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
322 // TODO get internal params after actual object creation?
325 // create outputs{output_create}
326 """.format(output_create = output_create)
333 def gen_memberdef(self):
335 static PyMemberDef Py_{shortname}_members[] = {{
336 """.format(**self.__dict__)
337 for p in get_params_types_names(self.new_proto):
338 tmp = " {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
339 pytype = member_types[p['type']]
340 out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
341 out += """ {NULL}, // sentinel
350 Py_{shortname}_del (Py_{shortname} * self, PyObject * unused)
351 {{""".format(**self.__dict__)
352 for input_param in self.do_inputs:
353 if input_param['type'] == 'fmat_t *':
355 free(self->{0[name]}.data);""".format(input_param)
356 for o in self.outputs:
358 del_out = delfromtype_fn[o['type']]
361 {del_out}(self->{name});
362 }}""".format(del_out = del_out, name = name)
363 del_fn = get_name(self.del_proto)
368 Py_TYPE(self)->tp_free((PyObject *) self);
370 """.format(del_fn = del_fn)
377 Py_{shortname}_do (Py_{shortname} * self, PyObject * args)
378 {{""".format(**self.__dict__)
379 input_params = self.do_inputs
380 output_params = self.do_outputs
384 PyObject *outputs;"""
385 for input_param in input_params:
387 PyObject *py_{0};""".format(input_param['name'])
388 refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
389 pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
391 if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
393 }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
394 for input_param in input_params:
397 if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
399 }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
400 if self.shortname in objinputsize:
403 if (self->{0[name]}.length != {expected_size}) {{
404 PyErr_Format (PyExc_ValueError,
405 "input size of {shortname} should be %d, not %d",
406 {expected_size}, self->{0[name]}.length);
408 }}""".format(input_param, expected_size = objinputsize[self.shortname], **self.__dict__)
412 // TODO: check input sizes"""
413 for output_param in output_params:
416 Py_INCREF(self->{0[name]});
417 if (!{pytoaubio}(self->{0[name]}, &(self->c_{0[name]}))) {{
419 }}""".format(output_param, pytoaubio = pytoaubio_fn[output_param['type']])
420 do_fn = get_name(self.do_proto)
421 inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
422 c_outputs = ", ".join(["&(self->c_%s)" % p['name'] for p in self.do_outputs])
423 outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
426 {do_fn}(self->o, {inputs}, {c_outputs});
429 inputs = inputs, c_outputs = c_outputs,
431 if len(self.do_outputs) > 1:
433 outputs = PyTuple_New({:d});""".format(len(self.do_outputs))
434 for i, p in enumerate(self.do_outputs):
436 PyTuple_SetItem( outputs, {i}, self->{p[name]});""".format(i = i, p = p)
439 outputs = self->{p[name]};""".format(p = self.do_outputs[0])
451 // {shortname} setters
452 """.format(**self.__dict__)
453 for set_param in self.prototypes['set']:
454 params = get_params_types_names(set_param)[1]
455 paramtype = params['type']
456 method_name = get_name(set_param)
457 param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
458 pyparamtype = pyargparse_chars[paramtype]
461 Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
466 if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
469 err = aubio_{shortname}_set_{param} (self->o, {param});
472 PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
477 """.format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
482 // {shortname} getters
483 """.format(**self.__dict__)
484 for method in self.prototypes['get']:
485 params = get_params_types_names(method)
486 method_name = get_name(method)
487 assert len(params) == 1, \
488 "get method has more than one parameter %s" % params
489 param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
490 paramtype = get_return_type(method)
491 ptypeconv = pyfromtype_fn[paramtype]
494 Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
496 {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
497 return (PyObject *){ptypeconv} ({param});
499 """.format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
503 def gen_methodef(self):
505 static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
506 for m in self.prototypes['set']:
508 shortname = name.replace('aubio_%s_' % self.shortname, '')
510 {{"{shortname}", (PyCFunction) Py{name},
511 METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
512 for m in self.prototypes['get']:
514 shortname = name.replace('aubio_%s_' % self.shortname, '')
516 {{"{shortname}", (PyCFunction) Py{name},
517 METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
519 {NULL} /* sentinel */
524 def gen_typeobject(self):
526 PyTypeObject Py_{shortname}Type = {{
527 //PyObject_HEAD_INIT (NULL)
529 PyVarObject_HEAD_INIT (NULL, 0)
531 sizeof (Py_{shortname}),
533 (destructor) Py_{shortname}_del,
543 (ternaryfunc)Py_{shortname}_do,
556 Py_{shortname}_methods,
557 Py_{shortname}_members,
564 (initproc) Py_{shortname}_init,
577 """.format(**self.__dict__)