]> sigrok.org Git - libsigrok.git/blob - src/input/csv.c
17c253a29d2f29aff5c3cabc6397da1d1fbfecc0
[libsigrok.git] / src / input / csv.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 Marc Schink <sigrok-dev@marcschink.de>
5  * Copyright (C) 2019 Gerhard Sittig <gerhard.sittig@gmx.net>
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "config.h"
22
23 #include <glib.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include <libsigrok/libsigrok.h>
28 #include "libsigrok-internal.h"
29 #include "scpi.h"       /* String un-quote for channel name from header line. */
30
31 #define LOG_PREFIX "input/csv"
32
33 #define CHUNK_SIZE      (4 * 1024 * 1024)
34
35 /*
36  * The CSV input module has the following options:
37  *
38  * single-column: Specifies the column number which stores the sample data for
39  *                single column mode and enables single column mode. Multi
40  *                column mode is used if this parameter is omitted.
41  *
42  * numchannels:   Specifies the number of channels to use. In multi column mode
43  *                the number of channels are the number of columns and in single
44  *                column mode the number of bits (LSB first) beginning at
45  *                'first-channel'.
46  *
47  * delimiter:     Specifies the delimiter for columns. Must be at least one
48  *                character. Comma is used as default delimiter.
49  *
50  * format:        Specifies the format of the sample data in single column mode.
51  *                Available formats are: 'bin', 'hex' and 'oct'. The binary
52  *                format is used by default. This option has no effect in multi
53  *                column mode.
54  *
55  * comment:       Specifies the prefix character(s) for comments. No prefix
56  *                characters are used by default which disables removing of
57  *                comments.
58  *
59  * samplerate:    Samplerate which the sample data was captured with. Default
60  *                value is 0.
61  *
62  * first-channel: Column number of the first channel in multi column mode and
63  *                position of the bit for the first channel in single column mode.
64  *                Default value is 0.
65  *
66  * header:        Determines if the first line should be treated as header
67  *                and used for channel names in multi column mode. Empty header
68  *                names will be replaced by the channel number. If enabled in
69  *                single column mode the first line will be skipped. Usage of
70  *                header is disabled by default.
71  *
72  * startline:     Line number to start processing sample data. Must be greater
73  *                than 0. The default line number to start processing is 1.
74  */
75
76 /*
77  * TODO
78  *
79  * - Determine how the text line handling can get improved, regarding
80  *   all of robustness and flexibility and correctness.
81  *   - The current implementation splits on "any run of CR and LF". Which
82  *     translates to: Line numbers are wrong in the presence of empty
83  *     lines in the input stream. See below for an (expensive) fix.
84  *   - Dropping support for CR style end-of-line markers could improve
85  *     the situation a lot. Code could search for and split on LF, and
86  *     trim optional trailing CR. This would result in proper support
87  *     for CRLF (Windows) as well as LF (Unix), and allow for correct
88  *     line number counts.
89  *   - When support for CR-only line termination cannot get dropped,
90  *     then the current implementation is inappropriate. Currently the
91  *     input stream is scanned for the first occurance of either of the
92  *     supported termination styles (which is good). For the remaining
93  *     session a consistent encoding of the text lines is assumed (which
94  *     is acceptable).
95  *   - When line numbers need to be correct and reliable, _and_ the full
96  *     set of previously supported line termination sequences are required,
97  *     and potentially more are to get added for improved compatibility
98  *     with more platforms or generators, then the current approach of
99  *     splitting on runs of termination characters needs to get replaced,
100  *     by the more expensive approach to scan for and count the initially
101  *     determined termination sequence.
102  *
103  * - Add support for analog input data? (optional)
104  *   - Needs a syntax first for user specs which channels (columns) are
105  *     logic and which are analog. May need heuristics(?) to guess from
106  *     input data in the absence of user provided specs.
107  */
108
109 /* Single column formats. */
110 enum single_col_format {
111         FORMAT_NONE,    /* Ignore this column. */
112         FORMAT_BIN,     /* Bin digits for a set of bits (or just one bit). */
113         FORMAT_HEX,     /* Hex digits for a set of bits. */
114         FORMAT_OCT,     /* Oct digits for a set of bits. */
115 };
116
117 static const char *col_format_text[] = {
118         [FORMAT_NONE] = "unknown",
119         [FORMAT_BIN] = "binary",
120         [FORMAT_HEX] = "hexadecimal",
121         [FORMAT_OCT] = "octal",
122 };
123
124 struct column_details {
125         size_t col_nr;
126         enum single_col_format text_format;
127         size_t channel_offset;
128         size_t channel_count;
129 };
130
131 struct context {
132         gboolean started;
133
134         /* Current selected samplerate. */
135         uint64_t samplerate;
136         gboolean samplerate_sent;
137
138         /* Number of channels. */
139         size_t num_channels;
140
141         /* Column delimiter character(s). */
142         GString *delimiter;
143
144         /* Comment prefix character(s). */
145         GString *comment;
146
147         /* Termination character(s) used in current stream. */
148         char *termination;
149
150         /* Determines if sample data is stored in multiple columns. */
151         gboolean multi_column_mode;
152
153         /* Parameters how to process the columns. */
154         size_t column_want_count;
155         struct column_details *column_details;
156
157         /* Column number of the sample data in single column mode. */
158         size_t single_column;
159
160         /* Column number of the first channel. */
161         size_t first_column;
162
163         /* Line number to start processing. */
164         size_t start_line;
165
166         /*
167          * Determines if the first line should be treated as header and used for
168          * channel names in multi column mode.
169          */
170         gboolean use_header;
171         gboolean header_seen;
172
173         /* Format sample data is stored in single column mode. */
174         enum single_col_format format;
175
176         size_t sample_unit_size;        /**!< Byte count for a single sample. */
177         uint8_t *sample_buffer;         /**!< Buffer for a single sample. */
178
179         uint8_t *datafeed_buffer;       /**!< Queue for datafeed submission. */
180         size_t datafeed_buf_size;
181         size_t datafeed_buf_fill;
182
183         /* Current line number. */
184         size_t line_number;
185
186         /* List of previously created sigrok channels. */
187         GSList *prev_sr_channels;
188 };
189
190 /*
191  * Primitive operations to handle sample sets:
192  * - Keep a buffer for datafeed submission, capable of holding many
193  *   samples (reduces call overhead, improves throughput).
194  * - Have a "current sample set" pointer reference one position in that
195  *   large samples buffer.
196  * - Clear the current sample set before text line inspection, then set
197  *   the bits which are found active in the current line of text input.
198  *   Phrase the API such that call sites can be kept simple. Advance to
199  *   the next sample set between lines, flush the larger buffer as needed
200  *   (when it is full, or upon EOF).
201  */
202
203 static void clear_logic_samples(struct context *inc)
204 {
205         inc->sample_buffer = &inc->datafeed_buffer[inc->datafeed_buf_fill];
206         memset(inc->sample_buffer, 0, inc->sample_unit_size);
207 }
208
209 static void set_logic_level(struct context *inc, size_t ch_idx, int on)
210 {
211         size_t byte_idx, bit_idx;
212         uint8_t bit_mask;
213
214         if (ch_idx >= inc->num_channels)
215                 return;
216         if (!on)
217                 return;
218
219         byte_idx = ch_idx / 8;
220         bit_idx = ch_idx % 8;
221         bit_mask = 1 << bit_idx;
222         inc->sample_buffer[byte_idx] |= bit_mask;
223 }
224
225 static int flush_logic_samples(const struct sr_input *in)
226 {
227         struct context *inc;
228         struct sr_datafeed_packet packet;
229         struct sr_datafeed_meta meta;
230         struct sr_config *src;
231         uint64_t samplerate;
232         struct sr_datafeed_logic logic;
233         int rc;
234
235         inc = in->priv;
236         if (!inc->datafeed_buf_fill)
237                 return SR_OK;
238
239         if (inc->samplerate && !inc->samplerate_sent) {
240                 packet.type = SR_DF_META;
241                 packet.payload = &meta;
242                 samplerate = inc->samplerate;
243                 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
244                 meta.config = g_slist_append(NULL, src);
245                 sr_session_send(in->sdi, &packet);
246                 g_slist_free(meta.config);
247                 sr_config_free(src);
248                 inc->samplerate_sent = TRUE;
249         }
250
251         memset(&packet, 0, sizeof(packet));
252         memset(&logic, 0, sizeof(logic));
253         packet.type = SR_DF_LOGIC;
254         packet.payload = &logic;
255         logic.unitsize = inc->sample_unit_size;
256         logic.length = inc->datafeed_buf_fill;
257         logic.data = inc->datafeed_buffer;
258
259         rc = sr_session_send(in->sdi, &packet);
260         if (rc != SR_OK)
261                 return rc;
262
263         inc->datafeed_buf_fill = 0;
264         return SR_OK;
265 }
266
267 static int queue_logic_samples(const struct sr_input *in)
268 {
269         struct context *inc;
270         int rc;
271
272         inc = in->priv;
273
274         inc->datafeed_buf_fill += inc->sample_unit_size;
275         if (inc->datafeed_buf_fill == inc->datafeed_buf_size) {
276                 rc = flush_logic_samples(in);
277                 if (rc != SR_OK)
278                         return rc;
279         }
280         return SR_OK;
281 }
282
283 static int make_column_details_single(struct context *inc,
284         size_t col_nr, size_t bit_count, enum single_col_format format)
285 {
286         struct column_details *details;
287
288         /*
289          * Need at least as many columns to also include the one with
290          * the single-column input data.
291          */
292         inc->column_want_count = col_nr;
293
294         /*
295          * Allocate the columns' processing details. Columns are counted
296          * from 1 (user's perspective), array items from 0 (programmer's
297          * perspective).
298          */
299         inc->column_details = g_malloc0_n(col_nr, sizeof(inc->column_details[0]));
300         details = &inc->column_details[col_nr - 1];
301         details->col_nr = col_nr;
302
303         /*
304          * In single-column mode this single column will hold all bits
305          * of all logic channels, in the user specified number format.
306          */
307         details->text_format = format;
308         details->channel_offset = 0;
309         details->channel_count = bit_count;
310
311         return SR_OK;
312 }
313
314 static int make_column_details_multi(struct context *inc,
315         size_t first_col, size_t last_col)
316 {
317         struct column_details *details;
318         size_t col_nr;
319
320         /*
321          * Need at least as many columns to also include the one with
322          * the last channel's data.
323          */
324         inc->column_want_count = last_col;
325
326         /*
327          * Allocate the columns' processing details. Columns are counted
328          * from 1, array items from 0.
329          * In multi-column mode each column will hold a single bit for
330          * the respective channel.
331          */
332         inc->column_details = g_malloc0_n(last_col, sizeof(inc->column_details[0]));
333         for (col_nr = first_col; col_nr <= last_col; col_nr++) {
334                 details = &inc->column_details[col_nr - 1];
335                 details->col_nr = col_nr;
336                 details->text_format = FORMAT_BIN;
337                 details->channel_offset = col_nr - first_col;
338                 details->channel_count = 1;
339         }
340
341
342         return SR_OK;
343 }
344
345 static const struct column_details *lookup_column_details(struct context *inc, size_t nr)
346 {
347         if (!inc || !inc->column_details)
348                 return NULL;
349         if (!nr || nr > inc->column_want_count)
350                 return NULL;
351         return &inc->column_details[nr - 1];
352 }
353
354 /*
355  * Primitive operations for text input: Strip comments off text lines.
356  * Split text lines into columns. Process input text for individual
357  * columns.
358  */
359
360 static void strip_comment(char *buf, const GString *prefix)
361 {
362         char *ptr;
363
364         if (!prefix->len)
365                 return;
366
367         if ((ptr = strstr(buf, prefix->str))) {
368                 *ptr = '\0';
369                 g_strstrip(buf);
370         }
371 }
372
373 /**
374  * @brief Splits a text line into a set of columns.
375  *
376  * @param[in] buf       The input text line to split.
377  * @param[in] inc       The input module's context.
378  *
379  * @returns An array of strings, representing the columns' text.
380  *
381  * This routine splits a text line on previously determined separators.
382  */
383 static char **split_line(char *buf, struct context *inc)
384 {
385         return g_strsplit(buf, inc->delimiter->str, 0);
386 }
387
388 /**
389  * @brief Parse a multi-bit field into several logic channels.
390  *
391  * @param[in] column    The input text, a run of bin/hex/oct digits.
392  * @param[in] inc       The input module's context.
393  * @param[in] col_nr    The involved column number (1-based).
394  *
395  * @retval SR_OK        Success.
396  * @retval SR_ERR       Invalid input data (empty, or format error).
397  *
398  * This routine modifies the logic levels in the current sample set,
399  * based on the text input and a user provided format spec.
400  */
401 static int parse_column(const char *column, struct context *inc, size_t col_nr)
402 {
403         const struct column_details *col_det;
404         size_t length, ch_rem, ch_idx, ch_inc;
405         const char *rdptr;
406         char c;
407         gboolean valid;
408         const char *type_text;
409         uint8_t bits;
410
411         /* See whether and how the columns needs to get processed. */
412         col_det = lookup_column_details(inc, col_nr);
413         if (!col_det) {
414                 sr_dbg("Column %zu in line %zu without processing details?",
415                         col_nr, inc->line_number);
416                 return SR_ERR;
417         }
418         if (col_det->text_format == FORMAT_NONE)
419                 return SR_OK;
420
421         /*
422          * Prepare to read the digits from the text end towards the start.
423          * A digit corresponds to a variable number of channels (depending
424          * on the value's radix). Prepare the mapping of text digits to
425          * (a number of) logic channels.
426          */
427         length = strlen(column);
428         if (!length) {
429                 sr_err("Column %zu in line %zu is empty.", col_nr,
430                         inc->line_number);
431                 return SR_ERR;
432         }
433         rdptr = &column[length];
434         ch_idx = col_det->channel_offset;
435         ch_rem = col_det->channel_count;
436
437         /*
438          * Get another digit and derive up to four logic channels' state from
439          * it. Make sure to not process more bits than the column has channels
440          * associated with it.
441          */
442         while (rdptr > column && ch_rem) {
443                 /* Check for valid digits according to the input radix. */
444                 c = *(--rdptr);
445                 switch (inc->format) {
446                 case FORMAT_BIN:
447                         valid = g_ascii_isxdigit(c) && c < '2';
448                         ch_inc = 1;
449                         break;
450                 case FORMAT_OCT:
451                         valid = g_ascii_isxdigit(c) && c < '8';
452                         ch_inc = 3;
453                         break;
454                 case FORMAT_HEX:
455                         valid = g_ascii_isxdigit(c);
456                         ch_inc = 4;
457                         break;
458                 default:
459                         valid = FALSE;
460                         break;
461                 }
462                 if (!valid) {
463                         type_text = col_format_text[inc->format];
464                         sr_err("Invalid text '%s' in %s type column %zu in line %zu.",
465                                 column, type_text, col_nr, inc->line_number);
466                         return SR_ERR;
467                 }
468                 /* Use the digit's bits for logic channels' data. */
469                 bits = g_ascii_xdigit_value(c);
470                 switch (inc->format) {
471                 case FORMAT_NONE:
472                         /* ShouldNotHappen(TM), but silences compiler warning. */
473                         return SR_ERR;
474                 case FORMAT_HEX:
475                         if (ch_rem >= 4) {
476                                 ch_rem--;
477                                 set_logic_level(inc, ch_idx + 3, bits & (1 << 3));
478                         }
479                         /* FALLTHROUGH */
480                 case FORMAT_OCT:
481                         if (ch_rem >= 3) {
482                                 ch_rem--;
483                                 set_logic_level(inc, ch_idx + 2, bits & (1 << 2));
484                         }
485                         if (ch_rem >= 2) {
486                                 ch_rem--;
487                                 set_logic_level(inc, ch_idx + 1, bits & (1 << 1));
488                         }
489                         /* FALLTHROUGH */
490                 case FORMAT_BIN:
491                         ch_rem--;
492                         set_logic_level(inc, ch_idx + 0, bits & (1 << 0));
493                         break;
494                 }
495                 ch_idx += ch_inc;
496         }
497         /*
498          * TODO Determine whether the availability of extra input data
499          * for unhandled logic channels is worth warning here. In this
500          * implementation users are in control, and can have the more
501          * significant bits ignored (which can be considered a feature
502          * and not really a limitation).
503          */
504
505         return SR_OK;
506 }
507
508 static int init(struct sr_input *in, GHashTable *options)
509 {
510         struct context *inc;
511         const char *s;
512         int ret;
513
514         in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
515         in->priv = inc = g_malloc0(sizeof(struct context));
516
517         inc->single_column = g_variant_get_uint32(g_hash_table_lookup(options, "single-column"));
518         inc->multi_column_mode = inc->single_column == 0;
519
520         inc->num_channels = g_variant_get_uint32(g_hash_table_lookup(options, "numchannels"));
521
522         inc->delimiter = g_string_new(g_variant_get_string(
523                         g_hash_table_lookup(options, "delimiter"), NULL));
524         if (inc->delimiter->len == 0) {
525                 sr_err("Column delimiter cannot be empty.");
526                 return SR_ERR_ARG;
527         }
528
529         s = g_variant_get_string(g_hash_table_lookup(options, "format"), NULL);
530         if (!g_ascii_strncasecmp(s, "bin", 3)) {
531                 inc->format = FORMAT_BIN;
532         } else if (!g_ascii_strncasecmp(s, "hex", 3)) {
533                 inc->format = FORMAT_HEX;
534         } else if (!g_ascii_strncasecmp(s, "oct", 3)) {
535                 inc->format = FORMAT_OCT;
536         } else {
537                 sr_err("Invalid format: '%s'", s);
538                 return SR_ERR_ARG;
539         }
540
541         inc->comment = g_string_new(g_variant_get_string(
542                         g_hash_table_lookup(options, "comment"), NULL));
543         if (g_string_equal(inc->comment, inc->delimiter)) {
544                 /*
545                  * Using the same sequence as comment leader and column
546                  * delimiter won't work. The user probably specified ';'
547                  * as the column delimiter but did not adjust the comment
548                  * leader. Try DWIM, drop comment strippin support here.
549                  */
550                 sr_warn("Comment leader and column delimiter conflict, disabling comment support.");
551                 g_string_truncate(inc->comment, 0);
552         }
553
554         inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
555
556         inc->first_column = g_variant_get_uint32(g_hash_table_lookup(options, "first-column"));
557
558         inc->use_header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
559
560         inc->start_line = g_variant_get_uint32(g_hash_table_lookup(options, "startline"));
561         if (inc->start_line < 1) {
562                 sr_err("Invalid start line %zu.", inc->start_line);
563                 return SR_ERR_ARG;
564         }
565
566         /*
567          * Derive the set of columns to inspect and their respective
568          * formats from simple input specs. Remain close to the previous
569          * set of option keywords and their meaning. Exclusively support
570          * a single column with multiple bits in it, or an adjacent set
571          * of colums with one bit each. The latter may not know the total
572          * column count here (when the user omitted the spec), and will
573          * derive it from the first text line of the input file.
574          */
575         if (inc->single_column && inc->num_channels) {
576                 sr_dbg("DIAG Got single column (%zu) and channels (%zu).",
577                         inc->single_column, inc->num_channels);
578                 sr_dbg("DIAG -> column %zu, %zu bits in %s format.",
579                         inc->single_column, inc->num_channels,
580                         col_format_text[inc->format]);
581                 ret = make_column_details_single(inc,
582                         inc->single_column, inc->num_channels, inc->format);
583                 if (ret != SR_OK)
584                         return ret;
585         } else if (inc->multi_column_mode) {
586                 sr_dbg("DIAG Got multi-column, first column %zu, count %zu.",
587                         inc->first_column, inc->num_channels);
588                 if (inc->num_channels) {
589                         sr_dbg("DIAG -> columns %zu-%zu, 1 bit each.",
590                                 inc->first_column,
591                                 inc->first_column + inc->num_channels - 1);
592                         ret = make_column_details_multi(inc, inc->first_column,
593                                 inc->first_column + inc->num_channels - 1);
594                         if (ret != SR_OK)
595                                 return ret;
596                 } else {
597                         sr_dbg("DIAG -> incomplete spec, have to update later.");
598                 }
599         } else {
600                 sr_err("Unknown or unsupported combination of option values.");
601                 return SR_ERR_ARG;
602         }
603
604         return SR_OK;
605 }
606
607 /*
608  * Check the channel list for consistency across file re-import. See
609  * the VCD input module for more details and motivation.
610  */
611
612 static void keep_header_for_reread(const struct sr_input *in)
613 {
614         struct context *inc;
615
616         inc = in->priv;
617         g_slist_free_full(inc->prev_sr_channels, sr_channel_free_cb);
618         inc->prev_sr_channels = in->sdi->channels;
619         in->sdi->channels = NULL;
620 }
621
622 static int check_header_in_reread(const struct sr_input *in)
623 {
624         struct context *inc;
625
626         if (!in)
627                 return FALSE;
628         inc = in->priv;
629         if (!inc)
630                 return FALSE;
631         if (!inc->prev_sr_channels)
632                 return TRUE;
633
634         if (sr_channel_lists_differ(inc->prev_sr_channels, in->sdi->channels)) {
635                 sr_err("Channel list change not supported for file re-read.");
636                 return FALSE;
637         }
638         g_slist_free_full(in->sdi->channels, sr_channel_free_cb);
639         in->sdi->channels = inc->prev_sr_channels;
640         inc->prev_sr_channels = NULL;
641
642         return TRUE;
643 }
644
645 static const char *delim_set = "\r\n";
646
647 static const char *get_line_termination(GString *buf)
648 {
649         const char *term;
650
651         term = NULL;
652         if (g_strstr_len(buf->str, buf->len, "\r\n"))
653                 term = "\r\n";
654         else if (memchr(buf->str, '\n', buf->len))
655                 term = "\n";
656         else if (memchr(buf->str, '\r', buf->len))
657                 term = "\r";
658
659         return term;
660 }
661
662 static int initial_parse(const struct sr_input *in, GString *buf)
663 {
664         struct context *inc;
665         GString *channel_name;
666         size_t num_columns, ch_idx, ch_name_idx, col_idx, col_nr;
667         size_t line_number, line_idx;
668         int ret;
669         char **lines, *line, **columns, *column;
670         const char *col_caption;
671         gboolean got_caption;
672         const struct column_details *detail;
673
674         ret = SR_OK;
675         inc = in->priv;
676         columns = NULL;
677
678         line_number = 0;
679         lines = g_strsplit_set(buf->str, delim_set, 0);
680         for (line_idx = 0; (line = lines[line_idx]); line_idx++) {
681                 line_number++;
682                 if (inc->start_line > line_number) {
683                         sr_spew("Line %zu skipped (before start).", line_number);
684                         continue;
685                 }
686                 if (line[0] == '\0') {
687                         sr_spew("Blank line %zu skipped.", line_number);
688                         continue;
689                 }
690                 strip_comment(line, inc->comment);
691                 if (line[0] == '\0') {
692                         sr_spew("Comment-only line %zu skipped.", line_number);
693                         continue;
694                 }
695
696                 /* Reached first proper line. */
697                 break;
698         }
699         if (!line) {
700                 /* Not enough data for a proper line yet. */
701                 ret = SR_ERR_NA;
702                 goto out;
703         }
704
705         /* See how many columns the current line has. */
706         columns = split_line(line, inc);
707         if (!columns) {
708                 sr_err("Error while parsing line %zu.", line_number);
709                 ret = SR_ERR;
710                 goto out;
711         }
712         num_columns = g_strv_length(columns);
713         if (!num_columns) {
714                 sr_err("Error while parsing line %zu.", line_number);
715                 ret = SR_ERR;
716                 goto out;
717         }
718         sr_dbg("DIAG Got %zu columns in text line: %s.", num_columns, line);
719
720         /* Optionally update incomplete multi-column specs. */
721         if (inc->multi_column_mode && !inc->num_channels) {
722                 inc->num_channels = num_columns - inc->first_column + 1;
723                 sr_dbg("DIAG -> multi-column update: columns %zu-%zu, 1 bit each.",
724                         inc->first_column,
725                         inc->first_column + inc->num_channels - 1);
726                 ret = make_column_details_multi(inc, inc->first_column,
727                         inc->first_column + inc->num_channels - 1);
728                 if (ret != SR_OK)
729                         goto out;
730         }
731
732         /*
733          * Assume all lines have equal length (column count). Bail out
734          * early on suspicious or insufficient input data (check input
735          * which became available here against previous user specs or
736          * auto-determined properties, regardless of layout variant).
737          */
738         if (num_columns < inc->column_want_count) {
739                 sr_err("Insufficient input text width for desired data amount, got %zu but want %zu columns.",
740                         num_columns, inc->column_want_count);
741                 ret = SR_ERR;
742                 goto out;
743         }
744
745         /*
746          * Determine channel names. Optionally use text from a header
747          * line (when requested by the user, and only works in multi
748          * column mode). In the absence of header text, or in single
749          * column mode, channels are assigned rather generic names.
750          *
751          * Manipulation of the column's caption is acceptable here, the
752          * header line will never get processed another time.
753          */
754         channel_name = g_string_sized_new(64);
755         for (col_idx = 0; col_idx < inc->column_want_count; col_idx++) {
756
757                 col_nr = col_idx + 1;
758                 detail = lookup_column_details(inc, col_nr);
759                 if (detail->text_format == FORMAT_NONE)
760                         continue;
761                 column = columns[col_idx];
762                 col_caption = sr_scpi_unquote_string(column);
763                 got_caption = inc->use_header && *col_caption;
764                 sr_dbg("DIAG col %zu, ch count %zu, text %s.",
765                         col_nr, detail->channel_count, col_caption);
766                 for (ch_idx = 0; ch_idx < detail->channel_count; ch_idx++) {
767                         ch_name_idx = detail->channel_offset + ch_idx;
768                         if (got_caption && detail->channel_count == 1)
769                                 g_string_assign(channel_name, col_caption);
770                         else if (got_caption)
771                                 g_string_printf(channel_name, "%s[%zu]",
772                                         col_caption, ch_idx);
773                         else
774                                 g_string_printf(channel_name, "%zu", ch_name_idx);
775                         sr_dbg("DIAG ch idx %zu, name %s.", ch_name_idx, channel_name->str);
776                         sr_channel_new(in->sdi, ch_name_idx, SR_CHANNEL_LOGIC, TRUE,
777                                 channel_name->str);
778                 }
779         }
780         g_string_free(channel_name, TRUE);
781         if (!check_header_in_reread(in)) {
782                 ret = SR_ERR_DATA;
783                 goto out;
784         }
785
786         /*
787          * Calculate the minimum buffer size to store the set of samples
788          * of all channels (unit size). Determine a larger buffer size
789          * for datafeed submission that is a multiple of the unit size.
790          * Allocate the larger buffer, the "sample buffer" will point
791          * to a location within that large buffer later.
792          */
793         inc->sample_unit_size = (inc->num_channels + 7) / 8;
794         inc->datafeed_buf_size = CHUNK_SIZE;
795         inc->datafeed_buf_size *= inc->sample_unit_size;
796         inc->datafeed_buffer = g_malloc(inc->datafeed_buf_size);
797         inc->datafeed_buf_fill = 0;
798
799 out:
800         if (columns)
801                 g_strfreev(columns);
802         g_strfreev(lines);
803
804         return ret;
805 }
806
807 /*
808  * Gets called from initial_receive(), which runs until the end-of-line
809  * encoding of the input stream could get determined. Assumes that this
810  * routine receives enough buffered initial input data to either see the
811  * BOM when there is one, or that no BOM will follow when a text line
812  * termination sequence was seen. Silently drops the UTF-8 BOM sequence
813  * from the input buffer if one was seen. Does not care to protect
814  * against multiple execution or dropping the BOM multiple times --
815  * there should be at most one in the input stream.
816  */
817 static void initial_bom_check(const struct sr_input *in)
818 {
819         static const char *utf8_bom = "\xef\xbb\xbf";
820
821         if (in->buf->len < strlen(utf8_bom))
822                 return;
823         if (strncmp(in->buf->str, utf8_bom, strlen(utf8_bom)) != 0)
824                 return;
825         g_string_erase(in->buf, 0, strlen(utf8_bom));
826 }
827
828 static int initial_receive(const struct sr_input *in)
829 {
830         struct context *inc;
831         GString *new_buf;
832         int len, ret;
833         char *p;
834         const char *termination;
835
836         initial_bom_check(in);
837
838         inc = in->priv;
839
840         termination = get_line_termination(in->buf);
841         if (!termination)
842                 /* Don't have a full line yet. */
843                 return SR_ERR_NA;
844
845         p = g_strrstr_len(in->buf->str, in->buf->len, termination);
846         if (!p)
847                 /* Don't have a full line yet. */
848                 return SR_ERR_NA;
849         len = p - in->buf->str - 1;
850         new_buf = g_string_new_len(in->buf->str, len);
851         g_string_append_c(new_buf, '\0');
852
853         inc->termination = g_strdup(termination);
854
855         if (in->buf->str[0] != '\0')
856                 ret = initial_parse(in, new_buf);
857         else
858                 ret = SR_OK;
859
860         g_string_free(new_buf, TRUE);
861
862         return ret;
863 }
864
865 static int process_buffer(struct sr_input *in, gboolean is_eof)
866 {
867         struct context *inc;
868         gsize num_columns;
869         size_t line_idx, col_idx, col_nr;
870         int ret;
871         char *p, **lines, *line, **columns, *column;
872
873         inc = in->priv;
874         if (!inc->started) {
875                 std_session_send_df_header(in->sdi);
876                 inc->started = TRUE;
877         }
878
879         /*
880          * Consider empty input non-fatal. Keep accumulating input until
881          * at least one full text line has become available. Grab the
882          * maximum amount of accumulated data that consists of full text
883          * lines, and process what has been received so far, leaving not
884          * yet complete lines for the next invocation.
885          *
886          * Enforce that all previously buffered data gets processed in
887          * the "EOF" condition. Do not insist in the presence of the
888          * termination sequence for the last line (may often be missing
889          * on Windows). A present termination sequence will just result
890          * in the "execution of an empty line", and does not harm.
891          */
892         if (!in->buf->len)
893                 return SR_OK;
894         if (is_eof) {
895                 p = in->buf->str + in->buf->len;
896         } else {
897                 p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination);
898                 if (!p)
899                         return SR_ERR;
900                 *p = '\0';
901                 p += strlen(inc->termination);
902         }
903         g_strstrip(in->buf->str);
904
905         ret = SR_OK;
906         lines = g_strsplit_set(in->buf->str, delim_set, 0);
907         for (line_idx = 0; (line = lines[line_idx]); line_idx++) {
908                 inc->line_number++;
909                 if (line[0] == '\0') {
910                         sr_spew("Blank line %zu skipped.", inc->line_number);
911                         continue;
912                 }
913
914                 /* Remove trailing comment. */
915                 strip_comment(line, inc->comment);
916                 if (line[0] == '\0') {
917                         sr_spew("Comment-only line %zu skipped.", inc->line_number);
918                         continue;
919                 }
920
921                 /* Skip the header line, its content was used as the channel names. */
922                 if (inc->use_header && !inc->header_seen) {
923                         sr_spew("Header line %zu skipped.", inc->line_number);
924                         inc->header_seen = TRUE;
925                         continue;
926                 }
927
928                 /* Split the line into columns, check for minimum length. */
929                 columns = split_line(line, inc);
930                 if (!columns) {
931                         sr_err("Error while parsing line %zu.", inc->line_number);
932                         g_strfreev(lines);
933                         return SR_ERR;
934                 }
935                 num_columns = g_strv_length(columns);
936                 if (num_columns < inc->column_want_count) {
937                         sr_err("Insufficient column count %zu in line %zu.",
938                                 num_columns, inc->line_number);
939                         g_strfreev(columns);
940                         g_strfreev(lines);
941                         return SR_ERR;
942                 }
943
944                 clear_logic_samples(inc);
945
946                 for (col_idx = 0; col_idx < inc->column_want_count; col_idx++) {
947                         column = columns[col_idx];
948                         col_nr = col_idx + 1;
949                         ret = parse_column(column, inc, col_nr);
950                         if (ret != SR_OK) {
951                                 g_strfreev(columns);
952                                 g_strfreev(lines);
953                                 return SR_ERR;
954                         }
955                 }
956
957                 /* Send sample data to the session bus (buffered). */
958                 ret = queue_logic_samples(in);
959                 if (ret != SR_OK) {
960                         sr_err("Sending samples failed.");
961                         g_strfreev(columns);
962                         g_strfreev(lines);
963                         return SR_ERR;
964                 }
965
966                 g_strfreev(columns);
967         }
968         g_strfreev(lines);
969         g_string_erase(in->buf, 0, p - in->buf->str);
970
971         return ret;
972 }
973
974 static int receive(struct sr_input *in, GString *buf)
975 {
976         struct context *inc;
977         int ret;
978
979         g_string_append_len(in->buf, buf->str, buf->len);
980
981         inc = in->priv;
982         if (!inc->termination) {
983                 ret = initial_receive(in);
984                 if (ret == SR_ERR_NA)
985                         /* Not enough data yet. */
986                         return SR_OK;
987                 else if (ret != SR_OK)
988                         return SR_ERR;
989
990                 /* sdi is ready, notify frontend. */
991                 in->sdi_ready = TRUE;
992                 return SR_OK;
993         }
994
995         ret = process_buffer(in, FALSE);
996
997         return ret;
998 }
999
1000 static int end(struct sr_input *in)
1001 {
1002         struct context *inc;
1003         int ret;
1004
1005         if (in->sdi_ready)
1006                 ret = process_buffer(in, TRUE);
1007         else
1008                 ret = SR_OK;
1009         if (ret != SR_OK)
1010                 return ret;
1011
1012         ret = flush_logic_samples(in);
1013         if (ret != SR_OK)
1014                 return ret;
1015
1016         inc = in->priv;
1017         if (inc->started)
1018                 std_session_send_df_end(in->sdi);
1019
1020         return ret;
1021 }
1022
1023 static void cleanup(struct sr_input *in)
1024 {
1025         struct context *inc;
1026
1027         keep_header_for_reread(in);
1028
1029         inc = in->priv;
1030
1031         g_free(inc->termination);
1032         inc->termination = NULL;
1033         g_free(inc->datafeed_buffer);
1034         inc->datafeed_buffer = NULL;
1035 }
1036
1037 static int reset(struct sr_input *in)
1038 {
1039         struct context *inc = in->priv;
1040
1041         cleanup(in);
1042         inc->started = FALSE;
1043         g_string_truncate(in->buf, 0);
1044
1045         return SR_OK;
1046 }
1047
1048 enum option_index {
1049         OPT_SINGLE_COL,
1050         OPT_NUM_LOGIC,
1051         OPT_DELIM,
1052         OPT_FORMAT,
1053         OPT_COMMENT,
1054         OPT_RATE,
1055         OPT_FIRST_COL,
1056         OPT_HEADER,
1057         OPT_START,
1058         OPT_MAX,
1059 };
1060
1061 static struct sr_option options[] = {
1062         [OPT_SINGLE_COL] = { "single-column", "Single column", "Enable single-column mode, using the specified column (>= 1); 0: multi-col. mode", NULL, NULL },
1063         [OPT_NUM_LOGIC] = { "numchannels", "Number of logic channels", "The number of (logic) channels (single-col. mode: number of bits beginning at 'first channel', LSB-first)", NULL, NULL },
1064         [OPT_DELIM] = { "delimiter", "Column delimiter", "The column delimiter (>= 1 characters)", NULL, NULL },
1065         [OPT_FORMAT] = { "format", "Data format (single-col. mode)", "The numeric format of the data (single-col. mode): bin, hex, oct", NULL, NULL },
1066         [OPT_COMMENT] = { "comment", "Comment character(s)", "The comment prefix character(s)", NULL, NULL },
1067         [OPT_RATE] = { "samplerate", "Samplerate (Hz)", "The sample rate (used during capture) in Hz", NULL, NULL },
1068         [OPT_FIRST_COL] = { "first-column", "First column", "The column number of the first channel (multi-col. mode)", NULL, NULL },
1069         [OPT_HEADER] = { "header", "Interpret first line as header (multi-col. mode)", "Treat the first line as header with channel names (multi-col. mode)", NULL, NULL },
1070         [OPT_START] = { "startline", "Start line", "The line number at which to start processing samples (>= 1)", NULL, NULL },
1071         [OPT_MAX] = ALL_ZERO,
1072 };
1073
1074 static const struct sr_option *get_options(void)
1075 {
1076         GSList *l;
1077
1078         if (!options[0].def) {
1079                 options[OPT_SINGLE_COL].def = g_variant_ref_sink(g_variant_new_uint32(0));
1080                 options[OPT_NUM_LOGIC].def = g_variant_ref_sink(g_variant_new_uint32(0));
1081                 options[OPT_DELIM].def = g_variant_ref_sink(g_variant_new_string(","));
1082                 options[OPT_FORMAT].def = g_variant_ref_sink(g_variant_new_string("bin"));
1083                 l = NULL;
1084                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("bin")));
1085                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("hex")));
1086                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("oct")));
1087                 options[OPT_FORMAT].values = l;
1088                 options[OPT_COMMENT].def = g_variant_ref_sink(g_variant_new_string(";"));
1089                 options[OPT_RATE].def = g_variant_ref_sink(g_variant_new_uint64(0));
1090                 options[OPT_FIRST_COL].def = g_variant_ref_sink(g_variant_new_uint32(1));
1091                 options[OPT_HEADER].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
1092                 options[OPT_START].def = g_variant_ref_sink(g_variant_new_uint32(1));
1093         }
1094
1095         return options;
1096 }
1097
1098 SR_PRIV struct sr_input_module input_csv = {
1099         .id = "csv",
1100         .name = "CSV",
1101         .desc = "Comma-separated values",
1102         .exts = (const char*[]){"csv", NULL},
1103         .options = get_options,
1104         .init = init,
1105         .receive = receive,
1106         .end = end,
1107         .cleanup = cleanup,
1108         .reset = reset,
1109 };