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