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