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