]> sigrok.org Git - libsigrokdecode.git/blob - instance.c
Drop references to obsolete sigrok-commits mailing list.
[libsigrokdecode.git] / instance.c
1 /*
2  * This file is part of the libsigrokdecode project.
3  *
4  * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
21 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode.h"
23 #include "config.h"
24 #include <glib.h>
25 #include <inttypes.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28
29 /** @cond PRIVATE */
30
31 extern SRD_PRIV GSList *sessions;
32
33 /* type_logic.c */
34 extern SRD_PRIV PyTypeObject srd_logic_type;
35
36 /** @endcond */
37
38 /**
39  * @file
40  *
41  * Decoder instance handling.
42  */
43
44 /**
45  * @defgroup grp_instances Decoder instances
46  *
47  * Decoder instance handling.
48  *
49  * @{
50  */
51
52 /**
53  * Set one or more options in a decoder instance.
54  *
55  * Handled options are removed from the hash.
56  *
57  * @param di Decoder instance.
58  * @param options A GHashTable of options to set.
59  *
60  * @return SRD_OK upon success, a (negative) error code otherwise.
61  *
62  * @since 0.1.0
63  */
64 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
65                 GHashTable *options)
66 {
67     struct srd_decoder_option *sdo;
68         PyObject *py_di_options, *py_optval;
69         GVariant *value;
70     GSList *l;
71     double val_double;
72         gint64 val_int;
73         int ret;
74         const char *val_str;
75
76         if (!di) {
77                 srd_err("Invalid decoder instance.");
78                 return SRD_ERR_ARG;
79         }
80
81         if (!options) {
82                 srd_err("Invalid options GHashTable.");
83                 return SRD_ERR_ARG;
84         }
85
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. */
90                         return SRD_OK;
91                 } else {
92                         srd_err("Protocol decoder has no options.");
93                         return SRD_ERR_ARG;
94                 }
95                 return SRD_OK;
96         }
97
98         ret = SRD_ERR_PYTHON;
99     py_optval = NULL;
100
101         /*
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
105          * instead.
106          */
107         if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
108                 goto err_out;
109         Py_DECREF(py_di_options);
110         py_di_options = PyDict_New();
111         PyObject_SetAttrString(di->py_inst, "options", py_di_options);
112
113     for (l = di->decoder->options; l; l = l->next) {
114         sdo = l->data;
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);
121                 goto err_out;
122             }
123         } else {
124             /* Use default for this option. */
125             value = sdo->def;
126         }
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. */
131                 PyErr_Clear();
132                 srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
133                 goto err_out;
134             }
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 */
139                 PyErr_Clear();
140                 srd_err("Option '%s' has invalid integer value.", sdo->id);
141                 goto err_out;
142             }
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 */
147                 PyErr_Clear();
148                 srd_err("Option '%s' has invalid float value.", sdo->id);
149                 goto err_out;
150             }
151         }
152                 if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1)
153                         goto err_out;
154         /* Not harmful even if we used the default. */
155         g_hash_table_remove(options, sdo->id);
156     }
157     if (g_hash_table_size(options) != 0)
158         srd_warn("Unknown options specified for '%s'", di->inst_id);
159
160         ret = SRD_OK;
161
162 err_out:
163         Py_XDECREF(py_optval);
164         if (PyErr_Occurred()) {
165                 srd_exception_catch("Stray exception in srd_inst_option_set().");
166                 ret = SRD_ERR_PYTHON;
167         }
168
169         return ret;
170 }
171
172 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_channel_set_all() */
173 static gint compare_channel_id(const struct srd_channel *pdch,
174                         const char *channel_id)
175 {
176         return strcmp(pdch->id, channel_id);
177 }
178
179 /**
180  * Set all channels in a decoder instance.
181  *
182  * This function sets _all_ channels for the specified decoder instance, i.e.,
183  * it overwrites any channels that were already defined (if any).
184  *
185  * @param di Decoder instance.
186  * @param new_channels A GHashTable of channels to set. Key is channel name,
187  *                     value is the channel number. Samples passed to this
188  *                     instance will be arranged in this order.
189  * @param unit_size Number of bytes per sample in the data stream to be passed
190  *                  to the decoder. The highest channel index specified in the
191  *                  channel map must lie within a sample unit.
192  *
193  * @return SRD_OK upon success, a (negative) error code otherwise.
194  *
195  * @since 0.3.0
196  */
197 SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
198                 GHashTable *new_channels, int unit_size)
199 {
200         GVariant *channel_val;
201         GList *l;
202         GSList *sl;
203         struct srd_channel *pdch;
204         int *new_channelmap, new_channelnum, num_required_channels, i;
205         char *channel_id;
206
207         srd_dbg("Setting channels for instance %s with list of %d channels, "
208                 "unitsize %d.", di->inst_id, g_hash_table_size(new_channels), unit_size);
209
210         if (g_hash_table_size(new_channels) == 0)
211                 /* No channels provided. */
212                 return SRD_OK;
213
214         if (di->dec_num_channels == 0) {
215                 /* Decoder has no channels. */
216                 srd_err("Protocol decoder %s has no channels to define.",
217                         di->decoder->name);
218                 return SRD_ERR_ARG;
219         }
220
221         new_channelmap = NULL;
222
223         if (!(new_channelmap = g_try_malloc(sizeof(int) * di->dec_num_channels))) {
224                 srd_err("Failed to g_malloc() new channel map.");
225                 return SRD_ERR_MALLOC;
226         }
227
228         /*
229          * For now, map all indexes to channel -1 (can be overridden later).
230          * This -1 is interpreted as an unspecified channel later.
231          */
232         for (i = 0; i < di->dec_num_channels; i++)
233                 new_channelmap[i] = -1;
234
235         for (l = g_hash_table_get_keys(new_channels); l; l = l->next) {
236                 channel_id = l->data;
237                 channel_val = g_hash_table_lookup(new_channels, channel_id);
238                 if (!g_variant_is_of_type(channel_val, G_VARIANT_TYPE_INT32)) {
239                         /* Channel name was specified without a value. */
240                         srd_err("No channel number was specified for %s.",
241                                         channel_id);
242                         g_free(new_channelmap);
243                         return SRD_ERR_ARG;
244                 }
245                 new_channelnum = g_variant_get_int32(channel_val);
246                 if (new_channelnum >= 8 * unit_size) {
247                         srd_err("Channel index %d not within data unit (%d bit).",
248                                 new_channelnum, 8 * unit_size);
249                         g_free(new_channelmap);
250                         return SRD_ERR_ARG;
251                 }
252                 if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
253                                 (GCompareFunc)compare_channel_id))) {
254                         /* Fall back on optional channels. */
255                         if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
256                              channel_id, (GCompareFunc) compare_channel_id))) {
257                                 srd_err("Protocol decoder %s has no channel "
258                                                 "'%s'.", di->decoder->name, channel_id);
259                                 g_free(new_channelmap);
260                                 return SRD_ERR_ARG;
261                         }
262                 }
263                 pdch = sl->data;
264                 new_channelmap[pdch->order] = new_channelnum;
265                 srd_dbg("Setting channel mapping: %s (index %d) = channel %d.",
266                         pdch->id, pdch->order, new_channelnum);
267         }
268         di->data_unitsize = unit_size;
269
270         srd_dbg("Final channel map:");
271         num_required_channels = g_slist_length(di->decoder->channels);
272         for (i = 0; i < di->dec_num_channels; i++) {
273                 srd_dbg(" - index %d = channel %d (%s)", i, new_channelmap[i],
274                         (i < num_required_channels) ? "required" : "optional");
275         }
276
277         /* Report an error if not all required channels were specified. */
278         for (i = 0; i < num_required_channels; i++) {
279                 if (new_channelmap[i] != -1)
280                         continue;
281                 pdch = g_slist_nth(di->decoder->channels, i)->data;
282                 srd_err("Required channel '%s' (index %d) was not specified.",
283                         pdch->id, i);
284                 return SRD_ERR;
285         }
286
287         g_free(di->dec_channelmap);
288         di->dec_channelmap = new_channelmap;
289
290         return SRD_OK;
291 }
292
293 /**
294  * Create a new protocol decoder instance.
295  *
296  * @param sess The session holding the protocol decoder instance.
297  * @param decoder_id Decoder 'id' field.
298  * @param options GHashtable of options which override the defaults set in
299  *                the decoder class. May be NULL.
300  *
301  * @return Pointer to a newly allocated struct srd_decoder_inst, or
302  *         NULL in case of failure.
303  *
304  * @since 0.3.0
305  */
306 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
307                 const char *decoder_id, GHashTable *options)
308 {
309         int i;
310         struct srd_decoder *dec;
311         struct srd_decoder_inst *di;
312         char *inst_id;
313
314         srd_dbg("Creating new %s instance.", decoder_id);
315
316         if (session_is_valid(sess) != SRD_OK) {
317                 srd_err("Invalid session.");
318                 return NULL;
319         }
320
321         if (!(dec = srd_decoder_get_by_id(decoder_id))) {
322                 srd_err("Protocol decoder %s not found.", decoder_id);
323                 return NULL;
324         }
325
326         if (!(di = g_try_malloc0(sizeof(struct srd_decoder_inst)))) {
327                 srd_err("Failed to g_malloc() instance.");
328                 return NULL;
329         }
330
331         di->decoder = dec;
332         di->sess = sess;
333         if (options) {
334                 inst_id = g_hash_table_lookup(options, "id");
335                 di->inst_id = g_strdup(inst_id ? inst_id : decoder_id);
336                 g_hash_table_remove(options, "id");
337         } else
338                 di->inst_id = g_strdup(decoder_id);
339
340         /*
341          * Prepare a default channel map, where samples come in the
342          * order in which the decoder class defined them.
343          */
344         di->dec_num_channels = g_slist_length(di->decoder->channels) +
345                         g_slist_length(di->decoder->opt_channels);
346         if (di->dec_num_channels) {
347                 if (!(di->dec_channelmap =
348                                 g_try_malloc(sizeof(int) * di->dec_num_channels))) {
349                         srd_err("Failed to g_malloc() channel map.");
350                         g_free(di);
351                         return NULL;
352                 }
353                 for (i = 0; i < di->dec_num_channels; i++)
354                         di->dec_channelmap[i] = i;
355                 di->data_unitsize = (di->dec_num_channels + 7) / 8;
356                 /*
357                  * Will be used to prepare a sample at every iteration
358                  * of the instance's decode() method.
359                  */
360                 if (!(di->channel_samples = g_try_malloc(di->dec_num_channels))) {
361                         srd_err("Failed to g_malloc() sample buffer.");
362                         g_free(di->dec_channelmap);
363                         g_free(di);
364                         return NULL;
365                 }
366         }
367
368         /* Create a new instance of this decoder class. */
369         if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
370                 if (PyErr_Occurred())
371                         srd_exception_catch("failed to create %s instance: ",
372                                         decoder_id);
373                 g_free(di->dec_channelmap);
374                 g_free(di);
375                 return NULL;
376         }
377
378         if (options && srd_inst_option_set(di, options) != SRD_OK) {
379                 g_free(di->dec_channelmap);
380                 g_free(di);
381                 return NULL;
382         }
383
384         /* Instance takes input from a frontend by default. */
385         sess->di_list = g_slist_append(sess->di_list, di);
386
387         return di;
388 }
389
390 /**
391  * Stack a decoder instance on top of another.
392  *
393  * @param sess The session holding the protocol decoder instances.
394  * @param di_bottom The instance on top of which di_top will be stacked.
395  * @param di_top The instance to go on top.
396  *
397  * @return SRD_OK upon success, a (negative) error code otherwise.
398  *
399  * @since 0.3.0
400  */
401 SRD_API int srd_inst_stack(struct srd_session *sess,
402                 struct srd_decoder_inst *di_bottom,
403                 struct srd_decoder_inst *di_top)
404 {
405
406         if (session_is_valid(sess) != SRD_OK) {
407                 srd_err("Invalid session.");
408                 return SRD_ERR_ARG;
409         }
410
411         if (!di_bottom || !di_top) {
412                 srd_err("Invalid from/to instance pair.");
413                 return SRD_ERR_ARG;
414         }
415
416         if (g_slist_find(sess->di_list, di_top)) {
417                 /* Remove from the unstacked list. */
418                 sess->di_list = g_slist_remove(sess->di_list, di_top);
419         }
420
421         /* Stack on top of source di. */
422         di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
423
424         srd_dbg("Stacked %s on top of %s.", di_top->inst_id, di_bottom->inst_id);
425
426         return SRD_OK;
427 }
428
429 /**
430  * Find a decoder instance by its instance ID.
431  *
432  * Only the bottom level of instances are searched -- instances already stacked
433  * on top of another one will not be found.
434  *
435  * @param sess The session holding the protocol decoder instance.
436  * @param inst_id The instance ID to be found.
437  *
438  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
439  *
440  * @since 0.3.0
441  */
442 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
443                 const char *inst_id)
444 {
445         GSList *l;
446         struct srd_decoder_inst *tmp, *di;
447
448         if (session_is_valid(sess) != SRD_OK) {
449                 srd_err("Invalid session.");
450                 return NULL;
451         }
452
453         di = NULL;
454         for (l = sess->di_list; l; l = l->next) {
455                 tmp = l->data;
456                 if (!strcmp(tmp->inst_id, inst_id)) {
457                         di = tmp;
458                         break;
459                 }
460         }
461
462         return di;
463 }
464
465 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
466                 struct srd_session *sess, const GSList *stack,
467                 const PyObject *obj)
468 {
469         const GSList *l;
470         struct srd_decoder_inst *tmp, *di;
471
472         if (session_is_valid(sess) != SRD_OK) {
473                 srd_err("Invalid session.");
474                 return NULL;
475         }
476
477         di = NULL;
478         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
479                 tmp = l->data;
480                 if (tmp->py_inst == obj)
481                         di = tmp;
482                 else if (tmp->next_di)
483                         di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
484         }
485
486         return di;
487 }
488
489 /**
490  * Find a decoder instance by its Python object.
491  *
492  * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
493  * This will recurse to find the instance anywhere in the stack tree of all
494  * sessions.
495  *
496  * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
497  *              stack to search. To start searching at the bottom level of
498  *              decoder instances, pass NULL.
499  * @param obj The Python class instantiation.
500  *
501  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
502  *
503  * @private
504  *
505  * @since 0.1.0
506  */
507 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
508                 const PyObject *obj)
509 {
510         struct srd_decoder_inst *di;
511         struct srd_session *sess;
512         GSList *l;
513
514         di = NULL;
515         for (l = sessions; di == NULL && l != NULL; l = l->next) {
516                 sess = l->data;
517                 di = srd_sess_inst_find_by_obj(sess, stack, obj);
518         }
519
520         return di;
521 }
522
523 /** @private */
524 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
525 {
526         PyObject *py_res;
527         GSList *l;
528         struct srd_decoder_inst *next_di;
529         int ret;
530
531         srd_dbg("Calling start() method on protocol decoder instance %s.",
532                         di->inst_id);
533
534         if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
535                 srd_exception_catch("Protocol decoder instance %s: ",
536                                 di->inst_id);
537                 return SRD_ERR_PYTHON;
538         }
539         Py_DecRef(py_res);
540
541         /* Start all the PDs stacked on top of this one. */
542         for (l = di->next_di; l; l = l->next) {
543                 next_di = l->data;
544                 if ((ret = srd_inst_start(next_di)) != SRD_OK)
545                         return ret;
546         }
547
548         return SRD_OK;
549 }
550
551 /**
552  * Run the specified decoder function.
553  *
554  * @param di The decoder instance to call. Must not be NULL.
555  * @param start_samplenum The starting sample number for the buffer's sample
556  *                        set, relative to the start of capture.
557  * @param end_samplenum The ending sample number for the buffer's sample
558  *                        set, relative to the start of capture.
559  * @param inbuf The buffer to decode. Must not be NULL.
560  * @param inbuflen Length of the buffer. Must be > 0.
561  *
562  * @return SRD_OK upon success, a (negative) error code otherwise.
563  *
564  * @private
565  *
566  * @since 0.1.0
567  */
568 SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
569                 uint64_t start_samplenum, uint64_t end_samplenum,
570                 const uint8_t *inbuf, uint64_t inbuflen)
571 {
572         PyObject *py_res;
573         srd_logic *logic;
574
575         srd_dbg("Calling decode() on instance %s with %" PRIu64 " bytes "
576                 "starting at sample %" PRIu64 ".", di->inst_id, inbuflen,
577                 start_samplenum);
578
579         /* Return an error upon unusable input. */
580         if (!di) {
581                 srd_dbg("empty decoder instance");
582                 return SRD_ERR_ARG;
583         }
584         if (!inbuf) {
585                 srd_dbg("NULL buffer pointer");
586                 return SRD_ERR_ARG;
587         }
588         if (inbuflen == 0) {
589                 srd_dbg("empty buffer");
590                 return SRD_ERR_ARG;
591         }
592
593         /*
594          * Create new srd_logic object. Each iteration around the PD's loop
595          * will fill one sample into this object.
596          */
597         logic = PyObject_New(srd_logic, &srd_logic_type);
598         Py_INCREF(logic);
599         logic->di = (struct srd_decoder_inst *)di;
600         logic->start_samplenum = start_samplenum;
601         logic->itercnt = 0;
602         logic->inbuf = (uint8_t *)inbuf;
603         logic->inbuflen = inbuflen;
604         logic->sample = PyList_New(2);
605         Py_INCREF(logic->sample);
606
607         Py_IncRef(di->py_inst);
608         if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
609                         "KKO", start_samplenum, end_samplenum, logic))) {
610                 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
611                 return SRD_ERR_PYTHON;
612         }
613         Py_DecRef(py_res);
614
615         return SRD_OK;
616 }
617
618 /** @private */
619 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
620 {
621         GSList *l;
622         struct srd_pd_output *pdo;
623
624         srd_dbg("Freeing instance %s", di->inst_id);
625
626         Py_DecRef(di->py_inst);
627         g_free(di->inst_id);
628         g_free(di->dec_channelmap);
629         g_slist_free(di->next_di);
630         for (l = di->pd_output; l; l = l->next) {
631                 pdo = l->data;
632                 g_free(pdo->proto_id);
633                 g_free(pdo);
634         }
635         g_slist_free(di->pd_output);
636         g_free(di);
637 }
638
639 /** @private */
640 SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
641 {
642         GSList *l;
643         struct srd_decoder_inst *di;
644
645         if (session_is_valid(sess) != SRD_OK) {
646                 srd_err("Invalid session.");
647                 return;
648         }
649
650         di = NULL;
651         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
652                 di = l->data;
653                 if (di->next_di)
654                         srd_inst_free_all(sess, di->next_di);
655                 srd_inst_free(di);
656         }
657         if (!stack) {
658                 g_slist_free(sess->di_list);
659                 sess->di_list = NULL;
660         }
661 }
662
663 /** @} */
664