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 SRD_PRIV void oldpins_array_free(struct srd_decoder_inst *di);
42 * Decoder instance handling.
46 * @defgroup grp_instances Decoder instances
48 * Decoder instance handling.
54 * Set one or more options in a decoder instance.
56 * Handled options are removed from the hash.
58 * @param di Decoder instance.
59 * @param options A GHashTable of options to set.
61 * @return SRD_OK upon success, a (negative) error code otherwise.
65 SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
68 struct srd_decoder_option *sdo;
69 PyObject *py_di_options, *py_optval;
76 PyGILState_STATE gstate;
79 srd_err("Invalid decoder instance.");
84 srd_err("Invalid options GHashTable.");
88 gstate = PyGILState_Ensure();
90 if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
91 /* Decoder has no options. */
92 PyGILState_Release(gstate);
93 if (g_hash_table_size(options) == 0) {
94 /* No options provided. */
97 srd_err("Protocol decoder has no options.");
103 ret = SRD_ERR_PYTHON;
107 * The 'options' tuple is a class variable, but we need to
108 * change it. Changing it directly will affect the entire class,
109 * so we need to create a new object for it, and populate that
112 if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
114 Py_DECREF(py_di_options);
115 py_di_options = PyDict_New();
116 PyObject_SetAttrString(di->py_inst, "options", py_di_options);
118 for (l = di->decoder->options; l; l = l->next) {
120 if ((value = g_hash_table_lookup(options, sdo->id))) {
121 /* A value was supplied for this option. */
122 if (!g_variant_type_equal(g_variant_get_type(value),
123 g_variant_get_type(sdo->def))) {
124 srd_err("Option '%s' should have the same type "
125 "as the default value.", sdo->id);
129 /* Use default for this option. */
132 if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
133 val_str = g_variant_get_string(value, NULL);
134 if (!(py_optval = PyUnicode_FromString(val_str))) {
135 /* Some UTF-8 encoding error. */
137 srd_err("Option '%s' requires a UTF-8 string value.", sdo->id);
140 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_INT64)) {
141 val_int = g_variant_get_int64(value);
142 if (!(py_optval = PyLong_FromLong(val_int))) {
143 /* ValueError Exception */
145 srd_err("Option '%s' has invalid integer value.", sdo->id);
148 } else if (g_variant_is_of_type(value, G_VARIANT_TYPE_DOUBLE)) {
149 val_double = g_variant_get_double(value);
150 if (!(py_optval = PyFloat_FromDouble(val_double))) {
151 /* ValueError Exception */
153 srd_err("Option '%s' has invalid float value.",
158 if (PyDict_SetItemString(py_di_options, sdo->id, py_optval) == -1)
160 /* Not harmful even if we used the default. */
161 g_hash_table_remove(options, sdo->id);
163 if (g_hash_table_size(options) != 0)
164 srd_warn("Unknown options specified for '%s'", di->inst_id);
169 Py_XDECREF(py_optval);
170 if (PyErr_Occurred()) {
171 srd_exception_catch("Stray exception in srd_inst_option_set()");
172 ret = SRD_ERR_PYTHON;
174 PyGILState_Release(gstate);
179 /* Helper GComparefunc for g_slist_find_custom() in srd_inst_channel_set_all() */
180 static gint compare_channel_id(const struct srd_channel *pdch,
181 const char *channel_id)
183 return strcmp(pdch->id, channel_id);
187 * Set all channels in a decoder instance.
189 * This function sets _all_ channels for the specified decoder instance, i.e.,
190 * it overwrites any channels that were already defined (if any).
192 * @param di Decoder instance.
193 * @param new_channels A GHashTable of channels to set. Key is channel name,
194 * value is the channel number. Samples passed to this
195 * instance will be arranged in this order.
197 * @return SRD_OK upon success, a (negative) error code otherwise.
201 SRD_API int srd_inst_channel_set_all(struct srd_decoder_inst *di,
202 GHashTable *new_channels)
204 GVariant *channel_val;
207 struct srd_channel *pdch;
208 int *new_channelmap, new_channelnum, num_required_channels, i;
211 srd_dbg("Setting channels for instance %s with list of %d channels.",
212 di->inst_id, g_hash_table_size(new_channels));
214 if (g_hash_table_size(new_channels) == 0)
215 /* No channels provided. */
218 if (di->dec_num_channels == 0) {
219 /* Decoder has no channels. */
220 srd_err("Protocol decoder %s has no channels to define.",
225 new_channelmap = g_malloc(sizeof(int) * di->dec_num_channels);
228 * For now, map all indexes to channel -1 (can be overridden later).
229 * This -1 is interpreted as an unspecified channel later.
231 for (i = 0; i < di->dec_num_channels; i++)
232 new_channelmap[i] = -1;
234 for (l = g_hash_table_get_keys(new_channels); l; l = l->next) {
235 channel_id = l->data;
236 channel_val = g_hash_table_lookup(new_channels, channel_id);
237 if (!g_variant_is_of_type(channel_val, G_VARIANT_TYPE_INT32)) {
238 /* Channel name was specified without a value. */
239 srd_err("No channel number was specified for %s.",
241 g_free(new_channelmap);
244 new_channelnum = g_variant_get_int32(channel_val);
245 if (!(sl = g_slist_find_custom(di->decoder->channels, channel_id,
246 (GCompareFunc)compare_channel_id))) {
247 /* Fall back on optional channels. */
248 if (!(sl = g_slist_find_custom(di->decoder->opt_channels,
249 channel_id, (GCompareFunc)compare_channel_id))) {
250 srd_err("Protocol decoder %s has no channel "
251 "'%s'.", di->decoder->name, channel_id);
252 g_free(new_channelmap);
257 new_channelmap[pdch->order] = new_channelnum;
258 srd_dbg("Setting channel mapping: %s (PD ch idx %d) = input data ch idx %d.",
259 pdch->id, pdch->order, new_channelnum);
262 srd_dbg("Final channel map:");
263 num_required_channels = g_slist_length(di->decoder->channels);
264 for (i = 0; i < di->dec_num_channels; i++) {
265 GSList *l = g_slist_nth(di->decoder->channels, i);
267 l = g_slist_nth(di->decoder->opt_channels,
268 i - num_required_channels);
270 srd_dbg(" - PD ch idx %d (%s) = input data ch idx %d (%s)", i,
271 pdch->id, new_channelmap[i],
272 (i < num_required_channels) ? "required" : "optional");
275 /* Report an error if not all required channels were specified. */
276 for (i = 0; i < num_required_channels; i++) {
277 if (new_channelmap[i] != -1)
279 pdch = g_slist_nth(di->decoder->channels, i)->data;
280 srd_err("Required channel '%s' (index %d) was not specified.",
285 g_free(di->dec_channelmap);
286 di->dec_channelmap = new_channelmap;
292 * Create a new protocol decoder instance.
294 * @param sess The session holding the protocol decoder instance.
295 * @param decoder_id Decoder 'id' field.
296 * @param options GHashtable of options which override the defaults set in
297 * the decoder class. May be NULL.
299 * @return Pointer to a newly allocated struct srd_decoder_inst, or
300 * NULL in case of failure.
304 SRD_API struct srd_decoder_inst *srd_inst_new(struct srd_session *sess,
305 const char *decoder_id, GHashTable *options)
308 struct srd_decoder *dec;
309 struct srd_decoder_inst *di;
311 PyGILState_STATE gstate;
314 srd_dbg("Creating new %s instance.", decoder_id);
316 if (session_is_valid(sess) != SRD_OK) {
317 srd_err("Invalid session.");
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 di->old_pins_array = g_array_sized_new(FALSE, TRUE, sizeof(uint8_t),
367 di->dec_num_channels);
368 g_array_set_size(di->old_pins_array, di->dec_num_channels);
369 memset(di->old_pins_array->data, SRD_INITIAL_PIN_SAME_AS_SAMPLE0,
370 di->dec_num_channels);
372 gstate = PyGILState_Ensure();
374 /* Create a new instance of this decoder class. */
375 if (!(di->py_inst = PyObject_CallObject(dec->py_dec, NULL))) {
376 if (PyErr_Occurred())
377 srd_exception_catch("Failed to create %s instance",
379 PyGILState_Release(gstate);
380 g_free(di->dec_channelmap);
385 PyGILState_Release(gstate);
387 if (options && srd_inst_option_set(di, options) != SRD_OK) {
388 g_free(di->dec_channelmap);
393 di->condition_list = NULL;
394 di->match_array = NULL;
395 di->abs_start_samplenum = 0;
396 di->abs_end_samplenum = 0;
399 di->abs_cur_samplenum = 0;
400 di->thread_handle = NULL;
401 di->got_new_samples = FALSE;
402 di->handled_all_samples = FALSE;
403 di->want_wait_terminate = FALSE;
406 * Strictly speaking initialization of statically allocated
407 * condition and mutex variables (or variables allocated on the
408 * stack) is not required, but won't harm either. Explicitly
409 * running init() will better match subsequent clear() calls.
411 g_cond_init(&di->got_new_samples_cond);
412 g_cond_init(&di->handled_all_samples_cond);
413 g_mutex_init(&di->data_mutex);
415 /* Instance takes input from a frontend by default. */
416 sess->di_list = g_slist_append(sess->di_list, di);
417 srd_dbg("Created new %s instance with ID %s.", decoder_id, di->inst_id);
422 static void srd_inst_join_decode_thread(struct srd_decoder_inst *di)
426 if (!di->thread_handle)
429 srd_dbg("%s: Joining decoder thread.", di->inst_id);
432 * Terminate potentially running threads which still
433 * execute the decoder instance's decode() method.
435 srd_dbg("%s: Raising want_term, sending got_new.", di->inst_id);
436 g_mutex_lock(&di->data_mutex);
437 di->want_wait_terminate = TRUE;
438 g_cond_signal(&di->got_new_samples_cond);
439 g_mutex_unlock(&di->data_mutex);
441 srd_dbg("%s: Running join().", di->inst_id);
442 (void)g_thread_join(di->thread_handle);
443 srd_dbg("%s: Call to join() done.", di->inst_id);
444 di->thread_handle = NULL;
447 * Reset condition and mutex variables, such that next
448 * operations on them will find them in a clean state.
450 g_cond_clear(&di->got_new_samples_cond);
451 g_cond_init(&di->got_new_samples_cond);
452 g_cond_clear(&di->handled_all_samples_cond);
453 g_cond_init(&di->handled_all_samples_cond);
454 g_mutex_clear(&di->data_mutex);
455 g_mutex_init(&di->data_mutex);
458 static void srd_inst_reset_state(struct srd_decoder_inst *di)
463 srd_dbg("%s: Resetting decoder state.", di->inst_id);
466 * Reset internal state of the decoder.
468 condition_list_free(di);
469 match_array_free(di);
470 di->abs_start_samplenum = 0;
471 di->abs_end_samplenum = 0;
474 di->abs_cur_samplenum = 0;
475 oldpins_array_free(di);
476 di->got_new_samples = FALSE;
477 di->handled_all_samples = FALSE;
478 di->want_wait_terminate = FALSE;
479 /* Conditions and mutex got reset after joining the thread. */
483 * Stack a decoder instance on top of another.
485 * @param sess The session holding the protocol decoder instances.
486 * @param di_bottom The instance on top of which di_top will be stacked.
487 * @param di_top The instance to go on top.
489 * @return SRD_OK upon success, a (negative) error code otherwise.
493 SRD_API int srd_inst_stack(struct srd_session *sess,
494 struct srd_decoder_inst *di_bottom,
495 struct srd_decoder_inst *di_top)
497 if (session_is_valid(sess) != SRD_OK) {
498 srd_err("Invalid session.");
502 if (!di_bottom || !di_top) {
503 srd_err("Invalid from/to instance pair.");
507 if (g_slist_find(sess->di_list, di_top)) {
508 /* Remove from the unstacked list. */
509 sess->di_list = g_slist_remove(sess->di_list, di_top);
512 /* Stack on top of source di. */
513 di_bottom->next_di = g_slist_append(di_bottom->next_di, di_top);
515 srd_dbg("Stacked %s onto %s.", di_top->inst_id, di_bottom->inst_id);
521 * Search a decoder instance and its stack for instance ID.
523 * @param[in] inst_id ID to search for.
524 * @param[in] stack A decoder instance, potentially with stacked instances.
526 * @return The matching instance, or NULL.
528 static struct srd_decoder_inst *srd_inst_find_by_id_stack(const char *inst_id,
529 struct srd_decoder_inst *stack)
532 struct srd_decoder_inst *tmp, *di;
534 if (!strcmp(stack->inst_id, inst_id))
537 /* Otherwise, look recursively in our stack. */
539 if (stack->next_di) {
540 for (l = stack->next_di; l; l = l->next) {
542 if (!strcmp(tmp->inst_id, inst_id)) {
553 * Find a decoder instance by its instance ID.
555 * This will recurse to find the instance anywhere in the stack tree of the
558 * @param sess The session holding the protocol decoder instance.
559 * @param inst_id The instance ID to be found.
561 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
565 SRD_API struct srd_decoder_inst *srd_inst_find_by_id(struct srd_session *sess,
569 struct srd_decoder_inst *tmp, *di;
571 if (session_is_valid(sess) != SRD_OK) {
572 srd_err("Invalid session.");
577 for (l = sess->di_list; l; l = l->next) {
579 if ((di = srd_inst_find_by_id_stack(inst_id, tmp)) != NULL)
586 static struct srd_decoder_inst *srd_sess_inst_find_by_obj(
587 struct srd_session *sess, const GSList *stack,
591 struct srd_decoder_inst *tmp, *di;
593 if (session_is_valid(sess) != SRD_OK) {
594 srd_err("Invalid session.");
599 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
601 if (tmp->py_inst == obj)
603 else if (tmp->next_di)
604 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
611 * Find a decoder instance by its Python object.
613 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
614 * This will recurse to find the instance anywhere in the stack tree of all
617 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
618 * stack to search. To start searching at the bottom level of
619 * decoder instances, pass NULL.
620 * @param obj The Python class instantiation.
622 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
628 SRD_PRIV struct srd_decoder_inst *srd_inst_find_by_obj(const GSList *stack,
631 struct srd_decoder_inst *di;
632 struct srd_session *sess;
636 for (l = sessions; di == NULL && l != NULL; l = l->next) {
638 di = srd_sess_inst_find_by_obj(sess, stack, obj);
645 * Set the list of initial (assumed) pin values.
647 * @param di Decoder instance to use. Must not be NULL.
648 * @param initial_pins A GArray of uint8_t values. Must not be NULL.
652 SRD_API int srd_inst_initial_pins_set_all(struct srd_decoder_inst *di, GArray *initial_pins)
658 srd_err("Invalid decoder instance.");
665 if (initial_pins->len != (guint)di->dec_num_channels) {
666 srd_err("Incorrect number of channels (need %d, got %d).",
667 di->dec_num_channels, initial_pins->len);
671 /* Sanity-check initial pin state values. */
672 for (i = 0; i < di->dec_num_channels; i++) {
673 if (initial_pins->data[i] <= 2)
675 srd_err("Invalid initial channel %d pin state: %d.",
676 i, initial_pins->data[i]);
680 s = g_string_sized_new(100);
681 for (i = 0; i < di->dec_num_channels; i++) {
682 di->old_pins_array->data[i] = initial_pins->data[i];
683 g_string_append_printf(s, "%d, ", di->old_pins_array->data[i]);
685 s = g_string_truncate(s, s->len - 2);
686 srd_dbg("Initial pins: %s.", s->str);
687 g_string_free(s, TRUE);
693 SRD_PRIV void oldpins_array_free(struct srd_decoder_inst *di)
697 if (!di->old_pins_array)
700 srd_dbg("%s: Releasing initial pin state.", di->inst_id);
702 g_array_free(di->old_pins_array, TRUE);
703 di->old_pins_array = NULL;
707 SRD_PRIV int srd_inst_start(struct srd_decoder_inst *di)
711 struct srd_decoder_inst *next_di;
713 PyGILState_STATE gstate;
715 srd_dbg("Calling start() method on protocol decoder instance %s.",
718 gstate = PyGILState_Ensure();
720 /* Run self.start(). */
721 if (!(py_res = PyObject_CallMethod(di->py_inst, "start", NULL))) {
722 srd_exception_catch("Protocol decoder instance %s",
724 PyGILState_Release(gstate);
725 return SRD_ERR_PYTHON;
729 /* Set self.samplenum to 0. */
730 PyObject_SetAttrString(di->py_inst, "samplenum", PyLong_FromLong(0));
732 /* Set self.matched to None. */
733 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
735 PyGILState_Release(gstate);
737 /* Start all the PDs stacked on top of this one. */
738 for (l = di->next_di; l; l = l->next) {
740 if ((ret = srd_inst_start(next_di)) != SRD_OK)
748 * Check whether the specified sample matches the specified term.
750 * In the case of SRD_TERM_SKIP, this function can modify
751 * term->num_samples_already_skipped.
753 * @param old_sample The value of the previous sample (0/1).
754 * @param sample The value of the current sample (0/1).
755 * @param term The term that should be checked for a match. Must not be NULL.
757 * @retval TRUE The current sample matches the specified term.
758 * @retval FALSE The current sample doesn't match the specified term, or an
759 * invalid term was provided.
763 static gboolean sample_matches(uint8_t old_sample, uint8_t sample, struct srd_term *term)
765 /* Caller ensures term != NULL. */
767 switch (term->type) {
776 case SRD_TERM_RISING_EDGE:
777 if (old_sample == 0 && sample == 1)
780 case SRD_TERM_FALLING_EDGE:
781 if (old_sample == 1 && sample == 0)
784 case SRD_TERM_EITHER_EDGE:
785 if ((old_sample == 1 && sample == 0) || (old_sample == 0 && sample == 1))
788 case SRD_TERM_NO_EDGE:
789 if ((old_sample == 0 && sample == 0) || (old_sample == 1 && sample == 1))
793 if (term->num_samples_already_skipped == term->num_samples_to_skip)
795 term->num_samples_already_skipped++;
798 srd_err("Unknown term type %d.", term->type);
806 SRD_PRIV void match_array_free(struct srd_decoder_inst *di)
808 if (!di || !di->match_array)
811 g_array_free(di->match_array, TRUE);
812 di->match_array = NULL;
816 SRD_PRIV void condition_list_free(struct srd_decoder_inst *di)
823 for (l = di->condition_list; l; l = l->next) {
826 g_slist_free_full(ll, g_free);
829 di->condition_list = NULL;
832 static gboolean have_non_null_conds(const struct srd_decoder_inst *di)
839 for (l = di->condition_list; l; l = l->next) {
848 static void update_old_pins_array(struct srd_decoder_inst *di,
849 const uint8_t *sample_pos)
852 int i, byte_offset, bit_offset;
854 if (!di || !di->dec_channelmap || !sample_pos)
857 for (i = 0; i < di->dec_num_channels; i++) {
858 byte_offset = di->dec_channelmap[i] / 8;
859 bit_offset = di->dec_channelmap[i] % 8;
860 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
861 di->old_pins_array->data[i] = sample;
865 static void update_old_pins_array_initial_pins(struct srd_decoder_inst *di)
868 int i, byte_offset, bit_offset;
869 const uint8_t *sample_pos;
871 if (!di || !di->dec_channelmap)
874 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
876 for (i = 0; i < di->dec_num_channels; i++) {
877 if (di->old_pins_array->data[i] != SRD_INITIAL_PIN_SAME_AS_SAMPLE0)
879 byte_offset = di->dec_channelmap[i] / 8;
880 bit_offset = di->dec_channelmap[i] % 8;
881 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
882 di->old_pins_array->data[i] = sample;
886 static gboolean term_matches(const struct srd_decoder_inst *di,
887 struct srd_term *term, const uint8_t *sample_pos)
889 uint8_t old_sample, sample;
890 int byte_offset, bit_offset, ch;
892 /* Caller ensures di, di->dec_channelmap, term, sample_pos != NULL. */
894 if (term->type == SRD_TERM_SKIP)
895 return sample_matches(0, 0, term);
898 byte_offset = di->dec_channelmap[ch] / 8;
899 bit_offset = di->dec_channelmap[ch] % 8;
900 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
901 old_sample = di->old_pins_array->data[ch];
903 return sample_matches(old_sample, sample, term);
906 static gboolean all_terms_match(const struct srd_decoder_inst *di,
907 const GSList *cond, const uint8_t *sample_pos)
910 struct srd_term *term;
912 /* Caller ensures di, cond, sample_pos != NULL. */
914 for (l = cond; l; l = l->next) {
916 if (!term_matches(di, term, sample_pos))
923 static gboolean at_least_one_condition_matched(
924 const struct srd_decoder_inst *di, unsigned int num_conditions)
928 /* Caller ensures di != NULL. */
930 for (i = 0; i < num_conditions; i++) {
931 if (di->match_array->data[i])
938 static gboolean find_match(struct srd_decoder_inst *di)
940 uint64_t i, j, num_samples_to_process;
942 const uint8_t *sample_pos;
943 unsigned int num_conditions;
945 /* Caller ensures di != NULL. */
947 /* Check whether the condition list is NULL/empty. */
948 if (!di->condition_list) {
949 srd_dbg("NULL/empty condition list, automatic match.");
953 /* Check whether we have any non-NULL conditions. */
954 if (!have_non_null_conds(di)) {
955 srd_dbg("Only NULL conditions in list, automatic match.");
959 num_samples_to_process = di->abs_end_samplenum - di->abs_cur_samplenum;
960 num_conditions = g_slist_length(di->condition_list);
962 /* di->match_array is NULL here. Create a new GArray. */
963 di->match_array = g_array_sized_new(FALSE, TRUE, sizeof(gboolean), num_conditions);
964 g_array_set_size(di->match_array, num_conditions);
966 /* Sample 0: Set di->old_pins_array for SRD_INITIAL_PIN_SAME_AS_SAMPLE0 pins. */
967 if (di->abs_cur_samplenum == 0)
968 update_old_pins_array_initial_pins(di);
970 for (i = 0; i < num_samples_to_process; i++, (di->abs_cur_samplenum)++) {
972 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
974 /* Check whether the current sample matches at least one of the conditions (logical OR). */
975 /* IMPORTANT: We need to check all conditions, even if there was a match already! */
976 for (l = di->condition_list, j = 0; l; l = l->next, j++) {
980 /* All terms in 'cond' must match (logical AND). */
981 di->match_array->data[j] = all_terms_match(di, cond, sample_pos);
984 update_old_pins_array(di, sample_pos);
986 /* If at least one condition matched we're done. */
987 if (at_least_one_condition_matched(di, num_conditions))
995 * Process available samples and check if they match the defined conditions.
997 * This function returns if there is an error, or when a match is found, or
998 * when all samples have been processed (whether a match was found or not).
999 * This function immediately terminates when the decoder's wait() method
1000 * invocation shall get terminated.
1002 * @param di The decoder instance to use. Must not be NULL.
1003 * @param found_match Will be set to TRUE if at least one condition matched,
1004 * FALSE otherwise. Must not be NULL.
1006 * @retval SRD_OK No errors occured, see found_match for the result.
1007 * @retval SRD_ERR_ARG Invalid arguments.
1011 SRD_PRIV int process_samples_until_condition_match(struct srd_decoder_inst *di, gboolean *found_match)
1013 if (!di || !found_match)
1016 *found_match = FALSE;
1017 if (di->want_wait_terminate)
1020 /* Check if any of the current condition(s) match. */
1022 /* Feed the (next chunk of the) buffer to find_match(). */
1023 *found_match = find_match(di);
1025 /* Did we handle all samples yet? */
1026 if (di->abs_cur_samplenum >= di->abs_end_samplenum) {
1027 srd_dbg("Done, handled all samples (abs cur %" PRIu64
1028 " / abs end %" PRIu64 ").",
1029 di->abs_cur_samplenum, di->abs_end_samplenum);
1033 /* If we didn't find a match, continue looking. */
1034 if (!(*found_match))
1037 /* At least one condition matched, return. */
1045 * Worker thread (per PD-stack).
1047 * @param data Pointer to the lowest-level PD's device instance.
1050 * @return NULL if there was an error.
1052 static gpointer di_thread(gpointer data)
1055 struct srd_decoder_inst *di;
1057 PyGILState_STATE gstate;
1064 srd_dbg("%s: Starting thread routine for decoder.", di->inst_id);
1066 gstate = PyGILState_Ensure();
1069 * Call self.decode(). Only returns if the PD throws an exception.
1070 * "Regular" termination of the decode() method is not expected.
1072 Py_IncRef(di->py_inst);
1073 srd_dbg("%s: Calling decode() method.", di->inst_id);
1074 py_res = PyObject_CallMethod(di->py_inst, "decode", NULL);
1075 srd_dbg("%s: decode() method terminated.", di->inst_id);
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.
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);
1092 * Check for the termination cause of the decode() method.
1093 * Though this is mostly for information.
1095 if (!py_res && wanted_term) {
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.
1101 srd_dbg("%s: Thread done (!res, want_term).", di->inst_id);
1103 PyGILState_Release(gstate);
1108 * The decode() invocation terminated unexpectedly. Have
1109 * the back trace printed, and terminate the thread which
1110 * executed the decode() method.
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);
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.
1124 srd_dbg("%s: decode() terminated (req %d).", di->inst_id, wanted_term);
1128 PyGILState_Release(gstate);
1130 srd_dbg("%s: Thread done (with res).", di->inst_id);
1136 * Decode a chunk of samples.
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).
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'.
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);
1154 * The chunk size ('inbuflen') can be arbitrary and can differ between calls.
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);
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);
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.
1181 * @return SRD_OK upon success, a (negative) error code otherwise.
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)
1189 /* Return an error upon unusable input. */
1191 srd_dbg("empty decoder instance");
1195 srd_dbg("NULL buffer pointer");
1198 if (inbuflen == 0) {
1199 srd_dbg("empty buffer");
1202 if (unitsize == 0) {
1203 srd_dbg("unitsize 0");
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);
1215 di->data_unitsize = unitsize;
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,
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,
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;
1236 di->inbuflen = inbuflen;
1237 di->got_new_samples = TRUE;
1238 di->handled_all_samples = FALSE;
1239 di->want_wait_terminate = FALSE;
1241 /* Signal the thread that we have new data. */
1242 g_cond_signal(&di->got_new_samples_cond);
1243 g_mutex_unlock(&di->data_mutex);
1245 /* When all samples in this chunk were handled, return. */
1246 g_mutex_lock(&di->data_mutex);
1247 while (!di->handled_all_samples && !di->want_wait_terminate)
1248 g_cond_wait(&di->handled_all_samples_cond, &di->data_mutex);
1249 g_mutex_unlock(&di->data_mutex);
1255 SRD_PRIV void srd_inst_free(struct srd_decoder_inst *di)
1258 struct srd_pd_output *pdo;
1259 PyGILState_STATE gstate;
1261 srd_dbg("Freeing instance %s", di->inst_id);
1263 srd_inst_join_decode_thread(di);
1265 srd_inst_reset_state(di);
1267 gstate = PyGILState_Ensure();
1268 Py_DecRef(di->py_inst);
1269 PyGILState_Release(gstate);
1271 g_free(di->inst_id);
1272 g_free(di->dec_channelmap);
1273 g_free(di->channel_samples);
1274 g_slist_free(di->next_di);
1275 for (l = di->pd_output; l; l = l->next) {
1277 g_free(pdo->proto_id);
1280 g_slist_free(di->pd_output);
1285 SRD_PRIV void srd_inst_free_all(struct srd_session *sess)
1287 if (session_is_valid(sess) != SRD_OK) {
1288 srd_err("Invalid session.");
1292 g_slist_free_full(sess->di_list, (GDestroyNotify)srd_inst_free);