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