]> sigrok.org Git - libsigrok.git/blame - src/input/csv.c
input/csv: accept user provided analog resolution in column formats
[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 *
72903e9d
GS
38 * column_formats: Specifies the data formats and channel counts for the
39 * input file's text columns. Accepts a comma separated list of tuples
40 * with: an optional column repeat count ('*' as a wildcard meaning
41 * "all remaining columns", only applicable to the last field), a format
42 * specifying character ('x' hexadecimal, 'o' octal, 'b' binary, 'l'
43 * single-bit logic), and an optional bit count (translating to: logic
44 * channels communicated in that column). This "column_formats" option
45 * is most versatile, other forms of specifying the column layout only
46 * exist for backwards compatibility.
4a35548b 47 *
72903e9d
GS
48 * single_column: Specifies the column number which contains the logic data
49 * for single-column mode. All logic data is taken from several bits
50 * which all are kept within that one column. Only exists for backwards
51 * compatibility, see "column_formats" for more flexibility.
4a35548b 52 *
72903e9d
GS
53 * first_column: Specifies the number of the first column with logic data
54 * in simple multi-column mode. Only exists for backwards compatibility,
55 * see "column_formats" for more flexibility.
4a35548b 56 *
72903e9d
GS
57 * logic_channels: Specifies the number of logic channels. Is required in
58 * simple single-column mode. Is optional in simple multi-column mode
59 * (and defaults to all remaining columns). Only exists for backwards
60 * compatibility, see "column_formats" for more flexibility.
4a35548b 61 *
72903e9d
GS
62 * single_format: Specifies the format of the input text in simple single-
63 * column mode. Available formats are: 'bin' (default), 'hex' and 'oct'.
64 * Simple multi-column mode always uses single-bit data per column.
65 * Only exists for backwards compatibility, see "column_formats" for
66 * more flexibility.
4a35548b 67 *
72903e9d
GS
68 * start_line: Specifies at which line to start processing the input file.
69 * Allows to skip leading lines which neither are header nor data lines.
70 * By default all of the input file gets processed.
4a35548b 71 *
72903e9d
GS
72 * header: Boolean option, controls whether the first processed line is used
73 * to determine channel names. Off by default. Generic channel names are
74 * used in the absence of header line content.
4a35548b 75 *
72903e9d
GS
76 * samplerate: Specifies the samplerate of the input data. Defaults to 0.
77 * User specs take precedence over data which optionally gets derived
78 * from input data.
4a35548b 79 *
72903e9d
GS
80 * column_separator: Specifies the sequence which separates the text file
81 * columns. Cannot be empty. Defaults to comma.
82 *
83 * comment_leader: Specifies the sequence which starts comments that run
84 * up to the end of the current text line. Can be empty to disable
85 * comment support. Defaults to semicolon.
86 *
87 * Typical examples of using these options:
88 * - ... -I csv:column_formats=*l ...
89 * All columns are single-bit logic data. Identical to the previous
90 * multi-column mode (the default when no options were given at all).
91 * - ... -I csv:column_formats=3-,*l ...
92 * Ignore the first three columns, get single-bit logic data from all
93 * remaining lines (multi-column mode with first-column above 1).
94 * - ... -I csv:column_formats=3-,4l,x8 ...
95 * Ignore the first three columns, get single-bit logic data from the
96 * next four columns, then eight-bit data in hex format from the next
97 * column. More columns may follow in the input text but won't get
98 * processed. (Mix of previous multi-column as well as single-column
99 * modes.)
100 * - ... -I csv:column_formats=4x8,b16,5l ...
101 * Get eight-bit data in hex format from the first four columns, then
102 * sixteen-bit data in binary format, then five times single-bit data.
103 * - ... -I csv:single_column=2:single_format=bin:logic_channels=8 ...
104 * Get eight logic bits in binary format from column 2. (Simple
105 * single-column mode, corresponds to the "-,b8" format.)
106 * - ... -I csv:first_column=6:logic_channels=4 ...
107 * Get four single-bit logic channels from columns 6 to 9 respectively.
108 * (Simple multi-column mode, corresponds to the "5-,4b" format.)
109 * - ... -I csv:start_line=20:header=yes:...
110 * Skip the first 19 text lines. Use line 20 to derive channel names.
111 * Data starts at line 21.
4a35548b
MS
112 */
113
ccff468b
GS
114/*
115 * TODO
116 *
43bdef26 117 * - Extend support for analog input data? (optional)
43bdef26
GS
118 * - Determine why analog samples of 'double' data type get scrambled
119 * in sigrok-cli screen output. Is analog.encoding->unitsize not
120 * handled properly? A sigrok-cli or libsigrok (src/output) issue?
5a971176
GS
121 * - Optionally get sample rate from timestamp column. Just best-effort
122 * approach, not necessarily reliable. Users can always specify rates.
123 * - Add a test suite for input modules in general, and CSV in specific?
124 * Becomes more important with the multitude of options and their
125 * interaction. Could cover edge cases (BOM presence, line termination
126 * absence, etc) and auto-stuff as well (channel names, channel counts,
127 * samplerates, etc).
ccff468b
GS
128 */
129
43bdef26
GS
130typedef float csv_analog_t; /* 'double' currently is flawed. */
131
4a35548b 132/* Single column formats. */
ad6a2bee 133enum single_col_format {
e53f32d2
GS
134 FORMAT_NONE, /* Ignore this column. */
135 FORMAT_BIN, /* Bin digits for a set of bits (or just one bit). */
136 FORMAT_HEX, /* Hex digits for a set of bits. */
137 FORMAT_OCT, /* Oct digits for a set of bits. */
43bdef26 138 FORMAT_ANALOG, /* Floating point number for an analog channel. */
e53f32d2
GS
139};
140
141static const char *col_format_text[] = {
142 [FORMAT_NONE] = "unknown",
143 [FORMAT_BIN] = "binary",
144 [FORMAT_HEX] = "hexadecimal",
145 [FORMAT_OCT] = "octal",
43bdef26 146 [FORMAT_ANALOG] = "analog",
e53f32d2
GS
147};
148
1a920e33
GS
149static const char col_format_char[] = {
150 [FORMAT_NONE] = '?',
151 [FORMAT_BIN] = 'b',
152 [FORMAT_HEX] = 'x',
153 [FORMAT_OCT] = 'o',
43bdef26 154 [FORMAT_ANALOG] = 'a',
1a920e33
GS
155};
156
e53f32d2
GS
157struct column_details {
158 size_t col_nr;
159 enum single_col_format text_format;
160 size_t channel_offset;
161 size_t channel_count;
a267bf45 162 int analog_digits;
4a35548b
MS
163};
164
165struct context {
41d214f6
BV
166 gboolean started;
167
4a35548b
MS
168 /* Current selected samplerate. */
169 uint64_t samplerate;
246aca5f 170 gboolean samplerate_sent;
4a35548b 171
a267bf45 172 /* Number of channels. */
836fac9c 173 size_t logic_channels;
43bdef26 174 size_t analog_channels;
4a35548b 175
836fac9c 176 /* Column delimiter (actually separator), comment leader, EOL sequence. */
4a35548b 177 GString *delimiter;
4a35548b 178 GString *comment;
41d214f6
BV
179 char *termination;
180
1a920e33
GS
181 /* Format specs for input columns, and processing state. */
182 size_t column_seen_count;
183 const char *column_formats;
e53f32d2
GS
184 size_t column_want_count;
185 struct column_details *column_details;
186
4a35548b 187 /* Line number to start processing. */
6433156c 188 size_t start_line;
4a35548b
MS
189
190 /*
191 * Determines if the first line should be treated as header and used for
ba7dd8bb 192 * channel names in multi column mode.
4a35548b 193 */
de8fe3b5
GS
194 gboolean use_header;
195 gboolean header_seen;
4a35548b 196
cd59e6ec
GS
197 size_t sample_unit_size; /**!< Byte count for a single sample. */
198 uint8_t *sample_buffer; /**!< Buffer for a single sample. */
43bdef26 199 csv_analog_t *analog_sample_buffer; /**!< Buffer for one set of analog values. */
4a35548b 200
cd59e6ec
GS
201 uint8_t *datafeed_buffer; /**!< Queue for datafeed submission. */
202 size_t datafeed_buf_size;
203 size_t datafeed_buf_fill;
43bdef26
GS
204 /* "Striped" layout, M samples for N channels each. */
205 csv_analog_t *analog_datafeed_buffer; /**!< Queue for analog datafeed. */
206 size_t analog_datafeed_buf_size;
207 size_t analog_datafeed_buf_fill;
a267bf45
GS
208 GSList **analog_datafeed_channels;
209 int *analog_datafeed_digits;
4a35548b 210
4a35548b 211 /* Current line number. */
6433156c 212 size_t line_number;
affaf540
GS
213
214 /* List of previously created sigrok channels. */
215 GSList *prev_sr_channels;
4a35548b
MS
216};
217
626c388a
GS
218/*
219 * Primitive operations to handle sample sets:
220 * - Keep a buffer for datafeed submission, capable of holding many
221 * samples (reduces call overhead, improves throughput).
222 * - Have a "current sample set" pointer reference one position in that
223 * large samples buffer.
224 * - Clear the current sample set before text line inspection, then set
225 * the bits which are found active in the current line of text input.
226 * Phrase the API such that call sites can be kept simple. Advance to
227 * the next sample set between lines, flush the larger buffer as needed
228 * (when it is full, or upon EOF).
229 */
230
43bdef26
GS
231static int flush_samplerate(const struct sr_input *in)
232{
233 struct context *inc;
234 struct sr_datafeed_packet packet;
235 struct sr_datafeed_meta meta;
236 struct sr_config *src;
237
238 inc = in->priv;
239 if (inc->samplerate && !inc->samplerate_sent) {
240 packet.type = SR_DF_META;
241 packet.payload = &meta;
242 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(inc->samplerate));
243 meta.config = g_slist_append(NULL, src);
244 sr_session_send(in->sdi, &packet);
245 g_slist_free(meta.config);
246 sr_config_free(src);
247 inc->samplerate_sent = TRUE;
248 }
249
250 return SR_OK;
251}
252
626c388a
GS
253static void clear_logic_samples(struct context *inc)
254{
43bdef26
GS
255 if (!inc->logic_channels)
256 return;
626c388a
GS
257 inc->sample_buffer = &inc->datafeed_buffer[inc->datafeed_buf_fill];
258 memset(inc->sample_buffer, 0, inc->sample_unit_size);
259}
260
261static void set_logic_level(struct context *inc, size_t ch_idx, int on)
262{
263 size_t byte_idx, bit_idx;
264 uint8_t bit_mask;
265
836fac9c 266 if (ch_idx >= inc->logic_channels)
626c388a
GS
267 return;
268 if (!on)
269 return;
270
271 byte_idx = ch_idx / 8;
272 bit_idx = ch_idx % 8;
273 bit_mask = 1 << bit_idx;
274 inc->sample_buffer[byte_idx] |= bit_mask;
275}
276
277static int flush_logic_samples(const struct sr_input *in)
278{
279 struct context *inc;
280 struct sr_datafeed_packet packet;
281 struct sr_datafeed_logic logic;
282 int rc;
283
284 inc = in->priv;
285 if (!inc->datafeed_buf_fill)
286 return SR_OK;
287
43bdef26
GS
288 rc = flush_samplerate(in);
289 if (rc != SR_OK)
290 return rc;
246aca5f 291
626c388a
GS
292 memset(&packet, 0, sizeof(packet));
293 memset(&logic, 0, sizeof(logic));
294 packet.type = SR_DF_LOGIC;
295 packet.payload = &logic;
296 logic.unitsize = inc->sample_unit_size;
297 logic.length = inc->datafeed_buf_fill;
298 logic.data = inc->datafeed_buffer;
299
300 rc = sr_session_send(in->sdi, &packet);
301 if (rc != SR_OK)
302 return rc;
303
304 inc->datafeed_buf_fill = 0;
305 return SR_OK;
306}
307
308static int queue_logic_samples(const struct sr_input *in)
309{
310 struct context *inc;
311 int rc;
312
313 inc = in->priv;
836fac9c
GS
314 if (!inc->logic_channels)
315 return SR_OK;
626c388a
GS
316
317 inc->datafeed_buf_fill += inc->sample_unit_size;
318 if (inc->datafeed_buf_fill == inc->datafeed_buf_size) {
319 rc = flush_logic_samples(in);
320 if (rc != SR_OK)
321 return rc;
322 }
323 return SR_OK;
324}
325
43bdef26
GS
326static void set_analog_value(struct context *inc, size_t ch_idx, csv_analog_t value);
327
328static void clear_analog_samples(struct context *inc)
329{
330 size_t idx;
331
332 if (!inc->analog_channels)
333 return;
334 inc->analog_sample_buffer = &inc->analog_datafeed_buffer[inc->analog_datafeed_buf_fill];
335 for (idx = 0; idx < inc->analog_channels; idx++)
336 set_analog_value(inc, idx, 0.0);
337}
338
339static void set_analog_value(struct context *inc, size_t ch_idx, csv_analog_t value)
340{
341 if (ch_idx >= inc->analog_channels)
342 return;
343 if (!value)
344 return;
345 inc->analog_sample_buffer[ch_idx * inc->analog_datafeed_buf_size] = value;
346}
347
348static int flush_analog_samples(const struct sr_input *in)
349{
43bdef26
GS
350 struct context *inc;
351 struct sr_datafeed_packet packet;
352 struct sr_datafeed_analog analog;
353 struct sr_analog_encoding encoding;
354 struct sr_analog_meaning meaning;
355 struct sr_analog_spec spec;
356 csv_analog_t *samples;
357 size_t ch_idx;
a267bf45 358 int digits;
43bdef26
GS
359 int rc;
360
361 inc = in->priv;
362 if (!inc->analog_datafeed_buf_fill)
363 return SR_OK;
364
365 rc = flush_samplerate(in);
366 if (rc != SR_OK)
367 return rc;
368
369 samples = inc->analog_datafeed_buffer;
370 for (ch_idx = 0; ch_idx < inc->analog_channels; ch_idx++) {
a267bf45 371 digits = inc->analog_datafeed_digits[ch_idx];
43bdef26
GS
372 sr_analog_init(&analog, &encoding, &meaning, &spec, digits);
373 memset(&packet, 0, sizeof(packet));
374 packet.type = SR_DF_ANALOG;
375 packet.payload = &analog;
376 analog.num_samples = inc->analog_datafeed_buf_fill;
377 analog.data = samples;
378 analog.meaning->channels = inc->analog_datafeed_channels[ch_idx];
379 analog.meaning->mq = 0;
380 analog.meaning->mqflags = 0;
381 analog.meaning->unit = 0;
382 analog.encoding->unitsize = sizeof(samples[0]);
383 analog.encoding->is_signed = TRUE;
384 analog.encoding->is_float = TRUE;
385#ifdef WORDS_BIGENDIAN
386 analog.encoding->is_bigendian = TRUE;
387#else
388 analog.encoding->is_bigendian = FALSE;
389#endif
390 analog.encoding->digits = spec.spec_digits;
391 rc = sr_session_send(in->sdi, &packet);
392 if (rc != SR_OK)
393 return rc;
394 samples += inc->analog_datafeed_buf_size;
395 }
396
397 inc->analog_datafeed_buf_fill = 0;
398 return SR_OK;
399}
400
401static int queue_analog_samples(const struct sr_input *in)
402{
403 struct context *inc;
404 int rc;
405
406 inc = in->priv;
407 if (!inc->analog_channels)
408 return SR_OK;
409
410 inc->analog_datafeed_buf_fill++;
411 if (inc->analog_datafeed_buf_fill == inc->analog_datafeed_buf_size) {
412 rc = flush_analog_samples(in);
413 if (rc != SR_OK)
414 return rc;
415 }
416 return SR_OK;
417}
418
2142a79b
GS
419/* Helpers for "column processing". */
420
421static int split_column_format(const char *spec,
422 size_t *column_count, enum single_col_format *format, size_t *bit_count)
423{
424 size_t count;
425 char *endp, format_char;
426 enum single_col_format format_code;
427
428 if (!spec || !*spec)
429 return SR_ERR_ARG;
430
1a920e33 431 /* Get the (optional, decimal, default 1) column count. Accept '*'. */
2142a79b 432 endp = NULL;
1a920e33 433 if (*spec == '*') {
5ada72fc 434 /* Workaround, strtoul("*") won't always yield expected endp. */
1a920e33
GS
435 count = 0;
436 endp = (char *)&spec[1];
437 } else {
438 count = strtoul(spec, &endp, 10);
439 }
2142a79b
GS
440 if (!endp)
441 return SR_ERR_ARG;
442 if (endp == spec)
443 count = 1;
444 if (column_count)
445 *column_count = count;
446 spec = endp;
447
448 /* Get the (mandatory, single letter) type spec (-/xob/l). */
449 format_char = *spec++;
450 switch (format_char) {
5ada72fc 451 case '-':
2142a79b
GS
452 case '/':
453 format_char = '-';
454 format_code = FORMAT_NONE;
455 break;
456 case 'x':
457 format_code = FORMAT_HEX;
458 break;
459 case 'o':
460 format_code = FORMAT_OCT;
461 break;
462 case 'b':
463 case 'l':
464 format_code = FORMAT_BIN;
465 break;
43bdef26
GS
466 case 'a':
467 format_code = FORMAT_ANALOG;
468 break;
2142a79b
GS
469 default: /* includes NUL */
470 return SR_ERR_ARG;
471 }
472 if (format)
473 *format = format_code;
474
475 /* Get the (optional, decimal, default 1) bit count. */
476 endp = NULL;
477 count = strtoul(spec, &endp, 10);
478 if (!endp)
479 return SR_ERR_ARG;
480 if (endp == spec)
a267bf45 481 count = (format_code == FORMAT_ANALOG) ? 3 : 1;
43bdef26 482 if (!format_code)
2142a79b
GS
483 count = 0;
484 if (format_char == 'l')
485 count = 1;
486 if (bit_count)
487 *bit_count = count;
488 spec = endp;
489
490 /* Input spec must have been exhausted. */
491 if (*spec)
492 return SR_ERR_ARG;
493
494 return SR_OK;
495}
496
9e7af34e
GS
497static int make_column_details_from_format(const struct sr_input *in,
498 const char *column_format, char **column_texts)
2142a79b 499{
9e7af34e 500 struct context *inc;
2142a79b 501 char **formats, *format;
43bdef26 502 size_t format_count, column_count, logic_count, analog_count;
1a920e33 503 size_t auto_column_count;
43bdef26 504 size_t format_idx, c, b, column_idx, channel_idx, analog_idx;
2142a79b
GS
505 enum single_col_format f;
506 struct column_details *detail;
9e7af34e
GS
507 GString *channel_name;
508 size_t create_idx;
509 char *column;
510 const char *caption;
43bdef26 511 int channel_type, channel_sdi_nr;
2142a79b
GS
512 int ret;
513
9e7af34e
GS
514 inc = in->priv;
515 inc->column_seen_count = g_strv_length(column_texts);
516
2142a79b
GS
517 /* Split the input spec, count involved columns and bits. */
518 formats = g_strsplit(column_format, ",", 0);
519 if (!formats) {
520 sr_err("Cannot parse columns format %s (comma split).", column_format);
521 return SR_ERR_ARG;
522 }
523 format_count = g_strv_length(formats);
524 if (!format_count) {
525 sr_err("Cannot parse columns format %s (field count).", column_format);
526 g_strfreev(formats);
527 return SR_ERR_ARG;
528 }
43bdef26 529 column_count = logic_count = analog_count = 0;
1a920e33 530 auto_column_count = 0;
2142a79b
GS
531 for (format_idx = 0; format_idx < format_count; format_idx++) {
532 format = formats[format_idx];
533 ret = split_column_format(format, &c, &f, &b);
534 sr_dbg("fmt %s -> %zu cols, %s fmt, %zu bits, rc %d", format, c, col_format_text[f], b, ret);
535 if (ret != SR_OK) {
536 sr_err("Cannot parse columns format %s (field split, %s).", column_format, format);
537 g_strfreev(formats);
538 return SR_ERR_ARG;
539 }
1a920e33
GS
540 if (f && !c) {
541 /* User requested "auto-count", must be last format. */
542 if (formats[format_idx + 1]) {
543 sr_err("Auto column count must be last format field.");
544 g_strfreev(formats);
545 return SR_ERR_ARG;
546 }
547 auto_column_count = inc->column_seen_count - column_count;
548 c = auto_column_count;
549 }
2142a79b 550 column_count += c;
43bdef26
GS
551 if (f == FORMAT_ANALOG)
552 analog_count += c;
553 else if (f)
554 logic_count += c * b;
2142a79b 555 }
43bdef26
GS
556 sr_dbg("Column format %s -> %zu columns, %zu logic, %zu analog channels.",
557 column_format, column_count, logic_count, analog_count);
2142a79b 558
9e7af34e 559 /* Allocate and fill in "column processing" details. Create channels. */
2142a79b 560 inc->column_want_count = column_count;
9e7af34e
GS
561 if (inc->column_seen_count < inc->column_want_count) {
562 sr_err("Insufficient input text width for desired data amount, got %zu but want %zu columns.",
563 inc->column_seen_count, inc->column_want_count);
564 g_strfreev(formats);
565 return SR_ERR_ARG;
566 }
2142a79b 567 inc->column_details = g_malloc0_n(column_count, sizeof(inc->column_details[0]));
43bdef26 568 column_idx = channel_idx = analog_idx = 0;
9e7af34e 569 channel_name = g_string_sized_new(64);
2142a79b 570 for (format_idx = 0; format_idx < format_count; format_idx++) {
9e7af34e 571 /* Process a format field, which can span multiple columns. */
2142a79b
GS
572 format = formats[format_idx];
573 (void)split_column_format(format, &c, &f, &b);
1a920e33
GS
574 if (f && !c)
575 c = auto_column_count;
2142a79b 576 while (c-- > 0) {
9e7af34e 577 /* Fill in a column's processing details. */
2142a79b
GS
578 detail = &inc->column_details[column_idx++];
579 detail->col_nr = column_idx;
580 detail->text_format = f;
43bdef26
GS
581 if (detail->text_format == FORMAT_ANALOG) {
582 detail->channel_offset = analog_idx;
583 detail->channel_count = 1;
a267bf45 584 detail->analog_digits = b;
43bdef26
GS
585 analog_idx += detail->channel_count;
586 } else if (detail->text_format) {
2142a79b
GS
587 detail->channel_offset = channel_idx;
588 detail->channel_count = b;
43bdef26 589 channel_idx += detail->channel_count;
2142a79b
GS
590 }
591 sr_dbg("detail -> col %zu, fmt %s, ch off/cnt %zu/%zu",
592 detail->col_nr, col_format_text[detail->text_format],
593 detail->channel_offset, detail->channel_count);
9e7af34e
GS
594 if (!detail->text_format)
595 continue;
596 /*
597 * Create channels with appropriate names. Optionally
598 * use text from a header line (when requested by the
599 * user). In the absence of header text, channels are
600 * assigned rather generic names.
601 *
602 * Manipulation of the column's caption (when a header
603 * line is seen) is acceptable, because this header
604 * line won't get processed another time.
605 */
606 column = column_texts[detail->col_nr - 1];
607 if (inc->use_header && column && *column)
608 caption = sr_scpi_unquote_string(column);
609 else
610 caption = NULL;
611 if (!caption || !*caption)
612 caption = NULL;
613 for (create_idx = 0; create_idx < detail->channel_count; create_idx++) {
614 if (caption && detail->channel_count == 1) {
615 g_string_assign(channel_name, caption);
616 } else if (caption) {
617 g_string_printf(channel_name, "%s[%zu]",
618 caption, create_idx);
619 } else {
620 g_string_printf(channel_name, "%zu",
621 detail->channel_offset + create_idx);
622 }
43bdef26
GS
623 if (detail->text_format == FORMAT_ANALOG) {
624 channel_sdi_nr = logic_count + detail->channel_offset + create_idx;
625 channel_type = SR_CHANNEL_ANALOG;
626 } else {
627 channel_sdi_nr = detail->channel_offset + create_idx;
628 channel_type = SR_CHANNEL_LOGIC;
629 }
630 sr_channel_new(in->sdi, channel_sdi_nr,
631 channel_type, TRUE, channel_name->str);
9e7af34e 632 }
2142a79b
GS
633 }
634 }
635 inc->logic_channels = channel_idx;
43bdef26 636 inc->analog_channels = analog_idx;
9e7af34e 637 g_string_free(channel_name, TRUE);
2142a79b
GS
638 g_strfreev(formats);
639
640 return SR_OK;
641}
642
e53f32d2
GS
643static const struct column_details *lookup_column_details(struct context *inc, size_t nr)
644{
645 if (!inc || !inc->column_details)
646 return NULL;
647 if (!nr || nr > inc->column_want_count)
648 return NULL;
649 return &inc->column_details[nr - 1];
650}
651
19267272
GS
652/*
653 * Primitive operations for text input: Strip comments off text lines.
654 * Split text lines into columns. Process input text for individual
655 * columns.
656 */
657
41d214f6 658static void strip_comment(char *buf, const GString *prefix)
4a35548b
MS
659{
660 char *ptr;
661
662 if (!prefix->len)
663 return;
664
b2c4dde2 665 if ((ptr = strstr(buf, prefix->str))) {
41d214f6 666 *ptr = '\0';
b2c4dde2
GS
667 g_strstrip(buf);
668 }
4a35548b
MS
669}
670
19267272 671/**
e53f32d2 672 * @brief Splits a text line into a set of columns.
19267272 673 *
e53f32d2 674 * @param[in] buf The input text line to split.
19267272
GS
675 * @param[in] inc The input module's context.
676 *
e53f32d2 677 * @returns An array of strings, representing the columns' text.
19267272 678 *
e53f32d2 679 * This routine splits a text line on previously determined separators.
19267272 680 */
e53f32d2 681static char **split_line(char *buf, struct context *inc)
4a35548b 682{
e53f32d2 683 return g_strsplit(buf, inc->delimiter->str, 0);
4a35548b
MS
684}
685
19267272 686/**
e53f32d2 687 * @brief Parse a multi-bit field into several logic channels.
19267272 688 *
e53f32d2 689 * @param[in] column The input text, a run of bin/hex/oct digits.
19267272 690 * @param[in] inc The input module's context.
836fac9c 691 * @param[in] details The column processing details.
19267272
GS
692 *
693 * @retval SR_OK Success.
694 * @retval SR_ERR Invalid input data (empty, or format error).
695 *
696 * This routine modifies the logic levels in the current sample set,
e53f32d2 697 * based on the text input and a user provided format spec.
19267272 698 */
836fac9c
GS
699static int parse_logic(const char *column, struct context *inc,
700 const struct column_details *details)
4a35548b 701{
e53f32d2
GS
702 size_t length, ch_rem, ch_idx, ch_inc;
703 const char *rdptr;
4a35548b 704 char c;
e53f32d2
GS
705 gboolean valid;
706 const char *type_text;
707 uint8_t bits;
708
e53f32d2
GS
709 /*
710 * Prepare to read the digits from the text end towards the start.
711 * A digit corresponds to a variable number of channels (depending
712 * on the value's radix). Prepare the mapping of text digits to
713 * (a number of) logic channels.
714 */
715 length = strlen(column);
4a35548b 716 if (!length) {
836fac9c 717 sr_err("Column %zu in line %zu is empty.", details->col_nr,
41d214f6 718 inc->line_number);
4a35548b
MS
719 return SR_ERR;
720 }
e53f32d2 721 rdptr = &column[length];
836fac9c
GS
722 ch_idx = details->channel_offset;
723 ch_rem = details->channel_count;
4a35548b 724
e53f32d2
GS
725 /*
726 * Get another digit and derive up to four logic channels' state from
727 * it. Make sure to not process more bits than the column has channels
728 * associated with it.
729 */
730 while (rdptr > column && ch_rem) {
731 /* Check for valid digits according to the input radix. */
732 c = *(--rdptr);
836fac9c 733 switch (details->text_format) {
e53f32d2
GS
734 case FORMAT_BIN:
735 valid = g_ascii_isxdigit(c) && c < '2';
736 ch_inc = 1;
737 break;
738 case FORMAT_OCT:
739 valid = g_ascii_isxdigit(c) && c < '8';
740 ch_inc = 3;
741 break;
742 case FORMAT_HEX:
743 valid = g_ascii_isxdigit(c);
744 ch_inc = 4;
745 break;
746 default:
747 valid = FALSE;
748 break;
4a35548b 749 }
e53f32d2 750 if (!valid) {
836fac9c 751 type_text = col_format_text[details->text_format];
e53f32d2 752 sr_err("Invalid text '%s' in %s type column %zu in line %zu.",
836fac9c 753 column, type_text, details->col_nr, inc->line_number);
4a35548b 754 return SR_ERR;
e53f32d2
GS
755 }
756 /* Use the digit's bits for logic channels' data. */
757 bits = g_ascii_xdigit_value(c);
836fac9c 758 switch (details->text_format) {
e53f32d2
GS
759 case FORMAT_HEX:
760 if (ch_rem >= 4) {
761 ch_rem--;
762 set_logic_level(inc, ch_idx + 3, bits & (1 << 3));
763 }
764 /* FALLTHROUGH */
765 case FORMAT_OCT:
766 if (ch_rem >= 3) {
767 ch_rem--;
768 set_logic_level(inc, ch_idx + 2, bits & (1 << 2));
769 }
770 if (ch_rem >= 2) {
771 ch_rem--;
772 set_logic_level(inc, ch_idx + 1, bits & (1 << 1));
773 }
774 /* FALLTHROUGH */
775 case FORMAT_BIN:
776 ch_rem--;
777 set_logic_level(inc, ch_idx + 0, bits & (1 << 0));
778 break;
43bdef26 779 case FORMAT_ANALOG:
836fac9c
GS
780 case FORMAT_NONE:
781 /* ShouldNotHappen(TM), but silences compiler warning. */
782 return SR_ERR;
4a35548b 783 }
e53f32d2 784 ch_idx += ch_inc;
4a35548b 785 }
e53f32d2
GS
786 /*
787 * TODO Determine whether the availability of extra input data
788 * for unhandled logic channels is worth warning here. In this
789 * implementation users are in control, and can have the more
790 * significant bits ignored (which can be considered a feature
791 * and not really a limitation).
792 */
4a35548b
MS
793
794 return SR_OK;
795}
796
43bdef26
GS
797/**
798 * @brief Parse a floating point text into an analog value.
799 *
800 * @param[in] column The input text, a floating point number.
801 * @param[in] inc The input module's context.
802 * @param[in] details The column processing details.
803 *
804 * @retval SR_OK Success.
805 * @retval SR_ERR Invalid input data (empty, or format error).
806 *
807 * This routine modifies the analog values in the current sample set,
808 * based on the text input and a user provided format spec.
809 */
810static int parse_analog(const char *column, struct context *inc,
811 const struct column_details *details)
812{
813 size_t length;
814 double dvalue; float fvalue;
815 csv_analog_t value;
816 int ret;
817
818 if (details->text_format != FORMAT_ANALOG)
819 return SR_ERR_BUG;
820
821 length = strlen(column);
822 if (!length) {
823 sr_err("Column %zu in line %zu is empty.", details->col_nr,
824 inc->line_number);
825 return SR_ERR;
826 }
827 if (sizeof(value) == sizeof(double)) {
828 ret = sr_atod_ascii(column, &dvalue);
829 value = dvalue;
830 } else if (sizeof(value) == sizeof(float)) {
831 ret = sr_atof_ascii(column, &fvalue);
832 value = fvalue;
833 } else {
834 ret = SR_ERR_BUG;
835 }
836 if (ret != SR_OK) {
837 sr_err("Cannot parse analog text %s in column %zu in line %zu.",
838 column, details->col_nr, inc->line_number);
839 return SR_ERR_DATA;
840 }
841 set_analog_value(inc, details->channel_offset, value);
842
843 return SR_OK;
844}
845
836fac9c
GS
846/**
847 * @brief Parse routine which ignores the input text.
848 *
849 * This routine exists to unify dispatch code paths, mapping input file
850 * columns' data types to their respective parse routines.
851 */
852static int parse_ignore(const char *column, struct context *inc,
853 const struct column_details *details)
854{
855 (void)column;
856 (void)inc;
857 (void)details;
858 return SR_OK;
859}
860
861typedef int (*col_parse_cb)(const char *column, struct context *inc,
862 const struct column_details *details);
863
864static const col_parse_cb col_parse_funcs[] = {
865 [FORMAT_NONE] = parse_ignore,
866 [FORMAT_BIN] = parse_logic,
867 [FORMAT_OCT] = parse_logic,
868 [FORMAT_HEX] = parse_logic,
43bdef26 869 [FORMAT_ANALOG] = parse_analog,
836fac9c
GS
870};
871
41d214f6 872static int init(struct sr_input *in, GHashTable *options)
4a35548b 873{
41d214f6 874 struct context *inc;
1a920e33 875 size_t single_column, first_column, logic_channels;
41d214f6 876 const char *s;
836fac9c 877 enum single_col_format format;
1a920e33 878 char format_char;
4a35548b 879
836fac9c
GS
880 in->sdi = g_malloc0(sizeof(*in->sdi));
881 in->priv = inc = g_malloc0(sizeof(*inc));
4a35548b 882
72903e9d 883 single_column = g_variant_get_uint32(g_hash_table_lookup(options, "single_column"));
72903e9d 884 logic_channels = g_variant_get_uint32(g_hash_table_lookup(options, "logic_channels"));
41d214f6 885 inc->delimiter = g_string_new(g_variant_get_string(
72903e9d 886 g_hash_table_lookup(options, "column_separator"), NULL));
836fac9c 887 if (!inc->delimiter->len) {
72903e9d 888 sr_err("Column separator cannot be empty.");
41d214f6 889 return SR_ERR_ARG;
4a35548b 890 }
72903e9d 891 s = g_variant_get_string(g_hash_table_lookup(options, "single_format"), NULL);
836fac9c
GS
892 if (g_ascii_strncasecmp(s, "bin", 3) == 0) {
893 format = FORMAT_BIN;
894 } else if (g_ascii_strncasecmp(s, "hex", 3) == 0) {
895 format = FORMAT_HEX;
896 } else if (g_ascii_strncasecmp(s, "oct", 3) == 0) {
897 format = FORMAT_OCT;
41d214f6 898 } else {
72903e9d 899 sr_err("Invalid single-column format: '%s'", s);
41d214f6 900 return SR_ERR_ARG;
4a35548b 901 }
41d214f6 902 inc->comment = g_string_new(g_variant_get_string(
72903e9d 903 g_hash_table_lookup(options, "comment_leader"), NULL));
41d214f6 904 if (g_string_equal(inc->comment, inc->delimiter)) {
e53f32d2
GS
905 /*
906 * Using the same sequence as comment leader and column
72903e9d
GS
907 * separator won't work. The user probably specified ';'
908 * as the column separator but did not adjust the comment
e53f32d2
GS
909 * leader. Try DWIM, drop comment strippin support here.
910 */
72903e9d 911 sr_warn("Comment leader and column separator conflict, disabling comment support.");
41d214f6 912 g_string_truncate(inc->comment, 0);
4a35548b 913 }
6e8d95a5 914 inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
72903e9d 915 first_column = g_variant_get_uint32(g_hash_table_lookup(options, "first_column"));
de8fe3b5 916 inc->use_header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
72903e9d 917 inc->start_line = g_variant_get_uint32(g_hash_table_lookup(options, "start_line"));
41d214f6 918 if (inc->start_line < 1) {
6433156c 919 sr_err("Invalid start line %zu.", inc->start_line);
41d214f6 920 return SR_ERR_ARG;
4a35548b
MS
921 }
922
e53f32d2 923 /*
1a920e33
GS
924 * Scan flexible, to get prefered format specs which describe
925 * the input file's data formats. As well as some simple specs
926 * for backwards compatibility and user convenience.
927 *
928 * This logic ends up with a copy of the format string, either
929 * user provided or internally derived. Actual creation of the
930 * column processing details gets deferred until the first line
931 * of input data was seen. To support automatic determination of
932 * e.g. channel counts from column counts.
e53f32d2 933 */
72903e9d 934 s = g_variant_get_string(g_hash_table_lookup(options, "column_formats"), NULL);
2142a79b 935 if (s && *s) {
1a920e33 936 inc->column_formats = g_strdup(s);
72903e9d 937 sr_dbg("User specified column_formats: %s.", s);
1a920e33
GS
938 } else if (single_column && logic_channels) {
939 format_char = col_format_char[format];
940 if (single_column == 1) {
941 inc->column_formats = g_strdup_printf("%c%zu",
942 format_char, logic_channels);
e53f32d2 943 } else {
1a920e33
GS
944 inc->column_formats = g_strdup_printf("%zu-,%c%zu",
945 single_column - 1,
946 format_char, logic_channels);
e53f32d2 947 }
72903e9d 948 sr_dbg("Backwards compat single_column, col %zu, fmt %s, bits %zu -> %s.",
1a920e33
GS
949 single_column, col_format_text[format], logic_channels,
950 inc->column_formats);
951 } else if (!single_column) {
952 if (first_column > 1) {
953 inc->column_formats = g_strdup_printf("%zu-,%zul",
954 first_column - 1, logic_channels);
955 } else {
956 inc->column_formats = g_strdup_printf("%zul",
957 logic_channels);
958 }
959 sr_dbg("Backwards compat multi-column, col %zu, chans %zu -> %s.",
960 first_column, logic_channels,
961 inc->column_formats);
e53f32d2 962 } else {
72903e9d 963 sr_warn("Unknown or unsupported columns layout spec, assuming simple multi-column mode.");
1a920e33 964 inc->column_formats = g_strdup("*l");
4a35548b
MS
965 }
966
41d214f6
BV
967 return SR_OK;
968}
4a35548b 969
affaf540
GS
970/*
971 * Check the channel list for consistency across file re-import. See
972 * the VCD input module for more details and motivation.
973 */
974
975static void keep_header_for_reread(const struct sr_input *in)
976{
977 struct context *inc;
978
979 inc = in->priv;
980 g_slist_free_full(inc->prev_sr_channels, sr_channel_free_cb);
981 inc->prev_sr_channels = in->sdi->channels;
982 in->sdi->channels = NULL;
983}
984
985static int check_header_in_reread(const struct sr_input *in)
986{
987 struct context *inc;
988
989 if (!in)
990 return FALSE;
991 inc = in->priv;
992 if (!inc)
993 return FALSE;
994 if (!inc->prev_sr_channels)
995 return TRUE;
996
997 if (sr_channel_lists_differ(inc->prev_sr_channels, in->sdi->channels)) {
998 sr_err("Channel list change not supported for file re-read.");
999 return FALSE;
1000 }
1001 g_slist_free_full(in->sdi->channels, sr_channel_free_cb);
1002 in->sdi->channels = inc->prev_sr_channels;
1003 inc->prev_sr_channels = NULL;
1004
1005 return TRUE;
1006}
1007
492dfa90
GS
1008static const char *delim_set = "\r\n";
1009
329733d9 1010static const char *get_line_termination(GString *buf)
41d214f6 1011{
329733d9 1012 const char *term;
4a35548b 1013
41d214f6
BV
1014 term = NULL;
1015 if (g_strstr_len(buf->str, buf->len, "\r\n"))
1016 term = "\r\n";
1017 else if (memchr(buf->str, '\n', buf->len))
1018 term = "\n";
1019 else if (memchr(buf->str, '\r', buf->len))
1020 term = "\r";
4a35548b 1021
41d214f6
BV
1022 return term;
1023}
4a35548b 1024
41d214f6
BV
1025static int initial_parse(const struct sr_input *in, GString *buf)
1026{
1027 struct context *inc;
9e7af34e 1028 size_t num_columns;
43bdef26 1029 size_t line_number, line_idx, ch_idx;
41d214f6 1030 int ret;
9e7af34e 1031 char **lines, *line, **columns;
41d214f6
BV
1032
1033 ret = SR_OK;
1034 inc = in->priv;
1035 columns = NULL;
1036
9e7af34e 1037 /* Search for the first line to process (header or data). */
41d214f6 1038 line_number = 0;
ef0b9935
GS
1039 if (inc->termination)
1040 lines = g_strsplit(buf->str, inc->termination, 0);
1041 else
1042 lines = g_strsplit_set(buf->str, delim_set, 0);
e53f32d2 1043 for (line_idx = 0; (line = lines[line_idx]); line_idx++) {
41d214f6
BV
1044 line_number++;
1045 if (inc->start_line > line_number) {
e53f32d2 1046 sr_spew("Line %zu skipped (before start).", line_number);
4a35548b
MS
1047 continue;
1048 }
df0db9fd 1049 if (line[0] == '\0') {
41d214f6
BV
1050 sr_spew("Blank line %zu skipped.", line_number);
1051 continue;
1052 }
df0db9fd
GS
1053 strip_comment(line, inc->comment);
1054 if (line[0] == '\0') {
41d214f6 1055 sr_spew("Comment-only line %zu skipped.", line_number);
4a35548b
MS
1056 continue;
1057 }
1058
41d214f6
BV
1059 /* Reached first proper line. */
1060 break;
1061 }
e53f32d2 1062 if (!line) {
41d214f6 1063 /* Not enough data for a proper line yet. */
60107497 1064 ret = SR_ERR_NA;
41d214f6 1065 goto out;
4a35548b
MS
1066 }
1067
9e7af34e 1068 /* Get the number of columns in the line. */
e53f32d2 1069 columns = split_line(line, inc);
df0db9fd 1070 if (!columns) {
41d214f6
BV
1071 sr_err("Error while parsing line %zu.", line_number);
1072 ret = SR_ERR;
1073 goto out;
4a35548b 1074 }
4a35548b 1075 num_columns = g_strv_length(columns);
4a35548b 1076 if (!num_columns) {
e53f32d2 1077 sr_err("Error while parsing line %zu.", line_number);
41d214f6
BV
1078 ret = SR_ERR;
1079 goto out;
4a35548b 1080 }
e53f32d2
GS
1081 sr_dbg("DIAG Got %zu columns in text line: %s.", num_columns, line);
1082
1a920e33 1083 /*
9e7af34e
GS
1084 * Interpret the user provided column format specs. This might
1085 * involve inspection of the now received input text, to support
1086 * e.g. automatic detection of channel counts in the absence of
1087 * user provided specs. Optionally a header line is used to get
1088 * channels' names.
1089 *
1090 * Check the then created channels for consistency across .reset
1091 * and .receive sequences (file re-load).
1a920e33 1092 */
9e7af34e 1093 ret = make_column_details_from_format(in, inc->column_formats, columns);
1a920e33
GS
1094 if (ret != SR_OK) {
1095 sr_err("Cannot parse columns format using line %zu.", line_number);
1096 goto out;
4a35548b 1097 }
affaf540
GS
1098 if (!check_header_in_reread(in)) {
1099 ret = SR_ERR_DATA;
1100 goto out;
1101 }
4a35548b
MS
1102
1103 /*
9e7af34e 1104 * Allocate buffer memory for datafeed submission of sample data.
cd59e6ec
GS
1105 * Calculate the minimum buffer size to store the set of samples
1106 * of all channels (unit size). Determine a larger buffer size
1107 * for datafeed submission that is a multiple of the unit size.
626c388a
GS
1108 * Allocate the larger buffer, the "sample buffer" will point
1109 * to a location within that large buffer later.
4a35548b 1110 */
43bdef26
GS
1111 if (inc->logic_channels) {
1112 inc->sample_unit_size = (inc->logic_channels + 7) / 8;
1113 inc->datafeed_buf_size = CHUNK_SIZE;
1114 inc->datafeed_buf_size *= inc->sample_unit_size;
1115 inc->datafeed_buffer = g_malloc(inc->datafeed_buf_size);
1116 if (!inc->datafeed_buffer) {
1117 sr_err("Cannot allocate datafeed send buffer (logic).");
1118 ret = SR_ERR_MALLOC;
1119 goto out;
1120 }
1121 inc->datafeed_buf_fill = 0;
1122 }
1123
1124 if (inc->analog_channels) {
1125 size_t sample_size, sample_count;
a267bf45
GS
1126 size_t detail_idx;
1127 int *digits_item;
43bdef26
GS
1128 sample_size = sizeof(inc->analog_datafeed_buffer[0]);
1129 inc->analog_datafeed_buf_size = CHUNK_SIZE;
1130 inc->analog_datafeed_buf_size /= sample_size;
1131 inc->analog_datafeed_buf_size /= inc->analog_channels;
1132 sample_count = inc->analog_channels * inc->analog_datafeed_buf_size;
1133 inc->analog_datafeed_buffer = g_malloc0(sample_count * sample_size);
1134 if (!inc->analog_datafeed_buffer) {
1135 sr_err("Cannot allocate datafeed send buffer (analog).");
1136 ret = SR_ERR_MALLOC;
1137 goto out;
1138 }
1139 inc->analog_datafeed_buf_fill = 0;
1140 inc->analog_datafeed_channels = g_malloc0_n(inc->analog_channels, sizeof(inc->analog_datafeed_channels[0]));
1141 for (ch_idx = 0; ch_idx < inc->analog_channels; ch_idx++) {
1142 void *channel;
1143 channel = g_slist_nth_data(in->sdi->channels, inc->logic_channels + ch_idx);
1144 inc->analog_datafeed_channels[ch_idx] = g_slist_append(NULL, channel);
1145 }
a267bf45
GS
1146 inc->analog_datafeed_digits = g_malloc0(inc->analog_channels * sizeof(inc->analog_datafeed_digits[0]));
1147 digits_item = inc->analog_datafeed_digits;
1148 for (detail_idx = 0; detail_idx < inc->column_want_count; detail_idx++) {
1149 if (inc->column_details[detail_idx].text_format != FORMAT_ANALOG)
1150 continue;
1151 *digits_item++ = inc->column_details[detail_idx].analog_digits;
1152 }
43bdef26 1153 }
4a35548b 1154
41d214f6
BV
1155out:
1156 if (columns)
1157 g_strfreev(columns);
1158 g_strfreev(lines);
4a35548b 1159
41d214f6 1160 return ret;
4a35548b
MS
1161}
1162
4439363a
GS
1163/*
1164 * Gets called from initial_receive(), which runs until the end-of-line
1165 * encoding of the input stream could get determined. Assumes that this
1166 * routine receives enough buffered initial input data to either see the
1167 * BOM when there is one, or that no BOM will follow when a text line
1168 * termination sequence was seen. Silently drops the UTF-8 BOM sequence
1169 * from the input buffer if one was seen. Does not care to protect
1170 * against multiple execution or dropping the BOM multiple times --
1171 * there should be at most one in the input stream.
1172 */
1173static void initial_bom_check(const struct sr_input *in)
1174{
1175 static const char *utf8_bom = "\xef\xbb\xbf";
1176
1177 if (in->buf->len < strlen(utf8_bom))
1178 return;
1179 if (strncmp(in->buf->str, utf8_bom, strlen(utf8_bom)) != 0)
1180 return;
1181 g_string_erase(in->buf, 0, strlen(utf8_bom));
1182}
1183
41d214f6 1184static int initial_receive(const struct sr_input *in)
4a35548b 1185{
41d214f6
BV
1186 struct context *inc;
1187 GString *new_buf;
1188 int len, ret;
329733d9
UH
1189 char *p;
1190 const char *termination;
4a35548b 1191
4439363a
GS
1192 initial_bom_check(in);
1193
41d214f6 1194 inc = in->priv;
4a35548b 1195
df0db9fd
GS
1196 termination = get_line_termination(in->buf);
1197 if (!termination)
41d214f6 1198 /* Don't have a full line yet. */
d0181813 1199 return SR_ERR_NA;
4a35548b 1200
df0db9fd
GS
1201 p = g_strrstr_len(in->buf->str, in->buf->len, termination);
1202 if (!p)
41d214f6 1203 /* Don't have a full line yet. */
d0181813 1204 return SR_ERR_NA;
41d214f6
BV
1205 len = p - in->buf->str - 1;
1206 new_buf = g_string_new_len(in->buf->str, len);
1207 g_string_append_c(new_buf, '\0');
4a35548b 1208
41d214f6
BV
1209 inc->termination = g_strdup(termination);
1210
1211 if (in->buf->str[0] != '\0')
1212 ret = initial_parse(in, new_buf);
1213 else
1214 ret = SR_OK;
1215
1216 g_string_free(new_buf, TRUE);
1217
1218 return ret;
1219}
1220
7f4c3a62 1221static int process_buffer(struct sr_input *in, gboolean is_eof)
41d214f6 1222{
41d214f6
BV
1223 struct context *inc;
1224 gsize num_columns;
e53f32d2 1225 size_t line_idx, col_idx, col_nr;
836fac9c
GS
1226 const struct column_details *details;
1227 col_parse_cb parse_func;
ad6a2bee 1228 int ret;
e53f32d2 1229 char *p, **lines, *line, **columns, *column;
41d214f6 1230
41d214f6 1231 inc = in->priv;
d0181813 1232 if (!inc->started) {
bee2b016 1233 std_session_send_df_header(in->sdi);
d0181813 1234 inc->started = TRUE;
4a35548b
MS
1235 }
1236
4555d3bd
GS
1237 /*
1238 * Consider empty input non-fatal. Keep accumulating input until
1239 * at least one full text line has become available. Grab the
1240 * maximum amount of accumulated data that consists of full text
1241 * lines, and process what has been received so far, leaving not
1242 * yet complete lines for the next invocation.
7f4c3a62
GS
1243 *
1244 * Enforce that all previously buffered data gets processed in
1245 * the "EOF" condition. Do not insist in the presence of the
1246 * termination sequence for the last line (may often be missing
1247 * on Windows). A present termination sequence will just result
1248 * in the "execution of an empty line", and does not harm.
4555d3bd
GS
1249 */
1250 if (!in->buf->len)
1251 return SR_OK;
7f4c3a62
GS
1252 if (is_eof) {
1253 p = in->buf->str + in->buf->len;
1254 } else {
1255 p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination);
1256 if (!p)
1257 return SR_ERR;
1258 *p = '\0';
1259 p += strlen(inc->termination);
1260 }
41d214f6 1261 g_strstrip(in->buf->str);
4a35548b 1262
18078d05 1263 ret = SR_OK;
ef0b9935 1264 lines = g_strsplit(in->buf->str, inc->termination, 0);
e53f32d2 1265 for (line_idx = 0; (line = lines[line_idx]); line_idx++) {
41d214f6 1266 inc->line_number++;
ef0b9935
GS
1267 if (inc->line_number < inc->start_line) {
1268 sr_spew("Line %zu skipped (before start).", inc->line_number);
1269 continue;
1270 }
df0db9fd 1271 if (line[0] == '\0') {
41d214f6 1272 sr_spew("Blank line %zu skipped.", inc->line_number);
4a35548b
MS
1273 continue;
1274 }
1275
1276 /* Remove trailing comment. */
df0db9fd
GS
1277 strip_comment(line, inc->comment);
1278 if (line[0] == '\0') {
41d214f6 1279 sr_spew("Comment-only line %zu skipped.", inc->line_number);
4a35548b
MS
1280 continue;
1281 }
1282
160691b9 1283 /* Skip the header line, its content was used as the channel names. */
de8fe3b5 1284 if (inc->use_header && !inc->header_seen) {
160691b9 1285 sr_spew("Header line %zu skipped.", inc->line_number);
de8fe3b5 1286 inc->header_seen = TRUE;
160691b9
JS
1287 continue;
1288 }
1289
e53f32d2
GS
1290 /* Split the line into columns, check for minimum length. */
1291 columns = split_line(line, inc);
df0db9fd 1292 if (!columns) {
41d214f6 1293 sr_err("Error while parsing line %zu.", inc->line_number);
2355d229 1294 g_strfreev(lines);
4a35548b
MS
1295 return SR_ERR;
1296 }
4a35548b 1297 num_columns = g_strv_length(columns);
e53f32d2
GS
1298 if (num_columns < inc->column_want_count) {
1299 sr_err("Insufficient column count %zu in line %zu.",
1300 num_columns, inc->line_number);
4a35548b 1301 g_strfreev(columns);
2355d229 1302 g_strfreev(lines);
4a35548b
MS
1303 return SR_ERR;
1304 }
1305
836fac9c 1306 /* Have the columns of the current text line processed. */
626c388a 1307 clear_logic_samples(inc);
43bdef26 1308 clear_analog_samples(inc);
e53f32d2
GS
1309 for (col_idx = 0; col_idx < inc->column_want_count; col_idx++) {
1310 column = columns[col_idx];
1311 col_nr = col_idx + 1;
836fac9c
GS
1312 details = lookup_column_details(inc, col_nr);
1313 if (!details || !details->text_format)
1314 continue;
1315 parse_func = col_parse_funcs[details->text_format];
1316 if (!parse_func)
1317 continue;
1318 ret = parse_func(column, inc, details);
e53f32d2
GS
1319 if (ret != SR_OK) {
1320 g_strfreev(columns);
1321 g_strfreev(lines);
1322 return SR_ERR;
1323 }
4a35548b
MS
1324 }
1325
626c388a
GS
1326 /* Send sample data to the session bus (buffered). */
1327 ret = queue_logic_samples(in);
43bdef26 1328 ret += queue_analog_samples(in);
41d214f6 1329 if (ret != SR_OK) {
4a35548b 1330 sr_err("Sending samples failed.");
cd59e6ec 1331 g_strfreev(columns);
2355d229 1332 g_strfreev(lines);
4a35548b
MS
1333 return SR_ERR;
1334 }
cd59e6ec 1335
41d214f6
BV
1336 g_strfreev(columns);
1337 }
1338 g_strfreev(lines);
241c386a 1339 g_string_erase(in->buf, 0, p - in->buf->str);
41d214f6 1340
7066fd46 1341 return ret;
41d214f6
BV
1342}
1343
7066fd46 1344static int receive(struct sr_input *in, GString *buf)
41d214f6
BV
1345{
1346 struct context *inc;
7066fd46
BV
1347 int ret;
1348
1349 g_string_append_len(in->buf, buf->str, buf->len);
41d214f6
BV
1350
1351 inc = in->priv;
1a920e33 1352 if (!inc->column_seen_count) {
df0db9fd
GS
1353 ret = initial_receive(in);
1354 if (ret == SR_ERR_NA)
7066fd46
BV
1355 /* Not enough data yet. */
1356 return SR_OK;
1357 else if (ret != SR_OK)
1358 return SR_ERR;
1359
1360 /* sdi is ready, notify frontend. */
1361 in->sdi_ready = TRUE;
41d214f6 1362 return SR_OK;
7066fd46
BV
1363 }
1364
7f4c3a62 1365 ret = process_buffer(in, FALSE);
7066fd46
BV
1366
1367 return ret;
1368}
1369
1370static int end(struct sr_input *in)
1371{
1372 struct context *inc;
7066fd46 1373 int ret;
41d214f6 1374
7066fd46 1375 if (in->sdi_ready)
7f4c3a62 1376 ret = process_buffer(in, TRUE);
7066fd46
BV
1377 else
1378 ret = SR_OK;
cd59e6ec
GS
1379 if (ret != SR_OK)
1380 return ret;
1381
626c388a 1382 ret = flush_logic_samples(in);
43bdef26 1383 ret += flush_analog_samples(in);
cd59e6ec
GS
1384 if (ret != SR_OK)
1385 return ret;
7066fd46
BV
1386
1387 inc = in->priv;
3be42bc2 1388 if (inc->started)
bee2b016 1389 std_session_send_df_end(in->sdi);
4a35548b 1390
7066fd46
BV
1391 return ret;
1392}
1393
d5cc282f 1394static void cleanup(struct sr_input *in)
7066fd46
BV
1395{
1396 struct context *inc;
1397
affaf540
GS
1398 keep_header_for_reread(in);
1399
7066fd46
BV
1400 inc = in->priv;
1401
b1f83103 1402 g_free(inc->termination);
539188e5 1403 inc->termination = NULL;
cd59e6ec 1404 g_free(inc->datafeed_buffer);
539188e5 1405 inc->datafeed_buffer = NULL;
43bdef26
GS
1406 g_free(inc->analog_datafeed_buffer);
1407 inc->analog_datafeed_buffer = NULL;
4a35548b
MS
1408}
1409
ad93bfb0
SA
1410static int reset(struct sr_input *in)
1411{
1412 struct context *inc = in->priv;
1413
1414 cleanup(in);
1415 inc->started = FALSE;
1416 g_string_truncate(in->buf, 0);
1417
1418 return SR_OK;
1419}
1420
c6aa9870 1421enum option_index {
2142a79b 1422 OPT_COL_FMTS,
c6aa9870 1423 OPT_SINGLE_COL,
72903e9d 1424 OPT_FIRST_COL,
c6aa9870 1425 OPT_NUM_LOGIC,
c6aa9870 1426 OPT_FORMAT,
c6aa9870 1427 OPT_START,
72903e9d
GS
1428 OPT_HEADER,
1429 OPT_RATE,
1430 OPT_DELIM,
1431 OPT_COMMENT,
c6aa9870
GS
1432 OPT_MAX,
1433};
1434
41d214f6 1435static struct sr_option options[] = {
72903e9d
GS
1436 [OPT_COL_FMTS] = {
1437 "column_formats", "Column format specs",
1438 "Specifies text columns data types: comma separated list of [<cols>]<fmt>[<bits>], with -/x/o/b/l format specifiers.",
1439 NULL, NULL,
1440 },
1441 [OPT_SINGLE_COL] = {
1442 "single_column", "Single column",
1443 "Enable single-column mode, exclusively use text from the specified column (number starting at 1).",
1444 NULL, NULL,
1445 },
1446 [OPT_FIRST_COL] = {
1447 "first_column", "First column",
1448 "Number of the first column with logic data in simple multi-column mode (number starting at 1, default 1).",
1449 NULL, NULL,
1450 },
1451 [OPT_NUM_LOGIC] = {
1452 "logic_channels", "Number of logic channels",
1453 "Logic channel count, required in simple single-column mode, defaults to \"all remaining columns\" in simple multi-column mode. Obsoleted by 'column_formats'.",
1454 NULL, NULL,
1455 },
1456 [OPT_FORMAT] = {
1457 "single_format", "Data format for simple single-column mode.",
1458 "The number format of single-column mode input data: bin, hex, oct.",
1459 NULL, NULL,
1460 },
1461 [OPT_START] = {
1462 "start_line", "Start line",
1463 "The line number at which to start processing input text (default: 1).",
1464 NULL, NULL,
1465 },
1466 [OPT_HEADER] = {
1467 "header", "Get channel names from first line.",
1468 "Use the first processed line's column captions (when available) as channel names.",
1469 NULL, NULL,
1470 },
1471 [OPT_RATE] = {
1472 "samplerate", "Samplerate (Hz)",
1473 "The input data's sample rate in Hz.",
1474 NULL, NULL,
1475 },
1476 [OPT_DELIM] = {
1477 "column_separator", "Column separator",
1478 "The sequence which separates text columns. Non-empty text, comma by default.",
1479 NULL, NULL,
1480 },
1481 [OPT_COMMENT] = {
1482 "comment_leader", "Comment leader character",
1483 "The text which starts comments at the end of text lines.",
1484 NULL, NULL,
1485 },
c6aa9870 1486 [OPT_MAX] = ALL_ZERO,
41d214f6
BV
1487};
1488
2c240774 1489static const struct sr_option *get_options(void)
41d214f6 1490{
31c41782
UH
1491 GSList *l;
1492
41d214f6 1493 if (!options[0].def) {
1a920e33 1494 options[OPT_COL_FMTS].def = g_variant_ref_sink(g_variant_new_string(""));
e53f32d2 1495 options[OPT_SINGLE_COL].def = g_variant_ref_sink(g_variant_new_uint32(0));
72903e9d 1496 options[OPT_FIRST_COL].def = g_variant_ref_sink(g_variant_new_uint32(1));
e53f32d2 1497 options[OPT_NUM_LOGIC].def = g_variant_ref_sink(g_variant_new_uint32(0));
c6aa9870 1498 options[OPT_FORMAT].def = g_variant_ref_sink(g_variant_new_string("bin"));
31c41782
UH
1499 l = NULL;
1500 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("bin")));
1501 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("hex")));
1502 l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("oct")));
c6aa9870 1503 options[OPT_FORMAT].values = l;
e53f32d2 1504 options[OPT_START].def = g_variant_ref_sink(g_variant_new_uint32(1));
72903e9d
GS
1505 options[OPT_HEADER].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
1506 options[OPT_RATE].def = g_variant_ref_sink(g_variant_new_uint64(0));
1507 options[OPT_DELIM].def = g_variant_ref_sink(g_variant_new_string(","));
1508 options[OPT_COMMENT].def = g_variant_ref_sink(g_variant_new_string(";"));
41d214f6
BV
1509 }
1510
1511 return options;
1512}
1513
d4c93774 1514SR_PRIV struct sr_input_module input_csv = {
4a35548b 1515 .id = "csv",
41d214f6
BV
1516 .name = "CSV",
1517 .desc = "Comma-separated values",
c7bc82ff 1518 .exts = (const char*[]){"csv", NULL},
41d214f6 1519 .options = get_options,
4a35548b 1520 .init = init,
41d214f6 1521 .receive = receive,
7066fd46 1522 .end = end,
41d214f6 1523 .cleanup = cleanup,
ad93bfb0 1524 .reset = reset,
4a35548b 1525};