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-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode.h"
31 extern SRD_PRIV 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 struct srd_decoder_option *sdo;
68 PyObject *py_di_options, *py_optval;
77 srd_err("Invalid decoder instance.");
82 srd_err("Invalid options GHashTable.");
86 if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
87 /* Decoder has no options. */
88 if (g_hash_table_size(options) == 0) {
89 /* No options provided. */
92 srd_err("Protocol decoder has no options.");
102 * The 'options' tuple is a class variable, but we need to
103 * change it. Changing it directly will affect the entire class,
104 * so we need to create a new object for it, and populate that
107 if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
109 Py_DECREF(py_di_options);
110 py_di_options = PyDict_New();
111 PyObject_SetAttrString(di->py_inst, "options", py_di_options);
113 for (l = di->decoder->options; l; l = l->next) {
115 if ((value = g_hash_table_lookup(options, sdo->id))) {
116 /* A value was supplied for this option. */
117 if (!g_variant_type_equal(g_variant_get_type(value),
118 g_variant_get_type(sdo->def))) {
119 srd_err("Option '%s' should have the same type "
120 "as the default value.", sdo->id);
124 /* Use default for this option. */
127 if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
128 val_str = g_variant_get_string(value, NULL);
129 if (!(py_optval = PyUnicode_FromString(val_str))) {
130 /* Some UTF-8 encoding error. */
132 srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
135 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
136 val_int = g_variant_get_int64(value);
137 if (!(py_optval = PyLong_FromLong(val_int))) {
138 /* ValueError Exception */
140 srd_err("Option '%s' has invalid integer value.", sdo->id);
143 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_DOUBLE)) {
144 val_double = g_variant_get_double(value);
145 if (!(py_optval = PyFloat_FromDouble(val_double))) {
146 /* ValueError Exception */
148 srd_err("Option '%s' has invalid float value.",
153 if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1)
155 /* Not harmful even if we used the default. */
156 g_hash_table_remove(options, sdo->id);
158 if (g_hash_table_size(options) != 0)
159 srd_warn("Unknown options specified for '%s'", di->inst_id);
164 Py_XDECREF(py_optval);
165 if (PyErr_Occurred()) {
166 srd_exception_catch("Stray exception in srd_inst_option_set().");
167 ret = SRD_ERR_PYTHON;
173 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_channel_set_all() */
174 static gint compare_channel_id(const struct srd_channel *pdch,
175 const char *channel_id)
177 return strcmp(pdch->id, channel_id);
181 * Set all channels in a decoder instance.
183 * This function sets _all_ channels for the specified decoder instance, i.e.,
184 * it overwrites any channels that were already defined (if any).
186 * @param di Decoder instance.
187 * @param new_channels A GHashTable of channels to set. Key is channel name,
188 * value is the channel number. Samples passed to this
189 * instance will be arranged in this order.
190 * @param unit_size Number of bytes per sample in the data stream to be passed
191 * to the decoder. The highest channel index specified in the
192 * channel map must lie within a sample unit.
194 * @return SRD_OK upon success, a (negative) error code otherwise.
198 SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
199 GHashTable *new_channels, int unit_size)
201 GVariant *channel_val;
204 struct srd_channel *pdch;
205 int *new_channelmap, new_channelnum, num_required_channels, i;
208 srd_dbg("Setting channels for instance %s with list of %d channels, "
209 "unitsize %d.", di->inst_id, g_hash_table_size(new_channels),
212 if (g_hash_table_size(new_channels) == 0)
213 /* No channels provided. */
216 if (di->dec_num_channels == 0) {
217 /* Decoder has no channels. */
218 srd_err("Protocol decoder %s has no channels to define.",
223 new_channelmap = g_malloc(sizeof(int) * di->dec_num_channels);
226 * For now, map all indexes to channel -1 (can be overridden later).
227 * This -1 is interpreted as an unspecified channel later.
229 for (i = 0; i < di->dec_num_channels; i++)
230 new_channelmap[i] = -1;
232 for (l = g_hash_table_get_keys(new_channels); l; l = l->next) {
233 channel_id = l->data;
234 channel_val = g_hash_table_lookup(new_channels, channel_id);
235 if (!g_variant_is_of_type(channel_val, G_VARIANT_TYPE_INT32)) {
236 /* Channel name was specified without a value. */
237 srd_err("No channel number was specified for %s.",
239 g_free(new_channelmap);
242 new_channelnum = g_variant_get_int32(channel_val);
243 if (new_channelnum >= 8 * unit_size) {
244 srd_err("Channel index %d not within data unit (%d bit).",
245 new_channelnum, 8 * unit_size);
246 g_free(new_channelmap);
249 if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
250 (GCompareFunc)compare_channel_id))) {
251 /* Fall back on optional channels. */
252 if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
253 channel_id, (GCompareFunc)compare_channel_id))) {
254 srd_err("Protocol decoder %s has no channel "
255 "'%s'.", di->decoder->name, channel_id);
256 g_free(new_channelmap);
261 new_channelmap[pdch->order] = new_channelnum;
262 srd_dbg("Setting channel mapping: %s (index %d) = channel %d.",
263 pdch->id, pdch->order, new_channelnum);
265 di->data_unitsize = unit_size;
267 srd_dbg("Final channel map:");
268 num_required_channels = g_slist_length(di->decoder->channels);
269 for (i = 0; i < di->dec_num_channels; i++) {
270 srd_dbg(" - index %d = channel %d (%s)", i, new_channelmap[i],
271 (i < num_required_channels) ? "required" : "optional");
274 /* Report an error if not all required channels were specified. */
275 for (i = 0; i < num_required_channels; i++) {
276 if (new_channelmap[i] != -1)
278 pdch = g_slist_nth(di->decoder->channels, i)->data;
279 srd_err("Required channel '%s' (index %d) was not specified.",
284 g_free(di->dec_channelmap);
285 di->dec_channelmap = new_channelmap;
291 * Create a new protocol decoder instance.
293 * @param sess The session holding the protocol decoder instance.
294 * @param decoder_id Decoder 'id' field.
295 * @param options GHashtable of options which override the defaults set in
296 * the decoder class. May be NULL.
298 * @return Pointer to a newly allocated struct srd_decoder_inst, or
299 * NULL in case of failure.
303 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
304 const char *decoder_id, GHashTable *options)
307 struct srd_decoder *dec;
308 struct srd_decoder_inst *di;
311 srd_dbg("Creating new %s instance.", decoder_id);
313 if (session_is_valid(sess) != SRD_OK) {
314 srd_err("Invalid session.");
318 if (!(dec = srd_decoder_get_by_id(decoder_id))) {
319 srd_err("Protocol decoder %s not found.", decoder_id);
323 di = g_malloc0(sizeof(struct srd_decoder_inst));
328 inst_id = g_hash_table_lookup(options, "id");
329 di->inst_id = g_strdup(inst_id ? inst_id : decoder_id);
330 g_hash_table_remove(options, "id");
332 di->inst_id = g_strdup(decoder_id);
335 * Prepare a default channel map, where samples come in the
336 * order in which the decoder class defined them.
338 di->dec_num_channels = g_slist_length(di->decoder->channels) +
339 g_slist_length(di->decoder->opt_channels);
340 if (di->dec_num_channels) {
342 g_malloc(sizeof(int) * di->dec_num_channels);
343 for (i = 0; i < di->dec_num_channels; i++)
344 di->dec_channelmap[i] = i;
345 di->data_unitsize = (di->dec_num_channels + 7) / 8;
347 * Will be used to prepare a sample at every iteration
348 * of the instance's decode() method.
350 di->channel_samples = g_malloc(di->dec_num_channels);
353 /* Create a new instance of this decoder class. */
354 if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
355 if (PyErr_Occurred())
356 srd_exception_catch("failed to create %s instance: ",
358 g_free(di->dec_channelmap);
363 if (options && srd_inst_option_set(di, options) != SRD_OK) {
364 g_free(di->dec_channelmap);
369 /* Instance takes input from a frontend by default. */
370 sess->di_list = g_slist_append(sess->di_list, di);
376 * Stack a decoder instance on top of another.
378 * @param sess The session holding the protocol decoder instances.
379 * @param di_bottom The instance on top of which di_top will be stacked.
380 * @param di_top The instance to go on top.
382 * @return SRD_OK upon success, a (negative) error code otherwise.
386 SRD_API int srd_inst_stack(struct srd_session *sess,
387 struct srd_decoder_inst *di_bottom,
388 struct srd_decoder_inst *di_top)
391 if (session_is_valid(sess) != SRD_OK) {
392 srd_err("Invalid session.");
396 if (!di_bottom || !di_top) {
397 srd_err("Invalid from/to instance pair.");
401 if (g_slist_find(sess->di_list, di_top)) {
402 /* Remove from the unstacked list. */
403 sess->di_list = g_slist_remove(sess->di_list, di_top);
406 /* Stack on top of source di. */
407 di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
409 srd_dbg("Stacked %s onto %s.", di_top->inst_id, di_bottom->inst_id);
415 * Find a decoder instance by its instance ID.
417 * Only the bottom level of instances are searched -- instances already stacked
418 * on top of another one will not be found.
420 * @param sess The session holding the protocol decoder instance.
421 * @param inst_id The instance ID to be found.
423 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
427 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
431 struct srd_decoder_inst *tmp, *di;
433 if (session_is_valid(sess) != SRD_OK) {
434 srd_err("Invalid session.");
439 for (l = sess->di_list; l; l = l->next) {
441 if (!strcmp(tmp->inst_id, inst_id)) {
450 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
451 struct srd_session *sess, const GSList *stack,
455 struct srd_decoder_inst *tmp, *di;
457 if (session_is_valid(sess) != SRD_OK) {
458 srd_err("Invalid session.");
463 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
465 if (tmp->py_inst == obj)
467 else if (tmp->next_di)
468 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
475 * Find a decoder instance by its Python object.
477 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
478 * This will recurse to find the instance anywhere in the stack tree of all
481 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
482 * stack to search. To start searching at the bottom level of
483 * decoder instances, pass NULL.
484 * @param obj The Python class instantiation.
486 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
492 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
495 struct srd_decoder_inst *di;
496 struct srd_session *sess;
500 for (l = sessions; di == NULL && l != NULL; l = l->next) {
502 di = srd_sess_inst_find_by_obj(sess, stack, obj);
509 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
513 struct srd_decoder_inst *next_di;
516 srd_dbg("Calling start() method on protocol decoder instance %s.",
519 if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
520 srd_exception_catch("Protocol decoder instance %s: ",
522 return SRD_ERR_PYTHON;
526 /* Start all the PDs stacked on top of this one. */
527 for (l = di->next_di; l; l = l->next) {
529 if ((ret = srd_inst_start(next_di)) != SRD_OK)
537 * Run the specified decoder function.
539 * @param di The decoder instance to call. Must not be NULL.
540 * @param start_samplenum The starting sample number for the buffer's sample
541 * set, relative to the start of capture.
542 * @param end_samplenum The ending sample number for the buffer's sample
543 * set, relative to the start of capture.
544 * @param inbuf The buffer to decode. Must not be NULL.
545 * @param inbuflen Length of the buffer. Must be > 0.
547 * @return SRD_OK upon success, a (negative) error code otherwise.
553 SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
554 uint64_t start_samplenum, uint64_t end_samplenum,
555 const uint8_t *inbuf, uint64_t inbuflen)
560 srd_dbg("Calling decode() on instance %s with %" PRIu64 " bytes "
561 "starting at sample %" PRIu64 ".", di->inst_id, inbuflen,
564 /* Return an error upon unusable input. */
566 srd_dbg("empty decoder instance");
570 srd_dbg("NULL buffer pointer");
574 srd_dbg("empty buffer");
579 * Create new srd_logic object. Each iteration around the PD's loop
580 * will fill one sample into this object.
582 logic = PyObject_New(srd_logic, &srd_logic_type);
584 logic->di = (struct srd_decoder_inst *)di;
585 logic->start_samplenum = start_samplenum;
587 logic->inbuf = (uint8_t *)inbuf;
588 logic->inbuflen = inbuflen;
589 logic->sample = PyList_New(2);
590 Py_INCREF(logic->sample);
592 Py_IncRef(di->py_inst);
593 if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
594 "KKO", start_samplenum, end_samplenum, logic))) {
595 srd_exception_catch("Protocol decoder instance %s: ",
597 return SRD_ERR_PYTHON;
605 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
608 struct srd_pd_output *pdo;
610 srd_dbg("Freeing instance %s", di->inst_id);
612 Py_DecRef(di->py_inst);
614 g_free(di->dec_channelmap);
615 g_slist_free(di->next_di);
616 for (l = di->pd_output; l; l = l->next) {
618 g_free(pdo->proto_id);
621 g_slist_free(di->pd_output);
626 SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
629 struct srd_decoder_inst *di;
631 if (session_is_valid(sess) != SRD_OK) {
632 srd_err("Invalid session.");
637 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
640 srd_inst_free_all(sess, di->next_di);
644 g_slist_free(sess->di_list);
645 sess->di_list = NULL;