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