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