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)))
186 out += self.gen_struct()
187 out += self.gen_doc()
188 out += self.gen_new()
189 out += self.gen_init()
190 out += self.gen_del()
192 out += self.gen_memberdef()
193 out += self.gen_set()
194 out += self.gen_get()
195 out += self.gen_methodef()
196 out += self.gen_typeobject()
199 def gen_struct(self):
201 // {shortname} structure
204 // pointer to aubio object
214 # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
215 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')
216 return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
220 // TODO: add documentation
221 static char Py_{shortname}_doc[] = \"undefined\";
223 return out.format(**self.__dict__)
229 Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
231 Py_{shortname} *self;
232 """.format(**self.__dict__)
233 params = self.input_params
236 {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
237 plist = ", ".join(["\"%s\"" % p['name'] for p in params])
239 static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
240 argchars = "".join([pyargparse_chars[p['type']] for p in params])
241 arglist = ", ".join(["&%s" % p['name'] for p in params])
243 if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
247 """.format(argchars = argchars, arglist = arglist)
249 self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
253 """.format(**self.__dict__)
254 params = self.input_params
256 out += self.check_valid(p)
258 return (PyObject *)self;
263 def check_valid(self, p):
264 if p['type'] == 'uint_t':
265 return self.check_valid_uint(p)
266 if p['type'] == 'char_t*':
267 return self.check_valid_char(p)
269 print ("ERROR, no idea how to check %s for validity" % p['type'])
271 def check_valid_uint(self, p):
274 self->{name} = {defval};
275 if ((sint_t){name} > 0) {{
276 self->{name} = {name};
277 }} else if ((sint_t){name} < 0) {{
278 PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
281 """.format(defval = aubiodefvalue[name], name = name)
283 def check_valid_char(self, p):
286 self->{name} = {defval};
287 if ({name} != NULL) {{
288 self->{name} = {name};
290 """.format(defval = aubiodefvalue[name], name = name)
296 Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
298 """.format(**self.__dict__)
299 new_name = get_name(self.new_proto)
300 new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
302 self->o = {new_name}({new_params});
303 """.format(new_name = new_name, new_params = new_params)
305 paramvals = "self->method"
307 // return -1 and set error string on failure
308 if (self->o == NULL) {{
309 PyErr_Format (PyExc_RuntimeError, "failed creating {shortname}");
312 """.format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
314 for o in self.outputs:
316 self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
318 // TODO get internal params after actual object creation?
321 // create outputs{output_create}
322 """.format(output_create = output_create)
329 def gen_memberdef(self):
331 static PyMemberDef Py_{shortname}_members[] = {{
332 """.format(**self.__dict__)
333 for p in get_params_types_names(self.new_proto):
334 tmp = " {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
335 pytype = member_types[p['type']]
336 out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
337 out += """ {NULL}, // sentinel
346 Py_{shortname}_del (Py_{shortname} * self, PyObject * unused)
347 {{""".format(**self.__dict__)
348 for input_param in self.do_inputs:
349 if input_param['type'] == 'fmat_t *':
351 free(self->{0[name]}.data);""".format(input_param)
352 for o in self.outputs:
354 del_out = delfromtype_fn[o['type']]
357 {del_out}(self->{name});
358 }}""".format(del_out = del_out, name = name)
359 del_fn = get_name(self.del_proto)
364 Py_TYPE(self)->tp_free((PyObject *) self);
366 """.format(del_fn = del_fn)
373 Py_{shortname}_do (Py_{shortname} * self, PyObject * args)
374 {{""".format(**self.__dict__)
375 input_params = self.do_inputs
376 output_params = self.do_outputs
380 PyObject *outputs;"""
381 for input_param in input_params:
383 PyObject *py_{0};""".format(input_param['name'])
384 refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
385 pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
387 if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
389 }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
390 for input_param in input_params:
393 if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
395 }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
396 if self.shortname in objinputsize:
399 if (self->{0[name]}.length != {expected_size}) {{
400 PyErr_Format (PyExc_ValueError,
401 "input size of {shortname} should be %d, not %d",
402 {expected_size}, self->{0[name]}.length);
404 }}""".format(input_param, expected_size = objinputsize[self.shortname], **self.__dict__)
408 // TODO: check input sizes"""
409 for output_param in output_params:
412 Py_INCREF(self->{0[name]});
413 if (!{pytoaubio}(self->{0[name]}, &(self->c_{0[name]}))) {{
415 }}""".format(output_param, pytoaubio = pytoaubio_fn[output_param['type']])
416 do_fn = get_name(self.do_proto)
417 inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
418 c_outputs = ", ".join(["&(self->c_%s)" % p['name'] for p in self.do_outputs])
419 outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
422 {do_fn}(self->o, {inputs}, {c_outputs});
425 inputs = inputs, c_outputs = c_outputs,
427 if len(self.do_outputs) > 1:
429 outputs = PyTuple_New(2);""".format(len(self.do_outputs))
430 for i, p in enumerate(self.do_outputs):
432 PyTuple_SetItem( outputs, {i}, self->{p[name]});""".format(i = i, p = p)
435 outputs = self->{p[name]};""".format(p = self.do_outputs[0])
447 // {shortname} setters
448 """.format(**self.__dict__)
449 for set_param in self.prototypes['set']:
450 params = get_params_types_names(set_param)[1]
451 paramtype = params['type']
452 method_name = get_name(set_param)
453 param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
454 pyparamtype = pyargparse_chars[paramtype]
457 Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
462 if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
465 err = aubio_{shortname}_set_{param} (self->o, {param});
468 PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
473 """.format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
478 // {shortname} getters
479 """.format(**self.__dict__)
480 for method in self.prototypes['get']:
481 params = get_params_types_names(method)
482 method_name = get_name(method)
483 assert len(params) == 1, \
484 "get method has more than one parameter %s" % params
485 param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
486 paramtype = get_return_type(method)
487 ptypeconv = pyfromtype_fn[paramtype]
490 Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
492 {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
493 return (PyObject *){ptypeconv} ({param});
495 """.format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
499 def gen_methodef(self):
501 static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
502 for m in self.prototypes['set']:
504 shortname = name.replace('aubio_%s_' % self.shortname, '')
506 {{"{shortname}", (PyCFunction) Py{name},
507 METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
508 for m in self.prototypes['get']:
510 shortname = name.replace('aubio_%s_' % self.shortname, '')
512 {{"{shortname}", (PyCFunction) Py{name},
513 METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
515 {NULL} /* sentinel */
520 def gen_typeobject(self):
522 PyTypeObject Py_{shortname}Type = {{
523 //PyObject_HEAD_INIT (NULL)
525 PyVarObject_HEAD_INIT (NULL, 0)
527 sizeof (Py_{shortname}),
529 (destructor) Py_{shortname}_del,
539 (ternaryfunc)Py_{shortname}_do,
552 Py_{shortname}_methods,
553 Py_{shortname}_members,
560 (initproc) Py_{shortname}_init,
573 """.format(**self.__dict__)