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