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