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