2 * This file is part of the libsigrokdecode project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode-internal.h"
31 extern GSList *sessions;
34 extern SRD_PRIV PyTypeObject srd_logic_type;
41 * Decoder instance handling.
45 * @defgroup grp_instances Decoder instances
47 * Decoder instance handling.
53 * Set one or more options in a decoder instance.
55 * Handled options are removed from the hash.
57 * @param di Decoder instance.
58 * @param options A GHashTable of options to set.
60 * @return SRD_OK upon success, a (negative) error code otherwise.
64 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
67 PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
68 PyObject *py_optlist, *py_classval;
71 unsigned long long int val_ull;
73 int num_optkeys, ret, size, i;
78 srd_err("Invalid decoder instance.");
83 srd_err("Invalid options GHashTable.");
87 if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
88 /* Decoder has no options. */
89 if (g_hash_table_size(options) == 0) {
90 /* No options provided. */
93 srd_err("Protocol decoder has no options.");
101 py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
102 py_optlist = py_classval = NULL;
103 py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");
105 /* All of these are synthesized objects, so they're good. */
106 py_dec_optkeys = PyDict_Keys(py_dec_options);
107 num_optkeys = PyList_Size(py_dec_optkeys);
110 * The 'options' dictionary is a class variable, but we need to
111 * change it. Changing it directly will affect the entire class,
112 * so we need to create a new object for it, and populate that
115 if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
117 Py_DECREF(py_di_options);
118 py_di_options = PyDict_New();
119 PyObject_SetAttrString(di->py_inst, "options", py_di_options);
120 for (i = 0; i < num_optkeys; i++) {
121 /* Get the default class value for this option. */
122 py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
123 if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
125 if (!(py_classval = PyList_GetItem(py_optlist, 1)))
127 if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
128 srd_err("Options of type %s are not yet supported.",
129 Py_TYPE(py_classval)->tp_name);
133 if ((value = g_hash_table_lookup(options, key))) {
134 dbg = g_variant_print(value, TRUE);
135 srd_dbg("got option '%s' = %s", key, dbg);
137 /* An override for this option was provided. */
138 if (PyUnicode_Check(py_classval)) {
139 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
140 srd_err("Option '%s' requires a string value.", key);
143 val_str = g_variant_get_string(value, NULL);
144 if (!(py_optval = PyUnicode_FromString(val_str))) {
145 /* Some UTF-8 encoding error. */
147 srd_err("Option '%s' requires a UTF-8 string value.", key);
150 } else if (PyLong_Check(py_classval)) {
151 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
152 srd_err("Option '%s' requires an integer value.", key);
155 val_int = g_variant_get_int64(value);
156 if (!(py_optval = PyLong_FromLong(val_int))) {
157 /* ValueError Exception */
159 srd_err("Option '%s' has invalid integer value.", key);
163 g_hash_table_remove(options, key);
165 /* Use the class default for this option. */
166 if (PyUnicode_Check(py_classval)) {
167 /* Make a brand new copy of the string. */
168 py_ustr = PyUnicode_AS_UNICODE(py_classval);
169 size = PyUnicode_GET_SIZE(py_classval);
170 py_optval = PyUnicode_FromUnicode(py_ustr, size);
171 } else if (PyLong_Check(py_classval)) {
172 /* Make a brand new copy of the integer. */
173 val_ull = PyLong_AsUnsignedLongLong(py_classval);
174 if (val_ull == (unsigned long long)-1) {
175 /* OverFlowError exception */
177 srd_err("Invalid integer value for %s: "
178 "expected integer.", key);
181 if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
187 * If we got here, py_optval holds a known good new reference
188 * to the instance option to set.
190 if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
199 Py_XDECREF(py_di_options);
200 Py_XDECREF(py_dec_optkeys);
201 Py_XDECREF(py_dec_options);
203 if (PyErr_Occurred()) {
204 srd_exception_catch("Stray exception in srd_inst_option_set().");
205 ret = SRD_ERR_PYTHON;
211 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_probe_set_all() */
212 static gint compare_probe_id(const struct srd_probe *a, const char *probe_id)
214 return strcmp(a->id, probe_id);
218 * Set all probes in a decoder instance.
220 * This function sets _all_ probes for the specified decoder instance, i.e.,
221 * it overwrites any probes that were already defined (if any).
223 * @param di Decoder instance.
224 * @param new_probes A GHashTable of probes to set. Key is probe name, value is
225 * the probe number. Samples passed to this instance will be
226 * arranged in this order.
228 * @return SRD_OK upon success, a (negative) error code otherwise.
232 SRD_API int srd_inst_probe_set_all(struct srd_decoder_inst *di,
233 GHashTable *new_probes)
239 int *new_probemap, new_probenum, num_required_probes, num_probes, i;
242 srd_dbg("set probes called for instance %s with list of %d probes",
243 di->inst_id, g_hash_table_size(new_probes));
245 if (g_hash_table_size(new_probes) == 0)
246 /* No probes provided. */
249 if (di->dec_num_probes == 0) {
250 /* Decoder has no probes. */
251 srd_err("Protocol decoder %s has no probes to define.",
258 if (!(new_probemap = g_try_malloc(sizeof(int) * di->dec_num_probes))) {
259 srd_err("Failed to g_malloc() new probe map.");
260 return SRD_ERR_MALLOC;
264 * For now, map all indexes to probe -1 (can be overridden later).
265 * This -1 is interpreted as an unspecified probe later.
267 for (i = 0; i < di->dec_num_probes; i++)
268 new_probemap[i] = -1;
271 for (l = g_hash_table_get_keys(new_probes); l; l = l->next) {
273 probe_val = g_hash_table_lookup(new_probes, probe_id);
274 if (!g_variant_is_of_type(probe_val, G_VARIANT_TYPE_INT32)) {
275 /* Probe name was specified without a value. */
276 srd_err("No probe number was specified for %s.",
278 g_free(new_probemap);
281 new_probenum = g_variant_get_int32(probe_val);
282 if (!(sl = g_slist_find_custom(di->decoder->probes, probe_id,
283 (GCompareFunc)compare_probe_id))) {
284 /* Fall back on optional probes. */
285 if (!(sl = g_slist_find_custom(di->decoder->opt_probes,
286 probe_id, (GCompareFunc) compare_probe_id))) {
287 srd_err("Protocol decoder %s has no probe "
288 "'%s'.", di->decoder->name, probe_id);
289 g_free(new_probemap);
294 new_probemap[p->order] = new_probenum;
295 srd_dbg("Setting probe mapping: %s (index %d) = probe %d.",
296 p->id, p->order, new_probenum);
299 di->data_unitsize = (num_probes + 7) / 8;
301 srd_dbg("Final probe map:");
302 num_required_probes = g_slist_length(di->decoder->probes);
303 for (i = 0; i < di->dec_num_probes; i++) {
304 srd_dbg(" - index %d = probe %d (%s)", i, new_probemap[i],
305 (i < num_required_probes) ? "required" : "optional");
308 /* Report an error if not all required probes were specified. */
309 for (i = 0; i < num_required_probes; i++) {
310 if (new_probemap[i] != -1)
312 p = g_slist_nth(di->decoder->probes, i)->data;
313 srd_err("Required probe '%s' (index %d) was not specified.",
318 g_free(di->dec_probemap);
319 di->dec_probemap = new_probemap;
325 * Create a new protocol decoder instance.
327 * @param sess The session holding the protocol decoder instance.
328 * @param decoder_id Decoder 'id' field.
329 * @param options GHashtable of options which override the defaults set in
330 * the decoder class. May be NULL.
332 * @return Pointer to a newly allocated struct srd_decoder_inst, or
333 * NULL in case of failure.
337 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
338 const char *decoder_id, GHashTable *options)
341 struct srd_decoder *dec;
342 struct srd_decoder_inst *di;
345 srd_dbg("Creating new %s instance.", decoder_id);
347 if (session_is_valid(sess) != SRD_OK) {
348 srd_err("Invalid session.");
352 if (!(dec = srd_decoder_get_by_id(decoder_id))) {
353 srd_err("Protocol decoder %s not found.", decoder_id);
357 if (!(di = g_try_malloc0(sizeof(struct srd_decoder_inst)))) {
358 srd_err("Failed to g_malloc() instance.");
365 inst_id = g_hash_table_lookup(options, "id");
366 di->inst_id = g_strdup(inst_id ? inst_id : decoder_id);
367 g_hash_table_remove(options, "id");
369 di->inst_id = g_strdup(decoder_id);
372 * Prepare a default probe map, where samples come in the
373 * order in which the decoder class defined them.
375 di->dec_num_probes = g_slist_length(di->decoder->probes) +
376 g_slist_length(di->decoder->opt_probes);
377 if (di->dec_num_probes) {
378 if (!(di->dec_probemap =
379 g_try_malloc(sizeof(int) * di->dec_num_probes))) {
380 srd_err("Failed to g_malloc() probe map.");
384 for (i = 0; i < di->dec_num_probes; i++)
385 di->dec_probemap[i] = i;
386 di->data_unitsize = (di->dec_num_probes + 7) / 8;
388 * Will be used to prepare a sample at every iteration
389 * of the instance's decode() method.
391 if (!(di->probe_samples = g_try_malloc(di->dec_num_probes))) {
392 srd_err("Failed to g_malloc() sample buffer.");
393 g_free(di->dec_probemap);
399 /* Create a new instance of this decoder class. */
400 if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
401 if (PyErr_Occurred())
402 srd_exception_catch("failed to create %s instance: ",
404 g_free(di->dec_probemap);
409 if (options && srd_inst_option_set(di, options) != SRD_OK) {
410 g_free(di->dec_probemap);
415 /* Instance takes input from a frontend by default. */
416 sess->di_list = g_slist_append(sess->di_list, di);
422 * Stack a decoder instance on top of another.
424 * @param sess The session holding the protocol decoder instances.
425 * @param di_bottom The instance on top of which di_top will be stacked.
426 * @param di_top The instance to go on top.
428 * @return SRD_OK upon success, a (negative) error code otherwise.
432 SRD_API int srd_inst_stack(struct srd_session *sess,
433 struct srd_decoder_inst *di_bottom,
434 struct srd_decoder_inst *di_top)
437 if (session_is_valid(sess) != SRD_OK) {
438 srd_err("Invalid session.");
442 if (!di_bottom || !di_top) {
443 srd_err("Invalid from/to instance pair.");
447 if (g_slist_find(sess->di_list, di_top)) {
448 /* Remove from the unstacked list. */
449 sess->di_list = g_slist_remove(sess->di_list, di_top);
452 /* Stack on top of source di. */
453 di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
455 srd_dbg("Stacked %s on top of %s.", di_top->inst_id, di_bottom->inst_id);
461 * Find a decoder instance by its instance ID.
463 * Only the bottom level of instances are searched -- instances already stacked
464 * on top of another one will not be found.
466 * @param sess The session holding the protocol decoder instance.
467 * @param inst_id The instance ID to be found.
469 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
473 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
477 struct srd_decoder_inst *tmp, *di;
479 if (session_is_valid(sess) != SRD_OK) {
480 srd_err("Invalid session.");
485 for (l = sess->di_list; l; l = l->next) {
487 if (!strcmp(tmp->inst_id, inst_id)) {
496 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
497 struct srd_session *sess, const GSList *stack,
501 struct srd_decoder_inst *tmp, *di;
503 if (session_is_valid(sess) != SRD_OK) {
504 srd_err("Invalid session.");
509 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
511 if (tmp->py_inst == obj)
513 else if (tmp->next_di)
514 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
521 * Find a decoder instance by its Python object.
523 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
524 * This will recurse to find the instance anywhere in the stack tree of all
527 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
528 * stack to search. To start searching at the bottom level of
529 * decoder instances, pass NULL.
530 * @param obj The Python class instantiation.
532 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
538 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
541 struct srd_decoder_inst *di;
542 struct srd_session *sess;
546 for (l = sessions; di == NULL && l != NULL; l = l->next) {
548 di = srd_sess_inst_find_by_obj(sess, stack, obj);
555 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
559 struct srd_decoder_inst *next_di;
562 srd_dbg("Calling start() method on protocol decoder instance %s.",
565 if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
566 srd_exception_catch("Protocol decoder instance %s: ",
568 return SRD_ERR_PYTHON;
572 /* Start all the PDs stacked on top of this one. */
573 for (l = di->next_di; l; l = l->next) {
575 if ((ret = srd_inst_start(next_di)) != SRD_OK)
583 * Run the specified decoder function.
585 * @param di The decoder instance to call. Must not be NULL.
586 * @param start_samplenum The starting sample number for the buffer's sample
587 * set, relative to the start of capture.
588 * @param end_samplenum The ending sample number for the buffer's sample
589 * set, relative to the start of capture.
590 * @param inbuf The buffer to decode. Must not be NULL.
591 * @param inbuflen Length of the buffer. Must be > 0.
593 * @return SRD_OK upon success, a (negative) error code otherwise.
599 SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
600 uint64_t start_samplenum, uint64_t end_samplenum,
601 const uint8_t *inbuf, uint64_t inbuflen)
606 srd_dbg("Calling decode() on instance %s with %" PRIu64 " bytes "
607 "starting at sample %" PRIu64 ".", di->inst_id, inbuflen,
610 /* Return an error upon unusable input. */
612 srd_dbg("empty decoder instance");
616 srd_dbg("NULL buffer pointer");
620 srd_dbg("empty buffer");
625 * Create new srd_logic object. Each iteration around the PD's loop
626 * will fill one sample into this object.
628 logic = PyObject_New(srd_logic, &srd_logic_type);
630 logic->di = (struct srd_decoder_inst *)di;
631 logic->start_samplenum = start_samplenum;
633 logic->inbuf = (uint8_t *)inbuf;
634 logic->inbuflen = inbuflen;
635 logic->sample = PyList_New(2);
636 Py_INCREF(logic->sample);
638 Py_IncRef(di->py_inst);
639 if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
640 "KKO", start_samplenum, end_samplenum, logic))) {
641 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
642 return SRD_ERR_PYTHON;
650 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
653 struct srd_pd_output *pdo;
655 srd_dbg("Freeing instance %s", di->inst_id);
657 Py_DecRef(di->py_inst);
659 g_free(di->dec_probemap);
660 g_slist_free(di->next_di);
661 for (l = di->pd_output; l; l = l->next) {
663 g_free(pdo->proto_id);
666 g_slist_free(di->pd_output);
671 SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
674 struct srd_decoder_inst *di;
676 if (session_is_valid(sess) != SRD_OK) {
677 srd_err("Invalid session.");
682 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
685 srd_inst_free_all(sess, di->next_di);
689 g_slist_free(sess->di_list);
690 sess->di_list = NULL;