]> sigrok.org Git - libsigrokdecode.git/blob - type_decoder.c
f2ac87d27f633b5e626c2a493dc5c6be96f12e13
[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 static const char *output_type_name(unsigned int idx)
31 {
32         static const char names[][16] = {
33                 "OUTPUT_ANN",
34                 "OUTPUT_PYTHON",
35                 "OUTPUT_BINARY",
36                 "OUTPUT_META",
37                 "(invalid)"
38         };
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         g_free((void *)pdb->data);
129         g_free(pdb);
130 }
131
132 static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
133                 struct srd_proto_data *pdata)
134 {
135         struct srd_proto_data_binary *pdb;
136         PyObject *py_tmp;
137         Py_ssize_t size;
138         int bin_class;
139         char *class_name, *buf;
140         PyGILState_STATE gstate;
141
142         gstate = PyGILState_Ensure();
143
144         /* Should be a list of [binary class, bytes]. */
145         if (!PyList_Check(obj)) {
146                 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_BINARY.",
147                         di->decoder->name);
148                 goto err;
149         }
150
151         /* Should have 2 elements. */
152         if (PyList_Size(obj) != 2) {
153                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list "
154                                 "with %zd elements instead of 2", di->decoder->name,
155                                 PyList_Size(obj));
156                 goto err;
157         }
158
159         /* The first element should be an integer. */
160         py_tmp = PyList_GetItem(obj, 0);
161         if (!PyLong_Check(py_tmp)) {
162                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
163                         "but first element was not an integer.", di->decoder->name);
164                 goto err;
165         }
166         bin_class = PyLong_AsLong(py_tmp);
167         if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
168                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
169                         "unregistered binary class %d.", di->decoder->name, bin_class);
170                 goto err;
171         }
172
173         /* Second element should be bytes. */
174         py_tmp = PyList_GetItem(obj, 1);
175         if (!PyBytes_Check(py_tmp)) {
176                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
177                         "but second element was not bytes.", di->decoder->name);
178                 goto err;
179         }
180
181         /* Consider an empty set of bytes a bug. */
182         if (PyBytes_Size(py_tmp) == 0) {
183                 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
184                                 "with empty data set.", di->decoder->name);
185                 goto err;
186         }
187
188         if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
189                 goto err;
190
191         PyGILState_Release(gstate);
192
193         pdb = g_malloc(sizeof(struct srd_proto_data_binary));
194         pdb->bin_class = bin_class;
195         pdb->size = size;
196         if (!(pdb->data = g_try_malloc(pdb->size))) {
197                 g_free(pdb);
198                 return SRD_ERR_MALLOC;
199         }
200         memcpy((void *)pdb->data, (const void *)buf, pdb->size);
201         pdata->data = pdb;
202
203         return SRD_OK;
204
205 err:
206         PyGILState_Release(gstate);
207
208         return SRD_ERR_PYTHON;
209 }
210
211 static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
212 {
213         long long intvalue;
214         double dvalue;
215         PyGILState_STATE gstate;
216
217         gstate = PyGILState_Ensure();
218
219         if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_INT64)) {
220                 if (!PyLong_Check(obj)) {
221                         PyErr_Format(PyExc_TypeError, "This output was registered "
222                                         "as 'int', but something else was passed.");
223                         goto err;
224                 }
225                 intvalue = PyLong_AsLongLong(obj);
226                 if (PyErr_Occurred())
227                         goto err;
228                 pdata->data = g_variant_new_int64(intvalue);
229         } else if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_DOUBLE)) {
230                 if (!PyFloat_Check(obj)) {
231                         PyErr_Format(PyExc_TypeError, "This output was registered "
232                                         "as 'float', but something else was passed.");
233                         goto err;
234                 }
235                 dvalue = PyFloat_AsDouble(obj);
236                 if (PyErr_Occurred())
237                         goto err;
238                 pdata->data = g_variant_new_double(dvalue);
239         }
240
241         PyGILState_Release(gstate);
242
243         return SRD_OK;
244
245 err:
246         PyGILState_Release(gstate);
247
248         return SRD_ERR_PYTHON;
249 }
250
251 static void release_meta(GVariant *gvar)
252 {
253         if (!gvar)
254                 return;
255         g_variant_unref(gvar);
256 }
257
258 static PyObject *Decoder_put(PyObject *self, PyObject *args)
259 {
260         GSList *l;
261         PyObject *py_data, *py_res;
262         struct srd_decoder_inst *di, *next_di;
263         struct srd_pd_output *pdo;
264         struct srd_proto_data pdata;
265         uint64_t start_sample, end_sample;
266         int output_id;
267         struct srd_pd_callback *cb;
268         PyGILState_STATE gstate;
269
270         py_data = NULL;
271
272         gstate = PyGILState_Ensure();
273
274         if (!(di = srd_inst_find_by_obj(NULL, self))) {
275                 /* Shouldn't happen. */
276                 srd_dbg("put(): self instance not found.");
277                 goto err;
278         }
279
280         if (!PyArg_ParseTuple(args, "KKiO", &start_sample, &end_sample,
281                 &output_id, &py_data)) {
282                 /*
283                  * This throws an exception, but by returning NULL here we let
284                  * Python raise it. This results in a much better trace in
285                  * controller.c on the decode() method call.
286                  */
287                 goto err;
288         }
289
290         if (!(l = g_slist_nth(di->pd_output, output_id))) {
291                 srd_err("Protocol decoder %s submitted invalid output ID %d.",
292                         di->decoder->name, output_id);
293                 goto err;
294         }
295         pdo = l->data;
296
297         srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on oid %d.",
298                  di->inst_id, start_sample, end_sample,
299                  output_type_name(pdo->output_type), output_id);
300
301         pdata.start_sample = start_sample;
302         pdata.end_sample = end_sample;
303         pdata.pdo = pdo;
304         pdata.data = NULL;
305
306         switch (pdo->output_type) {
307         case SRD_OUTPUT_ANN:
308                 /* Annotations are only fed to callbacks. */
309                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
310                         /* Convert from PyDict to srd_proto_data_annotation. */
311                         if (convert_annotation(di, py_data, &pdata) != SRD_OK) {
312                                 /* An error was already logged. */
313                                 break;
314                         }
315                         Py_BEGIN_ALLOW_THREADS
316                         cb->cb(&pdata, cb->cb_data);
317                         Py_END_ALLOW_THREADS
318                         release_annotation(pdata.data);
319                 }
320                 break;
321         case SRD_OUTPUT_PYTHON:
322                 for (l = di->next_di; l; l = l->next) {
323                         next_di = l->data;
324                         srd_spew("Sending %" PRIu64 "-%" PRIu64 " to instance %s",
325                                  start_sample, end_sample, next_di->inst_id);
326                         if (!(py_res = PyObject_CallMethod(
327                                 next_di->py_inst, "decode", "KKO", start_sample,
328                                 end_sample, py_data))) {
329                                 srd_exception_catch("Calling %s decode() failed",
330                                                         next_di->inst_id);
331                         }
332                         Py_XDECREF(py_res);
333                 }
334                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
335                         /*
336                          * Frontends aren't really supposed to get Python
337                          * callbacks, but it's useful for testing.
338                          */
339                         pdata.data = py_data;
340                         cb->cb(&pdata, cb->cb_data);
341                 }
342                 break;
343         case SRD_OUTPUT_BINARY:
344                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
345                         /* Convert from PyDict to srd_proto_data_binary. */
346                         if (convert_binary(di, py_data, &pdata) != SRD_OK) {
347                                 /* An error was already logged. */
348                                 break;
349                         }
350                         Py_BEGIN_ALLOW_THREADS
351                         cb->cb(&pdata, cb->cb_data);
352                         Py_END_ALLOW_THREADS
353                         release_binary(pdata.data);
354                 }
355                 break;
356         case SRD_OUTPUT_META:
357                 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
358                         /* Annotations need converting from PyObject. */
359                         if (convert_meta(&pdata, py_data) != SRD_OK) {
360                                 /* An exception was already set up. */
361                                 break;
362                         }
363                         Py_BEGIN_ALLOW_THREADS
364                         cb->cb(&pdata, cb->cb_data);
365                         Py_END_ALLOW_THREADS
366                         release_meta(pdata.data);
367                 }
368                 break;
369         default:
370                 srd_err("Protocol decoder %s submitted invalid output type %d.",
371                         di->decoder->name, pdo->output_type);
372                 break;
373         }
374
375         PyGILState_Release(gstate);
376
377         Py_RETURN_NONE;
378
379 err:
380         PyGILState_Release(gstate);
381
382         return NULL;
383 }
384
385 static PyObject *Decoder_register(PyObject *self, PyObject *args,
386                 PyObject *kwargs)
387 {
388         struct srd_decoder_inst *di;
389         struct srd_pd_output *pdo;
390         PyObject *py_new_output_id;
391         PyTypeObject *meta_type_py;
392         const GVariantType *meta_type_gv;
393         int output_type;
394         char *proto_id, *meta_name, *meta_descr;
395         char *keywords[] = { "output_type", "proto_id", "meta", NULL };
396         PyGILState_STATE gstate;
397         gboolean is_meta;
398         GSList *l;
399         struct srd_pd_output *cmp;
400
401         gstate = PyGILState_Ensure();
402
403         meta_type_py = NULL;
404         meta_type_gv = NULL;
405         meta_name = meta_descr = NULL;
406
407         if (!(di = srd_inst_find_by_obj(NULL, self))) {
408                 PyErr_SetString(PyExc_Exception, "decoder instance not found");
409                 goto err;
410         }
411
412         /* Default to instance ID, which defaults to class ID. */
413         proto_id = di->inst_id;
414         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
415                         &output_type, &proto_id,
416                         &meta_type_py, &meta_name, &meta_descr)) {
417                 /* Let Python raise this exception. */
418                 goto err;
419         }
420
421         /* Check if the meta value's type is supported. */
422         is_meta = output_type == SRD_OUTPUT_META;
423         if (is_meta) {
424                 if (meta_type_py == &PyLong_Type)
425                         meta_type_gv = G_VARIANT_TYPE_INT64;
426                 else if (meta_type_py == &PyFloat_Type)
427                         meta_type_gv = G_VARIANT_TYPE_DOUBLE;
428                 else {
429                         PyErr_Format(PyExc_TypeError, "Unsupported type.");
430                         goto err;
431                 }
432         }
433
434         pdo = NULL;
435         for (l = di->pd_output; l; l = l->next) {
436                 cmp = l->data;
437                 if (cmp->output_type != output_type)
438                         continue;
439                 if (strcmp(cmp->proto_id, proto_id) != 0)
440                         continue;
441                 if (is_meta && cmp->meta_type != meta_type_gv)
442                         continue;
443                 if (is_meta && strcmp(cmp->meta_name, meta_name) != 0)
444                         continue;
445                 if (is_meta && strcmp(cmp->meta_descr, meta_descr) != 0)
446                         continue;
447                 pdo = cmp;
448                 break;
449         }
450         if (pdo) {
451                 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
452                 PyGILState_Release(gstate);
453                 return py_new_output_id;
454         }
455
456         srd_dbg("Instance %s creating new output type %d for %s.",
457                 di->inst_id, output_type, proto_id);
458
459         pdo = g_malloc(sizeof(struct srd_pd_output));
460
461         /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
462         pdo->pdo_id = g_slist_length(di->pd_output);
463         pdo->output_type = output_type;
464         pdo->di = di;
465         pdo->proto_id = g_strdup(proto_id);
466
467         if (output_type == SRD_OUTPUT_META) {
468                 pdo->meta_type = meta_type_gv;
469                 pdo->meta_name = g_strdup(meta_name);
470                 pdo->meta_descr = g_strdup(meta_descr);
471         }
472
473         di->pd_output = g_slist_append(di->pd_output, pdo);
474         py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
475
476         PyGILState_Release(gstate);
477
478         return py_new_output_id;
479
480 err:
481         PyGILState_Release(gstate);
482
483         return NULL;
484 }
485
486 static int get_term_type(const char *v)
487 {
488         switch (v[0]) {
489         case 'h':
490                 return SRD_TERM_HIGH;
491         case 'l':
492                 return SRD_TERM_LOW;
493         case 'r':
494                 return SRD_TERM_RISING_EDGE;
495         case 'f':
496                 return SRD_TERM_FALLING_EDGE;
497         case 'e':
498                 return SRD_TERM_EITHER_EDGE;
499         case 'n':
500                 return SRD_TERM_NO_EDGE;
501         default:
502                 return -1;
503         }
504
505         return -1;
506 }
507
508 /**
509  * Get the pin values at the current sample number.
510  *
511  * @param di The decoder instance to use. Must not be NULL.
512  *           The number of channels must be >= 1.
513  *
514  * @return A newly allocated PyTuple containing the pin values at the
515  *         current sample number.
516  */
517 static PyObject *get_current_pinvalues(const struct srd_decoder_inst *di)
518 {
519         int i;
520         uint8_t sample;
521         const uint8_t *sample_pos;
522         int byte_offset, bit_offset;
523         PyObject *py_pinvalues;
524         PyGILState_STATE gstate;
525
526         if (!di) {
527                 srd_err("Invalid decoder instance.");
528                 return NULL;
529         }
530
531         gstate = PyGILState_Ensure();
532
533         py_pinvalues = PyTuple_New(di->dec_num_channels);
534
535         for (i = 0; i < di->dec_num_channels; i++) {
536                 /* A channelmap value of -1 means "unused optional channel". */
537                 if (di->dec_channelmap[i] == -1) {
538                         /* Value of unused channel is 0xff, instead of 0 or 1. */
539                         PyTuple_SetItem(py_pinvalues, i, PyLong_FromLong(0xff));
540                 } else {
541                         sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
542                         byte_offset = di->dec_channelmap[i] / 8;
543                         bit_offset = di->dec_channelmap[i] % 8;
544                         sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
545                         PyTuple_SetItem(py_pinvalues, i, PyLong_FromLong(sample));
546                 }
547         }
548
549         PyGILState_Release(gstate);
550
551         return py_pinvalues;
552 }
553
554 /**
555  * Create a list of terms in the specified condition.
556  *
557  * If there are no terms in the condition, 'term_list' will be NULL.
558  *
559  * @param py_dict A Python dict containing terms. Must not be NULL.
560  * @param term_list Pointer to a GSList which will be set to the newly
561  *                  created list of terms. Must not be NULL.
562  *
563  * @return SRD_OK upon success, a negative error code otherwise.
564  */
565 static int create_term_list(PyObject *py_dict, GSList **term_list)
566 {
567         Py_ssize_t pos = 0;
568         PyObject *py_key, *py_value;
569         struct srd_term *term;
570         uint64_t num_samples_to_skip;
571         char *term_str;
572         PyGILState_STATE gstate;
573
574         if (!py_dict || !term_list)
575                 return SRD_ERR_ARG;
576
577         /* "Create" an empty GSList of terms. */
578         *term_list = NULL;
579
580         gstate = PyGILState_Ensure();
581
582         /* Iterate over all items in the current dict. */
583         while (PyDict_Next(py_dict, &pos, &py_key, &py_value)) {
584                 /* Check whether the current key is a string or a number. */
585                 if (PyLong_Check(py_key)) {
586                         /* The key is a number. */
587                         /* TODO: Check if the number is a valid channel. */
588                         /* Get the value string. */
589                         if ((py_pydictitem_as_str(py_dict, py_key, &term_str)) != SRD_OK) {
590                                 srd_err("Failed to get the value.");
591                                 goto err;
592                         }
593                         term = g_malloc(sizeof(struct srd_term));
594                         term->type = get_term_type(term_str);
595                         term->channel = PyLong_AsLong(py_key);
596                         g_free(term_str);
597                 } else if (PyUnicode_Check(py_key)) {
598                         /* The key is a string. */
599                         /* TODO: Check if it's "skip". */
600                         if ((py_pydictitem_as_long(py_dict, py_key, &num_samples_to_skip)) != SRD_OK) {
601                                 srd_err("Failed to get number of samples to skip.");
602                                 goto err;
603                         }
604                         term = g_malloc(sizeof(struct srd_term));
605                         term->type = SRD_TERM_SKIP;
606                         term->num_samples_to_skip = num_samples_to_skip;
607                         term->num_samples_already_skipped = 0;
608                 } else {
609                         srd_err("Term key is neither a string nor a number.");
610                         goto err;
611                 }
612
613                 /* Add the term to the list of terms. */
614                 *term_list = g_slist_append(*term_list, term);
615         }
616
617         PyGILState_Release(gstate);
618
619         return SRD_OK;
620
621 err:
622         PyGILState_Release(gstate);
623
624         return SRD_ERR;
625 }
626
627 /**
628  * Replace the current condition list with the new one.
629  *
630  * @param self TODO. Must not be NULL.
631  * @param args TODO. Must not be NULL.
632  *
633  * @retval SRD_OK The new condition list was set successfully.
634  * @retval SRD_ERR There was an error setting the new condition list.
635  *                 The contents of di->condition_list are undefined.
636  * @retval 9999 TODO.
637  */
638 static int set_new_condition_list(PyObject *self, PyObject *args)
639 {
640         struct srd_decoder_inst *di;
641         GSList *term_list;
642         PyObject *py_conditionlist, *py_conds, *py_dict;
643         int i, num_conditions, ret;
644         PyGILState_STATE gstate;
645
646         if (!self || !args)
647                 return SRD_ERR_ARG;
648
649         gstate = PyGILState_Ensure();
650
651         /* Get the decoder instance. */
652         if (!(di = srd_inst_find_by_obj(NULL, self))) {
653                 PyErr_SetString(PyExc_Exception, "decoder instance not found");
654                 goto err;
655         }
656
657         /*
658          * Return an error condition from .wait() when termination is
659          * requested, such that decode() will terminate.
660          */
661         if (di->want_wait_terminate) {
662                 srd_dbg("%s: %s: Skip (want_term).", di->inst_id, __func__);
663                 goto err;
664         }
665
666         /*
667          * Parse the argument of self.wait() into 'py_conds', and check
668          * the data type. The argument is optional, None is assumed in
669          * its absence. None or an empty dict or an empty list mean that
670          * there is no condition, and the next available sample shall
671          * get returned to the caller.
672          */
673         py_conds = Py_None;
674         if (!PyArg_ParseTuple(args, "|O", &py_conds)) {
675                 /* Let Python raise this exception. */
676                 goto err;
677         }
678         if (py_conds == Py_None) {
679                 /* 'py_conds' is None. */
680                 goto ret_9999;
681         } else if (PyList_Check(py_conds)) {
682                 /* 'py_conds' is a list. */
683                 py_conditionlist = py_conds;
684                 num_conditions = PyList_Size(py_conditionlist);
685                 if (num_conditions == 0)
686                         goto ret_9999; /* The PD invoked self.wait([]). */
687                 Py_IncRef(py_conditionlist);
688         } else if (PyDict_Check(py_conds)) {
689                 /* 'py_conds' is a dict. */
690                 if (PyDict_Size(py_conds) == 0)
691                         goto ret_9999; /* The PD invoked self.wait({}). */
692                 /* Make a list and put the dict in there for convenience. */
693                 py_conditionlist = PyList_New(1);
694                 Py_IncRef(py_conds);
695                 PyList_SetItem(py_conditionlist, 0, py_conds);
696                 num_conditions = 1;
697         } else {
698                 srd_err("Condition list is neither a list nor a dict.");
699                 goto err;
700         }
701
702         /* Free the old condition list. */
703         condition_list_free(di);
704
705         ret = SRD_OK;
706
707         /* Iterate over the conditions, set di->condition_list accordingly. */
708         for (i = 0; i < num_conditions; i++) {
709                 /* Get a condition (dict) from the condition list. */
710                 py_dict = PyList_GetItem(py_conditionlist, i);
711                 if (!PyDict_Check(py_dict)) {
712                         srd_err("Condition is not a dict.");
713                         ret = SRD_ERR;
714                         break;
715                 }
716
717                 /* Create the list of terms in this condition. */
718                 if ((ret = create_term_list(py_dict, &term_list)) < 0)
719                         break;
720
721                 /* Add the new condition to the PD instance's condition list. */
722                 di->condition_list = g_slist_append(di->condition_list, term_list);
723         }
724
725         Py_DecRef(py_conditionlist);
726
727         PyGILState_Release(gstate);
728
729         return ret;
730
731 err:
732         PyGILState_Release(gstate);
733
734         return SRD_ERR;
735
736 ret_9999:
737         PyGILState_Release(gstate);
738
739         return 9999;
740 }
741
742 /**
743  * Create a SKIP condition list for condition-less .wait() calls.
744  *
745  * @param di Decoder instance.
746  * @param count Number of samples to skip.
747  *
748  * @retval SRD_OK The new condition list was set successfully.
749  * @retval SRD_ERR There was an error setting the new condition list.
750  *                 The contents of di->condition_list are undefined.
751  *
752  * This routine is a reduced and specialized version of the @ref
753  * set_new_condition_list() and @ref create_term_list() routines which
754  * gets invoked when .wait() was called without specifications for
755  * conditions. This minor duplication of the SKIP term list creation
756  * simplifies the logic and avoids the creation of expensive Python
757  * objects with "constant" values which the caller did not pass in the
758  * first place. It results in maximum sharing of match handling code
759  * paths.
760  */
761 static int set_skip_condition(struct srd_decoder_inst *di, uint64_t count)
762 {
763         struct srd_term *term;
764         GSList *term_list;
765
766         condition_list_free(di);
767         term = g_malloc(sizeof(*term));
768         term->type = SRD_TERM_SKIP;
769         term->num_samples_to_skip = count;
770         term->num_samples_already_skipped = 0;
771         term_list = g_slist_append(NULL, term);
772         di->condition_list = g_slist_append(di->condition_list, term_list);
773
774         return SRD_OK;
775 }
776
777 static PyObject *Decoder_wait(PyObject *self, PyObject *args)
778 {
779         int ret;
780         uint64_t skip_count;
781         unsigned int i;
782         gboolean found_match;
783         struct srd_decoder_inst *di;
784         PyObject *py_pinvalues, *py_matched;
785         PyGILState_STATE gstate;
786
787         if (!self || !args)
788                 return NULL;
789
790         gstate = PyGILState_Ensure();
791
792         if (!(di = srd_inst_find_by_obj(NULL, self))) {
793                 PyErr_SetString(PyExc_Exception, "decoder instance not found");
794                 PyGILState_Release(gstate);
795                 Py_RETURN_NONE;
796         }
797
798         ret = set_new_condition_list(self, args);
799         if (ret < 0) {
800                 srd_dbg("%s: %s: Aborting wait().", di->inst_id, __func__);
801                 goto err;
802         }
803         if (ret == 9999) {
804                 /*
805                  * Empty condition list, automatic match. Arrange for the
806                  * execution of regular match handling code paths such that
807                  * the next available sample is returned to the caller.
808                  * Make sure to skip one sample when "anywhere within the
809                  * stream", yet make sure to not skip sample number 0.
810                  */
811                 if (di->abs_cur_samplenum)
812                         skip_count = 1;
813                 else if (!di->condition_list)
814                         skip_count = 0;
815                 else
816                         skip_count = 1;
817                 ret = set_skip_condition(di, skip_count);
818                 if (ret < 0) {
819                         srd_dbg("%s: %s: Cannot setup condition-less wait().",
820                                 di->inst_id, __func__);
821                         goto err;
822                 }
823         }
824
825         while (1) {
826
827                 Py_BEGIN_ALLOW_THREADS
828
829                 /* Wait for new samples to process, or termination request. */
830                 g_mutex_lock(&di->data_mutex);
831                 while (!di->got_new_samples && !di->want_wait_terminate)
832                         g_cond_wait(&di->got_new_samples_cond, &di->data_mutex);
833
834                 /*
835                  * Check whether any of the current condition(s) match.
836                  * Arrange for termination requests to take a code path which
837                  * won't find new samples to process, pretends to have processed
838                  * previously stored samples, and returns to the main thread,
839                  * while the termination request still gets signalled.
840                  */
841                 found_match = FALSE;
842
843                 /* Ignore return value for now, should never be negative. */
844                 (void)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 }