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