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