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