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