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