]> sigrok.org Git - libsigrok.git/blob - src/input/csv.c
input/csv: include section nits
[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 {
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         unsigned int 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         unsigned int 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         unsigned int 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         unsigned int 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         int 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 }
187
188 static int parse_binstr(const char *str, struct context *inc)
189 {
190         gsize i, j, length;
191
192         length = strlen(str);
193
194         if (!length) {
195                 sr_err("Column %u in line %zu is empty.", inc->single_column,
196                         inc->line_number);
197                 return SR_ERR;
198         }
199
200         /* Clear buffer in order to set bits only. */
201         memset(inc->sample_buffer, 0, inc->sample_unit_size);
202
203         i = inc->first_channel;
204
205         for (j = 0; i < length && j < inc->num_channels; i++, j++) {
206                 if (str[length - i - 1] == '1') {
207                         inc->sample_buffer[j / 8] |= (1 << (j % 8));
208                 } else if (str[length - i - 1] != '0') {
209                         sr_err("Invalid value '%s' in column %u in line %zu.",
210                                 str, inc->single_column, inc->line_number);
211                         return SR_ERR;
212                 }
213         }
214
215         return SR_OK;
216 }
217
218 static int parse_hexstr(const char *str, struct context *inc)
219 {
220         gsize i, j, k, length;
221         uint8_t value;
222         char c;
223
224         length = strlen(str);
225
226         if (!length) {
227                 sr_err("Column %u in line %zu is empty.", inc->single_column,
228                         inc->line_number);
229                 return SR_ERR;
230         }
231
232         /* Clear buffer in order to set bits only. */
233         memset(inc->sample_buffer, 0, inc->sample_unit_size);
234
235         /* Calculate the position of the first hexadecimal digit. */
236         i = inc->first_channel / 4;
237
238         for (j = 0; i < length && j < inc->num_channels; i++) {
239                 c = str[length - i - 1];
240
241                 if (!g_ascii_isxdigit(c)) {
242                         sr_err("Invalid value '%s' in column %u in line %zu.",
243                                 str, inc->single_column, inc->line_number);
244                         return SR_ERR;
245                 }
246
247                 value = g_ascii_xdigit_value(c);
248
249                 k = (inc->first_channel + j) % 4;
250
251                 for (; j < inc->num_channels && k < 4; k++) {
252                         if (value & (1 << k))
253                                 inc->sample_buffer[j / 8] |= (1 << (j % 8));
254
255                         j++;
256                 }
257         }
258
259         return SR_OK;
260 }
261
262 static int parse_octstr(const char *str, struct context *inc)
263 {
264         gsize i, j, k, length;
265         uint8_t value;
266         char c;
267
268         length = strlen(str);
269
270         if (!length) {
271                 sr_err("Column %u in line %zu is empty.", inc->single_column,
272                         inc->line_number);
273                 return SR_ERR;
274         }
275
276         /* Clear buffer in order to set bits only. */
277         memset(inc->sample_buffer, 0, inc->sample_unit_size);
278
279         /* Calculate the position of the first octal digit. */
280         i = inc->first_channel / 3;
281
282         for (j = 0; i < length && j < inc->num_channels; i++) {
283                 c = str[length - i - 1];
284
285                 if (c < '0' || c > '7') {
286                         sr_err("Invalid value '%s' in column %u in line %zu.",
287                                 str, inc->single_column, inc->line_number);
288                         return SR_ERR;
289                 }
290
291                 value = g_ascii_xdigit_value(c);
292
293                 k = (inc->first_channel + j) % 3;
294
295                 for (; j < inc->num_channels && k < 3; k++) {
296                         if (value & (1 << k))
297                                 inc->sample_buffer[j / 8] |= (1 << (j % 8));
298
299                         j++;
300                 }
301         }
302
303         return SR_OK;
304 }
305
306 static char **parse_line(char *buf, struct context *inc, int max_columns)
307 {
308         const char *str, *remainder;
309         GSList *list, *l;
310         char **columns;
311         char *column;
312         gsize n, k;
313
314         n = 0;
315         k = 0;
316         list = NULL;
317
318         remainder = buf;
319         str = strstr(remainder, inc->delimiter->str);
320
321         while (str && max_columns) {
322                 if (n >= inc->first_column) {
323                         column = g_strndup(remainder, str - remainder);
324                         list = g_slist_prepend(list, g_strstrip(column));
325
326                         max_columns--;
327                         k++;
328                 }
329
330                 remainder = str + inc->delimiter->len;
331                 str = strstr(remainder, inc->delimiter->str);
332                 n++;
333         }
334
335         if (buf[0] && max_columns && n >= inc->first_column) {
336                 column = g_strdup(remainder);
337                 list = g_slist_prepend(list, g_strstrip(column));
338                 k++;
339         }
340
341         if (!(columns = g_try_new(char *, k + 1)))
342                 return NULL;
343
344         columns[k--] = NULL;
345
346         for (l = list; l; l = l->next)
347                 columns[k--] = l->data;
348
349         g_slist_free(list);
350
351         return columns;
352 }
353
354 static int parse_multi_columns(char **columns, struct context *inc)
355 {
356         gsize i;
357         char *column;
358
359         /* Clear buffer in order to set bits only. */
360         memset(inc->sample_buffer, 0, inc->sample_unit_size);
361
362         for (i = 0; i < inc->num_channels; i++) {
363                 column = columns[i];
364                 if (column[0] == '1') {
365                         inc->sample_buffer[i / 8] |= (1 << (i % 8));
366                 } else if (!strlen(column)) {
367                         sr_err("Column %zu in line %zu is empty.",
368                                 inc->first_channel + i, inc->line_number);
369                         return SR_ERR;
370                 } else if (column[0] != '0') {
371                         sr_err("Invalid value '%s' in column %zu in line %zu.",
372                                 column, inc->first_channel + i,
373                                 inc->line_number);
374                         return SR_ERR;
375                 }
376         }
377
378         return SR_OK;
379 }
380
381 static int parse_single_column(const char *column, struct context *inc)
382 {
383         int res;
384
385         res = SR_ERR;
386
387         switch (inc->format) {
388         case FORMAT_BIN:
389                 res = parse_binstr(column, inc);
390                 break;
391         case FORMAT_HEX:
392                 res = parse_hexstr(column, inc);
393                 break;
394         case FORMAT_OCT:
395                 res = parse_octstr(column, inc);
396                 break;
397         }
398
399         return res;
400 }
401
402 static int flush_samples(const struct sr_input *in)
403 {
404         struct context *inc;
405         struct sr_datafeed_packet packet;
406         struct sr_datafeed_logic logic;
407         int rc;
408
409         inc = in->priv;
410         if (!inc->datafeed_buf_fill)
411                 return SR_OK;
412
413         memset(&packet, 0, sizeof(packet));
414         memset(&logic, 0, sizeof(logic));
415         packet.type = SR_DF_LOGIC;
416         packet.payload = &logic;
417         logic.unitsize = inc->sample_unit_size;
418         logic.length = inc->datafeed_buf_fill;
419         logic.data = inc->datafeed_buffer;
420
421         rc = sr_session_send(in->sdi, &packet);
422         if (rc != SR_OK)
423                 return rc;
424
425         inc->datafeed_buf_fill = 0;
426         return SR_OK;
427 }
428
429 static int queue_samples(const struct sr_input *in)
430 {
431         struct context *inc;
432         int rc;
433
434         inc = in->priv;
435
436         inc->datafeed_buf_fill += inc->sample_unit_size;
437         if (inc->datafeed_buf_fill == inc->datafeed_buf_size) {
438                 rc = flush_samples(in);
439                 if (rc != SR_OK)
440                         return rc;
441         }
442         inc->sample_buffer = &inc->datafeed_buffer[inc->datafeed_buf_fill];
443         return SR_OK;
444 }
445
446 static int init(struct sr_input *in, GHashTable *options)
447 {
448         struct context *inc;
449         const char *s;
450
451         in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
452         in->priv = inc = g_malloc0(sizeof(struct context));
453
454         inc->single_column = g_variant_get_int32(g_hash_table_lookup(options, "single-column"));
455         inc->multi_column_mode = inc->single_column == 0;
456
457         inc->num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
458
459         inc->delimiter = g_string_new(g_variant_get_string(
460                         g_hash_table_lookup(options, "delimiter"), NULL));
461         if (inc->delimiter->len == 0) {
462                 sr_err("Delimiter must be at least one character.");
463                 return SR_ERR_ARG;
464         }
465
466         s = g_variant_get_string(g_hash_table_lookup(options, "format"), NULL);
467         if (!g_ascii_strncasecmp(s, "bin", 3)) {
468                 inc->format = FORMAT_BIN;
469         } else if (!g_ascii_strncasecmp(s, "hex", 3)) {
470                 inc->format = FORMAT_HEX;
471         } else if (!g_ascii_strncasecmp(s, "oct", 3)) {
472                 inc->format = FORMAT_OCT;
473         } else {
474                 sr_err("Invalid format: '%s'", s);
475                 return SR_ERR_ARG;
476         }
477
478         inc->comment = g_string_new(g_variant_get_string(
479                         g_hash_table_lookup(options, "comment"), NULL));
480         if (g_string_equal(inc->comment, inc->delimiter)) {
481                 /* That's never going to work. Likely the result of the user
482                  * setting the delimiter to ; -- the default comment. Clearing
483                  * the comment setting will work in that case. */
484                 g_string_truncate(inc->comment, 0);
485         }
486
487         inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
488
489         inc->first_channel = g_variant_get_int32(g_hash_table_lookup(options, "first-channel"));
490
491         inc->header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
492
493         inc->start_line = g_variant_get_int32(g_hash_table_lookup(options, "startline"));
494         if (inc->start_line < 1) {
495                 sr_err("Invalid start line %zu.", inc->start_line);
496                 return SR_ERR_ARG;
497         }
498
499         if (inc->multi_column_mode)
500                 inc->first_column = inc->first_channel;
501         else
502                 inc->first_column = inc->single_column;
503
504         if (!inc->multi_column_mode && !inc->num_channels) {
505                 sr_err("Number of channels needs to be specified in single column mode.");
506                 return SR_ERR_ARG;
507         }
508
509         return SR_OK;
510 }
511
512 /*
513  * Check the channel list for consistency across file re-import. See
514  * the VCD input module for more details and motivation.
515  */
516
517 static void keep_header_for_reread(const struct sr_input *in)
518 {
519         struct context *inc;
520
521         inc = in->priv;
522         g_slist_free_full(inc->prev_sr_channels, sr_channel_free_cb);
523         inc->prev_sr_channels = in->sdi->channels;
524         in->sdi->channels = NULL;
525 }
526
527 static int check_header_in_reread(const struct sr_input *in)
528 {
529         struct context *inc;
530
531         if (!in)
532                 return FALSE;
533         inc = in->priv;
534         if (!inc)
535                 return FALSE;
536         if (!inc->prev_sr_channels)
537                 return TRUE;
538
539         if (sr_channel_lists_differ(inc->prev_sr_channels, in->sdi->channels)) {
540                 sr_err("Channel list change not supported for file re-read.");
541                 return FALSE;
542         }
543         g_slist_free_full(in->sdi->channels, sr_channel_free_cb);
544         in->sdi->channels = inc->prev_sr_channels;
545         inc->prev_sr_channels = NULL;
546
547         return TRUE;
548 }
549
550 static const char *delim_set = "\r\n";
551
552 static const char *get_line_termination(GString *buf)
553 {
554         const char *term;
555
556         term = NULL;
557         if (g_strstr_len(buf->str, buf->len, "\r\n"))
558                 term = "\r\n";
559         else if (memchr(buf->str, '\n', buf->len))
560                 term = "\n";
561         else if (memchr(buf->str, '\r', buf->len))
562                 term = "\r";
563
564         return term;
565 }
566
567 static int initial_parse(const struct sr_input *in, GString *buf)
568 {
569         struct context *inc;
570         GString *channel_name;
571         unsigned int num_columns, i;
572         size_t line_number, l;
573         int ret;
574         char **lines, *line, **columns, *column;
575
576         ret = SR_OK;
577         inc = in->priv;
578         columns = NULL;
579
580         line_number = 0;
581         lines = g_strsplit_set(buf->str, delim_set, 0);
582         for (l = 0; lines[l]; l++) {
583                 line_number++;
584                 line = lines[l];
585                 if (inc->start_line > line_number) {
586                         sr_spew("Line %zu skipped.", line_number);
587                         continue;
588                 }
589                 if (line[0] == '\0') {
590                         sr_spew("Blank line %zu skipped.", line_number);
591                         continue;
592                 }
593                 strip_comment(line, inc->comment);
594                 if (line[0] == '\0') {
595                         sr_spew("Comment-only line %zu skipped.", line_number);
596                         continue;
597                 }
598
599                 /* Reached first proper line. */
600                 break;
601         }
602         if (!lines[l]) {
603                 /* Not enough data for a proper line yet. */
604                 ret = SR_ERR_NA;
605                 goto out;
606         }
607
608         /*
609          * In order to determine the number of columns parse the current line
610          * without limiting the number of columns.
611          */
612         columns = parse_line(line, inc, -1);
613         if (!columns) {
614                 sr_err("Error while parsing line %zu.", line_number);
615                 ret = SR_ERR;
616                 goto out;
617         }
618         num_columns = g_strv_length(columns);
619
620         /* Ensure that the first column is not out of bounds. */
621         if (!num_columns) {
622                 sr_err("Column %u in line %zu is out of bounds.",
623                         inc->first_column, line_number);
624                 ret = SR_ERR;
625                 goto out;
626         }
627
628         if (inc->multi_column_mode) {
629                 /*
630                  * Detect the number of channels in multi column mode
631                  * automatically if not specified.
632                  */
633                 if (!inc->num_channels) {
634                         inc->num_channels = num_columns;
635                         sr_dbg("Number of auto-detected channels: %u.",
636                                 inc->num_channels);
637                 }
638
639                 /*
640                  * Ensure that the number of channels does not exceed the number
641                  * of columns in multi column mode.
642                  */
643                 if (num_columns < inc->num_channels) {
644                         sr_err("Not enough columns for desired number of channels in line %zu.",
645                                 line_number);
646                         ret = SR_ERR;
647                         goto out;
648                 }
649         }
650
651         channel_name = g_string_sized_new(64);
652         for (i = 0; i < inc->num_channels; i++) {
653                 column = columns[i];
654                 if (inc->header && inc->multi_column_mode && column[0] != '\0')
655                         g_string_assign(channel_name, column);
656                 else
657                         g_string_printf(channel_name, "%u", i);
658                 sr_channel_new(in->sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name->str);
659         }
660         g_string_free(channel_name, TRUE);
661         if (!check_header_in_reread(in)) {
662                 ret = SR_ERR_DATA;
663                 goto out;
664         }
665
666         /*
667          * Calculate the minimum buffer size to store the set of samples
668          * of all channels (unit size). Determine a larger buffer size
669          * for datafeed submission that is a multiple of the unit size.
670          * Allocate the larger buffer, and have the "sample buffer" point
671          * to a location within that large buffer.
672          */
673         inc->sample_unit_size = (inc->num_channels + 7) / 8;
674         inc->datafeed_buf_size = CHUNK_SIZE;
675         inc->datafeed_buf_size *= inc->sample_unit_size;
676         inc->datafeed_buffer = g_malloc(inc->datafeed_buf_size);
677         inc->datafeed_buf_fill = 0;
678         inc->sample_buffer = &inc->datafeed_buffer[inc->datafeed_buf_fill];
679
680 out:
681         if (columns)
682                 g_strfreev(columns);
683         g_strfreev(lines);
684
685         return ret;
686 }
687
688 /*
689  * Gets called from initial_receive(), which runs until the end-of-line
690  * encoding of the input stream could get determined. Assumes that this
691  * routine receives enough buffered initial input data to either see the
692  * BOM when there is one, or that no BOM will follow when a text line
693  * termination sequence was seen. Silently drops the UTF-8 BOM sequence
694  * from the input buffer if one was seen. Does not care to protect
695  * against multiple execution or dropping the BOM multiple times --
696  * there should be at most one in the input stream.
697  */
698 static void initial_bom_check(const struct sr_input *in)
699 {
700         static const char *utf8_bom = "\xef\xbb\xbf";
701
702         if (in->buf->len < strlen(utf8_bom))
703                 return;
704         if (strncmp(in->buf->str, utf8_bom, strlen(utf8_bom)) != 0)
705                 return;
706         g_string_erase(in->buf, 0, strlen(utf8_bom));
707 }
708
709 static int initial_receive(const struct sr_input *in)
710 {
711         struct context *inc;
712         GString *new_buf;
713         int len, ret;
714         char *p;
715         const char *termination;
716
717         initial_bom_check(in);
718
719         inc = in->priv;
720
721         termination = get_line_termination(in->buf);
722         if (!termination)
723                 /* Don't have a full line yet. */
724                 return SR_ERR_NA;
725
726         p = g_strrstr_len(in->buf->str, in->buf->len, termination);
727         if (!p)
728                 /* Don't have a full line yet. */
729                 return SR_ERR_NA;
730         len = p - in->buf->str - 1;
731         new_buf = g_string_new_len(in->buf->str, len);
732         g_string_append_c(new_buf, '\0');
733
734         inc->termination = g_strdup(termination);
735
736         if (in->buf->str[0] != '\0')
737                 ret = initial_parse(in, new_buf);
738         else
739                 ret = SR_OK;
740
741         g_string_free(new_buf, TRUE);
742
743         return ret;
744 }
745
746 static int process_buffer(struct sr_input *in, gboolean is_eof)
747 {
748         struct sr_datafeed_packet packet;
749         struct sr_datafeed_meta meta;
750         struct sr_config *src;
751         struct context *inc;
752         gsize num_columns;
753         uint64_t samplerate;
754         int max_columns, ret, l;
755         char *p, **lines, *line, **columns;
756
757         inc = in->priv;
758         if (!inc->started) {
759                 std_session_send_df_header(in->sdi);
760
761                 if (inc->samplerate) {
762                         packet.type = SR_DF_META;
763                         packet.payload = &meta;
764                         samplerate = inc->samplerate;
765                         src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
766                         meta.config = g_slist_append(NULL, src);
767                         sr_session_send(in->sdi, &packet);
768                         g_slist_free(meta.config);
769                         sr_config_free(src);
770                 }
771
772                 inc->started = TRUE;
773         }
774
775         /* Limit the number of columns to parse. */
776         if (inc->multi_column_mode)
777                 max_columns = inc->num_channels;
778         else
779                 max_columns = 1;
780
781         /*
782          * Consider empty input non-fatal. Keep accumulating input until
783          * at least one full text line has become available. Grab the
784          * maximum amount of accumulated data that consists of full text
785          * lines, and process what has been received so far, leaving not
786          * yet complete lines for the next invocation.
787          *
788          * Enforce that all previously buffered data gets processed in
789          * the "EOF" condition. Do not insist in the presence of the
790          * termination sequence for the last line (may often be missing
791          * on Windows). A present termination sequence will just result
792          * in the "execution of an empty line", and does not harm.
793          */
794         if (!in->buf->len)
795                 return SR_OK;
796         if (is_eof) {
797                 p = in->buf->str + in->buf->len;
798         } else {
799                 p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination);
800                 if (!p)
801                         return SR_ERR;
802                 *p = '\0';
803                 p += strlen(inc->termination);
804         }
805         g_strstrip(in->buf->str);
806
807         ret = SR_OK;
808         lines = g_strsplit_set(in->buf->str, delim_set, 0);
809         for (l = 0; lines[l]; l++) {
810                 inc->line_number++;
811                 line = lines[l];
812                 if (line[0] == '\0') {
813                         sr_spew("Blank line %zu skipped.", inc->line_number);
814                         continue;
815                 }
816
817                 /* Remove trailing comment. */
818                 strip_comment(line, inc->comment);
819                 if (line[0] == '\0') {
820                         sr_spew("Comment-only line %zu skipped.", inc->line_number);
821                         continue;
822                 }
823
824                 /* Skip the header line, its content was used as the channel names. */
825                 if (inc->header) {
826                         sr_spew("Header line %zu skipped.", inc->line_number);
827                         inc->header = FALSE;
828                         continue;
829                 }
830
831                 columns = parse_line(line, inc, max_columns);
832                 if (!columns) {
833                         sr_err("Error while parsing line %zu.", inc->line_number);
834                         g_strfreev(lines);
835                         return SR_ERR;
836                 }
837                 num_columns = g_strv_length(columns);
838                 if (!num_columns) {
839                         sr_err("Column %u in line %zu is out of bounds.",
840                                 inc->first_column, inc->line_number);
841                         g_strfreev(columns);
842                         g_strfreev(lines);
843                         return SR_ERR;
844                 }
845                 /*
846                  * Ensure that the number of channels does not exceed the number
847                  * of columns in multi column mode.
848                  */
849                 if (inc->multi_column_mode && num_columns < inc->num_channels) {
850                         sr_err("Not enough columns for desired number of channels in line %zu.",
851                                 inc->line_number);
852                         g_strfreev(columns);
853                         g_strfreev(lines);
854                         return SR_ERR;
855                 }
856
857                 if (inc->multi_column_mode)
858                         ret = parse_multi_columns(columns, inc);
859                 else
860                         ret = parse_single_column(columns[0], inc);
861                 if (ret != SR_OK) {
862                         g_strfreev(columns);
863                         g_strfreev(lines);
864                         return SR_ERR;
865                 }
866
867                 /* Send sample data to the session bus. */
868                 ret = queue_samples(in);
869                 if (ret != SR_OK) {
870                         sr_err("Sending samples failed.");
871                         g_strfreev(columns);
872                         g_strfreev(lines);
873                         return SR_ERR;
874                 }
875
876                 g_strfreev(columns);
877         }
878         g_strfreev(lines);
879         g_string_erase(in->buf, 0, p - in->buf->str);
880
881         return ret;
882 }
883
884 static int receive(struct sr_input *in, GString *buf)
885 {
886         struct context *inc;
887         int ret;
888
889         g_string_append_len(in->buf, buf->str, buf->len);
890
891         inc = in->priv;
892         if (!inc->termination) {
893                 ret = initial_receive(in);
894                 if (ret == SR_ERR_NA)
895                         /* Not enough data yet. */
896                         return SR_OK;
897                 else if (ret != SR_OK)
898                         return SR_ERR;
899
900                 /* sdi is ready, notify frontend. */
901                 in->sdi_ready = TRUE;
902                 return SR_OK;
903         }
904
905         ret = process_buffer(in, FALSE);
906
907         return ret;
908 }
909
910 static int end(struct sr_input *in)
911 {
912         struct context *inc;
913         int ret;
914
915         if (in->sdi_ready)
916                 ret = process_buffer(in, TRUE);
917         else
918                 ret = SR_OK;
919         if (ret != SR_OK)
920                 return ret;
921
922         ret = flush_samples(in);
923         if (ret != SR_OK)
924                 return ret;
925
926         inc = in->priv;
927         if (inc->started)
928                 std_session_send_df_end(in->sdi);
929
930         return ret;
931 }
932
933 static void cleanup(struct sr_input *in)
934 {
935         struct context *inc;
936
937         keep_header_for_reread(in);
938
939         inc = in->priv;
940
941         g_free(inc->termination);
942         inc->termination = NULL;
943         g_free(inc->datafeed_buffer);
944         inc->datafeed_buffer = NULL;
945 }
946
947 static int reset(struct sr_input *in)
948 {
949         struct context *inc = in->priv;
950
951         cleanup(in);
952         inc->started = FALSE;
953         g_string_truncate(in->buf, 0);
954
955         return SR_OK;
956 }
957
958 static struct sr_option options[] = {
959         { "single-column", "Single column", "Enable single-column mode, using the specified column (>= 1); 0: multi-col. mode", NULL, NULL },
960         { "numchannels", "Number of logic channels", "The number of (logic) channels (single-col. mode: number of bits beginning at 'first channel', LSB-first)", NULL, NULL },
961         { "delimiter", "Column delimiter", "The column delimiter (>= 1 characters)", NULL, NULL },
962         { "format", "Data format (single-col. mode)", "The numeric format of the data (single-col. mode): bin, hex, oct", NULL, NULL },
963         { "comment", "Comment character(s)", "The comment prefix character(s)", NULL, NULL },
964         { "samplerate", "Samplerate (Hz)", "The sample rate (used during capture) in Hz", NULL, NULL },
965         { "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 },
966         { "header", "Interpret first line as header (multi-col. mode)", "Treat the first line as header with channel names (multi-col. mode)", NULL, NULL },
967         { "startline", "Start line", "The line number at which to start processing samples (>= 1)", NULL, NULL },
968         ALL_ZERO
969 };
970
971 static const struct sr_option *get_options(void)
972 {
973         GSList *l;
974
975         if (!options[0].def) {
976                 options[0].def = g_variant_ref_sink(g_variant_new_int32(0));
977                 options[1].def = g_variant_ref_sink(g_variant_new_int32(0));
978                 options[2].def = g_variant_ref_sink(g_variant_new_string(","));
979                 options[3].def = g_variant_ref_sink(g_variant_new_string("bin"));
980                 l = NULL;
981                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("bin")));
982                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("hex")));
983                 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("oct")));
984                 options[3].values = l;
985                 options[4].def = g_variant_ref_sink(g_variant_new_string(";"));
986                 options[5].def = g_variant_ref_sink(g_variant_new_uint64(0));
987                 options[6].def = g_variant_ref_sink(g_variant_new_int32(0));
988                 options[7].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
989                 options[8].def = g_variant_ref_sink(g_variant_new_int32(1));
990         }
991
992         return options;
993 }
994
995 SR_PRIV struct sr_input_module input_csv = {
996         .id = "csv",
997         .name = "CSV",
998         .desc = "Comma-separated values",
999         .exts = (const char*[]){"csv", NULL},
1000         .options = get_options,
1001         .init = init,
1002         .receive = receive,
1003         .end = end,
1004         .cleanup = cleanup,
1005         .reset = reset,
1006 };