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