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