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 static const char *output_type_name(unsigned int idx)
36 static const char names[][16] = {
44 return names[MIN(idx, G_N_ELEMENTS(names) - 1)];
47 static void release_annotation(struct srd_proto_data_annotation *pda)
52 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);
113 pda = g_malloc(sizeof(struct srd_proto_data_annotation));
114 pda->ann_class = ann_class;
115 pda->ann_text = ann_text;
118 PyGILState_Release(gstate);
123 PyGILState_Release(gstate);
125 return SRD_ERR_PYTHON;
128 static void release_binary(struct srd_proto_data_binary *pdb)
132 g_free((void *)pdb->data);
136 static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
137 struct srd_proto_data *pdata)
139 struct srd_proto_data_binary *pdb;
143 char *class_name, *buf;
144 PyGILState_STATE gstate;
146 gstate = PyGILState_Ensure();
148 /* Should be a list of [binary class, bytes]. */
149 if (!PyList_Check(obj)) {
150 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_BINARY.",
155 /* Should have 2 elements. */
156 if (PyList_Size(obj) != 2) {
157 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list "
158 "with %zd elements instead of 2", di->decoder->name,
163 /* The first element should be an integer. */
164 py_tmp = PyList_GetItem(obj, 0);
165 if (!PyLong_Check(py_tmp)) {
166 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
167 "but first element was not an integer.", di->decoder->name);
170 bin_class = PyLong_AsLong(py_tmp);
171 if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
172 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
173 "unregistered binary class %d.", di->decoder->name, bin_class);
177 /* Second element should be bytes. */
178 py_tmp = PyList_GetItem(obj, 1);
179 if (!PyBytes_Check(py_tmp)) {
180 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
181 "but second element was not bytes.", di->decoder->name);
185 /* Consider an empty set of bytes a bug. */
186 if (PyBytes_Size(py_tmp) == 0) {
187 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
188 "with empty data set.", di->decoder->name);
192 if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
195 PyGILState_Release(gstate);
197 pdb = g_malloc(sizeof(struct srd_proto_data_binary));
198 pdb->bin_class = bin_class;
200 if (!(pdb->data = g_try_malloc(pdb->size))) {
202 return SRD_ERR_MALLOC;
204 memcpy((void *)pdb->data, (const void *)buf, pdb->size);
210 PyGILState_Release(gstate);
212 return SRD_ERR_PYTHON;
215 static inline struct srd_decoder_inst *srd_sess_inst_find_by_obj(
216 struct srd_session *sess, const GSList *stack, const PyObject *obj)
219 struct srd_decoder_inst *tmp, *di;
225 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
227 if (tmp->py_inst == obj)
229 else if (tmp->next_di)
230 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
237 * Find a decoder instance by its Python object.
239 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
240 * This will recurse to find the instance anywhere in the stack tree of all
243 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
244 * stack to search. To start searching at the bottom level of
245 * decoder instances, pass NULL.
246 * @param obj The Python class instantiation.
248 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
252 static inline struct srd_decoder_inst *srd_inst_find_by_obj(
253 const GSList *stack, const PyObject *obj)
255 struct srd_decoder_inst *di;
256 struct srd_session *sess;
259 /* Performance shortcut: Handle the most common case first. */
260 sess = sessions->data;
261 di = sess->di_list->data;
262 if (di->py_inst == obj)
266 for (l = sessions; di == NULL && l != NULL; l = l->next) {
268 di = srd_sess_inst_find_by_obj(sess, stack, obj);
274 static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
278 PyGILState_STATE gstate;
280 gstate = PyGILState_Ensure();
282 if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_INT64)) {
283 if (!PyLong_Check(obj)) {
284 PyErr_Format(PyExc_TypeError, "This output was registered "
285 "as 'int', but something else was passed.");
288 intvalue = PyLong_AsLongLong(obj);
289 if (PyErr_Occurred())
291 pdata->data = g_variant_new_int64(intvalue);
292 } else if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_DOUBLE)) {
293 if (!PyFloat_Check(obj)) {
294 PyErr_Format(PyExc_TypeError, "This output was registered "
295 "as 'float', but something else was passed.");
298 dvalue = PyFloat_AsDouble(obj);
299 if (PyErr_Occurred())
301 pdata->data = g_variant_new_double(dvalue);
304 PyGILState_Release(gstate);
309 PyGILState_Release(gstate);
311 return SRD_ERR_PYTHON;
314 static void release_meta(GVariant *gvar)
318 g_variant_unref(gvar);
321 static PyObject *Decoder_put(PyObject *self, PyObject *args)
324 PyObject *py_data, *py_res;
325 struct srd_decoder_inst *di, *next_di;
326 struct srd_pd_output *pdo;
327 struct srd_proto_data pdata;
328 uint64_t start_sample, end_sample;
330 struct srd_pd_callback *cb;
331 PyGILState_STATE gstate;
335 gstate = PyGILState_Ensure();
337 if (!(di = srd_inst_find_by_obj(NULL, self))) {
338 /* Shouldn't happen. */
339 srd_dbg("put(): self instance not found.");
343 if (!PyArg_ParseTuple(args, "KKiO", &start_sample, &end_sample,
344 &output_id, &py_data)) {
346 * This throws an exception, but by returning NULL here we let
347 * Python raise it. This results in a much better trace in
348 * controller.c on the decode() method call.
353 if (!(l = g_slist_nth(di->pd_output, output_id))) {
354 srd_err("Protocol decoder %s submitted invalid output ID %d.",
355 di->decoder->name, output_id);
360 srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on oid %d.",
361 di->inst_id, start_sample, end_sample,
362 output_type_name(pdo->output_type), output_id);
364 pdata.start_sample = start_sample;
365 pdata.end_sample = end_sample;
369 switch (pdo->output_type) {
371 /* Annotations are only fed to callbacks. */
372 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
373 /* Convert from PyDict to srd_proto_data_annotation. */
374 if (convert_annotation(di, py_data, &pdata) != SRD_OK) {
375 /* An error was already logged. */
378 Py_BEGIN_ALLOW_THREADS
379 cb->cb(&pdata, cb->cb_data);
381 release_annotation(pdata.data);
384 case SRD_OUTPUT_PYTHON:
385 for (l = di->next_di; l; l = l->next) {
387 srd_spew("Sending %" PRIu64 "-%" PRIu64 " to instance %s",
388 start_sample, end_sample, next_di->inst_id);
389 if (!(py_res = PyObject_CallMethod(
390 next_di->py_inst, "decode", "KKO", start_sample,
391 end_sample, py_data))) {
392 srd_exception_catch("Calling %s decode() failed",
397 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
399 * Frontends aren't really supposed to get Python
400 * callbacks, but it's useful for testing.
402 pdata.data = py_data;
403 cb->cb(&pdata, cb->cb_data);
406 case SRD_OUTPUT_BINARY:
407 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
408 /* Convert from PyDict to srd_proto_data_binary. */
409 if (convert_binary(di, py_data, &pdata) != SRD_OK) {
410 /* An error was already logged. */
413 Py_BEGIN_ALLOW_THREADS
414 cb->cb(&pdata, cb->cb_data);
416 release_binary(pdata.data);
419 case SRD_OUTPUT_META:
420 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
421 /* Annotations need converting from PyObject. */
422 if (convert_meta(&pdata, py_data) != SRD_OK) {
423 /* An exception was already set up. */
426 Py_BEGIN_ALLOW_THREADS
427 cb->cb(&pdata, cb->cb_data);
429 release_meta(pdata.data);
433 srd_err("Protocol decoder %s submitted invalid output type %d.",
434 di->decoder->name, pdo->output_type);
438 PyGILState_Release(gstate);
443 PyGILState_Release(gstate);
448 static PyObject *Decoder_register(PyObject *self, PyObject *args,
451 struct srd_decoder_inst *di;
452 struct srd_pd_output *pdo;
453 PyObject *py_new_output_id;
454 PyTypeObject *meta_type_py;
455 const GVariantType *meta_type_gv;
457 char *proto_id, *meta_name, *meta_descr;
458 char *keywords[] = { "output_type", "proto_id", "meta", NULL };
459 PyGILState_STATE gstate;
462 struct srd_pd_output *cmp;
464 gstate = PyGILState_Ensure();
468 meta_name = meta_descr = NULL;
470 if (!(di = srd_inst_find_by_obj(NULL, self))) {
471 PyErr_SetString(PyExc_Exception, "decoder instance not found");
475 /* Default to instance ID, which defaults to class ID. */
476 proto_id = di->inst_id;
477 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
478 &output_type, &proto_id,
479 &meta_type_py, &meta_name, &meta_descr)) {
480 /* Let Python raise this exception. */
484 /* Check if the meta value's type is supported. */
485 is_meta = output_type == SRD_OUTPUT_META;
487 if (meta_type_py == &PyLong_Type)
488 meta_type_gv = G_VARIANT_TYPE_INT64;
489 else if (meta_type_py == &PyFloat_Type)
490 meta_type_gv = G_VARIANT_TYPE_DOUBLE;
492 PyErr_Format(PyExc_TypeError, "Unsupported type.");
498 for (l = di->pd_output; l; l = l->next) {
500 if (cmp->output_type != output_type)
502 if (strcmp(cmp->proto_id, proto_id) != 0)
504 if (is_meta && cmp->meta_type != meta_type_gv)
506 if (is_meta && strcmp(cmp->meta_name, meta_name) != 0)
508 if (is_meta && strcmp(cmp->meta_descr, meta_descr) != 0)
514 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
515 PyGILState_Release(gstate);
516 return py_new_output_id;
519 srd_dbg("Instance %s creating new output type %d for %s.",
520 di->inst_id, output_type, proto_id);
522 pdo = g_malloc(sizeof(struct srd_pd_output));
524 /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
525 pdo->pdo_id = g_slist_length(di->pd_output);
526 pdo->output_type = output_type;
528 pdo->proto_id = g_strdup(proto_id);
530 if (output_type == SRD_OUTPUT_META) {
531 pdo->meta_type = meta_type_gv;
532 pdo->meta_name = g_strdup(meta_name);
533 pdo->meta_descr = g_strdup(meta_descr);
536 di->pd_output = g_slist_append(di->pd_output, pdo);
537 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
539 PyGILState_Release(gstate);
541 return py_new_output_id;
544 PyGILState_Release(gstate);
549 static int get_term_type(const char *v)
553 return SRD_TERM_HIGH;
557 return SRD_TERM_RISING_EDGE;
559 return SRD_TERM_FALLING_EDGE;
561 return SRD_TERM_EITHER_EDGE;
563 return SRD_TERM_NO_EDGE;
572 * Get the pin values at the current sample number.
574 * @param di The decoder instance to use. Must not be NULL.
575 * The number of channels must be >= 1.
577 * @return A newly allocated PyTuple containing the pin values at the
578 * current sample number.
580 static PyObject *get_current_pinvalues(const struct srd_decoder_inst *di)
584 const uint8_t *sample_pos;
585 int byte_offset, bit_offset;
586 PyObject *py_pinvalues;
587 PyGILState_STATE gstate;
590 srd_err("Invalid decoder instance.");
594 gstate = PyGILState_Ensure();
596 py_pinvalues = PyTuple_New(di->dec_num_channels);
598 for (i = 0; i < di->dec_num_channels; i++) {
599 /* A channelmap value of -1 means "unused optional channel". */
600 if (di->dec_channelmap[i] == -1) {
601 /* Value of unused channel is 0xff, instead of 0 or 1. */
602 PyTuple_SetItem(py_pinvalues, i, PyLong_FromLong(0xff));
604 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
605 byte_offset = di->dec_channelmap[i] / 8;
606 bit_offset = di->dec_channelmap[i] % 8;
607 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
608 PyTuple_SetItem(py_pinvalues, i, PyLong_FromLong(sample));
612 PyGILState_Release(gstate);
618 * Create a list of terms in the specified condition.
620 * If there are no terms in the condition, 'term_list' will be NULL.
622 * @param py_dict A Python dict containing terms. Must not be NULL.
623 * @param term_list Pointer to a GSList which will be set to the newly
624 * created list of terms. Must not be NULL.
626 * @return SRD_OK upon success, a negative error code otherwise.
628 static int create_term_list(PyObject *py_dict, GSList **term_list)
631 PyObject *py_key, *py_value;
632 struct srd_term *term;
633 uint64_t num_samples_to_skip;
635 PyGILState_STATE gstate;
637 if (!py_dict || !term_list)
640 /* "Create" an empty GSList of terms. */
643 gstate = PyGILState_Ensure();
645 /* Iterate over all items in the current dict. */
646 while (PyDict_Next(py_dict, &pos, &py_key, &py_value)) {
647 /* Check whether the current key is a string or a number. */
648 if (PyLong_Check(py_key)) {
649 /* The key is a number. */
650 /* TODO: Check if the number is a valid channel. */
651 /* Get the value string. */
652 if ((py_pydictitem_as_str(py_dict, py_key, &term_str)) != SRD_OK) {
653 srd_err("Failed to get the value.");
656 term = g_malloc(sizeof(struct srd_term));
657 term->type = get_term_type(term_str);
658 term->channel = PyLong_AsLong(py_key);
660 } else if (PyUnicode_Check(py_key)) {
661 /* The key is a string. */
662 /* TODO: Check if it's "skip". */
663 if ((py_pydictitem_as_long(py_dict, py_key, &num_samples_to_skip)) != SRD_OK) {
664 srd_err("Failed to get number of samples to skip.");
667 term = g_malloc(sizeof(struct srd_term));
668 term->type = SRD_TERM_SKIP;
669 term->num_samples_to_skip = num_samples_to_skip;
670 term->num_samples_already_skipped = 0;
672 srd_err("Term key is neither a string nor a number.");
676 /* Add the term to the list of terms. */
677 *term_list = g_slist_append(*term_list, term);
680 PyGILState_Release(gstate);
685 PyGILState_Release(gstate);
691 * Replace the current condition list with the new one.
693 * @param self TODO. Must not be NULL.
694 * @param args TODO. Must not be NULL.
696 * @retval SRD_OK The new condition list was set successfully.
697 * @retval SRD_ERR There was an error setting the new condition list.
698 * The contents of di->condition_list are undefined.
701 static int set_new_condition_list(PyObject *self, PyObject *args)
703 struct srd_decoder_inst *di;
705 PyObject *py_conditionlist, *py_conds, *py_dict;
706 int i, num_conditions, ret;
707 PyGILState_STATE gstate;
712 gstate = PyGILState_Ensure();
714 /* Get the decoder instance. */
715 if (!(di = srd_inst_find_by_obj(NULL, self))) {
716 PyErr_SetString(PyExc_Exception, "decoder instance not found");
721 * Return an error condition from .wait() when termination is
722 * requested, such that decode() will terminate.
724 if (di->want_wait_terminate) {
725 srd_dbg("%s: %s: Skip (want_term).", di->inst_id, __func__);
730 * Parse the argument of self.wait() into 'py_conds', and check
731 * the data type. The argument is optional, None is assumed in
732 * its absence. None or an empty dict or an empty list mean that
733 * there is no condition, and the next available sample shall
734 * get returned to the caller.
737 if (!PyArg_ParseTuple(args, "|O", &py_conds)) {
738 /* Let Python raise this exception. */
741 if (py_conds == Py_None) {
742 /* 'py_conds' is None. */
744 } else if (PyList_Check(py_conds)) {
745 /* 'py_conds' is a list. */
746 py_conditionlist = py_conds;
747 num_conditions = PyList_Size(py_conditionlist);
748 if (num_conditions == 0)
749 goto ret_9999; /* The PD invoked self.wait([]). */
750 Py_IncRef(py_conditionlist);
751 } else if (PyDict_Check(py_conds)) {
752 /* 'py_conds' is a dict. */
753 if (PyDict_Size(py_conds) == 0)
754 goto ret_9999; /* The PD invoked self.wait({}). */
755 /* Make a list and put the dict in there for convenience. */
756 py_conditionlist = PyList_New(1);
758 PyList_SetItem(py_conditionlist, 0, py_conds);
761 srd_err("Condition list is neither a list nor a dict.");
765 /* Free the old condition list. */
766 condition_list_free(di);
770 /* Iterate over the conditions, set di->condition_list accordingly. */
771 for (i = 0; i < num_conditions; i++) {
772 /* Get a condition (dict) from the condition list. */
773 py_dict = PyList_GetItem(py_conditionlist, i);
774 if (!PyDict_Check(py_dict)) {
775 srd_err("Condition is not a dict.");
780 /* Create the list of terms in this condition. */
781 if ((ret = create_term_list(py_dict, &term_list)) < 0)
784 /* Add the new condition to the PD instance's condition list. */
785 di->condition_list = g_slist_append(di->condition_list, term_list);
788 Py_DecRef(py_conditionlist);
790 PyGILState_Release(gstate);
795 PyGILState_Release(gstate);
800 PyGILState_Release(gstate);
806 * Create a SKIP condition list for condition-less .wait() calls.
808 * @param di Decoder instance.
809 * @param count Number of samples to skip.
811 * @retval SRD_OK The new condition list was set successfully.
812 * @retval SRD_ERR There was an error setting the new condition list.
813 * The contents of di->condition_list are undefined.
815 * This routine is a reduced and specialized version of the @ref
816 * set_new_condition_list() and @ref create_term_list() routines which
817 * gets invoked when .wait() was called without specifications for
818 * conditions. This minor duplication of the SKIP term list creation
819 * simplifies the logic and avoids the creation of expensive Python
820 * objects with "constant" values which the caller did not pass in the
821 * first place. It results in maximum sharing of match handling code
824 static int set_skip_condition(struct srd_decoder_inst *di, uint64_t count)
826 struct srd_term *term;
829 condition_list_free(di);
830 term = g_malloc(sizeof(*term));
831 term->type = SRD_TERM_SKIP;
832 term->num_samples_to_skip = count;
833 term->num_samples_already_skipped = 0;
834 term_list = g_slist_append(NULL, term);
835 di->condition_list = g_slist_append(di->condition_list, term_list);
840 static PyObject *Decoder_wait(PyObject *self, PyObject *args)
845 gboolean found_match;
846 struct srd_decoder_inst *di;
847 PyObject *py_pinvalues, *py_matched;
848 PyGILState_STATE gstate;
853 gstate = PyGILState_Ensure();
855 if (!(di = srd_inst_find_by_obj(NULL, self))) {
856 PyErr_SetString(PyExc_Exception, "decoder instance not found");
857 PyGILState_Release(gstate);
861 ret = set_new_condition_list(self, args);
863 srd_dbg("%s: %s: Aborting wait().", di->inst_id, __func__);
868 * Empty condition list, automatic match. Arrange for the
869 * execution of regular match handling code paths such that
870 * the next available sample is returned to the caller.
871 * Make sure to skip one sample when "anywhere within the
872 * stream", yet make sure to not skip sample number 0.
874 if (di->abs_cur_samplenum)
876 else if (!di->condition_list)
880 ret = set_skip_condition(di, skip_count);
882 srd_dbg("%s: %s: Cannot setup condition-less wait().",
883 di->inst_id, __func__);
890 Py_BEGIN_ALLOW_THREADS
892 /* Wait for new samples to process, or termination request. */
893 g_mutex_lock(&di->data_mutex);
894 while (!di->got_new_samples && !di->want_wait_terminate)
895 g_cond_wait(&di->got_new_samples_cond, &di->data_mutex);
898 * Check whether any of the current condition(s) match.
899 * Arrange for termination requests to take a code path which
900 * won't find new samples to process, pretends to have processed
901 * previously stored samples, and returns to the main thread,
902 * while the termination request still gets signalled.
906 /* Ignore return value for now, should never be negative. */
907 (void)process_samples_until_condition_match(di, &found_match);
911 /* If there's a match, set self.samplenum etc. and return. */
913 /* Set self.samplenum to the (absolute) sample number that matched. */
914 PyObject_SetAttrString(di->py_inst, "samplenum",
915 PyLong_FromLong(di->abs_cur_samplenum));
917 if (di->match_array && di->match_array->len > 0) {
918 py_matched = PyTuple_New(di->match_array->len);
919 for (i = 0; i < di->match_array->len; i++)
920 PyTuple_SetItem(py_matched, i, PyBool_FromLong(di->match_array->data[i]));
921 PyObject_SetAttrString(di->py_inst, "matched", py_matched);
922 match_array_free(di);
924 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
927 py_pinvalues = get_current_pinvalues(di);
929 g_mutex_unlock(&di->data_mutex);
931 PyGILState_Release(gstate);
936 /* No match, reset state for the next chunk. */
937 di->got_new_samples = FALSE;
938 di->handled_all_samples = TRUE;
939 di->abs_start_samplenum = 0;
940 di->abs_end_samplenum = 0;
944 /* Signal the main thread that we handled all samples. */
945 g_cond_signal(&di->handled_all_samples_cond);
948 * When termination of wait() and decode() was requested,
949 * then exit the loop after releasing the mutex.
951 if (di->want_wait_terminate) {
952 srd_dbg("%s: %s: Will return from wait().",
953 di->inst_id, __func__);
954 g_mutex_unlock(&di->data_mutex);
958 g_mutex_unlock(&di->data_mutex);
961 PyGILState_Release(gstate);
966 PyGILState_Release(gstate);
972 * Return whether the specified channel was supplied to the decoder.
974 * @param self TODO. Must not be NULL.
975 * @param args TODO. Must not be NULL.
977 * @retval Py_True The channel has been supplied by the frontend.
978 * @retval Py_False The channel has been supplied by the frontend.
979 * @retval NULL An error occurred.
981 static PyObject *Decoder_has_channel(PyObject *self, PyObject *args)
984 struct srd_decoder_inst *di;
985 PyGILState_STATE gstate;
990 gstate = PyGILState_Ensure();
992 if (!(di = srd_inst_find_by_obj(NULL, self))) {
993 PyErr_SetString(PyExc_Exception, "decoder instance not found");
998 * Get the integer argument of self.has_channel(). Check for
999 * the range of supported PD input channel numbers.
1001 if (!PyArg_ParseTuple(args, "i", &idx)) {
1002 /* Let Python raise this exception. */
1006 count = g_slist_length(di->decoder->channels) +
1007 g_slist_length(di->decoder->opt_channels);
1008 if (idx < 0 || idx >= count) {
1009 srd_err("Invalid index %d, PD channel count %d.", idx, count);
1010 PyErr_SetString(PyExc_IndexError, "invalid channel index");
1014 PyGILState_Release(gstate);
1016 return (di->dec_channelmap[idx] == -1) ? Py_False : Py_True;
1019 PyGILState_Release(gstate);
1024 static PyMethodDef Decoder_methods[] = {
1025 { "put", Decoder_put, METH_VARARGS,
1026 "Accepts a dictionary with the following keys: startsample, endsample, data" },
1027 { "register", (PyCFunction)Decoder_register, METH_VARARGS|METH_KEYWORDS,
1028 "Register a new output stream" },
1029 { "wait", Decoder_wait, METH_VARARGS,
1030 "Wait for one or more conditions to occur" },
1031 { "has_channel", Decoder_has_channel, METH_VARARGS,
1032 "Report whether a channel was supplied" },
1033 {NULL, NULL, 0, NULL}
1037 * Create the sigrokdecode.Decoder type.
1039 * @return The new type object.
1043 SRD_PRIV PyObject *srd_Decoder_type_new(void)
1046 PyType_Slot slots[] = {
1047 { Py_tp_doc, "sigrok Decoder base class" },
1048 { Py_tp_methods, Decoder_methods },
1049 { Py_tp_new, (void *)&PyType_GenericNew },
1053 PyGILState_STATE gstate;
1055 gstate = PyGILState_Ensure();
1057 spec.name = "sigrokdecode.Decoder";
1058 spec.basicsize = sizeof(srd_Decoder);
1060 spec.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1063 py_obj = PyType_FromSpec(&spec);
1065 PyGILState_Release(gstate);