]> sigrok.org Git - libsigrokdecode.git/blame_incremental - instance.c
ltc242x: Rename the 'ref' option to 'vref'.
[libsigrokdecode.git] / instance.c
... / ...
CommitLineData
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 <config.h>
22#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23#include "libsigrokdecode.h"
24#include <glib.h>
25#include <inttypes.h>
26#include <stdlib.h>
27#include <stdint.h>
28
29/** @cond PRIVATE */
30
31extern SRD_PRIV GSList *sessions;
32
33/** @endcond */
34
35/**
36 * @file
37 *
38 * Decoder instance handling.
39 */
40
41/**
42 * @defgroup grp_instances Decoder instances
43 *
44 * Decoder instance handling.
45 *
46 * @{
47 */
48
49static void oldpins_array_seed(struct srd_decoder_inst *di)
50{
51 size_t count;
52 GArray *arr;
53
54 if (!di)
55 return;
56 if (di->old_pins_array)
57 return;
58
59 count = di->dec_num_channels;
60 arr = g_array_sized_new(FALSE, TRUE, sizeof(uint8_t), count);
61 g_array_set_size(arr, count);
62 if (arr->data)
63 memset(arr->data, SRD_INITIAL_PIN_SAME_AS_SAMPLE0, count);
64 di->old_pins_array = arr;
65}
66
67static void oldpins_array_free(struct srd_decoder_inst *di)
68{
69 if (!di)
70 return;
71 if (!di->old_pins_array)
72 return;
73
74 srd_dbg("%s: Releasing initial pin state.", di->inst_id);
75
76 g_array_free(di->old_pins_array, TRUE);
77 di->old_pins_array = NULL;
78}
79
80/**
81 * Set one or more options in a decoder instance.
82 *
83 * Handled options are removed from the hash.
84 *
85 * @param di Decoder instance.
86 * @param options A GHashTable of options to set.
87 *
88 * @return SRD_OK upon success, a (negative) error code otherwise.
89 *
90 * @since 0.1.0
91 */
92SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
93 GHashTable *options)
94{
95 struct srd_decoder_option *sdo;
96 PyObject *py_di_options, *py_optval;
97 GVariant *value;
98 GSList *l;
99 double val_double;
100 gint64 val_int;
101 int ret;
102 const char *val_str;
103 PyGILState_STATE gstate;
104
105 if (!di) {
106 srd_err("Invalid decoder instance.");
107 return SRD_ERR_ARG;
108 }
109
110 if (!options) {
111 srd_err("Invalid options GHashTable.");
112 return SRD_ERR_ARG;
113 }
114
115 gstate = PyGILState_Ensure();
116
117 if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
118 /* Decoder has no options. */
119 PyGILState_Release(gstate);
120 if (g_hash_table_size(options) == 0) {
121 /* No options provided. */
122 return SRD_OK;
123 } else {
124 srd_err("Protocol decoder has no options.");
125 return SRD_ERR_ARG;
126 }
127 return SRD_OK;
128 }
129
130 ret = SRD_ERR_PYTHON;
131 py_optval = NULL;
132
133 /*
134 * The 'options' tuple is a class variable, but we need to
135 * change it. Changing it directly will affect the entire class,
136 * so we need to create a new object for it, and populate that
137 * instead.
138 */
139 if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
140 goto err_out;
141 Py_DECREF(py_di_options);
142 py_di_options = PyDict_New();
143 PyObject_SetAttrString(di->py_inst, "options", py_di_options);
144 Py_DECREF(py_di_options);
145
146 for (l = di->decoder->options; l; l = l->next) {
147 sdo = l->data;
148 if ((value = g_hash_table_lookup(options, sdo->id))) {
149 /* A value was supplied for this option. */
150 if (!g_variant_type_equal(g_variant_get_type(value),
151 g_variant_get_type(sdo->def))) {
152 srd_err("Option '%s' should have the same type "
153 "as the default value.", sdo->id);
154 goto err_out;
155 }
156 } else {
157 /* Use default for this option. */
158 value = sdo->def;
159 }
160 if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
161 val_str = g_variant_get_string(value, NULL);
162 if (!(py_optval = PyUnicode_FromString(val_str))) {
163 /* Some UTF-8 encoding error. */
164 PyErr_Clear();
165 srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
166 goto err_out;
167 }
168 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
169 val_int = g_variant_get_int64(value);
170 if (!(py_optval = PyLong_FromLong(val_int))) {
171 /* ValueError Exception */
172 PyErr_Clear();
173 srd_err("Option '%s' has invalid integer value.", sdo->id);
174 goto err_out;
175 }
176 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_DOUBLE)) {
177 val_double = g_variant_get_double(value);
178 if (!(py_optval = PyFloat_FromDouble(val_double))) {
179 /* ValueError Exception */
180 PyErr_Clear();
181 srd_err("Option '%s' has invalid float value.",
182 sdo->id);
183 goto err_out;
184 }
185 }
186 if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1) {
187 Py_XDECREF(py_optval);
188 goto err_out;
189 }
190 /* Not harmful even if we used the default. */
191 g_hash_table_remove(options, sdo->id);
192 Py_XDECREF(py_optval);
193 }
194 if (g_hash_table_size(options) != 0)
195 srd_warn("Unknown options specified for '%s'", di->inst_id);
196
197 ret = SRD_OK;
198
199err_out:
200 if (PyErr_Occurred()) {
201 srd_exception_catch("Stray exception in srd_inst_option_set()");
202 ret = SRD_ERR_PYTHON;
203 }
204 PyGILState_Release(gstate);
205
206 return ret;
207}
208
209/* Helper GComparefunc for g_slist_find_custom() in srd_inst_channel_set_all(). */
210static gint compare_channel_id(const struct srd_channel *pdch,
211 const char *channel_id)
212{
213 return strcmp(pdch->id, channel_id);
214}
215
216/**
217 * Set all channels in a decoder instance.
218 *
219 * This function sets _all_ channels for the specified decoder instance, i.e.,
220 * it overwrites any channels that were already defined (if any).
221 *
222 * @param di Decoder instance.
223 * @param new_channels A GHashTable of channels to set. Key is channel name,
224 * value is the channel number. Samples passed to this
225 * instance will be arranged in this order.
226 *
227 * @return SRD_OK upon success, a (negative) error code otherwise.
228 *
229 * @since 0.4.0
230 */
231SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
232 GHashTable *new_channels)
233{
234 GVariant *channel_val;
235 GList *l;
236 GSList *sl;
237 struct srd_channel *pdch;
238 int *new_channelmap, new_channelnum, num_required_channels, i;
239 char *channel_id;
240
241 srd_dbg("Setting channels for instance %s with list of %d channels.",
242 di->inst_id, g_hash_table_size(new_channels));
243
244 if (g_hash_table_size(new_channels) == 0)
245 /* No channels provided. */
246 return SRD_OK;
247
248 if (di->dec_num_channels == 0) {
249 /* Decoder has no channels. */
250 srd_err("Protocol decoder %s has no channels to define.",
251 di->decoder->name);
252 return SRD_ERR_ARG;
253 }
254
255 new_channelmap = g_malloc0(sizeof(int) * di->dec_num_channels);
256
257 /*
258 * For now, map all indexes to channel -1 (can be overridden later).
259 * This -1 is interpreted as an unspecified channel later.
260 */
261 for (i = 0; i < di->dec_num_channels; i++)
262 new_channelmap[i] = -1;
263
264 for (l = g_hash_table_get_keys(new_channels); l; l = l->next) {
265 channel_id = l->data;
266 channel_val = g_hash_table_lookup(new_channels, channel_id);
267 if (!g_variant_is_of_type(channel_val, G_VARIANT_TYPE_INT32)) {
268 /* Channel name was specified without a value. */
269 srd_err("No channel number was specified for %s.",
270 channel_id);
271 g_free(new_channelmap);
272 return SRD_ERR_ARG;
273 }
274 new_channelnum = g_variant_get_int32(channel_val);
275 if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
276 (GCompareFunc)compare_channel_id))) {
277 /* Fall back on optional channels. */
278 if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
279 channel_id, (GCompareFunc)compare_channel_id))) {
280 srd_err("Protocol decoder %s has no channel "
281 "'%s'.", di->decoder->name, channel_id);
282 g_free(new_channelmap);
283 return SRD_ERR_ARG;
284 }
285 }
286 pdch = sl->data;
287 new_channelmap[pdch->order] = new_channelnum;
288 srd_dbg("Setting channel mapping: %s (PD ch idx %d) = input data ch idx %d.",
289 pdch->id, pdch->order, new_channelnum);
290 }
291
292 srd_dbg("Final channel map:");
293 num_required_channels = g_slist_length(di->decoder->channels);
294 for (i = 0; i < di->dec_num_channels; i++) {
295 GSList *ll = g_slist_nth(di->decoder->channels, i);
296 if (!ll)
297 ll = g_slist_nth(di->decoder->opt_channels,
298 i - num_required_channels);
299 pdch = ll->data;
300 srd_dbg(" - PD ch idx %d (%s) = input data ch idx %d (%s)", i,
301 pdch->id, new_channelmap[i],
302 (i < num_required_channels) ? "required" : "optional");
303 }
304
305 /* Report an error if not all required channels were specified. */
306 for (i = 0; i < num_required_channels; i++) {
307 if (new_channelmap[i] != -1)
308 continue;
309 pdch = g_slist_nth(di->decoder->channels, i)->data;
310 srd_err("Required channel '%s' (index %d) was not specified.",
311 pdch->id, i);
312 g_free(new_channelmap);
313 return SRD_ERR;
314 }
315
316 g_free(di->dec_channelmap);
317 di->dec_channelmap = new_channelmap;
318
319 return SRD_OK;
320}
321
322/**
323 * Create a new protocol decoder instance.
324 *
325 * @param sess The session holding the protocol decoder instance.
326 * Must not be NULL.
327 * @param decoder_id Decoder 'id' field.
328 * @param options GHashtable of options which override the defaults set in
329 * the decoder class. May be NULL.
330 *
331 * @return Pointer to a newly allocated struct srd_decoder_inst, or
332 * NULL in case of failure.
333 *
334 * @since 0.3.0
335 */
336SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
337 const char *decoder_id, GHashTable *options)
338{
339 int i;
340 struct srd_decoder *dec;
341 struct srd_decoder_inst *di;
342 char *inst_id;
343 PyGILState_STATE gstate;
344
345 i = 1;
346
347 if (!sess)
348 return NULL;
349
350 if (!(dec = srd_decoder_get_by_id(decoder_id))) {
351 srd_err("Protocol decoder %s not found.", decoder_id);
352 return NULL;
353 }
354
355 di = g_malloc0(sizeof(struct srd_decoder_inst));
356
357 di->decoder = dec;
358 di->sess = sess;
359
360 if (options) {
361 inst_id = g_hash_table_lookup(options, "id");
362 if (inst_id)
363 di->inst_id = g_strdup(inst_id);
364 g_hash_table_remove(options, "id");
365 }
366
367 /* Create a unique instance ID (as none was provided). */
368 if (!di->inst_id) {
369 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
370 while (srd_inst_find_by_id(sess, di->inst_id)) {
371 g_free(di->inst_id);
372 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
373 }
374 }
375
376 /*
377 * Prepare a default channel map, where samples come in the
378 * order in which the decoder class defined them.
379 */
380 di->dec_num_channels = g_slist_length(di->decoder->channels) +
381 g_slist_length(di->decoder->opt_channels);
382 if (di->dec_num_channels) {
383 di->dec_channelmap =
384 g_malloc(sizeof(int) * di->dec_num_channels);
385 for (i = 0; i < di->dec_num_channels; i++)
386 di->dec_channelmap[i] = i;
387 /*
388 * Will be used to prepare a sample at every iteration
389 * of the instance's decode() method.
390 */
391 di->channel_samples = g_malloc(di->dec_num_channels);
392 }
393
394 /* Default to the initial pins being the same as in sample 0. */
395 oldpins_array_seed(di);
396
397 gstate = PyGILState_Ensure();
398
399 /* Create a new instance of this decoder class. */
400 if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
401 if (PyErr_Occurred())
402 srd_exception_catch("Failed to create %s instance",
403 decoder_id);
404 PyGILState_Release(gstate);
405 g_free(di->dec_channelmap);
406 g_free(di);
407 return NULL;
408 }
409
410 PyGILState_Release(gstate);
411
412 if (options && srd_inst_option_set(di, options) != SRD_OK) {
413 g_free(di->dec_channelmap);
414 g_free(di);
415 return NULL;
416 }
417
418 di->condition_list = NULL;
419 di->match_array = NULL;
420 di->abs_start_samplenum = 0;
421 di->abs_end_samplenum = 0;
422 di->inbuf = NULL;
423 di->inbuflen = 0;
424 di->abs_cur_samplenum = 0;
425 di->thread_handle = NULL;
426 di->got_new_samples = FALSE;
427 di->handled_all_samples = FALSE;
428 di->want_wait_terminate = FALSE;
429 di->decoder_state = SRD_OK;
430
431 /*
432 * Strictly speaking initialization of statically allocated
433 * condition and mutex variables (or variables allocated on the
434 * stack) is not required, but won't harm either. Explicitly
435 * running init() will better match subsequent clear() calls.
436 */
437 g_cond_init(&di->got_new_samples_cond);
438 g_cond_init(&di->handled_all_samples_cond);
439 g_mutex_init(&di->data_mutex);
440
441 /* Instance takes input from a frontend by default. */
442 sess->di_list = g_slist_append(sess->di_list, di);
443 srd_dbg("Creating new %s instance %s.", decoder_id, di->inst_id);
444
445 return di;
446}
447
448static void srd_inst_join_decode_thread(struct srd_decoder_inst *di)
449{
450 if (!di)
451 return;
452 if (!di->thread_handle)
453 return;
454
455 srd_dbg("%s: Joining decoder thread.", di->inst_id);
456
457 /*
458 * Terminate potentially running threads which still
459 * execute the decoder instance's decode() method.
460 */
461 srd_dbg("%s: Raising want_term, sending got_new.", di->inst_id);
462 g_mutex_lock(&di->data_mutex);
463 di->want_wait_terminate = TRUE;
464 g_cond_signal(&di->got_new_samples_cond);
465 g_mutex_unlock(&di->data_mutex);
466
467 srd_dbg("%s: Running join().", di->inst_id);
468 (void)g_thread_join(di->thread_handle);
469 srd_dbg("%s: Call to join() done.", di->inst_id);
470 di->thread_handle = NULL;
471
472 /*
473 * Reset condition and mutex variables, such that next
474 * operations on them will find them in a clean state.
475 */
476 g_cond_clear(&di->got_new_samples_cond);
477 g_cond_init(&di->got_new_samples_cond);
478 g_cond_clear(&di->handled_all_samples_cond);
479 g_cond_init(&di->handled_all_samples_cond);
480 g_mutex_clear(&di->data_mutex);
481 g_mutex_init(&di->data_mutex);
482}
483
484static void srd_inst_reset_state(struct srd_decoder_inst *di)
485{
486 if (!di)
487 return;
488
489 srd_dbg("%s: Resetting decoder state.", di->inst_id);
490
491 /* Reset internal state of the decoder. */
492 condition_list_free(di);
493 match_array_free(di);
494 di->abs_start_samplenum = 0;
495 di->abs_end_samplenum = 0;
496 di->inbuf = NULL;
497 di->inbuflen = 0;
498 di->abs_cur_samplenum = 0;
499 oldpins_array_free(di);
500 di->got_new_samples = FALSE;
501 di->handled_all_samples = FALSE;
502 di->want_wait_terminate = FALSE;
503 di->decoder_state = SRD_OK;
504 /* Conditions and mutex got reset after joining the thread. */
505}
506
507/**
508 * Stack a decoder instance on top of another.
509 *
510 * @param sess The session holding the protocol decoder instances.
511 * Must not be NULL.
512 * @param di_bottom The instance on top of which di_top will be stacked.
513 * @param di_top The instance to go on top.
514 *
515 * @return SRD_OK upon success, a (negative) error code otherwise.
516 *
517 * @since 0.3.0
518 */
519SRD_API int srd_inst_stack(struct srd_session *sess,
520 struct srd_decoder_inst *di_bottom,
521 struct srd_decoder_inst *di_top)
522{
523 if (!sess)
524 return SRD_ERR_ARG;
525
526 if (!di_bottom || !di_top) {
527 srd_err("Invalid from/to instance pair.");
528 return SRD_ERR_ARG;
529 }
530
531 if (g_slist_find(sess->di_list, di_top)) {
532 /* Remove from the unstacked list. */
533 sess->di_list = g_slist_remove(sess->di_list, di_top);
534 }
535
536 /*
537 * Check if there's at least one matching input/output pair
538 * for the stacked PDs. We warn if that's not the case, but it's
539 * not a hard error for the time being.
540 */
541 gboolean at_least_one_match = FALSE;
542 for (GSList *out = di_bottom->decoder->outputs; out; out = out->next) {
543 const char *o = out->data;
544 for (GSList *in = di_top->decoder->inputs; in; in = in->next) {
545 const char *i = in->data;
546 if (!strcmp(o, i)) {
547 at_least_one_match = TRUE;
548 break;
549 }
550 }
551 }
552
553 if (!at_least_one_match)
554 srd_warn("No matching in-/output when stacking %s onto %s.",
555 di_top->inst_id, di_bottom->inst_id);
556
557 /* Stack on top of source di. */
558 di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
559
560 srd_dbg("Stacking %s onto %s.", di_top->inst_id, di_bottom->inst_id);
561
562 return SRD_OK;
563}
564
565/**
566 * Search a decoder instance and its stack for instance ID.
567 *
568 * @param[in] inst_id ID to search for.
569 * @param[in] stack A decoder instance, potentially with stacked instances.
570 *
571 * @return The matching instance, or NULL.
572 */
573static struct srd_decoder_inst *srd_inst_find_by_id_stack(const char *inst_id,
574 struct srd_decoder_inst *stack)
575{
576 const GSList *l;
577 struct srd_decoder_inst *tmp, *di;
578
579 if (!strcmp(stack->inst_id, inst_id))
580 return stack;
581
582 /* Otherwise, look recursively in our stack. */
583 di = NULL;
584 if (stack->next_di) {
585 for (l = stack->next_di; l; l = l->next) {
586 tmp = l->data;
587 if (!strcmp(tmp->inst_id, inst_id)) {
588 di = tmp;
589 break;
590 }
591 }
592 }
593
594 return di;
595}
596
597/**
598 * Find a decoder instance by its instance ID.
599 *
600 * This will recurse to find the instance anywhere in the stack tree of the
601 * given session.
602 *
603 * @param sess The session holding the protocol decoder instance.
604 * Must not be NULL.
605 * @param inst_id The instance ID to be found.
606 *
607 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
608 *
609 * @since 0.3.0
610 */
611SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
612 const char *inst_id)
613{
614 GSList *l;
615 struct srd_decoder_inst *tmp, *di;
616
617 if (!sess)
618 return NULL;
619
620 di = NULL;
621 for (l = sess->di_list; l; l = l->next) {
622 tmp = l->data;
623 if ((di = srd_inst_find_by_id_stack(inst_id, tmp)) != NULL)
624 break;
625 }
626
627 return di;
628}
629
630/**
631 * Set the list of initial (assumed) pin values.
632 *
633 * @param di Decoder instance to use. Must not be NULL.
634 * @param initial_pins A GArray of uint8_t values. Must not be NULL.
635 *
636 * @since 0.5.0
637 */
638SRD_API int srd_inst_initial_pins_set_all(struct srd_decoder_inst *di, GArray *initial_pins)
639{
640 int i;
641 GString *s;
642
643 if (!di) {
644 srd_err("Invalid decoder instance.");
645 return SRD_ERR_ARG;
646 }
647
648 if (!initial_pins)
649 return SRD_ERR_ARG;
650
651 if (initial_pins->len != (guint)di->dec_num_channels) {
652 srd_err("Incorrect number of channels (need %d, got %d).",
653 di->dec_num_channels, initial_pins->len);
654 return SRD_ERR_ARG;
655 }
656
657 /* Sanity-check initial pin state values. */
658 for (i = 0; i < di->dec_num_channels; i++) {
659 if (initial_pins->data[i] <= 2)
660 continue;
661 srd_err("Invalid initial channel %d pin state: %d.",
662 i, initial_pins->data[i]);
663 return SRD_ERR_ARG;
664 }
665
666 s = g_string_sized_new(100);
667 oldpins_array_seed(di);
668 for (i = 0; i < di->dec_num_channels; i++) {
669 di->old_pins_array->data[i] = initial_pins->data[i];
670 g_string_append_printf(s, "%d, ", di->old_pins_array->data[i]);
671 }
672 s = g_string_truncate(s, s->len - 2);
673 srd_dbg("Initial pins: %s.", s->str);
674 g_string_free(s, TRUE);
675
676 return SRD_OK;
677}
678
679/** @private */
680SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
681{
682 PyObject *py_res, *py_samplenum;
683 GSList *l;
684 struct srd_decoder_inst *next_di;
685 int ret;
686 PyGILState_STATE gstate;
687
688 srd_dbg("Calling start() of instance %s.", di->inst_id);
689
690 gstate = PyGILState_Ensure();
691
692 /* Run self.start(). */
693 if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
694 srd_exception_catch("Protocol decoder instance %s",
695 di->inst_id);
696 PyGILState_Release(gstate);
697 return SRD_ERR_PYTHON;
698 }
699 Py_DECREF(py_res);
700
701 /* Set self.samplenum to 0. */
702 py_samplenum = PyLong_FromLong(0);
703 PyObject_SetAttrString(di->py_inst, "samplenum", py_samplenum);
704 Py_DECREF(py_samplenum);
705
706 /* Set self.matched to None. */
707 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
708
709 PyGILState_Release(gstate);
710
711 /* Start all the PDs stacked on top of this one. */
712 for (l = di->next_di; l; l = l->next) {
713 next_di = l->data;
714 if ((ret = srd_inst_start(next_di)) != SRD_OK)
715 return ret;
716 }
717
718 return SRD_OK;
719}
720
721/**
722 * Check whether the specified sample matches the specified term.
723 *
724 * In the case of SRD_TERM_SKIP, this function can modify
725 * term->num_samples_already_skipped.
726 *
727 * @param old_sample The value of the previous sample (0/1).
728 * @param sample The value of the current sample (0/1).
729 * @param term The term that should be checked for a match. Must not be NULL.
730 *
731 * @retval TRUE The current sample matches the specified term.
732 * @retval FALSE The current sample doesn't match the specified term, or an
733 * invalid term was provided.
734 *
735 * @private
736 */
737__attribute__((always_inline))
738static inline gboolean sample_matches(uint8_t old_sample, uint8_t sample, struct srd_term *term)
739{
740 /* Caller ensures term != NULL. */
741
742 switch (term->type) {
743 case SRD_TERM_HIGH:
744 if (sample == 1)
745 return TRUE;
746 break;
747 case SRD_TERM_LOW:
748 if (sample == 0)
749 return TRUE;
750 break;
751 case SRD_TERM_RISING_EDGE:
752 if (old_sample == 0 && sample == 1)
753 return TRUE;
754 break;
755 case SRD_TERM_FALLING_EDGE:
756 if (old_sample == 1 && sample == 0)
757 return TRUE;
758 break;
759 case SRD_TERM_EITHER_EDGE:
760 if ((old_sample == 1 && sample == 0) || (old_sample == 0 && sample == 1))
761 return TRUE;
762 break;
763 case SRD_TERM_NO_EDGE:
764 if ((old_sample == 0 && sample == 0) || (old_sample == 1 && sample == 1))
765 return TRUE;
766 break;
767 case SRD_TERM_SKIP:
768 if (term->num_samples_already_skipped == term->num_samples_to_skip)
769 return TRUE;
770 term->num_samples_already_skipped++;
771 break;
772 default:
773 srd_err("Unknown term type %d.", term->type);
774 break;
775 }
776
777 return FALSE;
778}
779
780/** @private */
781SRD_PRIV void match_array_free(struct srd_decoder_inst *di)
782{
783 if (!di || !di->match_array)
784 return;
785
786 g_array_free(di->match_array, TRUE);
787 di->match_array = NULL;
788}
789
790/** @private */
791SRD_PRIV void condition_list_free(struct srd_decoder_inst *di)
792{
793 GSList *l, *ll;
794
795 if (!di)
796 return;
797
798 for (l = di->condition_list; l; l = l->next) {
799 ll = l->data;
800 if (ll)
801 g_slist_free_full(ll, g_free);
802 }
803
804 g_slist_free(di->condition_list);
805 di->condition_list = NULL;
806}
807
808static gboolean have_non_null_conds(const struct srd_decoder_inst *di)
809{
810 GSList *l, *cond;
811
812 if (!di)
813 return FALSE;
814
815 for (l = di->condition_list; l; l = l->next) {
816 cond = l->data;
817 if (cond)
818 return TRUE;
819 }
820
821 return FALSE;
822}
823
824static void update_old_pins_array(struct srd_decoder_inst *di,
825 const uint8_t *sample_pos)
826{
827 uint8_t sample;
828 int i, byte_offset, bit_offset;
829
830 if (!di || !di->dec_channelmap || !sample_pos)
831 return;
832
833 oldpins_array_seed(di);
834 for (i = 0; i < di->dec_num_channels; i++) {
835 if (di->dec_channelmap[i] == -1)
836 continue; /* Ignore unused optional channels. */
837 byte_offset = di->dec_channelmap[i] / 8;
838 bit_offset = di->dec_channelmap[i] % 8;
839 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
840 di->old_pins_array->data[i] = sample;
841 }
842}
843
844static void update_old_pins_array_initial_pins(struct srd_decoder_inst *di)
845{
846 uint8_t sample;
847 int i, byte_offset, bit_offset;
848 const uint8_t *sample_pos;
849
850 if (!di || !di->dec_channelmap)
851 return;
852
853 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
854
855 oldpins_array_seed(di);
856 for (i = 0; i < di->dec_num_channels; i++) {
857 if (di->old_pins_array->data[i] != SRD_INITIAL_PIN_SAME_AS_SAMPLE0)
858 continue;
859 if (di->dec_channelmap[i] == -1)
860 continue; /* Ignore unused optional channels. */
861 byte_offset = di->dec_channelmap[i] / 8;
862 bit_offset = di->dec_channelmap[i] % 8;
863 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
864 di->old_pins_array->data[i] = sample;
865 }
866}
867
868static gboolean term_matches(const struct srd_decoder_inst *di,
869 struct srd_term *term, const uint8_t *sample_pos)
870{
871 uint8_t old_sample, sample;
872 int byte_offset, bit_offset, ch;
873
874 /* Caller ensures di, di->dec_channelmap, term, sample_pos != NULL. */
875
876 if (term->type == SRD_TERM_SKIP)
877 return sample_matches(0, 0, term);
878
879 ch = term->channel;
880 byte_offset = di->dec_channelmap[ch] / 8;
881 bit_offset = di->dec_channelmap[ch] % 8;
882 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
883 old_sample = di->old_pins_array->data[ch];
884
885 return sample_matches(old_sample, sample, term);
886}
887
888static gboolean all_terms_match(const struct srd_decoder_inst *di,
889 const GSList *cond, const uint8_t *sample_pos)
890{
891 const GSList *l;
892 struct srd_term *term;
893
894 /* Caller ensures di, cond, sample_pos != NULL. */
895
896 for (l = cond; l; l = l->next) {
897 term = l->data;
898 if (term->type == SRD_TERM_ALWAYS_FALSE)
899 return FALSE;
900 if (!term_matches(di, term, sample_pos))
901 return FALSE;
902 }
903
904 return TRUE;
905}
906
907static gboolean at_least_one_condition_matched(
908 const struct srd_decoder_inst *di, unsigned int num_conditions)
909{
910 unsigned int i;
911
912 /* Caller ensures di != NULL. */
913
914 for (i = 0; i < num_conditions; i++) {
915 if (di->match_array->data[i])
916 return TRUE;
917 }
918
919 return FALSE;
920}
921
922static gboolean find_match(struct srd_decoder_inst *di)
923{
924 uint64_t i, j, num_samples_to_process;
925 GSList *l, *cond;
926 const uint8_t *sample_pos;
927 unsigned int num_conditions;
928
929 /* Caller ensures di != NULL. */
930
931 /* Check whether the condition list is NULL/empty. */
932 if (!di->condition_list) {
933 srd_dbg("NULL/empty condition list, automatic match.");
934 return TRUE;
935 }
936
937 /* Check whether we have any non-NULL conditions. */
938 if (!have_non_null_conds(di)) {
939 srd_dbg("Only NULL conditions in list, automatic match.");
940 return TRUE;
941 }
942
943 num_samples_to_process = di->abs_end_samplenum - di->abs_cur_samplenum;
944 num_conditions = g_slist_length(di->condition_list);
945
946 /* di->match_array is NULL here. Create a new GArray. */
947 di->match_array = g_array_sized_new(FALSE, TRUE, sizeof(gboolean), num_conditions);
948 g_array_set_size(di->match_array, num_conditions);
949
950 /* Sample 0: Set di->old_pins_array for SRD_INITIAL_PIN_SAME_AS_SAMPLE0 pins. */
951 if (di->abs_cur_samplenum == 0)
952 update_old_pins_array_initial_pins(di);
953
954 for (i = 0; i < num_samples_to_process; i++, (di->abs_cur_samplenum)++) {
955
956 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
957
958 /* Check whether the current sample matches at least one of the conditions (logical OR). */
959 /* IMPORTANT: We need to check all conditions, even if there was a match already! */
960 for (l = di->condition_list, j = 0; l; l = l->next, j++) {
961 cond = l->data;
962 if (!cond)
963 continue;
964 /* All terms in 'cond' must match (logical AND). */
965 di->match_array->data[j] = all_terms_match(di, cond, sample_pos);
966 }
967
968 update_old_pins_array(di, sample_pos);
969
970 /* If at least one condition matched we're done. */
971 if (at_least_one_condition_matched(di, num_conditions))
972 return TRUE;
973 }
974
975 return FALSE;
976}
977
978/**
979 * Process available samples and check if they match the defined conditions.
980 *
981 * This function returns if there is an error, or when a match is found, or
982 * when all samples have been processed (whether a match was found or not).
983 * This function immediately terminates when the decoder's wait() method
984 * invocation shall get terminated.
985 *
986 * @param di The decoder instance to use. Must not be NULL.
987 * @param found_match Will be set to TRUE if at least one condition matched,
988 * FALSE otherwise. Must not be NULL.
989 *
990 * @retval SRD_OK No errors occured, see found_match for the result.
991 * @retval SRD_ERR_ARG Invalid arguments.
992 *
993 * @private
994 */
995SRD_PRIV int process_samples_until_condition_match(struct srd_decoder_inst *di, gboolean *found_match)
996{
997 if (!di || !found_match)
998 return SRD_ERR_ARG;
999
1000 *found_match = FALSE;
1001 if (di->want_wait_terminate)
1002 return SRD_OK;
1003
1004 /* Check if any of the current condition(s) match. */
1005 while (TRUE) {
1006 /* Feed the (next chunk of the) buffer to find_match(). */
1007 *found_match = find_match(di);
1008
1009 /* Did we handle all samples yet? */
1010 if (di->abs_cur_samplenum >= di->abs_end_samplenum) {
1011 srd_dbg("Done, handled all samples (abs cur %" PRIu64
1012 " / abs end %" PRIu64 ").",
1013 di->abs_cur_samplenum, di->abs_end_samplenum);
1014 return SRD_OK;
1015 }
1016
1017 /* If we didn't find a match, continue looking. */
1018 if (!(*found_match))
1019 continue;
1020
1021 /* At least one condition matched, return. */
1022 return SRD_OK;
1023 }
1024
1025 return SRD_OK;
1026}
1027
1028/**
1029 * Worker thread (per PD-stack).
1030 *
1031 * @param data Pointer to the lowest-level PD's device instance.
1032 * Must not be NULL.
1033 *
1034 * @return NULL if there was an error.
1035 */
1036static gpointer di_thread(gpointer data)
1037{
1038 PyObject *py_res;
1039 struct srd_decoder_inst *di;
1040 int wanted_term;
1041 PyGILState_STATE gstate;
1042
1043 if (!data)
1044 return NULL;
1045
1046 di = data;
1047
1048 srd_dbg("%s: Starting thread routine for decoder.", di->inst_id);
1049
1050 gstate = PyGILState_Ensure();
1051
1052 /*
1053 * Call self.decode(). Only returns if the PD throws an exception.
1054 * "Regular" termination of the decode() method is not expected.
1055 */
1056 Py_INCREF(di->py_inst);
1057 srd_dbg("%s: Calling decode().", di->inst_id);
1058 py_res = PyObject_CallMethod(di->py_inst, "decode", NULL);
1059 srd_dbg("%s: decode() terminated.", di->inst_id);
1060
1061 if (!py_res)
1062 di->decoder_state = SRD_ERR;
1063
1064 /*
1065 * Make sure to unblock potentially pending srd_inst_decode()
1066 * calls in application threads after the decode() method might
1067 * have terminated, while it neither has processed sample data
1068 * nor has terminated upon request. This happens e.g. when "need
1069 * a samplerate to decode" exception is thrown.
1070 */
1071 g_mutex_lock(&di->data_mutex);
1072 wanted_term = di->want_wait_terminate;
1073 di->want_wait_terminate = TRUE;
1074 di->handled_all_samples = TRUE;
1075 g_cond_signal(&di->handled_all_samples_cond);
1076 g_mutex_unlock(&di->data_mutex);
1077
1078 /*
1079 * Check for the termination cause of the decode() method.
1080 * Though this is mostly for information.
1081 */
1082 if (!py_res && wanted_term) {
1083 /*
1084 * Silently ignore errors upon return from decode() calls
1085 * when termination was requested. Terminate the thread
1086 * which executed this instance's decode() logic.
1087 */
1088 srd_dbg("%s: Thread done (!res, want_term).", di->inst_id);
1089 PyErr_Clear();
1090 PyGILState_Release(gstate);
1091 return NULL;
1092 }
1093 if (!py_res) {
1094 /*
1095 * The decode() invocation terminated unexpectedly. Have
1096 * the back trace printed, and terminate the thread which
1097 * executed the decode() method.
1098 */
1099 srd_dbg("%s: decode() terminated unrequested.", di->inst_id);
1100 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
1101 srd_dbg("%s: Thread done (!res, !want_term).", di->inst_id);
1102 PyGILState_Release(gstate);
1103 return NULL;
1104 }
1105
1106 /*
1107 * TODO: By design the decode() method is not supposed to terminate.
1108 * Nevertheless we have the thread joined, and srd backend calls to
1109 * decode() will re-start another thread transparently.
1110 */
1111 srd_dbg("%s: decode() terminated (req %d).", di->inst_id, wanted_term);
1112 Py_DECREF(py_res);
1113 PyErr_Clear();
1114
1115 PyGILState_Release(gstate);
1116
1117 srd_dbg("%s: Thread done (with res).", di->inst_id);
1118
1119 return NULL;
1120}
1121
1122/**
1123 * Decode a chunk of samples.
1124 *
1125 * The calls to this function must provide the samples that shall be
1126 * used by the protocol decoder
1127 * - in the correct order ([...]5, 6, 4, 7, 8[...] is a bug),
1128 * - starting from sample zero (2, 3, 4, 5, 6[...] is a bug),
1129 * - consecutively, with no gaps (0, 1, 2, 4, 5[...] is a bug).
1130 *
1131 * The start- and end-sample numbers are absolute sample numbers (relative
1132 * to the start of the whole capture/file/stream), i.e. they are not relative
1133 * sample numbers within the chunk specified by 'inbuf' and 'inbuflen'.
1134 *
1135 * Correct example (4096 samples total, 4 chunks @ 1024 samples each):
1136 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1137 * srd_inst_decode(di, 1024, 2048, inbuf, 1024, 1);
1138 * srd_inst_decode(di, 2048, 3072, inbuf, 1024, 1);
1139 * srd_inst_decode(di, 3072, 4096, inbuf, 1024, 1);
1140 *
1141 * The chunk size ('inbuflen') can be arbitrary and can differ between calls.
1142 *
1143 * Correct example (4096 samples total, 7 chunks @ various samples each):
1144 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1145 * srd_inst_decode(di, 1024, 1124, inbuf, 100, 1);
1146 * srd_inst_decode(di, 1124, 1424, inbuf, 300, 1);
1147 * srd_inst_decode(di, 1424, 1643, inbuf, 219, 1);
1148 * srd_inst_decode(di, 1643, 2048, inbuf, 405, 1);
1149 * srd_inst_decode(di, 2048, 3072, inbuf, 1024, 1);
1150 * srd_inst_decode(di, 3072, 4096, inbuf, 1024, 1);
1151 *
1152 * INCORRECT example (4096 samples total, 4 chunks @ 1024 samples each, but
1153 * the start- and end-samplenumbers are not absolute):
1154 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1155 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1156 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1157 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1158 *
1159 * @param di The decoder instance to call. Must not be NULL.
1160 * @param abs_start_samplenum The absolute starting sample number for the
1161 * buffer's sample set, relative to the start of capture.
1162 * @param abs_end_samplenum The absolute ending sample number for the
1163 * buffer's sample set, relative to the start of capture.
1164 * @param inbuf The buffer to decode. Must not be NULL.
1165 * @param inbuflen Length of the buffer. Must be > 0.
1166 * @param unitsize The number of bytes per sample. Must be > 0.
1167 *
1168 * @return SRD_OK upon success, a (negative) error code otherwise.
1169 *
1170 * @private
1171 */
1172SRD_PRIV int srd_inst_decode(struct srd_decoder_inst *di,
1173 uint64_t abs_start_samplenum, uint64_t abs_end_samplenum,
1174 const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
1175{
1176 /* Return an error upon unusable input. */
1177 if (!di) {
1178 srd_dbg("empty decoder instance");
1179 return SRD_ERR_ARG;
1180 }
1181 if (!inbuf) {
1182 srd_dbg("NULL buffer pointer");
1183 return SRD_ERR_ARG;
1184 }
1185 if (inbuflen == 0) {
1186 srd_dbg("empty buffer");
1187 return SRD_ERR_ARG;
1188 }
1189 if (unitsize == 0) {
1190 srd_dbg("unitsize 0");
1191 return SRD_ERR_ARG;
1192 }
1193
1194 if (abs_start_samplenum != di->abs_cur_samplenum ||
1195 abs_end_samplenum < abs_start_samplenum) {
1196 srd_dbg("Incorrect sample numbers: start=%" PRIu64 ", cur=%"
1197 PRIu64 ", end=%" PRIu64 ".", abs_start_samplenum,
1198 di->abs_cur_samplenum, abs_end_samplenum);
1199 return SRD_ERR_ARG;
1200 }
1201
1202 di->data_unitsize = unitsize;
1203
1204 srd_dbg("Decoding: abs start sample %" PRIu64 ", abs end sample %"
1205 PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
1206 "%d), instance %s.", abs_start_samplenum, abs_end_samplenum,
1207 abs_end_samplenum - abs_start_samplenum, inbuflen, di->data_unitsize,
1208 di->inst_id);
1209
1210 /* If this is the first call, start the worker thread. */
1211 if (!di->thread_handle) {
1212 srd_dbg("No worker thread for this decoder stack "
1213 "exists yet, creating one: %s.", di->inst_id);
1214 di->thread_handle = g_thread_new(di->inst_id,
1215 di_thread, di);
1216 }
1217
1218 /* Push the new sample chunk to the worker thread. */
1219 g_mutex_lock(&di->data_mutex);
1220 di->abs_start_samplenum = abs_start_samplenum;
1221 di->abs_end_samplenum = abs_end_samplenum;
1222 di->inbuf = inbuf;
1223 di->inbuflen = inbuflen;
1224 di->got_new_samples = TRUE;
1225 di->handled_all_samples = FALSE;
1226
1227 /* Signal the thread that we have new data. */
1228 g_cond_signal(&di->got_new_samples_cond);
1229 g_mutex_unlock(&di->data_mutex);
1230
1231 /* When all samples in this chunk were handled, return. */
1232 g_mutex_lock(&di->data_mutex);
1233 while (!di->handled_all_samples && !di->want_wait_terminate)
1234 g_cond_wait(&di->handled_all_samples_cond, &di->data_mutex);
1235 g_mutex_unlock(&di->data_mutex);
1236
1237 if (di->want_wait_terminate)
1238 return SRD_ERR_TERM_REQ;
1239
1240 return SRD_OK;
1241}
1242
1243/**
1244 * Terminate current decoder work, prepare for re-use on new input data.
1245 *
1246 * Terminates all decoder operations in the specified decoder instance
1247 * and the instances stacked on top of it. Resets internal state such
1248 * that the previously constructed stack can process new input data that
1249 * is not related to previously processed input data. This avoids the
1250 * expensive and complex re-construction of decoder stacks.
1251 *
1252 * Callers are expected to follow up with start, metadata, and decode
1253 * calls like they would for newly constructed decoder stacks.
1254 *
1255 * @param di The decoder instance to call. Must not be NULL.
1256 *
1257 * @return SRD_OK upon success, a (negative) error code otherwise.
1258 *
1259 * @private
1260 */
1261SRD_PRIV int srd_inst_terminate_reset(struct srd_decoder_inst *di)
1262{
1263 PyGILState_STATE gstate;
1264 PyObject *py_ret;
1265 GSList *l;
1266 int ret;
1267
1268 if (!di)
1269 return SRD_ERR_ARG;
1270
1271 /*
1272 * Request termination and wait for previously initiated
1273 * background operation to finish. Reset internal state, but
1274 * do not start releasing resources yet. This shall result in
1275 * decoders' state just like after creation. This block handles
1276 * the C language library side.
1277 */
1278 srd_dbg("Terminating instance %s", di->inst_id);
1279 srd_inst_join_decode_thread(di);
1280 srd_inst_reset_state(di);
1281
1282 /*
1283 * Have the Python side's .reset() method executed (if the PD
1284 * implements it). It's assumed that .reset() assigns variables
1285 * very much like __init__() used to do in the past. Thus memory
1286 * that was allocated in previous calls gets released by Python
1287 * as it's not referenced any longer.
1288 */
1289 gstate = PyGILState_Ensure();
1290 if (PyObject_HasAttrString(di->py_inst, "reset")) {
1291 srd_dbg("Calling reset() of instance %s", di->inst_id);
1292 py_ret = PyObject_CallMethod(di->py_inst, "reset", NULL);
1293 Py_XDECREF(py_ret);
1294 }
1295 PyGILState_Release(gstate);
1296
1297 /* Pass the "restart" request to all stacked decoders. */
1298 for (l = di->next_di; l; l = l->next) {
1299 ret = srd_inst_terminate_reset(l->data);
1300 if (ret != SRD_OK)
1301 return ret;
1302 }
1303
1304 return di->decoder_state;
1305}
1306
1307/** @private */
1308SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
1309{
1310 GSList *l;
1311 struct srd_pd_output *pdo;
1312 PyGILState_STATE gstate;
1313
1314 srd_dbg("Freeing instance %s.", di->inst_id);
1315
1316 srd_inst_join_decode_thread(di);
1317
1318 srd_inst_reset_state(di);
1319
1320 gstate = PyGILState_Ensure();
1321 Py_DECREF(di->py_inst);
1322 PyGILState_Release(gstate);
1323
1324 g_free(di->inst_id);
1325 g_free(di->dec_channelmap);
1326 g_free(di->channel_samples);
1327 g_slist_free(di->next_di);
1328 for (l = di->pd_output; l; l = l->next) {
1329 pdo = l->data;
1330 g_free(pdo->proto_id);
1331 g_free(pdo);
1332 }
1333 g_slist_free(di->pd_output);
1334 g_free(di);
1335}
1336
1337/** @private */
1338SRD_PRIV void srd_inst_free_all(struct srd_session *sess)
1339{
1340 if (!sess)
1341 return;
1342
1343 g_slist_free_full(sess->di_list, (GDestroyNotify)srd_inst_free);
1344}
1345
1346/** @} */