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