2 * This file is part of the libsigrokdecode project.
4 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
21 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode.h"
26 extern SRD_PRIV GSList *sessions;
33 /* This is only used for nicer srd_dbg() output. */
34 SRD_PRIV const char *output_type_name(unsigned int idx)
36 static const char names[][16] = {
45 return names[MIN(idx, G_N_ELEMENTS(names) - 1)];
48 static void release_annotation(struct srd_proto_data_annotation *pda)
53 g_strfreev(pda->ann_text);
56 static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
57 struct srd_proto_data *pdata)
60 struct srd_pd_output *pdo;
61 struct srd_proto_data_annotation *pda;
64 PyGILState_STATE gstate;
66 gstate = PyGILState_Ensure();
68 /* Should be a list of [annotation class, [string, ...]]. */
69 if (!PyList_Check(obj)) {
70 srd_err("Protocol decoder %s submitted an annotation that"
71 " is not a list", di->decoder->name);
75 /* Should have 2 elements. */
76 if (PyList_Size(obj) != 2) {
77 srd_err("Protocol decoder %s submitted annotation list with "
78 "%zd elements instead of 2", di->decoder->name,
84 * The first element should be an integer matching a previously
85 * registered annotation class.
87 py_tmp = PyList_GetItem(obj, 0);
88 if (!PyLong_Check(py_tmp)) {
89 srd_err("Protocol decoder %s submitted annotation list, but "
90 "first element was not an integer.", di->decoder->name);
93 ann_class = PyLong_AsLong(py_tmp);
94 if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_class))) {
95 srd_err("Protocol decoder %s submitted data to unregistered "
96 "annotation class %d.", di->decoder->name, ann_class);
100 /* Second element must be a list. */
101 py_tmp = PyList_GetItem(obj, 1);
102 if (!PyList_Check(py_tmp)) {
103 srd_err("Protocol decoder %s submitted annotation list, but "
104 "second element was not a list.", di->decoder->name);
107 if (py_strseq_to_char(py_tmp, &ann_text) != SRD_OK) {
108 srd_err("Protocol decoder %s submitted annotation list, but "
109 "second element was malformed.", di->decoder->name);
114 pda->ann_class = ann_class;
115 pda->ann_text = ann_text;
117 PyGILState_Release(gstate);
122 PyGILState_Release(gstate);
124 return SRD_ERR_PYTHON;
127 static void release_logic(struct srd_proto_data_logic *pdl)
131 g_free((void *)pdl->data);
134 static int convert_logic(struct srd_decoder_inst *di, PyObject *obj,
135 struct srd_proto_data *pdata)
137 struct srd_proto_data_logic *pdl;
141 char *class_name, *buf;
142 PyGILState_STATE gstate;
144 gstate = PyGILState_Ensure();
146 /* Should be a list of [logic class, bytes]. */
147 if (!PyList_Check(obj)) {
148 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_LOGIC.",
153 /* Should have 2 elements. */
154 if (PyList_Size(obj) != 2) {
155 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list "
156 "with %zd elements instead of 2", di->decoder->name,
161 /* The first element should be an integer. */
162 py_tmp = PyList_GetItem(obj, 0);
163 if (!PyLong_Check(py_tmp)) {
164 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list, "
165 "but first element was not an integer.", di->decoder->name);
168 logic_class = PyLong_AsLong(py_tmp);
169 if (!(class_name = g_slist_nth_data(di->decoder->logic_output_channels, logic_class))) {
170 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC with "
171 "unregistered logic class %d.", di->decoder->name, logic_class);
175 /* Second element should be bytes. */
176 py_tmp = PyList_GetItem(obj, 1);
177 if (!PyBytes_Check(py_tmp)) {
178 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list, "
179 "but second element was not bytes.", di->decoder->name);
183 /* Consider an empty set of bytes a bug. */
184 if (PyBytes_Size(py_tmp) == 0) {
185 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC "
186 "with empty data set.", di->decoder->name);
190 if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
193 PyGILState_Release(gstate);
196 pdl->logic_class = logic_class;
198 if (!(pdl->data = g_try_malloc(pdl->size)))
199 return SRD_ERR_MALLOC;
200 memcpy((void *)pdl->data, (const void *)buf, pdl->size);
205 PyGILState_Release(gstate);
207 return SRD_ERR_PYTHON;
210 static void release_binary(struct srd_proto_data_binary *pdb)
214 g_free((void *)pdb->data);
217 static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
218 struct srd_proto_data *pdata)
220 struct srd_proto_data_binary *pdb;
224 char *class_name, *buf;
225 PyGILState_STATE gstate;
227 gstate = PyGILState_Ensure();
229 /* Should be a list of [binary class, bytes]. */
230 if (!PyList_Check(obj)) {
231 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_BINARY.",
236 /* Should have 2 elements. */
237 if (PyList_Size(obj) != 2) {
238 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list "
239 "with %zd elements instead of 2", di->decoder->name,
244 /* The first element should be an integer. */
245 py_tmp = PyList_GetItem(obj, 0);
246 if (!PyLong_Check(py_tmp)) {
247 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
248 "but first element was not an integer.", di->decoder->name);
251 bin_class = PyLong_AsLong(py_tmp);
252 if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
253 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
254 "unregistered binary class %d.", di->decoder->name, bin_class);
258 /* Second element should be bytes. */
259 py_tmp = PyList_GetItem(obj, 1);
260 if (!PyBytes_Check(py_tmp)) {
261 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
262 "but second element was not bytes.", di->decoder->name);
266 /* Consider an empty set of bytes a bug. */
267 if (PyBytes_Size(py_tmp) == 0) {
268 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
269 "with empty data set.", di->decoder->name);
273 if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
276 PyGILState_Release(gstate);
279 pdb->bin_class = bin_class;
281 if (!(pdb->data = g_try_malloc(pdb->size)))
282 return SRD_ERR_MALLOC;
283 memcpy((void *)pdb->data, (const void *)buf, pdb->size);
288 PyGILState_Release(gstate);
290 return SRD_ERR_PYTHON;
293 static inline struct srd_decoder_inst *srd_sess_inst_find_by_obj(
294 struct srd_session *sess, const GSList *stack, const PyObject *obj)
297 struct srd_decoder_inst *tmp, *di;
303 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
305 if (tmp->py_inst == obj)
307 else if (tmp->next_di)
308 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
315 * Find a decoder instance by its Python object.
317 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
318 * This will recurse to find the instance anywhere in the stack tree of all
321 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
322 * stack to search. To start searching at the bottom level of
323 * decoder instances, pass NULL.
324 * @param obj The Python class instantiation.
326 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
330 static inline struct srd_decoder_inst *srd_inst_find_by_obj(
331 const GSList *stack, const PyObject *obj)
333 struct srd_decoder_inst *di;
334 struct srd_session *sess;
337 /* Performance shortcut: Handle the most common case first. */
338 sess = sessions->data;
339 di = sess->di_list->data;
340 if (di->py_inst == obj)
344 for (l = sessions; di == NULL && l != NULL; l = l->next) {
346 di = srd_sess_inst_find_by_obj(sess, stack, obj);
352 static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
356 PyGILState_STATE gstate;
358 gstate = PyGILState_Ensure();
360 if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_INT64)) {
361 if (!PyLong_Check(obj)) {
362 PyErr_Format(PyExc_TypeError, "This output was registered "
363 "as 'int', but something else was passed.");
366 intvalue = PyLong_AsLongLong(obj);
367 if (PyErr_Occurred())
369 pdata->data = g_variant_new_int64(intvalue);
370 } else if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_DOUBLE)) {
371 if (!PyFloat_Check(obj)) {
372 PyErr_Format(PyExc_TypeError, "This output was registered "
373 "as 'float', but something else was passed.");
376 dvalue = PyFloat_AsDouble(obj);
377 if (PyErr_Occurred())
379 pdata->data = g_variant_new_double(dvalue);
382 PyGILState_Release(gstate);
387 PyGILState_Release(gstate);
389 return SRD_ERR_PYTHON;
392 static void release_meta(GVariant *gvar)
396 g_variant_unref(gvar);
399 static PyObject *Decoder_put(PyObject *self, PyObject *args)
402 PyObject *py_data, *py_res;
403 struct srd_decoder_inst *di, *next_di;
404 struct srd_pd_output *pdo;
405 struct srd_proto_data pdata;
406 struct srd_proto_data_annotation pda;
407 struct srd_proto_data_binary pdb;
408 uint64_t start_sample, end_sample;
410 struct srd_pd_callback *cb;
411 PyGILState_STATE gstate;
415 gstate = PyGILState_Ensure();
417 if (!(di = srd_inst_find_by_obj(NULL, self))) {
418 /* Shouldn't happen. */
419 srd_dbg("put(): self instance not found.");
423 if (!PyArg_ParseTuple(args, "KKiO", &start_sample, &end_sample,
424 &output_id, &py_data)) {
426 * This throws an exception, but by returning NULL here we let
427 * Python raise it. This results in a much better trace in
428 * controller.c on the decode() method call.
433 if (!(l = g_slist_nth(di->pd_output, output_id))) {
434 srd_err("Protocol decoder %s submitted invalid output ID %d.",
435 di->decoder->name, output_id);
440 /* Upon SRD_OUTPUT_PYTHON for stacked PDs, we have a nicer log message later. */
441 if (pdo->output_type != SRD_OUTPUT_PYTHON && di->next_di != NULL) {
442 srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on "
443 "oid %d (%s).", di->inst_id, start_sample, end_sample,
444 output_type_name(pdo->output_type), output_id,
448 pdata.start_sample = start_sample;
449 pdata.end_sample = end_sample;
453 switch (pdo->output_type) {
455 /* Annotations are only fed to callbacks. */
456 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
458 /* Convert from PyDict to srd_proto_data_annotation. */
459 if (convert_annotation(di, py_data, &pdata) != SRD_OK) {
460 /* An error was already logged. */
463 Py_BEGIN_ALLOW_THREADS
464 cb->cb(&pdata, cb->cb_data);
466 release_annotation(pdata.data);
469 case SRD_OUTPUT_PYTHON:
470 for (l = di->next_di; l; l = l->next) {
472 srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s "
473 "on oid %d (%s) to instance %s.", di->inst_id,
475 end_sample, output_type_name(pdo->output_type),
476 output_id, pdo->proto_id, next_di->inst_id);
477 if (!(py_res = PyObject_CallMethod(
478 next_di->py_inst, "decode", "KKO", start_sample,
479 end_sample, py_data))) {
480 srd_exception_catch("Calling %s decode() failed",
485 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
487 * Frontends aren't really supposed to get Python
488 * callbacks, but it's useful for testing.
490 pdata.data = py_data;
491 cb->cb(&pdata, cb->cb_data);
494 case SRD_OUTPUT_BINARY:
495 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
497 /* Convert from PyDict to srd_proto_data_binary. */
498 if (convert_binary(di, py_data, &pdata) != SRD_OK) {
499 /* An error was already logged. */
502 Py_BEGIN_ALLOW_THREADS
503 cb->cb(&pdata, cb->cb_data);
505 release_binary(pdata.data);
508 case SRD_OUTPUT_LOGIC:
509 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
511 /* Convert from PyDict to srd_proto_data_logic. */
512 if (convert_logic(di, py_data, &pdata) != SRD_OK) {
513 /* An error was already logged. */
516 Py_BEGIN_ALLOW_THREADS
517 cb->cb(&pdata, cb->cb_data);
519 release_logic(pdata.data);
522 case SRD_OUTPUT_META:
523 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
524 /* Annotations need converting from PyObject. */
525 if (convert_meta(&pdata, py_data) != SRD_OK) {
526 /* An exception was already set up. */
529 Py_BEGIN_ALLOW_THREADS
530 cb->cb(&pdata, cb->cb_data);
532 release_meta(pdata.data);
536 srd_err("Protocol decoder %s submitted invalid output type %d.",
537 di->decoder->name, pdo->output_type);
541 PyGILState_Release(gstate);
546 PyGILState_Release(gstate);
551 static PyObject *Decoder_register(PyObject *self, PyObject *args,
554 struct srd_decoder_inst *di;
555 struct srd_pd_output *pdo;
556 PyObject *py_new_output_id;
557 PyTypeObject *meta_type_py;
558 const GVariantType *meta_type_gv;
560 char *proto_id, *meta_name, *meta_descr;
561 char *keywords[] = { "output_type", "proto_id", "meta", NULL };
562 PyGILState_STATE gstate;
565 struct srd_pd_output *cmp;
567 gstate = PyGILState_Ensure();
571 meta_name = meta_descr = NULL;
573 if (!(di = srd_inst_find_by_obj(NULL, self))) {
574 PyErr_SetString(PyExc_Exception, "decoder instance not found");
578 /* Default to instance ID, which defaults to class ID. */
579 proto_id = di->inst_id;
580 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
581 &output_type, &proto_id,
582 &meta_type_py, &meta_name, &meta_descr)) {
583 /* Let Python raise this exception. */
587 /* Check if the meta value's type is supported. */
588 is_meta = output_type == SRD_OUTPUT_META;
590 if (meta_type_py == &PyLong_Type)
591 meta_type_gv = G_VARIANT_TYPE_INT64;
592 else if (meta_type_py == &PyFloat_Type)
593 meta_type_gv = G_VARIANT_TYPE_DOUBLE;
595 PyErr_Format(PyExc_TypeError, "Unsupported type.");
601 for (l = di->pd_output; l; l = l->next) {
603 if (cmp->output_type != output_type)
605 if (strcmp(cmp->proto_id, proto_id) != 0)
607 if (is_meta && cmp->meta_type != meta_type_gv)
609 if (is_meta && strcmp(cmp->meta_name, meta_name) != 0)
611 if (is_meta && strcmp(cmp->meta_descr, meta_descr) != 0)
617 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
618 PyGILState_Release(gstate);
619 return py_new_output_id;
622 pdo = g_malloc(sizeof(struct srd_pd_output));
624 /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
625 pdo->pdo_id = g_slist_length(di->pd_output);
626 pdo->output_type = output_type;
628 pdo->proto_id = g_strdup(proto_id);
630 if (output_type == SRD_OUTPUT_META) {
631 pdo->meta_type = meta_type_gv;
632 pdo->meta_name = g_strdup(meta_name);
633 pdo->meta_descr = g_strdup(meta_descr);
636 di->pd_output = g_slist_append(di->pd_output, pdo);
637 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
639 PyGILState_Release(gstate);
641 srd_dbg("Instance %s creating new output type %s as oid %d (%s).",
642 di->inst_id, output_type_name(output_type), pdo->pdo_id,
645 return py_new_output_id;
648 PyGILState_Release(gstate);
653 static int get_term_type(const char *v)
657 return SRD_TERM_HIGH;
661 return SRD_TERM_RISING_EDGE;
663 return SRD_TERM_FALLING_EDGE;
665 return SRD_TERM_EITHER_EDGE;
667 return SRD_TERM_NO_EDGE;
676 * Get the pin values at the current sample number.
678 * @param di The decoder instance to use. Must not be NULL.
679 * The number of channels must be >= 1.
681 * @return A newly allocated PyTuple containing the pin values at the
682 * current sample number.
684 static PyObject *get_current_pinvalues(const struct srd_decoder_inst *di)
688 const uint8_t *sample_pos;
689 int byte_offset, bit_offset;
690 PyObject *py_pinvalues;
691 PyGILState_STATE gstate;
694 srd_err("Invalid decoder instance.");
698 gstate = PyGILState_Ensure();
700 py_pinvalues = PyTuple_New(di->dec_num_channels);
702 for (i = 0; i < di->dec_num_channels; i++) {
703 /* A channelmap value of -1 means "unused optional channel". */
704 if (di->dec_channelmap[i] == -1) {
705 /* Value of unused channel is 0xff, instead of 0 or 1. */
706 PyTuple_SetItem(py_pinvalues, i, PyLong_FromUnsignedLong(0xff));
708 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
709 byte_offset = di->dec_channelmap[i] / 8;
710 bit_offset = di->dec_channelmap[i] % 8;
711 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
712 PyTuple_SetItem(py_pinvalues, i, PyLong_FromUnsignedLong(sample));
716 PyGILState_Release(gstate);
722 * Create a list of terms in the specified condition.
724 * If there are no terms in the condition, 'term_list' will be NULL.
726 * @param di The decoder instance to use. Must not be NULL.
727 * @param py_dict A Python dict containing terms. Must not be NULL.
728 * @param term_list Pointer to a GSList which will be set to the newly
729 * created list of terms. Must not be NULL.
731 * @return SRD_OK upon success, a negative error code otherwise.
733 static int create_term_list(struct srd_decoder_inst *di,
734 PyObject *py_dict, GSList **term_list)
737 PyObject *py_key, *py_value;
738 struct srd_term *term;
739 int64_t num_samples_to_skip;
741 PyGILState_STATE gstate;
743 if (!py_dict || !term_list)
746 /* "Create" an empty GSList of terms. */
749 gstate = PyGILState_Ensure();
751 /* Iterate over all items in the current dict. */
752 while (PyDict_Next(py_dict, &pos, &py_key, &py_value)) {
753 /* Check whether the current key is a string or a number. */
754 if (PyLong_Check(py_key)) {
755 /* The key is a number. */
756 /* Get the value string. */
757 if ((py_pydictitem_as_str(py_dict, py_key, &term_str)) != SRD_OK) {
758 srd_err("Failed to get the value.");
761 term = g_malloc(sizeof(struct srd_term));
762 term->type = get_term_type(term_str);
763 term->channel = PyLong_AsLong(py_key);
764 if (term->channel < 0 || term->channel >= di->dec_num_channels)
765 term->type = SRD_TERM_ALWAYS_FALSE;
767 } else if (PyUnicode_Check(py_key)) {
768 /* The key is a string. */
769 /* TODO: Check if the key is "skip". */
770 if ((py_pydictitem_as_long(py_dict, py_key, &num_samples_to_skip)) != SRD_OK) {
771 srd_err("Failed to get number of samples to skip.");
774 term = g_malloc(sizeof(struct srd_term));
775 term->type = SRD_TERM_SKIP;
776 term->num_samples_to_skip = num_samples_to_skip;
777 term->num_samples_already_skipped = 0;
778 if (num_samples_to_skip < 0)
779 term->type = SRD_TERM_ALWAYS_FALSE;
781 srd_err("Term key is neither a string nor a number.");
785 /* Add the term to the list of terms. */
786 *term_list = g_slist_append(*term_list, term);
789 PyGILState_Release(gstate);
794 PyGILState_Release(gstate);
800 * Replace the current condition list with the new one.
802 * @param self TODO. Must not be NULL.
803 * @param args TODO. Must not be NULL.
805 * @retval SRD_OK The new condition list was set successfully.
806 * @retval SRD_ERR There was an error setting the new condition list.
807 * The contents of di->condition_list are undefined.
810 static int set_new_condition_list(PyObject *self, PyObject *args)
812 struct srd_decoder_inst *di;
814 PyObject *py_conditionlist, *py_conds, *py_dict;
815 int i, num_conditions, ret;
816 PyGILState_STATE gstate;
821 gstate = PyGILState_Ensure();
823 /* Get the decoder instance. */
824 if (!(di = srd_inst_find_by_obj(NULL, self))) {
825 PyErr_SetString(PyExc_Exception, "decoder instance not found");
830 * Return an error condition from .wait() when termination is
831 * requested, such that decode() will terminate.
833 if (di->want_wait_terminate) {
834 srd_dbg("%s: %s: Skip (want_term).", di->inst_id, __func__);
839 * Parse the argument of self.wait() into 'py_conds', and check
840 * the data type. The argument is optional, None is assumed in
841 * its absence. None or an empty dict or an empty list mean that
842 * there is no condition, and the next available sample shall
843 * get returned to the caller.
846 if (!PyArg_ParseTuple(args, "|O", &py_conds)) {
847 /* Let Python raise this exception. */
850 if (py_conds == Py_None) {
851 /* 'py_conds' is None. */
853 } else if (PyList_Check(py_conds)) {
854 /* 'py_conds' is a list. */
855 py_conditionlist = py_conds;
856 num_conditions = PyList_Size(py_conditionlist);
857 if (num_conditions == 0)
858 goto ret_9999; /* The PD invoked self.wait([]). */
859 Py_INCREF(py_conditionlist);
860 } else if (PyDict_Check(py_conds)) {
861 /* 'py_conds' is a dict. */
862 if (PyDict_Size(py_conds) == 0)
863 goto ret_9999; /* The PD invoked self.wait({}). */
864 /* Make a list and put the dict in there for convenience. */
865 py_conditionlist = PyList_New(1);
867 PyList_SetItem(py_conditionlist, 0, py_conds);
870 srd_err("Condition list is neither a list nor a dict.");
874 /* Free the old condition list. */
875 condition_list_free(di);
879 /* Iterate over the conditions, set di->condition_list accordingly. */
880 for (i = 0; i < num_conditions; i++) {
881 /* Get a condition (dict) from the condition list. */
882 py_dict = PyList_GetItem(py_conditionlist, i);
883 if (!PyDict_Check(py_dict)) {
884 srd_err("Condition is not a dict.");
889 /* Create the list of terms in this condition. */
890 if ((ret = create_term_list(di, py_dict, &term_list)) < 0)
893 /* Add the new condition to the PD instance's condition list. */
894 di->condition_list = g_slist_append(di->condition_list, term_list);
897 Py_DecRef(py_conditionlist);
899 PyGILState_Release(gstate);
904 PyGILState_Release(gstate);
909 PyGILState_Release(gstate);
915 * Create a SKIP condition list for condition-less .wait() calls.
917 * @param di Decoder instance.
918 * @param count Number of samples to skip.
920 * @retval SRD_OK The new condition list was set successfully.
921 * @retval SRD_ERR There was an error setting the new condition list.
922 * The contents of di->condition_list are undefined.
924 * This routine is a reduced and specialized version of the @ref
925 * set_new_condition_list() and @ref create_term_list() routines which
926 * gets invoked when .wait() was called without specifications for
927 * conditions. This minor duplication of the SKIP term list creation
928 * simplifies the logic and avoids the creation of expensive Python
929 * objects with "constant" values which the caller did not pass in the
930 * first place. It results in maximum sharing of match handling code
933 static int set_skip_condition(struct srd_decoder_inst *di, uint64_t count)
935 struct srd_term *term;
938 condition_list_free(di);
939 term = g_malloc(sizeof(*term));
940 term->type = SRD_TERM_SKIP;
941 term->num_samples_to_skip = count;
942 term->num_samples_already_skipped = 0;
943 term_list = g_slist_append(NULL, term);
944 di->condition_list = g_slist_append(di->condition_list, term_list);
949 static PyObject *Decoder_wait(PyObject *self, PyObject *args)
954 gboolean found_match;
955 struct srd_decoder_inst *di;
956 PyObject *py_pinvalues, *py_matched, *py_samplenum;
957 PyGILState_STATE gstate;
962 gstate = PyGILState_Ensure();
964 if (!(di = srd_inst_find_by_obj(NULL, self))) {
965 PyErr_SetString(PyExc_Exception, "decoder instance not found");
966 PyGILState_Release(gstate);
970 ret = set_new_condition_list(self, args);
972 srd_dbg("%s: %s: Aborting wait().", di->inst_id, __func__);
977 * Empty condition list, automatic match. Arrange for the
978 * execution of regular match handling code paths such that
979 * the next available sample is returned to the caller.
980 * Make sure to skip one sample when "anywhere within the
981 * stream", yet make sure to not skip sample number 0.
983 if (di->abs_cur_samplenum)
985 else if (!di->condition_list)
989 ret = set_skip_condition(di, skip_count);
991 srd_dbg("%s: %s: Cannot setup condition-less wait().",
992 di->inst_id, __func__);
999 Py_BEGIN_ALLOW_THREADS
1001 /* Wait for new samples to process, or termination request. */
1002 g_mutex_lock(&di->data_mutex);
1003 while (!di->got_new_samples && !di->want_wait_terminate)
1004 g_cond_wait(&di->got_new_samples_cond, &di->data_mutex);
1007 * Check whether any of the current condition(s) match.
1008 * Arrange for termination requests to take a code path which
1009 * won't find new samples to process, pretends to have processed
1010 * previously stored samples, and returns to the main thread,
1011 * while the termination request still gets signalled.
1013 found_match = FALSE;
1015 /* Ignore return value for now, should never be negative. */
1016 (void)process_samples_until_condition_match(di, &found_match);
1018 Py_END_ALLOW_THREADS
1020 /* If there's a match, set self.samplenum etc. and return. */
1022 /* Set self.samplenum to the (absolute) sample number that matched. */
1023 py_samplenum = PyLong_FromUnsignedLongLong(di->abs_cur_samplenum);
1024 PyObject_SetAttrString(di->py_inst, "samplenum", py_samplenum);
1025 Py_DECREF(py_samplenum);
1027 if (di->match_array && di->match_array->len > 0) {
1028 py_matched = PyTuple_New(di->match_array->len);
1029 for (i = 0; i < di->match_array->len; i++)
1030 PyTuple_SetItem(py_matched, i, PyBool_FromLong(di->match_array->data[i]));
1031 PyObject_SetAttrString(di->py_inst, "matched", py_matched);
1032 Py_DECREF(py_matched);
1033 match_array_free(di);
1035 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
1038 py_pinvalues = get_current_pinvalues(di);
1040 g_mutex_unlock(&di->data_mutex);
1042 PyGILState_Release(gstate);
1044 return py_pinvalues;
1047 /* No match, reset state for the next chunk. */
1048 di->got_new_samples = FALSE;
1049 di->handled_all_samples = TRUE;
1050 di->abs_start_samplenum = 0;
1051 di->abs_end_samplenum = 0;
1055 /* Signal the main thread that we handled all samples. */
1056 g_cond_signal(&di->handled_all_samples_cond);
1059 * When termination of wait() and decode() was requested,
1060 * then exit the loop after releasing the mutex.
1062 if (di->want_wait_terminate) {
1063 srd_dbg("%s: %s: Will return from wait().",
1064 di->inst_id, __func__);
1065 g_mutex_unlock(&di->data_mutex);
1069 g_mutex_unlock(&di->data_mutex);
1072 PyGILState_Release(gstate);
1077 PyGILState_Release(gstate);
1083 * Return whether the specified channel was supplied to the decoder.
1085 * @param self TODO. Must not be NULL.
1086 * @param args TODO. Must not be NULL.
1088 * @retval Py_True The channel has been supplied by the frontend.
1089 * @retval Py_False The channel has been supplied by the frontend.
1090 * @retval NULL An error occurred.
1092 static PyObject *Decoder_has_channel(PyObject *self, PyObject *args)
1095 struct srd_decoder_inst *di;
1096 PyGILState_STATE gstate;
1101 gstate = PyGILState_Ensure();
1103 if (!(di = srd_inst_find_by_obj(NULL, self))) {
1104 PyErr_SetString(PyExc_Exception, "decoder instance not found");
1109 * Get the integer argument of self.has_channel(). Check for
1110 * the range of supported PD input channel numbers.
1112 if (!PyArg_ParseTuple(args, "i", &idx)) {
1113 /* Let Python raise this exception. */
1117 count = g_slist_length(di->decoder->channels) +
1118 g_slist_length(di->decoder->opt_channels);
1119 if (idx < 0 || idx >= count) {
1120 srd_err("Invalid index %d, PD channel count %d.", idx, count);
1121 PyErr_SetString(PyExc_IndexError, "invalid channel index");
1125 PyGILState_Release(gstate);
1127 return (di->dec_channelmap[idx] == -1) ? Py_False : Py_True;
1130 PyGILState_Release(gstate);
1135 static PyMethodDef Decoder_methods[] = {
1136 { "put", Decoder_put, METH_VARARGS,
1137 "Accepts a dictionary with the following keys: startsample, endsample, data" },
1138 { "register", (PyCFunction)(void(*)(void))Decoder_register, METH_VARARGS|METH_KEYWORDS,
1139 "Register a new output stream" },
1140 { "wait", Decoder_wait, METH_VARARGS,
1141 "Wait for one or more conditions to occur" },
1142 { "has_channel", Decoder_has_channel, METH_VARARGS,
1143 "Report whether a channel was supplied" },
1144 {NULL, NULL, 0, NULL}
1148 * Create the sigrokdecode.Decoder type.
1150 * @return The new type object.
1154 SRD_PRIV PyObject *srd_Decoder_type_new(void)
1157 PyType_Slot slots[] = {
1158 { Py_tp_doc, "sigrok Decoder base class" },
1159 { Py_tp_methods, Decoder_methods },
1160 { Py_tp_new, (void *)&PyType_GenericNew },
1164 PyGILState_STATE gstate;
1166 gstate = PyGILState_Ensure();
1168 spec.name = "sigrokdecode.Decoder";
1169 spec.basicsize = sizeof(srd_Decoder);
1171 spec.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1174 py_obj = PyType_FromSpec(&spec);
1176 PyGILState_Release(gstate);