]> sigrok.org Git - libsigrokdecode.git/blame - type_decoder.c
Add initial OUTPUT_LOGIC support.
[libsigrokdecode.git] / type_decoder.c
CommitLineData
d0a0ed03 1/*
50bd5d25 2 * This file is part of the libsigrokdecode project.
d0a0ed03
BV
3 *
4 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
36784362 20#include <config.h>
f6c7eade
MC
21#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */
22#include "libsigrokdecode.h"
dbeaab27 23#include <inttypes.h>
d0a0ed03 24
a4e9ca6f
UH
25/** @cond PRIVATE */
26extern SRD_PRIV GSList *sessions;
27/** @endcond */
28
17475b09
UH
29typedef struct {
30 PyObject_HEAD
31} srd_Decoder;
32
7969d803 33/* This is only used for nicer srd_dbg() output. */
5c723a57 34SRD_PRIV const char *output_type_name(unsigned int idx)
201a85a8
DE
35{
36 static const char names[][16] = {
37 "OUTPUT_ANN",
38 "OUTPUT_PYTHON",
39 "OUTPUT_BINARY",
ddcde186 40 "OUTPUT_LOGIC",
201a85a8
DE
41 "OUTPUT_META",
42 "(invalid)"
43 };
7969d803 44
201a85a8
DE
45 return names[MIN(idx, G_N_ELEMENTS(names) - 1)];
46}
58572aed 47
c1b2bbc1
GS
48static void release_annotation(struct srd_proto_data_annotation *pda)
49{
50 if (!pda)
51 return;
52 if (pda->ann_text)
53 g_strfreev(pda->ann_text);
c1b2bbc1
GS
54}
55
4f75f1c1 56static int convert_annotation(struct srd_decoder_inst *di, PyObject *obj,
0b922460 57 struct srd_proto_data *pdata)
d0a0ed03
BV
58{
59 PyObject *py_tmp;
60 struct srd_pd_output *pdo;
0b922460 61 struct srd_proto_data_annotation *pda;
280d554c 62 int ann_class;
0b922460 63 char **ann_text;
514b2edc
UH
64 PyGILState_STATE gstate;
65
66 gstate = PyGILState_Ensure();
d0a0ed03 67
280d554c 68 /* Should be a list of [annotation class, [string, ...]]. */
0679f5bf 69 if (!PyList_Check(obj)) {
201a85a8 70 srd_err("Protocol decoder %s submitted an annotation that"
0679f5bf 71 " is not a list", di->decoder->name);
514b2edc 72 goto err;
d0a0ed03
BV
73 }
74
361fdcaa 75 /* Should have 2 elements. */
d0a0ed03 76 if (PyList_Size(obj) != 2) {
c9bfccc6 77 srd_err("Protocol decoder %s submitted annotation list with "
4916b173 78 "%zd elements instead of 2", di->decoder->name,
c9bfccc6 79 PyList_Size(obj));
514b2edc 80 goto err;
d0a0ed03
BV
81 }
82
c9bfccc6
UH
83 /*
84 * The first element should be an integer matching a previously
280d554c 85 * registered annotation class.
c9bfccc6 86 */
d0a0ed03
BV
87 py_tmp = PyList_GetItem(obj, 0);
88 if (!PyLong_Check(py_tmp)) {
c9bfccc6
UH
89 srd_err("Protocol decoder %s submitted annotation list, but "
90 "first element was not an integer.", di->decoder->name);
514b2edc 91 goto err;
d0a0ed03 92 }
280d554c
UH
93 ann_class = PyLong_AsLong(py_tmp);
94 if (!(pdo = g_slist_nth_data(di->decoder->annotations, ann_class))) {
d906d3f9 95 srd_err("Protocol decoder %s submitted data to unregistered "
280d554c 96 "annotation class %d.", di->decoder->name, ann_class);
514b2edc 97 goto err;
d0a0ed03 98 }
d0a0ed03 99
361fdcaa 100 /* Second element must be a list. */
d0a0ed03
BV
101 py_tmp = PyList_GetItem(obj, 1);
102 if (!PyList_Check(py_tmp)) {
d906d3f9 103 srd_err("Protocol decoder %s submitted annotation list, but "
c9bfccc6 104 "second element was not a list.", di->decoder->name);
514b2edc 105 goto err;
d0a0ed03 106 }
62a2b15c 107 if (py_strseq_to_char(py_tmp, &ann_text) != SRD_OK) {
d906d3f9 108 srd_err("Protocol decoder %s submitted annotation list, but "
c9bfccc6 109 "second element was malformed.", di->decoder->name);
514b2edc 110 goto err;
d0a0ed03
BV
111 }
112
ee63c5dd 113 pda = pdata->data;
280d554c 114 pda->ann_class = ann_class;
0b922460 115 pda->ann_text = ann_text;
0b922460 116
514b2edc
UH
117 PyGILState_Release(gstate);
118
d0a0ed03 119 return SRD_OK;
514b2edc
UH
120
121err:
122 PyGILState_Release(gstate);
123
124 return SRD_ERR_PYTHON;
d0a0ed03
BV
125}
126
ddcde186
UH
127static void release_logic(struct srd_proto_data_logic *pdl)
128{
129 if (!pdl)
130 return;
131 g_free((void *)pdl->data);
132}
133
134static int convert_logic(struct srd_decoder_inst *di, PyObject *obj,
135 struct srd_proto_data *pdata)
136{
137 struct srd_proto_data_logic *pdl;
138 PyObject *py_tmp;
139 Py_ssize_t size;
140 int logic_class;
141 char *class_name, *buf;
142 PyGILState_STATE gstate;
143
144 gstate = PyGILState_Ensure();
145
146 /* Should be a list of [logic class, bytes]. */
147 if (!PyList_Check(obj)) {
148 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_LOGIC.",
149 di->decoder->name);
150 goto err;
151 }
152
153 /* Should have 2 elements. */
154 if (PyList_Size(obj) != 2) {
155 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list "
156 "with %zd elements instead of 2", di->decoder->name,
157 PyList_Size(obj));
158 goto err;
159 }
160
161 /* The first element should be an integer. */
162 py_tmp = PyList_GetItem(obj, 0);
163 if (!PyLong_Check(py_tmp)) {
164 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list, "
165 "but first element was not an integer.", di->decoder->name);
166 goto err;
167 }
168 logic_class = PyLong_AsLong(py_tmp);
169 if (!(class_name = g_slist_nth_data(di->decoder->logic_output_channels, logic_class))) {
170 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC with "
171 "unregistered logic class %d.", di->decoder->name, logic_class);
172 goto err;
173 }
174
175 /* Second element should be bytes. */
176 py_tmp = PyList_GetItem(obj, 1);
177 if (!PyBytes_Check(py_tmp)) {
178 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC list, "
179 "but second element was not bytes.", di->decoder->name);
180 goto err;
181 }
182
183 /* Consider an empty set of bytes a bug. */
184 if (PyBytes_Size(py_tmp) == 0) {
185 srd_err("Protocol decoder %s submitted SRD_OUTPUT_LOGIC "
186 "with empty data set.", di->decoder->name);
187 goto err;
188 }
189
190 if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
191 goto err;
192
193 PyGILState_Release(gstate);
194
195 pdl = pdata->data;
196 pdl->logic_class = logic_class;
197 pdl->size = size;
198 if (!(pdl->data = g_try_malloc(pdl->size)))
199 return SRD_ERR_MALLOC;
200 memcpy((void *)pdl->data, (const void *)buf, pdl->size);
201
202 return SRD_OK;
203
204err:
205 PyGILState_Release(gstate);
206
207 return SRD_ERR_PYTHON;
208}
209
c1b2bbc1
GS
210static void release_binary(struct srd_proto_data_binary *pdb)
211{
212 if (!pdb)
213 return;
8390f85a 214 g_free((void *)pdb->data);
c1b2bbc1
GS
215}
216
d75d8a7c
BV
217static int convert_binary(struct srd_decoder_inst *di, PyObject *obj,
218 struct srd_proto_data *pdata)
219{
220 struct srd_proto_data_binary *pdb;
221 PyObject *py_tmp;
222 Py_ssize_t size;
223 int bin_class;
224 char *class_name, *buf;
514b2edc
UH
225 PyGILState_STATE gstate;
226
227 gstate = PyGILState_Ensure();
d75d8a7c 228
2824e811
UH
229 /* Should be a list of [binary class, bytes]. */
230 if (!PyList_Check(obj)) {
231 srd_err("Protocol decoder %s submitted non-list for SRD_OUTPUT_BINARY.",
201a85a8 232 di->decoder->name);
514b2edc 233 goto err;
d75d8a7c
BV
234 }
235
236 /* Should have 2 elements. */
2824e811
UH
237 if (PyList_Size(obj) != 2) {
238 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list "
4916b173 239 "with %zd elements instead of 2", di->decoder->name,
d75d8a7c 240 PyList_Size(obj));
514b2edc 241 goto err;
d75d8a7c
BV
242 }
243
244 /* The first element should be an integer. */
2824e811 245 py_tmp = PyList_GetItem(obj, 0);
d75d8a7c 246 if (!PyLong_Check(py_tmp)) {
2824e811 247 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
d75d8a7c 248 "but first element was not an integer.", di->decoder->name);
514b2edc 249 goto err;
d75d8a7c
BV
250 }
251 bin_class = PyLong_AsLong(py_tmp);
252 if (!(class_name = g_slist_nth_data(di->decoder->binary, bin_class))) {
253 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY with "
254 "unregistered binary class %d.", di->decoder->name, bin_class);
514b2edc 255 goto err;
d75d8a7c
BV
256 }
257
258 /* Second element should be bytes. */
2824e811 259 py_tmp = PyList_GetItem(obj, 1);
d75d8a7c 260 if (!PyBytes_Check(py_tmp)) {
2824e811 261 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY list, "
d75d8a7c 262 "but second element was not bytes.", di->decoder->name);
514b2edc 263 goto err;
d75d8a7c
BV
264 }
265
266 /* Consider an empty set of bytes a bug. */
267 if (PyBytes_Size(py_tmp) == 0) {
268 srd_err("Protocol decoder %s submitted SRD_OUTPUT_BINARY "
269 "with empty data set.", di->decoder->name);
514b2edc 270 goto err;
d75d8a7c
BV
271 }
272
d75d8a7c 273 if (PyBytes_AsStringAndSize(py_tmp, &buf, &size) == -1)
514b2edc
UH
274 goto err;
275
276 PyGILState_Release(gstate);
277
c94631f1 278 pdb = pdata->data;
d75d8a7c
BV
279 pdb->bin_class = bin_class;
280 pdb->size = size;
c94631f1 281 if (!(pdb->data = g_try_malloc(pdb->size)))
d75d8a7c
BV
282 return SRD_ERR_MALLOC;
283 memcpy((void *)pdb->data, (const void *)buf, pdb->size);
d75d8a7c
BV
284
285 return SRD_OK;
514b2edc
UH
286
287err:
288 PyGILState_Release(gstate);
289
290 return SRD_ERR_PYTHON;
d75d8a7c
BV
291}
292
29adc171 293static inline struct srd_decoder_inst *srd_sess_inst_find_by_obj(
a4e9ca6f
UH
294 struct srd_session *sess, const GSList *stack, const PyObject *obj)
295{
296 const GSList *l;
297 struct srd_decoder_inst *tmp, *di;
298
299 if (!sess)
300 return NULL;
301
302 di = NULL;
303 for (l = stack ? stack : sess->di_list; di == NULL && l != NULL; l = l->next) {
304 tmp = l->data;
305 if (tmp->py_inst == obj)
306 di = tmp;
307 else if (tmp->next_di)
308 di = srd_sess_inst_find_by_obj(sess, tmp->next_di, obj);
309 }
310
311 return di;
312}
313
314/**
315 * Find a decoder instance by its Python object.
316 *
317 * I.e. find that instance's instantiation of the sigrokdecode.Decoder class.
318 * This will recurse to find the instance anywhere in the stack tree of all
319 * sessions.
320 *
321 * @param stack Pointer to a GSList of struct srd_decoder_inst, indicating the
322 * stack to search. To start searching at the bottom level of
323 * decoder instances, pass NULL.
324 * @param obj The Python class instantiation.
325 *
326 * @return Pointer to struct srd_decoder_inst, or NULL if not found.
327 *
328 * @since 0.1.0
329 */
29adc171 330static inline struct srd_decoder_inst *srd_inst_find_by_obj(
a4e9ca6f
UH
331 const GSList *stack, const PyObject *obj)
332{
333 struct srd_decoder_inst *di;
334 struct srd_session *sess;
335 GSList *l;
336
996b17db
UH
337 /* Performance shortcut: Handle the most common case first. */
338 sess = sessions->data;
339 di = sess->di_list->data;
340 if (di->py_inst == obj)
4f0d192d 341 return di;
996b17db 342
a4e9ca6f
UH
343 di = NULL;
344 for (l = sessions; di == NULL && l != NULL; l = l->next) {
345 sess = l->data;
346 di = srd_sess_inst_find_by_obj(sess, stack, obj);
347 }
348
349 return di;
350}
351
7ee0c40b
BV
352static int convert_meta(struct srd_proto_data *pdata, PyObject *obj)
353{
354 long long intvalue;
355 double dvalue;
514b2edc
UH
356 PyGILState_STATE gstate;
357
358 gstate = PyGILState_Ensure();
7ee0c40b 359
ec31b982 360 if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_INT64)) {
7ee0c40b
BV
361 if (!PyLong_Check(obj)) {
362 PyErr_Format(PyExc_TypeError, "This output was registered "
201a85a8 363 "as 'int', but something else was passed.");
514b2edc 364 goto err;
7ee0c40b
BV
365 }
366 intvalue = PyLong_AsLongLong(obj);
367 if (PyErr_Occurred())
514b2edc 368 goto err;
7ee0c40b 369 pdata->data = g_variant_new_int64(intvalue);
ec31b982 370 } else if (g_variant_type_equal(pdata->pdo->meta_type, G_VARIANT_TYPE_DOUBLE)) {
7ee0c40b
BV
371 if (!PyFloat_Check(obj)) {
372 PyErr_Format(PyExc_TypeError, "This output was registered "
201a85a8 373 "as 'float', but something else was passed.");
514b2edc 374 goto err;
7ee0c40b
BV
375 }
376 dvalue = PyFloat_AsDouble(obj);
377 if (PyErr_Occurred())
514b2edc 378 goto err;
7ee0c40b
BV
379 pdata->data = g_variant_new_double(dvalue);
380 }
381
514b2edc
UH
382 PyGILState_Release(gstate);
383
7ee0c40b 384 return SRD_OK;
514b2edc
UH
385
386err:
387 PyGILState_Release(gstate);
388
389 return SRD_ERR_PYTHON;
7ee0c40b
BV
390}
391
287e2788
UH
392static void release_meta(GVariant *gvar)
393{
394 if (!gvar)
395 return;
396 g_variant_unref(gvar);
397}
398
d0a0ed03
BV
399static PyObject *Decoder_put(PyObject *self, PyObject *args)
400{
401 GSList *l;
4f75f1c1 402 PyObject *py_data, *py_res;
a8b72b05 403 struct srd_decoder_inst *di, *next_di;
d0a0ed03 404 struct srd_pd_output *pdo;
8a9f60b1 405 struct srd_proto_data pdata;
ee63c5dd 406 struct srd_proto_data_annotation pda;
c94631f1 407 struct srd_proto_data_binary pdb;
d0a0ed03
BV
408 uint64_t start_sample, end_sample;
409 int output_id;
2994587f 410 struct srd_pd_callback *cb;
514b2edc
UH
411 PyGILState_STATE gstate;
412
287e2788
UH
413 py_data = NULL;
414
514b2edc 415 gstate = PyGILState_Ensure();
d0a0ed03 416
a8b72b05 417 if (!(di = srd_inst_find_by_obj(NULL, self))) {
58572aed 418 /* Shouldn't happen. */
7a1712c4 419 srd_dbg("put(): self instance not found.");
514b2edc 420 goto err;
58572aed 421 }
d0a0ed03 422
c9bfccc6 423 if (!PyArg_ParseTuple(args, "KKiO", &start_sample, &end_sample,
3d14e7c9 424 &output_id, &py_data)) {
c9bfccc6
UH
425 /*
426 * This throws an exception, but by returning NULL here we let
427 * Python raise it. This results in a much better trace in
428 * controller.c on the decode() method call.
429 */
514b2edc 430 goto err;
c9bfccc6 431 }
d0a0ed03
BV
432
433 if (!(l = g_slist_nth(di->pd_output, output_id))) {
d906d3f9 434 srd_err("Protocol decoder %s submitted invalid output ID %d.",
c9bfccc6 435 di->decoder->name, output_id);
514b2edc 436 goto err;
d0a0ed03
BV
437 }
438 pdo = l->data;
439
43dc0396
UH
440 /* Upon SRD_OUTPUT_PYTHON for stacked PDs, we have a nicer log message later. */
441 if (pdo->output_type != SRD_OUTPUT_PYTHON && di->next_di != NULL) {
755e4a1e
UH
442 srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s on "
443 "oid %d (%s).", di->inst_id, start_sample, end_sample,
444 output_type_name(pdo->output_type), output_id,
445 pdo->proto_id);
43dc0396 446 }
58572aed 447
8a9f60b1
UH
448 pdata.start_sample = start_sample;
449 pdata.end_sample = end_sample;
450 pdata.pdo = pdo;
451 pdata.data = NULL;
d0a0ed03
BV
452
453 switch (pdo->output_type) {
454 case SRD_OUTPUT_ANN:
455 /* Annotations are only fed to callbacks. */
32cfb920 456 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
ee63c5dd 457 pdata.data = &pda;
d75d8a7c 458 /* Convert from PyDict to srd_proto_data_annotation. */
8a9f60b1 459 if (convert_annotation(di, py_data, &pdata) != SRD_OK) {
d0a0ed03
BV
460 /* An error was already logged. */
461 break;
462 }
514b2edc 463 Py_BEGIN_ALLOW_THREADS
8a9f60b1 464 cb->cb(&pdata, cb->cb_data);
514b2edc 465 Py_END_ALLOW_THREADS
c1b2bbc1 466 release_annotation(pdata.data);
d0a0ed03
BV
467 }
468 break;
f2a5df42 469 case SRD_OUTPUT_PYTHON:
d0a0ed03
BV
470 for (l = di->next_di; l; l = l->next) {
471 next_di = l->data;
755e4a1e
UH
472 srd_spew("Instance %s put %" PRIu64 "-%" PRIu64 " %s "
473 "on oid %d (%s) to instance %s.", di->inst_id,
474 start_sample,
43dc0396 475 end_sample, output_type_name(pdo->output_type),
755e4a1e 476 output_id, pdo->proto_id, next_di->inst_id);
c9bfccc6 477 if (!(py_res = PyObject_CallMethod(
3d14e7c9
BV
478 next_di->py_inst, "decode", "KKO", start_sample,
479 end_sample, py_data))) {
201a85a8 480 srd_exception_catch("Calling %s decode() failed",
3d14e7c9 481 next_di->inst_id);
d0a0ed03
BV
482 }
483 Py_XDECREF(py_res);
484 }
3d14e7c9 485 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
7969d803
UH
486 /*
487 * Frontends aren't really supposed to get Python
488 * callbacks, but it's useful for testing.
489 */
8a9f60b1
UH
490 pdata.data = py_data;
491 cb->cb(&pdata, cb->cb_data);
3d14e7c9 492 }
d0a0ed03
BV
493 break;
494 case SRD_OUTPUT_BINARY:
d75d8a7c 495 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
c94631f1 496 pdata.data = &pdb;
d75d8a7c 497 /* Convert from PyDict to srd_proto_data_binary. */
8a9f60b1 498 if (convert_binary(di, py_data, &pdata) != SRD_OK) {
d75d8a7c
BV
499 /* An error was already logged. */
500 break;
501 }
514b2edc 502 Py_BEGIN_ALLOW_THREADS
8a9f60b1 503 cb->cb(&pdata, cb->cb_data);
514b2edc 504 Py_END_ALLOW_THREADS
c1b2bbc1 505 release_binary(pdata.data);
d75d8a7c 506 }
d0a0ed03 507 break;
ddcde186
UH
508 case SRD_OUTPUT_LOGIC:
509 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
510 pdata.data = &pdb;
511 /* Convert from PyDict to srd_proto_data_logic. */
512 if (convert_logic(di, py_data, &pdata) != SRD_OK) {
513 /* An error was already logged. */
514 break;
515 }
516 Py_BEGIN_ALLOW_THREADS
517 cb->cb(&pdata, cb->cb_data);
518 Py_END_ALLOW_THREADS
519 release_logic(pdata.data);
520 }
521 break;
7ee0c40b
BV
522 case SRD_OUTPUT_META:
523 if ((cb = srd_pd_output_callback_find(di->sess, pdo->output_type))) {
524 /* Annotations need converting from PyObject. */
8a9f60b1 525 if (convert_meta(&pdata, py_data) != SRD_OK) {
7ee0c40b
BV
526 /* An exception was already set up. */
527 break;
528 }
514b2edc 529 Py_BEGIN_ALLOW_THREADS
8a9f60b1 530 cb->cb(&pdata, cb->cb_data);
514b2edc 531 Py_END_ALLOW_THREADS
287e2788 532 release_meta(pdata.data);
7ee0c40b
BV
533 }
534 break;
d0a0ed03 535 default:
d906d3f9 536 srd_err("Protocol decoder %s submitted invalid output type %d.",
c9bfccc6 537 di->decoder->name, pdo->output_type);
d0a0ed03
BV
538 break;
539 }
540
514b2edc
UH
541 PyGILState_Release(gstate);
542
d0a0ed03 543 Py_RETURN_NONE;
514b2edc
UH
544
545err:
546 PyGILState_Release(gstate);
547
548 return NULL;
d0a0ed03
BV
549}
550
7ee0c40b
BV
551static PyObject *Decoder_register(PyObject *self, PyObject *args,
552 PyObject *kwargs)
d0a0ed03 553{
a8b72b05 554 struct srd_decoder_inst *di;
7ee0c40b
BV
555 struct srd_pd_output *pdo;
556 PyObject *py_new_output_id;
557 PyTypeObject *meta_type_py;
558 const GVariantType *meta_type_gv;
559 int output_type;
560 char *proto_id, *meta_name, *meta_descr;
7969d803 561 char *keywords[] = { "output_type", "proto_id", "meta", NULL };
514b2edc 562 PyGILState_STATE gstate;
7d82e3c1
GS
563 gboolean is_meta;
564 GSList *l;
565 struct srd_pd_output *cmp;
514b2edc
UH
566
567 gstate = PyGILState_Ensure();
7ee0c40b
BV
568
569 meta_type_py = NULL;
570 meta_type_gv = NULL;
571 meta_name = meta_descr = NULL;
d0a0ed03 572
a8b72b05 573 if (!(di = srd_inst_find_by_obj(NULL, self))) {
d0a0ed03 574 PyErr_SetString(PyExc_Exception, "decoder instance not found");
514b2edc 575 goto err;
d0a0ed03
BV
576 }
577
7969d803 578 /* Default to instance ID, which defaults to class ID. */
7ee0c40b
BV
579 proto_id = di->inst_id;
580 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
581 &output_type, &proto_id,
582 &meta_type_py, &meta_name, &meta_descr)) {
511e2123 583 /* Let Python raise this exception. */
514b2edc 584 goto err;
d0a0ed03
BV
585 }
586
7ee0c40b 587 /* Check if the meta value's type is supported. */
7d82e3c1
GS
588 is_meta = output_type == SRD_OUTPUT_META;
589 if (is_meta) {
7ee0c40b
BV
590 if (meta_type_py == &PyLong_Type)
591 meta_type_gv = G_VARIANT_TYPE_INT64;
592 else if (meta_type_py == &PyFloat_Type)
593 meta_type_gv = G_VARIANT_TYPE_DOUBLE;
594 else {
201a85a8 595 PyErr_Format(PyExc_TypeError, "Unsupported type.");
514b2edc 596 goto err;
7ee0c40b
BV
597 }
598 }
599
7d82e3c1
GS
600 pdo = NULL;
601 for (l = di->pd_output; l; l = l->next) {
602 cmp = l->data;
603 if (cmp->output_type != output_type)
604 continue;
605 if (strcmp(cmp->proto_id, proto_id) != 0)
606 continue;
607 if (is_meta && cmp->meta_type != meta_type_gv)
608 continue;
609 if (is_meta && strcmp(cmp->meta_name, meta_name) != 0)
610 continue;
611 if (is_meta && strcmp(cmp->meta_descr, meta_descr) != 0)
612 continue;
613 pdo = cmp;
614 break;
615 }
616 if (pdo) {
617 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
618 PyGILState_Release(gstate);
619 return py_new_output_id;
620 }
621
077fa8ac 622 pdo = g_malloc(sizeof(struct srd_pd_output));
7ee0c40b
BV
623
624 /* pdo_id is just a simple index, nothing is deleted from this list anyway. */
625 pdo->pdo_id = g_slist_length(di->pd_output);
626 pdo->output_type = output_type;
627 pdo->di = di;
628 pdo->proto_id = g_strdup(proto_id);
629
630 if (output_type == SRD_OUTPUT_META) {
631 pdo->meta_type = meta_type_gv;
632 pdo->meta_name = g_strdup(meta_name);
633 pdo->meta_descr = g_strdup(meta_descr);
634 }
635
636 di->pd_output = g_slist_append(di->pd_output, pdo);
637 py_new_output_id = Py_BuildValue("i", pdo->pdo_id);
638
514b2edc
UH
639 PyGILState_Release(gstate);
640
755e4a1e
UH
641 srd_dbg("Instance %s creating new output type %s as oid %d (%s).",
642 di->inst_id, output_type_name(output_type), pdo->pdo_id,
643 proto_id);
644
7ee0c40b 645 return py_new_output_id;
514b2edc
UH
646
647err:
648 PyGILState_Release(gstate);
649
650 return NULL;
7ee0c40b
BV
651}
652
21dfd91d
UH
653static int get_term_type(const char *v)
654{
655 switch (v[0]) {
656 case 'h':
657 return SRD_TERM_HIGH;
658 case 'l':
659 return SRD_TERM_LOW;
660 case 'r':
661 return SRD_TERM_RISING_EDGE;
662 case 'f':
663 return SRD_TERM_FALLING_EDGE;
664 case 'e':
665 return SRD_TERM_EITHER_EDGE;
666 case 'n':
667 return SRD_TERM_NO_EDGE;
4e7ccaf9
UH
668 default:
669 return -1;
21dfd91d
UH
670 }
671
672 return -1;
673}
674
675/**
676 * Get the pin values at the current sample number.
677 *
678 * @param di The decoder instance to use. Must not be NULL.
679 * The number of channels must be >= 1.
680 *
681 * @return A newly allocated PyTuple containing the pin values at the
682 * current sample number.
683 */
684static PyObject *get_current_pinvalues(const struct srd_decoder_inst *di)
685{
686 int i;
687 uint8_t sample;
688 const uint8_t *sample_pos;
689 int byte_offset, bit_offset;
690 PyObject *py_pinvalues;
514b2edc
UH
691 PyGILState_STATE gstate;
692
21dfd91d
UH
693 if (!di) {
694 srd_err("Invalid decoder instance.");
695 return NULL;
696 }
697
73578d2e
UH
698 gstate = PyGILState_Ensure();
699
21dfd91d
UH
700 py_pinvalues = PyTuple_New(di->dec_num_channels);
701
702 for (i = 0; i < di->dec_num_channels; i++) {
703 /* A channelmap value of -1 means "unused optional channel". */
704 if (di->dec_channelmap[i] == -1) {
705 /* Value of unused channel is 0xff, instead of 0 or 1. */
3d9e87aa 706 PyTuple_SetItem(py_pinvalues, i, PyLong_FromUnsignedLong(0xff));
21dfd91d 707 } else {
4564e8e5 708 sample_pos = di->inbuf + ((di->abs_cur_samplenum - di->abs_start_samplenum) * di->data_unitsize);
21dfd91d
UH
709 byte_offset = di->dec_channelmap[i] / 8;
710 bit_offset = di->dec_channelmap[i] % 8;
711 sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0;
3d9e87aa 712 PyTuple_SetItem(py_pinvalues, i, PyLong_FromUnsignedLong(sample));
21dfd91d
UH
713 }
714 }
715
514b2edc
UH
716 PyGILState_Release(gstate);
717
21dfd91d
UH
718 return py_pinvalues;
719}
720
721/**
722 * Create a list of terms in the specified condition.
723 *
724 * If there are no terms in the condition, 'term_list' will be NULL.
725 *
1cb40e10 726 * @param di The decoder instance to use. Must not be NULL.
21dfd91d
UH
727 * @param py_dict A Python dict containing terms. Must not be NULL.
728 * @param term_list Pointer to a GSList which will be set to the newly
729 * created list of terms. Must not be NULL.
730 *
731 * @return SRD_OK upon success, a negative error code otherwise.
732 */
1cb40e10
GS
733static int create_term_list(struct srd_decoder_inst *di,
734 PyObject *py_dict, GSList **term_list)
21dfd91d
UH
735{
736 Py_ssize_t pos = 0;
737 PyObject *py_key, *py_value;
738 struct srd_term *term;
1cb40e10 739 int64_t num_samples_to_skip;
21dfd91d 740 char *term_str;
514b2edc 741 PyGILState_STATE gstate;
21dfd91d
UH
742
743 if (!py_dict || !term_list)
744 return SRD_ERR_ARG;
745
746 /* "Create" an empty GSList of terms. */
747 *term_list = NULL;
748
514b2edc
UH
749 gstate = PyGILState_Ensure();
750
21dfd91d
UH
751 /* Iterate over all items in the current dict. */
752 while (PyDict_Next(py_dict, &pos, &py_key, &py_value)) {
753 /* Check whether the current key is a string or a number. */
754 if (PyLong_Check(py_key)) {
755 /* The key is a number. */
21dfd91d
UH
756 /* Get the value string. */
757 if ((py_pydictitem_as_str(py_dict, py_key, &term_str)) != SRD_OK) {
758 srd_err("Failed to get the value.");
514b2edc 759 goto err;
21dfd91d 760 }
35c10c0e 761 term = g_malloc(sizeof(struct srd_term));
21dfd91d
UH
762 term->type = get_term_type(term_str);
763 term->channel = PyLong_AsLong(py_key);
1cb40e10
GS
764 if (term->channel < 0 || term->channel >= di->dec_num_channels)
765 term->type = SRD_TERM_ALWAYS_FALSE;
21dfd91d
UH
766 g_free(term_str);
767 } else if (PyUnicode_Check(py_key)) {
768 /* The key is a string. */
1cb40e10 769 /* TODO: Check if the key is "skip". */
21dfd91d
UH
770 if ((py_pydictitem_as_long(py_dict, py_key, &num_samples_to_skip)) != SRD_OK) {
771 srd_err("Failed to get number of samples to skip.");
514b2edc 772 goto err;
21dfd91d 773 }
35c10c0e 774 term = g_malloc(sizeof(struct srd_term));
21dfd91d
UH
775 term->type = SRD_TERM_SKIP;
776 term->num_samples_to_skip = num_samples_to_skip;
777 term->num_samples_already_skipped = 0;
99e26489 778 if (num_samples_to_skip < 0)
1cb40e10 779 term->type = SRD_TERM_ALWAYS_FALSE;
21dfd91d
UH
780 } else {
781 srd_err("Term key is neither a string nor a number.");
514b2edc 782 goto err;
21dfd91d
UH
783 }
784
785 /* Add the term to the list of terms. */
786 *term_list = g_slist_append(*term_list, term);
787 }
788
514b2edc
UH
789 PyGILState_Release(gstate);
790
21dfd91d 791 return SRD_OK;
514b2edc
UH
792
793err:
794 PyGILState_Release(gstate);
795
796 return SRD_ERR;
21dfd91d
UH
797}
798
799/**
800 * Replace the current condition list with the new one.
801 *
802 * @param self TODO. Must not be NULL.
803 * @param args TODO. Must not be NULL.
804 *
805 * @retval SRD_OK The new condition list was set successfully.
806 * @retval SRD_ERR There was an error setting the new condition list.
807 * The contents of di->condition_list are undefined.
808 * @retval 9999 TODO.
809 */
810static int set_new_condition_list(PyObject *self, PyObject *args)
811{
812 struct srd_decoder_inst *di;
813 GSList *term_list;
814 PyObject *py_conditionlist, *py_conds, *py_dict;
815 int i, num_conditions, ret;
514b2edc 816 PyGILState_STATE gstate;
21dfd91d
UH
817
818 if (!self || !args)
819 return SRD_ERR_ARG;
820
514b2edc
UH
821 gstate = PyGILState_Ensure();
822
21dfd91d
UH
823 /* Get the decoder instance. */
824 if (!(di = srd_inst_find_by_obj(NULL, self))) {
825 PyErr_SetString(PyExc_Exception, "decoder instance not found");
514b2edc 826 goto err;
21dfd91d
UH
827 }
828
04383ea8
GS
829 /*
830 * Return an error condition from .wait() when termination is
831 * requested, such that decode() will terminate.
832 */
833 if (di->want_wait_terminate) {
834 srd_dbg("%s: %s: Skip (want_term).", di->inst_id, __func__);
514b2edc 835 goto err;
04383ea8
GS
836 }
837
6e19f325
GS
838 /*
839 * Parse the argument of self.wait() into 'py_conds', and check
840 * the data type. The argument is optional, None is assumed in
841 * its absence. None or an empty dict or an empty list mean that
842 * there is no condition, and the next available sample shall
843 * get returned to the caller.
844 */
845 py_conds = Py_None;
846 if (!PyArg_ParseTuple(args, "|O", &py_conds)) {
21dfd91d 847 /* Let Python raise this exception. */
514b2edc 848 goto err;
21dfd91d 849 }
6e19f325
GS
850 if (py_conds == Py_None) {
851 /* 'py_conds' is None. */
514b2edc 852 goto ret_9999;
6e19f325 853 } else if (PyList_Check(py_conds)) {
21dfd91d
UH
854 /* 'py_conds' is a list. */
855 py_conditionlist = py_conds;
856 num_conditions = PyList_Size(py_conditionlist);
857 if (num_conditions == 0)
514b2edc 858 goto ret_9999; /* The PD invoked self.wait([]). */
733047ed 859 Py_INCREF(py_conditionlist);
21dfd91d
UH
860 } else if (PyDict_Check(py_conds)) {
861 /* 'py_conds' is a dict. */
862 if (PyDict_Size(py_conds) == 0)
514b2edc 863 goto ret_9999; /* The PD invoked self.wait({}). */
21dfd91d
UH
864 /* Make a list and put the dict in there for convenience. */
865 py_conditionlist = PyList_New(1);
733047ed 866 Py_INCREF(py_conds);
21dfd91d
UH
867 PyList_SetItem(py_conditionlist, 0, py_conds);
868 num_conditions = 1;
869 } else {
870 srd_err("Condition list is neither a list nor a dict.");
514b2edc 871 goto err;
21dfd91d
UH
872 }
873
874 /* Free the old condition list. */
875 condition_list_free(di);
876
877 ret = SRD_OK;
878
879 /* Iterate over the conditions, set di->condition_list accordingly. */
880 for (i = 0; i < num_conditions; i++) {
881 /* Get a condition (dict) from the condition list. */
882 py_dict = PyList_GetItem(py_conditionlist, i);
883 if (!PyDict_Check(py_dict)) {
884 srd_err("Condition is not a dict.");
885 ret = SRD_ERR;
886 break;
887 }
888
889 /* Create the list of terms in this condition. */
1cb40e10 890 if ((ret = create_term_list(di, py_dict, &term_list)) < 0)
21dfd91d
UH
891 break;
892
893 /* Add the new condition to the PD instance's condition list. */
894 di->condition_list = g_slist_append(di->condition_list, term_list);
895 }
896
897 Py_DecRef(py_conditionlist);
898
514b2edc
UH
899 PyGILState_Release(gstate);
900
21dfd91d 901 return ret;
514b2edc
UH
902
903err:
904 PyGILState_Release(gstate);
905
906 return SRD_ERR;
907
908ret_9999:
909 PyGILState_Release(gstate);
910
911 return 9999;
21dfd91d
UH
912}
913
96e1cee7
GS
914/**
915 * Create a SKIP condition list for condition-less .wait() calls.
916 *
917 * @param di Decoder instance.
918 * @param count Number of samples to skip.
919 *
920 * @retval SRD_OK The new condition list was set successfully.
921 * @retval SRD_ERR There was an error setting the new condition list.
922 * The contents of di->condition_list are undefined.
923 *
924 * This routine is a reduced and specialized version of the @ref
925 * set_new_condition_list() and @ref create_term_list() routines which
926 * gets invoked when .wait() was called without specifications for
927 * conditions. This minor duplication of the SKIP term list creation
928 * simplifies the logic and avoids the creation of expensive Python
929 * objects with "constant" values which the caller did not pass in the
930 * first place. It results in maximum sharing of match handling code
931 * paths.
932 */
933static int set_skip_condition(struct srd_decoder_inst *di, uint64_t count)
934{
935 struct srd_term *term;
936 GSList *term_list;
937
938 condition_list_free(di);
35c10c0e 939 term = g_malloc(sizeof(*term));
96e1cee7
GS
940 term->type = SRD_TERM_SKIP;
941 term->num_samples_to_skip = count;
942 term->num_samples_already_skipped = 0;
943 term_list = g_slist_append(NULL, term);
944 di->condition_list = g_slist_append(di->condition_list, term_list);
945
946 return SRD_OK;
947}
948
21dfd91d
UH
949static PyObject *Decoder_wait(PyObject *self, PyObject *args)
950{
951 int ret;
96e1cee7 952 uint64_t skip_count;
21dfd91d
UH
953 unsigned int i;
954 gboolean found_match;
955 struct srd_decoder_inst *di;
e2768fbc 956 PyObject *py_pinvalues, *py_matched, *py_samplenum;
514b2edc 957 PyGILState_STATE gstate;
21dfd91d
UH
958
959 if (!self || !args)
960 return NULL;
961
514b2edc
UH
962 gstate = PyGILState_Ensure();
963
21dfd91d
UH
964 if (!(di = srd_inst_find_by_obj(NULL, self))) {
965 PyErr_SetString(PyExc_Exception, "decoder instance not found");
514b2edc 966 PyGILState_Release(gstate);
21dfd91d
UH
967 Py_RETURN_NONE;
968 }
969
970 ret = set_new_condition_list(self, args);
04383ea8
GS
971 if (ret < 0) {
972 srd_dbg("%s: %s: Aborting wait().", di->inst_id, __func__);
514b2edc 973 goto err;
04383ea8 974 }
21dfd91d 975 if (ret == 9999) {
96e1cee7
GS
976 /*
977 * Empty condition list, automatic match. Arrange for the
978 * execution of regular match handling code paths such that
979 * the next available sample is returned to the caller.
980 * Make sure to skip one sample when "anywhere within the
981 * stream", yet make sure to not skip sample number 0.
982 */
983 if (di->abs_cur_samplenum)
984 skip_count = 1;
985 else if (!di->condition_list)
986 skip_count = 0;
987 else
988 skip_count = 1;
989 ret = set_skip_condition(di, skip_count);
990 if (ret < 0) {
991 srd_dbg("%s: %s: Cannot setup condition-less wait().",
992 di->inst_id, __func__);
514b2edc 993 goto err;
96e1cee7 994 }
21dfd91d
UH
995 }
996
997 while (1) {
514b2edc
UH
998
999 Py_BEGIN_ALLOW_THREADS
1000
04383ea8 1001 /* Wait for new samples to process, or termination request. */
21dfd91d 1002 g_mutex_lock(&di->data_mutex);
04383ea8 1003 while (!di->got_new_samples && !di->want_wait_terminate)
21dfd91d
UH
1004 g_cond_wait(&di->got_new_samples_cond, &di->data_mutex);
1005
04383ea8
GS
1006 /*
1007 * Check whether any of the current condition(s) match.
1008 * Arrange for termination requests to take a code path which
1009 * won't find new samples to process, pretends to have processed
1010 * previously stored samples, and returns to the main thread,
1011 * while the termination request still gets signalled.
1012 */
1013 found_match = FALSE;
60d4764a
UH
1014
1015 /* Ignore return value for now, should never be negative. */
1016 (void)process_samples_until_condition_match(di, &found_match);
21dfd91d 1017
514b2edc
UH
1018 Py_END_ALLOW_THREADS
1019
21dfd91d
UH
1020 /* If there's a match, set self.samplenum etc. and return. */
1021 if (found_match) {
1022 /* Set self.samplenum to the (absolute) sample number that matched. */
3d9e87aa 1023 py_samplenum = PyLong_FromUnsignedLongLong(di->abs_cur_samplenum);
e2768fbc
UH
1024 PyObject_SetAttrString(di->py_inst, "samplenum", py_samplenum);
1025 Py_DECREF(py_samplenum);
21dfd91d
UH
1026
1027 if (di->match_array && di->match_array->len > 0) {
1028 py_matched = PyTuple_New(di->match_array->len);
1029 for (i = 0; i < di->match_array->len; i++)
1030 PyTuple_SetItem(py_matched, i, PyBool_FromLong(di->match_array->data[i]));
1031 PyObject_SetAttrString(di->py_inst, "matched", py_matched);
e2768fbc 1032 Py_DECREF(py_matched);
21dfd91d
UH
1033 match_array_free(di);
1034 } else {
1035 PyObject_SetAttrString(di->py_inst, "matched", Py_None);
1036 }
fa168be6 1037
21dfd91d
UH
1038 py_pinvalues = get_current_pinvalues(di);
1039
1040 g_mutex_unlock(&di->data_mutex);
1041
514b2edc
UH
1042 PyGILState_Release(gstate);
1043
21dfd91d
UH
1044 return py_pinvalues;
1045 }
1046
1047 /* No match, reset state for the next chunk. */
1048 di->got_new_samples = FALSE;
1049 di->handled_all_samples = TRUE;
4564e8e5
UH
1050 di->abs_start_samplenum = 0;
1051 di->abs_end_samplenum = 0;
21dfd91d
UH
1052 di->inbuf = NULL;
1053 di->inbuflen = 0;
1054
1055 /* Signal the main thread that we handled all samples. */
1056 g_cond_signal(&di->handled_all_samples_cond);
1057
04383ea8
GS
1058 /*
1059 * When termination of wait() and decode() was requested,
1060 * then exit the loop after releasing the mutex.
1061 */
1062 if (di->want_wait_terminate) {
1063 srd_dbg("%s: %s: Will return from wait().",
1064 di->inst_id, __func__);
1065 g_mutex_unlock(&di->data_mutex);
514b2edc 1066 goto err;
04383ea8
GS
1067 }
1068
21dfd91d
UH
1069 g_mutex_unlock(&di->data_mutex);
1070 }
1071
514b2edc
UH
1072 PyGILState_Release(gstate);
1073
21dfd91d 1074 Py_RETURN_NONE;
514b2edc
UH
1075
1076err:
1077 PyGILState_Release(gstate);
1078
1079 return NULL;
21dfd91d
UH
1080}
1081
1082/**
1083 * Return whether the specified channel was supplied to the decoder.
1084 *
1085 * @param self TODO. Must not be NULL.
1086 * @param args TODO. Must not be NULL.
1087 *
1088 * @retval Py_True The channel has been supplied by the frontend.
1089 * @retval Py_False The channel has been supplied by the frontend.
1090 * @retval NULL An error occurred.
1091 */
1092static PyObject *Decoder_has_channel(PyObject *self, PyObject *args)
1093{
cd8d9188 1094 int idx, count;
21dfd91d 1095 struct srd_decoder_inst *di;
514b2edc 1096 PyGILState_STATE gstate;
21dfd91d
UH
1097
1098 if (!self || !args)
1099 return NULL;
1100
514b2edc
UH
1101 gstate = PyGILState_Ensure();
1102
21dfd91d
UH
1103 if (!(di = srd_inst_find_by_obj(NULL, self))) {
1104 PyErr_SetString(PyExc_Exception, "decoder instance not found");
514b2edc 1105 goto err;
21dfd91d
UH
1106 }
1107
cd8d9188
GS
1108 /*
1109 * Get the integer argument of self.has_channel(). Check for
1110 * the range of supported PD input channel numbers.
1111 */
1112 if (!PyArg_ParseTuple(args, "i", &idx)) {
21dfd91d 1113 /* Let Python raise this exception. */
514b2edc 1114 goto err;
21dfd91d
UH
1115 }
1116
cd8d9188
GS
1117 count = g_slist_length(di->decoder->channels) +
1118 g_slist_length(di->decoder->opt_channels);
1119 if (idx < 0 || idx >= count) {
1120 srd_err("Invalid index %d, PD channel count %d.", idx, count);
1121 PyErr_SetString(PyExc_IndexError, "invalid channel index");
514b2edc 1122 goto err;
21dfd91d
UH
1123 }
1124
514b2edc
UH
1125 PyGILState_Release(gstate);
1126
21dfd91d 1127 return (di->dec_channelmap[idx] == -1) ? Py_False : Py_True;
514b2edc
UH
1128
1129err:
1130 PyGILState_Release(gstate);
1131
1132 return NULL;
21dfd91d
UH
1133}
1134
d0a0ed03 1135static PyMethodDef Decoder_methods[] = {
7969d803
UH
1136 { "put", Decoder_put, METH_VARARGS,
1137 "Accepts a dictionary with the following keys: startsample, endsample, data" },
9e3ed177 1138 { "register", (PyCFunction)(void(*)(void))Decoder_register, METH_VARARGS|METH_KEYWORDS,
7969d803
UH
1139 "Register a new output stream" },
1140 { "wait", Decoder_wait, METH_VARARGS,
1141 "Wait for one or more conditions to occur" },
1142 { "has_channel", Decoder_has_channel, METH_VARARGS,
1143 "Report whether a channel was supplied" },
d0a0ed03
BV
1144 {NULL, NULL, 0, NULL}
1145};
1146
21dfd91d
UH
1147/**
1148 * Create the sigrokdecode.Decoder type.
1149 *
201a85a8 1150 * @return The new type object.
21dfd91d 1151 *
201a85a8
DE
1152 * @private
1153 */
1154SRD_PRIV PyObject *srd_Decoder_type_new(void)
1155{
1156 PyType_Spec spec;
1157 PyType_Slot slots[] = {
1158 { Py_tp_doc, "sigrok Decoder base class" },
1159 { Py_tp_methods, Decoder_methods },
1160 { Py_tp_new, (void *)&PyType_GenericNew },
1161 { 0, NULL }
1162 };
514b2edc
UH
1163 PyObject *py_obj;
1164 PyGILState_STATE gstate;
1165
1166 gstate = PyGILState_Ensure();
1167
201a85a8
DE
1168 spec.name = "sigrokdecode.Decoder";
1169 spec.basicsize = sizeof(srd_Decoder);
1170 spec.itemsize = 0;
1171 spec.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1172 spec.slots = slots;
1173
514b2edc
UH
1174 py_obj = PyType_FromSpec(&spec);
1175
1176 PyGILState_Release(gstate);
1177
1178 return py_obj;
201a85a8 1179}