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