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