]> sigrok.org Git - libsigrokdecode.git/blame - instance.c
Support adding multiple instances of a decoder
[libsigrokdecode.git] / instance.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
36784362 21#include <config.h>
f6c7eade
MC
22#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23#include "libsigrokdecode.h"
b2c19614 24#include <glib.h>
1aef2f93 25#include <inttypes.h>
0bdadba2 26#include <stdlib.h>
32cfb920 27#include <stdint.h>
b2c19614 28
32cfb920 29/** @cond PRIVATE */
d906d3f9 30
23a29d24 31extern SRD_PRIV GSList *sessions;
b2c19614 32
201a85a8
DE
33/* module_sigrokdecode.c */
34extern SRD_PRIV PyObject *srd_logic_type;
b2c19614 35
57790bc8
UH
36/** @endcond */
37
b2c19614 38/**
190b71cf 39 * @file
8c664ca2 40 *
190b71cf 41 * Decoder instance handling.
b2c19614 42 */
4895418c
UH
43
44/**
45 * @defgroup grp_instances Decoder instances
46 *
47 * Decoder instance handling.
48 *
49 * @{
50 */
51
7ce7775c 52/**
b33b8aa5 53 * Set one or more options in a decoder instance.
0bdadba2 54 *
361fdcaa
UH
55 * Handled options are removed from the hash.
56 *
0bdadba2
BV
57 * @param di Decoder instance.
58 * @param options A GHashTable of options to set.
7ce7775c 59 *
0bdadba2 60 * @return SRD_OK upon success, a (negative) error code otherwise.
8c664ca2
UH
61 *
62 * @since 0.1.0
0bdadba2 63 */
b33b8aa5 64SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
0ff2d191 65 GHashTable *options)
0bdadba2 66{
d841d5b2 67 struct srd_decoder_option *sdo;
84c1c0b5 68 PyObject *py_di_options, *py_optval;
2f395bff 69 GVariant *value;
d841d5b2
UH
70 GSList *l;
71 double val_double;
2f395bff 72 gint64 val_int;
84c1c0b5 73 int ret;
2f395bff 74 const char *val_str;
0bdadba2 75
3af0e345
UH
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
c9bfccc6 86 if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
0bdadba2 87 /* Decoder has no options. */
e431d9cc
BV
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 }
0bdadba2 95 return SRD_OK;
e431d9cc 96 }
0bdadba2
BV
97
98 ret = SRD_ERR_PYTHON;
d841d5b2 99 py_optval = NULL;
119d6258
BV
100
101 /*
84c1c0b5 102 * The 'options' tuple is a class variable, but we need to
119d6258
BV
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 */
a8b72b05 107 if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
0bdadba2 108 goto err_out;
119d6258
BV
109 Py_DECREF(py_di_options);
110 py_di_options = PyDict_New();
111 PyObject_SetAttrString(di->py_inst, "options", py_di_options);
0bdadba2 112
d841d5b2
UH
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),
bd6594c0 118 g_variant_get_type(sdo->def))) {
d841d5b2
UH
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.",
149 sdo->id);
150 goto err_out;
151 }
152 }
84c1c0b5 153 if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1)
0bdadba2 154 goto err_out;
d841d5b2
UH
155 /* Not harmful even if we used the default. */
156 g_hash_table_remove(options, sdo->id);
157 }
158 if (g_hash_table_size(options) != 0)
159 srd_warn("Unknown options specified for '%s'", di->inst_id);
0bdadba2
BV
160
161 ret = SRD_OK;
162
163err_out:
84c1c0b5 164 Py_XDECREF(py_optval);
7fc7bde6 165 if (PyErr_Occurred()) {
201a85a8 166 srd_exception_catch("Stray exception in srd_inst_option_set()");
7fc7bde6
BV
167 ret = SRD_ERR_PYTHON;
168 }
0bdadba2
BV
169
170 return ret;
171}
172
6a15597a
UH
173/* Helper GComparefunc for g_slist_find_custom() in srd_inst_channel_set_all() */
174static gint compare_channel_id(const struct srd_channel *pdch,
175 const char *channel_id)
f38ec285 176{
6a15597a 177 return strcmp(pdch->id, channel_id);
f38ec285
BV
178}
179
0bdadba2 180/**
6a15597a 181 * Set all channels in a decoder instance.
b33b8aa5 182 *
6a15597a
UH
183 * This function sets _all_ channels for the specified decoder instance, i.e.,
184 * it overwrites any channels that were already defined (if any).
0bdadba2
BV
185 *
186 * @param di Decoder instance.
6a15597a
UH
187 * @param new_channels A GHashTable of channels to set. Key is channel name,
188 * value is the channel number. Samples passed to this
189 * instance will be arranged in this order.
12243c22 190 *
0bdadba2 191 * @return SRD_OK upon success, a (negative) error code otherwise.
8c664ca2 192 *
cda2d36c 193 * @since 0.4.0
0bdadba2 194 */
6a15597a 195SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
cda2d36c 196 GHashTable *new_channels)
0bdadba2 197{
6a15597a 198 GVariant *channel_val;
f38ec285
BV
199 GList *l;
200 GSList *sl;
6a15597a
UH
201 struct srd_channel *pdch;
202 int *new_channelmap, new_channelnum, num_required_channels, i;
203 char *channel_id;
0bdadba2 204
cda2d36c
UH
205 srd_dbg("Setting channels for instance %s with list of %d channels.",
206 di->inst_id, g_hash_table_size(new_channels));
ce46beed 207
6a15597a
UH
208 if (g_hash_table_size(new_channels) == 0)
209 /* No channels provided. */
0bdadba2
BV
210 return SRD_OK;
211
6a15597a
UH
212 if (di->dec_num_channels == 0) {
213 /* Decoder has no channels. */
214 srd_err("Protocol decoder %s has no channels to define.",
c9bfccc6 215 di->decoder->name);
f38ec285
BV
216 return SRD_ERR_ARG;
217 }
0bdadba2 218
077fa8ac 219 new_channelmap = g_malloc(sizeof(int) * di->dec_num_channels);
0bdadba2 220
38ff5046 221 /*
6a15597a
UH
222 * For now, map all indexes to channel -1 (can be overridden later).
223 * This -1 is interpreted as an unspecified channel later.
38ff5046 224 */
6a15597a
UH
225 for (i = 0; i < di->dec_num_channels; i++)
226 new_channelmap[i] = -1;
227
228 for (l = g_hash_table_get_keys(new_channels); l; l = l->next) {
229 channel_id = l->data;
230 channel_val = g_hash_table_lookup(new_channels, channel_id);
231 if (!g_variant_is_of_type(channel_val, G_VARIANT_TYPE_INT32)) {
232 /* Channel name was specified without a value. */
233 srd_err("No channel number was specified for %s.",
234 channel_id);
235 g_free(new_channelmap);
be873260
BV
236 return SRD_ERR_ARG;
237 }
6a15597a 238 new_channelnum = g_variant_get_int32(channel_val);
6a15597a
UH
239 if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
240 (GCompareFunc)compare_channel_id))) {
241 /* Fall back on optional channels. */
242 if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
d841d5b2 243 channel_id, (GCompareFunc)compare_channel_id))) {
6a15597a 244 srd_err("Protocol decoder %s has no channel "
d841d5b2 245 "'%s'.", di->decoder->name, channel_id);
6a15597a 246 g_free(new_channelmap);
f38ec285
BV
247 return SRD_ERR_ARG;
248 }
249 }
6a15597a
UH
250 pdch = sl->data;
251 new_channelmap[pdch->order] = new_channelnum;
252 srd_dbg("Setting channel mapping: %s (index %d) = channel %d.",
253 pdch->id, pdch->order, new_channelnum);
38ff5046
UH
254 }
255
6a15597a
UH
256 srd_dbg("Final channel map:");
257 num_required_channels = g_slist_length(di->decoder->channels);
258 for (i = 0; i < di->dec_num_channels; i++) {
259 srd_dbg(" - index %d = channel %d (%s)", i, new_channelmap[i],
d841d5b2 260 (i < num_required_channels) ? "required" : "optional");
f38ec285 261 }
38ff5046 262
6a15597a
UH
263 /* Report an error if not all required channels were specified. */
264 for (i = 0; i < num_required_channels; i++) {
265 if (new_channelmap[i] != -1)
9bf7f71c 266 continue;
6a15597a
UH
267 pdch = g_slist_nth(di->decoder->channels, i)->data;
268 srd_err("Required channel '%s' (index %d) was not specified.",
269 pdch->id, i);
9bf7f71c
UH
270 return SRD_ERR;
271 }
272
6a15597a
UH
273 g_free(di->dec_channelmap);
274 di->dec_channelmap = new_channelmap;
0bdadba2 275
f38ec285 276 return SRD_OK;
0bdadba2
BV
277}
278
279/**
280 * Create a new protocol decoder instance.
7ce7775c 281 *
32cfb920 282 * @param sess The session holding the protocol decoder instance.
38ff5046 283 * @param decoder_id Decoder 'id' field.
0bdadba2 284 * @param options GHashtable of options which override the defaults set in
38ff5046 285 * the decoder class. May be NULL.
12243c22 286 *
a8b72b05 287 * @return Pointer to a newly allocated struct srd_decoder_inst, or
c9bfccc6 288 * NULL in case of failure.
8c664ca2 289 *
69075817 290 * @since 0.3.0
7ce7775c 291 */
32cfb920
BV
292SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
293 const char *decoder_id, GHashTable *options)
b2c19614 294{
c9bfccc6 295 int i;
b2c19614 296 struct srd_decoder *dec;
a8b72b05
BV
297 struct srd_decoder_inst *di;
298 char *inst_id;
b2c19614 299
3262ef02 300 i = 1;
7a1712c4 301 srd_dbg("Creating new %s instance.", decoder_id);
7ce7775c 302
32cfb920
BV
303 if (session_is_valid(sess) != SRD_OK) {
304 srd_err("Invalid session.");
305 return NULL;
306 }
307
9d122fd5 308 if (!(dec = srd_decoder_get_by_id(decoder_id))) {
0bdadba2 309 srd_err("Protocol decoder %s not found.", decoder_id);
b2c19614 310 return NULL;
0bdadba2 311 }
b2c19614 312
077fa8ac 313 di = g_malloc0(sizeof(struct srd_decoder_inst));
0bdadba2 314
b2c19614 315 di->decoder = dec;
32cfb920 316 di->sess = sess;
3262ef02 317
38ff5046
UH
318 if (options) {
319 inst_id = g_hash_table_lookup(options, "id");
3262ef02
KP
320 if (inst_id)
321 di->inst_id = g_strdup(inst_id);
38ff5046 322 g_hash_table_remove(options, "id");
3262ef02
KP
323 }
324
325 /* Create a unique instance ID (as none was provided). */
326 if (!di->inst_id) {
327 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
328 while (srd_inst_find_by_id(sess, di->inst_id)) {
329 g_free(di->inst_id);
330 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
331 }
332 }
b2c19614 333
361fdcaa 334 /*
6a15597a 335 * Prepare a default channel map, where samples come in the
f38ec285
BV
336 * order in which the decoder class defined them.
337 */
6a15597a
UH
338 di->dec_num_channels = g_slist_length(di->decoder->channels) +
339 g_slist_length(di->decoder->opt_channels);
340 if (di->dec_num_channels) {
077fa8ac
UH
341 di->dec_channelmap =
342 g_malloc(sizeof(int) * di->dec_num_channels);
6a15597a
UH
343 for (i = 0; i < di->dec_num_channels; i++)
344 di->dec_channelmap[i] = i;
37b94c20
BV
345 /*
346 * Will be used to prepare a sample at every iteration
347 * of the instance's decode() method.
348 */
077fa8ac 349 di->channel_samples = g_malloc(di->dec_num_channels);
f38ec285 350 }
f38ec285 351
0bdadba2 352 /* Create a new instance of this decoder class. */
a8b72b05 353 if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
b2c19614 354 if (PyErr_Occurred())
201a85a8 355 srd_exception_catch("Failed to create %s instance",
69075817 356 decoder_id);
6a15597a 357 g_free(di->dec_channelmap);
0bdadba2 358 g_free(di);
7ce7775c 359 return NULL;
b2c19614 360 }
7ce7775c 361
38ff5046 362 if (options && srd_inst_option_set(di, options) != SRD_OK) {
6a15597a 363 g_free(di->dec_channelmap);
0bdadba2
BV
364 g_free(di);
365 return NULL;
366 }
b2c19614 367
21dfd91d
UH
368 di->condition_list = NULL;
369 di->match_array = NULL;
370 di->start_samplenum = 0;
371 di->end_samplenum = 0;
372 di->inbuf = NULL;
373 di->inbuflen = 0;
374 di->cur_samplenum = 0;
375 di->old_pins_array = NULL;
376 di->thread_handle = NULL;
377 di->got_new_samples = FALSE;
378 di->handled_all_samples = FALSE;
379
f38ec285 380 /* Instance takes input from a frontend by default. */
32cfb920 381 sess->di_list = g_slist_append(sess->di_list, di);
3262ef02 382 srd_dbg("Created new %s instance with ID %s.", decoder_id, di->inst_id);
f38ec285 383
b2c19614
BV
384 return di;
385}
386
582c8473
BV
387/**
388 * Stack a decoder instance on top of another.
389 *
32cfb920 390 * @param sess The session holding the protocol decoder instances.
4d2c7619
BV
391 * @param di_bottom The instance on top of which di_top will be stacked.
392 * @param di_top The instance to go on top.
582c8473
BV
393 *
394 * @return SRD_OK upon success, a (negative) error code otherwise.
8c664ca2 395 *
69075817 396 * @since 0.3.0
582c8473 397 */
32cfb920 398SRD_API int srd_inst_stack(struct srd_session *sess,
4d2c7619
BV
399 struct srd_decoder_inst *di_bottom,
400 struct srd_decoder_inst *di_top)
7ce7775c 401{
32cfb920
BV
402
403 if (session_is_valid(sess) != SRD_OK) {
404 srd_err("Invalid session.");
405 return SRD_ERR_ARG;
406 }
407
4d2c7619 408 if (!di_bottom || !di_top) {
d906d3f9 409 srd_err("Invalid from/to instance pair.");
7ce7775c
BV
410 return SRD_ERR_ARG;
411 }
412
4d2c7619 413 if (g_slist_find(sess->di_list, di_top)) {
2072ae0c 414 /* Remove from the unstacked list. */
4d2c7619 415 sess->di_list = g_slist_remove(sess->di_list, di_top);
7ce7775c
BV
416 }
417
7ce7775c 418 /* Stack on top of source di. */
4d2c7619
BV
419 di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
420
d841d5b2 421 srd_dbg("Stacked %s onto %s.", di_top->inst_id, di_bottom->inst_id);
7ce7775c
BV
422
423 return SRD_OK;
424}
425
2072ae0c 426/**
361fdcaa
UH
427 * Find a decoder instance by its instance ID.
428 *
429 * Only the bottom level of instances are searched -- instances already stacked
430 * on top of another one will not be found.
2072ae0c 431 *
32cfb920 432 * @param sess The session holding the protocol decoder instance.
ed2306a6 433 * @param inst_id The instance ID to be found.
2072ae0c 434 *
a8b72b05 435 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
8c664ca2 436 *
69075817 437 * @since 0.3.0
2072ae0c 438 */
32cfb920
BV
439SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
440 const char *inst_id)
7ce7775c
BV
441{
442 GSList *l;
a8b72b05 443 struct srd_decoder_inst *tmp, *di;
b2c19614 444
32cfb920
BV
445 if (session_is_valid(sess) != SRD_OK) {
446 srd_err("Invalid session.");
447 return NULL;
448 }
449
7ce7775c 450 di = NULL;
32cfb920 451 for (l = sess->di_list; l; l = l->next) {
7ce7775c 452 tmp = l->data;
a8b72b05 453 if (!strcmp(tmp->inst_id, inst_id)) {
7ce7775c
BV
454 di = tmp;
455 break;
456 }
457 }
458
459 return di;
460}
461
32cfb920
BV
462static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
463 struct srd_session *sess, const GSList *stack,
464 const PyObject *obj)
465{
466 const GSList *l;
467 struct srd_decoder_inst *tmp, *di;
468
469 if (session_is_valid(sess) != SRD_OK) {
470 srd_err("Invalid session.");
471 return NULL;
472 }
473
474 di = NULL;
475 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
476 tmp = l->data;
477 if (tmp->py_inst == obj)
478 di = tmp;
479 else if (tmp->next_di)
480 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
481 }
482
483 return di;
484}
485
2072ae0c 486/**
361fdcaa
UH
487 * Find a decoder instance by its Python object.
488 *
489 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
32cfb920
BV
490 * This will recurse to find the instance anywhere in the stack tree of all
491 * sessions.
2072ae0c 492 *
361fdcaa
UH
493 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
494 * stack to search. To start searching at the bottom level of
495 * decoder instances, pass NULL.
511e2123 496 * @param obj The Python class instantiation.
2072ae0c 497 *
a8b72b05 498 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
57790bc8
UH
499 *
500 * @private
8c664ca2
UH
501 *
502 * @since 0.1.0
2072ae0c 503 */
abeeed8b 504SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
0ff2d191 505 const PyObject *obj)
2072ae0c 506{
32cfb920
BV
507 struct srd_decoder_inst *di;
508 struct srd_session *sess;
509 GSList *l;
2072ae0c
BV
510
511 di = NULL;
32cfb920
BV
512 for (l = sessions; di == NULL && l != NULL; l = l->next) {
513 sess = l->data;
514 di = srd_sess_inst_find_by_obj(sess, stack, obj);
2072ae0c
BV
515 }
516
517 return di;
518}
519
21dfd91d
UH
520/**
521 * Set the list of initial (assumed) pin values.
522 *
523 * If the list already exists, do nothing.
524 *
525 * @param di Decoder instance to use. Must not be NULL.
526 *
527 * @private
528 */
529static void set_initial_pin_values(struct srd_decoder_inst *di)
530{
531 int i;
532 GString *s;
533 PyObject *py_initial_pins;
534
535 if (!di || !di->py_inst) {
536 srd_err("Invalid decoder instance.");
537 return;
538 }
539
540 /* Nothing to do if di->old_pins_array is already != NULL. */
541 if (di->old_pins_array) {
542 srd_dbg("Initial pins already set, nothing to do.");
543 return;
544 }
545
546 /* Create an array of old (previous sample) pins, init to 0. */
547 di->old_pins_array = g_array_sized_new(FALSE, TRUE, sizeof(uint8_t), di->dec_num_channels);
548 g_array_set_size(di->old_pins_array, di->dec_num_channels);
549
550 /* Check if the decoder has set self.initial_pins. */
551 if (!PyObject_HasAttrString(di->py_inst, "initial_pins")) {
552 srd_dbg("Initial pins: all 0 (self.initial_pins not set).");
553 return;
554 }
555
556 /* Get self.initial_pins. */
557 py_initial_pins = PyObject_GetAttrString(di->py_inst, "initial_pins");
558
559 /* Fill di->old_pins_array based on self.initial_pins. */
560 s = g_string_sized_new(100);
561 for (i = 0; i < di->dec_num_channels; i++) {
562 di->old_pins_array->data[i] = PyLong_AsLong(PyList_GetItem(py_initial_pins, i));
563 g_string_append_printf(s, "%d, ", di->old_pins_array->data[i]);
564 }
565 s = g_string_truncate(s, s->len - 2);
566 srd_dbg("Initial pins: %s.", s->str);
567 g_string_free(s, TRUE);
568}
569
57790bc8 570/** @private */
ed416497 571SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
b2c19614 572{
ed416497 573 PyObject *py_res;
2072ae0c 574 GSList *l;
a8b72b05 575 struct srd_decoder_inst *next_di;
ed416497 576 int ret;
b2c19614 577
7a1712c4 578 srd_dbg("Calling start() method on protocol decoder instance %s.",
ed416497 579 di->inst_id);
b2c19614 580
21dfd91d 581 /* Run self.start(). */
ed416497 582 if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
201a85a8 583 srd_exception_catch("Protocol decoder instance %s",
ed416497 584 di->inst_id);
7ce7775c
BV
585 return SRD_ERR_PYTHON;
586 }
f38ec285 587 Py_DecRef(py_res);
7ce7775c 588
21dfd91d
UH
589 /* Set the initial pins based on self.initial_pins. */
590 set_initial_pin_values(di);
591
592 /* Set self.samplenum to 0. */
593 PyObject_SetAttrString(di->py_inst, "samplenum", PyLong_FromLong(0));
594
595 /* Set self.matches to None. */
596 PyObject_SetAttrString(di->py_inst, "matches", Py_None);
597
ed416497 598 /* Start all the PDs stacked on top of this one. */
2072ae0c
BV
599 for (l = di->next_di; l; l = l->next) {
600 next_di = l->data;
ed416497
BV
601 if ((ret = srd_inst_start(next_di)) != SRD_OK)
602 return ret;
2072ae0c
BV
603 }
604
b2c19614
BV
605 return SRD_OK;
606}
607
21dfd91d
UH
608/**
609 * Check whether the specified sample matches the specified term.
610 *
611 * In the case of SRD_TERM_SKIP, this function can modify
612 * term->num_samples_already_skipped.
613 *
614 * @param old_sample The value of the previous sample (0/1).
615 * @param sample The value of the current sample (0/1).
616 * @param term The term that should be checked for a match. Must not be NULL.
617 *
618 * @retval TRUE The current sample matches the specified term.
619 * @retval FALSE The current sample doesn't match the specified term, or an
620 * invalid term was provided.
621 *
622 * @private
623 */
624static gboolean sample_matches(uint8_t old_sample, uint8_t sample, struct srd_term *term)
625{
626 if (!term)
627 return FALSE;
628
629 switch (term->type) {
630 case SRD_TERM_HIGH:
631 if (sample == 1)
632 return TRUE;
633 break;
634 case SRD_TERM_LOW:
635 if (sample == 0)
636 return TRUE;
637 break;
638 case SRD_TERM_RISING_EDGE:
639 if (old_sample == 0 && sample == 1)
640 return TRUE;
641 break;
642 case SRD_TERM_FALLING_EDGE:
643 if (old_sample == 1 && sample == 0)
644 return TRUE;
645 break;
646 case SRD_TERM_EITHER_EDGE:
647 if ((old_sample == 1 && sample == 0) || (old_sample == 0 && sample == 1))
648 return TRUE;
649 break;
650 case SRD_TERM_NO_EDGE:
651 if ((old_sample == 0 && sample == 0) || (old_sample == 1 && sample == 1))
652 return TRUE;
653 break;
654 case SRD_TERM_SKIP:
655 if (term->num_samples_already_skipped == term->num_samples_to_skip)
656 return TRUE;
657 term->num_samples_already_skipped++;
658 break;
659 default:
660 srd_err("Unknown term type %d.", term->type);
661 break;
662 }
663
664 return FALSE;
665}
666
667SRD_PRIV void match_array_free(struct srd_decoder_inst *di)
668{
669 if (!di || !di->match_array)
670 return;
671
672 g_array_free(di->match_array, TRUE);
673 di->match_array = NULL;
674}
675
676SRD_PRIV void condition_list_free(struct srd_decoder_inst *di)
677{
678 GSList *l, *ll;
679
680 if (!di)
681 return;
682
683 for (l = di->condition_list; l; l = l->next) {
684 ll = l->data;
685 if (ll)
686 g_slist_free_full(ll, g_free);
687 }
688
689 di->condition_list = NULL;
690}
691
692static gboolean have_non_null_conds(const struct srd_decoder_inst *di)
693{
694 GSList *l, *cond;
695
696 if (!di)
697 return FALSE;
698
699 for (l = di->condition_list; l; l = l->next) {
700 cond = l->data;
701 if (cond)
702 return TRUE;
703 }
704
705 return FALSE;
706}
707
708static void update_old_pins_array(struct srd_decoder_inst *di,
709 const uint8_t *sample_pos)
710{
711 uint8_t sample;
712 int i, byte_offset, bit_offset;
713
714 if (!di || !di->dec_channelmap || !sample_pos)
715 return;
716
717 for (i = 0; i < di->dec_num_channels; i++) {
718 byte_offset = di->dec_channelmap[i] / 8;
719 bit_offset = di->dec_channelmap[i] % 8;
720 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
721 di->old_pins_array->data[i] = sample;
722 }
723}
724
725static gboolean term_matches(const struct srd_decoder_inst *di,
726 struct srd_term *term, const uint8_t *sample_pos)
727{
728 uint8_t old_sample, sample;
729 int byte_offset, bit_offset, ch;
730
731 if (!di || !di->dec_channelmap || !term || !sample_pos)
732 return FALSE;
733
734 /* Overwritten below (or ignored for SRD_TERM_SKIP). */
735 old_sample = sample = 0;
736
737 if (term->type != SRD_TERM_SKIP) {
738 ch = term->channel;
739 byte_offset = di->dec_channelmap[ch] / 8;
740 bit_offset = di->dec_channelmap[ch] % 8;
741 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
742 old_sample = di->old_pins_array->data[ch];
743 }
744
745 return sample_matches(old_sample, sample, term);
746}
747
748static gboolean all_terms_match(const struct srd_decoder_inst *di,
749 const GSList *cond, const uint8_t *sample_pos)
750{
751 const GSList *l;
752 struct srd_term *term;
753
754 if (!di || !cond || !sample_pos)
755 return FALSE;
756
757 for (l = cond; l; l = l->next) {
758 term = l->data;
759 if (!term_matches(di, term, sample_pos))
760 return FALSE;
761 }
762
763 return TRUE;
764}
765
766static gboolean at_least_one_condition_matched(
767 const struct srd_decoder_inst *di, unsigned int num_conditions)
768{
769 unsigned int i;
770
771 if (!di)
772 return FALSE;
773
774 for (i = 0; i < num_conditions; i++) {
775 if (di->match_array->data[i])
776 return TRUE;
777 }
778
779 return FALSE;
780}
781
782static gboolean find_match(struct srd_decoder_inst *di)
783{
784 static uint64_t s = 0;
785 uint64_t i, j, num_samples_to_process;
786 GSList *l, *cond;
787 const uint8_t *sample_pos;
788 unsigned int num_conditions;
789
790 /* Check whether the condition list is NULL/empty. */
791 if (!di->condition_list) {
792 srd_dbg("NULL/empty condition list, automatic match.");
793 return TRUE;
794 }
795
796 /* Check whether we have any non-NULL conditions. */
797 if (!have_non_null_conds(di)) {
798 srd_dbg("Only NULL conditions in list, automatic match.");
799 return TRUE;
800 }
801
802 num_samples_to_process = di->end_samplenum - di->cur_samplenum;
803 num_conditions = g_slist_length(di->condition_list);
804
805 /* di->match_array is NULL here. Create a new GArray. */
806 di->match_array = g_array_sized_new(FALSE, TRUE, sizeof(gboolean), num_conditions);
807 g_array_set_size(di->match_array, num_conditions);
808
809 for (i = 0, s = 0; i < num_samples_to_process; i++, s++, (di->cur_samplenum)++) {
810
811 sample_pos = di->inbuf + ((di->cur_samplenum - di->start_samplenum) * di->data_unitsize);
812
813 /* Check whether the current sample matches at least one of the conditions (logical OR). */
814 /* IMPORTANT: We need to check all conditions, even if there was a match already! */
815 for (l = di->condition_list, j = 0; l; l = l->next, j++) {
816 cond = l->data;
817 if (!cond)
818 continue;
819 /* All terms in 'cond' must match (logical AND). */
820 di->match_array->data[j] = all_terms_match(di, cond, sample_pos);
821 }
822
823 update_old_pins_array(di, sample_pos);
824
825 /* If at least one condition matched we're done. */
826 if (at_least_one_condition_matched(di, num_conditions))
827 return TRUE;
828 }
829
830 return FALSE;
831}
832
833/**
834 * Process available samples and check if they match the defined conditions.
835 *
836 * This function returns if there is an error, or when a match is found, or
837 * when all samples have been processed (whether a match was found or not).
838 *
839 * @param di The decoder instance to use. Must not be NULL.
840 * @param found_match Will be set to TRUE if at least one condition matched,
841 * FALSE otherwise. Must not be NULL.
842 *
843 * @retval SRD_OK No errors occured, see found_match for the result.
844 * @retval SRD_ERR_ARG Invalid arguments.
845 *
846 * @private
847 */
848SRD_PRIV int process_samples_until_condition_match(struct srd_decoder_inst *di, gboolean *found_match)
849{
850 if (!di || !found_match)
851 return SRD_ERR_ARG;
852
853 /* Check if any of the current condition(s) match. */
854 while (TRUE) {
855 /* Feed the (next chunk of the) buffer to find_match(). */
856 *found_match = find_match(di);
857
858 /* Did we handle all samples yet? */
859 if (di->cur_samplenum >= di->end_samplenum) {
860 srd_dbg("Done, handled all samples (%" PRIu64 "/%" PRIu64 ").",
861 di->cur_samplenum, di->end_samplenum);
862 return SRD_OK;
863 }
864
865 /* If we didn't find a match, continue looking. */
866 if (!(*found_match))
867 continue;
868
869 /* At least one condition matched, return. */
870 return SRD_OK;
871 }
872
873 return SRD_OK;
874}
875
876/**
877 * Worker thread (per PD-stack).
878 *
879 * @param data Pointer to the lowest-level PD's device instance.
880 * Must not be NULL.
881 *
882 * @return NULL if there was an error.
883 */
884static gpointer di_thread(gpointer data)
885{
886 PyObject *py_res;
887 struct srd_decoder_inst *di;
888
889 if (!data)
890 return NULL;
891
892 di = data;
893
894 /* Call self.decode(). Only returns if the PD throws an exception. */
895 Py_IncRef(di->py_inst);
896 if (!(py_res = PyObject_CallMethod(di->py_inst, "decode", NULL))) {
897 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
898 exit(1); /* TODO: Proper shutdown. This is a hack. */
899 return NULL;
900 }
901 Py_DecRef(py_res);
902
903 return NULL;
904}
905
b2c19614 906/**
e959f49a 907 * Decode a chunk of samples.
b2c19614 908 *
ed416497 909 * @param di The decoder instance to call. Must not be NULL.
d906d3f9 910 * @param start_samplenum The starting sample number for the buffer's sample
7a1712c4 911 * set, relative to the start of capture.
ed416497
BV
912 * @param end_samplenum The ending sample number for the buffer's sample
913 * set, relative to the start of capture.
7a1712c4
UH
914 * @param inbuf The buffer to decode. Must not be NULL.
915 * @param inbuflen Length of the buffer. Must be > 0.
e959f49a 916 * @param unitsize The number of bytes per sample. Must be > 0.
b2c19614
BV
917 *
918 * @return SRD_OK upon success, a (negative) error code otherwise.
57790bc8
UH
919 *
920 * @private
b2c19614 921 */
21dfd91d 922SRD_PRIV int srd_inst_decode(struct srd_decoder_inst *di,
ed416497 923 uint64_t start_samplenum, uint64_t end_samplenum,
cda2d36c 924 const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
b2c19614 925{
d906d3f9 926 PyObject *py_res;
bc5f5a43 927 srd_logic *logic;
04867deb 928 long apiver;
b2c19614 929
d906d3f9 930 /* Return an error upon unusable input. */
7a1712c4
UH
931 if (!di) {
932 srd_dbg("empty decoder instance");
d906d3f9
BV
933 return SRD_ERR_ARG;
934 }
7a1712c4
UH
935 if (!inbuf) {
936 srd_dbg("NULL buffer pointer");
d906d3f9
BV
937 return SRD_ERR_ARG;
938 }
939 if (inbuflen == 0) {
7a1712c4 940 srd_dbg("empty buffer");
d906d3f9 941 return SRD_ERR_ARG;
80f8083b
UH
942 }
943 if (unitsize == 0) {
944 srd_dbg("unitsize 0");
945 return SRD_ERR_ARG;
d906d3f9 946 }
b2c19614 947
21dfd91d 948 di->data_unitsize = unitsize;
2730fe23 949
e959f49a 950 srd_dbg("Decoding: start sample %" PRIu64 ", end sample %"
2730fe23
UH
951 PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
952 "%d), instance %s.", start_samplenum, end_samplenum,
953 end_samplenum - start_samplenum, inbuflen, di->data_unitsize,
954 di->inst_id);
955
04867deb
UH
956 apiver = srd_decoder_apiver(di->decoder);
957
958 if (apiver == 2) {
959 /*
960 * Create new srd_logic object. Each iteration around the PD's
961 * loop will fill one sample into this object.
962 */
963 logic = PyObject_New(srd_logic, (PyTypeObject *)srd_logic_type);
964 Py_INCREF(logic);
965 logic->di = (struct srd_decoder_inst *)di;
966 logic->start_samplenum = start_samplenum;
967 logic->itercnt = 0;
968 logic->inbuf = (uint8_t *)inbuf;
969 logic->inbuflen = inbuflen;
970 logic->sample = PyList_New(2);
971 Py_INCREF(logic->sample);
972
973 Py_IncRef(di->py_inst);
974 if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
ed416497 975 "KKO", start_samplenum, end_samplenum, logic))) {
04867deb
UH
976 srd_exception_catch("Protocol decoder instance %s",
977 di->inst_id);
978 return SRD_ERR_PYTHON;
979 }
980 Py_DecRef(py_res);
21dfd91d
UH
981 } else {
982 /* If this is the first call, start the worker thread. */
983 if (!di->thread_handle)
984 di->thread_handle = g_thread_new("di_thread",
985 di_thread, di);
986
987 /* Push the new sample chunk to the worker thread. */
988 g_mutex_lock(&di->data_mutex);
989 di->start_samplenum = start_samplenum;
990 di->end_samplenum = end_samplenum;
991 di->inbuf = inbuf;
992 di->inbuflen = inbuflen;
993 di->got_new_samples = TRUE;
994 di->handled_all_samples = FALSE;
995
996 /* Signal the thread that we have new data. */
997 g_cond_signal(&di->got_new_samples_cond);
998 g_mutex_unlock(&di->data_mutex);
999
1000 /* When all samples in this chunk were handled, return. */
1001 g_mutex_lock(&di->data_mutex);
1002 while (!di->handled_all_samples)
1003 g_cond_wait(&di->handled_all_samples_cond, &di->data_mutex);
1004 g_mutex_unlock(&di->data_mutex);
b2c19614 1005 }
bc5f5a43 1006
b2c19614
BV
1007 return SRD_OK;
1008}
1009
57790bc8 1010/** @private */
12243c22 1011SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
fa12a21e
BV
1012{
1013 GSList *l;
1014 struct srd_pd_output *pdo;
1015
a8b72b05 1016 srd_dbg("Freeing instance %s", di->inst_id);
fa12a21e 1017
a8b72b05
BV
1018 Py_DecRef(di->py_inst);
1019 g_free(di->inst_id);
6a15597a 1020 g_free(di->dec_channelmap);
d2297b87 1021 g_free(di->channel_samples);
fa12a21e
BV
1022 g_slist_free(di->next_di);
1023 for (l = di->pd_output; l; l = l->next) {
1024 pdo = l->data;
1025 g_free(pdo->proto_id);
1026 g_free(pdo);
1027 }
1028 g_slist_free(di->pd_output);
e592ac89 1029 g_free(di);
fa12a21e
BV
1030}
1031
57790bc8 1032/** @private */
3262ef02 1033SRD_PRIV void srd_inst_free_all(struct srd_session *sess)
fa12a21e 1034{
32cfb920
BV
1035 if (session_is_valid(sess) != SRD_OK) {
1036 srd_err("Invalid session.");
1037 return;
1038 }
1039
3262ef02 1040 g_slist_free_full(sess->di_list, (GDestroyNotify)srd_inst_free);
fa12a21e 1041}
b2c19614 1042
4895418c 1043/** @} */