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