]> sigrok.org Git - libsigrok.git/blame - src/input/logicport.c
input/logicport: introduce input module for LogicPort File (*.lpf)
[libsigrok.git] / src / input / logicport.c
CommitLineData
e1b115bd
GS
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2018 Gerhard Sittig <gerhard.sittig@gmx.net>
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 2 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
20/*
21 * See the LA1034 vendor's http://www.pctestinstruments.com/ website.
22 *
23 * The hardware comes with (Windows only) software which uses the .lpf
24 * ("LogicPort File") filename extension for project files, which hold
25 * both the configuration as well as sample data (up to 2K samples). In
26 * the absence of an attached logic analyzer, the software provides a
27 * demo mode which generates random input signals. The software installs
28 * example project files (with samples), too.
29 *
30 * The file format is "mostly text", is line oriented, though it uses
31 * funny DC1 separator characters as well as line continuation by means
32 * of a combination of DC1 and slashes. Fortunately the last text line
33 * is terminated by means of CRLF.
34 *
35 * The software is rather complex and has features which don't easily
36 * translate to sigrok semantics (like one signal being a member of
37 * multiple groups, display format specs for groups' values).
38 *
39 * This input module implementation supports the following features:
40 * - input format auto detection
41 * - sample period to sample rate conversion
42 * - wire names, acquisition filters ("enabled") and inversion flags
43 * - decompression (repetition counters for sample data)
44 * - strict '0' and '1' levels (as well as ignoring 'U' values)
45 * - signal names (user assigned names, "aliases" for "wires")
46 * - signal groups (no support for multiple assignments, no support for
47 * display format specs)
48 * - "logic" channels (mere bits, no support for analog channels, also
49 * nothing analog "gets derived from" any signal groups) -- libsigrok
50 * using applications might provide such a feature if they want to
51 */
52
53#include <config.h>
54#include <ctype.h>
55#include <glib.h>
56#include <stdint.h>
57#include <stdlib.h>
58#include <string.h>
59#include <unistd.h>
60#include <libsigrok/libsigrok.h>
61#include "libsigrok-internal.h"
62
63/* TODO: Move these helpers to some library API routine group. */
64struct sr_channel_group *sr_channel_group_new(const char *name, void *priv);
65void sr_channel_group_free(struct sr_channel_group *cg);
66
67#define LOG_PREFIX "input/logicport"
68
69#define MAX_CHANNELS 34
70#define CHUNK_SIZE (4 * 1024 * 1024)
71
72#define CRLF "\r\n"
73#define DC1_CHR '\x11'
74#define DC1_STR "\x11"
75#define CONT_OPEN "/" DC1_STR
76#define CONT_CLOSE DC1_STR "/"
77
78/*
79 * This is some heuristics (read: a HACK). The current implementation
80 * neither processes nor displays the user's notes, but takes their
81 * presence as a hint that all relevant input was seen, and sample data
82 * can get forwarded to the session bus.
83 */
84#define LAST_KEYWORD "NotesString"
85
86/*
87 * The vendor software supports signal groups, and a single signal can
88 * be a member in multiple groups at the same time. The sigrok project
89 * does not support that configuration. Let's ignore the "All Signals"
90 * group by default, thus reducing the probability of a conflict.
91 */
92#define SKIP_SIGNAL_GROUP "All Signals"
93
94struct signal_group_desc {
95 char *name;
96 uint64_t mask;
97};
98
99struct context {
100 gboolean got_header;
101 gboolean ch_feed_prep;
102 gboolean header_sent;
103 gboolean rate_sent;
104 char *sw_version;
105 size_t sw_build;
106 GString *cont_buff;
107 size_t channel_count;
108 size_t sample_lines_total;
109 size_t sample_lines_read;
110 size_t sample_lines_fed;
111 uint64_t samples_got_uncomp;
112 enum {
113 SAMPLEDATA_NONE,
114 SAMPLEDATA_OPEN_BRACE,
115 SAMPLEDATA_WIRES_COUNT,
116 SAMPLEDATA_DATA_LINES,
117 SAMPLEDATA_CLOSE_BRACE,
118 } in_sample_data;
119 struct sample_data_entry {
120 uint64_t bits;
121 size_t repeat;
122 } *sample_data_queue;
123 uint64_t sample_rate;
124 uint64_t wires_all_mask;
125 uint64_t wires_enabled;
126 uint64_t wires_inverted;
127 uint64_t wires_undefined;
128 char *wire_names[MAX_CHANNELS];
129 char *signal_names[MAX_CHANNELS];
130 uint64_t wires_grouped;
131 GSList *signal_groups;
132 GSList *channels;
133 size_t unitsize;
134 size_t samples_per_chunk;
135 size_t samples_in_buffer;
136 uint8_t *feed_buffer;
137};
138
139static struct signal_group_desc *alloc_signal_group(const char *name)
140{
141 struct signal_group_desc *desc;
142
143 desc = g_malloc0(sizeof(*desc));
144 if (!desc)
145 return NULL;
146 if (name) {
147 desc->name = g_strdup(name);
148 if (!desc->name) {
149 g_free(desc);
150 return NULL;
151 }
152 }
153
154 return desc;
155}
156
157static void free_signal_group(struct signal_group_desc *desc)
158{
159 if (!desc)
160 return;
161 g_free(desc->name);
162 g_free(desc);
163}
164
165struct sr_channel_group *sr_channel_group_new(const char *name, void *priv)
166{
167 struct sr_channel_group *cg;
168
169 cg = g_malloc0(sizeof(*cg));
170 if (!cg)
171 return NULL;
172 if (name && *name) {
173 cg->name = g_strdup(name);
174 if (!cg->name) {
175 g_free(cg);
176 return NULL;
177 }
178 }
179 cg->priv = priv;
180
181 return cg;
182}
183
184void sr_channel_group_free(struct sr_channel_group *cg)
185{
186 if (!cg)
187 return;
188 g_free(cg->name);
189 g_slist_free(cg->channels);
190}
191
192/* Wrapper for GDestroyNotify compatibility. */
193static void sg_free(void *p)
194{
195 return free_signal_group(p);
196}
197
198static int check_vers_line(char *line, int need_key,
199 gchar **version, gchar **build)
200{
201 static const char *keyword = "Version";
202 static const char *caution = " CAUTION: Do not change the contents of this file.";
203 char *read_ptr;
204 const char *prev_ptr;
205
206 read_ptr = line;
207 if (version)
208 *version = NULL;
209 if (build)
210 *build = NULL;
211
212 /* Expect the 'Version' literal, followed by a DC1 separator. */
213 if (need_key) {
214 if (strncmp(read_ptr, keyword, strlen(keyword)) != 0)
215 return SR_ERR_DATA;
216 read_ptr += strlen(keyword);
217 if (*read_ptr != DC1_CHR)
218 return SR_ERR_DATA;
219 read_ptr++;
220 }
221
222 /* Expect some "\d+\.\d+" style version string and DC1. */
223 if (!*read_ptr)
224 return SR_ERR_DATA;
225 if (version)
226 *version = read_ptr;
227 prev_ptr = read_ptr;
228 read_ptr += strspn(read_ptr, "0123456789.");
229 if (read_ptr == prev_ptr)
230 return SR_ERR_DATA;
231 if (*read_ptr != DC1_CHR)
232 return SR_ERR_DATA;
233 *read_ptr++ = '\0';
234
235 /* Expect some "\d+" style build number and DC1. */
236 if (!*read_ptr)
237 return SR_ERR_DATA;
238 if (build)
239 *build = read_ptr;
240 prev_ptr = read_ptr;
241 read_ptr += strspn(read_ptr, "0123456789");
242 if (read_ptr == prev_ptr)
243 return SR_ERR_DATA;
244 if (*read_ptr != DC1_CHR)
245 return SR_ERR_DATA;
246 *read_ptr++ = '\0';
247
248 /* Expect the 'CAUTION...' text (weak test, only part of the text). */
249 if (strncmp(read_ptr, caution, strlen(caution)) != 0)
250 return SR_ERR_DATA;
251 read_ptr += strlen(caution);
252
253 /* No check for CRLF, due to the weak CAUTION test. */
254 return SR_OK;
255}
256
257static int process_wire_names(struct context *inc, char **names)
258{
259 size_t count, idx;
260
261 /*
262 * The 'names' array contains the *wire* names, plus a 'Count'
263 * label for the last column.
264 */
265 count = g_strv_length(names);
266 if (count != inc->channel_count + 1)
267 return SR_ERR_DATA;
268 if (strcmp(names[inc->channel_count], "Count") != 0)
269 return SR_ERR_DATA;
270
271 for (idx = 0; idx < inc->channel_count; idx++)
272 inc->wire_names[idx] = g_strdup(names[idx]);
273
274 return SR_OK;
275}
276
277static int process_signal_names(struct context *inc, char **names)
278{
279 size_t count, idx;
280
281 /*
282 * The 'names' array contains the *signal* names (and no other
283 * entries, unlike the *wire* names).
284 */
285 count = g_strv_length(names);
286 if (count != inc->channel_count)
287 return SR_ERR_DATA;
288
289 for (idx = 0; idx < inc->channel_count; idx++)
290 inc->signal_names[idx] = g_strdup(names[idx]);
291
292 return SR_OK;
293}
294
295static int process_signal_group(struct context *inc, char **args)
296{
297 char *name, *wires;
298 struct signal_group_desc *desc;
299 uint64_t bit_tmpl, bit_mask;
300 char *p, *endp;
301 size_t idx;
302
303 /*
304 * List of arguments that we receive:
305 * - [0] group name
306 * - [1] - [5] uncertain meaning, four integers and one boolean
307 * - [6] comma separated list of wire indices (zero based)
308 * - [7] - [9] uncertain meaning, a boolean, two integers
309 * - [10] - [35] uncertain meaning, 26 empty columns
310 */
311
312 /* Check for the minimum amount of input data. */
313 if (!args)
314 return SR_ERR_DATA;
315 if (g_strv_length(args) < 7)
316 return SR_ERR_DATA;
317 name = args[0];
318 wires = args[6];
319
320 /* Accept empty names and empty signal lists. Silently ignore. */
321 if (!name || !*name)
322 return SR_OK;
323 if (!wires || !*wires)
324 return SR_OK;
325 /*
326 * TODO: Introduce a user configurable "ignore" option? Skip the
327 * "All Signals" group by default, and in addition whatever
328 * the user specified?
329 */
330 if (strcmp(name, SKIP_SIGNAL_GROUP) == 0) {
331 sr_info("Skipping signal group '%s'", name);
332 return SR_OK;
333 }
334
335 /*
336 * Create the descriptor here to store the member list to. We
337 * cannot access signal names and sigrok channels yet, they
338 * only become avilable at a later point in time.
339 */
340 desc = alloc_signal_group(name);
341 if (!desc)
342 return SR_ERR_MALLOC;
343 inc->signal_groups = g_slist_append(inc->signal_groups, desc);
344
345 /*
346 * Determine the bit mask of the group's signals' indices.
347 *
348 * Implementation note: Use a "template" for a single bit, to
349 * avoid portability issues with upper bits. Without this 64bit
350 * intermediate variable, I would not know how to phrase e.g.
351 * (1ULL << 33) in portable, robust, and easy to maintain ways
352 * on all platforms that are supported by sigrok.
353 */
354 bit_tmpl = 1UL << 0;
355 bit_mask = 0;
356 p = wires;
357 while (p && *p) {
358 endp = NULL;
359 idx = strtoul(p, &endp, 0);
360 if (!endp || endp == p)
361 return SR_ERR_DATA;
362 if (*endp && *endp != ',')
363 return SR_ERR_DATA;
364 p = endp;
365 if (*p == ',')
366 p++;
367 if (idx >= MAX_CHANNELS)
368 return SR_ERR_DATA;
369 bit_mask = bit_tmpl << idx;
370 if (inc->wires_grouped & bit_mask) {
371 sr_warn("Not adding signal at index %zu to group %s (multiple assignments)",
372 idx, name);
373 } else {
374 desc->mask |= bit_mask;
375 inc->wires_grouped |= bit_mask;
376 }
377 }
378 sr_dbg("'Group' done, name '%s', mask 0x%" PRIx64 ".",
379 desc->name, desc->mask);
380
381 return SR_OK;
382}
383
384static int process_ungrouped_signals(struct context *inc)
385{
386 uint64_t bit_mask;
387 struct signal_group_desc *desc;
388
389 /*
390 * Only create the "ungrouped" channel group if there are any
391 * groups of other signals already.
392 */
393 if (!inc->signal_groups)
394 return SR_OK;
395
396 /*
397 * Determine the bit mask of signals that are part of the
398 * acquisition and are not a member of any other group.
399 */
400 bit_mask = inc->wires_all_mask;
401 bit_mask &= inc->wires_enabled;
402 bit_mask &= ~inc->wires_grouped;
403 sr_dbg("'ungrouped' check: all 0x%" PRIx64 ", en 0x%" PRIx64 ", grp 0x%" PRIx64 " -> un 0x%" PRIx64 ".",
404 inc->wires_all_mask, inc->wires_enabled,
405 inc->wires_grouped, bit_mask);
406 if (!bit_mask)
407 return SR_OK;
408
409 /* Create a sigrok channel group without a name. */
410 desc = alloc_signal_group(NULL);
411 if (!desc)
412 return SR_ERR_MALLOC;
413 inc->signal_groups = g_slist_append(inc->signal_groups, desc);
414 desc->mask = bit_mask;
415
416 return SR_OK;
417}
418
419static int process_enabled_channels(struct context *inc, char **flags)
420{
421 size_t count, idx;
422 uint64_t bits, mask;
423
424 /*
425 * The 'flags' array contains (the textual representation of)
426 * the "enabled" state of the acquisition device's channels.
427 */
428 count = g_strv_length(flags);
429 if (count != inc->channel_count)
430 return SR_ERR_DATA;
431 bits = 0;
432 mask = 1UL << 0;
433 for (idx = 0; idx < inc->channel_count; idx++, mask <<= 1) {
434 if (strcmp(flags[idx], "True") == 0)
435 bits |= mask;
436 }
437 inc->wires_enabled = bits;
438
439 return SR_OK;
440}
441
442static int process_inverted_channels(struct context *inc, char **flags)
443{
444 size_t count, idx;
445 uint64_t bits, mask;
446
447 /*
448 * The 'flags' array contains (the textual representation of)
449 * the "inverted" state of the acquisition device's channels.
450 */
451 count = g_strv_length(flags);
452 if (count != inc->channel_count)
453 return SR_ERR_DATA;
454 bits = 0;
455 mask = 1UL << 0;
456 for (idx = 0; idx < inc->channel_count; idx++, mask <<= 1) {
457 if (strcmp(flags[idx], "True") == 0)
458 bits |= mask;
459 }
460 inc->wires_inverted = bits;
461
462 return SR_OK;
463}
464
465static int process_sample_line(struct context *inc, char **values)
466{
467 size_t count, idx;
468 struct sample_data_entry *entry;
469 uint64_t mask;
470 long conv_ret;
471 int rc;
472
473 /*
474 * The 'values' array contains '0'/'1' text representation of
475 * wire's values, as well as a (a textual representation of a)
476 * repeat counter for that set of samples.
477 */
478 count = g_strv_length(values);
479 if (count != inc->channel_count + 1)
480 return SR_ERR_DATA;
481 entry = &inc->sample_data_queue[inc->sample_lines_read];
482 entry->bits = 0;
483 mask = 1UL << 0;
484 for (idx = 0; idx < inc->channel_count; idx++, mask <<= 1) {
485 if (strcmp(values[idx], "1") == 0)
486 entry->bits |= mask;
487 if (strcmp(values[idx], "U") == 0)
488 inc->wires_undefined |= mask;
489 }
490 rc = sr_atol(values[inc->channel_count], &conv_ret);
491 if (rc != SR_OK)
492 return rc;
493 entry->repeat = conv_ret;
494 inc->samples_got_uncomp += entry->repeat;
495
496 return SR_OK;
497}
498
499static int process_keyvalue_line(struct context *inc, char *line)
500{
501 char *sep, *key, *arg;
502 char **args;
503 int rc;
504 char *version, *build;
505 long build_num;
506 int wires, samples;
507 size_t alloc_size;
508 double period, dbl_rate;
509 uint64_t int_rate;
510
511 /*
512 * Process lines of the 'SampleData' block. Inspection of the
513 * block got started below in the "regular keyword line" section.
514 * The code here handles the remaining number of lines: Opening
515 * and closing braces, wire names, and sample data sets. Note
516 * that the wire names and sample values are separated by comma,
517 * not by DC1 like other key/value pairs and argument lists.
518 */
519 switch (inc->in_sample_data) {
520 case SAMPLEDATA_OPEN_BRACE:
521 if (strcmp(line, "{") != 0)
522 return SR_ERR_DATA;
523 inc->in_sample_data++;
524 return SR_OK;
525 case SAMPLEDATA_WIRES_COUNT:
526 while (isspace(*line))
527 line++;
528 args = g_strsplit(line, ",", 0);
529 rc = process_wire_names(inc, args);
530 g_strfreev(args);
531 if (rc)
532 return rc;
533 inc->in_sample_data++;
534 inc->sample_lines_read = 0;
535 return SR_OK;
536 case SAMPLEDATA_DATA_LINES:
537 while (isspace(*line))
538 line++;
539 args = g_strsplit(line, ",", 0);
540 rc = process_sample_line(inc, args);
541 g_strfreev(args);
542 if (rc)
543 return rc;
544 inc->sample_lines_read++;
545 if (inc->sample_lines_read == inc->sample_lines_total)
546 inc->in_sample_data++;
547 return SR_OK;
548 case SAMPLEDATA_CLOSE_BRACE:
549 if (strcmp(line, "}") != 0)
550 return SR_ERR_DATA;
551 sr_dbg("'SampleData' done: samples count %" PRIu64 ".",
552 inc->samples_got_uncomp);
553 inc->sample_lines_fed = 0;
554 inc->in_sample_data = SAMPLEDATA_NONE;
555 return SR_OK;
556 case SAMPLEDATA_NONE:
557 /* EMPTY */ /* Fall through to regular keyword-line logic. */
558 break;
559 }
560
561 /* Process regular key/value lines separated by DC1. */
562 key = line;
563 sep = strchr(line, DC1_CHR);
564 if (!sep)
565 return SR_ERR_DATA;
566 *sep++ = '\0';
567 arg = sep;
568 if (strcmp(key, "Version") == 0) {
569 rc = check_vers_line(arg, 0, &version, &build);
570 if (rc == SR_OK) {
571 inc->sw_version = g_strdup(version ? version : "?");
572 rc = sr_atol(build, &build_num);
573 inc->sw_build = build_num;
574 }
575 sr_dbg("'Version' line: version %s, build %zu.",
576 inc->sw_version, inc->sw_build);
577 return rc;
578 }
579 if (strcmp(key, "AcquiredSamplePeriod") == 0) {
580 rc = sr_atod(arg, &period);
581 if (rc != SR_OK)
582 return rc;
583 /*
584 * Implementation detail: The vendor's software provides
585 * 1/2/5 choices in the 1kHz - 500MHz range. Unfortunately
586 * the choice of saving the sample _period_ as a floating
587 * point number in the text file yields inaccurate results
588 * for naive implementations of the conversion (0.1 is an
589 * "odd number" in the computer's internal representation).
590 * The below logic of rounding to integer and then rounding
591 * to full kHz works for the samplerate value's range.
592 * "Simplifying" the implementation will introduce errors.
593 */
594 dbl_rate = 1.0 / period;
595 int_rate = (uint64_t)(dbl_rate + 0.5);
596 int_rate += 500;
597 int_rate /= 1000;
598 int_rate *= 1000;
599 inc->sample_rate = int_rate;
600 if (!inc->sample_rate)
601 return SR_ERR_DATA;
602 sr_dbg("Sample rate: %" PRIu64 ".", inc->sample_rate);
603 return SR_OK;
604 }
605 if (strcmp(key, "AcquiredChannelList") == 0) {
606 args = g_strsplit(arg, DC1_STR, 0);
607 rc = process_enabled_channels(inc, args);
608 g_strfreev(args);
609 if (rc)
610 return rc;
611 sr_dbg("Enabled channels: 0x%" PRIx64 ".",
612 inc->wires_enabled);
613 return SR_OK;
614 }
615 if (strcmp(key, "InvertedChannelList") == 0) {
616 args = g_strsplit(arg, DC1_STR, 0);
617 rc = process_inverted_channels(inc, args);
618 g_strfreev(args);
619 sr_dbg("Inverted channels: 0x%" PRIx64 ".",
620 inc->wires_inverted);
621 return SR_OK;
622 }
623 if (strcmp(key, "Signals") == 0) {
624 args = g_strsplit(arg, DC1_STR, 0);
625 rc = process_signal_names(inc, args);
626 g_strfreev(args);
627 if (rc)
628 return rc;
629 sr_dbg("Got signal names.");
630 return SR_OK;
631 }
632 if (strcmp(key, "SampleData") == 0) {
633 args = g_strsplit(arg, DC1_STR, 3);
634 if (!args || !args[0] || !args[1]) {
635 g_strfreev(args);
636 return SR_ERR_DATA;
637 }
638 rc = sr_atoi(args[0], &wires);
639 if (rc) {
640 g_strfreev(args);
641 return SR_ERR_DATA;
642 }
643 rc = sr_atoi(args[1], &samples);
644 if (rc) {
645 g_strfreev(args);
646 return SR_ERR_DATA;
647 }
648 g_strfreev(args);
649 if (!wires || !samples)
650 return SR_ERR_DATA;
651 inc->channel_count = wires;
652 inc->sample_lines_total = samples;
653 sr_dbg("'SampleData' start: wires %zu, sample lines %zu.",
654 inc->channel_count, inc->sample_lines_total);
655 if (inc->channel_count > MAX_CHANNELS)
656 return SR_ERR_DATA;
657 inc->in_sample_data = SAMPLEDATA_OPEN_BRACE;
658 alloc_size = sizeof(inc->sample_data_queue[0]);
659 alloc_size *= inc->sample_lines_total;
660 inc->sample_data_queue = g_malloc0(alloc_size);
661 if (!inc->sample_data_queue)
662 return SR_ERR_DATA;
663 inc->sample_lines_fed = 0;
664 return SR_OK;
665 }
666 if (strcmp(key, "Group") == 0) {
667 args = g_strsplit(arg, DC1_STR, 0);
668 rc = process_signal_group(inc, args);
669 g_strfreev(args);
670 if (rc)
671 return rc;
672 return SR_OK;
673 }
674 if (strcmp(key, LAST_KEYWORD) == 0) {
675 sr_dbg("'" LAST_KEYWORD "' seen, assuming \"header done\".");
676 inc->got_header = TRUE;
677 return SR_OK;
678 }
679
680 /* Unsupported keyword, silently ignore the line. */
681 return SR_OK;
682}
683
684/* Check for, and isolate another line of text input. */
685static int have_text_line(struct sr_input *in, char **line, char **next)
686{
687 char *sol_ptr, *eol_ptr;
688
689 if (!in || !in->buf || !in->buf->str)
690 return 0;
691 sol_ptr = in->buf->str;
692 eol_ptr = strstr(sol_ptr, CRLF);
693 if (!eol_ptr)
694 return 0;
695 if (line)
696 *line = sol_ptr;
697 *eol_ptr = '\0';
698 eol_ptr += strlen(CRLF);
699 if (next)
700 *next = eol_ptr;
701
702 return 1;
703}
704
705/* Handle line continuation. Have logical lines processed. */
706static int process_text_line(struct context *inc, char *line)
707{
708 char *p;
709 int is_cont_end;
710 int rc;
711
712 /*
713 * Handle line continuation in the input stream. Notice that
714 * continued lines can start and end on the same input line.
715 * The text between the markers can be empty, too.
716 *
717 * Make the result look like a regular line. Put a DC1 delimiter
718 * between the keyword and the right hand side. Strip the /<DC1>
719 * and <DC1>/ "braces". Put CRLF between all continued parts,
720 * this makes the data appear "most intuitive and natural"
721 * should we e.g. pass on user's notes in a future version.
722 */
723 is_cont_end = 0;
724 if (!inc->cont_buff) {
725 p = strstr(line, CONT_OPEN);
726 if (p) {
727 /* Start of continuation. */
728 inc->cont_buff = g_string_new_len(line, p - line + 1);
729 inc->cont_buff->str[inc->cont_buff->len - 1] = DC1_CHR;
730 line = p + strlen(CONT_OPEN);
731 }
732 /* Regular line, fall through to below regular logic. */
733 }
734 if (inc->cont_buff) {
735 p = strstr(line, CONT_CLOSE);
736 is_cont_end = p != NULL;
737 if (is_cont_end)
738 *p = '\0';
739 g_string_append_len(inc->cont_buff, line, strlen(line));
740 if (!is_cont_end) {
741 /* Keep accumulating. */
742 g_string_append_len(inc->cont_buff, CRLF, strlen(CRLF));
743 return SR_OK;
744 }
745 /* End of continuation. */
746 line = inc->cont_buff->str;
747 }
748
749 /*
750 * Process a logical line of input. It either was received from
751 * the caller, or is the result of accumulating continued lines.
752 */
753 rc = process_keyvalue_line(inc, line);
754
755 /* Release the accumulation buffer when a continuation ended. */
756 if (is_cont_end) {
757 g_string_free(inc->cont_buff, TRUE);
758 inc->cont_buff = NULL;
759 }
760
761 return rc;
762}
763
764/* Tell whether received data is sufficient for session feed preparation. */
765static int have_header(GString *buf)
766{
767 const char *assumed_last_key = CRLF LAST_KEYWORD CONT_OPEN;
768
769 if (strstr(buf->str, assumed_last_key))
770 return TRUE;
771
772 return FALSE;
773}
774
775/* Process/inspect previously received input data. Get header parameters. */
776static int parse_header(struct sr_input *in)
777{
778 struct context *inc;
779 char *line, *next;
780 int rc;
781
782 inc = in->priv;
783 while (have_text_line(in, &line, &next)) {
784 rc = process_text_line(inc, line);
785 g_string_erase(in->buf, 0, next - line);
786 if (rc)
787 return rc;
788 }
789
790 return SR_OK;
791}
792
793/* Create sigrok channels and groups. Allocate the session feed buffer. */
794static int create_channels_groups_buffer(struct sr_input *in)
795{
796 struct context *inc;
797 uint64_t mask;
798 size_t idx;
799 const char *name;
800 gboolean enabled;
801 struct sr_channel *ch;
802 struct sr_dev_inst *sdi;
803 GSList *l;
804 struct signal_group_desc *desc;
805 struct sr_channel_group *cg;
806
807 inc = in->priv;
808
809 mask = 1UL << 0;
810 for (idx = 0; idx < inc->channel_count; idx++, mask <<= 1) {
811 name = inc->signal_names[idx];
812 if (!name || !*name)
813 name = inc->wire_names[idx];
814 enabled = (inc->wires_enabled & mask) ? TRUE : FALSE;
815 ch = sr_channel_new(in->sdi, idx,
816 SR_CHANNEL_LOGIC, enabled, name);
817 if (!ch)
818 return SR_ERR_MALLOC;
819 inc->channels = g_slist_append(inc->channels, ch);
820 }
821
822 sdi = in->sdi;
823 for (l = inc->signal_groups; l; l = l->next) {
824 desc = l->data;
825 cg = sr_channel_group_new(desc->name, NULL);
826 if (!cg)
827 return SR_ERR_MALLOC;
828 sdi->channel_groups = g_slist_append(sdi->channel_groups, cg);
829 mask = 1UL << 0;
830 for (idx = 0; idx < inc->channel_count; idx++, mask <<= 1) {
831 if (!(desc->mask & mask))
832 continue;
833 ch = g_slist_nth_data(inc->channels, idx);
834 if (!ch)
835 return SR_ERR_DATA;
836 cg->channels = g_slist_append(cg->channels, ch);
837 }
838 }
839
840 inc->unitsize = (inc->channel_count + 7) / 8;
841 inc->samples_per_chunk = CHUNK_SIZE / inc->unitsize;
842 inc->samples_in_buffer = 0;
843 inc->feed_buffer = g_malloc0(inc->samples_per_chunk * inc->unitsize);
844 if (!inc->feed_buffer)
845 return SR_ERR_MALLOC;
846
847 return SR_OK;
848}
849
850/* Send all accumulated sample data values to the session. */
851static int send_buffer(struct sr_input *in)
852{
853 struct context *inc;
854 struct sr_datafeed_packet packet;
855 struct sr_datafeed_meta meta;
856 struct sr_config *src;
857 struct sr_datafeed_logic logic;
858 int rc;
859
860 inc = in->priv;
861 if (!inc->samples_in_buffer)
862 return SR_OK;
863
864 if (!inc->header_sent) {
865 rc = std_session_send_df_header(in->sdi);
866 if (rc)
867 return rc;
868 inc->header_sent = TRUE;
869 }
870
871 if (inc->sample_rate && !inc->rate_sent) {
872 packet.type = SR_DF_META;
873 packet.payload = &meta;
874 src = sr_config_new(SR_CONF_SAMPLERATE,
875 g_variant_new_uint64(inc->sample_rate));
876 meta.config = g_slist_append(NULL, src);
877 rc = sr_session_send(in->sdi, &packet);
878 g_slist_free(meta.config);
879 sr_config_free(src);
880 if (rc)
881 return rc;
882 inc->rate_sent = TRUE;
883 }
884
885 packet.type = SR_DF_LOGIC;
886 packet.payload = &logic;
887 logic.unitsize = inc->unitsize;
888 logic.data = inc->feed_buffer;
889 logic.length = inc->unitsize * inc->samples_in_buffer;
890 rc = sr_session_send(in->sdi, &packet);
891
892 inc->samples_in_buffer = 0;
893
894 if (rc)
895 return rc;
896
897 return SR_OK;
898}
899
900/*
901 * Add N copies of the current sample to the buffer. Send the buffer to
902 * the session feed when a maximum amount of data was collected.
903 */
904static int add_samples(struct sr_input *in, uint64_t samples, size_t count)
905{
906 struct context *inc;
907 uint8_t sample_buffer[sizeof(uint64_t)];
908 size_t idx;
909 size_t copy_count;
910 uint8_t *p;
911 int rc;
912
913 inc = in->priv;
914 for (idx = 0; idx < inc->unitsize; idx++) {
915 sample_buffer[idx] = samples & 0xff;
916 samples >>= 8;
917 }
918 while (count) {
919 copy_count = inc->samples_per_chunk - inc->samples_in_buffer;
920 if (copy_count > count)
921 copy_count = count;
922 count -= copy_count;
923
924 p = inc->feed_buffer + inc->samples_in_buffer * inc->unitsize;
925 while (copy_count-- > 0) {
926 memcpy(p, sample_buffer, inc->unitsize);
927 p += inc->unitsize;
928 inc->samples_in_buffer++;
929 }
930
931 if (inc->samples_in_buffer == inc->samples_per_chunk) {
932 rc = send_buffer(in);
933 if (rc)
934 return rc;
935 }
936 }
937
938 return SR_OK;
939}
940
941/* Pass on previously received samples to the session. */
942static int process_queued_samples(struct sr_input *in)
943{
944 struct context *inc;
945 struct sample_data_entry *entry;
946 uint64_t sample_bits;
947 int rc;
948
949 inc = in->priv;
950 while (inc->sample_lines_fed < inc->sample_lines_total) {
951 entry = &inc->sample_data_queue[inc->sample_lines_fed++];
952 sample_bits = entry->bits;
953 sample_bits ^= inc->wires_inverted;
954 sample_bits &= inc->wires_enabled;
955 rc = add_samples(in, sample_bits, entry->repeat);
956 if (rc)
957 return rc;
958 }
959
960 return SR_OK;
961}
962
963/*
964 * Create required resources between having read the input file and
965 * sending sample data to the session. Send initial packets before
966 * sample data follows.
967 */
968static int prepare_session_feed(struct sr_input *in)
969{
970 struct context *inc;
971 int rc;
972
973 inc = in->priv;
974 if (inc->ch_feed_prep)
975 return SR_OK;
976
977 /* Got channel names? At least fallbacks? */
978 if (!inc->wire_names[0] || !inc->wire_names[0][0])
979 return SR_ERR_DATA;
980 /* Samples seen? Seen them all? */
981 if (!inc->channel_count)
982 return SR_ERR_DATA;
983 if (!inc->sample_lines_total)
984 return SR_ERR_DATA;
985 if (inc->in_sample_data)
986 return SR_ERR_DATA;
987 if (!inc->sample_data_queue)
988 return SR_ERR_DATA;
989 inc->sample_lines_fed = 0;
990
991 /*
992 * Normalize some variants of input data.
993 * - Let's create a mask for the maximum possible
994 * bit positions, it will be useful to avoid garbage
995 * in other code paths, too.
996 * - Input files _might_ specify which channels were
997 * enabled during acquisition. _Or_ not specify the
998 * enabled channels, but provide 'U' values in some
999 * columns. When neither was seen, assume that all
1000 * channels are enabled.
1001 * - If there are any signal groups, put all signals into
1002 * an anonymous group that are not part of another group.
1003 */
1004 inc->wires_all_mask = 1UL << 0;
1005 inc->wires_all_mask <<= inc->channel_count;
1006 inc->wires_all_mask--;
1007 sr_dbg("all wires mask: 0x%" PRIx64 ".", inc->wires_all_mask);
1008 if (!inc->wires_enabled) {
1009 inc->wires_enabled = ~inc->wires_undefined;
1010 inc->wires_enabled &= ~inc->wires_all_mask;
1011 sr_dbg("enabled from undefined: 0x%" PRIx64 ".",
1012 inc->wires_enabled);
1013 }
1014 if (!inc->wires_enabled) {
1015 inc->wires_enabled = inc->wires_all_mask;
1016 sr_dbg("enabled from total mask: 0x%" PRIx64 ".",
1017 inc->wires_enabled);
1018 }
1019 sr_dbg("enabled mask: 0x%" PRIx64 ".",
1020 inc->wires_enabled);
1021 rc = process_ungrouped_signals(inc);
1022 if (rc)
1023 return rc;
1024
1025 /*
1026 * "Start" the session: Create channels, send the DF
1027 * header to the session. Optionally send the sample
1028 * rate before sample data will be sent.
1029 */
1030 rc = create_channels_groups_buffer(in);
1031 if (rc)
1032 return rc;
1033
1034 inc->ch_feed_prep = TRUE;
1035
1036 return SR_OK;
1037}
1038
1039static int format_match(GHashTable *metadata)
1040{
1041 GString *buf, *tmpbuf;
1042 int rc;
1043 gchar *version, *build;
1044
1045 /* Get a copy of the start of the file's content. */
1046 buf = g_hash_table_lookup(metadata, GINT_TO_POINTER(SR_INPUT_META_HEADER));
1047 if (!buf || !buf->str)
1048 return SR_ERR_ARG;
1049 tmpbuf = g_string_new_len(buf->str, buf->len);
1050 if (!tmpbuf || !tmpbuf->str)
1051 return SR_ERR_MALLOC;
1052
1053 /* See if we can spot a typical first LPF line. */
1054 rc = check_vers_line(tmpbuf->str, 1, &version, &build);
1055 if (rc == SR_OK && version && build) {
1056 sr_dbg("Looks like a LogicProbe project, version %s, build %s.",
1057 version, build);
1058 }
1059 g_string_free(tmpbuf, TRUE);
1060
1061 return rc;
1062}
1063
1064static int init(struct sr_input *in, GHashTable *options)
1065{
1066 struct context *inc;
1067
1068 (void)options;
1069
1070 in->sdi = g_malloc0(sizeof(*in->sdi));
1071
1072 inc = g_malloc0(sizeof(*inc));
1073 if (!inc)
1074 return SR_ERR_MALLOC;
1075 in->priv = inc;
1076
1077 return SR_OK;
1078}
1079
1080static int receive(struct sr_input *in, GString *buf)
1081{
1082 struct context *inc;
1083 int rc;
1084
1085 /* Accumulate another chunk of input data. */
1086 g_string_append_len(in->buf, buf->str, buf->len);
1087
1088 /*
1089 * Wait for the full header's availability, then process it in a
1090 * single call, and set the "ready" flag. Make sure sample data
1091 * and the header get processed in disjoint calls to receive(),
1092 * the backend requires those separate phases.
1093 */
1094 inc = in->priv;
1095 if (!inc->got_header) {
1096 if (!have_header(in->buf))
1097 return SR_OK;
1098 rc = parse_header(in);
1099 if (rc)
1100 return rc;
1101 rc = prepare_session_feed(in);
1102 if (rc)
1103 return rc;
1104 in->sdi_ready = TRUE;
1105 return SR_OK;
1106 }
1107
1108 /* Process sample data, after the header got processed. */
1109 rc = process_queued_samples(in);
1110
1111 return rc;
1112}
1113
1114static int end(struct sr_input *in)
1115{
1116 struct context *inc;
1117 int rc;
1118
1119 /* Nothing to do here if we never started feeding the session. */
1120 if (!in->sdi_ready)
1121 return SR_OK;
1122
1123 /*
1124 * Process sample data that may not have been forwarded before.
1125 * Flush any potentially queued samples.
1126 */
1127 rc = process_queued_samples(in);
1128 if (rc)
1129 return rc;
1130 rc = send_buffer(in);
1131 if (rc)
1132 return rc;
1133
1134 /* End the session feed if one was started. */
1135 inc = in->priv;
1136 if (inc->header_sent) {
1137 rc = std_session_send_df_end(in->sdi);
1138 inc->header_sent = FALSE;
1139 }
1140
1141 return rc;
1142}
1143
1144static void cleanup(struct sr_input *in)
1145{
1146 struct context *inc;
1147 size_t idx;
1148
1149 if (!in)
1150 return;
1151
1152 inc = in->priv;
1153 if (!inc)
1154 return;
1155
1156 /*
1157 * Release potentially allocated resources. Void all references
1158 * and scalars, so that re-runs start out fresh again.
1159 */
1160 g_free(inc->sw_version);
1161 g_string_free(inc->cont_buff, TRUE);
1162 g_free(inc->sample_data_queue);
1163 for (idx = 0; idx < inc->channel_count; idx++)
1164 g_free(inc->wire_names[idx]);
1165 for (idx = 0; idx < inc->channel_count; idx++)
1166 g_free(inc->signal_names[idx]);
1167 g_slist_free_full(inc->signal_groups, sg_free);
1168 g_slist_free_full(inc->channels, g_free);
1169 g_free(inc->feed_buffer);
1170 memset(inc, 0, sizeof(*inc));
1171}
1172
1173static int reset(struct sr_input *in)
1174{
1175 struct context *inc;
1176
1177 inc = in->priv;
1178 cleanup(in);
1179 inc->ch_feed_prep = FALSE;
1180 inc->header_sent = FALSE;
1181 inc->rate_sent = FALSE;
1182 g_string_truncate(in->buf, 0);
1183
1184 return SR_OK;
1185}
1186
1187static struct sr_option options[] = {
1188 ALL_ZERO,
1189};
1190
1191static const struct sr_option *get_options(void)
1192{
1193 return options;
1194}
1195
1196SR_PRIV struct sr_input_module input_logicport = {
1197 .id = "logicport",
1198 .name = "LogicPort File",
1199 .desc = "Intronix LA1034 LogicPort project",
1200 .exts = (const char *[]){ "lpf", NULL },
1201 .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
1202 .options = get_options,
1203 .format_match = format_match,
1204 .init = init,
1205 .receive = receive,
1206 .end = end,
1207 .cleanup = cleanup,
1208 .reset = reset,
1209};