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