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