2 * This file is part of the libsigrokdecode project.
4 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
22 #include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
23 #include "libsigrokdecode.h"
31 extern SRD_PRIV GSList *sessions;
33 static void srd_inst_join_decode_thread(struct srd_decoder_inst *di);
34 static void srd_inst_reset_state(struct srd_decoder_inst *di);
35 static void oldpins_array_seed(struct srd_decoder_inst *di);
36 static void oldpins_array_free(struct srd_decoder_inst *di);
43 * Decoder instance handling.
47 * @defgroup grp_instances Decoder instances
49 * Decoder instance handling.
55 * Set one or more options in a decoder instance.
57 * Handled options are removed from the hash.
59 * @param di Decoder instance.
60 * @param options A GHashTable of options to set.
62 * @return SRD_OK upon success, a (negative) error code otherwise.
66 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
69 struct srd_decoder_option *sdo;
70 PyObject *py_di_options, *py_optval;
77 PyGILState_STATE gstate;
80 srd_err("Invalid decoder instance.");
85 srd_err("Invalid options GHashTable.");
89 gstate = PyGILState_Ensure();
91 if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
92 /* Decoder has no options. */
93 PyGILState_Release(gstate);
94 if (g_hash_table_size(options) == 0) {
95 /* No options provided. */
98 srd_err("Protocol decoder has no options.");
104 ret = SRD_ERR_PYTHON;
108 * The 'options' tuple is a class variable, but we need to
109 * change it. Changing it directly will affect the entire class,
110 * so we need to create a new object for it, and populate that
113 if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
115 Py_DECREF(py_di_options);
116 py_di_options = PyDict_New();
117 PyObject_SetAttrString(di->py_inst, "options", py_di_options);
119 for (l = di->decoder->options; l; l = l->next) {
121 if ((value = g_hash_table_lookup(options, sdo->id))) {
122 /* A value was supplied for this option. */
123 if (!g_variant_type_equal(g_variant_get_type(value),
124 g_variant_get_type(sdo->def))) {
125 srd_err("Option '%s' should have the same type "
126 "as the default value.", sdo->id);
130 /* Use default for this option. */
133 if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
134 val_str = g_variant_get_string(value, NULL);
135 if (!(py_optval = PyUnicode_FromString(val_str))) {
136 /* Some UTF-8 encoding error. */
138 srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
141 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
142 val_int = g_variant_get_int64(value);
143 if (!(py_optval = PyLong_FromLong(val_int))) {
144 /* ValueError Exception */
146 srd_err("Option '%s' has invalid integer value.", sdo->id);
149 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_DOUBLE)) {
150 val_double = g_variant_get_double(value);
151 if (!(py_optval = PyFloat_FromDouble(val_double))) {
152 /* ValueError Exception */
154 srd_err("Option '%s' has invalid float value.",
159 if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1)
161 /* Not harmful even if we used the default. */
162 g_hash_table_remove(options, sdo->id);
164 if (g_hash_table_size(options) != 0)
165 srd_warn("Unknown options specified for '%s'", di->inst_id);
170 Py_XDECREF(py_optval);
171 if (PyErr_Occurred()) {
172 srd_exception_catch("Stray exception in srd_inst_option_set()");
173 ret = SRD_ERR_PYTHON;
175 PyGILState_Release(gstate);
180 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_channel_set_all(). */
181 static gint compare_channel_id(const struct srd_channel *pdch,
182 const char *channel_id)
184 return strcmp(pdch->id, channel_id);
188 * Set all channels in a decoder instance.
190 * This function sets _all_ channels for the specified decoder instance, i.e.,
191 * it overwrites any channels that were already defined (if any).
193 * @param di Decoder instance.
194 * @param new_channels A GHashTable of channels to set. Key is channel name,
195 * value is the channel number. Samples passed to this
196 * instance will be arranged in this order.
198 * @return SRD_OK upon success, a (negative) error code otherwise.
202 SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
203 GHashTable *new_channels)
205 GVariant *channel_val;
208 struct srd_channel *pdch;
209 int *new_channelmap, new_channelnum, num_required_channels, i;
212 srd_dbg("Setting channels for instance %s with list of %d channels.",
213 di->inst_id, g_hash_table_size(new_channels));
215 if (g_hash_table_size(new_channels) == 0)
216 /* No channels provided. */
219 if (di->dec_num_channels == 0) {
220 /* Decoder has no channels. */
221 srd_err("Protocol decoder %s has no channels to define.",
226 new_channelmap = g_malloc0(sizeof(int) * di->dec_num_channels);
229 * For now, map all indexes to channel -1 (can be overridden later).
230 * This -1 is interpreted as an unspecified channel later.
232 for (i = 0; i < di->dec_num_channels; i++)
233 new_channelmap[i] = -1;
235 for (l = g_hash_table_get_keys(new_channels); l; l = l->next) {
236 channel_id = l->data;
237 channel_val = g_hash_table_lookup(new_channels, channel_id);
238 if (!g_variant_is_of_type(channel_val, G_VARIANT_TYPE_INT32)) {
239 /* Channel name was specified without a value. */
240 srd_err("No channel number was specified for %s.",
242 g_free(new_channelmap);
245 new_channelnum = g_variant_get_int32(channel_val);
246 if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
247 (GCompareFunc)compare_channel_id))) {
248 /* Fall back on optional channels. */
249 if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
250 channel_id, (GCompareFunc)compare_channel_id))) {
251 srd_err("Protocol decoder %s has no channel "
252 "'%s'.", di->decoder->name, channel_id);
253 g_free(new_channelmap);
258 new_channelmap[pdch->order] = new_channelnum;
259 srd_dbg("Setting channel mapping: %s (PD ch idx %d) = input data ch idx %d.",
260 pdch->id, pdch->order, new_channelnum);
263 srd_dbg("Final channel map:");
264 num_required_channels = g_slist_length(di->decoder->channels);
265 for (i = 0; i < di->dec_num_channels; i++) {
266 GSList *ll = g_slist_nth(di->decoder->channels, i);
268 ll = g_slist_nth(di->decoder->opt_channels,
269 i - num_required_channels);
271 srd_dbg(" - PD ch idx %d (%s) = input data ch idx %d (%s)", i,
272 pdch->id, new_channelmap[i],
273 (i < num_required_channels) ? "required" : "optional");
276 /* Report an error if not all required channels were specified. */
277 for (i = 0; i < num_required_channels; i++) {
278 if (new_channelmap[i] != -1)
280 pdch = g_slist_nth(di->decoder->channels, i)->data;
281 srd_err("Required channel '%s' (index %d) was not specified.",
283 g_free(new_channelmap);
287 g_free(di->dec_channelmap);
288 di->dec_channelmap = new_channelmap;
294 * Create a new protocol decoder instance.
296 * @param sess The session holding the protocol decoder instance.
298 * @param decoder_id Decoder 'id' field.
299 * @param options GHashtable of options which override the defaults set in
300 * the decoder class. May be NULL.
302 * @return Pointer to a newly allocated struct srd_decoder_inst, or
303 * NULL in case of failure.
307 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
308 const char *decoder_id, GHashTable *options)
311 struct srd_decoder *dec;
312 struct srd_decoder_inst *di;
314 PyGILState_STATE gstate;
321 if (!(dec = srd_decoder_get_by_id(decoder_id))) {
322 srd_err("Protocol decoder %s not found.", decoder_id);
326 di = g_malloc0(sizeof(struct srd_decoder_inst));
332 inst_id = g_hash_table_lookup(options, "id");
334 di->inst_id = g_strdup(inst_id);
335 g_hash_table_remove(options, "id");
338 /* Create a unique instance ID (as none was provided). */
340 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
341 while (srd_inst_find_by_id(sess, di->inst_id)) {
343 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
348 * Prepare a default channel map, where samples come in the
349 * order in which the decoder class defined them.
351 di->dec_num_channels = g_slist_length(di->decoder->channels) +
352 g_slist_length(di->decoder->opt_channels);
353 if (di->dec_num_channels) {
355 g_malloc(sizeof(int) * di->dec_num_channels);
356 for (i = 0; i < di->dec_num_channels; i++)
357 di->dec_channelmap[i] = i;
359 * Will be used to prepare a sample at every iteration
360 * of the instance's decode() method.
362 di->channel_samples = g_malloc(di->dec_num_channels);
365 /* Default to the initial pins being the same as in sample 0. */
366 oldpins_array_seed(di);
368 gstate = PyGILState_Ensure();
370 /* Create a new instance of this decoder class. */
371 if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
372 if (PyErr_Occurred())
373 srd_exception_catch("Failed to create %s instance",
375 PyGILState_Release(gstate);
376 g_free(di->dec_channelmap);
381 PyGILState_Release(gstate);
383 if (options && srd_inst_option_set(di, options) != SRD_OK) {
384 g_free(di->dec_channelmap);
389 di->condition_list = NULL;
390 di->match_array = NULL;
391 di->abs_start_samplenum = 0;
392 di->abs_end_samplenum = 0;
395 di->abs_cur_samplenum = 0;
396 di->thread_handle = NULL;
397 di->got_new_samples = FALSE;
398 di->handled_all_samples = FALSE;
399 di->want_wait_terminate = FALSE;
400 di->decoder_state = SRD_OK;
403 * Strictly speaking initialization of statically allocated
404 * condition and mutex variables (or variables allocated on the
405 * stack) is not required, but won't harm either. Explicitly
406 * running init() will better match subsequent clear() calls.
408 g_cond_init(&di->got_new_samples_cond);
409 g_cond_init(&di->handled_all_samples_cond);
410 g_mutex_init(&di->data_mutex);
412 /* Instance takes input from a frontend by default. */
413 sess->di_list = g_slist_append(sess->di_list, di);
414 srd_dbg("Creating new %s instance %s.", decoder_id, di->inst_id);
419 static void srd_inst_join_decode_thread(struct srd_decoder_inst *di)
423 if (!di->thread_handle)
426 srd_dbg("%s: Joining decoder thread.", di->inst_id);
429 * Terminate potentially running threads which still
430 * execute the decoder instance's decode() method.
432 srd_dbg("%s: Raising want_term, sending got_new.", di->inst_id);
433 g_mutex_lock(&di->data_mutex);
434 di->want_wait_terminate = TRUE;
435 g_cond_signal(&di->got_new_samples_cond);
436 g_mutex_unlock(&di->data_mutex);
438 srd_dbg("%s: Running join().", di->inst_id);
439 (void)g_thread_join(di->thread_handle);
440 srd_dbg("%s: Call to join() done.", di->inst_id);
441 di->thread_handle = NULL;
444 * Reset condition and mutex variables, such that next
445 * operations on them will find them in a clean state.
447 g_cond_clear(&di->got_new_samples_cond);
448 g_cond_init(&di->got_new_samples_cond);
449 g_cond_clear(&di->handled_all_samples_cond);
450 g_cond_init(&di->handled_all_samples_cond);
451 g_mutex_clear(&di->data_mutex);
452 g_mutex_init(&di->data_mutex);
455 static void srd_inst_reset_state(struct srd_decoder_inst *di)
460 srd_dbg("%s: Resetting decoder state.", di->inst_id);
462 /* Reset internal state of the decoder. */
463 condition_list_free(di);
464 match_array_free(di);
465 di->abs_start_samplenum = 0;
466 di->abs_end_samplenum = 0;
469 di->abs_cur_samplenum = 0;
470 oldpins_array_free(di);
471 di->got_new_samples = FALSE;
472 di->handled_all_samples = FALSE;
473 di->want_wait_terminate = FALSE;
474 di->decoder_state = SRD_OK;
475 /* Conditions and mutex got reset after joining the thread. */
479 * Stack a decoder instance on top of another.
481 * @param sess The session holding the protocol decoder instances.
483 * @param di_bottom The instance on top of which di_top will be stacked.
484 * @param di_top The instance to go on top.
486 * @return SRD_OK upon success, a (negative) error code otherwise.
490 SRD_API int srd_inst_stack(struct srd_session *sess,
491 struct srd_decoder_inst *di_bottom,
492 struct srd_decoder_inst *di_top)
497 if (!di_bottom || !di_top) {
498 srd_err("Invalid from/to instance pair.");
502 if (g_slist_find(sess->di_list, di_top)) {
503 /* Remove from the unstacked list. */
504 sess->di_list = g_slist_remove(sess->di_list, di_top);
507 /* Stack on top of source di. */
508 di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
510 srd_dbg("Stacking %s onto %s.", di_top->inst_id, di_bottom->inst_id);
516 * Search a decoder instance and its stack for instance ID.
518 * @param[in] inst_id ID to search for.
519 * @param[in] stack A decoder instance, potentially with stacked instances.
521 * @return The matching instance, or NULL.
523 static struct srd_decoder_inst *srd_inst_find_by_id_stack(const char *inst_id,
524 struct srd_decoder_inst *stack)
527 struct srd_decoder_inst *tmp, *di;
529 if (!strcmp(stack->inst_id, inst_id))
532 /* Otherwise, look recursively in our stack. */
534 if (stack->next_di) {
535 for (l = stack->next_di; l; l = l->next) {
537 if (!strcmp(tmp->inst_id, inst_id)) {
548 * Find a decoder instance by its instance ID.
550 * This will recurse to find the instance anywhere in the stack tree of the
553 * @param sess The session holding the protocol decoder instance.
555 * @param inst_id The instance ID to be found.
557 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
561 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
565 struct srd_decoder_inst *tmp, *di;
571 for (l = sess->di_list; l; l = l->next) {
573 if ((di = srd_inst_find_by_id_stack(inst_id, tmp)) != NULL)
581 * Set the list of initial (assumed) pin values.
583 * @param di Decoder instance to use. Must not be NULL.
584 * @param initial_pins A GArray of uint8_t values. Must not be NULL.
588 SRD_API int srd_inst_initial_pins_set_all(struct srd_decoder_inst *di, GArray *initial_pins)
594 srd_err("Invalid decoder instance.");
601 if (initial_pins->len != (guint)di->dec_num_channels) {
602 srd_err("Incorrect number of channels (need %d, got %d).",
603 di->dec_num_channels, initial_pins->len);
607 /* Sanity-check initial pin state values. */
608 for (i = 0; i < di->dec_num_channels; i++) {
609 if (initial_pins->data[i] <= 2)
611 srd_err("Invalid initial channel %d pin state: %d.",
612 i, initial_pins->data[i]);
616 s = g_string_sized_new(100);
617 oldpins_array_seed(di);
618 for (i = 0; i < di->dec_num_channels; i++) {
619 di->old_pins_array->data[i] = initial_pins->data[i];
620 g_string_append_printf(s, "%d, ", di->old_pins_array->data[i]);
622 s = g_string_truncate(s, s->len - 2);
623 srd_dbg("Initial pins: %s.", s->str);
624 g_string_free(s, TRUE);
629 static void oldpins_array_seed(struct srd_decoder_inst *di)
636 if (di->old_pins_array)
639 count = di->dec_num_channels;
640 arr = g_array_sized_new(FALSE, TRUE, sizeof(uint8_t), count);
641 g_array_set_size(arr, count);
642 memset(arr->data, SRD_INITIAL_PIN_SAME_AS_SAMPLE0, count);
643 di->old_pins_array = arr;
646 static void oldpins_array_free(struct srd_decoder_inst *di)
650 if (!di->old_pins_array)
653 srd_dbg("%s: Releasing initial pin state.", di->inst_id);
655 g_array_free(di->old_pins_array, TRUE);
656 di->old_pins_array = NULL;
660 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
664 struct srd_decoder_inst *next_di;
666 PyGILState_STATE gstate;
668 srd_dbg("Calling start() of instance %s.", di->inst_id);
670 gstate = PyGILState_Ensure();
672 /* Run self.start(). */
673 if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
674 srd_exception_catch("Protocol decoder instance %s",
676 PyGILState_Release(gstate);
677 return SRD_ERR_PYTHON;
681 /* Set self.samplenum to 0. */
682 PyObject_SetAttrString(di->py_inst, "samplenum", PyLong_FromLong(0));
684 /* Set self.matched to None. */
685 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
687 PyGILState_Release(gstate);
689 /* Start all the PDs stacked on top of this one. */
690 for (l = di->next_di; l; l = l->next) {
692 if ((ret = srd_inst_start(next_di)) != SRD_OK)
700 * Check whether the specified sample matches the specified term.
702 * In the case of SRD_TERM_SKIP, this function can modify
703 * term->num_samples_already_skipped.
705 * @param old_sample The value of the previous sample (0/1).
706 * @param sample The value of the current sample (0/1).
707 * @param term The term that should be checked for a match. Must not be NULL.
709 * @retval TRUE The current sample matches the specified term.
710 * @retval FALSE The current sample doesn't match the specified term, or an
711 * invalid term was provided.
715 __attribute__((always_inline))
716 static inline gboolean sample_matches(uint8_t old_sample, uint8_t sample, struct srd_term *term)
718 /* Caller ensures term != NULL. */
720 switch (term->type) {
729 case SRD_TERM_RISING_EDGE:
730 if (old_sample == 0 && sample == 1)
733 case SRD_TERM_FALLING_EDGE:
734 if (old_sample == 1 && sample == 0)
737 case SRD_TERM_EITHER_EDGE:
738 if ((old_sample == 1 && sample == 0) || (old_sample == 0 && sample == 1))
741 case SRD_TERM_NO_EDGE:
742 if ((old_sample == 0 && sample == 0) || (old_sample == 1 && sample == 1))
746 if (term->num_samples_already_skipped == term->num_samples_to_skip)
748 term->num_samples_already_skipped++;
751 srd_err("Unknown term type %d.", term->type);
759 SRD_PRIV void match_array_free(struct srd_decoder_inst *di)
761 if (!di || !di->match_array)
764 g_array_free(di->match_array, TRUE);
765 di->match_array = NULL;
769 SRD_PRIV void condition_list_free(struct srd_decoder_inst *di)
776 for (l = di->condition_list; l; l = l->next) {
779 g_slist_free_full(ll, g_free);
782 di->condition_list = NULL;
785 static gboolean have_non_null_conds(const struct srd_decoder_inst *di)
792 for (l = di->condition_list; l; l = l->next) {
801 static void update_old_pins_array(struct srd_decoder_inst *di,
802 const uint8_t *sample_pos)
805 int i, byte_offset, bit_offset;
807 if (!di || !di->dec_channelmap || !sample_pos)
810 oldpins_array_seed(di);
811 for (i = 0; i < di->dec_num_channels; i++) {
812 byte_offset = di->dec_channelmap[i] / 8;
813 bit_offset = di->dec_channelmap[i] % 8;
814 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
815 di->old_pins_array->data[i] = sample;
819 static void update_old_pins_array_initial_pins(struct srd_decoder_inst *di)
822 int i, byte_offset, bit_offset;
823 const uint8_t *sample_pos;
825 if (!di || !di->dec_channelmap)
828 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
830 oldpins_array_seed(di);
831 for (i = 0; i < di->dec_num_channels; i++) {
832 if (di->old_pins_array->data[i] != SRD_INITIAL_PIN_SAME_AS_SAMPLE0)
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;
841 static gboolean term_matches(const struct srd_decoder_inst *di,
842 struct srd_term *term, const uint8_t *sample_pos)
844 uint8_t old_sample, sample;
845 int byte_offset, bit_offset, ch;
847 /* Caller ensures di, di->dec_channelmap, term, sample_pos != NULL. */
849 if (term->type == SRD_TERM_SKIP)
850 return sample_matches(0, 0, term);
853 byte_offset = di->dec_channelmap[ch] / 8;
854 bit_offset = di->dec_channelmap[ch] % 8;
855 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
856 old_sample = di->old_pins_array->data[ch];
858 return sample_matches(old_sample, sample, term);
861 static gboolean all_terms_match(const struct srd_decoder_inst *di,
862 const GSList *cond, const uint8_t *sample_pos)
865 struct srd_term *term;
867 /* Caller ensures di, cond, sample_pos != NULL. */
869 for (l = cond; l; l = l->next) {
871 if (!term_matches(di, term, sample_pos))
878 static gboolean at_least_one_condition_matched(
879 const struct srd_decoder_inst *di, unsigned int num_conditions)
883 /* Caller ensures di != NULL. */
885 for (i = 0; i < num_conditions; i++) {
886 if (di->match_array->data[i])
893 static gboolean find_match(struct srd_decoder_inst *di)
895 uint64_t i, j, num_samples_to_process;
897 const uint8_t *sample_pos;
898 unsigned int num_conditions;
900 /* Caller ensures di != NULL. */
902 /* Check whether the condition list is NULL/empty. */
903 if (!di->condition_list) {
904 srd_dbg("NULL/empty condition list, automatic match.");
908 /* Check whether we have any non-NULL conditions. */
909 if (!have_non_null_conds(di)) {
910 srd_dbg("Only NULL conditions in list, automatic match.");
914 num_samples_to_process = di->abs_end_samplenum - di->abs_cur_samplenum;
915 num_conditions = g_slist_length(di->condition_list);
917 /* di->match_array is NULL here. Create a new GArray. */
918 di->match_array = g_array_sized_new(FALSE, TRUE, sizeof(gboolean), num_conditions);
919 g_array_set_size(di->match_array, num_conditions);
921 /* Sample 0: Set di->old_pins_array for SRD_INITIAL_PIN_SAME_AS_SAMPLE0 pins. */
922 if (di->abs_cur_samplenum == 0)
923 update_old_pins_array_initial_pins(di);
925 for (i = 0; i < num_samples_to_process; i++, (di->abs_cur_samplenum)++) {
927 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
929 /* Check whether the current sample matches at least one of the conditions (logical OR). */
930 /* IMPORTANT: We need to check all conditions, even if there was a match already! */
931 for (l = di->condition_list, j = 0; l; l = l->next, j++) {
935 /* All terms in 'cond' must match (logical AND). */
936 di->match_array->data[j] = all_terms_match(di, cond, sample_pos);
939 update_old_pins_array(di, sample_pos);
941 /* If at least one condition matched we're done. */
942 if (at_least_one_condition_matched(di, num_conditions))
950 * Process available samples and check if they match the defined conditions.
952 * This function returns if there is an error, or when a match is found, or
953 * when all samples have been processed (whether a match was found or not).
954 * This function immediately terminates when the decoder's wait() method
955 * invocation shall get terminated.
957 * @param di The decoder instance to use. Must not be NULL.
958 * @param found_match Will be set to TRUE if at least one condition matched,
959 * FALSE otherwise. Must not be NULL.
961 * @retval SRD_OK No errors occured, see found_match for the result.
962 * @retval SRD_ERR_ARG Invalid arguments.
966 SRD_PRIV int process_samples_until_condition_match(struct srd_decoder_inst *di, gboolean *found_match)
968 if (!di || !found_match)
971 *found_match = FALSE;
972 if (di->want_wait_terminate)
975 /* Check if any of the current condition(s) match. */
977 /* Feed the (next chunk of the) buffer to find_match(). */
978 *found_match = find_match(di);
980 /* Did we handle all samples yet? */
981 if (di->abs_cur_samplenum >= di->abs_end_samplenum) {
982 srd_dbg("Done, handled all samples (abs cur %" PRIu64
983 " / abs end %" PRIu64 ").",
984 di->abs_cur_samplenum, di->abs_end_samplenum);
988 /* If we didn't find a match, continue looking. */
992 /* At least one condition matched, return. */
1000 * Worker thread (per PD-stack).
1002 * @param data Pointer to the lowest-level PD's device instance.
1005 * @return NULL if there was an error.
1007 static gpointer di_thread(gpointer data)
1010 struct srd_decoder_inst *di;
1012 PyGILState_STATE gstate;
1019 srd_dbg("%s: Starting thread routine for decoder.", di->inst_id);
1021 gstate = PyGILState_Ensure();
1024 * Call self.decode(). Only returns if the PD throws an exception.
1025 * "Regular" termination of the decode() method is not expected.
1027 Py_IncRef(di->py_inst);
1028 srd_dbg("%s: Calling decode().", di->inst_id);
1029 py_res = PyObject_CallMethod(di->py_inst, "decode", NULL);
1030 srd_dbg("%s: decode() terminated.", di->inst_id);
1033 di->decoder_state = SRD_ERR;
1036 * Make sure to unblock potentially pending srd_inst_decode()
1037 * calls in application threads after the decode() method might
1038 * have terminated, while it neither has processed sample data
1039 * nor has terminated upon request. This happens e.g. when "need
1040 * a samplerate to decode" exception is thrown.
1042 g_mutex_lock(&di->data_mutex);
1043 wanted_term = di->want_wait_terminate;
1044 di->want_wait_terminate = TRUE;
1045 di->handled_all_samples = TRUE;
1046 g_cond_signal(&di->handled_all_samples_cond);
1047 g_mutex_unlock(&di->data_mutex);
1050 * Check for the termination cause of the decode() method.
1051 * Though this is mostly for information.
1053 if (!py_res && wanted_term) {
1055 * Silently ignore errors upon return from decode() calls
1056 * when termination was requested. Terminate the thread
1057 * which executed this instance's decode() logic.
1059 srd_dbg("%s: Thread done (!res, want_term).", di->inst_id);
1061 PyGILState_Release(gstate);
1066 * The decode() invocation terminated unexpectedly. Have
1067 * the back trace printed, and terminate the thread which
1068 * executed the decode() method.
1070 srd_dbg("%s: decode() terminated unrequested.", di->inst_id);
1071 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
1072 srd_dbg("%s: Thread done (!res, !want_term).", di->inst_id);
1073 PyGILState_Release(gstate);
1078 * TODO: By design the decode() method is not supposed to terminate.
1079 * Nevertheless we have the thread joined, and srd backend calls to
1080 * decode() will re-start another thread transparently.
1082 srd_dbg("%s: decode() terminated (req %d).", di->inst_id, wanted_term);
1086 PyGILState_Release(gstate);
1088 srd_dbg("%s: Thread done (with res).", di->inst_id);
1094 * Decode a chunk of samples.
1096 * The calls to this function must provide the samples that shall be
1097 * used by the protocol decoder
1098 * - in the correct order ([...]5, 6, 4, 7, 8[...] is a bug),
1099 * - starting from sample zero (2, 3, 4, 5, 6[...] is a bug),
1100 * - consecutively, with no gaps (0, 1, 2, 4, 5[...] is a bug).
1102 * The start- and end-sample numbers are absolute sample numbers (relative
1103 * to the start of the whole capture/file/stream), i.e. they are not relative
1104 * sample numbers within the chunk specified by 'inbuf' and 'inbuflen'.
1106 * Correct example (4096 samples total, 4 chunks @ 1024 samples each):
1107 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1108 * srd_inst_decode(di, 1024, 2048, inbuf, 1024, 1);
1109 * srd_inst_decode(di, 2048, 3072, inbuf, 1024, 1);
1110 * srd_inst_decode(di, 3072, 4096, inbuf, 1024, 1);
1112 * The chunk size ('inbuflen') can be arbitrary and can differ between calls.
1114 * Correct example (4096 samples total, 7 chunks @ various samples each):
1115 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1116 * srd_inst_decode(di, 1024, 1124, inbuf, 100, 1);
1117 * srd_inst_decode(di, 1124, 1424, inbuf, 300, 1);
1118 * srd_inst_decode(di, 1424, 1643, inbuf, 219, 1);
1119 * srd_inst_decode(di, 1643, 2048, inbuf, 405, 1);
1120 * srd_inst_decode(di, 2048, 3072, inbuf, 1024, 1);
1121 * srd_inst_decode(di, 3072, 4096, inbuf, 1024, 1);
1123 * INCORRECT example (4096 samples total, 4 chunks @ 1024 samples each, but
1124 * the start- and end-samplenumbers are not absolute):
1125 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1126 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1127 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1128 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1130 * @param di The decoder instance to call. Must not be NULL.
1131 * @param abs_start_samplenum The absolute starting sample number for the
1132 * buffer's sample set, relative to the start of capture.
1133 * @param abs_end_samplenum The absolute ending sample number for the
1134 * buffer's sample set, relative to the start of capture.
1135 * @param inbuf The buffer to decode. Must not be NULL.
1136 * @param inbuflen Length of the buffer. Must be > 0.
1137 * @param unitsize The number of bytes per sample. Must be > 0.
1139 * @return SRD_OK upon success, a (negative) error code otherwise.
1143 SRD_PRIV int srd_inst_decode(struct srd_decoder_inst *di,
1144 uint64_t abs_start_samplenum, uint64_t abs_end_samplenum,
1145 const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
1147 /* Return an error upon unusable input. */
1149 srd_dbg("empty decoder instance");
1153 srd_dbg("NULL buffer pointer");
1156 if (inbuflen == 0) {
1157 srd_dbg("empty buffer");
1160 if (unitsize == 0) {
1161 srd_dbg("unitsize 0");
1165 if (abs_start_samplenum != di->abs_cur_samplenum ||
1166 abs_end_samplenum < abs_start_samplenum) {
1167 srd_dbg("Incorrect sample numbers: start=%" PRIu64 ", cur=%"
1168 PRIu64 ", end=%" PRIu64 ".", abs_start_samplenum,
1169 di->abs_cur_samplenum, abs_end_samplenum);
1173 di->data_unitsize = unitsize;
1175 srd_dbg("Decoding: abs start sample %" PRIu64 ", abs end sample %"
1176 PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
1177 "%d), instance %s.", abs_start_samplenum, abs_end_samplenum,
1178 abs_end_samplenum - abs_start_samplenum, inbuflen, di->data_unitsize,
1181 /* If this is the first call, start the worker thread. */
1182 if (!di->thread_handle) {
1183 srd_dbg("No worker thread for this decoder stack "
1184 "exists yet, creating one: %s.", di->inst_id);
1185 di->thread_handle = g_thread_new(di->inst_id,
1189 /* Push the new sample chunk to the worker thread. */
1190 g_mutex_lock(&di->data_mutex);
1191 di->abs_start_samplenum = abs_start_samplenum;
1192 di->abs_end_samplenum = abs_end_samplenum;
1194 di->inbuflen = inbuflen;
1195 di->got_new_samples = TRUE;
1196 di->handled_all_samples = FALSE;
1198 /* Signal the thread that we have new data. */
1199 g_cond_signal(&di->got_new_samples_cond);
1200 g_mutex_unlock(&di->data_mutex);
1202 /* When all samples in this chunk were handled, return. */
1203 g_mutex_lock(&di->data_mutex);
1204 while (!di->handled_all_samples && !di->want_wait_terminate)
1205 g_cond_wait(&di->handled_all_samples_cond, &di->data_mutex);
1206 g_mutex_unlock(&di->data_mutex);
1208 if (di->want_wait_terminate)
1209 return SRD_ERR_TERM_REQ;
1215 * Terminate current decoder work, prepare for re-use on new input data.
1217 * Terminates all decoder operations in the specified decoder instance
1218 * and the instances stacked on top of it. Resets internal state such
1219 * that the previously constructed stack can process new input data that
1220 * is not related to previously processed input data. This avoids the
1221 * expensive and complex re-construction of decoder stacks.
1223 * Callers are expected to follow up with start, metadata, and decode
1224 * calls like they would for newly constructed decoder stacks.
1226 * @param di The decoder instance to call. Must not be NULL.
1228 * @return SRD_OK upon success, a (negative) error code otherwise.
1232 SRD_PRIV int srd_inst_terminate_reset(struct srd_decoder_inst *di)
1234 PyGILState_STATE gstate;
1243 * Request termination and wait for previously initiated
1244 * background operation to finish. Reset internal state, but
1245 * do not start releasing resources yet. This shall result in
1246 * decoders' state just like after creation. This block handles
1247 * the C language library side.
1249 srd_dbg("Terminating instance %s", di->inst_id);
1250 srd_inst_join_decode_thread(di);
1251 srd_inst_reset_state(di);
1254 * Have the Python side's .reset() method executed (if the PD
1255 * implements it). It's assumed that .reset() assigns variables
1256 * very much like __init__() used to do in the past. Thus memory
1257 * that was allocated in previous calls gets released by Python
1258 * as it's not referenced any longer.
1260 gstate = PyGILState_Ensure();
1261 if (PyObject_HasAttrString(di->py_inst, "reset")) {
1262 srd_dbg("Calling reset() of instance %s", di->inst_id);
1263 py_ret = PyObject_CallMethod(di->py_inst, "reset", NULL);
1266 PyGILState_Release(gstate);
1268 /* Pass the "restart" request to all stacked decoders. */
1269 for (l = di->next_di; l; l = l->next) {
1270 ret = srd_inst_terminate_reset(l->data);
1275 return di->decoder_state;
1279 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
1282 struct srd_pd_output *pdo;
1283 PyGILState_STATE gstate;
1285 srd_dbg("Freeing instance %s.", di->inst_id);
1287 srd_inst_join_decode_thread(di);
1289 srd_inst_reset_state(di);
1291 gstate = PyGILState_Ensure();
1292 Py_DecRef(di->py_inst);
1293 PyGILState_Release(gstate);
1295 g_free(di->inst_id);
1296 g_free(di->dec_channelmap);
1297 g_free(di->channel_samples);
1298 g_slist_free(di->next_di);
1299 for (l = di->pd_output; l; l = l->next) {
1301 g_free(pdo->proto_id);
1304 g_slist_free(di->pd_output);
1309 SRD_PRIV void srd_inst_free_all(struct srd_session *sess)
1314 g_slist_free_full(sess->di_list, (GDestroyNotify)srd_inst_free);