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->hop_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',
99 name = proto.replace(' *', '* ').split()[1].split('(')[0]
100 name = name.replace('*','')
101 if name == '': raise ValueError(proto + "gave empty name")
104 def get_return_type(proto):
106 paramregex = re.compile('(\w+ ?\*?).*')
107 outputs = paramregex.findall(proto)
108 assert len(outputs) == 1
109 return outputs[0].replace(' ', '')
112 """ arg = 'foo *name'
113 return ['foo*', 'name'] """
115 type_arg = {} #'type': l[0], 'name': l[1]}
116 type_arg['type'] = " ".join(l[:-1])
117 type_arg['name'] = l[-1]
119 if type_arg['name'].startswith('*'):
120 # ['foo', '*name'] -> ['foo*', 'name']
121 type_arg['type'] += '*'
122 type_arg['name'] = type_arg['name'][1:]
123 if type_arg['type'].endswith(' *'):
124 # ['foo *', 'name'] -> ['foo*', 'name']
125 type_arg['type'] = type_arg['type'].replace(' *','*')
126 if type_arg['type'].startswith('const '):
127 # ['foo *', 'name'] -> ['foo*', 'name']
128 type_arg['type'] = type_arg['type'].replace('const ','')
131 def get_params(proto):
132 """ get the list of parameters from a function prototype
133 example: proto = "int main (int argc, char ** argv)"
134 returns: ['int argc', 'char ** argv']
137 paramregex = re.compile('.*\((.*)\);')
138 a = paramregex.findall(proto)[0].split(', ')
139 #a = [i.replace('const ', '') for i in a]
142 def get_input_params(proto):
143 a = get_params(proto)
144 return [i.replace('const ', '') for i in a if (i.startswith('const ') or i.startswith('uint_t ') or i.startswith('smpl_t '))]
146 def get_output_params(proto):
147 a = get_params(proto)
148 return [i for i in a if not i.startswith('const ')][1:]
150 def get_params_types_names(proto):
151 """ get the list of parameters from a function prototype
152 example: proto = "int main (int argc, char ** argv)"
153 returns: [['int', 'argc'], ['char **','argv']]
155 a = list(map(split_type, get_params(proto)))
157 #import sys; sys.exit(1)
160 class MappedObject(object):
162 def __init__(self, prototypes, usedouble = False):
164 pyargparse_chars['smpl_t'] = 'd'
165 self.prototypes = prototypes
167 self.shortname = prototypes['shortname']
168 self.longname = prototypes['longname']
169 self.new_proto = prototypes['new'][0]
170 self.del_proto = prototypes['del'][0]
171 self.do_proto = prototypes['do'][0]
172 self.input_params = get_params_types_names(self.new_proto)
173 self.input_params_list = "; ".join(get_input_params(self.new_proto))
174 self.outputs = get_params_types_names(self.do_proto)[2:]
175 self.do_inputs = [get_params_types_names(self.do_proto)[1]]
176 self.do_outputs = get_params_types_names(self.do_proto)[2:]
177 struct_output_str = ["PyObject *{0[name]}; {1} c_{0[name]}".format(i, i['type'][:-1]) for i in self.do_outputs]
178 self.struct_outputs = ";\n ".join(struct_output_str)
180 #print ("input_params: ", map(split_type, get_input_params(self.do_proto)))
181 #print ("output_params", map(split_type, get_output_params(self.do_proto)))
185 out += self.gen_struct()
186 out += self.gen_doc()
187 out += self.gen_new()
188 out += self.gen_init()
189 out += self.gen_del()
191 out += self.gen_memberdef()
192 out += self.gen_set()
193 out += self.gen_get()
194 out += self.gen_methodef()
195 out += self.gen_typeobject()
198 def gen_struct(self):
200 // {shortname} structure
203 // pointer to aubio object
213 # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
214 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')
215 return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
219 // TODO: add documentation
220 static char Py_{shortname}_doc[] = \"undefined\";
222 return out.format(**self.__dict__)
228 Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
230 Py_{shortname} *self;
231 """.format(**self.__dict__)
232 params = self.input_params
235 {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
236 plist = ", ".join(["\"%s\"" % p['name'] for p in params])
238 static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
239 argchars = "".join([pyargparse_chars[p['type']] for p in params])
240 arglist = ", ".join(["&%s" % p['name'] for p in params])
242 if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
246 """.format(argchars = argchars, arglist = arglist)
248 self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
252 """.format(**self.__dict__)
253 params = self.input_params
255 out += self.check_valid(p)
257 return (PyObject *)self;
262 def check_valid(self, p):
263 if p['type'] == 'uint_t':
264 return self.check_valid_uint(p)
265 if p['type'] == 'char_t*':
266 return self.check_valid_char(p)
268 print ("ERROR, no idea how to check %s for validity" % p['type'])
270 def check_valid_uint(self, p):
273 self->{name} = {defval};
274 if ((sint_t){name} > 0) {{
275 self->{name} = {name};
276 }} else if ((sint_t){name} < 0) {{
277 PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
280 """.format(defval = aubiodefvalue[name], name = name)
282 def check_valid_char(self, p):
285 self->{name} = {defval};
286 if ({name} != NULL) {{
287 self->{name} = {name};
289 """.format(defval = aubiodefvalue[name], name = name)
295 Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
297 """.format(**self.__dict__)
298 new_name = get_name(self.new_proto)
299 new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
301 self->o = {new_name}({new_params});
302 """.format(new_name = new_name, new_params = new_params)
304 paramvals = "self->method"
306 // return -1 and set error string on failure
307 if (self->o == NULL) {{
308 PyErr_Format (PyExc_Exception, "failed creating {shortname}");
311 """.format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
313 for o in self.outputs:
315 self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
317 // TODO get internal params after actual object creation?
320 // create outputs{output_create}
321 """.format(output_create = output_create)
328 def gen_memberdef(self):
330 static PyMemberDef Py_{shortname}_members[] = {{
331 """.format(**self.__dict__)
332 for p in get_params_types_names(self.new_proto):
333 tmp = " {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
334 pytype = member_types[p['type']]
335 out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
336 out += """ {NULL}, // sentinel
345 Py_{shortname}_del (Py_{shortname} * self, PyObject * unused)
346 {{""".format(**self.__dict__)
347 for input_param in self.do_inputs:
348 if input_param['type'] == 'fmat_t *':
350 free(self->{0[name]}.data);""".format(input_param)
351 for o in self.outputs:
353 del_out = delfromtype_fn[o['type']]
355 {del_out}(self->{name});""".format(del_out = del_out, name = name)
356 del_fn = get_name(self.del_proto)
361 Py_TYPE(self)->tp_free((PyObject *) self);
363 """.format(del_fn = del_fn)
370 Py_{shortname}_do (Py_{shortname} * self, PyObject * args)
371 {{""".format(**self.__dict__)
372 input_params = self.do_inputs
373 output_params = self.do_outputs
376 for input_param in input_params:
378 PyObject *py_{0};""".format(input_param['name'])
379 refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
380 pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
382 if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
384 }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
385 for input_param in input_params:
388 if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
390 }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
391 if self.shortname in objinputsize:
394 if (self->{0[name]}.length != {expected_size}) {{
395 PyErr_Format (PyExc_ValueError,
396 "input size of {shortname} should be %d, not %d",
397 {expected_size}, self->{0[name]}.length);
399 }}""".format(input_param, expected_size = objinputsize[self.shortname], **self.__dict__)
403 // TODO: check input sizes"""
404 for output_param in output_params:
407 Py_INCREF(self->{0[name]});
408 if (!{pytoaubio}(self->{0[name]}, &(self->c_{0[name]}))) {{
410 }}""".format(output_param, pytoaubio = pytoaubio_fn[output_param['type']])
411 do_fn = get_name(self.do_proto)
412 inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
413 c_outputs = ", ".join(["&(self->c_%s)" % p['name'] for p in self.do_outputs])
414 outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
417 {do_fn}(self->o, {inputs}, {c_outputs});
423 inputs = inputs, outputs = outputs, c_outputs = c_outputs,
429 // {shortname} setters
430 """.format(**self.__dict__)
431 for set_param in self.prototypes['set']:
432 params = get_params_types_names(set_param)[1]
433 paramtype = params['type']
434 method_name = get_name(set_param)
435 param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
436 pyparamtype = pyargparse_chars[paramtype]
439 Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
444 if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
447 err = aubio_{shortname}_set_{param} (self->o, {param});
450 PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
455 """.format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
460 // {shortname} getters
461 """.format(**self.__dict__)
462 for method in self.prototypes['get']:
463 params = get_params_types_names(method)
464 method_name = get_name(method)
465 assert len(params) == 1, \
466 "get method has more than one parameter %s" % params
467 param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
468 paramtype = get_return_type(method)
469 ptypeconv = pyfromtype_fn[paramtype]
472 Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
474 {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
475 return (PyObject *){ptypeconv} ({param});
477 """.format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
481 def gen_methodef(self):
483 static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
484 for m in self.prototypes['set']:
486 shortname = name.replace('aubio_%s_' % self.shortname, '')
488 {{"{shortname}", (PyCFunction) Py{name},
489 METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
490 for m in self.prototypes['get']:
492 shortname = name.replace('aubio_%s_' % self.shortname, '')
494 {{"{shortname}", (PyCFunction) Py{name},
495 METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
497 {NULL} /* sentinel */
502 def gen_typeobject(self):
504 PyTypeObject Py_{shortname}Type = {{
505 //PyObject_HEAD_INIT (NULL)
507 PyVarObject_HEAD_INIT (NULL, 0)
509 sizeof (Py_{shortname}),
511 (destructor) Py_{shortname}_del,
521 (ternaryfunc)Py_{shortname}_do,
534 Py_{shortname}_methods,
535 Py_{shortname}_members,
542 (initproc) Py_{shortname}_init,
555 """.format(**self.__dict__)