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"
29 /* This is only used for nicer srd_dbg() output.
31 static const char *output_type_name(unsigned int idx)
33 static const char names[][16] = {
40 return names[MIN(idx, G_N_ELEMENTS(names) - 1)];
43 static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
44 struct srd_proto_data *pdata)
47 struct srd_pd_output *pdo;
48 struct srd_proto_data_annotation *pda;
52 /* Should be a list of [annotation class, [string, ...]]. */
53 if (!PyList_Check(obj)) {
54 srd_err("Protocol decoder %s submitted an annotation that"
55 " is not a list", di->decoder->name);
56 return SRD_ERR_PYTHON;
59 /* Should have 2 elements. */
60 if (PyList_Size(obj) != 2) {
61 srd_err("Protocol decoder %s submitted annotation list with "
62 "%zd elements instead of 2", di->decoder->name,
64 return SRD_ERR_PYTHON;
68 * The first element should be an integer matching a previously
69 * registered annotation class.
71 py_tmp = PyList_GetItem(obj, 0);
72 if (!PyLong_Check(py_tmp)) {
73 srd_err("Protocol decoder %s submitted annotation list, but "
74 "first element was not an integer.", di->decoder->name);
75 return SRD_ERR_PYTHON;
77 ann_class = PyLong_AsLong(py_tmp);
78 if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_class))) {
79 srd_err("Protocol decoder %s submitted data to unregistered "
80 "annotation class %d.", di->decoder->name, ann_class);
81 return SRD_ERR_PYTHON;
84 /* Second element must be a list. */
85 py_tmp = PyList_GetItem(obj, 1);
86 if (!PyList_Check(py_tmp)) {
87 srd_err("Protocol decoder %s submitted annotation list, but "
88 "second element was not a list.", di->decoder->name);
89 return SRD_ERR_PYTHON;
91 if (py_strseq_to_char(py_tmp, &ann_text) != SRD_OK) {
92 srd_err("Protocol decoder %s submitted annotation list, but "
93 "second element was malformed.", di->decoder->name);
94 return SRD_ERR_PYTHON;
97 pda = g_malloc(sizeof(struct srd_proto_data_annotation));
98 pda->ann_class = ann_class;
99 pda->ann_text = ann_text;
105 static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
106 struct srd_proto_data *pdata)
108 struct srd_proto_data_binary *pdb;
112 char *class_name, *buf;
114 /* Should be a list of [binary class, bytes]. */
115 if (!PyList_Check(obj)) {
116 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_BINARY.",
118 return SRD_ERR_PYTHON;
121 /* Should have 2 elements. */
122 if (PyList_Size(obj) != 2) {
123 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list "
124 "with %zd elements instead of 2", di->decoder->name,
126 return SRD_ERR_PYTHON;
129 /* The first element should be an integer. */
130 py_tmp = PyList_GetItem(obj, 0);
131 if (!PyLong_Check(py_tmp)) {
132 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
133 "but first element was not an integer.", di->decoder->name);
134 return SRD_ERR_PYTHON;
136 bin_class = PyLong_AsLong(py_tmp);
137 if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
138 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
139 "unregistered binary class %d.", di->decoder->name, bin_class);
140 return SRD_ERR_PYTHON;
143 /* Second element should be bytes. */
144 py_tmp = PyList_GetItem(obj, 1);
145 if (!PyBytes_Check(py_tmp)) {
146 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
147 "but second element was not bytes.", di->decoder->name);
148 return SRD_ERR_PYTHON;
151 /* Consider an empty set of bytes a bug. */
152 if (PyBytes_Size(py_tmp) == 0) {
153 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
154 "with empty data set.", di->decoder->name);
155 return SRD_ERR_PYTHON;
158 pdb = g_malloc(sizeof(struct srd_proto_data_binary));
159 if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
160 return SRD_ERR_PYTHON;
161 pdb->bin_class = bin_class;
163 if (!(pdb->data = g_try_malloc(pdb->size)))
164 return SRD_ERR_MALLOC;
165 memcpy((void *)pdb->data, (const void *)buf, pdb->size);
171 static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
176 if (pdata->pdo->meta_type == G_VARIANT_TYPE_INT64) {
177 if (!PyLong_Check(obj)) {
178 PyErr_Format(PyExc_TypeError, "This output was registered "
179 "as 'int', but something else was passed.");
180 return SRD_ERR_PYTHON;
182 intvalue = PyLong_AsLongLong(obj);
183 if (PyErr_Occurred())
184 return SRD_ERR_PYTHON;
185 pdata->data = g_variant_new_int64(intvalue);
186 } else if (pdata->pdo->meta_type == G_VARIANT_TYPE_DOUBLE) {
187 if (!PyFloat_Check(obj)) {
188 PyErr_Format(PyExc_TypeError, "This output was registered "
189 "as 'float', but something else was passed.");
190 return SRD_ERR_PYTHON;
192 dvalue = PyFloat_AsDouble(obj);
193 if (PyErr_Occurred())
194 return SRD_ERR_PYTHON;
195 pdata->data = g_variant_new_double(dvalue);
201 static PyObject *Decoder_put(PyObject *self, PyObject *args)
204 PyObject *py_data, *py_res;
205 struct srd_decoder_inst *di, *next_di;
206 struct srd_pd_output *pdo;
207 struct srd_proto_data *pdata;
208 uint64_t start_sample, end_sample;
210 struct srd_pd_callback *cb;
212 if (!(di = srd_inst_find_by_obj(NULL, self))) {
213 /* Shouldn't happen. */
214 srd_dbg("put(): self instance not found.");
218 if (!PyArg_ParseTuple(args, "KKiO", &start_sample, &end_sample,
219 &output_id, &py_data)) {
221 * This throws an exception, but by returning NULL here we let
222 * Python raise it. This results in a much better trace in
223 * controller.c on the decode() method call.
228 if (!(l = g_slist_nth(di->pd_output, output_id))) {
229 srd_err("Protocol decoder %s submitted invalid output ID %d.",
230 di->decoder->name, output_id);
235 srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on oid %d.",
236 di->inst_id, start_sample, end_sample,
237 output_type_name(pdo->output_type), output_id);
239 pdata = g_malloc0(sizeof(struct srd_proto_data));
240 pdata->start_sample = start_sample;
241 pdata->end_sample = end_sample;
244 switch (pdo->output_type) {
246 /* Annotations are only fed to callbacks. */
247 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
248 /* Convert from PyDict to srd_proto_data_annotation. */
249 if (convert_annotation(di, py_data, pdata) != SRD_OK) {
250 /* An error was already logged. */
253 cb->cb(pdata, cb->cb_data);
256 case SRD_OUTPUT_PYTHON:
257 for (l = di->next_di; l; l = l->next) {
259 srd_spew("Sending %" PRIu64 "-%" PRIu64 " to instance %s",
260 start_sample, end_sample, next_di->inst_id);
261 if (!(py_res = PyObject_CallMethod(
262 next_di->py_inst, "decode", "KKO", start_sample,
263 end_sample, py_data))) {
264 srd_exception_catch("Calling %s decode() failed",
269 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
270 /* Frontends aren't really supposed to get Python
271 * callbacks, but it's useful for testing. */
272 pdata->data = py_data;
273 cb->cb(pdata, cb->cb_data);
276 case SRD_OUTPUT_BINARY:
277 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
278 /* Convert from PyDict to srd_proto_data_binary. */
279 if (convert_binary(di, py_data, pdata) != SRD_OK) {
280 /* An error was already logged. */
283 cb->cb(pdata, cb->cb_data);
286 case SRD_OUTPUT_META:
287 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
288 /* Annotations need converting from PyObject. */
289 if (convert_meta(pdata, py_data) != SRD_OK) {
290 /* An exception was already set up. */
293 cb->cb(pdata, cb->cb_data);
297 srd_err("Protocol decoder %s submitted invalid output type %d.",
298 di->decoder->name, pdo->output_type);
307 static PyObject *Decoder_register(PyObject *self, PyObject *args,
310 struct srd_decoder_inst *di;
311 struct srd_pd_output *pdo;
312 PyObject *py_new_output_id;
313 PyTypeObject *meta_type_py;
314 const GVariantType *meta_type_gv;
316 char *proto_id, *meta_name, *meta_descr;
317 char *keywords[] = {"output_type", "proto_id", "meta", NULL};
321 meta_name = meta_descr = NULL;
323 if (!(di = srd_inst_find_by_obj(NULL, self))) {
324 PyErr_SetString(PyExc_Exception, "decoder instance not found");
328 /* Default to instance id, which defaults to class id. */
329 proto_id = di->inst_id;
330 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
331 &output_type, &proto_id,
332 &meta_type_py, &meta_name, &meta_descr)) {
333 /* Let Python raise this exception. */
337 /* Check if the meta value's type is supported. */
338 if (output_type == SRD_OUTPUT_META) {
339 if (meta_type_py == &PyLong_Type)
340 meta_type_gv = G_VARIANT_TYPE_INT64;
341 else if (meta_type_py == &PyFloat_Type)
342 meta_type_gv = G_VARIANT_TYPE_DOUBLE;
344 PyErr_Format(PyExc_TypeError, "Unsupported type.");
349 srd_dbg("Instance %s creating new output type %d for %s.",
350 di->inst_id, output_type, proto_id);
352 pdo = g_malloc(sizeof(struct srd_pd_output));
354 /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
355 pdo->pdo_id = g_slist_length(di->pd_output);
356 pdo->output_type = output_type;
358 pdo->proto_id = g_strdup(proto_id);
360 if (output_type == SRD_OUTPUT_META) {
361 pdo->meta_type = meta_type_gv;
362 pdo->meta_name = g_strdup(meta_name);
363 pdo->meta_descr = g_strdup(meta_descr);
366 di->pd_output = g_slist_append(di->pd_output, pdo);
367 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
369 return py_new_output_id;
372 static int get_term_type(const char *v)
376 return SRD_TERM_HIGH;
380 return SRD_TERM_RISING_EDGE;
382 return SRD_TERM_FALLING_EDGE;
384 return SRD_TERM_EITHER_EDGE;
386 return SRD_TERM_NO_EDGE;
393 * Get the pin values at the current sample number.
395 * @param di The decoder instance to use. Must not be NULL.
396 * The number of channels must be >= 1.
398 * @return A newly allocated PyTuple containing the pin values at the
399 * current sample number.
401 static PyObject *get_current_pinvalues(const struct srd_decoder_inst *di)
405 const uint8_t *sample_pos;
406 int byte_offset, bit_offset;
407 PyObject *py_pinvalues;
410 srd_err("Invalid decoder instance.");
414 py_pinvalues = PyTuple_New(di->dec_num_channels);
416 for (i = 0; i < di->dec_num_channels; i++) {
417 /* A channelmap value of -1 means "unused optional channel". */
418 if (di->dec_channelmap[i] == -1) {
419 /* Value of unused channel is 0xff, instead of 0 or 1. */
420 PyTuple_SetItem(py_pinvalues, i, PyLong_FromLong(0xff));
422 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
423 byte_offset = di->dec_channelmap[i] / 8;
424 bit_offset = di->dec_channelmap[i] % 8;
425 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
426 PyTuple_SetItem(py_pinvalues, i, PyLong_FromLong(sample));
434 * Create a list of terms in the specified condition.
436 * If there are no terms in the condition, 'term_list' will be NULL.
438 * @param py_dict A Python dict containing terms. Must not be NULL.
439 * @param term_list Pointer to a GSList which will be set to the newly
440 * created list of terms. Must not be NULL.
442 * @return SRD_OK upon success, a negative error code otherwise.
444 static int create_term_list(PyObject *py_dict, GSList **term_list)
447 PyObject *py_key, *py_value;
448 struct srd_term *term;
449 uint64_t num_samples_to_skip;
452 if (!py_dict || !term_list)
455 /* "Create" an empty GSList of terms. */
458 /* Iterate over all items in the current dict. */
459 while (PyDict_Next(py_dict, &pos, &py_key, &py_value)) {
460 /* Check whether the current key is a string or a number. */
461 if (PyLong_Check(py_key)) {
462 /* The key is a number. */
463 /* TODO: Check if the number is a valid channel. */
464 /* Get the value string. */
465 if ((py_pydictitem_as_str(py_dict, py_key, &term_str)) != SRD_OK) {
466 srd_err("Failed to get the value.");
469 term = g_malloc0(sizeof(struct srd_term));
470 term->type = get_term_type(term_str);
471 term->channel = PyLong_AsLong(py_key);
473 } else if (PyUnicode_Check(py_key)) {
474 /* The key is a string. */
475 /* TODO: Check if it's "skip". */
476 if ((py_pydictitem_as_long(py_dict, py_key, &num_samples_to_skip)) != SRD_OK) {
477 srd_err("Failed to get number of samples to skip.");
480 term = g_malloc0(sizeof(struct srd_term));
481 term->type = SRD_TERM_SKIP;
482 term->num_samples_to_skip = num_samples_to_skip;
483 term->num_samples_already_skipped = 0;
485 srd_err("Term key is neither a string nor a number.");
489 /* Add the term to the list of terms. */
490 *term_list = g_slist_append(*term_list, term);
497 * Replace the current condition list with the new one.
499 * @param self TODO. Must not be NULL.
500 * @param args TODO. Must not be NULL.
502 * @retval SRD_OK The new condition list was set successfully.
503 * @retval SRD_ERR There was an error setting the new condition list.
504 * The contents of di->condition_list are undefined.
507 static int set_new_condition_list(PyObject *self, PyObject *args)
509 struct srd_decoder_inst *di;
511 PyObject *py_conditionlist, *py_conds, *py_dict;
512 int i, num_conditions, ret;
517 /* Get the decoder instance. */
518 if (!(di = srd_inst_find_by_obj(NULL, self))) {
519 PyErr_SetString(PyExc_Exception, "decoder instance not found");
524 * Return an error condition from .wait() when termination is
525 * requested, such that decode() will terminate.
527 if (di->want_wait_terminate) {
528 srd_dbg("%s: %s: Skip (want_term).", di->inst_id, __func__);
532 /* Parse the argument of self.wait() into 'py_conds'. */
533 if (!PyArg_ParseTuple(args, "O", &py_conds)) {
534 /* Let Python raise this exception. */
538 /* Check whether 'py_conds' is a dict or a list. */
539 if (PyList_Check(py_conds)) {
540 /* 'py_conds' is a list. */
541 py_conditionlist = py_conds;
542 num_conditions = PyList_Size(py_conditionlist);
543 if (num_conditions == 0)
544 return 9999; /* The PD invoked self.wait([]). */
545 Py_IncRef(py_conditionlist);
546 } else if (PyDict_Check(py_conds)) {
547 /* 'py_conds' is a dict. */
548 if (PyDict_Size(py_conds) == 0)
549 return 9999; /* The PD invoked self.wait({}). */
550 /* Make a list and put the dict in there for convenience. */
551 py_conditionlist = PyList_New(1);
553 PyList_SetItem(py_conditionlist, 0, py_conds);
556 srd_err("Condition list is neither a list nor a dict.");
560 /* Free the old condition list. */
561 condition_list_free(di);
565 /* Iterate over the conditions, set di->condition_list accordingly. */
566 for (i = 0; i < num_conditions; i++) {
567 /* Get a condition (dict) from the condition list. */
568 py_dict = PyList_GetItem(py_conditionlist, i);
569 if (!PyDict_Check(py_dict)) {
570 srd_err("Condition is not a dict.");
575 /* Create the list of terms in this condition. */
576 if ((ret = create_term_list(py_dict, &term_list)) < 0)
579 /* Add the new condition to the PD instance's condition list. */
580 di->condition_list = g_slist_append(di->condition_list, term_list);
583 Py_DecRef(py_conditionlist);
588 static PyObject *Decoder_wait(PyObject *self, PyObject *args)
592 gboolean found_match;
593 struct srd_decoder_inst *di;
594 PyObject *py_pinvalues, *py_matched;
599 if (!(di = srd_inst_find_by_obj(NULL, self))) {
600 PyErr_SetString(PyExc_Exception, "decoder instance not found");
604 ret = set_new_condition_list(self, args);
606 srd_dbg("%s: %s: Aborting wait().", di->inst_id, __func__);
610 /* Empty condition list, automatic match. */
611 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
612 /* Leave self.samplenum unchanged (== di->abs_cur_samplenum). */
613 return get_current_pinvalues(di);
617 /* Wait for new samples to process, or termination request. */
618 g_mutex_lock(&di->data_mutex);
619 while (!di->got_new_samples && !di->want_wait_terminate)
620 g_cond_wait(&di->got_new_samples_cond, &di->data_mutex);
623 * Check whether any of the current condition(s) match.
624 * Arrange for termination requests to take a code path which
625 * won't find new samples to process, pretends to have processed
626 * previously stored samples, and returns to the main thread,
627 * while the termination request still gets signalled.
630 ret = process_samples_until_condition_match(di, &found_match);
632 /* If there's a match, set self.samplenum etc. and return. */
634 /* Set self.samplenum to the (absolute) sample number that matched. */
635 PyObject_SetAttrString(di->py_inst, "samplenum",
636 PyLong_FromLong(di->abs_cur_samplenum));
638 if (di->match_array && di->match_array->len > 0) {
639 py_matched = PyTuple_New(di->match_array->len);
640 for (i = 0; i < di->match_array->len; i++)
641 PyTuple_SetItem(py_matched, i, PyBool_FromLong(di->match_array->data[i]));
642 PyObject_SetAttrString(di->py_inst, "matched", py_matched);
643 match_array_free(di);
645 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
648 py_pinvalues = get_current_pinvalues(di);
650 g_mutex_unlock(&di->data_mutex);
655 /* No match, reset state for the next chunk. */
656 di->got_new_samples = FALSE;
657 di->handled_all_samples = TRUE;
658 di->abs_start_samplenum = 0;
659 di->abs_end_samplenum = 0;
663 /* Signal the main thread that we handled all samples. */
664 g_cond_signal(&di->handled_all_samples_cond);
667 * When termination of wait() and decode() was requested,
668 * then exit the loop after releasing the mutex.
670 if (di->want_wait_terminate) {
671 srd_dbg("%s: %s: Will return from wait().",
672 di->inst_id, __func__);
673 g_mutex_unlock(&di->data_mutex);
677 g_mutex_unlock(&di->data_mutex);
684 * Return whether the specified channel was supplied to the decoder.
686 * @param self TODO. Must not be NULL.
687 * @param args TODO. Must not be NULL.
689 * @retval Py_True The channel has been supplied by the frontend.
690 * @retval Py_False The channel has been supplied by the frontend.
691 * @retval NULL An error occurred.
693 static PyObject *Decoder_has_channel(PyObject *self, PyObject *args)
696 struct srd_decoder_inst *di;
697 PyObject *py_channel;
702 if (!(di = srd_inst_find_by_obj(NULL, self))) {
703 PyErr_SetString(PyExc_Exception, "decoder instance not found");
707 /* Parse the argument of self.has_channel() into 'py_channel'. */
708 if (!PyArg_ParseTuple(args, "O", &py_channel)) {
709 /* Let Python raise this exception. */
713 if (!PyLong_Check(py_channel)) {
714 PyErr_SetString(PyExc_Exception, "channel index not a number");
718 idx = PyLong_AsLong(py_channel);
719 max_idx = g_slist_length(di->decoder->channels)
720 + g_slist_length(di->decoder->opt_channels) - 1;
722 if (idx < 0 || idx > max_idx) {
723 srd_err("Invalid channel index %d/%d.", idx, max_idx);
724 PyErr_SetString(PyExc_Exception, "invalid channel");
728 return (di->dec_channelmap[idx] == -1) ? Py_False : Py_True;
731 static PyMethodDef Decoder_methods[] = {
732 {"put", Decoder_put, METH_VARARGS,
733 "Accepts a dictionary with the following keys: startsample, endsample, data"},
734 {"register", (PyCFunction)Decoder_register, METH_VARARGS|METH_KEYWORDS,
735 "Register a new output stream"},
736 {"wait", Decoder_wait, METH_VARARGS,
737 "Wait for one or more conditions to occur"},
738 {"has_channel", Decoder_has_channel, METH_VARARGS,
739 "Report whether a channel was supplied"},
740 {NULL, NULL, 0, NULL}
744 * Create the sigrokdecode.Decoder type.
746 * @return The new type object.
750 SRD_PRIV PyObject *srd_Decoder_type_new(void)
753 PyType_Slot slots[] = {
754 { Py_tp_doc, "sigrok Decoder base class" },
755 { Py_tp_methods, Decoder_methods },
756 { Py_tp_new, (void *)&PyType_GenericNew },
759 spec.name = "sigrokdecode.Decoder";
760 spec.basicsize = sizeof(srd_Decoder);
762 spec.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
765 return PyType_FromSpec(&spec);