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