]> sigrok.org Git - libsigrokdecode.git/blob - controller.c
Add a 'guess_bitrate' protocol decoder.
[libsigrokdecode.git] / controller.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.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22 #include "libsigrokdecode-internal.h"
23 #include "config.h"
24 #include <glib.h>
25 #include <inttypes.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28
29 /**
30  * @mainpage libsigrokdecode API
31  *
32  * @section sec_intro Introduction
33  *
34  * The <a href="http://sigrok.org">sigrok</a> project aims at creating a
35  * portable, cross-platform, Free/Libre/Open-Source signal analysis software
36  * suite that supports various device types (such as logic analyzers,
37  * oscilloscopes, multimeters, and more).
38  *
39  * <a href="http://sigrok.org/wiki/Libsigrokdecode">libsigrokdecode</a> is a
40  * shared library written in C which provides the basic API for (streaming)
41  * protocol decoding functionality.
42  *
43  * The <a href="http://sigrok.org/wiki/Protocol_decoders">protocol decoders</a>
44  * are written in Python (>= 3.0).
45  *
46  * @section sec_api API reference
47  *
48  * See the "Modules" page for an introduction to various libsigrokdecode
49  * related topics and the detailed API documentation of the respective
50  * functions.
51  *
52  * You can also browse the API documentation by file, or review all
53  * data structures.
54  *
55  * @section sec_mailinglists Mailing lists
56  *
57  * There are two mailing lists for sigrok/libsigrokdecode: <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-devel">sigrok-devel</a> and <a href="https://lists.sourceforge.net/lists/listinfo/sigrok-commits">sigrok-commits</a>.
58  *
59  * @section sec_irc IRC
60  *
61  * You can find the sigrok developers in the
62  * <a href="irc://chat.freenode.net/sigrok">\#sigrok</a>
63  * IRC channel on Freenode.
64  *
65  * @section sec_website Website
66  *
67  * <a href="http://sigrok.org/wiki/Libsigrokdecode">sigrok.org/wiki/Libsigrokdecode</a>
68  */
69
70 /**
71  * @file
72  *
73  * Initializing and shutting down libsigrokdecode.
74  */
75
76 /**
77  * @defgroup grp_init Initialization
78  *
79  * Initializing and shutting down libsigrokdecode.
80  *
81  * Before using any of the libsigrokdecode functionality, srd_init() must
82  * be called to initialize the library.
83  *
84  * When libsigrokdecode functionality is no longer needed, srd_exit() should
85  * be called.
86  *
87  * @{
88  */
89
90 /** @cond PRIVATE */
91
92 SRD_PRIV GSList *sessions = NULL;
93 static int max_session_id = -1;
94
95 static int session_is_valid(struct srd_session *sess);
96
97 /* decoder.c */
98 extern SRD_PRIV GSList *pd_list;
99
100 /* module_sigrokdecode.c */
101 extern PyMODINIT_FUNC PyInit_sigrokdecode(void);
102
103 /* type_logic.c */
104 extern SRD_PRIV PyTypeObject srd_logic_type;
105
106 /** @endcond */
107
108 /**
109  * Initialize libsigrokdecode.
110  *
111  * This initializes the Python interpreter, and creates and initializes
112  * a "sigrokdecode" Python module.
113  *
114  * Then, it searches for sigrok protocol decoders in the "decoders"
115  * subdirectory of the the libsigrokdecode installation directory.
116  * All decoders that are found are loaded into memory and added to an
117  * internal list of decoders, which can be queried via srd_decoder_list().
118  *
119  * The caller is responsible for calling the clean-up function srd_exit(),
120  * which will properly shut down libsigrokdecode and free its allocated memory.
121  *
122  * Multiple calls to srd_init(), without calling srd_exit() in between,
123  * are not allowed.
124  *
125  * @param path Path to an extra directory containing protocol decoders
126  *             which will be added to the Python sys.path. May be NULL.
127  *
128  * @return SRD_OK upon success, a (negative) error code otherwise.
129  *         Upon Python errors, SRD_ERR_PYTHON is returned. If the decoders
130  *         directory cannot be accessed, SRD_ERR_DECODERS_DIR is returned.
131  *         If not enough memory could be allocated, SRD_ERR_MALLOC is returned.
132  *
133  * @since 0.1.0
134  */
135 SRD_API int srd_init(const char *path)
136 {
137         int ret;
138         char *env_path;
139
140         if (max_session_id != -1) {
141                 srd_err("libsigrokdecode is already initialized.");
142                 return SRD_ERR;
143         }
144
145         srd_dbg("Initializing libsigrokdecode.");
146
147         /* Add our own module to the list of built-in modules. */
148         PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
149
150         /* Initialize the Python interpreter. */
151         Py_Initialize();
152
153         /* Installed decoders. */
154         if ((ret = srd_decoder_searchpath_add(DECODERS_DIR)) != SRD_OK) {
155                 Py_Finalize();
156                 return ret;
157         }
158
159         /* Path specified by the user. */
160         if (path) {
161                 if ((ret = srd_decoder_searchpath_add(path)) != SRD_OK) {
162                         Py_Finalize();
163                         return ret;
164                 }
165         }
166
167         /* Environment variable overrides everything, for debugging. */
168         if ((env_path = getenv("SIGROKDECODE_DIR"))) {
169                 if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) {
170                         Py_Finalize();
171                         return ret;
172                 }
173         }
174
175         max_session_id = 0;
176
177         return SRD_OK;
178 }
179
180 /**
181  * Shutdown libsigrokdecode.
182  *
183  * This frees all the memory allocated for protocol decoders and shuts down
184  * the Python interpreter.
185  *
186  * This function should only be called if there was a (successful!) invocation
187  * of srd_init() before. Calling this function multiple times in a row, without
188  * any successful srd_init() calls in between, is not allowed.
189  *
190  * @return SRD_OK upon success, a (negative) error code otherwise.
191  *
192  * @since 0.1.0
193  */
194 SRD_API int srd_exit(void)
195 {
196         GSList *l;
197
198         srd_dbg("Exiting libsigrokdecode.");
199
200         for (l = sessions; l; l = l->next)
201                 srd_session_destroy((struct srd_session *)l->data);
202
203         srd_decoder_unload_all();
204         g_slist_free(pd_list);
205         pd_list = NULL;
206
207         /* Py_Finalize() returns void, any finalization errors are ignored. */
208         Py_Finalize();
209
210         max_session_id = -1;
211
212         return SRD_OK;
213 }
214
215 /**
216  * Add an additional search directory for the protocol decoders.
217  *
218  * The specified directory is prepended (not appended!) to Python's sys.path,
219  * in order to search for sigrok protocol decoders in the specified
220  * directories first, and in the generic Python module directories (and in
221  * the current working directory) last. This avoids conflicts if there are
222  * Python modules which have the same name as a sigrok protocol decoder in
223  * sys.path or in the current working directory.
224  *
225  * @param path Path to the directory containing protocol decoders which shall
226  *             be added to the Python sys.path, or NULL.
227  *
228  * @return SRD_OK upon success, a (negative) error code otherwise.
229  *
230  * @private
231  *
232  * @since 0.1.0
233  */
234 SRD_PRIV int srd_decoder_searchpath_add(const char *path)
235 {
236         PyObject *py_cur_path, *py_item;
237         GString *new_path;
238         int wc_len, i;
239         wchar_t *wc_new_path;
240         char *item;
241
242         srd_dbg("Adding '%s' to module path.", path);
243
244         new_path = g_string_sized_new(256);
245         g_string_assign(new_path, path);
246         py_cur_path = PySys_GetObject("path");
247         for (i = 0; i < PyList_Size(py_cur_path); i++) {
248                 g_string_append(new_path, G_SEARCHPATH_SEPARATOR_S);
249                 py_item = PyList_GetItem(py_cur_path, i);
250                 if (!PyUnicode_Check(py_item))
251                         /* Shouldn't happen. */
252                         continue;
253                 if (py_str_as_str(py_item, &item) != SRD_OK)
254                         continue;
255                 g_string_append(new_path, item);
256                 g_free(item);
257         }
258
259         /* Convert to wide chars. */
260         wc_len = sizeof(wchar_t) * (new_path->len + 1);
261         if (!(wc_new_path = g_try_malloc(wc_len))) {
262                 srd_dbg("malloc failed");
263                 return SRD_ERR_MALLOC;
264         }
265         mbstowcs(wc_new_path, new_path->str, wc_len);
266         PySys_SetPath(wc_new_path);
267         g_string_free(new_path, TRUE);
268         g_free(wc_new_path);
269
270         return SRD_OK;
271 }
272
273 /** @} */
274
275 /**
276  * @defgroup grp_instances Decoder instances
277  *
278  * Decoder instance handling.
279  *
280  * @{
281  */
282
283 /**
284  * Set one or more options in a decoder instance.
285  *
286  * Handled options are removed from the hash.
287  *
288  * @param di Decoder instance.
289  * @param options A GHashTable of options to set.
290  *
291  * @return SRD_OK upon success, a (negative) error code otherwise.
292  *
293  * @since 0.1.0
294  */
295 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
296                 GHashTable *options)
297 {
298         PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
299         PyObject *py_optlist, *py_classval;
300         Py_UNICODE *py_ustr;
301         GVariant *value;
302         unsigned long long int val_ull;
303         gint64 val_int;
304         int num_optkeys, ret, size, i;
305         const char *val_str;
306         char *dbg, *key;
307
308         if (!di) {
309                 srd_err("Invalid decoder instance.");
310                 return SRD_ERR_ARG;
311         }
312
313         if (!options) {
314                 srd_err("Invalid options GHashTable.");
315                 return SRD_ERR_ARG;
316         }
317
318         if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
319                 /* Decoder has no options. */
320                 if (g_hash_table_size(options) == 0) {
321                         /* No options provided. */
322                         return SRD_OK;
323                 } else {
324                         srd_err("Protocol decoder has no options.");
325                         return SRD_ERR_ARG;
326                 }
327                 return SRD_OK;
328         }
329
330         ret = SRD_ERR_PYTHON;
331         key = NULL;
332         py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
333         py_optlist = py_classval = NULL;
334         py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");
335
336         /* All of these are synthesized objects, so they're good. */
337         py_dec_optkeys = PyDict_Keys(py_dec_options);
338         num_optkeys = PyList_Size(py_dec_optkeys);
339
340         /*
341          * The 'options' dictionary is a class variable, but we need to
342          * change it. Changing it directly will affect the entire class,
343          * so we need to create a new object for it, and populate that
344          * instead.
345          */
346         if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
347                 goto err_out;
348         Py_DECREF(py_di_options);
349         py_di_options = PyDict_New();
350         PyObject_SetAttrString(di->py_inst, "options", py_di_options);
351         for (i = 0; i < num_optkeys; i++) {
352                 /* Get the default class value for this option. */
353                 py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
354                 if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
355                         goto err_out;
356                 if (!(py_classval = PyList_GetItem(py_optlist, 1)))
357                         goto err_out;
358                 if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
359                         srd_err("Options of type %s are not yet supported.",
360                                 Py_TYPE(py_classval)->tp_name);
361                         goto err_out;
362                 }
363
364                 if ((value = g_hash_table_lookup(options, key))) {
365                         dbg = g_variant_print(value, TRUE);
366                         srd_dbg("got option '%s' = %s", key, dbg);
367                         g_free(dbg);
368                         /* An override for this option was provided. */
369                         if (PyUnicode_Check(py_classval)) {
370                                 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
371                                         srd_err("Option '%s' requires a string value.", key);
372                                         goto err_out;
373                                 }
374                                 val_str = g_variant_get_string(value, NULL);
375                                 if (!(py_optval = PyUnicode_FromString(val_str))) {
376                                         /* Some UTF-8 encoding error. */
377                                         PyErr_Clear();
378                                         srd_err("Option '%s' requires a UTF-8 string value.", key);
379                                         goto err_out;
380                                 }
381                         } else if (PyLong_Check(py_classval)) {
382                                 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
383                                         srd_err("Option '%s' requires an integer value.", key);
384                                         goto err_out;
385                                 }
386                                 val_int = g_variant_get_int64(value);
387                                 if (!(py_optval = PyLong_FromLong(val_int))) {
388                                         /* ValueError Exception */
389                                         PyErr_Clear();
390                                         srd_err("Option '%s' has invalid integer value.", key);
391                                         goto err_out;
392                                 }
393                         }
394                         g_hash_table_remove(options, key);
395                 } else {
396                         /* Use the class default for this option. */
397                         if (PyUnicode_Check(py_classval)) {
398                                 /* Make a brand new copy of the string. */
399                                 py_ustr = PyUnicode_AS_UNICODE(py_classval);
400                                 size = PyUnicode_GET_SIZE(py_classval);
401                                 py_optval = PyUnicode_FromUnicode(py_ustr, size);
402                         } else if (PyLong_Check(py_classval)) {
403                                 /* Make a brand new copy of the integer. */
404                                 val_ull = PyLong_AsUnsignedLongLong(py_classval);
405                                 if (val_ull == (unsigned long long)-1) {
406                                         /* OverFlowError exception */
407                                         PyErr_Clear();
408                                         srd_err("Invalid integer value for %s: "
409                                                 "expected integer.", key);
410                                         goto err_out;
411                                 }
412                                 if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
413                                         goto err_out;
414                         }
415                 }
416
417                 /*
418                  * If we got here, py_optval holds a known good new reference
419                  * to the instance option to set.
420                  */
421                 if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
422                         goto err_out;
423                 g_free(key);
424                 key = NULL;
425         }
426
427         ret = SRD_OK;
428
429 err_out:
430         Py_XDECREF(py_di_options);
431         Py_XDECREF(py_dec_optkeys);
432         Py_XDECREF(py_dec_options);
433         g_free(key);
434         if (PyErr_Occurred()) {
435                 srd_exception_catch("Stray exception in srd_inst_option_set().");
436                 ret = SRD_ERR_PYTHON;
437         }
438
439         return ret;
440 }
441
442 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_probe_set_all() */
443 static gint compare_probe_id(const struct srd_probe *a, const char *probe_id)
444 {
445         return strcmp(a->id, probe_id);
446 }
447
448 /**
449  * Set all probes in a decoder instance.
450  *
451  * This function sets _all_ probes for the specified decoder instance, i.e.,
452  * it overwrites any probes that were already defined (if any).
453  *
454  * @param di Decoder instance.
455  * @param new_probes A GHashTable of probes to set. Key is probe name, value is
456  *                   the probe number. Samples passed to this instance will be
457  *                   arranged in this order.
458  *
459  * @return SRD_OK upon success, a (negative) error code otherwise.
460  *
461  * @since 0.1.0
462  */
463 SRD_API int srd_inst_probe_set_all(struct srd_decoder_inst *di,
464                 GHashTable *new_probes)
465 {
466         GVariant *probe_val;
467         GList *l;
468         GSList *sl;
469         struct srd_probe *p;
470         int *new_probemap, new_probenum;
471         char *probe_id;
472         int i, num_required_probes;
473
474         srd_dbg("set probes called for instance %s with list of %d probes",
475                 di->inst_id, g_hash_table_size(new_probes));
476
477         if (g_hash_table_size(new_probes) == 0)
478                 /* No probes provided. */
479                 return SRD_OK;
480
481         if (di->dec_num_probes == 0) {
482                 /* Decoder has no probes. */
483                 srd_err("Protocol decoder %s has no probes to define.",
484                         di->decoder->name);
485                 return SRD_ERR_ARG;
486         }
487
488         new_probemap = NULL;
489
490         if (!(new_probemap = g_try_malloc(sizeof(int) * di->dec_num_probes))) {
491                 srd_err("Failed to g_malloc() new probe map.");
492                 return SRD_ERR_MALLOC;
493         }
494
495         /*
496          * For now, map all indexes to probe -1 (can be overridden later).
497          * This -1 is interpreted as an unspecified probe later.
498          */
499         for (i = 0; i < di->dec_num_probes; i++)
500                 new_probemap[i] = -1;
501
502         for (l = g_hash_table_get_keys(new_probes); l; l = l->next) {
503                 probe_id = l->data;
504                 probe_val= g_hash_table_lookup(new_probes, probe_id);
505                 if (!g_variant_is_of_type(probe_val, G_VARIANT_TYPE_INT32)) {
506                         /* Probe name was specified without a value. */
507                         srd_err("No probe number was specified for %s.",
508                                         probe_id);
509                         g_free(new_probemap);
510                         return SRD_ERR_ARG;
511                 }
512                 new_probenum = g_variant_get_int32(probe_val);
513                 if (!(sl = g_slist_find_custom(di->decoder->probes, probe_id,
514                                 (GCompareFunc)compare_probe_id))) {
515                         /* Fall back on optional probes. */
516                         if (!(sl = g_slist_find_custom(di->decoder->opt_probes,
517                              probe_id, (GCompareFunc) compare_probe_id))) {
518                                 srd_err("Protocol decoder %s has no probe "
519                                                 "'%s'.", di->decoder->name, probe_id);
520                                 g_free(new_probemap);
521                                 return SRD_ERR_ARG;
522                         }
523                 }
524                 p = sl->data;
525                 new_probemap[p->order] = new_probenum;
526                 srd_dbg("Setting probe mapping: %s (index %d) = probe %d.",
527                         p->id, p->order, new_probenum);
528         }
529
530         srd_dbg("Final probe map:");
531         num_required_probes = g_slist_length(di->decoder->probes);
532         for (i = 0; i < di->dec_num_probes; i++) {
533                 srd_dbg(" - index %d = probe %d (%s)", i, new_probemap[i],
534                         (i < num_required_probes) ? "required" : "optional");
535         }
536
537         g_free(di->dec_probemap);
538         di->dec_probemap = new_probemap;
539
540         return SRD_OK;
541 }
542
543 /**
544  * Create a new protocol decoder instance.
545  *
546  * @param sess The session holding the protocol decoder instance.
547  * @param decoder_id Decoder 'id' field.
548  * @param options GHashtable of options which override the defaults set in
549  *                the decoder class. May be NULL.
550  *
551  * @return Pointer to a newly allocated struct srd_decoder_inst, or
552  *         NULL in case of failure.
553  *
554  * @since 0.1.0 (the API changed in 0.3.0, though)
555  */
556 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
557                 const char *decoder_id, GHashTable *options)
558 {
559         int i;
560         struct srd_decoder *dec;
561         struct srd_decoder_inst *di;
562         char *inst_id;
563
564         srd_dbg("Creating new %s instance.", decoder_id);
565
566         if (session_is_valid(sess) != SRD_OK) {
567                 srd_err("Invalid session.");
568                 return NULL;
569         }
570
571         if (!(dec = srd_decoder_get_by_id(decoder_id))) {
572                 srd_err("Protocol decoder %s not found.", decoder_id);
573                 return NULL;
574         }
575
576         if (!(di = g_try_malloc0(sizeof(struct srd_decoder_inst)))) {
577                 srd_err("Failed to g_malloc() instance.");
578                 return NULL;
579         }
580
581         di->decoder = dec;
582         di->sess = sess;
583         if (options) {
584                 inst_id = g_hash_table_lookup(options, "id");
585                 di->inst_id = g_strdup(inst_id ? inst_id : decoder_id);
586                 g_hash_table_remove(options, "id");
587         } else
588                 di->inst_id = g_strdup(decoder_id);
589
590         /*
591          * Prepare a default probe map, where samples come in the
592          * order in which the decoder class defined them.
593          */
594         di->dec_num_probes = g_slist_length(di->decoder->probes) +
595                              g_slist_length(di->decoder->opt_probes);
596         if (di->dec_num_probes) {
597                 if (!(di->dec_probemap =
598                      g_try_malloc(sizeof(int) * di->dec_num_probes))) {
599                         srd_err("Failed to g_malloc() probe map.");
600                         g_free(di);
601                         return NULL;
602                 }
603                 for (i = 0; i < di->dec_num_probes; i++)
604                         di->dec_probemap[i] = i;
605         }
606
607         /* Create a new instance of this decoder class. */
608         if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
609                 if (PyErr_Occurred())
610                         srd_exception_catch("failed to create %s instance: ",
611                                             decoder_id);
612                 g_free(di->dec_probemap);
613                 g_free(di);
614                 return NULL;
615         }
616
617         if (options && srd_inst_option_set(di, options) != SRD_OK) {
618                 g_free(di->dec_probemap);
619                 g_free(di);
620                 return NULL;
621         }
622
623         /* Instance takes input from a frontend by default. */
624         sess->di_list = g_slist_append(sess->di_list, di);
625
626         return di;
627 }
628
629 /**
630  * Stack a decoder instance on top of another.
631  *
632  * @param sess The session holding the protocol decoder instances.
633  * @param di_from The instance to move.
634  * @param di_to The instance on top of which di_from will be stacked.
635  *
636  * @return SRD_OK upon success, a (negative) error code otherwise.
637  *
638  * @since 0.1.0 (the API changed in 0.3.0, though)
639  */
640 SRD_API int srd_inst_stack(struct srd_session *sess,
641                 struct srd_decoder_inst *di_from, struct srd_decoder_inst *di_to)
642 {
643
644         if (session_is_valid(sess) != SRD_OK) {
645                 srd_err("Invalid session.");
646                 return SRD_ERR_ARG;
647         }
648
649         if (!di_from || !di_to) {
650                 srd_err("Invalid from/to instance pair.");
651                 return SRD_ERR_ARG;
652         }
653
654         if (g_slist_find(sess->di_list, di_to)) {
655                 /* Remove from the unstacked list. */
656                 sess->di_list = g_slist_remove(sess->di_list, di_to);
657         }
658
659         /* Stack on top of source di. */
660         di_from->next_di = g_slist_append(di_from->next_di, di_to);
661
662         return SRD_OK;
663 }
664
665 /**
666  * Find a decoder instance by its instance ID.
667  *
668  * Only the bottom level of instances are searched -- instances already stacked
669  * on top of another one will not be found.
670  *
671  * @param sess The session holding the protocol decoder instance.
672  * @param inst_id The instance ID to be found.
673  *
674  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
675  *
676  * @since 0.1.0 (the API changed in 0.3.0, though)
677  */
678 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
679                 const char *inst_id)
680 {
681         GSList *l;
682         struct srd_decoder_inst *tmp, *di;
683
684         if (session_is_valid(sess) != SRD_OK) {
685                 srd_err("Invalid session.");
686                 return NULL;
687         }
688
689         di = NULL;
690         for (l = sess->di_list; l; l = l->next) {
691                 tmp = l->data;
692                 if (!strcmp(tmp->inst_id, inst_id)) {
693                         di = tmp;
694                         break;
695                 }
696         }
697
698         return di;
699 }
700
701 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
702                 struct srd_session *sess, const GSList *stack,
703                 const PyObject *obj)
704 {
705         const GSList *l;
706         struct srd_decoder_inst *tmp, *di;
707
708         if (session_is_valid(sess) != SRD_OK) {
709                 srd_err("Invalid session.");
710                 return NULL;
711         }
712
713         di = NULL;
714         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
715                 tmp = l->data;
716                 if (tmp->py_inst == obj)
717                         di = tmp;
718                 else if (tmp->next_di)
719                         di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
720         }
721
722         return di;
723 }
724
725 /**
726  * Find a decoder instance by its Python object.
727  *
728  * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
729  * This will recurse to find the instance anywhere in the stack tree of all
730  * sessions.
731  *
732  * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
733  *              stack to search. To start searching at the bottom level of
734  *              decoder instances, pass NULL.
735  * @param obj The Python class instantiation.
736  *
737  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
738  *
739  * @private
740  *
741  * @since 0.1.0
742  */
743 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
744                 const PyObject *obj)
745 {
746         struct srd_decoder_inst *di;
747         struct srd_session *sess;
748         GSList *l;
749
750         di = NULL;
751         for (l = sessions; di == NULL && l != NULL; l = l->next) {
752                 sess = l->data;
753                 di = srd_sess_inst_find_by_obj(sess, stack, obj);
754         }
755
756         return di;
757 }
758
759 /** @private */
760 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di, PyObject *args)
761 {
762         PyObject *py_name, *py_res;
763         GSList *l;
764         struct srd_decoder_inst *next_di;
765
766         srd_dbg("Calling start() method on protocol decoder instance %s.",
767                 di->inst_id);
768
769         if (!(py_name = PyUnicode_FromString("start"))) {
770                 srd_err("Unable to build Python object for 'start'.");
771                 srd_exception_catch("Protocol decoder instance %s: ",
772                                     di->inst_id);
773                 return SRD_ERR_PYTHON;
774         }
775
776         if (!(py_res = PyObject_CallMethodObjArgs(di->py_inst,
777                                                   py_name, args, NULL))) {
778                 srd_exception_catch("Protocol decoder instance %s: ",
779                                     di->inst_id);
780                 return SRD_ERR_PYTHON;
781         }
782
783         Py_DecRef(py_res);
784         Py_DecRef(py_name);
785
786         /*
787          * Start all the PDs stacked on top of this one. Pass along the
788          * metadata all the way from the bottom PD, even though it's only
789          * applicable to logic data for now.
790          */
791         for (l = di->next_di; l; l = l->next) {
792                 next_di = l->data;
793                 srd_inst_start(next_di, args);
794         }
795
796         return SRD_OK;
797 }
798
799 /**
800  * Run the specified decoder function.
801  *
802  * @param start_samplenum The starting sample number for the buffer's sample
803  *                        set, relative to the start of capture.
804  * @param di The decoder instance to call. Must not be NULL.
805  * @param inbuf The buffer to decode. Must not be NULL.
806  * @param inbuflen Length of the buffer. Must be > 0.
807  *
808  * @return SRD_OK upon success, a (negative) error code otherwise.
809  *
810  * @private
811  *
812  * @since 0.1.0
813  */
814 SRD_PRIV int srd_inst_decode(uint64_t start_samplenum,
815                 const struct srd_decoder_inst *di, const uint8_t *inbuf,
816                 uint64_t inbuflen)
817 {
818         PyObject *py_res;
819         srd_logic *logic;
820         uint64_t end_samplenum;
821
822         srd_dbg("Calling decode() on instance %s with %" PRIu64 " bytes "
823                 "starting at sample %" PRIu64 ".", di->inst_id, inbuflen,
824                 start_samplenum);
825
826         /* Return an error upon unusable input. */
827         if (!di) {
828                 srd_dbg("empty decoder instance");
829                 return SRD_ERR_ARG;
830         }
831         if (!inbuf) {
832                 srd_dbg("NULL buffer pointer");
833                 return SRD_ERR_ARG;
834         }
835         if (inbuflen == 0) {
836                 srd_dbg("empty buffer");
837                 return SRD_ERR_ARG;
838         }
839
840         /*
841          * Create new srd_logic object. Each iteration around the PD's loop
842          * will fill one sample into this object.
843          */
844         logic = PyObject_New(srd_logic, &srd_logic_type);
845         Py_INCREF(logic);
846         logic->di = (struct srd_decoder_inst *)di;
847         logic->start_samplenum = start_samplenum;
848         logic->itercnt = 0;
849         logic->inbuf = (uint8_t *)inbuf;
850         logic->inbuflen = inbuflen;
851         logic->sample = PyList_New(2);
852         Py_INCREF(logic->sample);
853
854         Py_IncRef(di->py_inst);
855         end_samplenum = start_samplenum + inbuflen / di->data_unitsize;
856         if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
857                                            "KKO", logic->start_samplenum,
858                                            end_samplenum, logic))) {
859                 srd_exception_catch("Protocol decoder instance %s: ",
860                                     di->inst_id);
861                 return SRD_ERR_PYTHON;
862         }
863         Py_DecRef(py_res);
864
865         return SRD_OK;
866 }
867
868 /** @private */
869 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
870 {
871         GSList *l;
872         struct srd_pd_output *pdo;
873
874         srd_dbg("Freeing instance %s", di->inst_id);
875
876         Py_DecRef(di->py_inst);
877         g_free(di->inst_id);
878         g_free(di->dec_probemap);
879         g_slist_free(di->next_di);
880         for (l = di->pd_output; l; l = l->next) {
881                 pdo = l->data;
882                 g_free(pdo->proto_id);
883                 g_free(pdo);
884         }
885         g_slist_free(di->pd_output);
886         g_free(di);
887 }
888
889 /** @private */
890 SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
891 {
892         GSList *l;
893         struct srd_decoder_inst *di;
894
895         if (session_is_valid(sess) != SRD_OK) {
896                 srd_err("Invalid session.");
897                 return;
898         }
899
900         di = NULL;
901         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
902                 di = l->data;
903                 if (di->next_di)
904                         srd_inst_free_all(sess, di->next_di);
905                 srd_inst_free(di);
906         }
907         if (!stack) {
908                 g_slist_free(sess->di_list);
909                 sess->di_list = NULL;
910         }
911 }
912
913 /** @} */
914
915 /**
916  * @defgroup grp_session Session handling
917  *
918  * Starting and handling decoding sessions.
919  *
920  * @{
921  */
922
923 static int session_is_valid(struct srd_session *sess)
924 {
925
926         if (!sess || sess->session_id < 1)
927                 return SRD_ERR;
928
929         return SRD_OK;
930 }
931
932 /**
933  * Create a decoding session.
934  *
935  * A session holds all decoder instances, their stack relationships and
936  * output callbacks.
937  *
938  * @param sess A pointer which will hold a pointer to a newly
939  *             initialized session on return.
940  *
941  * @return SRD_OK upon success, a (negative) error code otherwise.
942  *
943  * @since 0.3.0
944  */
945 SRD_API int srd_session_new(struct srd_session **sess)
946 {
947
948         if (!sess) {
949                 srd_err("Invalid session pointer.");
950                 return SRD_ERR_ARG;
951         }
952
953         if (!(*sess = g_try_malloc(sizeof(struct srd_session))))
954                 return SRD_ERR_MALLOC;
955         (*sess)->session_id = ++max_session_id;
956         (*sess)->num_probes = (*sess)->unitsize = (*sess)->samplerate = 0;
957         (*sess)->di_list = (*sess)->callbacks = NULL;
958
959         /* Keep a list of all sessions, so we can clean up as needed. */
960         sessions = g_slist_append(sessions, *sess);
961
962         srd_dbg("Created session %d.", (*sess)->session_id);
963
964         return SRD_OK;
965 }
966
967 /**
968  * Start a decoding session.
969  *
970  * Decoders, instances and stack must have been prepared beforehand,
971  * and all SRD_CONF parameters set.
972  *
973  * @param sess The session to start.
974  *
975  * @return SRD_OK upon success, a (negative) error code otherwise.
976  *
977  * @since 0.1.0 (the API changed in 0.3.0, though)
978  */
979 SRD_API int srd_session_start(struct srd_session *sess)
980 {
981         PyObject *args;
982         GSList *d;
983         struct srd_decoder_inst *di;
984         int ret;
985
986         if (session_is_valid(sess) != SRD_OK) {
987                 srd_err("Invalid session pointer.");
988                 return SRD_ERR;
989         }
990         if (sess->num_probes == 0) {
991                 srd_err("Session has invalid number of probes.");
992                 return SRD_ERR;
993         }
994         if (sess->unitsize == 0) {
995                 srd_err("Session has invalid unitsize.");
996                 return SRD_ERR;
997         }
998         if (sess->samplerate == 0) {
999                 srd_err("Session has invalid samplerate.");
1000                 return SRD_ERR;
1001         }
1002
1003         ret = SRD_OK;
1004
1005         srd_dbg("Calling start() on all instances in session %d with "
1006                         "%" PRIu64 " probes, unitsize %" PRIu64
1007                         ", samplerate %" PRIu64 ".", sess->session_id,
1008                         sess->num_probes, sess->unitsize, sess->samplerate);
1009
1010         /*
1011          * Currently only one item of metadata is passed along to decoders,
1012          * samplerate. This can be extended as needed.
1013          */
1014         if (!(args = Py_BuildValue("{s:l}", "samplerate", (long)sess->samplerate))) {
1015                 srd_err("Unable to build Python object for metadata.");
1016                 return SRD_ERR_PYTHON;
1017         }
1018
1019         /* Run the start() method on all decoders receiving frontend data. */
1020         for (d = sess->di_list; d; d = d->next) {
1021                 di = d->data;
1022                 di->data_num_probes = sess->num_probes;
1023                 di->data_unitsize = sess->unitsize;
1024                 di->data_samplerate = sess->samplerate;
1025                 if ((ret = srd_inst_start(di, args)) != SRD_OK)
1026                         break;
1027         }
1028
1029         Py_DecRef(args);
1030
1031         return ret;
1032 }
1033
1034 /**
1035  * Set a configuration key in a session.
1036  *
1037  * @param sess The session to configure.
1038  * @param key The configuration key (SRD_CONF_*).
1039  * @param data The new value for the key, as a GVariant with GVariantType
1040  *             appropriate to that key. A floating reference can be passed
1041  *             in; its refcount will be sunk and unreferenced after use.
1042  *
1043  * @return SRD_OK upon success, a (negative) error code otherwise.
1044  *
1045  * @since 0.3.0
1046  */
1047 SRD_API int srd_session_config_set(struct srd_session *sess, int key,
1048                 GVariant *data)
1049 {
1050
1051         if (session_is_valid(sess) != SRD_OK) {
1052                 srd_err("Invalid session.");
1053                 return SRD_ERR_ARG;
1054         }
1055
1056         if (!data) {
1057                 srd_err("Invalid config data.");
1058                 return SRD_ERR_ARG;
1059         }
1060
1061         if (!g_variant_is_of_type(data, G_VARIANT_TYPE_UINT64)) {
1062                 srd_err("Value for key %d should be of type uint64.", key);
1063                 return SRD_ERR_ARG;
1064         }
1065
1066         switch (key) {
1067         case SRD_CONF_NUM_PROBES:
1068                 sess->num_probes = g_variant_get_uint64(data);
1069                 break;
1070         case SRD_CONF_UNITSIZE:
1071                 sess->unitsize = g_variant_get_uint64(data);
1072                 break;
1073         case SRD_CONF_SAMPLERATE:
1074                 sess->samplerate = g_variant_get_uint64(data);
1075                 break;
1076         default:
1077                 srd_err("Cannot set config for unknown key %d.", key);
1078                 return SRD_ERR_ARG;
1079         }
1080
1081         g_variant_unref(data);
1082
1083         return SRD_OK;
1084 }
1085
1086 /**
1087  * Send a chunk of logic sample data to a running decoder session.
1088  *
1089  * @param sess The session to use.
1090  * @param start_samplenum The sample number of the first sample in this chunk.
1091  * @param inbuf Pointer to sample data.
1092  * @param inbuflen Length in bytes of the buffer.
1093  *
1094  * @return SRD_OK upon success, a (negative) error code otherwise.
1095  *
1096  * @since 0.1.0
1097  */
1098 SRD_API int srd_session_send(struct srd_session *sess, uint64_t start_samplenum,
1099                 const uint8_t *inbuf, uint64_t inbuflen)
1100 {
1101         GSList *d;
1102         int ret;
1103
1104         if (session_is_valid(sess) != SRD_OK) {
1105                 srd_err("Invalid session.");
1106                 return SRD_ERR_ARG;
1107         }
1108
1109         srd_dbg("Calling decode() on all instances with starting sample "
1110                 "number %" PRIu64 ", %" PRIu64 " bytes at 0x%p",
1111                 start_samplenum, inbuflen, inbuf);
1112
1113         for (d = sess->di_list; d; d = d->next) {
1114                 if ((ret = srd_inst_decode(start_samplenum, d->data, inbuf,
1115                                            inbuflen)) != SRD_OK)
1116                         return ret;
1117         }
1118
1119         return SRD_OK;
1120 }
1121
1122 /**
1123  * Destroy a decoding session.
1124  *
1125  * All decoder instances and output callbacks are properly released.
1126  *
1127  * @param sess The session to be destroyed.
1128  *
1129  * @return SRD_OK upon success, a (negative) error code otherwise.
1130  *
1131  * @since 0.3.0
1132  */
1133 SRD_API int srd_session_destroy(struct srd_session *sess)
1134 {
1135         int session_id;
1136
1137         if (!sess) {
1138                 srd_err("Invalid session.");
1139                 return SRD_ERR_ARG;
1140         }
1141
1142         session_id = sess->session_id;
1143         if (sess->di_list)
1144                 srd_inst_free_all(sess, NULL);
1145         if (sess->callbacks)
1146                 g_slist_free_full(sess->callbacks, g_free);
1147         sessions = g_slist_remove(sessions, sess);
1148         g_free(sess);
1149
1150         srd_dbg("Destroyed session %d.", session_id);
1151
1152         return SRD_OK;
1153 }
1154
1155 /**
1156  * Register/add a decoder output callback function.
1157  *
1158  * The function will be called when a protocol decoder sends output back
1159  * to the PD controller (except for Python objects, which only go up the
1160  * stack).
1161  *
1162  * @param sess The output session in which to register the callback.
1163  * @param output_type The output type this callback will receive. Only one
1164  *                    callback per output type can be registered.
1165  * @param cb The function to call. Must not be NULL.
1166  * @param cb_data Private data for the callback function. Can be NULL.
1167  *
1168  * @since 0.1.0 (the API changed in 0.3.0, though)
1169  */
1170 SRD_API int srd_pd_output_callback_add(struct srd_session *sess,
1171                 int output_type, srd_pd_output_callback_t cb, void *cb_data)
1172 {
1173         struct srd_pd_callback *pd_cb;
1174
1175         if (session_is_valid(sess) != SRD_OK) {
1176                 srd_err("Invalid session.");
1177                 return SRD_ERR_ARG;
1178         }
1179
1180         srd_dbg("Registering new callback for output type %d.", output_type);
1181
1182         if (!(pd_cb = g_try_malloc(sizeof(struct srd_pd_callback)))) {
1183                 srd_err("Failed to g_malloc() struct srd_pd_callback.");
1184                 return SRD_ERR_MALLOC;
1185         }
1186
1187         pd_cb->output_type = output_type;
1188         pd_cb->cb = cb;
1189         pd_cb->cb_data = cb_data;
1190         sess->callbacks = g_slist_append(sess->callbacks, pd_cb);
1191
1192         return SRD_OK;
1193 }
1194
1195 /** @private */
1196 SRD_PRIV struct srd_pd_callback *srd_pd_output_callback_find(
1197                 struct srd_session *sess, int output_type)
1198 {
1199         GSList *l;
1200         struct srd_pd_callback *tmp, *pd_cb;
1201
1202         if (session_is_valid(sess) != SRD_OK) {
1203                 srd_err("Invalid session.");
1204                 return NULL;
1205         }
1206
1207         pd_cb = NULL;
1208         for (l = sess->callbacks; l; l = l->next) {
1209                 tmp = l->data;
1210                 if (tmp->output_type == output_type) {
1211                         pd_cb = tmp;
1212                         break;
1213                 }
1214         }
1215
1216         return pd_cb;
1217 }
1218
1219 /* This is the backend function to Python sigrokdecode.add() call. */
1220 /** @private */
1221 SRD_PRIV int srd_inst_pd_output_add(struct srd_decoder_inst *di,
1222                                     int output_type, const char *proto_id)
1223 {
1224         struct srd_pd_output *pdo;
1225
1226         srd_dbg("Instance %s creating new output type %d for %s.",
1227                 di->inst_id, output_type, proto_id);
1228
1229         if (!(pdo = g_try_malloc(sizeof(struct srd_pd_output)))) {
1230                 srd_err("Failed to g_malloc() struct srd_pd_output.");
1231                 return -1;
1232         }
1233
1234         /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
1235         pdo->pdo_id = g_slist_length(di->pd_output);
1236         pdo->output_type = output_type;
1237         pdo->di = di;
1238         pdo->proto_id = g_strdup(proto_id);
1239         di->pd_output = g_slist_append(di->pd_output, pdo);
1240
1241         return pdo->pdo_id;
1242 }
1243
1244 /** @} */