]> sigrok.org Git - libsigrokdecode.git/blob - type_decoder.c
Pass unitsize per sample chunk.
[libsigrokdecode.git] / type_decoder.c
1 /*
2  * This file is part of the libsigrokdecode project.
3  *
4  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
21 #include "libsigrokdecode.h"
22 #include "config.h"
23 #include <inttypes.h>
24
25 typedef struct {
26         PyObject_HEAD
27 } srd_Decoder;
28
29 /* This is only used for nicer srd_dbg() output. */
30 static const char *OUTPUT_TYPES[] = {
31         "OUTPUT_ANN",
32         "OUTPUT_PYTHON",
33         "OUTPUT_BINARY",
34         "OUTPUT_META",
35 };
36
37 static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
38                 struct srd_proto_data *pdata)
39 {
40         PyObject *py_tmp;
41         struct srd_pd_output *pdo;
42         struct srd_proto_data_annotation *pda;
43         int ann_class;
44         char **ann_text;
45
46         /* Should be a list of [annotation class, [string, ...]]. */
47         if (!PyList_Check(obj) && !PyTuple_Check(obj)) {
48                 srd_err("Protocol decoder %s submitted %s instead of list.",
49                         di->decoder->name, obj->ob_type->tp_name);
50                 return SRD_ERR_PYTHON;
51         }
52
53         /* Should have 2 elements. */
54         if (PyList_Size(obj) != 2) {
55                 srd_err("Protocol decoder %s submitted annotation list with "
56                         "%d elements instead of 2", di->decoder->name,
57                         PyList_Size(obj));
58                 return SRD_ERR_PYTHON;
59         }
60
61         /*
62          * The first element should be an integer matching a previously
63          * registered annotation class.
64          */
65         py_tmp = PyList_GetItem(obj, 0);
66         if (!PyLong_Check(py_tmp)) {
67                 srd_err("Protocol decoder %s submitted annotation list, but "
68                         "first element was not an integer.", di->decoder->name);
69                 return SRD_ERR_PYTHON;
70         }
71         ann_class = PyLong_AsLong(py_tmp);
72         if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_class))) {
73                 srd_err("Protocol decoder %s submitted data to unregistered "
74                         "annotation class %d.", di->decoder->name, ann_class);
75                 return SRD_ERR_PYTHON;
76         }
77
78         /* Second element must be a list. */
79         py_tmp = PyList_GetItem(obj, 1);
80         if (!PyList_Check(py_tmp)) {
81                 srd_err("Protocol decoder %s submitted annotation list, but "
82                         "second element was not a list.", di->decoder->name);
83                 return SRD_ERR_PYTHON;
84         }
85         if (py_strseq_to_char(py_tmp, &ann_text) != SRD_OK) {
86                 srd_err("Protocol decoder %s submitted annotation list, but "
87                         "second element was malformed.", di->decoder->name);
88                 return SRD_ERR_PYTHON;
89         }
90
91         pda = g_malloc(sizeof(struct srd_proto_data_annotation));
92         pda->ann_class = ann_class;
93         pda->ann_text = ann_text;
94         pdata->data = pda;
95
96         return SRD_OK;
97 }
98
99 static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
100                 struct srd_proto_data *pdata)
101 {
102         struct srd_proto_data_binary *pdb;
103         PyObject *py_tmp;
104         Py_ssize_t size;
105         int bin_class;
106         char *class_name, *buf;
107
108         /* Should be a tuple of (binary class, bytes). */
109         if (!PyTuple_Check(obj)) {
110                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
111                                 "%s instead of tuple.", di->decoder->name,
112                                 obj->ob_type->tp_name);
113                 return SRD_ERR_PYTHON;
114         }
115
116         /* Should have 2 elements. */
117         if (PyTuple_Size(obj) != 2) {
118                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple "
119                                 "with %d elements instead of 2", di->decoder->name,
120                                 PyList_Size(obj));
121                 return SRD_ERR_PYTHON;
122         }
123
124         /* The first element should be an integer. */
125         py_tmp = PyTuple_GetItem(obj, 0);
126         if (!PyLong_Check(py_tmp)) {
127                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple, "
128                         "but first element was not an integer.", di->decoder->name);
129                 return SRD_ERR_PYTHON;
130         }
131         bin_class = PyLong_AsLong(py_tmp);
132         if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
133                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
134                         "unregistered binary class %d.", di->decoder->name, bin_class);
135                 return SRD_ERR_PYTHON;
136         }
137
138         /* Second element should be bytes. */
139         py_tmp = PyTuple_GetItem(obj, 1);
140         if (!PyBytes_Check(py_tmp)) {
141                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY tuple, "
142                         "but second element was not bytes.", di->decoder->name);
143                 return SRD_ERR_PYTHON;
144         }
145
146         /* Consider an empty set of bytes a bug. */
147         if (PyBytes_Size(py_tmp) == 0) {
148                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
149                                 "with empty data set.", di->decoder->name);
150                 return SRD_ERR_PYTHON;
151         }
152
153         pdb = g_malloc(sizeof(struct srd_proto_data_binary));
154         if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
155                 return SRD_ERR_PYTHON;
156         pdb->bin_class = bin_class;
157         pdb->size = size;
158         if (!(pdb->data = g_try_malloc(pdb->size)))
159                 return SRD_ERR_MALLOC;
160         memcpy((void *)pdb->data, (const void *)buf, pdb->size);
161         pdata->data = pdb;
162
163         return SRD_OK;
164 }
165
166 static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
167 {
168         long long intvalue;
169         double dvalue;
170
171         if (pdata->pdo->meta_type == G_VARIANT_TYPE_INT64) {
172                 if (!PyLong_Check(obj)) {
173                         PyErr_Format(PyExc_TypeError, "This output was registered "
174                                         "as 'int', but '%s' was passed.", obj->ob_type->tp_name);
175                         return SRD_ERR_PYTHON;
176                 }
177                 intvalue = PyLong_AsLongLong(obj);
178                 if (PyErr_Occurred())
179                         return SRD_ERR_PYTHON;
180                 pdata->data = g_variant_new_int64(intvalue);
181         } else if (pdata->pdo->meta_type == G_VARIANT_TYPE_DOUBLE) {
182                 if (!PyFloat_Check(obj)) {
183                         PyErr_Format(PyExc_TypeError, "This output was registered "
184                                         "as 'float', but '%s' was passed.", obj->ob_type->tp_name);
185                         return SRD_ERR_PYTHON;
186                 }
187                 dvalue = PyFloat_AsDouble(obj);
188                 if (PyErr_Occurred())
189                         return SRD_ERR_PYTHON;
190                 pdata->data = g_variant_new_double(dvalue);
191         }
192
193         return SRD_OK;
194 }
195
196 static PyObject *Decoder_put(PyObject *self, PyObject *args)
197 {
198         GSList *l;
199         PyObject *py_data, *py_res;
200         struct srd_decoder_inst *di, *next_di;
201         struct srd_pd_output *pdo;
202         struct srd_proto_data *pdata;
203         uint64_t start_sample, end_sample;
204         int output_id;
205         struct srd_pd_callback *cb;
206
207         if (!(di = srd_inst_find_by_obj(NULL, self))) {
208                 /* Shouldn't happen. */
209                 srd_dbg("put(): self instance not found.");
210                 return NULL;
211         }
212
213         if (!PyArg_ParseTuple(args, "KKiO", &start_sample, &end_sample,
214                 &output_id, &py_data)) {
215                 /*
216                  * This throws an exception, but by returning NULL here we let
217                  * Python raise it. This results in a much better trace in
218                  * controller.c on the decode() method call.
219                  */
220                 return NULL;
221         }
222
223         if (!(l = g_slist_nth(di->pd_output, output_id))) {
224                 srd_err("Protocol decoder %s submitted invalid output ID %d.",
225                         di->decoder->name, output_id);
226                 return NULL;
227         }
228         pdo = l->data;
229
230         srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on oid %d.",
231                  di->inst_id, start_sample, end_sample,
232                  OUTPUT_TYPES[pdo->output_type], output_id);
233
234         pdata = g_malloc0(sizeof(struct srd_proto_data));
235         pdata->start_sample = start_sample;
236         pdata->end_sample = end_sample;
237         pdata->pdo = pdo;
238
239         switch (pdo->output_type) {
240         case SRD_OUTPUT_ANN:
241                 /* Annotations are only fed to callbacks. */
242                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
243                         /* Convert from PyDict to srd_proto_data_annotation. */
244                         if (convert_annotation(di, py_data, pdata) != SRD_OK) {
245                                 /* An error was already logged. */
246                                 break;
247                         }
248                         cb->cb(pdata, cb->cb_data);
249                 }
250                 break;
251         case SRD_OUTPUT_PYTHON:
252                 for (l = di->next_di; l; l = l->next) {
253                         next_di = l->data;
254                         srd_spew("Sending %d-%d to instance %s",
255                                  start_sample, end_sample, next_di->inst_id);
256                         if (!(py_res = PyObject_CallMethod(
257                                 next_di->py_inst, "decode", "KKO", start_sample,
258                                 end_sample, py_data))) {
259                                 srd_exception_catch("Calling %s decode(): ",
260                                                         next_di->inst_id);
261                         }
262                         Py_XDECREF(py_res);
263                 }
264                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
265                         /* Frontends aren't really supposed to get Python
266                          * callbacks, but it's useful for testing. */
267                         pdata->data = py_data;
268                         cb->cb(pdata, cb->cb_data);
269                 }
270                 break;
271         case SRD_OUTPUT_BINARY:
272                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
273                         /* Convert from PyDict to srd_proto_data_binary. */
274                         if (convert_binary(di, py_data, pdata) != SRD_OK) {
275                                 /* An error was already logged. */
276                                 break;
277                         }
278                         cb->cb(pdata, cb->cb_data);
279                 }
280                 break;
281         case SRD_OUTPUT_META:
282                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
283                         /* Annotations need converting from PyObject. */
284                         if (convert_meta(pdata, py_data) != SRD_OK) {
285                                 /* An exception was already set up. */
286                                 break;
287                         }
288                         cb->cb(pdata, cb->cb_data);
289                 }
290                 break;
291         default:
292                 srd_err("Protocol decoder %s submitted invalid output type %d.",
293                         di->decoder->name, pdo->output_type);
294                 break;
295         }
296
297         g_free(pdata);
298
299         Py_RETURN_NONE;
300 }
301
302 static PyObject *Decoder_register(PyObject *self, PyObject *args,
303                 PyObject *kwargs)
304 {
305         struct srd_decoder_inst *di;
306         struct srd_pd_output *pdo;
307         PyObject *py_new_output_id;
308         PyTypeObject *meta_type_py;
309         const GVariantType *meta_type_gv;
310         int output_type;
311         char *proto_id, *meta_name, *meta_descr;
312         char *keywords[] = {"output_type", "proto_id", "meta", NULL};
313
314         meta_type_py = NULL;
315         meta_type_gv = NULL;
316         meta_name = meta_descr = NULL;
317
318         if (!(di = srd_inst_find_by_obj(NULL, self))) {
319                 PyErr_SetString(PyExc_Exception, "decoder instance not found");
320                 return NULL;
321         }
322
323         /* Default to instance id, which defaults to class id. */
324         proto_id = di->inst_id;
325         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
326                         &output_type, &proto_id,
327                         &meta_type_py, &meta_name, &meta_descr)) {
328                 /* Let Python raise this exception. */
329                 return NULL;
330         }
331
332         /* Check if the meta value's type is supported. */
333         if (output_type == SRD_OUTPUT_META) {
334                 if (meta_type_py == &PyLong_Type)
335                         meta_type_gv = G_VARIANT_TYPE_INT64;
336                 else if (meta_type_py == &PyFloat_Type)
337                         meta_type_gv = G_VARIANT_TYPE_DOUBLE;
338                 else {
339                         PyErr_Format(PyExc_TypeError, "Unsupported type '%s'.",
340                                         meta_type_py->tp_name);
341                         return NULL;
342                 }
343         }
344
345         srd_dbg("Instance %s creating new output type %d for %s.",
346                 di->inst_id, output_type, proto_id);
347
348         pdo = g_malloc(sizeof(struct srd_pd_output));
349
350         /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
351         pdo->pdo_id = g_slist_length(di->pd_output);
352         pdo->output_type = output_type;
353         pdo->di = di;
354         pdo->proto_id = g_strdup(proto_id);
355
356         if (output_type == SRD_OUTPUT_META) {
357                 pdo->meta_type = meta_type_gv;
358                 pdo->meta_name = g_strdup(meta_name);
359                 pdo->meta_descr = g_strdup(meta_descr);
360         }
361
362         di->pd_output = g_slist_append(di->pd_output, pdo);
363         py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
364
365         return py_new_output_id;
366 }
367
368 static PyMethodDef Decoder_methods[] = {
369         {"put", Decoder_put, METH_VARARGS,
370          "Accepts a dictionary with the following keys: startsample, endsample, data"},
371         {"register", (PyCFunction)Decoder_register, METH_VARARGS|METH_KEYWORDS,
372                         "Register a new output stream"},
373         {NULL, NULL, 0, NULL}
374 };
375
376 /** @cond PRIVATE */
377 SRD_PRIV PyTypeObject srd_Decoder_type = {
378         PyVarObject_HEAD_INIT(NULL, 0)
379         .tp_name = "sigrokdecode.Decoder",
380         .tp_basicsize = sizeof(srd_Decoder),
381         .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
382         .tp_doc = "sigrok Decoder base class",
383         .tp_methods = Decoder_methods,
384 };
385 /** @endcond */