]> sigrok.org Git - libsigrokdecode.git/blob - instance.c
qi: Convert to PD API version 3
[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         srd_dbg("Creating new %s instance.", decoder_id);
301
302         if (session_is_valid(sess) != SRD_OK) {
303                 srd_err("Invalid session.");
304                 return NULL;
305         }
306
307         if (!(dec = srd_decoder_get_by_id(decoder_id))) {
308                 srd_err("Protocol decoder %s not found.", decoder_id);
309                 return NULL;
310         }
311
312         di = g_malloc0(sizeof(struct srd_decoder_inst));
313
314         di->decoder = dec;
315         di->sess = sess;
316         if (options) {
317                 inst_id = g_hash_table_lookup(options, "id");
318                 di->inst_id = g_strdup(inst_id ? inst_id : decoder_id);
319                 g_hash_table_remove(options, "id");
320         } else
321                 di->inst_id = g_strdup(decoder_id);
322
323         /*
324          * Prepare a default channel map, where samples come in the
325          * order in which the decoder class defined them.
326          */
327         di->dec_num_channels = g_slist_length(di->decoder->channels) +
328                         g_slist_length(di->decoder->opt_channels);
329         if (di->dec_num_channels) {
330                 di->dec_channelmap =
331                                 g_malloc(sizeof(int) * di->dec_num_channels);
332                 for (i = 0; i < di->dec_num_channels; i++)
333                         di->dec_channelmap[i] = i;
334                 /*
335                  * Will be used to prepare a sample at every iteration
336                  * of the instance's decode() method.
337                  */
338                 di->channel_samples = g_malloc(di->dec_num_channels);
339         }
340
341         /* Create a new instance of this decoder class. */
342         if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
343                 if (PyErr_Occurred())
344                         srd_exception_catch("Failed to create %s instance",
345                                         decoder_id);
346                 g_free(di->dec_channelmap);
347                 g_free(di);
348                 return NULL;
349         }
350
351         if (options && srd_inst_option_set(di, options) != SRD_OK) {
352                 g_free(di->dec_channelmap);
353                 g_free(di);
354                 return NULL;
355         }
356
357         di->condition_list = NULL;
358         di->match_array = NULL;
359         di->start_samplenum = 0;
360         di->end_samplenum = 0;
361         di->inbuf = NULL;
362         di->inbuflen = 0;
363         di->cur_samplenum = 0;
364         di->old_pins_array = NULL;
365         di->thread_handle = NULL;
366         di->got_new_samples = FALSE;
367         di->handled_all_samples = FALSE;
368
369         /* Instance takes input from a frontend by default. */
370         sess->di_list = g_slist_append(sess->di_list, di);
371
372         return di;
373 }
374
375 /**
376  * Stack a decoder instance on top of another.
377  *
378  * @param sess The session holding the protocol decoder instances.
379  * @param di_bottom The instance on top of which di_top will be stacked.
380  * @param di_top The instance to go on top.
381  *
382  * @return SRD_OK upon success, a (negative) error code otherwise.
383  *
384  * @since 0.3.0
385  */
386 SRD_API int srd_inst_stack(struct srd_session *sess,
387                 struct srd_decoder_inst *di_bottom,
388                 struct srd_decoder_inst *di_top)
389 {
390
391         if (session_is_valid(sess) != SRD_OK) {
392                 srd_err("Invalid session.");
393                 return SRD_ERR_ARG;
394         }
395
396         if (!di_bottom || !di_top) {
397                 srd_err("Invalid from/to instance pair.");
398                 return SRD_ERR_ARG;
399         }
400
401         if (g_slist_find(sess->di_list, di_top)) {
402                 /* Remove from the unstacked list. */
403                 sess->di_list = g_slist_remove(sess->di_list, di_top);
404         }
405
406         /* Stack on top of source di. */
407         di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
408
409         srd_dbg("Stacked %s onto %s.", di_top->inst_id, di_bottom->inst_id);
410
411         return SRD_OK;
412 }
413
414 /**
415  * Find a decoder instance by its instance ID.
416  *
417  * Only the bottom level of instances are searched -- instances already stacked
418  * on top of another one will not be found.
419  *
420  * @param sess The session holding the protocol decoder instance.
421  * @param inst_id The instance ID to be found.
422  *
423  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
424  *
425  * @since 0.3.0
426  */
427 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
428                 const char *inst_id)
429 {
430         GSList *l;
431         struct srd_decoder_inst *tmp, *di;
432
433         if (session_is_valid(sess) != SRD_OK) {
434                 srd_err("Invalid session.");
435                 return NULL;
436         }
437
438         di = NULL;
439         for (l = sess->di_list; l; l = l->next) {
440                 tmp = l->data;
441                 if (!strcmp(tmp->inst_id, inst_id)) {
442                         di = tmp;
443                         break;
444                 }
445         }
446
447         return di;
448 }
449
450 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
451                 struct srd_session *sess, const GSList *stack,
452                 const PyObject *obj)
453 {
454         const GSList *l;
455         struct srd_decoder_inst *tmp, *di;
456
457         if (session_is_valid(sess) != SRD_OK) {
458                 srd_err("Invalid session.");
459                 return NULL;
460         }
461
462         di = NULL;
463         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
464                 tmp = l->data;
465                 if (tmp->py_inst == obj)
466                         di = tmp;
467                 else if (tmp->next_di)
468                         di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
469         }
470
471         return di;
472 }
473
474 /**
475  * Find a decoder instance by its Python object.
476  *
477  * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
478  * This will recurse to find the instance anywhere in the stack tree of all
479  * sessions.
480  *
481  * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
482  *              stack to search. To start searching at the bottom level of
483  *              decoder instances, pass NULL.
484  * @param obj The Python class instantiation.
485  *
486  * @return Pointer to struct srd_decoder_inst, or NULL if not found.
487  *
488  * @private
489  *
490  * @since 0.1.0
491  */
492 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
493                 const PyObject *obj)
494 {
495         struct srd_decoder_inst *di;
496         struct srd_session *sess;
497         GSList *l;
498
499         di = NULL;
500         for (l = sessions; di == NULL && l != NULL; l = l->next) {
501                 sess = l->data;
502                 di = srd_sess_inst_find_by_obj(sess, stack, obj);
503         }
504
505         return di;
506 }
507
508 /**
509  * Set the list of initial (assumed) pin values.
510  *
511  * If the list already exists, do nothing.
512  *
513  * @param di Decoder instance to use. Must not be NULL.
514  *
515  * @private
516  */
517 static void set_initial_pin_values(struct srd_decoder_inst *di)
518 {
519         int i;
520         GString *s;
521         PyObject *py_initial_pins;
522
523         if (!di || !di->py_inst) {
524                 srd_err("Invalid decoder instance.");
525                 return;
526         }
527
528         /* Nothing to do if di->old_pins_array is already != NULL. */
529         if (di->old_pins_array) {
530                 srd_dbg("Initial pins already set, nothing to do.");
531                 return;
532         }
533
534         /* Create an array of old (previous sample) pins, init to 0. */
535         di->old_pins_array = g_array_sized_new(FALSE, TRUE, sizeof(uint8_t), di->dec_num_channels);
536         g_array_set_size(di->old_pins_array, di->dec_num_channels);
537
538         /* Check if the decoder has set self.initial_pins. */
539         if (!PyObject_HasAttrString(di->py_inst, "initial_pins")) {
540                 srd_dbg("Initial pins: all 0 (self.initial_pins not set).");
541                 return;
542         }
543
544         /* Get self.initial_pins. */
545         py_initial_pins = PyObject_GetAttrString(di->py_inst, "initial_pins");
546
547         /* Fill di->old_pins_array based on self.initial_pins. */
548         s = g_string_sized_new(100);
549         for (i = 0; i < di->dec_num_channels; i++) {
550                 di->old_pins_array->data[i] = PyLong_AsLong(PyList_GetItem(py_initial_pins, i));
551                 g_string_append_printf(s, "%d, ", di->old_pins_array->data[i]);
552         }
553         s = g_string_truncate(s, s->len - 2);
554         srd_dbg("Initial pins: %s.", s->str);
555         g_string_free(s, TRUE);
556 }
557
558 /** @private */
559 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
560 {
561         PyObject *py_res;
562         GSList *l;
563         struct srd_decoder_inst *next_di;
564         int ret;
565
566         srd_dbg("Calling start() method on protocol decoder instance %s.",
567                         di->inst_id);
568
569         /* Run self.start(). */
570         if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
571                 srd_exception_catch("Protocol decoder instance %s",
572                                 di->inst_id);
573                 return SRD_ERR_PYTHON;
574         }
575         Py_DecRef(py_res);
576
577         /* Set the initial pins based on self.initial_pins. */
578         set_initial_pin_values(di);
579
580         /* Set self.samplenum to 0. */
581         PyObject_SetAttrString(di->py_inst, "samplenum", PyLong_FromLong(0));
582
583         /* Set self.matches to None. */
584         PyObject_SetAttrString(di->py_inst, "matches", Py_None);
585
586         /* Start all the PDs stacked on top of this one. */
587         for (l = di->next_di; l; l = l->next) {
588                 next_di = l->data;
589                 if ((ret = srd_inst_start(next_di)) != SRD_OK)
590                         return ret;
591         }
592
593         return SRD_OK;
594 }
595
596 /**
597  * Check whether the specified sample matches the specified term.
598  *
599  * In the case of SRD_TERM_SKIP, this function can modify
600  * term->num_samples_already_skipped.
601  *
602  * @param old_sample The value of the previous sample (0/1).
603  * @param sample The value of the current sample (0/1).
604  * @param term The term that should be checked for a match. Must not be NULL.
605  *
606  * @retval TRUE The current sample matches the specified term.
607  * @retval FALSE The current sample doesn't match the specified term, or an
608  *               invalid term was provided.
609  *
610  * @private
611  */
612 static gboolean sample_matches(uint8_t old_sample, uint8_t sample, struct srd_term *term)
613 {
614         if (!term)
615                 return FALSE;
616
617         switch (term->type) {
618         case SRD_TERM_HIGH:
619                 if (sample == 1)
620                         return TRUE;
621                 break;
622         case SRD_TERM_LOW:
623                 if (sample == 0)
624                         return TRUE;
625                 break;
626         case SRD_TERM_RISING_EDGE:
627                 if (old_sample == 0 && sample == 1)
628                         return TRUE;
629                 break;
630         case SRD_TERM_FALLING_EDGE:
631                 if (old_sample == 1 && sample == 0)
632                         return TRUE;
633                 break;
634         case SRD_TERM_EITHER_EDGE:
635                 if ((old_sample == 1 && sample == 0) || (old_sample == 0 && sample == 1))
636                         return TRUE;
637                 break;
638         case SRD_TERM_NO_EDGE:
639                 if ((old_sample == 0 && sample == 0) || (old_sample == 1 && sample == 1))
640                         return TRUE;
641                 break;
642         case SRD_TERM_SKIP:
643                 if (term->num_samples_already_skipped == term->num_samples_to_skip)
644                         return TRUE;
645                 term->num_samples_already_skipped++;
646                 break;
647         default:
648                 srd_err("Unknown term type %d.", term->type);
649                 break;
650         }
651
652         return FALSE;
653 }
654
655 SRD_PRIV void match_array_free(struct srd_decoder_inst *di)
656 {
657         if (!di || !di->match_array)
658                 return;
659
660         g_array_free(di->match_array, TRUE);
661         di->match_array = NULL;
662 }
663
664 SRD_PRIV void condition_list_free(struct srd_decoder_inst *di)
665 {
666         GSList *l, *ll;
667
668         if (!di)
669                 return;
670
671         for (l = di->condition_list; l; l = l->next) {
672                 ll = l->data;
673                 if (ll)
674                         g_slist_free_full(ll, g_free);
675         }
676
677         di->condition_list = NULL;
678 }
679
680 static gboolean have_non_null_conds(const struct srd_decoder_inst *di)
681 {
682         GSList *l, *cond;
683
684         if (!di)
685                 return FALSE;
686
687         for (l = di->condition_list; l; l = l->next) {
688                 cond = l->data;
689                 if (cond)
690                         return TRUE;
691         }
692
693         return FALSE;
694 }
695
696 static void update_old_pins_array(struct srd_decoder_inst *di,
697                 const uint8_t *sample_pos)
698 {
699         uint8_t sample;
700         int i, byte_offset, bit_offset;
701
702         if (!di || !di->dec_channelmap || !sample_pos)
703                 return;
704
705         for (i = 0; i < di->dec_num_channels; i++) {
706                 byte_offset = di->dec_channelmap[i] / 8;
707                 bit_offset = di->dec_channelmap[i] % 8;
708                 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
709                 di->old_pins_array->data[i] = sample;
710         }
711 }
712
713 static gboolean term_matches(const struct srd_decoder_inst *di,
714                 struct srd_term *term, const uint8_t *sample_pos)
715 {
716         uint8_t old_sample, sample;
717         int byte_offset, bit_offset, ch;
718
719         if (!di || !di->dec_channelmap || !term || !sample_pos)
720                 return FALSE;
721
722         /* Overwritten below (or ignored for SRD_TERM_SKIP). */
723         old_sample = sample = 0;
724
725         if (term->type != SRD_TERM_SKIP) {
726                 ch = term->channel;
727                 byte_offset = di->dec_channelmap[ch] / 8;
728                 bit_offset = di->dec_channelmap[ch] % 8;
729                 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
730                 old_sample = di->old_pins_array->data[ch];
731         }
732
733         return sample_matches(old_sample, sample, term);
734 }
735
736 static gboolean all_terms_match(const struct srd_decoder_inst *di,
737                 const GSList *cond, const uint8_t *sample_pos)
738 {
739         const GSList *l;
740         struct srd_term *term;
741
742         if (!di || !cond || !sample_pos)
743                 return FALSE;
744
745         for (l = cond; l; l = l->next) {
746                 term = l->data;
747                 if (!term_matches(di, term, sample_pos))
748                         return FALSE;
749         }
750
751         return TRUE;
752 }
753
754 static gboolean at_least_one_condition_matched(
755                 const struct srd_decoder_inst *di, unsigned int num_conditions)
756 {
757         unsigned int i;
758
759         if (!di)
760                 return FALSE;
761
762         for (i = 0; i < num_conditions; i++) {
763                 if (di->match_array->data[i])
764                         return TRUE;
765         }
766
767         return FALSE;
768 }
769
770 static gboolean find_match(struct srd_decoder_inst *di)
771 {
772         static uint64_t s = 0;
773         uint64_t i, j, num_samples_to_process;
774         GSList *l, *cond;
775         const uint8_t *sample_pos;
776         unsigned int num_conditions;
777
778         /* Check whether the condition list is NULL/empty. */
779         if (!di->condition_list) {
780                 srd_dbg("NULL/empty condition list, automatic match.");
781                 return TRUE;
782         }
783
784         /* Check whether we have any non-NULL conditions. */
785         if (!have_non_null_conds(di)) {
786                 srd_dbg("Only NULL conditions in list, automatic match.");
787                 return TRUE;
788         }
789
790         num_samples_to_process = di->end_samplenum - di->cur_samplenum;
791         num_conditions = g_slist_length(di->condition_list);
792
793         /* di->match_array is NULL here. Create a new GArray. */
794         di->match_array = g_array_sized_new(FALSE, TRUE, sizeof(gboolean), num_conditions);
795         g_array_set_size(di->match_array, num_conditions);
796
797         for (i = 0, s = 0; i < num_samples_to_process; i++, s++, (di->cur_samplenum)++) {
798
799                 sample_pos = di->inbuf + ((di->cur_samplenum - di->start_samplenum) * di->data_unitsize);
800
801                 /* Check whether the current sample matches at least one of the conditions (logical OR). */
802                 /* IMPORTANT: We need to check all conditions, even if there was a match already! */
803                 for (l = di->condition_list, j = 0; l; l = l->next, j++) {
804                         cond = l->data;
805                         if (!cond)
806                                 continue;
807                         /* All terms in 'cond' must match (logical AND). */
808                         di->match_array->data[j] = all_terms_match(di, cond, sample_pos);
809                 }
810
811                 update_old_pins_array(di, sample_pos);
812
813                 /* If at least one condition matched we're done. */
814                 if (at_least_one_condition_matched(di, num_conditions))
815                         return TRUE;
816         }
817
818         return FALSE;
819 }
820
821 /**
822  * Process available samples and check if they match the defined conditions.
823  *
824  * This function returns if there is an error, or when a match is found, or
825  * when all samples have been processed (whether a match was found or not).
826  *
827  * @param di The decoder instance to use. Must not be NULL.
828  * @param found_match Will be set to TRUE if at least one condition matched,
829  *                    FALSE otherwise. Must not be NULL.
830  *
831  * @retval SRD_OK No errors occured, see found_match for the result.
832  * @retval SRD_ERR_ARG Invalid arguments.
833  *
834  * @private
835  */
836 SRD_PRIV int process_samples_until_condition_match(struct srd_decoder_inst *di, gboolean *found_match)
837 {
838         if (!di || !found_match)
839                 return SRD_ERR_ARG;
840
841         /* Check if any of the current condition(s) match. */
842         while (TRUE) {
843                 /* Feed the (next chunk of the) buffer to find_match(). */
844                 *found_match = find_match(di);
845
846                 /* Did we handle all samples yet? */
847                 if (di->cur_samplenum >= di->end_samplenum) {
848                         srd_dbg("Done, handled all samples (%" PRIu64 "/%" PRIu64 ").",
849                                 di->cur_samplenum, di->end_samplenum);
850                         return SRD_OK;
851                 }
852
853                 /* If we didn't find a match, continue looking. */
854                 if (!(*found_match))
855                         continue;
856
857                 /* At least one condition matched, return. */
858                 return SRD_OK;
859         }
860
861         return SRD_OK;
862 }
863
864 /**
865  * Worker thread (per PD-stack).
866  *
867  * @param data Pointer to the lowest-level PD's device instance.
868  *             Must not be NULL.
869  *
870  * @return NULL if there was an error.
871  */
872 static gpointer di_thread(gpointer data)
873 {
874         PyObject *py_res;
875         struct srd_decoder_inst *di;
876
877         if (!data)
878                 return NULL;
879
880         di = data;
881
882         /* Call self.decode(). Only returns if the PD throws an exception. */
883         Py_IncRef(di->py_inst);
884         if (!(py_res = PyObject_CallMethod(di->py_inst, "decode", NULL))) {
885                 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
886                 exit(1); /* TODO: Proper shutdown. This is a hack. */
887                 return NULL;
888         }
889         Py_DecRef(py_res);
890
891         return NULL;
892 }
893
894 /**
895  * Decode a chunk of samples.
896  *
897  * @param di The decoder instance to call. Must not be NULL.
898  * @param start_samplenum The starting sample number for the buffer's sample
899  *                        set, relative to the start of capture.
900  * @param end_samplenum The ending sample number for the buffer's sample
901  *                        set, relative to the start of capture.
902  * @param inbuf The buffer to decode. Must not be NULL.
903  * @param inbuflen Length of the buffer. Must be > 0.
904  * @param unitsize The number of bytes per sample. Must be > 0.
905  *
906  * @return SRD_OK upon success, a (negative) error code otherwise.
907  *
908  * @private
909  */
910 SRD_PRIV int srd_inst_decode(struct srd_decoder_inst *di,
911                 uint64_t start_samplenum, uint64_t end_samplenum,
912                 const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
913 {
914         PyObject *py_res;
915         srd_logic *logic;
916         long apiver;
917
918         /* Return an error upon unusable input. */
919         if (!di) {
920                 srd_dbg("empty decoder instance");
921                 return SRD_ERR_ARG;
922         }
923         if (!inbuf) {
924                 srd_dbg("NULL buffer pointer");
925                 return SRD_ERR_ARG;
926         }
927         if (inbuflen == 0) {
928                 srd_dbg("empty buffer");
929                 return SRD_ERR_ARG;
930         }
931         if (unitsize == 0) {
932                 srd_dbg("unitsize 0");
933                 return SRD_ERR_ARG;
934         }
935
936         di->data_unitsize = unitsize;
937
938         srd_dbg("Decoding: start sample %" PRIu64 ", end sample %"
939                 PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
940                 "%d), instance %s.", start_samplenum, end_samplenum,
941                 end_samplenum - start_samplenum, inbuflen, di->data_unitsize,
942                 di->inst_id);
943
944         apiver = srd_decoder_apiver(di->decoder);
945
946         if (apiver == 2) {
947                 /*
948                  * Create new srd_logic object. Each iteration around the PD's
949                  * loop will fill one sample into this object.
950                  */
951                 logic = PyObject_New(srd_logic, (PyTypeObject *)srd_logic_type);
952                 Py_INCREF(logic);
953                 logic->di = (struct srd_decoder_inst *)di;
954                 logic->start_samplenum = start_samplenum;
955                 logic->itercnt = 0;
956                 logic->inbuf = (uint8_t *)inbuf;
957                 logic->inbuflen = inbuflen;
958                 logic->sample = PyList_New(2);
959                 Py_INCREF(logic->sample);
960
961                 Py_IncRef(di->py_inst);
962                 if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
963                         "KKO", start_samplenum, end_samplenum, logic))) {
964                         srd_exception_catch("Protocol decoder instance %s",
965                                         di->inst_id);
966                         return SRD_ERR_PYTHON;
967                 }
968                 Py_DecRef(py_res);
969         } else {
970                 /* If this is the first call, start the worker thread. */
971                 if (!di->thread_handle)
972                         di->thread_handle = g_thread_new("di_thread",
973                                                          di_thread, di);
974
975                 /* Push the new sample chunk to the worker thread. */
976                 g_mutex_lock(&di->data_mutex);
977                 di->start_samplenum = start_samplenum;
978                 di->end_samplenum = end_samplenum;
979                 di->inbuf = inbuf;
980                 di->inbuflen = inbuflen;
981                 di->got_new_samples = TRUE;
982                 di->handled_all_samples = FALSE;
983
984                 /* Signal the thread that we have new data. */
985                 g_cond_signal(&di->got_new_samples_cond);
986                 g_mutex_unlock(&di->data_mutex);
987
988                 /* When all samples in this chunk were handled, return. */
989                 g_mutex_lock(&di->data_mutex);
990                 while (!di->handled_all_samples)
991                         g_cond_wait(&di->handled_all_samples_cond, &di->data_mutex);
992                 g_mutex_unlock(&di->data_mutex);
993         }
994
995         return SRD_OK;
996 }
997
998 /** @private */
999 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
1000 {
1001         GSList *l;
1002         struct srd_pd_output *pdo;
1003
1004         srd_dbg("Freeing instance %s", di->inst_id);
1005
1006         Py_DecRef(di->py_inst);
1007         g_free(di->inst_id);
1008         g_free(di->dec_channelmap);
1009         g_free(di->channel_samples);
1010         g_slist_free(di->next_di);
1011         for (l = di->pd_output; l; l = l->next) {
1012                 pdo = l->data;
1013                 g_free(pdo->proto_id);
1014                 g_free(pdo);
1015         }
1016         g_slist_free(di->pd_output);
1017         g_free(di);
1018 }
1019
1020 /** @private */
1021 SRD_PRIV void srd_inst_free_all(struct srd_session *sess, GSList *stack)
1022 {
1023         GSList *l;
1024         struct srd_decoder_inst *di;
1025
1026         if (session_is_valid(sess) != SRD_OK) {
1027                 srd_err("Invalid session.");
1028                 return;
1029         }
1030
1031         di = NULL;
1032         for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
1033                 di = l->data;
1034                 if (di->next_di)
1035                         srd_inst_free_all(sess, di->next_di);
1036                 srd_inst_free(di);
1037         }
1038         if (!stack) {
1039                 g_slist_free(sess->di_list);
1040                 sess->di_list = NULL;
1041         }
1042 }
1043
1044 /** @} */