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 name = proto.replace(' *', '* ').split()[1].split('(')[0]
89 name = name.replace('*','')
90 if name == '': raise ValueError(proto + "gave empty name")
93 def get_return_type(proto):
95 paramregex = re.compile('(\w+ ?\*?).*')
96 outputs = paramregex.findall(proto)
97 assert len(outputs) == 1
98 return outputs[0].replace(' ', '')
101 """ arg = 'foo *name'
102 return ['foo*', 'name'] """
104 type_arg = {} #'type': l[0], 'name': l[1]}
105 type_arg['type'] = " ".join(l[:-1])
106 type_arg['name'] = l[-1]
108 if type_arg['name'].startswith('*'):
109 # ['foo', '*name'] -> ['foo*', 'name']
110 type_arg['type'] += '*'
111 type_arg['name'] = type_arg['name'][1:]
112 if type_arg['type'].endswith(' *'):
113 # ['foo *', 'name'] -> ['foo*', 'name']
114 type_arg['type'] = type_arg['type'].replace(' *','*')
115 if type_arg['type'].startswith('const '):
116 # ['foo *', 'name'] -> ['foo*', 'name']
117 type_arg['type'] = type_arg['type'].replace('const ','')
120 def get_params(proto):
121 """ get the list of parameters from a function prototype
122 example: proto = "int main (int argc, char ** argv)"
123 returns: ['int argc', 'char ** argv']
126 paramregex = re.compile('.*\((.*)\);')
127 a = paramregex.findall(proto)[0].split(', ')
128 #a = [i.replace('const ', '') for i in a]
131 def get_input_params(proto):
132 a = get_params(proto)
133 return [i.replace('const ', '') for i in a if (i.startswith('const ') or i.startswith('uint_t ') or i.startswith('smpl_t '))]
135 def get_output_params(proto):
136 a = get_params(proto)
137 return [i for i in a if not i.startswith('const ')][1:]
139 def get_params_types_names(proto):
140 """ get the list of parameters from a function prototype
141 example: proto = "int main (int argc, char ** argv)"
142 returns: [['int', 'argc'], ['char **','argv']]
144 a = list(map(split_type, get_params(proto)))
146 #import sys; sys.exit(1)
149 class MappedObject(object):
151 def __init__(self, prototypes, usedouble = False):
153 pyargparse_chars['smpl_t'] = 'd'
154 self.prototypes = prototypes
156 self.shortname = prototypes['shortname']
157 self.longname = prototypes['longname']
158 self.new_proto = prototypes['new'][0]
159 self.del_proto = prototypes['del'][0]
160 self.do_proto = prototypes['do'][0]
161 self.input_params = get_params_types_names(self.new_proto)
162 self.input_params_list = "; ".join(get_input_params(self.new_proto))
163 self.outputs = get_params_types_names(self.do_proto)[2:]
164 self.do_inputs = [get_params_types_names(self.do_proto)[1]]
165 self.do_outputs = get_params_types_names(self.do_proto)[2:]
166 struct_output_str = ["PyObject *{0[name]}; {1} c_{0[name]}".format(i, i['type'][:-1]) for i in self.do_outputs]
167 self.struct_outputs = ";\n ".join(struct_output_str)
169 #print ("input_params: ", map(split_type, get_input_params(self.do_proto)))
170 #print ("output_params", map(split_type, get_output_params(self.do_proto)))
174 out += self.gen_struct()
175 out += self.gen_doc()
176 out += self.gen_new()
177 out += self.gen_init()
178 out += self.gen_del()
180 out += self.gen_memberdef()
181 out += self.gen_set()
182 out += self.gen_get()
183 out += self.gen_methodef()
184 out += self.gen_typeobject()
187 def gen_struct(self):
189 // {shortname} structure
192 // pointer to aubio object
202 # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
203 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')
204 return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
208 // TODO: add documentation
209 static char Py_{shortname}_doc[] = \"undefined\";
211 return out.format(**self.__dict__)
217 Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
219 Py_{shortname} *self;
220 """.format(**self.__dict__)
221 params = self.input_params
224 {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
225 plist = ", ".join(["\"%s\"" % p['name'] for p in params])
227 static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
228 argchars = "".join([pyargparse_chars[p['type']] for p in params])
229 arglist = ", ".join(["&%s" % p['name'] for p in params])
231 if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
235 """.format(argchars = argchars, arglist = arglist)
237 self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
241 """.format(**self.__dict__)
242 params = self.input_params
244 out += self.check_valid(p)
246 return (PyObject *)self;
251 def check_valid(self, p):
252 if p['type'] == 'uint_t':
253 return self.check_valid_uint(p)
254 if p['type'] == 'char_t*':
255 return self.check_valid_char(p)
257 print ("ERROR, no idea how to check %s for validity" % p['type'])
259 def check_valid_uint(self, p):
262 self->{name} = {defval};
263 if ((sint_t){name} > 0) {{
264 self->{name} = {name};
265 }} else if ((sint_t){name} < 0) {{
266 PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
269 """.format(defval = aubiodefvalue[name], name = name)
271 def check_valid_char(self, p):
274 self->{name} = {defval};
275 if ({name} != NULL) {{
276 self->{name} = {name};
278 """.format(defval = aubiodefvalue[name], name = name)
284 Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
286 """.format(**self.__dict__)
287 new_name = get_name(self.new_proto)
288 new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
290 self->o = {new_name}({new_params});
291 """.format(new_name = new_name, new_params = new_params)
293 paramvals = "self->method"
295 // return -1 and set error string on failure
296 if (self->o == NULL) {{
297 PyErr_Format (PyExc_Exception, "failed creating {shortname}");
300 """.format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
302 for o in self.outputs:
304 self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
306 // TODO get internal params after actual object creation?
309 // create outputs{output_create}
310 """.format(output_create = output_create)
317 def gen_memberdef(self):
319 static PyMemberDef Py_{shortname}_members[] = {{
320 """.format(**self.__dict__)
321 for p in get_params_types_names(self.new_proto):
322 tmp = " {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
323 pytype = member_types[p['type']]
324 out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
325 out += """ {NULL}, // sentinel
334 Py_{shortname}_del (Py_{shortname} * self, PyObject * unused)
335 {{""".format(**self.__dict__)
336 for input_param in self.do_inputs:
337 if input_param['type'] == 'fmat_t *':
339 free(self->{0[name]}.data);""".format(input_param)
340 for o in self.outputs:
342 del_out = delfromtype_fn[o['type']]
344 {del_out}(self->{name});""".format(del_out = del_out, name = name)
345 del_fn = get_name(self.del_proto)
350 Py_TYPE(self)->tp_free((PyObject *) self);
352 """.format(del_fn = del_fn)
359 Py_{shortname}_do (Py_{shortname} * self, PyObject * args)
360 {{""".format(**self.__dict__)
361 input_params = self.do_inputs
362 output_params = self.do_outputs
365 for input_param in input_params:
367 PyObject *py_{0};""".format(input_param['name'])
368 refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
369 pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
371 if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
373 }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
374 for input_param in input_params:
377 if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
379 }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
382 // TODO: check input sizes"""
383 for output_param in output_params:
386 Py_INCREF(self->{0[name]});
387 if (!{pytoaubio}(self->{0[name]}, &(self->c_{0[name]}))) {{
389 }}""".format(output_param, pytoaubio = pytoaubio_fn[output_param['type']])
390 do_fn = get_name(self.do_proto)
391 inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
392 c_outputs = ", ".join(["&(self->c_%s)" % p['name'] for p in self.do_outputs])
393 outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
396 {do_fn}(self->o, {inputs}, {c_outputs});
402 inputs = inputs, outputs = outputs, c_outputs = c_outputs,
408 // {shortname} setters
409 """.format(**self.__dict__)
410 for set_param in self.prototypes['set']:
411 params = get_params_types_names(set_param)[1]
412 paramtype = params['type']
413 method_name = get_name(set_param)
414 param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
415 pyparamtype = pyargparse_chars[paramtype]
418 Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
423 if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
426 err = aubio_{shortname}_set_{param} (self->o, {param});
429 PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
434 """.format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
439 // {shortname} getters
440 """.format(**self.__dict__)
441 for method in self.prototypes['get']:
442 params = get_params_types_names(method)
443 method_name = get_name(method)
444 assert len(params) == 1, \
445 "get method has more than one parameter %s" % params
446 param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
447 paramtype = get_return_type(method)
448 ptypeconv = pyfromtype_fn[paramtype]
451 Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
453 {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
454 return (PyObject *){ptypeconv} ({param});
456 """.format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
460 def gen_methodef(self):
462 static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
463 for m in self.prototypes['set']:
465 shortname = name.replace('aubio_%s_' % self.shortname, '')
467 {{"{shortname}", (PyCFunction) Py{name},
468 METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
469 for m in self.prototypes['get']:
471 shortname = name.replace('aubio_%s_' % self.shortname, '')
473 {{"{shortname}", (PyCFunction) Py{name},
474 METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
476 {NULL} /* sentinel */
481 def gen_typeobject(self):
483 PyTypeObject Py_{shortname}Type = {{
484 //PyObject_HEAD_INIT (NULL)
486 PyVarObject_HEAD_INIT (NULL, 0)
488 sizeof (Py_{shortname}),
490 (destructor) Py_{shortname}_del,
500 (ternaryfunc)Py_{shortname}_do,
513 Py_{shortname}_methods,
514 Py_{shortname}_members,
521 (initproc) Py_{shortname}_init,
534 """.format(**self.__dict__)