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',
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
21 'method': '"default"',
27 'char_t*': 'T_STRING',
29 'smpl_t': 'AUBIO_NPY_SMPL',
33 'smpl_t': 'PyFloat_FromDouble',
34 'uint_t': 'PyLong_FromLong', # was: 'PyInt_FromLong',
35 'fvec_t*': 'PyAubio_CFvecToArray',
36 'fmat_t*': 'PyAubio_CFmatToArray',
40 'fvec_t*': 'PyAubio_ArrayToCFvec',
41 'cvec_t*': 'PyAubio_PyCvecToCCvec',
42 #'fmat_t*': 'PyAubio_ArrayToCFmat',
46 'fvec_t*': 'new_py_fvec',
47 'fmat_t*': 'new_py_fmat',
48 'cvec_t*': 'new_py_cvec',
52 'fvec_t*': 'Py_DECREF',
53 'fmat_t*': 'Py_DECREF',
54 'cvec_t*': 'Py_DECREF',
66 'smpl_t': 'f', # if not usedouble else 'd',
79 'wavetable': 'self->hop_size',
80 'sampler': 'self->hop_size',
81 'mfcc': 'self->n_coeffs',
84 'filterbank': 'self->n_filters',
85 'tss': 'self->buf_size',
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',
102 name = proto.replace(' *', '* ').split()[1].split('(')[0]
103 name = name.replace('*','')
104 if name == '': raise ValueError(proto + "gave empty name")
107 def get_return_type(proto):
109 paramregex = re.compile('(\w+ ?\*?).*')
110 outputs = paramregex.findall(proto)
111 assert len(outputs) == 1
112 return outputs[0].replace(' ', '')
115 """ arg = 'foo *name'
116 return ['foo*', 'name'] """
118 type_arg = {} #'type': l[0], 'name': l[1]}
119 type_arg['type'] = " ".join(l[:-1])
120 type_arg['name'] = l[-1]
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 ','')
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']
140 paramregex = re.compile('.*\((.*)\);')
141 a = paramregex.findall(proto)[0].split(', ')
142 #a = [i.replace('const ', '') for i in a]
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 '))]
149 def get_output_params(proto):
150 a = get_params(proto)
151 return [i for i in a if not i.startswith('const ')][1:]
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']]
158 a = list(map(split_type, get_params(proto)))
160 #import sys; sys.exit(1)
163 class MappedObject(object):
165 def __init__(self, prototypes, usedouble = False):
167 pyargparse_chars['smpl_t'] = 'd'
168 self.prototypes = prototypes
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)
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)))
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()
195 out += self.gen_memberdef()
196 out += self.gen_set()
197 out += self.gen_get()
198 out += self.gen_methodef()
199 out += self.gen_typeobject()
200 except Exception as e:
201 print ("Failed generating code for", self.shortname)
205 def gen_struct(self):
207 // {shortname} structure
210 // pointer to aubio object
220 # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
221 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')
222 return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
226 // TODO: add documentation
227 static char Py_{shortname}_doc[] = \"undefined\";
229 return out.format(**self.__dict__)
235 Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
237 Py_{shortname} *self;
238 """.format(**self.__dict__)
239 params = self.input_params
242 {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
243 plist = ", ".join(["\"%s\"" % p['name'] for p in params])
245 static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
246 argchars = "".join([pyargparse_chars[p['type']] for p in params])
247 arglist = ", ".join(["&%s" % p['name'] for p in params])
249 if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
253 """.format(argchars = argchars, arglist = arglist)
255 self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
259 """.format(**self.__dict__)
260 params = self.input_params
262 out += self.check_valid(p)
264 return (PyObject *)self;
269 def check_valid(self, p):
270 if p['type'] == 'uint_t':
271 return self.check_valid_uint(p)
272 if p['type'] == 'char_t*':
273 return self.check_valid_char(p)
275 print ("ERROR, no idea how to check %s for validity" % p['type'])
277 def check_valid_uint(self, p):
280 self->{name} = {defval};
281 if ((sint_t){name} > 0) {{
282 self->{name} = {name};
283 }} else if ((sint_t){name} < 0) {{
284 PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
287 """.format(defval = aubiodefvalue[name], name = name)
289 def check_valid_char(self, p):
292 self->{name} = {defval};
293 if ({name} != NULL) {{
294 self->{name} = {name};
296 """.format(defval = aubiodefvalue[name], name = name)
302 Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
304 """.format(**self.__dict__)
305 new_name = get_name(self.new_proto)
306 new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
308 self->o = {new_name}({new_params});
309 """.format(new_name = new_name, new_params = new_params)
311 paramvals = "self->method"
313 // return -1 and set error string on failure
314 if (self->o == NULL) {{
315 PyErr_Format (PyExc_RuntimeError, "failed creating {shortname}");
318 """.format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
320 for o in self.outputs:
322 self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
324 // TODO get internal params after actual object creation?
327 // create outputs{output_create}
328 """.format(output_create = output_create)
335 def gen_memberdef(self):
337 static PyMemberDef Py_{shortname}_members[] = {{
338 """.format(**self.__dict__)
339 for p in get_params_types_names(self.new_proto):
340 tmp = " {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
341 pytype = member_types[p['type']]
342 out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
343 out += """ {NULL}, // sentinel
352 Py_{shortname}_del (Py_{shortname} * self, PyObject * unused)
353 {{""".format(**self.__dict__)
354 for input_param in self.do_inputs:
355 if input_param['type'] == 'fmat_t *':
357 free(self->{0[name]}.data);""".format(input_param)
358 for o in self.outputs:
360 del_out = delfromtype_fn[o['type']]
363 {del_out}(self->{name});
364 }}""".format(del_out = del_out, name = name)
365 del_fn = get_name(self.del_proto)
370 Py_TYPE(self)->tp_free((PyObject *) self);
372 """.format(del_fn = del_fn)
379 Py_{shortname}_do (Py_{shortname} * self, PyObject * args)
380 {{""".format(**self.__dict__)
381 input_params = self.do_inputs
382 output_params = self.do_outputs
386 PyObject *outputs;"""
387 for input_param in input_params:
389 PyObject *py_{0};""".format(input_param['name'])
390 refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
391 pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
393 if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
395 }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
396 for input_param in input_params:
399 if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
401 }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
402 if self.shortname in objinputsize:
405 if (self->{0[name]}.length != {expected_size}) {{
406 PyErr_Format (PyExc_ValueError,
407 "input size of {shortname} should be %d, not %d",
408 {expected_size}, self->{0[name]}.length);
410 }}""".format(input_param, expected_size = objinputsize[self.shortname], **self.__dict__)
414 // TODO: check input sizes"""
415 for output_param in output_params:
418 Py_INCREF(self->{0[name]});
419 if (!{pytoaubio}(self->{0[name]}, &(self->c_{0[name]}))) {{
421 }}""".format(output_param, pytoaubio = pytoaubio_fn[output_param['type']])
422 do_fn = get_name(self.do_proto)
423 inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
424 c_outputs = ", ".join(["&(self->c_%s)" % p['name'] for p in self.do_outputs])
425 outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
428 {do_fn}(self->o, {inputs}, {c_outputs});
431 inputs = inputs, c_outputs = c_outputs,
433 if len(self.do_outputs) > 1:
435 outputs = PyTuple_New({:d});""".format(len(self.do_outputs))
436 for i, p in enumerate(self.do_outputs):
438 PyTuple_SetItem( outputs, {i}, self->{p[name]});""".format(i = i, p = p)
441 outputs = self->{p[name]};""".format(p = self.do_outputs[0])
453 // {shortname} setters
454 """.format(**self.__dict__)
455 for set_param in self.prototypes['set']:
456 params = get_params_types_names(set_param)[1]
457 paramtype = params['type']
458 method_name = get_name(set_param)
459 param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
460 pyparamtype = pyargparse_chars[paramtype]
463 Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
468 if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
471 err = aubio_{shortname}_set_{param} (self->o, {param});
474 PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
479 """.format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
484 // {shortname} getters
485 """.format(**self.__dict__)
486 for method in self.prototypes['get']:
487 params = get_params_types_names(method)
488 method_name = get_name(method)
489 assert len(params) == 1, \
490 "get method has more than one parameter %s" % params
491 param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
492 paramtype = get_return_type(method)
493 ptypeconv = pyfromtype_fn[paramtype]
496 Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
498 {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
499 return (PyObject *){ptypeconv} ({param});
501 """.format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
505 def gen_methodef(self):
507 static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
508 for m in self.prototypes['set']:
510 shortname = name.replace('aubio_%s_' % self.shortname, '')
512 {{"{shortname}", (PyCFunction) Py{name},
513 METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
514 for m in self.prototypes['get']:
516 shortname = name.replace('aubio_%s_' % self.shortname, '')
518 {{"{shortname}", (PyCFunction) Py{name},
519 METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
521 {NULL} /* sentinel */
526 def gen_typeobject(self):
528 PyTypeObject Py_{shortname}Type = {{
529 //PyObject_HEAD_INIT (NULL)
531 PyVarObject_HEAD_INIT (NULL, 0)
533 sizeof (Py_{shortname}),
535 (destructor) Py_{shortname}_del,
545 (ternaryfunc)Py_{shortname}_do,
558 Py_{shortname}_methods,
559 Py_{shortname}_members,
566 (initproc) Py_{shortname}_init,
579 """.format(**self.__dict__)