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