]> sigrok.org Git - libsigrokdecode.git/blob - type_decoder.c
type_decoder: move Python doc strings to method implementations
[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 <config.h>
21 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode.h"
23 #include <inttypes.h>
24
25 /** @cond PRIVATE */
26 extern SRD_PRIV GSList *sessions;
27 /** @endcond */
28
29 typedef struct {
30         PyObject_HEAD
31 } srd_Decoder;
32
33 /* This is only used for nicer srd_dbg() output. */
34 SRD_PRIV const char *output_type_name(unsigned int idx)
35 {
36         static const char names[][16] = {
37                 "OUTPUT_ANN",
38                 "OUTPUT_PYTHON",
39                 "OUTPUT_BINARY",
40                 "OUTPUT_LOGIC",
41                 "OUTPUT_META",
42                 "(invalid)"
43         };
44
45         return names[MIN(idx, G_N_ELEMENTS(names) - 1)];
46 }
47
48 static void release_annotation(struct srd_proto_data_annotation *pda)
49 {
50         if (!pda)
51                 return;
52         if (pda->ann_text)
53                 g_strfreev(pda->ann_text);
54 }
55
56 static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
57                 struct srd_proto_data *pdata)
58 {
59         PyObject *py_tmp;
60         struct srd_pd_output *pdo;
61         struct srd_proto_data_annotation *pda;
62         int ann_class;
63         char **ann_text;
64         PyGILState_STATE gstate;
65
66         gstate = PyGILState_Ensure();
67
68         /* Should be a list of [annotation class, [string, ...]]. */
69         if (!PyList_Check(obj)) {
70                 srd_err("Protocol decoder %s submitted an annotation that"
71                         " is not a list", di->decoder->name);
72                 goto err;
73         }
74
75         /* Should have 2 elements. */
76         if (PyList_Size(obj) != 2) {
77                 srd_err("Protocol decoder %s submitted annotation list with "
78                         "%zd elements instead of 2", di->decoder->name,
79                         PyList_Size(obj));
80                 goto err;
81         }
82
83         /*
84          * The first element should be an integer matching a previously
85          * registered annotation class.
86          */
87         py_tmp = PyList_GetItem(obj, 0);
88         if (!PyLong_Check(py_tmp)) {
89                 srd_err("Protocol decoder %s submitted annotation list, but "
90                         "first element was not an integer.", di->decoder->name);
91                 goto err;
92         }
93         ann_class = PyLong_AsLong(py_tmp);
94         if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_class))) {
95                 srd_err("Protocol decoder %s submitted data to unregistered "
96                         "annotation class %d.", di->decoder->name, ann_class);
97                 goto err;
98         }
99
100         /* Second element must be a list. */
101         py_tmp = PyList_GetItem(obj, 1);
102         if (!PyList_Check(py_tmp)) {
103                 srd_err("Protocol decoder %s submitted annotation list, but "
104                         "second element was not a list.", di->decoder->name);
105                 goto err;
106         }
107         if (py_strseq_to_char(py_tmp, &ann_text) != SRD_OK) {
108                 srd_err("Protocol decoder %s submitted annotation list, but "
109                         "second element was malformed.", di->decoder->name);
110                 goto err;
111         }
112
113         pda = pdata->data;
114         pda->ann_class = ann_class;
115         pda->ann_text = ann_text;
116
117         PyGILState_Release(gstate);
118
119         return SRD_OK;
120
121 err:
122         PyGILState_Release(gstate);
123
124         return SRD_ERR_PYTHON;
125 }
126
127 static void release_logic(struct srd_proto_data_logic *pdl)
128 {
129         if (!pdl)
130                 return;
131         g_free((void *)pdl->data);
132 }
133
134 static int convert_logic(struct srd_decoder_inst *di, PyObject *obj,
135                 struct srd_proto_data *pdata)
136 {
137         struct srd_proto_data_logic *pdl;
138         PyObject *py_tmp;
139         Py_ssize_t size;
140         int logic_group;
141         char *group_name, *buf;
142         PyGILState_STATE gstate;
143
144         gstate = PyGILState_Ensure();
145
146         /* Should be a list of [logic group, bytes]. */
147         if (!PyList_Check(obj)) {
148                 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_LOGIC.",
149                         di->decoder->name);
150                 goto err;
151         }
152
153         /* Should have 2 elements. */
154         if (PyList_Size(obj) != 2) {
155                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list "
156                                 "with %zd elements instead of 2", di->decoder->name,
157                                 PyList_Size(obj));
158                 goto err;
159         }
160
161         /* The first element should be an integer. */
162         py_tmp = PyList_GetItem(obj, 0);
163         if (!PyLong_Check(py_tmp)) {
164                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list, "
165                         "but first element was not an integer.", di->decoder->name);
166                 goto err;
167         }
168         logic_group = PyLong_AsLong(py_tmp);
169         if (!(group_name = g_slist_nth_data(di->decoder->logic_output_channels, logic_group))) {
170                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC with "
171                         "unregistered logic group %d.", di->decoder->name, logic_group);
172                 goto err;
173         }
174
175         /* Second element should be bytes. */
176         py_tmp = PyList_GetItem(obj, 1);
177         if (!PyBytes_Check(py_tmp)) {
178                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list, "
179                         "but second element was not bytes.", di->decoder->name);
180                 goto err;
181         }
182
183         /* Consider an empty set of bytes a bug. */
184         if (PyBytes_Size(py_tmp) == 0) {
185                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC "
186                                 "with empty data set.", di->decoder->name);
187                 goto err;
188         }
189
190         if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
191                 goto err;
192
193         PyGILState_Release(gstate);
194
195         pdl = pdata->data;
196         pdl->logic_group = logic_group;
197         /* pdl->repeat_count is set by the caller as it depends on the sample range */
198         if (!(pdl->data = g_try_malloc(size)))
199                 return SRD_ERR_MALLOC;
200         memcpy((void *)pdl->data, (const void *)buf, size);
201
202         return SRD_OK;
203
204 err:
205         PyGILState_Release(gstate);
206
207         return SRD_ERR_PYTHON;
208 }
209
210 static void release_binary(struct srd_proto_data_binary *pdb)
211 {
212         if (!pdb)
213                 return;
214         g_free((void *)pdb->data);
215 }
216
217 static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
218                 struct srd_proto_data *pdata)
219 {
220         struct srd_proto_data_binary *pdb;
221         PyObject *py_tmp;
222         Py_ssize_t size;
223         int bin_class;
224         char *class_name, *buf;
225         PyGILState_STATE gstate;
226
227         gstate = PyGILState_Ensure();
228
229         /* Should be a list of [binary class, bytes]. */
230         if (!PyList_Check(obj)) {
231                 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_BINARY.",
232                         di->decoder->name);
233                 goto err;
234         }
235
236         /* Should have 2 elements. */
237         if (PyList_Size(obj) != 2) {
238                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list "
239                                 "with %zd elements instead of 2", di->decoder->name,
240                                 PyList_Size(obj));
241                 goto err;
242         }
243
244         /* The first element should be an integer. */
245         py_tmp = PyList_GetItem(obj, 0);
246         if (!PyLong_Check(py_tmp)) {
247                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
248                         "but first element was not an integer.", di->decoder->name);
249                 goto err;
250         }
251         bin_class = PyLong_AsLong(py_tmp);
252         if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
253                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
254                         "unregistered binary class %d.", di->decoder->name, bin_class);
255                 goto err;
256         }
257
258         /* Second element should be bytes. */
259         py_tmp = PyList_GetItem(obj, 1);
260         if (!PyBytes_Check(py_tmp)) {
261                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
262                         "but second element was not bytes.", di->decoder->name);
263                 goto err;
264         }
265
266         /* Consider an empty set of bytes a bug. */
267         if (PyBytes_Size(py_tmp) == 0) {
268                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
269                                 "with empty data set.", di->decoder->name);
270                 goto err;
271         }
272
273         if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
274                 goto err;
275
276         PyGILState_Release(gstate);
277
278         pdb = pdata->data;
279         pdb->bin_class = bin_class;
280         pdb->size = size;
281         if (!(pdb->data = g_try_malloc(pdb->size)))
282                 return SRD_ERR_MALLOC;
283         memcpy((void *)pdb->data, (const void *)buf, pdb->size);
284
285         return SRD_OK;
286
287 err:
288         PyGILState_Release(gstate);
289
290         return SRD_ERR_PYTHON;
291 }
292
293 static inline struct srd_decoder_inst *srd_sess_inst_find_by_obj(
294         struct srd_session *sess, const GSList *stack, const PyObject *obj)
295 {
296         const GSList *l;
297         struct srd_decoder_inst *tmp, *di;
298
299         if (!sess)
300                 return NULL;
301
302         di = NULL;
303         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
304                 tmp = l->data;
305                 if (tmp->py_inst == obj)
306                         di = tmp;
307                 else if (tmp->next_di)
308                         di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
309         }
310
311         return di;
312 }
313
314 /**
315  * Find a decoder instance by its Python object.
316  *
317  * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
318  * This will recurse to find the instance anywhere in the stack tree of all
319  * sessions.
320  *
321  * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
322  *              stack to search. To start searching at the bottom level of
323  *              decoder instances, pass NULL.
324  * @param obj The Python class instantiation.
325  *
326  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
327  *
328  * @since 0.1.0
329  */
330 static inline struct srd_decoder_inst *srd_inst_find_by_obj(
331                 const GSList *stack, const PyObject *obj)
332 {
333         struct srd_decoder_inst *di;
334         struct srd_session *sess;
335         GSList *l;
336
337         /* Performance shortcut: Handle the most common case first. */
338         sess = sessions->data;
339         di = sess->di_list->data;
340         if (di->py_inst == obj)
341                 return di;
342
343         di = NULL;
344         for (l = sessions; di == NULL && l != NULL; l = l->next) {
345                 sess = l->data;
346                 di = srd_sess_inst_find_by_obj(sess, stack, obj);
347         }
348
349         return di;
350 }
351
352 static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
353 {
354         long long intvalue;
355         double dvalue;
356         PyGILState_STATE gstate;
357
358         gstate = PyGILState_Ensure();
359
360         if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_INT64)) {
361                 if (!PyLong_Check(obj)) {
362                         PyErr_Format(PyExc_TypeError, "This output was registered "
363                                         "as 'int', but something else was passed.");
364                         goto err;
365                 }
366                 intvalue = PyLong_AsLongLong(obj);
367                 if (PyErr_Occurred())
368                         goto err;
369                 pdata->data = g_variant_new_int64(intvalue);
370         } else if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_DOUBLE)) {
371                 if (!PyFloat_Check(obj)) {
372                         PyErr_Format(PyExc_TypeError, "This output was registered "
373                                         "as 'float', but something else was passed.");
374                         goto err;
375                 }
376                 dvalue = PyFloat_AsDouble(obj);
377                 if (PyErr_Occurred())
378                         goto err;
379                 pdata->data = g_variant_new_double(dvalue);
380         }
381
382         PyGILState_Release(gstate);
383
384         return SRD_OK;
385
386 err:
387         PyGILState_Release(gstate);
388
389         return SRD_ERR_PYTHON;
390 }
391
392 static void release_meta(GVariant *gvar)
393 {
394         if (!gvar)
395                 return;
396         g_variant_unref(gvar);
397 }
398
399 PyDoc_STRVAR(Decoder_put_doc,
400         "Accepts a dictionary with the following keys: startsample, endsample, data"
401 );
402
403 static PyObject *Decoder_put(PyObject *self, PyObject *args)
404 {
405         GSList *l;
406         PyObject *py_data, *py_res;
407         struct srd_decoder_inst *di, *next_di;
408         struct srd_pd_output *pdo;
409         struct srd_proto_data pdata;
410         struct srd_proto_data_annotation pda;
411         struct srd_proto_data_binary pdb;
412         struct srd_proto_data_logic pdl;
413         uint64_t start_sample, end_sample;
414         int output_id;
415         struct srd_pd_callback *cb;
416         PyGILState_STATE gstate;
417
418         py_data = NULL;
419
420         gstate = PyGILState_Ensure();
421
422         if (!(di = srd_inst_find_by_obj(NULL, self))) {
423                 /* Shouldn't happen. */
424                 srd_dbg("put(): self instance not found.");
425                 goto err;
426         }
427
428         if (!PyArg_ParseTuple(args, "KKiO", &start_sample, &end_sample,
429                 &output_id, &py_data)) {
430                 /*
431                  * This throws an exception, but by returning NULL here we let
432                  * Python raise it. This results in a much better trace in
433                  * controller.c on the decode() method call.
434                  */
435                 goto err;
436         }
437
438         if (!(l = g_slist_nth(di->pd_output, output_id))) {
439                 srd_err("Protocol decoder %s submitted invalid output ID %d.",
440                         di->decoder->name, output_id);
441                 goto err;
442         }
443         pdo = l->data;
444
445         /* Upon SRD_OUTPUT_PYTHON for stacked PDs, we have a nicer log message later. */
446         if (pdo->output_type != SRD_OUTPUT_PYTHON && di->next_di != NULL) {
447                 srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on "
448                          "oid %d (%s).", di->inst_id, start_sample, end_sample,
449                          output_type_name(pdo->output_type), output_id,
450                          pdo->proto_id);
451         }
452
453         pdata.start_sample = start_sample;
454         pdata.end_sample = end_sample;
455         pdata.pdo = pdo;
456         pdata.data = NULL;
457
458         switch (pdo->output_type) {
459         case SRD_OUTPUT_ANN:
460                 /* Annotations are only fed to callbacks. */
461                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
462                         pdata.data = &pda;
463                         /* Convert from PyDict to srd_proto_data_annotation. */
464                         if (convert_annotation(di, py_data, &pdata) != SRD_OK) {
465                                 /* An error was already logged. */
466                                 break;
467                         }
468                         Py_BEGIN_ALLOW_THREADS
469                         cb->cb(&pdata, cb->cb_data);
470                         Py_END_ALLOW_THREADS
471                         release_annotation(pdata.data);
472                 }
473                 break;
474         case SRD_OUTPUT_PYTHON:
475                 for (l = di->next_di; l; l = l->next) {
476                         next_di = l->data;
477                         srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s "
478                                  "on oid %d (%s) to instance %s.", di->inst_id,
479                                  start_sample,
480                                  end_sample, output_type_name(pdo->output_type),
481                                  output_id, pdo->proto_id, next_di->inst_id);
482                         if (!(py_res = PyObject_CallMethod(
483                                 next_di->py_inst, "decode", "KKO", start_sample,
484                                 end_sample, py_data))) {
485                                 srd_exception_catch("Calling %s decode() failed",
486                                                         next_di->inst_id);
487                         }
488                         Py_XDECREF(py_res);
489                 }
490                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
491                         /*
492                          * Frontends aren't really supposed to get Python
493                          * callbacks, but it's useful for testing.
494                          */
495                         pdata.data = py_data;
496                         cb->cb(&pdata, cb->cb_data);
497                 }
498                 break;
499         case SRD_OUTPUT_BINARY:
500                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
501                         pdata.data = &pdb;
502                         /* Convert from PyDict to srd_proto_data_binary. */
503                         if (convert_binary(di, py_data, &pdata) != SRD_OK) {
504                                 /* An error was already logged. */
505                                 break;
506                         }
507                         Py_BEGIN_ALLOW_THREADS
508                         cb->cb(&pdata, cb->cb_data);
509                         Py_END_ALLOW_THREADS
510                         release_binary(pdata.data);
511                 }
512                 break;
513         case SRD_OUTPUT_LOGIC:
514                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
515                         pdata.data = &pdl;
516                         /* Convert from PyDict to srd_proto_data_logic. */
517                         if (convert_logic(di, py_data, &pdata) != SRD_OK) {
518                                 /* An error was already logged. */
519                                 break;
520                         }
521                         if (end_sample <= start_sample) {
522                                 srd_err("Ignored SRD_OUTPUT_LOGIC with invalid sample range.");
523                                 break;
524                         }
525                         pdl.repeat_count = (end_sample - start_sample) - 1;
526                         Py_BEGIN_ALLOW_THREADS
527                         cb->cb(&pdata, cb->cb_data);
528                         Py_END_ALLOW_THREADS
529                         release_logic(pdata.data);
530                 }
531                 break;
532         case SRD_OUTPUT_META:
533                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
534                         /* Annotations need converting from PyObject. */
535                         if (convert_meta(&pdata, py_data) != SRD_OK) {
536                                 /* An exception was already set up. */
537                                 break;
538                         }
539                         Py_BEGIN_ALLOW_THREADS
540                         cb->cb(&pdata, cb->cb_data);
541                         Py_END_ALLOW_THREADS
542                         release_meta(pdata.data);
543                 }
544                 break;
545         default:
546                 srd_err("Protocol decoder %s submitted invalid output type %d.",
547                         di->decoder->name, pdo->output_type);
548                 break;
549         }
550
551         PyGILState_Release(gstate);
552
553         Py_RETURN_NONE;
554
555 err:
556         PyGILState_Release(gstate);
557
558         return NULL;
559 }
560
561 PyDoc_STRVAR(Decoder_register_doc,
562         "Register a new output stream"
563 );
564
565 static PyObject *Decoder_register(PyObject *self,
566         PyObject *args, PyObject *kwargs)
567 {
568         struct srd_decoder_inst *di;
569         struct srd_pd_output *pdo;
570         PyObject *py_new_output_id;
571         PyTypeObject *meta_type_py;
572         const GVariantType *meta_type_gv;
573         int output_type;
574         char *proto_id, *meta_name, *meta_descr;
575         char *keywords[] = { "output_type", "proto_id", "meta", NULL };
576         PyGILState_STATE gstate;
577         gboolean is_meta;
578         GSList *l;
579         struct srd_pd_output *cmp;
580
581         gstate = PyGILState_Ensure();
582
583         meta_type_py = NULL;
584         meta_type_gv = NULL;
585         meta_name = meta_descr = NULL;
586
587         if (!(di = srd_inst_find_by_obj(NULL, self))) {
588                 PyErr_SetString(PyExc_Exception, "decoder instance not found");
589                 goto err;
590         }
591
592         /* Default to instance ID, which defaults to class ID. */
593         proto_id = di->inst_id;
594         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
595                         &output_type, &proto_id,
596                         &meta_type_py, &meta_name, &meta_descr)) {
597                 /* Let Python raise this exception. */
598                 goto err;
599         }
600
601         /* Check if the meta value's type is supported. */
602         is_meta = output_type == SRD_OUTPUT_META;
603         if (is_meta) {
604                 if (meta_type_py == &PyLong_Type)
605                         meta_type_gv = G_VARIANT_TYPE_INT64;
606                 else if (meta_type_py == &PyFloat_Type)
607                         meta_type_gv = G_VARIANT_TYPE_DOUBLE;
608                 else {
609                         PyErr_Format(PyExc_TypeError, "Unsupported type.");
610                         goto err;
611                 }
612         }
613
614         pdo = NULL;
615         for (l = di->pd_output; l; l = l->next) {
616                 cmp = l->data;
617                 if (cmp->output_type != output_type)
618                         continue;
619                 if (strcmp(cmp->proto_id, proto_id) != 0)
620                         continue;
621                 if (is_meta && cmp->meta_type != meta_type_gv)
622                         continue;
623                 if (is_meta && strcmp(cmp->meta_name, meta_name) != 0)
624                         continue;
625                 if (is_meta && strcmp(cmp->meta_descr, meta_descr) != 0)
626                         continue;
627                 pdo = cmp;
628                 break;
629         }
630         if (pdo) {
631                 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
632                 PyGILState_Release(gstate);
633                 return py_new_output_id;
634         }
635
636         pdo = g_malloc(sizeof(struct srd_pd_output));
637
638         /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
639         pdo->pdo_id = g_slist_length(di->pd_output);
640         pdo->output_type = output_type;
641         pdo->di = di;
642         pdo->proto_id = g_strdup(proto_id);
643
644         if (output_type == SRD_OUTPUT_META) {
645                 pdo->meta_type = meta_type_gv;
646                 pdo->meta_name = g_strdup(meta_name);
647                 pdo->meta_descr = g_strdup(meta_descr);
648         }
649
650         di->pd_output = g_slist_append(di->pd_output, pdo);
651         py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
652
653         PyGILState_Release(gstate);
654
655         srd_dbg("Instance %s creating new output type %s as oid %d (%s).",
656                 di->inst_id, output_type_name(output_type), pdo->pdo_id,
657                 proto_id);
658
659         return py_new_output_id;
660
661 err:
662         PyGILState_Release(gstate);
663
664         return NULL;
665 }
666
667 static int get_term_type(const char *v)
668 {
669         switch (v[0]) {
670         case 'h':
671                 return SRD_TERM_HIGH;
672         case 'l':
673                 return SRD_TERM_LOW;
674         case 'r':
675                 return SRD_TERM_RISING_EDGE;
676         case 'f':
677                 return SRD_TERM_FALLING_EDGE;
678         case 'e':
679                 return SRD_TERM_EITHER_EDGE;
680         case 'n':
681                 return SRD_TERM_NO_EDGE;
682         default:
683                 return -1;
684         }
685
686         return -1;
687 }
688
689 /**
690  * Get the pin values at the current sample number.
691  *
692  * @param di The decoder instance to use. Must not be NULL.
693  *           The number of channels must be >= 1.
694  *
695  * @return A newly allocated PyTuple containing the pin values at the
696  *         current sample number.
697  */
698 static PyObject *get_current_pinvalues(const struct srd_decoder_inst *di)
699 {
700         int i;
701         uint8_t sample;
702         const uint8_t *sample_pos;
703         int byte_offset, bit_offset;
704         PyObject *py_pinvalues;
705         PyGILState_STATE gstate;
706
707         if (!di) {
708                 srd_err("Invalid decoder instance.");
709                 return NULL;
710         }
711
712         gstate = PyGILState_Ensure();
713
714         py_pinvalues = PyTuple_New(di->dec_num_channels);
715
716         for (i = 0; i < di->dec_num_channels; i++) {
717                 /* A channelmap value of -1 means "unused optional channel". */
718                 if (di->dec_channelmap[i] == -1) {
719                         /* Value of unused channel is 0xff, instead of 0 or 1. */
720                         PyTuple_SetItem(py_pinvalues, i, PyLong_FromUnsignedLong(0xff));
721                 } else {
722                         sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
723                         byte_offset = di->dec_channelmap[i] / 8;
724                         bit_offset = di->dec_channelmap[i] % 8;
725                         sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
726                         PyTuple_SetItem(py_pinvalues, i, PyLong_FromUnsignedLong(sample));
727                 }
728         }
729
730         PyGILState_Release(gstate);
731
732         return py_pinvalues;
733 }
734
735 /**
736  * Create a list of terms in the specified condition.
737  *
738  * If there are no terms in the condition, 'term_list' will be NULL.
739  *
740  * @param di The decoder instance to use. Must not be NULL.
741  * @param py_dict A Python dict containing terms. Must not be NULL.
742  * @param term_list Pointer to a GSList which will be set to the newly
743  *                  created list of terms. Must not be NULL.
744  *
745  * @return SRD_OK upon success, a negative error code otherwise.
746  */
747 static int create_term_list(struct srd_decoder_inst *di,
748         PyObject *py_dict, GSList **term_list)
749 {
750         Py_ssize_t pos = 0;
751         PyObject *py_key, *py_value;
752         struct srd_term *term;
753         int64_t num_samples_to_skip;
754         char *term_str;
755         PyGILState_STATE gstate;
756
757         if (!py_dict || !term_list)
758                 return SRD_ERR_ARG;
759
760         /* "Create" an empty GSList of terms. */
761         *term_list = NULL;
762
763         gstate = PyGILState_Ensure();
764
765         /* Iterate over all items in the current dict. */
766         while (PyDict_Next(py_dict, &pos, &py_key, &py_value)) {
767                 /* Check whether the current key is a string or a number. */
768                 if (PyLong_Check(py_key)) {
769                         /* The key is a number. */
770                         /* Get the value string. */
771                         if ((py_pydictitem_as_str(py_dict, py_key, &term_str)) != SRD_OK) {
772                                 srd_err("Failed to get the value.");
773                                 goto err;
774                         }
775                         term = g_malloc(sizeof(struct srd_term));
776                         term->type = get_term_type(term_str);
777                         term->channel = PyLong_AsLong(py_key);
778                         if (term->channel < 0 || term->channel >= di->dec_num_channels)
779                                 term->type = SRD_TERM_ALWAYS_FALSE;
780                         g_free(term_str);
781                 } else if (PyUnicode_Check(py_key)) {
782                         /* The key is a string. */
783                         /* TODO: Check if the key is "skip". */
784                         if ((py_pydictitem_as_long(py_dict, py_key, &num_samples_to_skip)) != SRD_OK) {
785                                 srd_err("Failed to get number of samples to skip.");
786                                 goto err;
787                         }
788                         term = g_malloc(sizeof(struct srd_term));
789                         term->type = SRD_TERM_SKIP;
790                         term->num_samples_to_skip = num_samples_to_skip;
791                         term->num_samples_already_skipped = 0;
792                         if (num_samples_to_skip < 0)
793                                 term->type = SRD_TERM_ALWAYS_FALSE;
794                 } else {
795                         srd_err("Term key is neither a string nor a number.");
796                         goto err;
797                 }
798
799                 /* Add the term to the list of terms. */
800                 *term_list = g_slist_append(*term_list, term);
801         }
802
803         PyGILState_Release(gstate);
804
805         return SRD_OK;
806
807 err:
808         PyGILState_Release(gstate);
809
810         return SRD_ERR;
811 }
812
813 /**
814  * Replace the current condition list with the new one.
815  *
816  * @param self TODO. Must not be NULL.
817  * @param args TODO. Must not be NULL.
818  *
819  * @retval SRD_OK The new condition list was set successfully.
820  * @retval SRD_ERR There was an error setting the new condition list.
821  *                 The contents of di->condition_list are undefined.
822  * @retval 9999 TODO.
823  */
824 static int set_new_condition_list(PyObject *self, PyObject *args)
825 {
826         struct srd_decoder_inst *di;
827         GSList *term_list;
828         PyObject *py_conditionlist, *py_conds, *py_dict;
829         int i, num_conditions, ret;
830         PyGILState_STATE gstate;
831
832         if (!self || !args)
833                 return SRD_ERR_ARG;
834
835         gstate = PyGILState_Ensure();
836
837         /* Get the decoder instance. */
838         if (!(di = srd_inst_find_by_obj(NULL, self))) {
839                 PyErr_SetString(PyExc_Exception, "decoder instance not found");
840                 goto err;
841         }
842
843         /*
844          * Return an error condition from .wait() when termination is
845          * requested, such that decode() will terminate.
846          */
847         if (di->want_wait_terminate) {
848                 srd_dbg("%s: %s: Skip (want_term).", di->inst_id, __func__);
849                 goto err;
850         }
851
852         /*
853          * Parse the argument of self.wait() into 'py_conds', and check
854          * the data type. The argument is optional, None is assumed in
855          * its absence. None or an empty dict or an empty list mean that
856          * there is no condition, and the next available sample shall
857          * get returned to the caller.
858          */
859         py_conds = Py_None;
860         if (!PyArg_ParseTuple(args, "|O", &py_conds)) {
861                 /* Let Python raise this exception. */
862                 goto err;
863         }
864         if (py_conds == Py_None) {
865                 /* 'py_conds' is None. */
866                 goto ret_9999;
867         } else if (PyList_Check(py_conds)) {
868                 /* 'py_conds' is a list. */
869                 py_conditionlist = py_conds;
870                 num_conditions = PyList_Size(py_conditionlist);
871                 if (num_conditions == 0)
872                         goto ret_9999; /* The PD invoked self.wait([]). */
873                 Py_INCREF(py_conditionlist);
874         } else if (PyDict_Check(py_conds)) {
875                 /* 'py_conds' is a dict. */
876                 if (PyDict_Size(py_conds) == 0)
877                         goto ret_9999; /* The PD invoked self.wait({}). */
878                 /* Make a list and put the dict in there for convenience. */
879                 py_conditionlist = PyList_New(1);
880                 Py_INCREF(py_conds);
881                 PyList_SetItem(py_conditionlist, 0, py_conds);
882                 num_conditions = 1;
883         } else {
884                 srd_err("Condition list is neither a list nor a dict.");
885                 goto err;
886         }
887
888         /* Free the old condition list. */
889         condition_list_free(di);
890
891         ret = SRD_OK;
892
893         /* Iterate over the conditions, set di->condition_list accordingly. */
894         for (i = 0; i < num_conditions; i++) {
895                 /* Get a condition (dict) from the condition list. */
896                 py_dict = PyList_GetItem(py_conditionlist, i);
897                 if (!PyDict_Check(py_dict)) {
898                         srd_err("Condition is not a dict.");
899                         ret = SRD_ERR;
900                         break;
901                 }
902
903                 /* Create the list of terms in this condition. */
904                 if ((ret = create_term_list(di, py_dict, &term_list)) < 0)
905                         break;
906
907                 /* Add the new condition to the PD instance's condition list. */
908                 di->condition_list = g_slist_append(di->condition_list, term_list);
909         }
910
911         Py_DecRef(py_conditionlist);
912
913         PyGILState_Release(gstate);
914
915         return ret;
916
917 err:
918         PyGILState_Release(gstate);
919
920         return SRD_ERR;
921
922 ret_9999:
923         PyGILState_Release(gstate);
924
925         return 9999;
926 }
927
928 /**
929  * Create a SKIP condition list for condition-less .wait() calls.
930  *
931  * @param di Decoder instance.
932  * @param count Number of samples to skip.
933  *
934  * @retval SRD_OK The new condition list was set successfully.
935  * @retval SRD_ERR There was an error setting the new condition list.
936  *                 The contents of di->condition_list are undefined.
937  *
938  * This routine is a reduced and specialized version of the @ref
939  * set_new_condition_list() and @ref create_term_list() routines which
940  * gets invoked when .wait() was called without specifications for
941  * conditions. This minor duplication of the SKIP term list creation
942  * simplifies the logic and avoids the creation of expensive Python
943  * objects with "constant" values which the caller did not pass in the
944  * first place. It results in maximum sharing of match handling code
945  * paths.
946  */
947 static int set_skip_condition(struct srd_decoder_inst *di, uint64_t count)
948 {
949         struct srd_term *term;
950         GSList *term_list;
951
952         condition_list_free(di);
953         term = g_malloc(sizeof(*term));
954         term->type = SRD_TERM_SKIP;
955         term->num_samples_to_skip = count;
956         term->num_samples_already_skipped = 0;
957         term_list = g_slist_append(NULL, term);
958         di->condition_list = g_slist_append(di->condition_list, term_list);
959
960         return SRD_OK;
961 }
962
963 PyDoc_STRVAR(Decoder_wait_doc,
964         "Wait for one or more conditions to occur"
965 );
966
967 static PyObject *Decoder_wait(PyObject *self, PyObject *args)
968 {
969         int ret;
970         uint64_t skip_count;
971         unsigned int i;
972         gboolean found_match;
973         struct srd_decoder_inst *di;
974         PyObject *py_pinvalues, *py_matched, *py_samplenum;
975         PyGILState_STATE gstate;
976
977         if (!self || !args)
978                 return NULL;
979
980         gstate = PyGILState_Ensure();
981
982         if (!(di = srd_inst_find_by_obj(NULL, self))) {
983                 PyErr_SetString(PyExc_Exception, "decoder instance not found");
984                 PyGILState_Release(gstate);
985                 Py_RETURN_NONE;
986         }
987
988         ret = set_new_condition_list(self, args);
989         if (ret < 0) {
990                 srd_dbg("%s: %s: Aborting wait().", di->inst_id, __func__);
991                 goto err;
992         }
993         if (ret == 9999) {
994                 /*
995                  * Empty condition list, automatic match. Arrange for the
996                  * execution of regular match handling code paths such that
997                  * the next available sample is returned to the caller.
998                  * Make sure to skip one sample when "anywhere within the
999                  * stream", yet make sure to not skip sample number 0.
1000                  */
1001                 if (di->abs_cur_samplenum)
1002                         skip_count = 1;
1003                 else if (!di->condition_list)
1004                         skip_count = 0;
1005                 else
1006                         skip_count = 1;
1007                 ret = set_skip_condition(di, skip_count);
1008                 if (ret < 0) {
1009                         srd_dbg("%s: %s: Cannot setup condition-less wait().",
1010                                 di->inst_id, __func__);
1011                         goto err;
1012                 }
1013         }
1014
1015         while (1) {
1016
1017                 Py_BEGIN_ALLOW_THREADS
1018
1019                 /* Wait for new samples to process, or termination request. */
1020                 g_mutex_lock(&di->data_mutex);
1021                 while (!di->got_new_samples && !di->want_wait_terminate)
1022                         g_cond_wait(&di->got_new_samples_cond, &di->data_mutex);
1023
1024                 /*
1025                  * Check whether any of the current condition(s) match.
1026                  * Arrange for termination requests to take a code path which
1027                  * won't find new samples to process, pretends to have processed
1028                  * previously stored samples, and returns to the main thread,
1029                  * while the termination request still gets signalled.
1030                  */
1031                 found_match = FALSE;
1032
1033                 /* Ignore return value for now, should never be negative. */
1034                 (void)process_samples_until_condition_match(di, &found_match);
1035
1036                 Py_END_ALLOW_THREADS
1037
1038                 /* If there's a match, set self.samplenum etc. and return. */
1039                 if (found_match) {
1040                         /* Set self.samplenum to the (absolute) sample number that matched. */
1041                         py_samplenum = PyLong_FromUnsignedLongLong(di->abs_cur_samplenum);
1042                         PyObject_SetAttrString(di->py_inst, "samplenum", py_samplenum);
1043                         Py_DECREF(py_samplenum);
1044
1045                         if (di->match_array && di->match_array->len > 0) {
1046                                 py_matched = PyTuple_New(di->match_array->len);
1047                                 for (i = 0; i < di->match_array->len; i++)
1048                                         PyTuple_SetItem(py_matched, i, PyBool_FromLong(di->match_array->data[i]));
1049                                 PyObject_SetAttrString(di->py_inst, "matched", py_matched);
1050                                 Py_DECREF(py_matched);
1051                                 match_array_free(di);
1052                         } else {
1053                                 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
1054                         }
1055
1056                         py_pinvalues = get_current_pinvalues(di);
1057
1058                         g_mutex_unlock(&di->data_mutex);
1059
1060                         PyGILState_Release(gstate);
1061
1062                         return py_pinvalues;
1063                 }
1064
1065                 /* No match, reset state for the next chunk. */
1066                 di->got_new_samples = FALSE;
1067                 di->handled_all_samples = TRUE;
1068                 di->abs_start_samplenum = 0;
1069                 di->abs_end_samplenum = 0;
1070                 di->inbuf = NULL;
1071                 di->inbuflen = 0;
1072
1073                 /* Signal the main thread that we handled all samples. */
1074                 g_cond_signal(&di->handled_all_samples_cond);
1075
1076                 /*
1077                  * When termination of wait() and decode() was requested,
1078                  * then exit the loop after releasing the mutex.
1079                  */
1080                 if (di->want_wait_terminate) {
1081                         srd_dbg("%s: %s: Will return from wait().",
1082                                 di->inst_id, __func__);
1083                         g_mutex_unlock(&di->data_mutex);
1084                         goto err;
1085                 }
1086
1087                 g_mutex_unlock(&di->data_mutex);
1088         }
1089
1090         PyGILState_Release(gstate);
1091
1092         Py_RETURN_NONE;
1093
1094 err:
1095         PyGILState_Release(gstate);
1096
1097         return NULL;
1098 }
1099
1100 PyDoc_STRVAR(Decoder_has_channel_doc,
1101         "Report whether a channel was supplied"
1102 );
1103
1104 /**
1105  * Return whether the specified channel was supplied to the decoder.
1106  *
1107  * @param self TODO. Must not be NULL.
1108  * @param args TODO. Must not be NULL.
1109  *
1110  * @retval Py_True The channel has been supplied by the frontend.
1111  * @retval Py_False The channel has been supplied by the frontend.
1112  * @retval NULL An error occurred.
1113  */
1114 static PyObject *Decoder_has_channel(PyObject *self, PyObject *args)
1115 {
1116         int idx, count;
1117         struct srd_decoder_inst *di;
1118         PyGILState_STATE gstate;
1119         PyObject *bool_ret;
1120
1121         if (!self || !args)
1122                 return NULL;
1123
1124         gstate = PyGILState_Ensure();
1125
1126         if (!(di = srd_inst_find_by_obj(NULL, self))) {
1127                 PyErr_SetString(PyExc_Exception, "decoder instance not found");
1128                 goto err;
1129         }
1130
1131         /*
1132          * Get the integer argument of self.has_channel(). Check for
1133          * the range of supported PD input channel numbers.
1134          */
1135         if (!PyArg_ParseTuple(args, "i", &idx)) {
1136                 /* Let Python raise this exception. */
1137                 goto err;
1138         }
1139
1140         count = g_slist_length(di->decoder->channels) +
1141                 g_slist_length(di->decoder->opt_channels);
1142         if (idx < 0 || idx >= count) {
1143                 srd_err("Invalid index %d, PD channel count %d.", idx, count);
1144                 PyErr_SetString(PyExc_IndexError, "invalid channel index");
1145                 goto err;
1146         }
1147
1148         PyGILState_Release(gstate);
1149
1150         bool_ret = (di->dec_channelmap[idx] == -1) ? Py_False : Py_True;
1151         Py_INCREF(bool_ret);
1152         return bool_ret;
1153
1154 err:
1155         PyGILState_Release(gstate);
1156
1157         return NULL;
1158 }
1159
1160 PyDoc_STRVAR(Decoder_doc, "sigrok Decoder base class");
1161
1162 static PyMethodDef Decoder_methods[] = {
1163         { "put",
1164           Decoder_put, METH_VARARGS,
1165           Decoder_put_doc,
1166         },
1167         { "register",
1168           (PyCFunction)(void(*)(void))Decoder_register, METH_VARARGS | METH_KEYWORDS,
1169           Decoder_register_doc,
1170         },
1171         { "wait",
1172           Decoder_wait, METH_VARARGS,
1173           Decoder_wait_doc,
1174         },
1175         { "has_channel",
1176           Decoder_has_channel, METH_VARARGS,
1177           Decoder_has_channel_doc,
1178         },
1179         {NULL, NULL, 0, NULL}
1180 };
1181
1182 /**
1183  * Create the sigrokdecode.Decoder type.
1184  *
1185  * @return The new type object.
1186  *
1187  * @private
1188  */
1189 SRD_PRIV PyObject *srd_Decoder_type_new(void)
1190 {
1191         PyType_Spec spec;
1192         PyType_Slot slots[] = {
1193                 { Py_tp_doc, Decoder_doc },
1194                 { Py_tp_methods, Decoder_methods },
1195                 { Py_tp_new, (void *)&PyType_GenericNew },
1196                 { 0, NULL }
1197         };
1198         PyObject *py_obj;
1199         PyGILState_STATE gstate;
1200
1201         gstate = PyGILState_Ensure();
1202
1203         spec.name = "sigrokdecode.Decoder";
1204         spec.basicsize = sizeof(srd_Decoder);
1205         spec.itemsize = 0;
1206         spec.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1207         spec.slots = slots;
1208
1209         py_obj = PyType_FromSpec(&spec);
1210
1211         PyGILState_Release(gstate);
1212
1213         return py_obj;
1214 }