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