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 /* module_sigrokdecode.c */
34 extern SRD_PRIV PyObject *srd_logic_type;
36 static void srd_inst_join_decode_thread(struct srd_decoder_inst *di);
37 static void srd_inst_reset_state(struct srd_decoder_inst *di);
38 SRD_PRIV void oldpins_array_free(struct srd_decoder_inst *di);
45 * Decoder instance handling.
49 * @defgroup grp_instances Decoder instances
51 * Decoder instance handling.
57 * Set one or more options in a decoder instance.
59 * Handled options are removed from the hash.
61 * @param di Decoder instance.
62 * @param options A GHashTable of options to set.
64 * @return SRD_OK upon success, a (negative) error code otherwise.
68 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
71 struct srd_decoder_option *sdo;
72 PyObject *py_di_options, *py_optval;
81 srd_err("Invalid decoder instance.");
86 srd_err("Invalid options GHashTable.");
90 if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
91 /* Decoder has no options. */
92 if (g_hash_table_size(options) == 0) {
93 /* No options provided. */
96 srd_err("Protocol decoder has no options.");
102 ret = SRD_ERR_PYTHON;
106 * The 'options' tuple is a class variable, but we need to
107 * change it. Changing it directly will affect the entire class,
108 * so we need to create a new object for it, and populate that
111 if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
113 Py_DECREF(py_di_options);
114 py_di_options = PyDict_New();
115 PyObject_SetAttrString(di->py_inst, "options", py_di_options);
117 for (l = di->decoder->options; l; l = l->next) {
119 if ((value = g_hash_table_lookup(options, sdo->id))) {
120 /* A value was supplied for this option. */
121 if (!g_variant_type_equal(g_variant_get_type(value),
122 g_variant_get_type(sdo->def))) {
123 srd_err("Option '%s' should have the same type "
124 "as the default value.", sdo->id);
128 /* Use default for this option. */
131 if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
132 val_str = g_variant_get_string(value, NULL);
133 if (!(py_optval = PyUnicode_FromString(val_str))) {
134 /* Some UTF-8 encoding error. */
136 srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
139 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
140 val_int = g_variant_get_int64(value);
141 if (!(py_optval = PyLong_FromLong(val_int))) {
142 /* ValueError Exception */
144 srd_err("Option '%s' has invalid integer value.", sdo->id);
147 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_DOUBLE)) {
148 val_double = g_variant_get_double(value);
149 if (!(py_optval = PyFloat_FromDouble(val_double))) {
150 /* ValueError Exception */
152 srd_err("Option '%s' has invalid float value.",
157 if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1)
159 /* Not harmful even if we used the default. */
160 g_hash_table_remove(options, sdo->id);
162 if (g_hash_table_size(options) != 0)
163 srd_warn("Unknown options specified for '%s'", di->inst_id);
168 Py_XDECREF(py_optval);
169 if (PyErr_Occurred()) {
170 srd_exception_catch("Stray exception in srd_inst_option_set()");
171 ret = SRD_ERR_PYTHON;
177 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_channel_set_all() */
178 static gint compare_channel_id(const struct srd_channel *pdch,
179 const char *channel_id)
181 return strcmp(pdch->id, channel_id);
185 * Set all channels in a decoder instance.
187 * This function sets _all_ channels for the specified decoder instance, i.e.,
188 * it overwrites any channels that were already defined (if any).
190 * @param di Decoder instance.
191 * @param new_channels A GHashTable of channels to set. Key is channel name,
192 * value is the channel number. Samples passed to this
193 * instance will be arranged in this order.
195 * @return SRD_OK upon success, a (negative) error code otherwise.
199 SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
200 GHashTable *new_channels)
202 GVariant *channel_val;
205 struct srd_channel *pdch;
206 int *new_channelmap, new_channelnum, num_required_channels, i;
209 srd_dbg("Setting channels for instance %s with list of %d channels.",
210 di->inst_id, g_hash_table_size(new_channels));
212 if (g_hash_table_size(new_channels) == 0)
213 /* No channels provided. */
216 if (di->dec_num_channels == 0) {
217 /* Decoder has no channels. */
218 srd_err("Protocol decoder %s has no channels to define.",
223 new_channelmap = g_malloc(sizeof(int) * di->dec_num_channels);
226 * For now, map all indexes to channel -1 (can be overridden later).
227 * This -1 is interpreted as an unspecified channel later.
229 for (i = 0; i < di->dec_num_channels; i++)
230 new_channelmap[i] = -1;
232 for (l = g_hash_table_get_keys(new_channels); l; l = l->next) {
233 channel_id = l->data;
234 channel_val = g_hash_table_lookup(new_channels, channel_id);
235 if (!g_variant_is_of_type(channel_val, G_VARIANT_TYPE_INT32)) {
236 /* Channel name was specified without a value. */
237 srd_err("No channel number was specified for %s.",
239 g_free(new_channelmap);
242 new_channelnum = g_variant_get_int32(channel_val);
243 if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
244 (GCompareFunc)compare_channel_id))) {
245 /* Fall back on optional channels. */
246 if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
247 channel_id, (GCompareFunc)compare_channel_id))) {
248 srd_err("Protocol decoder %s has no channel "
249 "'%s'.", di->decoder->name, channel_id);
250 g_free(new_channelmap);
255 new_channelmap[pdch->order] = new_channelnum;
256 srd_dbg("Setting channel mapping: %s (index %d) = channel %d.",
257 pdch->id, pdch->order, new_channelnum);
260 srd_dbg("Final channel map:");
261 num_required_channels = g_slist_length(di->decoder->channels);
262 for (i = 0; i < di->dec_num_channels; i++) {
263 srd_dbg(" - index %d = channel %d (%s)", i, new_channelmap[i],
264 (i < num_required_channels) ? "required" : "optional");
267 /* Report an error if not all required channels were specified. */
268 for (i = 0; i < num_required_channels; i++) {
269 if (new_channelmap[i] != -1)
271 pdch = g_slist_nth(di->decoder->channels, i)->data;
272 srd_err("Required channel '%s' (index %d) was not specified.",
277 g_free(di->dec_channelmap);
278 di->dec_channelmap = new_channelmap;
284 * Create a new protocol decoder instance.
286 * @param sess The session holding the protocol decoder instance.
287 * @param decoder_id Decoder 'id' field.
288 * @param options GHashtable of options which override the defaults set in
289 * the decoder class. May be NULL.
291 * @return Pointer to a newly allocated struct srd_decoder_inst, or
292 * NULL in case of failure.
296 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
297 const char *decoder_id, GHashTable *options)
300 struct srd_decoder *dec;
301 struct srd_decoder_inst *di;
305 srd_dbg("Creating new %s instance.", decoder_id);
307 if (session_is_valid(sess) != SRD_OK) {
308 srd_err("Invalid session.");
312 if (!(dec = srd_decoder_get_by_id(decoder_id))) {
313 srd_err("Protocol decoder %s not found.", decoder_id);
317 di = g_malloc0(sizeof(struct srd_decoder_inst));
323 inst_id = g_hash_table_lookup(options, "id");
325 di->inst_id = g_strdup(inst_id);
326 g_hash_table_remove(options, "id");
329 /* Create a unique instance ID (as none was provided). */
331 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
332 while (srd_inst_find_by_id(sess, di->inst_id)) {
334 di->inst_id = g_strdup_printf("%s-%d", decoder_id, i++);
339 * Prepare a default channel map, where samples come in the
340 * order in which the decoder class defined them.
342 di->dec_num_channels = g_slist_length(di->decoder->channels) +
343 g_slist_length(di->decoder->opt_channels);
344 if (di->dec_num_channels) {
346 g_malloc(sizeof(int) * di->dec_num_channels);
347 for (i = 0; i < di->dec_num_channels; i++)
348 di->dec_channelmap[i] = i;
350 * Will be used to prepare a sample at every iteration
351 * of the instance's decode() method.
353 di->channel_samples = g_malloc(di->dec_num_channels);
356 /* Create a new instance of this decoder class. */
357 if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
358 if (PyErr_Occurred())
359 srd_exception_catch("Failed to create %s instance",
361 g_free(di->dec_channelmap);
366 if (options && srd_inst_option_set(di, options) != SRD_OK) {
367 g_free(di->dec_channelmap);
372 di->condition_list = NULL;
373 di->match_array = NULL;
374 di->abs_start_samplenum = 0;
375 di->abs_end_samplenum = 0;
378 di->abs_cur_samplenum = 0;
379 di->old_pins_array = NULL;
380 di->thread_handle = NULL;
381 di->got_new_samples = FALSE;
382 di->handled_all_samples = FALSE;
383 di->want_wait_terminate = FALSE;
386 * Strictly speaking initialization of statically allocated
387 * condition and mutex variables (or variables allocated on the
388 * stack) is not required, but won't harm either. Explicitly
389 * running init() will better match subsequent clear() calls.
391 g_cond_init(&di->got_new_samples_cond);
392 g_cond_init(&di->handled_all_samples_cond);
393 g_mutex_init(&di->data_mutex);
395 /* Instance takes input from a frontend by default. */
396 sess->di_list = g_slist_append(sess->di_list, di);
397 srd_dbg("Created new %s instance with ID %s.", decoder_id, di->inst_id);
402 static void srd_inst_join_decode_thread(struct srd_decoder_inst *di)
406 if (!di->thread_handle)
409 srd_dbg("%s: Joining decoder thread.", di->inst_id);
412 * Terminate potentially running threads which still
413 * execute the decoder instance's decode() method.
415 srd_dbg("%s: Raising want_term, sending got_new.", di->inst_id);
416 g_mutex_lock(&di->data_mutex);
417 di->want_wait_terminate = TRUE;
418 g_cond_signal(&di->got_new_samples_cond);
419 g_mutex_unlock(&di->data_mutex);
421 srd_dbg("%s: Running join().", di->inst_id);
422 (void)g_thread_join(di->thread_handle);
423 srd_dbg("%s: Call to join() done.", di->inst_id);
424 di->thread_handle = NULL;
427 * Reset condition and mutex variables, such that next
428 * operations on them will find them in a clean state.
430 g_cond_clear(&di->got_new_samples_cond);
431 g_cond_init(&di->got_new_samples_cond);
432 g_cond_clear(&di->handled_all_samples_cond);
433 g_cond_init(&di->handled_all_samples_cond);
434 g_mutex_clear(&di->data_mutex);
435 g_mutex_init(&di->data_mutex);
438 static void srd_inst_reset_state(struct srd_decoder_inst *di)
443 srd_dbg("%s: Resetting decoder state.", di->inst_id);
446 * Reset internal state of the decoder.
448 condition_list_free(di);
449 match_array_free(di);
450 di->abs_start_samplenum = 0;
451 di->abs_end_samplenum = 0;
454 di->abs_cur_samplenum = 0;
455 oldpins_array_free(di);
456 di->got_new_samples = FALSE;
457 di->handled_all_samples = FALSE;
458 di->want_wait_terminate = FALSE;
459 /* Conditions and mutex got reset after joining the thread. */
463 * Stack a decoder instance on top of another.
465 * @param sess The session holding the protocol decoder instances.
466 * @param di_bottom The instance on top of which di_top will be stacked.
467 * @param di_top The instance to go on top.
469 * @return SRD_OK upon success, a (negative) error code otherwise.
473 SRD_API int srd_inst_stack(struct srd_session *sess,
474 struct srd_decoder_inst *di_bottom,
475 struct srd_decoder_inst *di_top)
478 if (session_is_valid(sess) != SRD_OK) {
479 srd_err("Invalid session.");
483 if (!di_bottom || !di_top) {
484 srd_err("Invalid from/to instance pair.");
488 if (g_slist_find(sess->di_list, di_top)) {
489 /* Remove from the unstacked list. */
490 sess->di_list = g_slist_remove(sess->di_list, di_top);
493 /* Stack on top of source di. */
494 di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
496 srd_dbg("Stacked %s onto %s.", di_top->inst_id, di_bottom->inst_id);
502 * Search a decoder instance and its stack for instance ID.
504 * @param[in] inst_id ID to search for.
505 * @param[in] stack A decoder instance, potentially with stacked instances.
507 * @return The matching instance, or NULL.
509 static struct srd_decoder_inst *srd_inst_find_by_id_stack(const char *inst_id,
510 struct srd_decoder_inst *stack)
513 struct srd_decoder_inst *tmp, *di;
515 if (!strcmp(stack->inst_id, inst_id))
518 /* Otherwise, look recursively in our stack. */
520 if (stack->next_di) {
521 for (l = stack->next_di; l; l = l->next) {
523 if (!strcmp(tmp->inst_id, inst_id)) {
534 * Find a decoder instance by its instance ID.
536 * This will recurse to find the instance anywhere in the stack tree of the
539 * @param sess The session holding the protocol decoder instance.
540 * @param inst_id The instance ID to be found.
542 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
546 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
550 struct srd_decoder_inst *tmp, *di;
552 if (session_is_valid(sess) != SRD_OK) {
553 srd_err("Invalid session.");
558 for (l = sess->di_list; l; l = l->next) {
560 if ((di = srd_inst_find_by_id_stack(inst_id, tmp)) != NULL)
567 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
568 struct srd_session *sess, const GSList *stack,
572 struct srd_decoder_inst *tmp, *di;
574 if (session_is_valid(sess) != SRD_OK) {
575 srd_err("Invalid session.");
580 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
582 if (tmp->py_inst == obj)
584 else if (tmp->next_di)
585 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
592 * Find a decoder instance by its Python object.
594 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
595 * This will recurse to find the instance anywhere in the stack tree of all
598 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
599 * stack to search. To start searching at the bottom level of
600 * decoder instances, pass NULL.
601 * @param obj The Python class instantiation.
603 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
609 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
612 struct srd_decoder_inst *di;
613 struct srd_session *sess;
617 for (l = sessions; di == NULL && l != NULL; l = l->next) {
619 di = srd_sess_inst_find_by_obj(sess, stack, obj);
626 * Set the list of initial (assumed) pin values.
628 * If the list already exists, do nothing.
630 * @param di Decoder instance to use. Must not be NULL.
634 static void set_initial_pin_values(struct srd_decoder_inst *di)
638 PyObject *py_initial_pins;
640 if (!di || !di->py_inst) {
641 srd_err("Invalid decoder instance.");
645 /* Nothing to do if di->old_pins_array is already != NULL. */
646 if (di->old_pins_array) {
647 srd_dbg("Initial pins already set, nothing to do.");
651 /* Create an array of old (previous sample) pins, init to 0. */
652 di->old_pins_array = g_array_sized_new(FALSE, TRUE, sizeof(uint8_t), di->dec_num_channels);
653 g_array_set_size(di->old_pins_array, di->dec_num_channels);
655 /* Check if the decoder has set self.initial_pins. */
656 if (!PyObject_HasAttrString(di->py_inst, "initial_pins")) {
657 srd_dbg("Initial pins: all 0 (self.initial_pins not set).");
661 /* Get self.initial_pins. */
662 py_initial_pins = PyObject_GetAttrString(di->py_inst, "initial_pins");
664 /* Fill di->old_pins_array based on self.initial_pins. */
665 s = g_string_sized_new(100);
666 for (i = 0; i < di->dec_num_channels; i++) {
667 di->old_pins_array->data[i] = PyLong_AsLong(PyList_GetItem(py_initial_pins, i));
668 g_string_append_printf(s, "%d, ", di->old_pins_array->data[i]);
670 s = g_string_truncate(s, s->len - 2);
671 srd_dbg("Initial pins: %s.", s->str);
672 g_string_free(s, TRUE);
675 SRD_PRIV void oldpins_array_free(struct srd_decoder_inst *di)
679 if (!di->old_pins_array)
682 srd_dbg("%s: Releasing initial pin state.", di->inst_id);
684 g_array_free(di->old_pins_array, TRUE);
685 di->old_pins_array = NULL;
689 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
693 struct srd_decoder_inst *next_di;
696 srd_dbg("Calling start() method on protocol decoder instance %s.",
699 /* Run self.start(). */
700 if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
701 srd_exception_catch("Protocol decoder instance %s",
703 return SRD_ERR_PYTHON;
707 /* Set the initial pins based on self.initial_pins. */
708 set_initial_pin_values(di);
710 /* Set self.samplenum to 0. */
711 PyObject_SetAttrString(di->py_inst, "samplenum", PyLong_FromLong(0));
713 /* Set self.matched to None. */
714 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
716 /* Start all the PDs stacked on top of this one. */
717 for (l = di->next_di; l; l = l->next) {
719 if ((ret = srd_inst_start(next_di)) != SRD_OK)
727 * Check whether the specified sample matches the specified term.
729 * In the case of SRD_TERM_SKIP, this function can modify
730 * term->num_samples_already_skipped.
732 * @param old_sample The value of the previous sample (0/1).
733 * @param sample The value of the current sample (0/1).
734 * @param term The term that should be checked for a match. Must not be NULL.
736 * @retval TRUE The current sample matches the specified term.
737 * @retval FALSE The current sample doesn't match the specified term, or an
738 * invalid term was provided.
742 static gboolean sample_matches(uint8_t old_sample, uint8_t sample, struct srd_term *term)
747 switch (term->type) {
756 case SRD_TERM_RISING_EDGE:
757 if (old_sample == 0 && sample == 1)
760 case SRD_TERM_FALLING_EDGE:
761 if (old_sample == 1 && sample == 0)
764 case SRD_TERM_EITHER_EDGE:
765 if ((old_sample == 1 && sample == 0) || (old_sample == 0 && sample == 1))
768 case SRD_TERM_NO_EDGE:
769 if ((old_sample == 0 && sample == 0) || (old_sample == 1 && sample == 1))
773 if (term->num_samples_already_skipped == term->num_samples_to_skip)
775 term->num_samples_already_skipped++;
778 srd_err("Unknown term type %d.", term->type);
785 SRD_PRIV void match_array_free(struct srd_decoder_inst *di)
787 if (!di || !di->match_array)
790 g_array_free(di->match_array, TRUE);
791 di->match_array = NULL;
794 SRD_PRIV void condition_list_free(struct srd_decoder_inst *di)
801 for (l = di->condition_list; l; l = l->next) {
804 g_slist_free_full(ll, g_free);
807 di->condition_list = NULL;
810 static gboolean have_non_null_conds(const struct srd_decoder_inst *di)
817 for (l = di->condition_list; l; l = l->next) {
826 static void update_old_pins_array(struct srd_decoder_inst *di,
827 const uint8_t *sample_pos)
830 int i, byte_offset, bit_offset;
832 if (!di || !di->dec_channelmap || !sample_pos)
835 for (i = 0; i < di->dec_num_channels; i++) {
836 byte_offset = di->dec_channelmap[i] / 8;
837 bit_offset = di->dec_channelmap[i] % 8;
838 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
839 di->old_pins_array->data[i] = sample;
843 static gboolean term_matches(const struct srd_decoder_inst *di,
844 struct srd_term *term, const uint8_t *sample_pos)
846 uint8_t old_sample, sample;
847 int byte_offset, bit_offset, ch;
849 if (!di || !di->dec_channelmap || !term || !sample_pos)
852 /* Overwritten below (or ignored for SRD_TERM_SKIP). */
853 old_sample = sample = 0;
855 if (term->type != SRD_TERM_SKIP) {
857 byte_offset = di->dec_channelmap[ch] / 8;
858 bit_offset = di->dec_channelmap[ch] % 8;
859 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
860 old_sample = di->old_pins_array->data[ch];
863 return sample_matches(old_sample, sample, term);
866 static gboolean all_terms_match(const struct srd_decoder_inst *di,
867 const GSList *cond, const uint8_t *sample_pos)
870 struct srd_term *term;
872 if (!di || !cond || !sample_pos)
875 for (l = cond; l; l = l->next) {
877 if (!term_matches(di, term, sample_pos))
884 static gboolean at_least_one_condition_matched(
885 const struct srd_decoder_inst *di, unsigned int num_conditions)
892 for (i = 0; i < num_conditions; i++) {
893 if (di->match_array->data[i])
900 static gboolean find_match(struct srd_decoder_inst *di)
902 static uint64_t s = 0;
903 uint64_t i, j, num_samples_to_process;
905 const uint8_t *sample_pos;
906 unsigned int num_conditions;
908 /* Check whether the condition list is NULL/empty. */
909 if (!di->condition_list) {
910 srd_dbg("NULL/empty condition list, automatic match.");
914 /* Check whether we have any non-NULL conditions. */
915 if (!have_non_null_conds(di)) {
916 srd_dbg("Only NULL conditions in list, automatic match.");
920 num_samples_to_process = di->abs_end_samplenum - di->abs_cur_samplenum;
921 num_conditions = g_slist_length(di->condition_list);
923 /* di->match_array is NULL here. Create a new GArray. */
924 di->match_array = g_array_sized_new(FALSE, TRUE, sizeof(gboolean), num_conditions);
925 g_array_set_size(di->match_array, num_conditions);
927 for (i = 0, s = 0; i < num_samples_to_process; i++, s++, (di->abs_cur_samplenum)++) {
929 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
931 /* Check whether the current sample matches at least one of the conditions (logical OR). */
932 /* IMPORTANT: We need to check all conditions, even if there was a match already! */
933 for (l = di->condition_list, j = 0; l; l = l->next, j++) {
937 /* All terms in 'cond' must match (logical AND). */
938 di->match_array->data[j] = all_terms_match(di, cond, sample_pos);
941 update_old_pins_array(di, sample_pos);
943 /* If at least one condition matched we're done. */
944 if (at_least_one_condition_matched(di, num_conditions))
952 * Process available samples and check if they match the defined conditions.
954 * This function returns if there is an error, or when a match is found, or
955 * when all samples have been processed (whether a match was found or not).
956 * This function immediately terminates when the decoder's wait() method
957 * invocation shall get terminated.
959 * @param di The decoder instance to use. Must not be NULL.
960 * @param found_match Will be set to TRUE if at least one condition matched,
961 * FALSE otherwise. Must not be NULL.
963 * @retval SRD_OK No errors occured, see found_match for the result.
964 * @retval SRD_ERR_ARG Invalid arguments.
968 SRD_PRIV int process_samples_until_condition_match(struct srd_decoder_inst *di, gboolean *found_match)
970 if (!di || !found_match)
973 *found_match = FALSE;
974 if (di->want_wait_terminate)
977 /* Check if any of the current condition(s) match. */
979 /* Feed the (next chunk of the) buffer to find_match(). */
980 *found_match = find_match(di);
982 /* Did we handle all samples yet? */
983 if (di->abs_cur_samplenum >= di->abs_end_samplenum) {
984 srd_dbg("Done, handled all samples (abs cur %" PRIu64
985 " / abs end %" PRIu64 ").",
986 di->abs_cur_samplenum, di->abs_end_samplenum);
990 /* If we didn't find a match, continue looking. */
994 /* At least one condition matched, return. */
1002 * Worker thread (per PD-stack).
1004 * @param data Pointer to the lowest-level PD's device instance.
1007 * @return NULL if there was an error.
1009 static gpointer di_thread(gpointer data)
1012 struct srd_decoder_inst *di;
1020 srd_dbg("%s: Starting thread routine for decoder.", di->inst_id);
1023 * Call self.decode(). Only returns if the PD throws an exception.
1024 * "Regular" termination of the decode() method is not expected.
1026 Py_IncRef(di->py_inst);
1027 srd_dbg("%s: Calling decode() method.", di->inst_id);
1028 py_res = PyObject_CallMethod(di->py_inst, "decode", NULL);
1029 srd_dbg("%s: decode() method terminated.", di->inst_id);
1032 * Make sure to unblock potentially pending srd_inst_decode()
1033 * calls in application threads after the decode() method might
1034 * have terminated, while it neither has processed sample data
1035 * nor has terminated upon request. This happens e.g. when "need
1036 * a samplerate to decode" exception is thrown.
1038 g_mutex_lock(&di->data_mutex);
1039 wanted_term = di->want_wait_terminate;
1040 di->want_wait_terminate = TRUE;
1041 di->handled_all_samples = TRUE;
1042 g_cond_signal(&di->handled_all_samples_cond);
1043 g_mutex_unlock(&di->data_mutex);
1046 * Check for the termination cause of the decode() method.
1047 * Though this is mostly for information.
1049 if (!py_res && wanted_term) {
1051 * Silently ignore errors upon return from decode() calls
1052 * when termination was requested. Terminate the thread
1053 * which executed this instance's decode() logic.
1055 srd_dbg("%s: Thread done (!res, want_term).", di->inst_id);
1061 * The decode() invocation terminated unexpectedly. Have
1062 * the back trace printed, and terminate the thread which
1063 * executed the decode() method.
1065 srd_dbg("%s: decode() terminated unrequested.", di->inst_id);
1066 srd_exception_catch("Protocol decoder instance %s: ", di->inst_id);
1067 srd_dbg("%s: Thread done (!res, !want_term).", di->inst_id);
1072 * TODO: By design the decode() method is not supposed to terminate.
1073 * Nevertheless we have the thread joined, and srd backend calls to
1074 * decode() will re-start another thread transparently.
1076 srd_dbg("%s: decode() terminated (req %d).", di->inst_id, wanted_term);
1080 srd_dbg("%s: Thread done (with res).", di->inst_id);
1086 * Decode a chunk of samples.
1088 * The calls to this function must provide the samples that shall be
1089 * used by the protocol decoder
1090 * - in the correct order ([...]5, 6, 4, 7, 8[...] is a bug),
1091 * - starting from sample zero (2, 3, 4, 5, 6[...] is a bug),
1092 * - consecutively, with no gaps (0, 1, 2, 4, 5[...] is a bug).
1094 * The start- and end-sample numbers are absolute sample numbers (relative
1095 * to the start of the whole capture/file/stream), i.e. they are not relative
1096 * sample numbers within the chunk specified by 'inbuf' and 'inbuflen'.
1098 * Correct example (4096 samples total, 4 chunks @ 1024 samples each):
1099 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1100 * srd_inst_decode(di, 1024, 2048, inbuf, 1024, 1);
1101 * srd_inst_decode(di, 2048, 3072, inbuf, 1024, 1);
1102 * srd_inst_decode(di, 3072, 4096, inbuf, 1024, 1);
1104 * The chunk size ('inbuflen') can be arbitrary and can differ between calls.
1106 * Correct example (4096 samples total, 7 chunks @ various samples each):
1107 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1108 * srd_inst_decode(di, 1024, 1124, inbuf, 100, 1);
1109 * srd_inst_decode(di, 1124, 1424, inbuf, 300, 1);
1110 * srd_inst_decode(di, 1424, 1643, inbuf, 219, 1);
1111 * srd_inst_decode(di, 1643, 2048, inbuf, 405, 1);
1112 * srd_inst_decode(di, 2048, 3072, inbuf, 1024, 1);
1113 * srd_inst_decode(di, 3072, 4096, inbuf, 1024, 1);
1115 * INCORRECT example (4096 samples total, 4 chunks @ 1024 samples each, but
1116 * the start- and end-samplenumbers are not absolute):
1117 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1118 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1119 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1120 * srd_inst_decode(di, 0, 1024, inbuf, 1024, 1);
1122 * @param di The decoder instance to call. Must not be NULL.
1123 * @param abs_start_samplenum The absolute starting sample number for the
1124 * buffer's sample set, relative to the start of capture.
1125 * @param abs_end_samplenum The absolute ending sample number for the
1126 * buffer's sample set, relative to the start of capture.
1127 * @param inbuf The buffer to decode. Must not be NULL.
1128 * @param inbuflen Length of the buffer. Must be > 0.
1129 * @param unitsize The number of bytes per sample. Must be > 0.
1131 * @return SRD_OK upon success, a (negative) error code otherwise.
1135 SRD_PRIV int srd_inst_decode(struct srd_decoder_inst *di,
1136 uint64_t abs_start_samplenum, uint64_t abs_end_samplenum,
1137 const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
1143 /* Return an error upon unusable input. */
1145 srd_dbg("empty decoder instance");
1149 srd_dbg("NULL buffer pointer");
1152 if (inbuflen == 0) {
1153 srd_dbg("empty buffer");
1156 if (unitsize == 0) {
1157 srd_dbg("unitsize 0");
1161 if (abs_start_samplenum != di->abs_cur_samplenum ||
1162 abs_end_samplenum < abs_start_samplenum) {
1163 srd_dbg("Incorrect sample numbers: start=%" PRIu64 ", cur=%"
1164 PRIu64 ", end=%" PRIu64 ".", abs_start_samplenum,
1165 di->abs_cur_samplenum, abs_end_samplenum);
1169 di->data_unitsize = unitsize;
1171 srd_dbg("Decoding: abs start sample %" PRIu64 ", abs end sample %"
1172 PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
1173 "%d), instance %s.", abs_start_samplenum, abs_end_samplenum,
1174 abs_end_samplenum - abs_start_samplenum, inbuflen, di->data_unitsize,
1177 apiver = srd_decoder_apiver(di->decoder);
1181 * Create new srd_logic object. Each iteration around the PD's
1182 * loop will fill one sample into this object.
1184 logic = PyObject_New(srd_logic, (PyTypeObject *)srd_logic_type);
1186 logic->di = (struct srd_decoder_inst *)di;
1187 logic->abs_start_samplenum = abs_start_samplenum;
1189 logic->inbuf = (uint8_t *)inbuf;
1190 logic->inbuflen = inbuflen;
1191 logic->sample = PyList_New(2);
1192 Py_INCREF(logic->sample);
1194 Py_IncRef(di->py_inst);
1195 if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
1196 "KKO", abs_start_samplenum, abs_end_samplenum, logic))) {
1197 srd_exception_catch("Protocol decoder instance %s",
1199 return SRD_ERR_PYTHON;
1201 di->abs_cur_samplenum = abs_end_samplenum;
1204 /* If this is the first call, start the worker thread. */
1205 if (!di->thread_handle) {
1206 srd_dbg("No worker thread for this decoder stack "
1207 "exists yet, creating one: %s.", di->inst_id);
1208 di->thread_handle = g_thread_new(di->inst_id,
1212 /* Push the new sample chunk to the worker thread. */
1213 g_mutex_lock(&di->data_mutex);
1214 di->abs_start_samplenum = abs_start_samplenum;
1215 di->abs_end_samplenum = abs_end_samplenum;
1217 di->inbuflen = inbuflen;
1218 di->got_new_samples = TRUE;
1219 di->handled_all_samples = FALSE;
1220 di->want_wait_terminate = FALSE;
1222 /* Signal the thread that we have new data. */
1223 g_cond_signal(&di->got_new_samples_cond);
1224 g_mutex_unlock(&di->data_mutex);
1226 /* When all samples in this chunk were handled, return. */
1227 g_mutex_lock(&di->data_mutex);
1228 while (!di->handled_all_samples && !di->want_wait_terminate)
1229 g_cond_wait(&di->handled_all_samples_cond, &di->data_mutex);
1230 g_mutex_unlock(&di->data_mutex);
1237 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
1240 struct srd_pd_output *pdo;
1242 srd_dbg("Freeing instance %s", di->inst_id);
1244 srd_inst_join_decode_thread(di);
1245 srd_inst_reset_state(di);
1247 Py_DecRef(di->py_inst);
1248 g_free(di->inst_id);
1249 g_free(di->dec_channelmap);
1250 g_free(di->channel_samples);
1251 g_slist_free(di->next_di);
1252 for (l = di->pd_output; l; l = l->next) {
1254 g_free(pdo->proto_id);
1257 g_slist_free(di->pd_output);
1262 SRD_PRIV void srd_inst_free_all(struct srd_session *sess)
1264 if (session_is_valid(sess) != SRD_OK) {
1265 srd_err("Invalid session.");
1269 g_slist_free_full(sess->di_list, (GDestroyNotify)srd_inst_free);