]> sigrok.org Git - libsigrok.git/blame - src/input/csv.c
input/csv: improve "channel name from header line" logic
[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>
e53f32d2 5 * Copyright (C) 2019 Gerhard Sittig <gerhard.sittig@gmx.net>
4a35548b
MS
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
e05f1827
GS
21#include "config.h"
22
23#include <glib.h>
4a35548b
MS
24#include <stdlib.h>
25#include <string.h>
e05f1827 26
c1aae900 27#include <libsigrok/libsigrok.h>
4a35548b 28#include "libsigrok-internal.h"
f6dcb320 29#include "scpi.h" /* String un-quote for channel name from header line. */
4a35548b 30
3544f848 31#define LOG_PREFIX "input/csv"
4a35548b 32
9a4fd01a 33#define CHUNK_SIZE (4 * 1024 * 1024)
cd59e6ec 34
4a35548b
MS
35/*
36 * The CSV input module has the following options:
37 *
38 * single-column: Specifies the column number which stores the sample data for
39 * single column mode and enables single column mode. Multi
40 * column mode is used if this parameter is omitted.
41 *
ba7dd8bb
UH
42 * numchannels: Specifies the number of channels to use. In multi column mode
43 * the number of channels are the number of columns and in single
4a35548b 44 * column mode the number of bits (LSB first) beginning at
ba7dd8bb 45 * 'first-channel'.
4a35548b
MS
46 *
47 * delimiter: Specifies the delimiter for columns. Must be at least one
48 * character. Comma is used as default delimiter.
49 *
50 * format: Specifies the format of the sample data in single column mode.
51 * Available formats are: 'bin', 'hex' and 'oct'. The binary
52 * format is used by default. This option has no effect in multi
53 * column mode.
54 *
55 * comment: Specifies the prefix character(s) for comments. No prefix
56 * characters are used by default which disables removing of
57 * comments.
58 *
59 * samplerate: Samplerate which the sample data was captured with. Default
60 * value is 0.
61 *
ba7dd8bb
UH
62 * first-channel: Column number of the first channel in multi column mode and
63 * position of the bit for the first channel in single column mode.
4a35548b
MS
64 * Default value is 0.
65 *
66 * header: Determines if the first line should be treated as header
ba7dd8bb
UH
67 * and used for channel names in multi column mode. Empty header
68 * names will be replaced by the channel number. If enabled in
4a35548b
MS
69 * single column mode the first line will be skipped. Usage of
70 * header is disabled by default.
71 *
72 * startline: Line number to start processing sample data. Must be greater
73 * than 0. The default line number to start processing is 1.
74 */
75
ccff468b
GS
76/*
77 * TODO
78 *
79 * - Determine how the text line handling can get improved, regarding
80 * all of robustness and flexibility and correctness.
81 * - The current implementation splits on "any run of CR and LF". Which
82 * translates to: Line numbers are wrong in the presence of empty
de788af4 83 * lines in the input stream. See below for an (expensive) fix.
ccff468b
GS
84 * - Dropping support for CR style end-of-line markers could improve
85 * the situation a lot. Code could search for and split on LF, and
86 * trim optional trailing CR. This would result in proper support
87 * for CRLF (Windows) as well as LF (Unix), and allow for correct
88 * line number counts.
89 * - When support for CR-only line termination cannot get dropped,
90 * then the current implementation is inappropriate. Currently the
91 * input stream is scanned for the first occurance of either of the
92 * supported termination styles (which is good). For the remaining
93 * session a consistent encoding of the text lines is assumed (which
de788af4 94 * is acceptable).
ccff468b
GS
95 * - When line numbers need to be correct and reliable, _and_ the full
96 * set of previously supported line termination sequences are required,
97 * and potentially more are to get added for improved compatibility
98 * with more platforms or generators, then the current approach of
99 * splitting on runs of termination characters needs to get replaced,
100 * by the more expensive approach to scan for and count the initially
101 * determined termination sequence.
102 *
103 * - Add support for analog input data? (optional)
104 * - Needs a syntax first for user specs which channels (columns) are
105 * logic and which are analog. May need heuristics(?) to guess from
106 * input data in the absence of user provided specs.
107 */
108
4a35548b 109/* Single column formats. */
ad6a2bee 110enum single_col_format {
e53f32d2
GS
111 FORMAT_NONE, /* Ignore this column. */
112 FORMAT_BIN, /* Bin digits for a set of bits (or just one bit). */
113 FORMAT_HEX, /* Hex digits for a set of bits. */
114 FORMAT_OCT, /* Oct digits for a set of bits. */
115};
116
117static const char *col_format_text[] = {
118 [FORMAT_NONE] = "unknown",
119 [FORMAT_BIN] = "binary",
120 [FORMAT_HEX] = "hexadecimal",
121 [FORMAT_OCT] = "octal",
122};
123
124struct column_details {
125 size_t col_nr;
126 enum single_col_format text_format;
127 size_t channel_offset;
128 size_t channel_count;
4a35548b
MS
129};
130
131struct context {
41d214f6
BV
132 gboolean started;
133
4a35548b
MS
134 /* Current selected samplerate. */
135 uint64_t samplerate;
246aca5f 136 gboolean samplerate_sent;
4a35548b 137
ba7dd8bb 138 /* Number of channels. */
ad6a2bee 139 size_t num_channels;
4a35548b
MS
140
141 /* Column delimiter character(s). */
142 GString *delimiter;
143
144 /* Comment prefix character(s). */
145 GString *comment;
146
d9251a2c 147 /* Termination character(s) used in current stream. */
41d214f6
BV
148 char *termination;
149
4a35548b
MS
150 /* Determines if sample data is stored in multiple columns. */
151 gboolean multi_column_mode;
152
e53f32d2
GS
153 /* Parameters how to process the columns. */
154 size_t column_want_count;
155 struct column_details *column_details;
156
4a35548b 157 /* Column number of the sample data in single column mode. */
ad6a2bee 158 size_t single_column;
4a35548b 159
e53f32d2 160 /* Column number of the first channel. */
ad6a2bee 161 size_t first_column;
4a35548b 162
4a35548b 163 /* Line number to start processing. */
6433156c 164 size_t start_line;
4a35548b
MS
165
166 /*
167 * Determines if the first line should be treated as header and used for
ba7dd8bb 168 * channel names in multi column mode.
4a35548b 169 */
de8fe3b5
GS
170 gboolean use_header;
171 gboolean header_seen;
4a35548b
MS
172
173 /* Format sample data is stored in single column mode. */
ad6a2bee 174 enum single_col_format format;
4a35548b 175
cd59e6ec
GS
176 size_t sample_unit_size; /**!< Byte count for a single sample. */
177 uint8_t *sample_buffer; /**!< Buffer for a single sample. */
4a35548b 178
cd59e6ec
GS
179 uint8_t *datafeed_buffer; /**!< Queue for datafeed submission. */
180 size_t datafeed_buf_size;
181 size_t datafeed_buf_fill;
4a35548b 182
4a35548b 183 /* Current line number. */
6433156c 184 size_t line_number;
affaf540
GS
185
186 /* List of previously created sigrok channels. */
187 GSList *prev_sr_channels;
4a35548b
MS
188};
189
626c388a
GS
190/*
191 * Primitive operations to handle sample sets:
192 * - Keep a buffer for datafeed submission, capable of holding many
193 * samples (reduces call overhead, improves throughput).
194 * - Have a "current sample set" pointer reference one position in that
195 * large samples buffer.
196 * - Clear the current sample set before text line inspection, then set
197 * the bits which are found active in the current line of text input.
198 * Phrase the API such that call sites can be kept simple. Advance to
199 * the next sample set between lines, flush the larger buffer as needed
200 * (when it is full, or upon EOF).
201 */
202
203static void clear_logic_samples(struct context *inc)
204{
205 inc->sample_buffer = &inc->datafeed_buffer[inc->datafeed_buf_fill];
206 memset(inc->sample_buffer, 0, inc->sample_unit_size);
207}
208
209static void set_logic_level(struct context *inc, size_t ch_idx, int on)
210{
211 size_t byte_idx, bit_idx;
212 uint8_t bit_mask;
213
214 if (ch_idx >= inc->num_channels)
215 return;
216 if (!on)
217 return;
218
219 byte_idx = ch_idx / 8;
220 bit_idx = ch_idx % 8;
221 bit_mask = 1 << bit_idx;
222 inc->sample_buffer[byte_idx] |= bit_mask;
223}
224
225static int flush_logic_samples(const struct sr_input *in)
226{
227 struct context *inc;
228 struct sr_datafeed_packet packet;
246aca5f
GS
229 struct sr_datafeed_meta meta;
230 struct sr_config *src;
231 uint64_t samplerate;
626c388a
GS
232 struct sr_datafeed_logic logic;
233 int rc;
234
235 inc = in->priv;
236 if (!inc->datafeed_buf_fill)
237 return SR_OK;
238
246aca5f
GS
239 if (inc->samplerate && !inc->samplerate_sent) {
240 packet.type = SR_DF_META;
241 packet.payload = &meta;
242 samplerate = inc->samplerate;
243 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
244 meta.config = g_slist_append(NULL, src);
245 sr_session_send(in->sdi, &packet);
246 g_slist_free(meta.config);
247 sr_config_free(src);
248 inc->samplerate_sent = TRUE;
249 }
250
626c388a
GS
251 memset(&packet, 0, sizeof(packet));
252 memset(&logic, 0, sizeof(logic));
253 packet.type = SR_DF_LOGIC;
254 packet.payload = &logic;
255 logic.unitsize = inc->sample_unit_size;
256 logic.length = inc->datafeed_buf_fill;
257 logic.data = inc->datafeed_buffer;
258
259 rc = sr_session_send(in->sdi, &packet);
260 if (rc != SR_OK)
261 return rc;
262
263 inc->datafeed_buf_fill = 0;
264 return SR_OK;
265}
266
267static int queue_logic_samples(const struct sr_input *in)
268{
269 struct context *inc;
270 int rc;
271
272 inc = in->priv;
273
274 inc->datafeed_buf_fill += inc->sample_unit_size;
275 if (inc->datafeed_buf_fill == inc->datafeed_buf_size) {
276 rc = flush_logic_samples(in);
277 if (rc != SR_OK)
278 return rc;
279 }
280 return SR_OK;
281}
282
e53f32d2
GS
283static int make_column_details_single(struct context *inc,
284 size_t col_nr, size_t bit_count, enum single_col_format format)
285{
286 struct column_details *details;
287
288 /*
289 * Need at least as many columns to also include the one with
290 * the single-column input data.
291 */
292 inc->column_want_count = col_nr;
293
294 /*
295 * Allocate the columns' processing details. Columns are counted
296 * from 1 (user's perspective), array items from 0 (programmer's
297 * perspective).
298 */
299 inc->column_details = g_malloc0_n(col_nr, sizeof(inc->column_details[0]));
300 details = &inc->column_details[col_nr - 1];
301 details->col_nr = col_nr;
302
303 /*
304 * In single-column mode this single column will hold all bits
305 * of all logic channels, in the user specified number format.
306 */
307 details->text_format = format;
308 details->channel_offset = 0;
309 details->channel_count = bit_count;
310
311 return SR_OK;
312}
313
314static int make_column_details_multi(struct context *inc,
315 size_t first_col, size_t last_col)
316{
317 struct column_details *details;
318 size_t col_nr;
319
320 /*
321 * Need at least as many columns to also include the one with
322 * the last channel's data.
323 */
324 inc->column_want_count = last_col;
325
326 /*
327 * Allocate the columns' processing details. Columns are counted
328 * from 1, array items from 0.
329 * In multi-column mode each column will hold a single bit for
330 * the respective channel.
331 */
332 inc->column_details = g_malloc0_n(last_col, sizeof(inc->column_details[0]));
333 for (col_nr = first_col; col_nr <= last_col; col_nr++) {
334 details = &inc->column_details[col_nr - 1];
335 details->col_nr = col_nr;
336 details->text_format = FORMAT_BIN;
337 details->channel_offset = col_nr - first_col;
338 details->channel_count = 1;
339 }
340
341
342 return SR_OK;
343}
344
345static const struct column_details *lookup_column_details(struct context *inc, size_t nr)
346{
347 if (!inc || !inc->column_details)
348 return NULL;
349 if (!nr || nr > inc->column_want_count)
350 return NULL;
351 return &inc->column_details[nr - 1];
352}
353
19267272
GS
354/*
355 * Primitive operations for text input: Strip comments off text lines.
356 * Split text lines into columns. Process input text for individual
357 * columns.
358 */
359
41d214f6 360static void strip_comment(char *buf, const GString *prefix)
4a35548b
MS
361{
362 char *ptr;
363
364 if (!prefix->len)
365 return;
366
b2c4dde2 367 if ((ptr = strstr(buf, prefix->str))) {
41d214f6 368 *ptr = '\0';
b2c4dde2
GS
369 g_strstrip(buf);
370 }
4a35548b
MS
371}
372
19267272 373/**
e53f32d2 374 * @brief Splits a text line into a set of columns.
19267272 375 *
e53f32d2 376 * @param[in] buf The input text line to split.
19267272
GS
377 * @param[in] inc The input module's context.
378 *
e53f32d2 379 * @returns An array of strings, representing the columns' text.
19267272 380 *
e53f32d2 381 * This routine splits a text line on previously determined separators.
19267272 382 */
e53f32d2 383static char **split_line(char *buf, struct context *inc)
4a35548b 384{
e53f32d2 385 return g_strsplit(buf, inc->delimiter->str, 0);
4a35548b
MS
386}
387
19267272 388/**
e53f32d2 389 * @brief Parse a multi-bit field into several logic channels.
19267272 390 *
e53f32d2 391 * @param[in] column The input text, a run of bin/hex/oct digits.
19267272 392 * @param[in] inc The input module's context.
e53f32d2 393 * @param[in] col_nr The involved column number (1-based).
19267272
GS
394 *
395 * @retval SR_OK Success.
396 * @retval SR_ERR Invalid input data (empty, or format error).
397 *
398 * This routine modifies the logic levels in the current sample set,
e53f32d2 399 * based on the text input and a user provided format spec.
19267272 400 */
e53f32d2 401static int parse_column(const char *column, struct context *inc, size_t col_nr)
4a35548b 402{
e53f32d2
GS
403 const struct column_details *col_det;
404 size_t length, ch_rem, ch_idx, ch_inc;
405 const char *rdptr;
4a35548b 406 char c;
e53f32d2
GS
407 gboolean valid;
408 const char *type_text;
409 uint8_t bits;
410
411 /* See whether and how the columns needs to get processed. */
412 col_det = lookup_column_details(inc, col_nr);
413 if (!col_det) {
414 sr_dbg("Column %zu in line %zu without processing details?",
415 col_nr, inc->line_number);
4a35548b
MS
416 return SR_ERR;
417 }
e53f32d2
GS
418 if (col_det->text_format == FORMAT_NONE)
419 return SR_OK;
4a35548b 420
e53f32d2
GS
421 /*
422 * Prepare to read the digits from the text end towards the start.
423 * A digit corresponds to a variable number of channels (depending
424 * on the value's radix). Prepare the mapping of text digits to
425 * (a number of) logic channels.
426 */
427 length = strlen(column);
4a35548b 428 if (!length) {
e53f32d2 429 sr_err("Column %zu in line %zu is empty.", col_nr,
41d214f6 430 inc->line_number);
4a35548b
MS
431 return SR_ERR;
432 }
e53f32d2
GS
433 rdptr = &column[length];
434 ch_idx = col_det->channel_offset;
435 ch_rem = col_det->channel_count;
4a35548b 436
e53f32d2
GS
437 /*
438 * Get another digit and derive up to four logic channels' state from
439 * it. Make sure to not process more bits than the column has channels
440 * associated with it.
441 */
442 while (rdptr > column && ch_rem) {
443 /* Check for valid digits according to the input radix. */
444 c = *(--rdptr);
445 switch (inc->format) {
446 case FORMAT_BIN:
447 valid = g_ascii_isxdigit(c) && c < '2';
448 ch_inc = 1;
449 break;
450 case FORMAT_OCT:
451 valid = g_ascii_isxdigit(c) && c < '8';
452 ch_inc = 3;
453 break;
454 case FORMAT_HEX:
455 valid = g_ascii_isxdigit(c);
456 ch_inc = 4;
457 break;
458 default:
459 valid = FALSE;
460 break;
4a35548b 461 }
e53f32d2
GS
462 if (!valid) {
463 type_text = col_format_text[inc->format];
464 sr_err("Invalid text '%s' in %s type column %zu in line %zu.",
465 column, type_text, col_nr, inc->line_number);
4a35548b 466 return SR_ERR;
e53f32d2
GS
467 }
468 /* Use the digit's bits for logic channels' data. */
469 bits = g_ascii_xdigit_value(c);
470 switch (inc->format) {
471 case FORMAT_NONE:
472 /* ShouldNotHappen(TM), but silences compiler warning. */
4a35548b 473 return SR_ERR;
e53f32d2
GS
474 case FORMAT_HEX:
475 if (ch_rem >= 4) {
476 ch_rem--;
477 set_logic_level(inc, ch_idx + 3, bits & (1 << 3));
478 }
479 /* FALLTHROUGH */
480 case FORMAT_OCT:
481 if (ch_rem >= 3) {
482 ch_rem--;
483 set_logic_level(inc, ch_idx + 2, bits & (1 << 2));
484 }
485 if (ch_rem >= 2) {
486 ch_rem--;
487 set_logic_level(inc, ch_idx + 1, bits & (1 << 1));
488 }
489 /* FALLTHROUGH */
490 case FORMAT_BIN:
491 ch_rem--;
492 set_logic_level(inc, ch_idx + 0, bits & (1 << 0));
493 break;
4a35548b 494 }
e53f32d2 495 ch_idx += ch_inc;
4a35548b 496 }
e53f32d2
GS
497 /*
498 * TODO Determine whether the availability of extra input data
499 * for unhandled logic channels is worth warning here. In this
500 * implementation users are in control, and can have the more
501 * significant bits ignored (which can be considered a feature
502 * and not really a limitation).
503 */
4a35548b
MS
504
505 return SR_OK;
506}
507
41d214f6 508static int init(struct sr_input *in, GHashTable *options)
4a35548b 509{
41d214f6
BV
510 struct context *inc;
511 const char *s;
e53f32d2 512 int ret;
4a35548b 513
aac29cc1 514 in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
41d214f6 515 in->priv = inc = g_malloc0(sizeof(struct context));
4a35548b 516
ad6a2bee 517 inc->single_column = g_variant_get_uint32(g_hash_table_lookup(options, "single-column"));
41d214f6 518 inc->multi_column_mode = inc->single_column == 0;
4a35548b 519
ad6a2bee 520 inc->num_channels = g_variant_get_uint32(g_hash_table_lookup(options, "numchannels"));
4a35548b 521
41d214f6
BV
522 inc->delimiter = g_string_new(g_variant_get_string(
523 g_hash_table_lookup(options, "delimiter"), NULL));
524 if (inc->delimiter->len == 0) {
e53f32d2 525 sr_err("Column delimiter cannot be empty.");
41d214f6 526 return SR_ERR_ARG;
4a35548b
MS
527 }
528
41d214f6
BV
529 s = g_variant_get_string(g_hash_table_lookup(options, "format"), NULL);
530 if (!g_ascii_strncasecmp(s, "bin", 3)) {
531 inc->format = FORMAT_BIN;
532 } else if (!g_ascii_strncasecmp(s, "hex", 3)) {
533 inc->format = FORMAT_HEX;
534 } else if (!g_ascii_strncasecmp(s, "oct", 3)) {
535 inc->format = FORMAT_OCT;
536 } else {
537 sr_err("Invalid format: '%s'", s);
538 return SR_ERR_ARG;
4a35548b
MS
539 }
540
41d214f6
BV
541 inc->comment = g_string_new(g_variant_get_string(
542 g_hash_table_lookup(options, "comment"), NULL));
543 if (g_string_equal(inc->comment, inc->delimiter)) {
e53f32d2
GS
544 /*
545 * Using the same sequence as comment leader and column
546 * delimiter won't work. The user probably specified ';'
547 * as the column delimiter but did not adjust the comment
548 * leader. Try DWIM, drop comment strippin support here.
549 */
550 sr_warn("Comment leader and column delimiter conflict, disabling comment support.");
41d214f6 551 g_string_truncate(inc->comment, 0);
4a35548b
MS
552 }
553
6e8d95a5 554 inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
4a35548b 555
e53f32d2 556 inc->first_column = g_variant_get_uint32(g_hash_table_lookup(options, "first-column"));
4a35548b 557
de8fe3b5 558 inc->use_header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
4a35548b 559
ad6a2bee 560 inc->start_line = g_variant_get_uint32(g_hash_table_lookup(options, "startline"));
41d214f6 561 if (inc->start_line < 1) {
6433156c 562 sr_err("Invalid start line %zu.", inc->start_line);
41d214f6 563 return SR_ERR_ARG;
4a35548b
MS
564 }
565
e53f32d2
GS
566 /*
567 * Derive the set of columns to inspect and their respective
568 * formats from simple input specs. Remain close to the previous
569 * set of option keywords and their meaning. Exclusively support
570 * a single column with multiple bits in it, or an adjacent set
571 * of colums with one bit each. The latter may not know the total
572 * column count here (when the user omitted the spec), and will
573 * derive it from the first text line of the input file.
574 */
575 if (inc->single_column && inc->num_channels) {
576 sr_dbg("DIAG Got single column (%zu) and channels (%zu).",
577 inc->single_column, inc->num_channels);
578 sr_dbg("DIAG -> column %zu, %zu bits in %s format.",
579 inc->single_column, inc->num_channels,
580 col_format_text[inc->format]);
581 ret = make_column_details_single(inc,
582 inc->single_column, inc->num_channels, inc->format);
583 if (ret != SR_OK)
584 return ret;
585 } else if (inc->multi_column_mode) {
586 sr_dbg("DIAG Got multi-column, first column %zu, count %zu.",
587 inc->first_column, inc->num_channels);
588 if (inc->num_channels) {
589 sr_dbg("DIAG -> columns %zu-%zu, 1 bit each.",
590 inc->first_column,
591 inc->first_column + inc->num_channels - 1);
592 ret = make_column_details_multi(inc, inc->first_column,
593 inc->first_column + inc->num_channels - 1);
594 if (ret != SR_OK)
595 return ret;
596 } else {
597 sr_dbg("DIAG -> incomplete spec, have to update later.");
598 }
599 } else {
600 sr_err("Unknown or unsupported combination of option values.");
41d214f6 601 return SR_ERR_ARG;
4a35548b
MS
602 }
603
41d214f6
BV
604 return SR_OK;
605}
4a35548b 606
affaf540
GS
607/*
608 * Check the channel list for consistency across file re-import. See
609 * the VCD input module for more details and motivation.
610 */
611
612static void keep_header_for_reread(const struct sr_input *in)
613{
614 struct context *inc;
615
616 inc = in->priv;
617 g_slist_free_full(inc->prev_sr_channels, sr_channel_free_cb);
618 inc->prev_sr_channels = in->sdi->channels;
619 in->sdi->channels = NULL;
620}
621
622static int check_header_in_reread(const struct sr_input *in)
623{
624 struct context *inc;
625
626 if (!in)
627 return FALSE;
628 inc = in->priv;
629 if (!inc)
630 return FALSE;
631 if (!inc->prev_sr_channels)
632 return TRUE;
633
634 if (sr_channel_lists_differ(inc->prev_sr_channels, in->sdi->channels)) {
635 sr_err("Channel list change not supported for file re-read.");
636 return FALSE;
637 }
638 g_slist_free_full(in->sdi->channels, sr_channel_free_cb);
639 in->sdi->channels = inc->prev_sr_channels;
640 inc->prev_sr_channels = NULL;
641
642 return TRUE;
643}
644
492dfa90
GS
645static const char *delim_set = "\r\n";
646
329733d9 647static const char *get_line_termination(GString *buf)
41d214f6 648{
329733d9 649 const char *term;
4a35548b 650
41d214f6
BV
651 term = NULL;
652 if (g_strstr_len(buf->str, buf->len, "\r\n"))
653 term = "\r\n";
654 else if (memchr(buf->str, '\n', buf->len))
655 term = "\n";
656 else if (memchr(buf->str, '\r', buf->len))
657 term = "\r";
4a35548b 658
41d214f6
BV
659 return term;
660}
4a35548b 661
41d214f6
BV
662static int initial_parse(const struct sr_input *in, GString *buf)
663{
664 struct context *inc;
41d214f6 665 GString *channel_name;
e53f32d2
GS
666 size_t num_columns, ch_idx, ch_name_idx, col_idx, col_nr;
667 size_t line_number, line_idx;
41d214f6 668 int ret;
df0db9fd 669 char **lines, *line, **columns, *column;
f6dcb320
GS
670 const char *col_caption;
671 gboolean got_caption;
e53f32d2 672 const struct column_details *detail;
41d214f6
BV
673
674 ret = SR_OK;
675 inc = in->priv;
676 columns = NULL;
677
678 line_number = 0;
492dfa90 679 lines = g_strsplit_set(buf->str, delim_set, 0);
e53f32d2 680 for (line_idx = 0; (line = lines[line_idx]); line_idx++) {
41d214f6
BV
681 line_number++;
682 if (inc->start_line > line_number) {
e53f32d2 683 sr_spew("Line %zu skipped (before start).", line_number);
4a35548b
MS
684 continue;
685 }
df0db9fd 686 if (line[0] == '\0') {
41d214f6
BV
687 sr_spew("Blank line %zu skipped.", line_number);
688 continue;
689 }
df0db9fd
GS
690 strip_comment(line, inc->comment);
691 if (line[0] == '\0') {
41d214f6 692 sr_spew("Comment-only line %zu skipped.", line_number);
4a35548b
MS
693 continue;
694 }
695
41d214f6
BV
696 /* Reached first proper line. */
697 break;
698 }
e53f32d2 699 if (!line) {
41d214f6 700 /* Not enough data for a proper line yet. */
60107497 701 ret = SR_ERR_NA;
41d214f6 702 goto out;
4a35548b
MS
703 }
704
e53f32d2
GS
705 /* See how many columns the current line has. */
706 columns = split_line(line, inc);
df0db9fd 707 if (!columns) {
41d214f6
BV
708 sr_err("Error while parsing line %zu.", line_number);
709 ret = SR_ERR;
710 goto out;
4a35548b 711 }
4a35548b 712 num_columns = g_strv_length(columns);
4a35548b 713 if (!num_columns) {
e53f32d2 714 sr_err("Error while parsing line %zu.", line_number);
41d214f6
BV
715 ret = SR_ERR;
716 goto out;
4a35548b 717 }
e53f32d2
GS
718 sr_dbg("DIAG Got %zu columns in text line: %s.", num_columns, line);
719
720 /* Optionally update incomplete multi-column specs. */
721 if (inc->multi_column_mode && !inc->num_channels) {
722 inc->num_channels = num_columns - inc->first_column + 1;
723 sr_dbg("DIAG -> multi-column update: columns %zu-%zu, 1 bit each.",
724 inc->first_column,
725 inc->first_column + inc->num_channels - 1);
726 ret = make_column_details_multi(inc, inc->first_column,
727 inc->first_column + inc->num_channels - 1);
728 if (ret != SR_OK)
41d214f6 729 goto out;
4a35548b
MS
730 }
731
e53f32d2
GS
732 /*
733 * Assume all lines have equal length (column count). Bail out
734 * early on suspicious or insufficient input data (check input
735 * which became available here against previous user specs or
736 * auto-determined properties, regardless of layout variant).
737 */
738 if (num_columns < inc->column_want_count) {
739 sr_err("Insufficient input text width for desired data amount, got %zu but want %zu columns.",
740 num_columns, inc->column_want_count);
741 ret = SR_ERR;
742 goto out;
743 }
744
745 /*
746 * Determine channel names. Optionally use text from a header
747 * line (when requested by the user, and only works in multi
748 * column mode). In the absence of header text, or in single
749 * column mode, channels are assigned rather generic names.
f6dcb320
GS
750 *
751 * Manipulation of the column's caption is acceptable here, the
752 * header line will never get processed another time.
e53f32d2 753 */
41d214f6 754 channel_name = g_string_sized_new(64);
e53f32d2 755 for (col_idx = 0; col_idx < inc->column_want_count; col_idx++) {
f6dcb320 756
e53f32d2
GS
757 col_nr = col_idx + 1;
758 detail = lookup_column_details(inc, col_nr);
759 if (detail->text_format == FORMAT_NONE)
760 continue;
761 column = columns[col_idx];
f6dcb320
GS
762 col_caption = sr_scpi_unquote_string(column);
763 got_caption = inc->use_header && *col_caption;
e53f32d2 764 sr_dbg("DIAG col %zu, ch count %zu, text %s.",
f6dcb320 765 col_nr, detail->channel_count, col_caption);
e53f32d2
GS
766 for (ch_idx = 0; ch_idx < detail->channel_count; ch_idx++) {
767 ch_name_idx = detail->channel_offset + ch_idx;
f6dcb320
GS
768 if (got_caption && detail->channel_count == 1)
769 g_string_assign(channel_name, col_caption);
770 else if (got_caption)
771 g_string_printf(channel_name, "%s[%zu]",
772 col_caption, ch_idx);
e53f32d2
GS
773 else
774 g_string_printf(channel_name, "%zu", ch_name_idx);
775 sr_dbg("DIAG ch idx %zu, name %s.", ch_name_idx, channel_name->str);
776 sr_channel_new(in->sdi, ch_name_idx, SR_CHANNEL_LOGIC, TRUE,
777 channel_name->str);
778 }
4a35548b 779 }
41d214f6 780 g_string_free(channel_name, TRUE);
affaf540
GS
781 if (!check_header_in_reread(in)) {
782 ret = SR_ERR_DATA;
783 goto out;
784 }
4a35548b
MS
785
786 /*
cd59e6ec
GS
787 * Calculate the minimum buffer size to store the set of samples
788 * of all channels (unit size). Determine a larger buffer size
789 * for datafeed submission that is a multiple of the unit size.
626c388a
GS
790 * Allocate the larger buffer, the "sample buffer" will point
791 * to a location within that large buffer later.
4a35548b 792 */
cd59e6ec 793 inc->sample_unit_size = (inc->num_channels + 7) / 8;
8bc2fa6d 794 inc->datafeed_buf_size = CHUNK_SIZE;
cd59e6ec
GS
795 inc->datafeed_buf_size *= inc->sample_unit_size;
796 inc->datafeed_buffer = g_malloc(inc->datafeed_buf_size);
797 inc->datafeed_buf_fill = 0;
4a35548b 798
41d214f6
BV
799out:
800 if (columns)
801 g_strfreev(columns);
802 g_strfreev(lines);
4a35548b 803
41d214f6 804 return ret;
4a35548b
MS
805}
806
4439363a
GS
807/*
808 * Gets called from initial_receive(), which runs until the end-of-line
809 * encoding of the input stream could get determined. Assumes that this
810 * routine receives enough buffered initial input data to either see the
811 * BOM when there is one, or that no BOM will follow when a text line
812 * termination sequence was seen. Silently drops the UTF-8 BOM sequence
813 * from the input buffer if one was seen. Does not care to protect
814 * against multiple execution or dropping the BOM multiple times --
815 * there should be at most one in the input stream.
816 */
817static void initial_bom_check(const struct sr_input *in)
818{
819 static const char *utf8_bom = "\xef\xbb\xbf";
820
821 if (in->buf->len < strlen(utf8_bom))
822 return;
823 if (strncmp(in->buf->str, utf8_bom, strlen(utf8_bom)) != 0)
824 return;
825 g_string_erase(in->buf, 0, strlen(utf8_bom));
826}
827
41d214f6 828static int initial_receive(const struct sr_input *in)
4a35548b 829{
41d214f6
BV
830 struct context *inc;
831 GString *new_buf;
832 int len, ret;
329733d9
UH
833 char *p;
834 const char *termination;
4a35548b 835
4439363a
GS
836 initial_bom_check(in);
837
41d214f6 838 inc = in->priv;
4a35548b 839
df0db9fd
GS
840 termination = get_line_termination(in->buf);
841 if (!termination)
41d214f6 842 /* Don't have a full line yet. */
d0181813 843 return SR_ERR_NA;
4a35548b 844
df0db9fd
GS
845 p = g_strrstr_len(in->buf->str, in->buf->len, termination);
846 if (!p)
41d214f6 847 /* Don't have a full line yet. */
d0181813 848 return SR_ERR_NA;
41d214f6
BV
849 len = p - in->buf->str - 1;
850 new_buf = g_string_new_len(in->buf->str, len);
851 g_string_append_c(new_buf, '\0');
4a35548b 852
41d214f6
BV
853 inc->termination = g_strdup(termination);
854
855 if (in->buf->str[0] != '\0')
856 ret = initial_parse(in, new_buf);
857 else
858 ret = SR_OK;
859
860 g_string_free(new_buf, TRUE);
861
862 return ret;
863}
864
7f4c3a62 865static int process_buffer(struct sr_input *in, gboolean is_eof)
41d214f6 866{
41d214f6
BV
867 struct context *inc;
868 gsize num_columns;
e53f32d2 869 size_t line_idx, col_idx, col_nr;
ad6a2bee 870 int ret;
e53f32d2 871 char *p, **lines, *line, **columns, *column;
41d214f6 872
41d214f6 873 inc = in->priv;
d0181813 874 if (!inc->started) {
bee2b016 875 std_session_send_df_header(in->sdi);
d0181813 876 inc->started = TRUE;
4a35548b
MS
877 }
878
4555d3bd
GS
879 /*
880 * Consider empty input non-fatal. Keep accumulating input until
881 * at least one full text line has become available. Grab the
882 * maximum amount of accumulated data that consists of full text
883 * lines, and process what has been received so far, leaving not
884 * yet complete lines for the next invocation.
7f4c3a62
GS
885 *
886 * Enforce that all previously buffered data gets processed in
887 * the "EOF" condition. Do not insist in the presence of the
888 * termination sequence for the last line (may often be missing
889 * on Windows). A present termination sequence will just result
890 * in the "execution of an empty line", and does not harm.
4555d3bd
GS
891 */
892 if (!in->buf->len)
893 return SR_OK;
7f4c3a62
GS
894 if (is_eof) {
895 p = in->buf->str + in->buf->len;
896 } else {
897 p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination);
898 if (!p)
899 return SR_ERR;
900 *p = '\0';
901 p += strlen(inc->termination);
902 }
41d214f6 903 g_strstrip(in->buf->str);
4a35548b 904
18078d05 905 ret = SR_OK;
492dfa90 906 lines = g_strsplit_set(in->buf->str, delim_set, 0);
e53f32d2 907 for (line_idx = 0; (line = lines[line_idx]); line_idx++) {
41d214f6 908 inc->line_number++;
df0db9fd 909 if (line[0] == '\0') {
41d214f6 910 sr_spew("Blank line %zu skipped.", inc->line_number);
4a35548b
MS
911 continue;
912 }
913
914 /* Remove trailing comment. */
df0db9fd
GS
915 strip_comment(line, inc->comment);
916 if (line[0] == '\0') {
41d214f6 917 sr_spew("Comment-only line %zu skipped.", inc->line_number);
4a35548b
MS
918 continue;
919 }
920
160691b9 921 /* Skip the header line, its content was used as the channel names. */
de8fe3b5 922 if (inc->use_header && !inc->header_seen) {
160691b9 923 sr_spew("Header line %zu skipped.", inc->line_number);
de8fe3b5 924 inc->header_seen = TRUE;
160691b9
JS
925 continue;
926 }
927
e53f32d2
GS
928 /* Split the line into columns, check for minimum length. */
929 columns = split_line(line, inc);
df0db9fd 930 if (!columns) {
41d214f6 931 sr_err("Error while parsing line %zu.", inc->line_number);
2355d229 932 g_strfreev(lines);
4a35548b
MS
933 return SR_ERR;
934 }
4a35548b 935 num_columns = g_strv_length(columns);
e53f32d2
GS
936 if (num_columns < inc->column_want_count) {
937 sr_err("Insufficient column count %zu in line %zu.",
938 num_columns, inc->line_number);
4a35548b 939 g_strfreev(columns);
2355d229 940 g_strfreev(lines);
4a35548b
MS
941 return SR_ERR;
942 }
943
626c388a
GS
944 clear_logic_samples(inc);
945
e53f32d2
GS
946 for (col_idx = 0; col_idx < inc->column_want_count; col_idx++) {
947 column = columns[col_idx];
948 col_nr = col_idx + 1;
949 ret = parse_column(column, inc, col_nr);
950 if (ret != SR_OK) {
951 g_strfreev(columns);
952 g_strfreev(lines);
953 return SR_ERR;
954 }
4a35548b
MS
955 }
956
626c388a
GS
957 /* Send sample data to the session bus (buffered). */
958 ret = queue_logic_samples(in);
41d214f6 959 if (ret != SR_OK) {
4a35548b 960 sr_err("Sending samples failed.");
cd59e6ec 961 g_strfreev(columns);
2355d229 962 g_strfreev(lines);
4a35548b
MS
963 return SR_ERR;
964 }
cd59e6ec 965
41d214f6
BV
966 g_strfreev(columns);
967 }
968 g_strfreev(lines);
241c386a 969 g_string_erase(in->buf, 0, p - in->buf->str);
41d214f6 970
7066fd46 971 return ret;
41d214f6
BV
972}
973
7066fd46 974static int receive(struct sr_input *in, GString *buf)
41d214f6
BV
975{
976 struct context *inc;
7066fd46
BV
977 int ret;
978
979 g_string_append_len(in->buf, buf->str, buf->len);
41d214f6
BV
980
981 inc = in->priv;
7066fd46 982 if (!inc->termination) {
df0db9fd
GS
983 ret = initial_receive(in);
984 if (ret == SR_ERR_NA)
7066fd46
BV
985 /* Not enough data yet. */
986 return SR_OK;
987 else if (ret != SR_OK)
988 return SR_ERR;
989
990 /* sdi is ready, notify frontend. */
991 in->sdi_ready = TRUE;
41d214f6 992 return SR_OK;
7066fd46
BV
993 }
994
7f4c3a62 995 ret = process_buffer(in, FALSE);
7066fd46
BV
996
997 return ret;
998}
999
1000static int end(struct sr_input *in)
1001{
1002 struct context *inc;
7066fd46 1003 int ret;
41d214f6 1004
7066fd46 1005 if (in->sdi_ready)
7f4c3a62 1006 ret = process_buffer(in, TRUE);
7066fd46
BV
1007 else
1008 ret = SR_OK;
cd59e6ec
GS
1009 if (ret != SR_OK)
1010 return ret;
1011
626c388a 1012 ret = flush_logic_samples(in);
cd59e6ec
GS
1013 if (ret != SR_OK)
1014 return ret;
7066fd46
BV
1015
1016 inc = in->priv;
3be42bc2 1017 if (inc->started)
bee2b016 1018 std_session_send_df_end(in->sdi);
4a35548b 1019
7066fd46
BV
1020 return ret;
1021}
1022
d5cc282f 1023static void cleanup(struct sr_input *in)
7066fd46
BV
1024{
1025 struct context *inc;
1026
affaf540
GS
1027 keep_header_for_reread(in);
1028
7066fd46
BV
1029 inc = in->priv;
1030
b1f83103 1031 g_free(inc->termination);
539188e5 1032 inc->termination = NULL;
cd59e6ec 1033 g_free(inc->datafeed_buffer);
539188e5 1034 inc->datafeed_buffer = NULL;
4a35548b
MS
1035}
1036
ad93bfb0
SA
1037static int reset(struct sr_input *in)
1038{
1039 struct context *inc = in->priv;
1040
1041 cleanup(in);
1042 inc->started = FALSE;
1043 g_string_truncate(in->buf, 0);
1044
1045 return SR_OK;
1046}
1047
c6aa9870
GS
1048enum option_index {
1049 OPT_SINGLE_COL,
1050 OPT_NUM_LOGIC,
1051 OPT_DELIM,
1052 OPT_FORMAT,
1053 OPT_COMMENT,
1054 OPT_RATE,
e53f32d2 1055 OPT_FIRST_COL,
c6aa9870
GS
1056 OPT_HEADER,
1057 OPT_START,
1058 OPT_MAX,
1059};
1060
41d214f6 1061static struct sr_option options[] = {
c6aa9870
GS
1062 [OPT_SINGLE_COL] = { "single-column", "Single column", "Enable single-column mode, using the specified column (>= 1); 0: multi-col. mode", NULL, NULL },
1063 [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 },
1064 [OPT_DELIM] = { "delimiter", "Column delimiter", "The column delimiter (>= 1 characters)", NULL, NULL },
1065 [OPT_FORMAT] = { "format", "Data format (single-col. mode)", "The numeric format of the data (single-col. mode): bin, hex, oct", NULL, NULL },
1066 [OPT_COMMENT] = { "comment", "Comment character(s)", "The comment prefix character(s)", NULL, NULL },
1067 [OPT_RATE] = { "samplerate", "Samplerate (Hz)", "The sample rate (used during capture) in Hz", NULL, NULL },
e53f32d2 1068 [OPT_FIRST_COL] = { "first-column", "First column", "The column number of the first channel (multi-col. mode)", NULL, NULL },
c6aa9870
GS
1069 [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 },
1070 [OPT_START] = { "startline", "Start line", "The line number at which to start processing samples (>= 1)", NULL, NULL },
1071 [OPT_MAX] = ALL_ZERO,
41d214f6
BV
1072};
1073
2c240774 1074static const struct sr_option *get_options(void)
41d214f6 1075{
31c41782
UH
1076 GSList *l;
1077
41d214f6 1078 if (!options[0].def) {
e53f32d2
GS
1079 options[OPT_SINGLE_COL].def = g_variant_ref_sink(g_variant_new_uint32(0));
1080 options[OPT_NUM_LOGIC].def = g_variant_ref_sink(g_variant_new_uint32(0));
c6aa9870
GS
1081 options[OPT_DELIM].def = g_variant_ref_sink(g_variant_new_string(","));
1082 options[OPT_FORMAT].def = g_variant_ref_sink(g_variant_new_string("bin"));
31c41782
UH
1083 l = NULL;
1084 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("bin")));
1085 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("hex")));
1086 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("oct")));
c6aa9870
GS
1087 options[OPT_FORMAT].values = l;
1088 options[OPT_COMMENT].def = g_variant_ref_sink(g_variant_new_string(";"));
1089 options[OPT_RATE].def = g_variant_ref_sink(g_variant_new_uint64(0));
e53f32d2 1090 options[OPT_FIRST_COL].def = g_variant_ref_sink(g_variant_new_uint32(1));
c6aa9870 1091 options[OPT_HEADER].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
e53f32d2 1092 options[OPT_START].def = g_variant_ref_sink(g_variant_new_uint32(1));
41d214f6
BV
1093 }
1094
1095 return options;
1096}
1097
d4c93774 1098SR_PRIV struct sr_input_module input_csv = {
4a35548b 1099 .id = "csv",
41d214f6
BV
1100 .name = "CSV",
1101 .desc = "Comma-separated values",
c7bc82ff 1102 .exts = (const char*[]){"csv", NULL},
41d214f6 1103 .options = get_options,
4a35548b 1104 .init = init,
41d214f6 1105 .receive = receive,
7066fd46 1106 .end = end,
41d214f6 1107 .cleanup = cleanup,
ad93bfb0 1108 .reset = reset,
4a35548b 1109};