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