source: python/lib/gen_code.py @ 3d2e481

sampler
Last change on this file since 3d2e481 was 3d2e481, checked in by Paul Brossier <piem@piem.org>, 8 years ago

python/lib/gen_code.py: add ringbuffer

  • Property mode set to 100644
File size: 17.5 KB
Line 
1aubiodefvalue = {
2    # we have some clean up to do
3    'buf_size': 'Py_default_vector_length',
4    'win_s': 'Py_default_vector_length',
5    # and here too
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
11    'n_filters': '40',
12    'n_coeffs': '13',
13    'nelems': '10',
14    'flow': '0.',
15    'fhig': '1.',
16    'ilow': '0.',
17    'ihig': '1.',
18    'thrs': '0.5',
19    'ratio': '0.5',
20    'method': '"default"',
21    'uri': '"none"',
22    'transpose': '0.',
23    'maxwrite': 1024,
24    'maxrequest': 1024,
25    }
26
27member_types = {
28        'name': 'type',
29        'char_t*': 'T_STRING',
30        'uint_t': 'T_INT',
31        'smpl_t': 'AUBIO_NPY_SMPL',
32        }
33
34pyfromtype_fn = {
35        'smpl_t': 'PyFloat_FromDouble',
36        'uint_t': 'PyLong_FromLong', # was: 'PyInt_FromLong',
37        'fvec_t*': 'PyAubio_CFvecToArray',
38        'fmat_t*': 'PyAubio_CFmatToArray',
39        }
40
41pytoaubio_fn = {
42        'fvec_t*': 'PyAubio_ArrayToCFvec',
43        'cvec_t*': 'PyAubio_PyCvecToCCvec',
44        #'fmat_t*': 'PyAubio_ArrayToCFmat',
45        }
46
47newfromtype_fn = {
48        'fvec_t*': 'new_py_fvec',
49        'fmat_t*': 'new_py_fmat',
50        'cvec_t*': 'new_py_cvec',
51        }
52
53delfromtype_fn = {
54        'fvec_t*': 'Py_DECREF',
55        'fmat_t*': 'Py_DECREF',
56        'cvec_t*': 'Py_DECREF',
57        }
58
59param_init = {
60        'char_t*': 'NULL',
61        'uint_t': '0',
62        'sint_t': 0,
63        'smpl_t': 0.,
64        'lsmp_t': 0.,
65        }
66
67pyargparse_chars = {
68        'smpl_t': 'f', # if not usedouble else 'd',
69        'uint_t': 'I',
70        'sint_t': 'I',
71        'char_t*': 's',
72        'fmat_t*': 'O',
73        'fvec_t*': 'O',
74        'cvec_t*': 'O',
75        }
76
77objoutsize = {
78        'onset': '1',
79        'pitch': '1',
80        'notes': '3',
81        'wavetable': 'self->hop_size',
82        'sampler': 'self->hop_size',
83        'mfcc': 'self->n_coeffs',
84        'specdesc': '1',
85        'tempo': '1',
86        'filterbank': 'self->n_filters',
87        'tss': 'self->buf_size',
88        'pitchshift': 'self->hop_size',
89        'ringbuffer': 'self->maxrequest',
90        }
91
92objinputsize = {
93        'mfcc': 'self->buf_size / 2 + 1',
94        'notes': 'self->hop_size',
95        'onset': 'self->hop_size',
96        'pitch': 'self->hop_size',
97        'sampler': 'self->hop_size',
98        'specdesc': 'self->buf_size / 2 + 1',
99        'tempo': 'self->hop_size',
100        'wavetable': 'self->hop_size',
101        'tss': 'self->buf_size / 2 + 1',
102        'pitchshift': 'self->hop_size',
103        'ringbuffer': 'self->maxwrite',
104        }
105
106def get_name(proto):
107    name = proto.replace(' *', '* ').split()[1].split('(')[0]
108    name = name.replace('*','')
109    if name == '': raise ValueError(proto + "gave empty name")
110    return name
111
112def get_return_type(proto):
113    import re
114    paramregex = re.compile('(\w+ ?\*?).*')
115    outputs = paramregex.findall(proto)
116    assert len(outputs) == 1
117    return outputs[0].replace(' ', '')
118
119def split_type(arg):
120    """ arg = 'foo *name'
121        return ['foo*', 'name'] """
122    l = arg.split()
123    type_arg = {} #'type': l[0], 'name': l[1]}
124    type_arg['type'] = " ".join(l[:-1])
125    type_arg['name'] = l[-1]
126    # fix up type / name
127    if type_arg['name'].startswith('*'):
128        # ['foo', '*name'] -> ['foo*', 'name']
129        type_arg['type'] += '*'
130        type_arg['name'] = type_arg['name'][1:]
131    if type_arg['type'].endswith(' *'):
132        # ['foo *', 'name'] -> ['foo*', 'name']
133        type_arg['type'] = type_arg['type'].replace(' *','*')
134    if type_arg['type'].startswith('const '):
135        # ['foo *', 'name'] -> ['foo*', 'name']
136        type_arg['type'] = type_arg['type'].replace('const ','')
137    return type_arg
138
139def get_params(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']
143    """
144    import re
145    paramregex = re.compile('.*\((.*)\);')
146    a = paramregex.findall(proto)[0].split(', ')
147    #a = [i.replace('const ', '') for i in a]
148    return a
149
150def get_input_params(proto):
151    a = get_params(proto)
152    return [i.replace('const ', '') for i in a if (i.startswith('const ') or i.startswith('uint_t ') or i.startswith('smpl_t '))]
153
154def get_output_params(proto):
155    a = get_params(proto)
156    return [i for i in a if not i.startswith('const ')][1:]
157
158def get_params_types_names(proto):
159    """ get the list of parameters from a function prototype
160    example: proto = "int main (int argc, char ** argv)"
161    returns: [['int', 'argc'], ['char **','argv']]
162    """
163    a = list(map(split_type, get_params(proto)))
164    #print proto, a
165    #import sys; sys.exit(1)
166    return a
167
168class MappedObject(object):
169
170    def __init__(self, prototypes, usedouble = False):
171        if usedouble:
172            pyargparse_chars['smpl_t'] = 'd'
173        self.prototypes = prototypes
174
175        self.shortname = prototypes['shortname']
176        self.longname = prototypes['longname']
177        self.new_proto = prototypes['new'][0]
178        self.del_proto = prototypes['del'][0]
179        self.do_proto = prototypes['do'][0]
180        self.input_params = get_params_types_names(self.new_proto)
181        self.input_params_list = "; ".join(get_input_params(self.new_proto))
182        self.outputs = get_params_types_names(self.do_proto)[2:]
183        self.do_inputs = [get_params_types_names(self.do_proto)[1]]
184        self.do_outputs = get_params_types_names(self.do_proto)[2:]
185        struct_output_str = ["PyObject *{0[name]}; {1} c_{0[name]}".format(i, i['type'][:-1]) for i in self.do_outputs]
186        self.struct_outputs = ";\n    ".join(struct_output_str)
187
188        #print ("input_params: ", map(split_type, get_input_params(self.do_proto)))
189        #print ("output_params", map(split_type, get_output_params(self.do_proto)))
190
191    def gen_code(self):
192        out = ""
193        out += self.gen_struct()
194        out += self.gen_doc()
195        out += self.gen_new()
196        out += self.gen_init()
197        out += self.gen_del()
198        out += self.gen_do()
199        out += self.gen_memberdef()
200        out += self.gen_set()
201        out += self.gen_get()
202        out += self.gen_methodef()
203        out += self.gen_typeobject()
204        return out
205
206    def gen_struct(self):
207        out = """
208// {shortname} structure
209typedef struct{{
210    PyObject_HEAD
211    // pointer to aubio object
212    {longname} *o;
213    // input parameters
214    {input_params_list};
215    // do input vectors
216    {do_inputs_list};
217    // output results
218    {struct_outputs};
219}} Py_{shortname};
220"""
221        # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
222        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')
223        return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
224
225    def gen_doc(self):
226        out = """
227// TODO: add documentation
228static char Py_{shortname}_doc[] = \"undefined\";
229"""
230        return out.format(**self.__dict__)
231
232    def gen_new(self):
233        out = """
234// new {shortname}
235static PyObject *
236Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
237{{
238    Py_{shortname} *self;
239""".format(**self.__dict__)
240        params = self.input_params
241        for p in params:
242            out += """
243    {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
244        plist = ", ".join(["\"%s\"" % p['name'] for p in params])
245        out += """
246    static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
247        argchars = "".join([pyargparse_chars[p['type']] for p in params])
248        arglist = ", ".join(["&%s" % p['name'] for p in params])
249        out += """
250    if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
251              {arglist})) {{
252        return NULL;
253    }}
254""".format(argchars = argchars, arglist = arglist)
255        out += """
256    self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
257    if (self == NULL) {{
258        return NULL;
259    }}
260""".format(**self.__dict__)
261        params = self.input_params
262        for p in params:
263            out += self.check_valid(p)
264        out += """
265    return (PyObject *)self;
266}
267"""
268        return out
269
270    def check_valid(self, p):
271        if p['type'] == 'uint_t':
272            return self.check_valid_uint(p)
273        if p['type'] == 'char_t*':
274            return self.check_valid_char(p)
275        if p['type'] == 'smpl_t':
276            return self.check_valid_smpl(p)
277        else:
278            print ("ERROR, no idea how to check %s for validity" % p['type'])
279
280    def check_valid_uint(self, p):
281        name = p['name']
282        return """
283    self->{name} = {defval};
284    if ((sint_t){name} > 0) {{
285        self->{name} = {name};
286    }} else if ((sint_t){name} < 0) {{
287        PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
288        return NULL;
289    }}
290""".format(defval = aubiodefvalue[name], name = name)
291
292    def check_valid_char(self, p):
293        name = p['name']
294        return """
295    self->{name} = {defval};
296    if ({name} != NULL) {{
297        self->{name} = {name};
298    }}
299""".format(defval = aubiodefvalue[name], name = name)
300
301    def check_valid_smpl(self, p):
302        name = p['name']
303        return """
304    self->{name} = {defval};
305    if ({name} != 0.) {{
306        self->{name} = {name};
307    }}
308""".format(defval = aubiodefvalue[name], name = name)
309
310    def gen_init(self):
311        out = """
312// init {shortname}
313static int
314Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
315{{
316""".format(**self.__dict__)
317        new_name = get_name(self.new_proto)
318        new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
319        out += """
320  self->o = {new_name}({new_params});
321""".format(new_name = new_name, new_params = new_params)
322        paramchars = "%s"
323        paramvals = "self->method"
324        out += """
325  // return -1 and set error string on failure
326  if (self->o == NULL) {{
327    PyErr_Format (PyExc_RuntimeError, "failed creating {shortname}");
328    return -1;
329  }}
330""".format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
331        output_create = ""
332        for o in self.outputs:
333            output_create += """
334  self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
335        out += """
336  // TODO get internal params after actual object creation?
337"""
338        out += """
339  // create outputs{output_create}
340""".format(output_create = output_create)
341        out += """
342  return 0;
343}
344"""
345        return out
346
347    def gen_memberdef(self):
348        out = """
349static PyMemberDef Py_{shortname}_members[] = {{
350""".format(**self.__dict__)
351        for p in get_params_types_names(self.new_proto):
352            tmp = "  {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
353            pytype = member_types[p['type']]
354            out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
355        out += """  {NULL}, // sentinel
356};
357"""
358        return out
359
360    def gen_del(self):
361        out = """
362// del {shortname}
363static void
364Py_{shortname}_del  (Py_{shortname} * self, PyObject * unused)
365{{""".format(**self.__dict__)
366        for input_param in self.do_inputs:
367            if input_param['type'] == 'fmat_t *':
368                out += """
369  free(self->{0[name]}.data);""".format(input_param)
370        for o in self.outputs:
371            name = o['name']
372            del_out = delfromtype_fn[o['type']]
373            out += """
374  if (self->{name}) {{
375    {del_out}(self->{name});
376  }}""".format(del_out = del_out, name = name)
377        del_fn = get_name(self.del_proto)
378        out += """
379  if (self->o) {{
380    {del_fn}(self->o);
381  }}
382  Py_TYPE(self)->tp_free((PyObject *) self);
383}}
384""".format(del_fn = del_fn)
385        return out
386
387    def gen_do(self):
388        out = """
389// do {shortname}
390static PyObject*
391Py_{shortname}_do  (Py_{shortname} * self, PyObject * args)
392{{""".format(**self.__dict__)
393        input_params = self.do_inputs
394        output_params = self.do_outputs
395        #print input_params
396        #print output_params
397        out += """
398    PyObject *outputs;"""
399        for input_param in input_params:
400            out += """
401    PyObject *py_{0};""".format(input_param['name'])
402        refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
403        pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
404        out += """
405    if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
406        return NULL;
407    }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
408        for input_param in input_params:
409            out += """
410
411    if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
412        return NULL;
413    }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
414        if self.shortname in objinputsize:
415            out += """
416
417    if (self->{0[name]}.length != {expected_size}) {{
418        PyErr_Format (PyExc_ValueError,
419            "input size of {shortname} should be %d, not %d",
420            {expected_size}, self->{0[name]}.length);
421        return NULL;
422    }}""".format(input_param, expected_size = objinputsize[self.shortname], **self.__dict__)
423        else:
424            out += """
425
426    // TODO: check input sizes"""
427        for output_param in output_params:
428            out += """
429
430    Py_INCREF(self->{0[name]});
431    if (!{pytoaubio}(self->{0[name]}, &(self->c_{0[name]}))) {{
432        return NULL;
433    }}""".format(output_param, pytoaubio = pytoaubio_fn[output_param['type']])
434        do_fn = get_name(self.do_proto)
435        inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
436        c_outputs = ", ".join(["&(self->c_%s)" % p['name'] for p in self.do_outputs])
437        outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
438        out += """
439
440    {do_fn}(self->o, {inputs}, {c_outputs});
441""".format(
442        do_fn = do_fn,
443        inputs = inputs, c_outputs = c_outputs,
444        )
445        if len(self.do_outputs) > 1:
446            out += """
447    outputs = PyTuple_New({:d});""".format(len(self.do_outputs))
448            for i, p in enumerate(self.do_outputs):
449                out += """
450    PyTuple_SetItem( outputs, {i}, self->{p[name]});""".format(i = i, p = p)
451        else:
452            out += """
453    outputs = self->{p[name]};""".format(p = self.do_outputs[0])
454        out += """
455
456    return outputs;
457}}
458""".format(
459        outputs = outputs,
460        )
461        return out
462
463    def gen_set(self):
464        out = """
465// {shortname} setters
466""".format(**self.__dict__)
467        for set_param in self.prototypes['set']:
468            params = get_params_types_names(set_param)[1]
469            paramtype = params['type']
470            method_name = get_name(set_param)
471            param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
472            pyparamtype = pyargparse_chars[paramtype]
473            out += """
474static PyObject *
475Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
476{{
477  uint_t err = 0;
478  {paramtype} {param};
479
480  if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
481    return NULL;
482  }}
483  err = aubio_{shortname}_set_{param} (self->o, {param});
484
485  if (err > 0) {{
486    PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
487    return NULL;
488  }}
489  Py_RETURN_NONE;
490}}
491""".format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
492        return out
493
494    def gen_get(self):
495        out = """
496// {shortname} getters
497""".format(**self.__dict__)
498        for method in self.prototypes['get']:
499            params = get_params_types_names(method)
500            method_name = get_name(method)
501            assert len(params) == 1, \
502                "get method has more than one parameter %s" % params
503            param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
504            paramtype = get_return_type(method)
505            ptypeconv = pyfromtype_fn[paramtype]
506            out += """
507static PyObject *
508Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
509{{
510  {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
511  return (PyObject *){ptypeconv} ({param});
512}}
513""".format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
514        **self.__dict__)
515        return out
516
517    def gen_methodef(self):
518        out = """
519static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
520        for m in self.prototypes['set']:
521            name = get_name(m)
522            shortname = name.replace('aubio_%s_' % self.shortname, '')
523            out += """
524  {{"{shortname}", (PyCFunction) Py{name},
525    METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
526        for m in self.prototypes['get']:
527            name = get_name(m)
528            shortname = name.replace('aubio_%s_' % self.shortname, '')
529            out += """
530  {{"{shortname}", (PyCFunction) Py{name},
531    METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
532        out += """
533  {NULL} /* sentinel */
534};
535"""
536        return out
537
538    def gen_typeobject(self):
539        return """
540PyTypeObject Py_{shortname}Type = {{
541  //PyObject_HEAD_INIT (NULL)
542  //0,
543  PyVarObject_HEAD_INIT (NULL, 0)
544  "aubio.{shortname}",
545  sizeof (Py_{shortname}),
546  0,
547  (destructor) Py_{shortname}_del,
548  0,
549  0,
550  0,
551  0,
552  0,
553  0,
554  0,
555  0,
556  0,
557  (ternaryfunc)Py_{shortname}_do,
558  0,
559  0,
560  0,
561  0,
562  Py_TPFLAGS_DEFAULT,
563  Py_{shortname}_doc,
564  0,
565  0,
566  0,
567  0,
568  0,
569  0,
570  Py_{shortname}_methods,
571  Py_{shortname}_members,
572  0,
573  0,
574  0,
575  0,
576  0,
577  0,
578  (initproc) Py_{shortname}_init,
579  0,
580  Py_{shortname}_new,
581  0,
582  0,
583  0,
584  0,
585  0,
586  0,
587  0,
588  0,
589  0,
590}};
591""".format(**self.__dict__)
Note: See TracBrowser for help on using the repository browser.