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