]> sigrok.org Git - libsigrokdecode.git/blame - controller.c
Move session-specific functionality into session.c
[libsigrokdecode.git] / controller.c
CommitLineData
b2c19614 1/*
50bd5d25 2 * This file is part of the libsigrokdecode project.
b2c19614
BV
3 *
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
bc5f5a43 5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
b2c19614
BV
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
c1f86f02
UH
21#include "libsigrokdecode.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22#include "libsigrokdecode-internal.h"
7ce7775c 23#include "config.h"
b2c19614 24#include <glib.h>
1aef2f93 25#include <inttypes.h>
0bdadba2 26#include <stdlib.h>
32cfb920 27#include <stdint.h>
b2c19614 28
d7dae84b
UH
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
32cfb920 90/** @cond PRIVATE */
d906d3f9 91
fe9d91a8
BV
92extern GSList *sessions;
93extern int max_session_id;
57790bc8 94
c9bfccc6 95/* decoder.c */
55c3c5f4 96extern SRD_PRIV GSList *pd_list;
b2c19614 97
c9bfccc6 98/* module_sigrokdecode.c */
53a07a6d 99extern PyMODINIT_FUNC PyInit_sigrokdecode(void);
b2c19614 100
c9bfccc6 101/* type_logic.c */
55c3c5f4 102extern SRD_PRIV PyTypeObject srd_logic_type;
b2c19614 103
57790bc8
UH
104/** @endcond */
105
b2c19614
BV
106/**
107 * Initialize libsigrokdecode.
108 *
109 * This initializes the Python interpreter, and creates and initializes
361fdcaa 110 * a "sigrokdecode" Python module.
b2c19614 111 *
4cc0d9fe
UH
112 * Then, it searches for sigrok protocol decoders in the "decoders"
113 * subdirectory of the the libsigrokdecode installation directory.
b2c19614 114 * All decoders that are found are loaded into memory and added to an
4cc0d9fe 115 * internal list of decoders, which can be queried via srd_decoder_list().
b2c19614
BV
116 *
117 * The caller is responsible for calling the clean-up function srd_exit(),
118 * which will properly shut down libsigrokdecode and free its allocated memory.
119 *
7ce7775c 120 * Multiple calls to srd_init(), without calling srd_exit() in between,
b2c19614
BV
121 * are not allowed.
122 *
65e1c7d0 123 * @param path Path to an extra directory containing protocol decoders
4cc0d9fe 124 * which will be added to the Python sys.path. May be NULL.
65e1c7d0 125 *
b2c19614 126 * @return SRD_OK upon success, a (negative) error code otherwise.
4cc0d9fe
UH
127 * Upon Python errors, SRD_ERR_PYTHON is returned. If the decoders
128 * directory cannot be accessed, SRD_ERR_DECODERS_DIR is returned.
129 * If not enough memory could be allocated, SRD_ERR_MALLOC is returned.
8c664ca2
UH
130 *
131 * @since 0.1.0
b2c19614 132 */
abeeed8b 133SRD_API int srd_init(const char *path)
b2c19614
BV
134{
135 int ret;
65e1c7d0 136 char *env_path;
b2c19614 137
32cfb920
BV
138 if (max_session_id != -1) {
139 srd_err("libsigrokdecode is already initialized.");
140 return SRD_ERR;
141 }
142
7a1712c4 143 srd_dbg("Initializing libsigrokdecode.");
d906d3f9
BV
144
145 /* Add our own module to the list of built-in modules. */
bc5f5a43 146 PyImport_AppendInittab("sigrokdecode", PyInit_sigrokdecode);
5f802ec6 147
511e2123 148 /* Initialize the Python interpreter. */
b2c19614
BV
149 Py_Initialize();
150
65e1c7d0 151 /* Installed decoders. */
aafeeaea 152 if ((ret = srd_decoder_searchpath_add(DECODERS_DIR)) != SRD_OK) {
b2c19614
BV
153 Py_Finalize();
154 return ret;
155 }
156
65e1c7d0
BV
157 /* Path specified by the user. */
158 if (path) {
aafeeaea 159 if ((ret = srd_decoder_searchpath_add(path)) != SRD_OK) {
65e1c7d0
BV
160 Py_Finalize();
161 return ret;
162 }
163 }
164
165 /* Environment variable overrides everything, for debugging. */
166 if ((env_path = getenv("SIGROKDECODE_DIR"))) {
aafeeaea 167 if ((ret = srd_decoder_searchpath_add(env_path)) != SRD_OK) {
65e1c7d0
BV
168 Py_Finalize();
169 return ret;
170 }
171 }
172
32cfb920
BV
173 max_session_id = 0;
174
b2c19614
BV
175 return SRD_OK;
176}
177
b2c19614
BV
178/**
179 * Shutdown libsigrokdecode.
180 *
181 * This frees all the memory allocated for protocol decoders and shuts down
182 * the Python interpreter.
183 *
184 * This function should only be called if there was a (successful!) invocation
185 * of srd_init() before. Calling this function multiple times in a row, without
7ce7775c 186 * any successful srd_init() calls in between, is not allowed.
b2c19614
BV
187 *
188 * @return SRD_OK upon success, a (negative) error code otherwise.
8c664ca2
UH
189 *
190 * @since 0.1.0
b2c19614 191 */
55c3c5f4 192SRD_API int srd_exit(void)
b2c19614 193{
32cfb920
BV
194 GSList *l;
195
7a1712c4 196 srd_dbg("Exiting libsigrokdecode.");
d906d3f9 197
32cfb920
BV
198 for (l = sessions; l; l = l->next)
199 srd_session_destroy((struct srd_session *)l->data);
200
8ad6e500 201 srd_decoder_unload_all();
e5080882 202 g_slist_free(pd_list);
96c52595 203 pd_list = NULL;
b2c19614
BV
204
205 /* Py_Finalize() returns void, any finalization errors are ignored. */
206 Py_Finalize();
207
32cfb920
BV
208 max_session_id = -1;
209
b2c19614
BV
210 return SRD_OK;
211}
212
b2c19614 213/**
9d9fcb37
UH
214 * Add an additional search directory for the protocol decoders.
215 *
216 * The specified directory is prepended (not appended!) to Python's sys.path,
217 * in order to search for sigrok protocol decoders in the specified
218 * directories first, and in the generic Python module directories (and in
219 * the current working directory) last. This avoids conflicts if there are
220 * Python modules which have the same name as a sigrok protocol decoder in
221 * sys.path or in the current working directory.
b2c19614 222 *
361fdcaa
UH
223 * @param path Path to the directory containing protocol decoders which shall
224 * be added to the Python sys.path, or NULL.
9d9fcb37 225 *
65e1c7d0 226 * @return SRD_OK upon success, a (negative) error code otherwise.
57790bc8
UH
227 *
228 * @private
8c664ca2
UH
229 *
230 * @since 0.1.0
b2c19614 231 */
aafeeaea 232SRD_PRIV int srd_decoder_searchpath_add(const char *path)
b2c19614 233{
65e1c7d0
BV
234 PyObject *py_cur_path, *py_item;
235 GString *new_path;
236 int wc_len, i;
237 wchar_t *wc_new_path;
238 char *item;
239
8ad6e500 240 srd_dbg("Adding '%s' to module path.", path);
65e1c7d0
BV
241
242 new_path = g_string_sized_new(256);
e592ac89 243 g_string_assign(new_path, path);
65e1c7d0
BV
244 py_cur_path = PySys_GetObject("path");
245 for (i = 0; i < PyList_Size(py_cur_path); i++) {
e592ac89 246 g_string_append(new_path, G_SEARCHPATH_SEPARATOR_S);
65e1c7d0
BV
247 py_item = PyList_GetItem(py_cur_path, i);
248 if (!PyUnicode_Check(py_item))
249 /* Shouldn't happen. */
250 continue;
251 if (py_str_as_str(py_item, &item) != SRD_OK)
252 continue;
253 g_string_append(new_path, item);
e592ac89 254 g_free(item);
65e1c7d0 255 }
639c5689 256
65e1c7d0
BV
257 /* Convert to wide chars. */
258 wc_len = sizeof(wchar_t) * (new_path->len + 1);
259 if (!(wc_new_path = g_try_malloc(wc_len))) {
260 srd_dbg("malloc failed");
261 return SRD_ERR_MALLOC;
262 }
263 mbstowcs(wc_new_path, new_path->str, wc_len);
264 PySys_SetPath(wc_new_path);
265 g_string_free(new_path, TRUE);
266 g_free(wc_new_path);
267
65e1c7d0 268 return SRD_OK;
b2c19614
BV
269}
270
4895418c
UH
271/** @} */
272
273/**
274 * @defgroup grp_instances Decoder instances
275 *
276 * Decoder instance handling.
277 *
278 * @{
279 */
280
7ce7775c 281/**
b33b8aa5 282 * Set one or more options in a decoder instance.
0bdadba2 283 *
361fdcaa
UH
284 * Handled options are removed from the hash.
285 *
0bdadba2
BV
286 * @param di Decoder instance.
287 * @param options A GHashTable of options to set.
7ce7775c 288 *
0bdadba2 289 * @return SRD_OK upon success, a (negative) error code otherwise.
8c664ca2
UH
290 *
291 * @since 0.1.0
0bdadba2 292 */
b33b8aa5 293SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
0ff2d191 294 GHashTable *options)
0bdadba2
BV
295{
296 PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
297 PyObject *py_optlist, *py_classval;
298 Py_UNICODE *py_ustr;
2f395bff 299 GVariant *value;
0bdadba2 300 unsigned long long int val_ull;
2f395bff 301 gint64 val_int;
0bdadba2 302 int num_optkeys, ret, size, i;
2f395bff
BV
303 const char *val_str;
304 char *dbg, *key;
0bdadba2 305
3af0e345
UH
306 if (!di) {
307 srd_err("Invalid decoder instance.");
308 return SRD_ERR_ARG;
309 }
310
311 if (!options) {
312 srd_err("Invalid options GHashTable.");
313 return SRD_ERR_ARG;
314 }
315
c9bfccc6 316 if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
0bdadba2 317 /* Decoder has no options. */
e431d9cc
BV
318 if (g_hash_table_size(options) == 0) {
319 /* No options provided. */
320 return SRD_OK;
321 } else {
322 srd_err("Protocol decoder has no options.");
323 return SRD_ERR_ARG;
324 }
0bdadba2 325 return SRD_OK;
e431d9cc 326 }
0bdadba2
BV
327
328 ret = SRD_ERR_PYTHON;
329 key = NULL;
330 py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
331 py_optlist = py_classval = NULL;
332 py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");
0bdadba2
BV
333
334 /* All of these are synthesized objects, so they're good. */
335 py_dec_optkeys = PyDict_Keys(py_dec_options);
336 num_optkeys = PyList_Size(py_dec_optkeys);
119d6258
BV
337
338 /*
339 * The 'options' dictionary is a class variable, but we need to
340 * change it. Changing it directly will affect the entire class,
341 * so we need to create a new object for it, and populate that
342 * instead.
343 */
a8b72b05 344 if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
0bdadba2 345 goto err_out;
119d6258
BV
346 Py_DECREF(py_di_options);
347 py_di_options = PyDict_New();
348 PyObject_SetAttrString(di->py_inst, "options", py_di_options);
0bdadba2
BV
349 for (i = 0; i < num_optkeys; i++) {
350 /* Get the default class value for this option. */
351 py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
352 if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
353 goto err_out;
354 if (!(py_classval = PyList_GetItem(py_optlist, 1)))
355 goto err_out;
130ef08a 356 if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
c9bfccc6
UH
357 srd_err("Options of type %s are not yet supported.",
358 Py_TYPE(py_classval)->tp_name);
130ef08a
BV
359 goto err_out;
360 }
0bdadba2
BV
361
362 if ((value = g_hash_table_lookup(options, key))) {
2f395bff
BV
363 dbg = g_variant_print(value, TRUE);
364 srd_dbg("got option '%s' = %s", key, dbg);
365 g_free(dbg);
0bdadba2
BV
366 /* An override for this option was provided. */
367 if (PyUnicode_Check(py_classval)) {
2f395bff
BV
368 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
369 srd_err("Option '%s' requires a string value.", key);
370 goto err_out;
371 }
372 val_str = g_variant_get_string(value, NULL);
373 if (!(py_optval = PyUnicode_FromString(val_str))) {
0bdadba2
BV
374 /* Some UTF-8 encoding error. */
375 PyErr_Clear();
2f395bff 376 srd_err("Option '%s' requires a UTF-8 string value.", key);
0bdadba2
BV
377 goto err_out;
378 }
379 } else if (PyLong_Check(py_classval)) {
2f395bff
BV
380 if (!g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
381 srd_err("Option '%s' requires an integer value.", key);
382 goto err_out;
383 }
384 val_int = g_variant_get_int64(value);
385 if (!(py_optval = PyLong_FromLong(val_int))) {
0bdadba2
BV
386 /* ValueError Exception */
387 PyErr_Clear();
2f395bff 388 srd_err("Option '%s' has invalid integer value.", key);
0bdadba2
BV
389 goto err_out;
390 }
391 }
392 g_hash_table_remove(options, key);
393 } else {
394 /* Use the class default for this option. */
395 if (PyUnicode_Check(py_classval)) {
396 /* Make a brand new copy of the string. */
397 py_ustr = PyUnicode_AS_UNICODE(py_classval);
398 size = PyUnicode_GET_SIZE(py_classval);
399 py_optval = PyUnicode_FromUnicode(py_ustr, size);
400 } else if (PyLong_Check(py_classval)) {
401 /* Make a brand new copy of the integer. */
402 val_ull = PyLong_AsUnsignedLongLong(py_classval);
403 if (val_ull == (unsigned long long)-1) {
404 /* OverFlowError exception */
405 PyErr_Clear();
c9bfccc6
UH
406 srd_err("Invalid integer value for %s: "
407 "expected integer.", key);
0bdadba2
BV
408 goto err_out;
409 }
410 if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
411 goto err_out;
412 }
413 }
414
361fdcaa
UH
415 /*
416 * If we got here, py_optval holds a known good new reference
0bdadba2
BV
417 * to the instance option to set.
418 */
419 if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
420 goto err_out;
e592ac89 421 g_free(key);
b88e336b 422 key = NULL;
0bdadba2
BV
423 }
424
425 ret = SRD_OK;
426
427err_out:
0bdadba2
BV
428 Py_XDECREF(py_di_options);
429 Py_XDECREF(py_dec_optkeys);
430 Py_XDECREF(py_dec_options);
6f858319 431 g_free(key);
7fc7bde6 432 if (PyErr_Occurred()) {
aafeeaea 433 srd_exception_catch("Stray exception in srd_inst_option_set().");
7fc7bde6
BV
434 ret = SRD_ERR_PYTHON;
435 }
0bdadba2
BV
436
437 return ret;
438}
439
b33b8aa5 440/* Helper GComparefunc for g_slist_find_custom() in srd_inst_probe_set_all() */
abeeed8b 441static gint compare_probe_id(const struct srd_probe *a, const char *probe_id)
f38ec285 442{
f38ec285
BV
443 return strcmp(a->id, probe_id);
444}
445
0bdadba2 446/**
b33b8aa5
UH
447 * Set all probes in a decoder instance.
448 *
449 * This function sets _all_ probes for the specified decoder instance, i.e.,
450 * it overwrites any probes that were already defined (if any).
0bdadba2
BV
451 *
452 * @param di Decoder instance.
38ff5046
UH
453 * @param new_probes A GHashTable of probes to set. Key is probe name, value is
454 * the probe number. Samples passed to this instance will be
455 * arranged in this order.
12243c22 456 *
0bdadba2 457 * @return SRD_OK upon success, a (negative) error code otherwise.
8c664ca2
UH
458 *
459 * @since 0.1.0
0bdadba2 460 */
b33b8aa5 461SRD_API int srd_inst_probe_set_all(struct srd_decoder_inst *di,
0ff2d191 462 GHashTable *new_probes)
0bdadba2 463{
2f395bff 464 GVariant *probe_val;
f38ec285
BV
465 GList *l;
466 GSList *sl;
467 struct srd_probe *p;
ed416497 468 int *new_probemap, new_probenum, num_required_probes, num_probes, i;
2f395bff 469 char *probe_id;
0bdadba2 470
ce46beed 471 srd_dbg("set probes called for instance %s with list of %d probes",
a8b72b05 472 di->inst_id, g_hash_table_size(new_probes));
ce46beed 473
f38ec285 474 if (g_hash_table_size(new_probes) == 0)
0bdadba2
BV
475 /* No probes provided. */
476 return SRD_OK;
477
c9bfccc6 478 if (di->dec_num_probes == 0) {
0bdadba2 479 /* Decoder has no probes. */
f38ec285 480 srd_err("Protocol decoder %s has no probes to define.",
c9bfccc6 481 di->decoder->name);
f38ec285
BV
482 return SRD_ERR_ARG;
483 }
0bdadba2 484
f38ec285 485 new_probemap = NULL;
0bdadba2 486
f38ec285 487 if (!(new_probemap = g_try_malloc(sizeof(int) * di->dec_num_probes))) {
a61ece20 488 srd_err("Failed to g_malloc() new probe map.");
f38ec285 489 return SRD_ERR_MALLOC;
0bdadba2
BV
490 }
491
38ff5046
UH
492 /*
493 * For now, map all indexes to probe -1 (can be overridden later).
494 * This -1 is interpreted as an unspecified probe later.
495 */
496 for (i = 0; i < di->dec_num_probes; i++)
497 new_probemap[i] = -1;
498
ed416497 499 num_probes = 0;
f38ec285
BV
500 for (l = g_hash_table_get_keys(new_probes); l; l = l->next) {
501 probe_id = l->data;
69075817 502 probe_val = g_hash_table_lookup(new_probes, probe_id);
2f395bff 503 if (!g_variant_is_of_type(probe_val, G_VARIANT_TYPE_INT32)) {
be873260 504 /* Probe name was specified without a value. */
c9bfccc6 505 srd_err("No probe number was specified for %s.",
2f395bff 506 probe_id);
be873260
BV
507 g_free(new_probemap);
508 return SRD_ERR_ARG;
509 }
2f395bff 510 new_probenum = g_variant_get_int32(probe_val);
f38ec285
BV
511 if (!(sl = g_slist_find_custom(di->decoder->probes, probe_id,
512 (GCompareFunc)compare_probe_id))) {
513 /* Fall back on optional probes. */
dcdf4883 514 if (!(sl = g_slist_find_custom(di->decoder->opt_probes,
c9bfccc6
UH
515 probe_id, (GCompareFunc) compare_probe_id))) {
516 srd_err("Protocol decoder %s has no probe "
2f395bff 517 "'%s'.", di->decoder->name, probe_id);
f38ec285
BV
518 g_free(new_probemap);
519 return SRD_ERR_ARG;
520 }
521 }
522 p = sl->data;
523 new_probemap[p->order] = new_probenum;
38ff5046
UH
524 srd_dbg("Setting probe mapping: %s (index %d) = probe %d.",
525 p->id, p->order, new_probenum);
ed416497 526 num_probes++;
38ff5046 527 }
ed416497 528 di->data_unitsize = (num_probes + 7) / 8;
38ff5046
UH
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");
f38ec285 535 }
38ff5046 536
f38ec285
BV
537 g_free(di->dec_probemap);
538 di->dec_probemap = new_probemap;
0bdadba2 539
f38ec285 540 return SRD_OK;
0bdadba2
BV
541}
542
543/**
544 * Create a new protocol decoder instance.
7ce7775c 545 *
32cfb920 546 * @param sess The session holding the protocol decoder instance.
38ff5046 547 * @param decoder_id Decoder 'id' field.
0bdadba2 548 * @param options GHashtable of options which override the defaults set in
38ff5046 549 * the decoder class. May be NULL.
12243c22 550 *
a8b72b05 551 * @return Pointer to a newly allocated struct srd_decoder_inst, or
c9bfccc6 552 * NULL in case of failure.
8c664ca2 553 *
69075817 554 * @since 0.3.0
7ce7775c 555 */
32cfb920
BV
556SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
557 const char *decoder_id, GHashTable *options)
b2c19614 558{
c9bfccc6 559 int i;
b2c19614 560 struct srd_decoder *dec;
a8b72b05
BV
561 struct srd_decoder_inst *di;
562 char *inst_id;
b2c19614 563
7a1712c4 564 srd_dbg("Creating new %s instance.", decoder_id);
7ce7775c 565
32cfb920
BV
566 if (session_is_valid(sess) != SRD_OK) {
567 srd_err("Invalid session.");
568 return NULL;
569 }
570
9d122fd5 571 if (!(dec = srd_decoder_get_by_id(decoder_id))) {
0bdadba2 572 srd_err("Protocol decoder %s not found.", decoder_id);
b2c19614 573 return NULL;
0bdadba2 574 }
b2c19614 575
a8b72b05 576 if (!(di = g_try_malloc0(sizeof(struct srd_decoder_inst)))) {
a61ece20 577 srd_err("Failed to g_malloc() instance.");
7ce7775c
BV
578 return NULL;
579 }
0bdadba2 580
b2c19614 581 di->decoder = dec;
32cfb920 582 di->sess = sess;
38ff5046
UH
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);
b2c19614 589
361fdcaa
UH
590 /*
591 * Prepare a default probe map, where samples come in the
f38ec285
BV
592 * order in which the decoder class defined them.
593 */
594 di->dec_num_probes = g_slist_length(di->decoder->probes) +
69075817 595 g_slist_length(di->decoder->opt_probes);
19a90bab 596 if (di->dec_num_probes) {
c9bfccc6 597 if (!(di->dec_probemap =
69075817 598 g_try_malloc(sizeof(int) * di->dec_num_probes))) {
a61ece20 599 srd_err("Failed to g_malloc() probe map.");
19a90bab
BV
600 g_free(di);
601 return NULL;
602 }
603 for (i = 0; i < di->dec_num_probes; i++)
604 di->dec_probemap[i] = i;
f38ec285 605 }
ed416497 606 di->data_unitsize = (di->dec_num_probes + 7) / 8;
f38ec285 607
0bdadba2 608 /* Create a new instance of this decoder class. */
a8b72b05 609 if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
b2c19614 610 if (PyErr_Occurred())
aafeeaea 611 srd_exception_catch("failed to create %s instance: ",
69075817 612 decoder_id);
f38ec285 613 g_free(di->dec_probemap);
0bdadba2 614 g_free(di);
7ce7775c 615 return NULL;
b2c19614 616 }
7ce7775c 617
38ff5046 618 if (options && srd_inst_option_set(di, options) != SRD_OK) {
f38ec285 619 g_free(di->dec_probemap);
0bdadba2
BV
620 g_free(di);
621 return NULL;
622 }
b2c19614 623
f38ec285 624 /* Instance takes input from a frontend by default. */
32cfb920 625 sess->di_list = g_slist_append(sess->di_list, di);
f38ec285 626
b2c19614
BV
627 return di;
628}
629
582c8473
BV
630/**
631 * Stack a decoder instance on top of another.
632 *
32cfb920 633 * @param sess The session holding the protocol decoder instances.
582c8473
BV
634 * @param di_from The instance to move.
635 * @param di_to The instance on top of which di_from will be stacked.
636 *
637 * @return SRD_OK upon success, a (negative) error code otherwise.
8c664ca2 638 *
69075817 639 * @since 0.3.0
582c8473 640 */
32cfb920
BV
641SRD_API int srd_inst_stack(struct srd_session *sess,
642 struct srd_decoder_inst *di_from, struct srd_decoder_inst *di_to)
7ce7775c 643{
32cfb920
BV
644
645 if (session_is_valid(sess) != SRD_OK) {
646 srd_err("Invalid session.");
647 return SRD_ERR_ARG;
648 }
649
7ce7775c 650 if (!di_from || !di_to) {
d906d3f9 651 srd_err("Invalid from/to instance pair.");
7ce7775c
BV
652 return SRD_ERR_ARG;
653 }
654
32cfb920 655 if (g_slist_find(sess->di_list, di_to)) {
2072ae0c 656 /* Remove from the unstacked list. */
32cfb920 657 sess->di_list = g_slist_remove(sess->di_list, di_to);
7ce7775c
BV
658 }
659
7ce7775c
BV
660 /* Stack on top of source di. */
661 di_from->next_di = g_slist_append(di_from->next_di, di_to);
662
663 return SRD_OK;
664}
665
2072ae0c 666/**
361fdcaa
UH
667 * Find a decoder instance by its instance ID.
668 *
669 * Only the bottom level of instances are searched -- instances already stacked
670 * on top of another one will not be found.
2072ae0c 671 *
32cfb920 672 * @param sess The session holding the protocol decoder instance.
ed2306a6 673 * @param inst_id The instance ID to be found.
2072ae0c 674 *
a8b72b05 675 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
8c664ca2 676 *
69075817 677 * @since 0.3.0
2072ae0c 678 */
32cfb920
BV
679SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
680 const char *inst_id)
7ce7775c
BV
681{
682 GSList *l;
a8b72b05 683 struct srd_decoder_inst *tmp, *di;
b2c19614 684
32cfb920
BV
685 if (session_is_valid(sess) != SRD_OK) {
686 srd_err("Invalid session.");
687 return NULL;
688 }
689
7ce7775c 690 di = NULL;
32cfb920 691 for (l = sess->di_list; l; l = l->next) {
7ce7775c 692 tmp = l->data;
a8b72b05 693 if (!strcmp(tmp->inst_id, inst_id)) {
7ce7775c
BV
694 di = tmp;
695 break;
696 }
697 }
698
699 return di;
700}
701
32cfb920
BV
702static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
703 struct srd_session *sess, const GSList *stack,
704 const PyObject *obj)
705{
706 const GSList *l;
707 struct srd_decoder_inst *tmp, *di;
708
709 if (session_is_valid(sess) != SRD_OK) {
710 srd_err("Invalid session.");
711 return NULL;
712 }
713
714 di = NULL;
715 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
716 tmp = l->data;
717 if (tmp->py_inst == obj)
718 di = tmp;
719 else if (tmp->next_di)
720 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
721 }
722
723 return di;
724}
725
2072ae0c 726/**
361fdcaa
UH
727 * Find a decoder instance by its Python object.
728 *
729 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
32cfb920
BV
730 * This will recurse to find the instance anywhere in the stack tree of all
731 * sessions.
2072ae0c 732 *
361fdcaa
UH
733 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
734 * stack to search. To start searching at the bottom level of
735 * decoder instances, pass NULL.
511e2123 736 * @param obj The Python class instantiation.
2072ae0c 737 *
a8b72b05 738 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
57790bc8
UH
739 *
740 * @private
8c664ca2
UH
741 *
742 * @since 0.1.0
2072ae0c 743 */
abeeed8b 744SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
0ff2d191 745 const PyObject *obj)
2072ae0c 746{
32cfb920
BV
747 struct srd_decoder_inst *di;
748 struct srd_session *sess;
749 GSList *l;
2072ae0c
BV
750
751 di = NULL;
32cfb920
BV
752 for (l = sessions; di == NULL && l != NULL; l = l->next) {
753 sess = l->data;
754 di = srd_sess_inst_find_by_obj(sess, stack, obj);
2072ae0c
BV
755 }
756
757 return di;
758}
759
57790bc8 760/** @private */
ed416497 761SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
b2c19614 762{
ed416497 763 PyObject *py_res;
2072ae0c 764 GSList *l;
a8b72b05 765 struct srd_decoder_inst *next_di;
ed416497 766 int ret;
b2c19614 767
7a1712c4 768 srd_dbg("Calling start() method on protocol decoder instance %s.",
ed416497 769 di->inst_id);
b2c19614 770
ed416497 771 if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
aafeeaea 772 srd_exception_catch("Protocol decoder instance %s: ",
ed416497 773 di->inst_id);
7ce7775c
BV
774 return SRD_ERR_PYTHON;
775 }
f38ec285 776 Py_DecRef(py_res);
7ce7775c 777
ed416497 778 /* Start all the PDs stacked on top of this one. */
2072ae0c
BV
779 for (l = di->next_di; l; l = l->next) {
780 next_di = l->data;
ed416497
BV
781 if ((ret = srd_inst_start(next_di)) != SRD_OK)
782 return ret;
2072ae0c
BV
783 }
784
b2c19614
BV
785 return SRD_OK;
786}
787
b2c19614
BV
788/**
789 * Run the specified decoder function.
790 *
ed416497 791 * @param di The decoder instance to call. Must not be NULL.
d906d3f9 792 * @param start_samplenum The starting sample number for the buffer's sample
7a1712c4 793 * set, relative to the start of capture.
ed416497
BV
794 * @param end_samplenum The ending sample number for the buffer's sample
795 * set, relative to the start of capture.
7a1712c4
UH
796 * @param inbuf The buffer to decode. Must not be NULL.
797 * @param inbuflen Length of the buffer. Must be > 0.
b2c19614
BV
798 *
799 * @return SRD_OK upon success, a (negative) error code otherwise.
57790bc8
UH
800 *
801 * @private
8c664ca2
UH
802 *
803 * @since 0.1.0
b2c19614 804 */
ed416497
BV
805SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
806 uint64_t start_samplenum, uint64_t end_samplenum,
807 const uint8_t *inbuf, uint64_t inbuflen)
b2c19614 808{
d906d3f9 809 PyObject *py_res;
bc5f5a43 810 srd_logic *logic;
b2c19614 811
74bb0af5
UH
812 srd_dbg("Calling decode() on instance %s with %" PRIu64 " bytes "
813 "starting at sample %" PRIu64 ".", di->inst_id, inbuflen,
814 start_samplenum);
b2c19614 815
d906d3f9 816 /* Return an error upon unusable input. */
7a1712c4
UH
817 if (!di) {
818 srd_dbg("empty decoder instance");
d906d3f9
BV
819 return SRD_ERR_ARG;
820 }
7a1712c4
UH
821 if (!inbuf) {
822 srd_dbg("NULL buffer pointer");
d906d3f9
BV
823 return SRD_ERR_ARG;
824 }
825 if (inbuflen == 0) {
7a1712c4 826 srd_dbg("empty buffer");
d906d3f9
BV
827 return SRD_ERR_ARG;
828 }
b2c19614 829
361fdcaa
UH
830 /*
831 * Create new srd_logic object. Each iteration around the PD's loop
d906d3f9
BV
832 * will fill one sample into this object.
833 */
bc5f5a43
BV
834 logic = PyObject_New(srd_logic, &srd_logic_type);
835 Py_INCREF(logic);
abeeed8b 836 logic->di = (struct srd_decoder_inst *)di;
86528298 837 logic->start_samplenum = start_samplenum;
bc5f5a43 838 logic->itercnt = 0;
abeeed8b 839 logic->inbuf = (uint8_t *)inbuf;
bc5f5a43
BV
840 logic->inbuflen = inbuflen;
841 logic->sample = PyList_New(2);
842 Py_INCREF(logic->sample);
843
a8b72b05 844 Py_IncRef(di->py_inst);
a8b72b05 845 if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
ed416497
BV
846 "KKO", start_samplenum, end_samplenum, logic))) {
847 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
0ff2d191 848 return SRD_ERR_PYTHON;
b2c19614 849 }
d906d3f9 850 Py_DecRef(py_res);
bc5f5a43 851
b2c19614
BV
852 return SRD_OK;
853}
854
57790bc8 855/** @private */
12243c22 856SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
fa12a21e
BV
857{
858 GSList *l;
859 struct srd_pd_output *pdo;
860
a8b72b05 861 srd_dbg("Freeing instance %s", di->inst_id);
fa12a21e 862
a8b72b05
BV
863 Py_DecRef(di->py_inst);
864 g_free(di->inst_id);
fa12a21e
BV
865 g_free(di->dec_probemap);
866 g_slist_free(di->next_di);
867 for (l = di->pd_output; l; l = l->next) {
868 pdo = l->data;
869 g_free(pdo->proto_id);
870 g_free(pdo);
871 }
872 g_slist_free(di->pd_output);
e592ac89 873 g_free(di);
fa12a21e
BV
874}
875
57790bc8 876/** @private */
32cfb920 877SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
fa12a21e
BV
878{
879 GSList *l;
a8b72b05 880 struct srd_decoder_inst *di;
fa12a21e 881
32cfb920
BV
882 if (session_is_valid(sess) != SRD_OK) {
883 srd_err("Invalid session.");
884 return;
885 }
886
fa12a21e 887 di = NULL;
32cfb920 888 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
fa12a21e
BV
889 di = l->data;
890 if (di->next_di)
32cfb920 891 srd_inst_free_all(sess, di->next_di);
a8b72b05 892 srd_inst_free(di);
fa12a21e
BV
893 }
894 if (!stack) {
32cfb920
BV
895 g_slist_free(sess->di_list);
896 sess->di_list = NULL;
fa12a21e 897 }
fa12a21e 898}
b2c19614 899
4895418c
UH
900/** @} */
901