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