]> sigrok.org Git - libsigrok.git/blobdiff - src/input/csv.c
input/csv: improve "channel name from header line" logic
[libsigrok.git] / src / input / csv.c
index 1eb20bff72691bbf97ccf9bc8b0a637d47a76cd0..17c253a29d2f29aff5c3cabc6397da1d1fbfecc0 100644 (file)
@@ -2,6 +2,7 @@
  * This file is part of the libsigrok project.
  *
  * Copyright (C) 2013 Marc Schink <sigrok-dev@marcschink.de>
+ * Copyright (C) 2019 Gerhard Sittig <gerhard.sittig@gmx.net>
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <config.h>
+#include "config.h"
+
+#include <glib.h>
 #include <stdlib.h>
 #include <string.h>
-#include <glib.h>
+
 #include <libsigrok/libsigrok.h>
 #include "libsigrok-internal.h"
+#include "scpi.h"      /* String un-quote for channel name from header line. */
 
 #define LOG_PREFIX "input/csv"
 
+#define CHUNK_SIZE     (4 * 1024 * 1024)
+
 /*
  * The CSV input module has the following options:
  *
  *                than 0. The default line number to start processing is 1.
  */
 
+/*
+ * TODO
+ *
+ * - Determine how the text line handling can get improved, regarding
+ *   all of robustness and flexibility and correctness.
+ *   - The current implementation splits on "any run of CR and LF". Which
+ *     translates to: Line numbers are wrong in the presence of empty
+ *     lines in the input stream. See below for an (expensive) fix.
+ *   - Dropping support for CR style end-of-line markers could improve
+ *     the situation a lot. Code could search for and split on LF, and
+ *     trim optional trailing CR. This would result in proper support
+ *     for CRLF (Windows) as well as LF (Unix), and allow for correct
+ *     line number counts.
+ *   - When support for CR-only line termination cannot get dropped,
+ *     then the current implementation is inappropriate. Currently the
+ *     input stream is scanned for the first occurance of either of the
+ *     supported termination styles (which is good). For the remaining
+ *     session a consistent encoding of the text lines is assumed (which
+ *     is acceptable).
+ *   - When line numbers need to be correct and reliable, _and_ the full
+ *     set of previously supported line termination sequences are required,
+ *     and potentially more are to get added for improved compatibility
+ *     with more platforms or generators, then the current approach of
+ *     splitting on runs of termination characters needs to get replaced,
+ *     by the more expensive approach to scan for and count the initially
+ *     determined termination sequence.
+ *
+ * - Add support for analog input data? (optional)
+ *   - Needs a syntax first for user specs which channels (columns) are
+ *     logic and which are analog. May need heuristics(?) to guess from
+ *     input data in the absence of user provided specs.
+ */
+
 /* Single column formats. */
-enum {
-       FORMAT_BIN,
-       FORMAT_HEX,
-       FORMAT_OCT
+enum single_col_format {
+       FORMAT_NONE,    /* Ignore this column. */
+       FORMAT_BIN,     /* Bin digits for a set of bits (or just one bit). */
+       FORMAT_HEX,     /* Hex digits for a set of bits. */
+       FORMAT_OCT,     /* Oct digits for a set of bits. */
+};
+
+static const char *col_format_text[] = {
+       [FORMAT_NONE] = "unknown",
+       [FORMAT_BIN] = "binary",
+       [FORMAT_HEX] = "hexadecimal",
+       [FORMAT_OCT] = "octal",
+};
+
+struct column_details {
+       size_t col_nr;
+       enum single_col_format text_format;
+       size_t channel_offset;
+       size_t channel_count;
 };
 
 struct context {
@@ -79,9 +133,10 @@ struct context {
 
        /* Current selected samplerate. */
        uint64_t samplerate;
+       gboolean samplerate_sent;
 
        /* Number of channels. */
-       unsigned int num_channels;
+       size_t num_channels;
 
        /* Column delimiter character(s). */
        GString *delimiter;
@@ -89,27 +144,21 @@ struct context {
        /* Comment prefix character(s). */
        GString *comment;
 
-       /* Termination  character(s) used in current stream. */
+       /* Termination character(s) used in current stream. */
        char *termination;
 
        /* Determines if sample data is stored in multiple columns. */
        gboolean multi_column_mode;
 
-       /* Column number of the sample data in single column mode. */
-       unsigned int single_column;
+       /* Parameters how to process the columns. */
+       size_t column_want_count;
+       struct column_details *column_details;
 
-       /*
-        * Number of the first column to parse. Equivalent to the number of the
-        * first channel in multi column mode and the single column number in
-        * single column mode.
-        */
-       unsigned int first_column;
+       /* Column number of the sample data in single column mode. */
+       size_t single_column;
 
-       /*
-        * Column number of the first channel in multi column mode and position of
-        * the bit for the first channel in single column mode.
-        */
-       unsigned int first_channel;
+       /* Column number of the first channel. */
+       size_t first_column;
 
        /* Line number to start processing. */
        size_t start_line;
@@ -118,262 +167,340 @@ struct context {
         * Determines if the first line should be treated as header and used for
         * channel names in multi column mode.
         */
-       gboolean header;
+       gboolean use_header;
+       gboolean header_seen;
 
        /* Format sample data is stored in single column mode. */
-       int format;
+       enum single_col_format format;
 
-       /* Size of the sample buffer. */
-       size_t sample_buffer_size;
+       size_t sample_unit_size;        /**!< Byte count for a single sample. */
+       uint8_t *sample_buffer;         /**!< Buffer for a single sample. */
 
-       /* Buffer to store sample data. */
-       uint8_t *sample_buffer;
+       uint8_t *datafeed_buffer;       /**!< Queue for datafeed submission. */
+       size_t datafeed_buf_size;
+       size_t datafeed_buf_fill;
 
        /* Current line number. */
        size_t line_number;
+
+       /* List of previously created sigrok channels. */
+       GSList *prev_sr_channels;
 };
 
-static void strip_comment(char *buf, const GString *prefix)
+/*
+ * Primitive operations to handle sample sets:
+ * - Keep a buffer for datafeed submission, capable of holding many
+ *   samples (reduces call overhead, improves throughput).
+ * - Have a "current sample set" pointer reference one position in that
+ *   large samples buffer.
+ * - Clear the current sample set before text line inspection, then set
+ *   the bits which are found active in the current line of text input.
+ *   Phrase the API such that call sites can be kept simple. Advance to
+ *   the next sample set between lines, flush the larger buffer as needed
+ *   (when it is full, or upon EOF).
+ */
+
+static void clear_logic_samples(struct context *inc)
 {
-       char *ptr;
+       inc->sample_buffer = &inc->datafeed_buffer[inc->datafeed_buf_fill];
+       memset(inc->sample_buffer, 0, inc->sample_unit_size);
+}
 
-       if (!prefix->len)
+static void set_logic_level(struct context *inc, size_t ch_idx, int on)
+{
+       size_t byte_idx, bit_idx;
+       uint8_t bit_mask;
+
+       if (ch_idx >= inc->num_channels)
+               return;
+       if (!on)
                return;
 
-       if ((ptr = strstr(buf, prefix->str)))
-               *ptr = '\0';
+       byte_idx = ch_idx / 8;
+       bit_idx = ch_idx % 8;
+       bit_mask = 1 << bit_idx;
+       inc->sample_buffer[byte_idx] |= bit_mask;
 }
 
-static int parse_binstr(const char *str, struct context *inc)
+static int flush_logic_samples(const struct sr_input *in)
 {
-       gsize i, j, length;
+       struct context *inc;
+       struct sr_datafeed_packet packet;
+       struct sr_datafeed_meta meta;
+       struct sr_config *src;
+       uint64_t samplerate;
+       struct sr_datafeed_logic logic;
+       int rc;
 
-       length = strlen(str);
+       inc = in->priv;
+       if (!inc->datafeed_buf_fill)
+               return SR_OK;
 
-       if (!length) {
-               sr_err("Column %u in line %zu is empty.", inc->single_column,
-                       inc->line_number);
-               return SR_ERR;
+       if (inc->samplerate && !inc->samplerate_sent) {
+               packet.type = SR_DF_META;
+               packet.payload = &meta;
+               samplerate = inc->samplerate;
+               src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
+               meta.config = g_slist_append(NULL, src);
+               sr_session_send(in->sdi, &packet);
+               g_slist_free(meta.config);
+               sr_config_free(src);
+               inc->samplerate_sent = TRUE;
        }
 
-       /* Clear buffer in order to set bits only. */
-       memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
+       memset(&packet, 0, sizeof(packet));
+       memset(&logic, 0, sizeof(logic));
+       packet.type = SR_DF_LOGIC;
+       packet.payload = &logic;
+       logic.unitsize = inc->sample_unit_size;
+       logic.length = inc->datafeed_buf_fill;
+       logic.data = inc->datafeed_buffer;
 
-       i = inc->first_channel;
-
-       for (j = 0; i < length && j < inc->num_channels; i++, j++) {
-               if (str[length - i - 1] == '1') {
-                       inc->sample_buffer[j / 8] |= (1 << (j % 8));
-               } else if (str[length - i - 1] != '0') {
-                       sr_err("Invalid value '%s' in column %u in line %zu.",
-                               str, inc->single_column, inc->line_number);
-                       return SR_ERR;
-               }
-       }
+       rc = sr_session_send(in->sdi, &packet);
+       if (rc != SR_OK)
+               return rc;
 
+       inc->datafeed_buf_fill = 0;
        return SR_OK;
 }
 
-static int parse_hexstr(const char *str, struct context *inc)
+static int queue_logic_samples(const struct sr_input *in)
 {
-       gsize i, j, k, length;
-       uint8_t value;
-       char c;
+       struct context *inc;
+       int rc;
 
-       length = strlen(str);
+       inc = in->priv;
 
-       if (!length) {
-               sr_err("Column %u in line %zu is empty.", inc->single_column,
-                       inc->line_number);
-               return SR_ERR;
+       inc->datafeed_buf_fill += inc->sample_unit_size;
+       if (inc->datafeed_buf_fill == inc->datafeed_buf_size) {
+               rc = flush_logic_samples(in);
+               if (rc != SR_OK)
+                       return rc;
        }
+       return SR_OK;
+}
 
-       /* Clear buffer in order to set bits only. */
-       memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
-
-       /* Calculate the position of the first hexadecimal digit. */
-       i = inc->first_channel / 4;
-
-       for (j = 0; i < length && j < inc->num_channels; i++) {
-               c = str[length - i - 1];
-
-               if (!g_ascii_isxdigit(c)) {
-                       sr_err("Invalid value '%s' in column %u in line %zu.",
-                               str, inc->single_column, inc->line_number);
-                       return SR_ERR;
-               }
-
-               value = g_ascii_xdigit_value(c);
+static int make_column_details_single(struct context *inc,
+       size_t col_nr, size_t bit_count, enum single_col_format format)
+{
+       struct column_details *details;
 
-               k = (inc->first_channel + j) % 4;
+       /*
+        * Need at least as many columns to also include the one with
+        * the single-column input data.
+        */
+       inc->column_want_count = col_nr;
 
-               for (; j < inc->num_channels && k < 4; k++) {
-                       if (value & (1 << k))
-                               inc->sample_buffer[j / 8] |= (1 << (j % 8));
+       /*
+        * Allocate the columns' processing details. Columns are counted
+        * from 1 (user's perspective), array items from 0 (programmer's
+        * perspective).
+        */
+       inc->column_details = g_malloc0_n(col_nr, sizeof(inc->column_details[0]));
+       details = &inc->column_details[col_nr - 1];
+       details->col_nr = col_nr;
 
-                       j++;
-               }
-       }
+       /*
+        * In single-column mode this single column will hold all bits
+        * of all logic channels, in the user specified number format.
+        */
+       details->text_format = format;
+       details->channel_offset = 0;
+       details->channel_count = bit_count;
 
        return SR_OK;
 }
 
-static int parse_octstr(const char *str, struct context *inc)
+static int make_column_details_multi(struct context *inc,
+       size_t first_col, size_t last_col)
 {
-       gsize i, j, k, length;
-       uint8_t value;
-       char c;
+       struct column_details *details;
+       size_t col_nr;
 
-       length = strlen(str);
+       /*
+        * Need at least as many columns to also include the one with
+        * the last channel's data.
+        */
+       inc->column_want_count = last_col;
 
-       if (!length) {
-               sr_err("Column %u in line %zu is empty.", inc->single_column,
-                       inc->line_number);
-               return SR_ERR;
+       /*
+        * Allocate the columns' processing details. Columns are counted
+        * from 1, array items from 0.
+        * In multi-column mode each column will hold a single bit for
+        * the respective channel.
+        */
+       inc->column_details = g_malloc0_n(last_col, sizeof(inc->column_details[0]));
+       for (col_nr = first_col; col_nr <= last_col; col_nr++) {
+               details = &inc->column_details[col_nr - 1];
+               details->col_nr = col_nr;
+               details->text_format = FORMAT_BIN;
+               details->channel_offset = col_nr - first_col;
+               details->channel_count = 1;
        }
 
-       /* Clear buffer in order to set bits only. */
-       memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
-
-       /* Calculate the position of the first octal digit. */
-       i = inc->first_channel / 3;
-
-       for (j = 0; i < length && j < inc->num_channels; i++) {
-               c = str[length - i - 1];
-
-               if (c < '0' || c > '7') {
-                       sr_err("Invalid value '%s' in column %u in line %zu.",
-                               str, inc->single_column, inc->line_number);
-                       return SR_ERR;
-               }
-
-               value = g_ascii_xdigit_value(c);
-
-               k = (inc->first_channel + j) % 3;
-
-               for (; j < inc->num_channels && k < 3; k++) {
-                       if (value & (1 << k))
-                               inc->sample_buffer[j / 8] |= (1 << (j % 8));
-
-                       j++;
-               }
-       }
 
        return SR_OK;
 }
 
-static char **parse_line(char *buf, struct context *inc, int max_columns)
+static const struct column_details *lookup_column_details(struct context *inc, size_t nr)
 {
-       const char *str, *remainder;
-       GSList *list, *l;
-       char **columns;
-       char *column;
-       gsize n, k;
-
-       n = 0;
-       k = 0;
-       list = NULL;
-
-       remainder = buf;
-       str = strstr(remainder, inc->delimiter->str);
-
-       while (str && max_columns) {
-               if (n >= inc->first_column) {
-                       column = g_strndup(remainder, str - remainder);
-                       list = g_slist_prepend(list, g_strstrip(column));
-
-                       max_columns--;
-                       k++;
-               }
-
-               remainder = str + inc->delimiter->len;
-               str = strstr(remainder, inc->delimiter->str);
-               n++;
-       }
-
-       if (buf[0] && max_columns && n >= inc->first_column) {
-               column = g_strdup(remainder);
-               list = g_slist_prepend(list, g_strstrip(column));
-               k++;
-       }
-
-       if (!(columns = g_try_new(char *, k + 1)))
+       if (!inc || !inc->column_details)
                return NULL;
-
-       columns[k--] = NULL;
-
-       for (l = list; l; l = l->next)
-               columns[k--] = l->data;
-
-       g_slist_free(list);
-
-       return columns;
+       if (!nr || nr > inc->column_want_count)
+               return NULL;
+       return &inc->column_details[nr - 1];
 }
 
-static int parse_multi_columns(char **columns, struct context *inc)
+/*
+ * Primitive operations for text input: Strip comments off text lines.
+ * Split text lines into columns. Process input text for individual
+ * columns.
+ */
+
+static void strip_comment(char *buf, const GString *prefix)
 {
-       gsize i;
+       char *ptr;
 
-       /* Clear buffer in order to set bits only. */
-       memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
+       if (!prefix->len)
+               return;
 
-       for (i = 0; i < inc->num_channels; i++) {
-               if (columns[i][0] == '1') {
-                       inc->sample_buffer[i / 8] |= (1 << (i % 8));
-               } else if (!strlen(columns[i])) {
-                       sr_err("Column %zu in line %zu is empty.",
-                               inc->first_channel + i, inc->line_number);
-                       return SR_ERR;
-               } else if (columns[i][0] != '0') {
-                       sr_err("Invalid value '%s' in column %zu in line %zu.",
-                               columns[i], inc->first_channel + i,
-                               inc->line_number);
-                       return SR_ERR;
-               }
+       if ((ptr = strstr(buf, prefix->str))) {
+               *ptr = '\0';
+               g_strstrip(buf);
        }
-
-       return SR_OK;
 }
 
-static int parse_single_column(const char *column, struct context *inc)
+/**
+ * @brief Splits a text line into a set of columns.
+ *
+ * @param[in] buf      The input text line to split.
+ * @param[in] inc      The input module's context.
+ *
+ * @returns An array of strings, representing the columns' text.
+ *
+ * This routine splits a text line on previously determined separators.
+ */
+static char **split_line(char *buf, struct context *inc)
 {
-       int res;
-
-       res = SR_ERR;
-
-       switch (inc->format) {
-       case FORMAT_BIN:
-               res = parse_binstr(column, inc);
-               break;
-       case FORMAT_HEX:
-               res = parse_hexstr(column, inc);
-               break;
-       case FORMAT_OCT:
-               res = parse_octstr(column, inc);
-               break;
-       }
-
-       return res;
+       return g_strsplit(buf, inc->delimiter->str, 0);
 }
 
-static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
-               gsize buffer_size, gsize count)
+/**
+ * @brief Parse a multi-bit field into several logic channels.
+ *
+ * @param[in] column   The input text, a run of bin/hex/oct digits.
+ * @param[in] inc      The input module's context.
+ * @param[in] col_nr   The involved column number (1-based).
+ *
+ * @retval SR_OK       Success.
+ * @retval SR_ERR      Invalid input data (empty, or format error).
+ *
+ * This routine modifies the logic levels in the current sample set,
+ * based on the text input and a user provided format spec.
+ */
+static int parse_column(const char *column, struct context *inc, size_t col_nr)
 {
-       struct sr_datafeed_packet packet;
-       struct sr_datafeed_logic logic;
-       int res;
-       gsize i;
+       const struct column_details *col_det;
+       size_t length, ch_rem, ch_idx, ch_inc;
+       const char *rdptr;
+       char c;
+       gboolean valid;
+       const char *type_text;
+       uint8_t bits;
+
+       /* See whether and how the columns needs to get processed. */
+       col_det = lookup_column_details(inc, col_nr);
+       if (!col_det) {
+               sr_dbg("Column %zu in line %zu without processing details?",
+                       col_nr, inc->line_number);
+               return SR_ERR;
+       }
+       if (col_det->text_format == FORMAT_NONE)
+               return SR_OK;
 
-       packet.type = SR_DF_LOGIC;
-       packet.payload = &logic;
-       logic.unitsize = buffer_size;
-       logic.length = buffer_size;
-       logic.data = buffer;
+       /*
+        * Prepare to read the digits from the text end towards the start.
+        * A digit corresponds to a variable number of channels (depending
+        * on the value's radix). Prepare the mapping of text digits to
+        * (a number of) logic channels.
+        */
+       length = strlen(column);
+       if (!length) {
+               sr_err("Column %zu in line %zu is empty.", col_nr,
+                       inc->line_number);
+               return SR_ERR;
+       }
+       rdptr = &column[length];
+       ch_idx = col_det->channel_offset;
+       ch_rem = col_det->channel_count;
 
-       for (i = 0; i < count; i++) {
-               if ((res = sr_session_send(sdi, &packet)) != SR_OK)
-                       return res;
+       /*
+        * Get another digit and derive up to four logic channels' state from
+        * it. Make sure to not process more bits than the column has channels
+        * associated with it.
+        */
+       while (rdptr > column && ch_rem) {
+               /* Check for valid digits according to the input radix. */
+               c = *(--rdptr);
+               switch (inc->format) {
+               case FORMAT_BIN:
+                       valid = g_ascii_isxdigit(c) && c < '2';
+                       ch_inc = 1;
+                       break;
+               case FORMAT_OCT:
+                       valid = g_ascii_isxdigit(c) && c < '8';
+                       ch_inc = 3;
+                       break;
+               case FORMAT_HEX:
+                       valid = g_ascii_isxdigit(c);
+                       ch_inc = 4;
+                       break;
+               default:
+                       valid = FALSE;
+                       break;
+               }
+               if (!valid) {
+                       type_text = col_format_text[inc->format];
+                       sr_err("Invalid text '%s' in %s type column %zu in line %zu.",
+                               column, type_text, col_nr, inc->line_number);
+                       return SR_ERR;
+               }
+               /* Use the digit's bits for logic channels' data. */
+               bits = g_ascii_xdigit_value(c);
+               switch (inc->format) {
+               case FORMAT_NONE:
+                       /* ShouldNotHappen(TM), but silences compiler warning. */
+                       return SR_ERR;
+               case FORMAT_HEX:
+                       if (ch_rem >= 4) {
+                               ch_rem--;
+                               set_logic_level(inc, ch_idx + 3, bits & (1 << 3));
+                       }
+                       /* FALLTHROUGH */
+               case FORMAT_OCT:
+                       if (ch_rem >= 3) {
+                               ch_rem--;
+                               set_logic_level(inc, ch_idx + 2, bits & (1 << 2));
+                       }
+                       if (ch_rem >= 2) {
+                               ch_rem--;
+                               set_logic_level(inc, ch_idx + 1, bits & (1 << 1));
+                       }
+                       /* FALLTHROUGH */
+               case FORMAT_BIN:
+                       ch_rem--;
+                       set_logic_level(inc, ch_idx + 0, bits & (1 << 0));
+                       break;
+               }
+               ch_idx += ch_inc;
        }
+       /*
+        * TODO Determine whether the availability of extra input data
+        * for unhandled logic channels is worth warning here. In this
+        * implementation users are in control, and can have the more
+        * significant bits ignored (which can be considered a feature
+        * and not really a limitation).
+        */
 
        return SR_OK;
 }
@@ -382,19 +509,20 @@ static int init(struct sr_input *in, GHashTable *options)
 {
        struct context *inc;
        const char *s;
+       int ret;
 
        in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
        in->priv = inc = g_malloc0(sizeof(struct context));
 
-       inc->single_column = g_variant_get_int32(g_hash_table_lookup(options, "single-column"));
+       inc->single_column = g_variant_get_uint32(g_hash_table_lookup(options, "single-column"));
        inc->multi_column_mode = inc->single_column == 0;
 
-       inc->num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
+       inc->num_channels = g_variant_get_uint32(g_hash_table_lookup(options, "numchannels"));
 
        inc->delimiter = g_string_new(g_variant_get_string(
                        g_hash_table_lookup(options, "delimiter"), NULL));
        if (inc->delimiter->len == 0) {
-               sr_err("Delimiter must be at least one character.");
+               sr_err("Column delimiter cannot be empty.");
                return SR_ERR_ARG;
        }
 
@@ -413,37 +541,109 @@ static int init(struct sr_input *in, GHashTable *options)
        inc->comment = g_string_new(g_variant_get_string(
                        g_hash_table_lookup(options, "comment"), NULL));
        if (g_string_equal(inc->comment, inc->delimiter)) {
-               /* That's never going to work. Likely the result of the user
-                * setting the delimiter to ; -- the default comment. Clearing
-                * the comment setting will work in that case. */
+               /*
+                * Using the same sequence as comment leader and column
+                * delimiter won't work. The user probably specified ';'
+                * as the column delimiter but did not adjust the comment
+                * leader. Try DWIM, drop comment strippin support here.
+                */
+               sr_warn("Comment leader and column delimiter conflict, disabling comment support.");
                g_string_truncate(inc->comment, 0);
        }
 
        inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
 
-       inc->first_channel = g_variant_get_int32(g_hash_table_lookup(options, "first-channel"));
+       inc->first_column = g_variant_get_uint32(g_hash_table_lookup(options, "first-column"));
 
-       inc->header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
+       inc->use_header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
 
-       inc->start_line = g_variant_get_int32(g_hash_table_lookup(options, "startline"));
+       inc->start_line = g_variant_get_uint32(g_hash_table_lookup(options, "startline"));
        if (inc->start_line < 1) {
                sr_err("Invalid start line %zu.", inc->start_line);
                return SR_ERR_ARG;
        }
 
-       if (inc->multi_column_mode)
-               inc->first_column = inc->first_channel;
-       else
-               inc->first_column = inc->single_column;
-
-       if (!inc->multi_column_mode && !inc->num_channels) {
-               sr_err("Number of channels needs to be specified in single column mode.");
+       /*
+        * Derive the set of columns to inspect and their respective
+        * formats from simple input specs. Remain close to the previous
+        * set of option keywords and their meaning. Exclusively support
+        * a single column with multiple bits in it, or an adjacent set
+        * of colums with one bit each. The latter may not know the total
+        * column count here (when the user omitted the spec), and will
+        * derive it from the first text line of the input file.
+        */
+       if (inc->single_column && inc->num_channels) {
+               sr_dbg("DIAG Got single column (%zu) and channels (%zu).",
+                       inc->single_column, inc->num_channels);
+               sr_dbg("DIAG -> column %zu, %zu bits in %s format.",
+                       inc->single_column, inc->num_channels,
+                       col_format_text[inc->format]);
+               ret = make_column_details_single(inc,
+                       inc->single_column, inc->num_channels, inc->format);
+               if (ret != SR_OK)
+                       return ret;
+       } else if (inc->multi_column_mode) {
+               sr_dbg("DIAG Got multi-column, first column %zu, count %zu.",
+                       inc->first_column, inc->num_channels);
+               if (inc->num_channels) {
+                       sr_dbg("DIAG -> columns %zu-%zu, 1 bit each.",
+                               inc->first_column,
+                               inc->first_column + inc->num_channels - 1);
+                       ret = make_column_details_multi(inc, inc->first_column,
+                               inc->first_column + inc->num_channels - 1);
+                       if (ret != SR_OK)
+                               return ret;
+               } else {
+                       sr_dbg("DIAG -> incomplete spec, have to update later.");
+               }
+       } else {
+               sr_err("Unknown or unsupported combination of option values.");
                return SR_ERR_ARG;
        }
 
        return SR_OK;
 }
 
+/*
+ * Check the channel list for consistency across file re-import. See
+ * the VCD input module for more details and motivation.
+ */
+
+static void keep_header_for_reread(const struct sr_input *in)
+{
+       struct context *inc;
+
+       inc = in->priv;
+       g_slist_free_full(inc->prev_sr_channels, sr_channel_free_cb);
+       inc->prev_sr_channels = in->sdi->channels;
+       in->sdi->channels = NULL;
+}
+
+static int check_header_in_reread(const struct sr_input *in)
+{
+       struct context *inc;
+
+       if (!in)
+               return FALSE;
+       inc = in->priv;
+       if (!inc)
+               return FALSE;
+       if (!inc->prev_sr_channels)
+               return TRUE;
+
+       if (sr_channel_lists_differ(inc->prev_sr_channels, in->sdi->channels)) {
+               sr_err("Channel list change not supported for file re-read.");
+               return FALSE;
+       }
+       g_slist_free_full(in->sdi->channels, sr_channel_free_cb);
+       in->sdi->channels = inc->prev_sr_channels;
+       inc->prev_sr_channels = NULL;
+
+       return TRUE;
+}
+
+static const char *delim_set = "\r\n";
+
 static const char *get_line_termination(GString *buf)
 {
        const char *term;
@@ -463,29 +663,32 @@ static int initial_parse(const struct sr_input *in, GString *buf)
 {
        struct context *inc;
        GString *channel_name;
-       unsigned int num_columns, i;
-       size_t line_number, l;
+       size_t num_columns, ch_idx, ch_name_idx, col_idx, col_nr;
+       size_t line_number, line_idx;
        int ret;
-       char **lines, **columns;
+       char **lines, *line, **columns, *column;
+       const char *col_caption;
+       gboolean got_caption;
+       const struct column_details *detail;
 
        ret = SR_OK;
        inc = in->priv;
        columns = NULL;
 
        line_number = 0;
-       lines = g_strsplit_set(buf->str, "\r\n", 0);
-       for (l = 0; lines[l]; l++) {
+       lines = g_strsplit_set(buf->str, delim_set, 0);
+       for (line_idx = 0; (line = lines[line_idx]); line_idx++) {
                line_number++;
                if (inc->start_line > line_number) {
-                       sr_spew("Line %zu skipped.", line_number);
+                       sr_spew("Line %zu skipped (before start).", line_number);
                        continue;
                }
-               if (lines[l][0] == '\0') {
+               if (line[0] == '\0') {
                        sr_spew("Blank line %zu skipped.", line_number);
                        continue;
                }
-               strip_comment(lines[l], inc->comment);
-               if (lines[l][0] == '\0') {
+               strip_comment(line, inc->comment);
+               if (line[0] == '\0') {
                        sr_spew("Comment-only line %zu skipped.", line_number);
                        continue;
                }
@@ -493,70 +696,105 @@ static int initial_parse(const struct sr_input *in, GString *buf)
                /* Reached first proper line. */
                break;
        }
-       if (!lines[l]) {
+       if (!line) {
                /* Not enough data for a proper line yet. */
                ret = SR_ERR_NA;
                goto out;
        }
 
-       /*
-        * In order to determine the number of columns parse the current line
-        * without limiting the number of columns.
-        */
-       if (!(columns = parse_line(lines[l], inc, -1))) {
+       /* See how many columns the current line has. */
+       columns = split_line(line, inc);
+       if (!columns) {
                sr_err("Error while parsing line %zu.", line_number);
                ret = SR_ERR;
                goto out;
        }
        num_columns = g_strv_length(columns);
-
-       /* Ensure that the first column is not out of bounds. */
        if (!num_columns) {
-               sr_err("Column %u in line %zu is out of bounds.",
-                       inc->first_column, line_number);
+               sr_err("Error while parsing line %zu.", line_number);
                ret = SR_ERR;
                goto out;
        }
-
-       if (inc->multi_column_mode) {
-               /*
-                * Detect the number of channels in multi column mode
-                * automatically if not specified.
-                */
-               if (!inc->num_channels) {
-                       inc->num_channels = num_columns;
-                       sr_dbg("Number of auto-detected channels: %u.",
-                               inc->num_channels);
-               }
-
-               /*
-                * Ensure that the number of channels does not exceed the number
-                * of columns in multi column mode.
-                */
-               if (num_columns < inc->num_channels) {
-                       sr_err("Not enough columns for desired number of channels in line %zu.",
-                               line_number);
-                       ret = SR_ERR;
+       sr_dbg("DIAG Got %zu columns in text line: %s.", num_columns, line);
+
+       /* Optionally update incomplete multi-column specs. */
+       if (inc->multi_column_mode && !inc->num_channels) {
+               inc->num_channels = num_columns - inc->first_column + 1;
+               sr_dbg("DIAG -> multi-column update: columns %zu-%zu, 1 bit each.",
+                       inc->first_column,
+                       inc->first_column + inc->num_channels - 1);
+               ret = make_column_details_multi(inc, inc->first_column,
+                       inc->first_column + inc->num_channels - 1);
+               if (ret != SR_OK)
                        goto out;
-               }
        }
 
+       /*
+        * Assume all lines have equal length (column count). Bail out
+        * early on suspicious or insufficient input data (check input
+        * which became available here against previous user specs or
+        * auto-determined properties, regardless of layout variant).
+        */
+       if (num_columns < inc->column_want_count) {
+               sr_err("Insufficient input text width for desired data amount, got %zu but want %zu columns.",
+                       num_columns, inc->column_want_count);
+               ret = SR_ERR;
+               goto out;
+       }
+
+       /*
+        * Determine channel names. Optionally use text from a header
+        * line (when requested by the user, and only works in multi
+        * column mode). In the absence of header text, or in single
+        * column mode, channels are assigned rather generic names.
+        *
+        * Manipulation of the column's caption is acceptable here, the
+        * header line will never get processed another time.
+        */
        channel_name = g_string_sized_new(64);
-       for (i = 0; i < inc->num_channels; i++) {
-               if (inc->header && inc->multi_column_mode && columns[i][0] != '\0')
-                       g_string_assign(channel_name, columns[i]);
-               else
-                       g_string_printf(channel_name, "%u", i);
-               sr_channel_new(in->sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name->str);
+       for (col_idx = 0; col_idx < inc->column_want_count; col_idx++) {
+
+               col_nr = col_idx + 1;
+               detail = lookup_column_details(inc, col_nr);
+               if (detail->text_format == FORMAT_NONE)
+                       continue;
+               column = columns[col_idx];
+               col_caption = sr_scpi_unquote_string(column);
+               got_caption = inc->use_header && *col_caption;
+               sr_dbg("DIAG col %zu, ch count %zu, text %s.",
+                       col_nr, detail->channel_count, col_caption);
+               for (ch_idx = 0; ch_idx < detail->channel_count; ch_idx++) {
+                       ch_name_idx = detail->channel_offset + ch_idx;
+                       if (got_caption && detail->channel_count == 1)
+                               g_string_assign(channel_name, col_caption);
+                       else if (got_caption)
+                               g_string_printf(channel_name, "%s[%zu]",
+                                       col_caption, ch_idx);
+                       else
+                               g_string_printf(channel_name, "%zu", ch_name_idx);
+                       sr_dbg("DIAG ch idx %zu, name %s.", ch_name_idx, channel_name->str);
+                       sr_channel_new(in->sdi, ch_name_idx, SR_CHANNEL_LOGIC, TRUE,
+                               channel_name->str);
+               }
        }
        g_string_free(channel_name, TRUE);
+       if (!check_header_in_reread(in)) {
+               ret = SR_ERR_DATA;
+               goto out;
+       }
 
        /*
-        * Calculate the minimum buffer size to store the sample data of the
-        * channels.
+        * Calculate the minimum buffer size to store the set of samples
+        * of all channels (unit size). Determine a larger buffer size
+        * for datafeed submission that is a multiple of the unit size.
+        * Allocate the larger buffer, the "sample buffer" will point
+        * to a location within that large buffer later.
         */
-       inc->sample_buffer_size = (inc->num_channels + 7) >> 3;
-       inc->sample_buffer = g_malloc(inc->sample_buffer_size);
+       inc->sample_unit_size = (inc->num_channels + 7) / 8;
+       inc->datafeed_buf_size = CHUNK_SIZE;
+       inc->datafeed_buf_size *= inc->sample_unit_size;
+       inc->datafeed_buffer = g_malloc(inc->datafeed_buf_size);
+       inc->datafeed_buf_fill = 0;
 
 out:
        if (columns)
@@ -566,6 +804,27 @@ out:
        return ret;
 }
 
+/*
+ * Gets called from initial_receive(), which runs until the end-of-line
+ * encoding of the input stream could get determined. Assumes that this
+ * routine receives enough buffered initial input data to either see the
+ * BOM when there is one, or that no BOM will follow when a text line
+ * termination sequence was seen. Silently drops the UTF-8 BOM sequence
+ * from the input buffer if one was seen. Does not care to protect
+ * against multiple execution or dropping the BOM multiple times --
+ * there should be at most one in the input stream.
+ */
+static void initial_bom_check(const struct sr_input *in)
+{
+       static const char *utf8_bom = "\xef\xbb\xbf";
+
+       if (in->buf->len < strlen(utf8_bom))
+               return;
+       if (strncmp(in->buf->str, utf8_bom, strlen(utf8_bom)) != 0)
+               return;
+       g_string_erase(in->buf, 0, strlen(utf8_bom));
+}
+
 static int initial_receive(const struct sr_input *in)
 {
        struct context *inc;
@@ -574,13 +833,17 @@ static int initial_receive(const struct sr_input *in)
        char *p;
        const char *termination;
 
+       initial_bom_check(in);
+
        inc = in->priv;
 
-       if (!(termination = get_line_termination(in->buf)))
+       termination = get_line_termination(in->buf);
+       if (!termination)
                /* Don't have a full line yet. */
                return SR_ERR_NA;
 
-       if (!(p = g_strrstr_len(in->buf->str, in->buf->len, termination)))
+       p = g_strrstr_len(in->buf->str, in->buf->len, termination);
+       if (!p)
                /* Don't have a full line yet. */
                return SR_ERR_NA;
        len = p - in->buf->str - 1;
@@ -599,113 +862,111 @@ static int initial_receive(const struct sr_input *in)
        return ret;
 }
 
-static int process_buffer(struct sr_input *in)
+static int process_buffer(struct sr_input *in, gboolean is_eof)
 {
-       struct sr_datafeed_packet packet;
-       struct sr_datafeed_meta meta;
-       struct sr_config *src;
        struct context *inc;
        gsize num_columns;
-       uint64_t samplerate;
-       int max_columns, ret, l;
-       char *p, **lines, **columns;
+       size_t line_idx, col_idx, col_nr;
+       int ret;
+       char *p, **lines, *line, **columns, *column;
 
        inc = in->priv;
        if (!inc->started) {
                std_session_send_df_header(in->sdi);
-
-               if (inc->samplerate) {
-                       packet.type = SR_DF_META;
-                       packet.payload = &meta;
-                       samplerate = inc->samplerate;
-                       src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
-                       meta.config = g_slist_append(NULL, src);
-                       sr_session_send(in->sdi, &packet);
-                       g_slist_free(meta.config);
-                       sr_config_free(src);
-               }
-
                inc->started = TRUE;
        }
 
-       if (!(p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination)))
-               /* Don't have a full line. */
-               return SR_ERR;
-
-       *p = '\0';
+       /*
+        * Consider empty input non-fatal. Keep accumulating input until
+        * at least one full text line has become available. Grab the
+        * maximum amount of accumulated data that consists of full text
+        * lines, and process what has been received so far, leaving not
+        * yet complete lines for the next invocation.
+        *
+        * Enforce that all previously buffered data gets processed in
+        * the "EOF" condition. Do not insist in the presence of the
+        * termination sequence for the last line (may often be missing
+        * on Windows). A present termination sequence will just result
+        * in the "execution of an empty line", and does not harm.
+        */
+       if (!in->buf->len)
+               return SR_OK;
+       if (is_eof) {
+               p = in->buf->str + in->buf->len;
+       } else {
+               p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination);
+               if (!p)
+                       return SR_ERR;
+               *p = '\0';
+               p += strlen(inc->termination);
+       }
        g_strstrip(in->buf->str);
 
-       /* Limit the number of columns to parse. */
-       if (inc->multi_column_mode)
-               max_columns = inc->num_channels;
-       else
-               max_columns = 1;
-
        ret = SR_OK;
-       lines = g_strsplit_set(in->buf->str, "\r\n", 0);
-       for (l = 0; lines[l]; l++) {
+       lines = g_strsplit_set(in->buf->str, delim_set, 0);
+       for (line_idx = 0; (line = lines[line_idx]); line_idx++) {
                inc->line_number++;
-               if (lines[l][0] == '\0') {
+               if (line[0] == '\0') {
                        sr_spew("Blank line %zu skipped.", inc->line_number);
                        continue;
                }
 
                /* Remove trailing comment. */
-               strip_comment(lines[l], inc->comment);
-               if (lines[l][0] == '\0') {
+               strip_comment(line, inc->comment);
+               if (line[0] == '\0') {
                        sr_spew("Comment-only line %zu skipped.", inc->line_number);
                        continue;
                }
 
                /* Skip the header line, its content was used as the channel names. */
-               if (inc->header) {
+               if (inc->use_header && !inc->header_seen) {
                        sr_spew("Header line %zu skipped.", inc->line_number);
-                       inc->header = FALSE;
+                       inc->header_seen = TRUE;
                        continue;
                }
 
-               if (!(columns = parse_line(lines[l], inc, max_columns))) {
+               /* Split the line into columns, check for minimum length. */
+               columns = split_line(line, inc);
+               if (!columns) {
                        sr_err("Error while parsing line %zu.", inc->line_number);
+                       g_strfreev(lines);
                        return SR_ERR;
                }
                num_columns = g_strv_length(columns);
-               if (!num_columns) {
-                       sr_err("Column %u in line %zu is out of bounds.",
-                               inc->first_column, inc->line_number);
-                       g_strfreev(columns);
-                       return SR_ERR;
-               }
-               /*
-                * Ensure that the number of channels does not exceed the number
-                * of columns in multi column mode.
-                */
-               if (inc->multi_column_mode && num_columns < inc->num_channels) {
-                       sr_err("Not enough columns for desired number of channels in line %zu.",
-                               inc->line_number);
+               if (num_columns < inc->column_want_count) {
+                       sr_err("Insufficient column count %zu in line %zu.",
+                               num_columns, inc->line_number);
                        g_strfreev(columns);
+                       g_strfreev(lines);
                        return SR_ERR;
                }
 
-               if (inc->multi_column_mode)
-                       ret = parse_multi_columns(columns, inc);
-               else
-                       ret = parse_single_column(columns[0], inc);
-               if (ret != SR_OK) {
-                       g_strfreev(columns);
-                       return SR_ERR;
+               clear_logic_samples(inc);
+
+               for (col_idx = 0; col_idx < inc->column_want_count; col_idx++) {
+                       column = columns[col_idx];
+                       col_nr = col_idx + 1;
+                       ret = parse_column(column, inc, col_nr);
+                       if (ret != SR_OK) {
+                               g_strfreev(columns);
+                               g_strfreev(lines);
+                               return SR_ERR;
+                       }
                }
 
-               /* Send sample data to the session bus. */
-               ret = send_samples(in->sdi, inc->sample_buffer,
-                       inc->sample_buffer_size, 1);
+               /* Send sample data to the session bus (buffered). */
+               ret = queue_logic_samples(in);
                if (ret != SR_OK) {
                        sr_err("Sending samples failed.");
+                       g_strfreev(columns);
+                       g_strfreev(lines);
                        return SR_ERR;
                }
+
                g_strfreev(columns);
        }
        g_strfreev(lines);
-       g_string_erase(in->buf, 0, p - in->buf->str + 1);
+       g_string_erase(in->buf, 0, p - in->buf->str);
 
        return ret;
 }
@@ -719,7 +980,8 @@ static int receive(struct sr_input *in, GString *buf)
 
        inc = in->priv;
        if (!inc->termination) {
-               if ((ret = initial_receive(in)) == SR_ERR_NA)
+               ret = initial_receive(in);
+               if (ret == SR_ERR_NA)
                        /* Not enough data yet. */
                        return SR_OK;
                else if (ret != SR_OK)
@@ -730,7 +992,7 @@ static int receive(struct sr_input *in, GString *buf)
                return SR_OK;
        }
 
-       ret = process_buffer(in);
+       ret = process_buffer(in, FALSE);
 
        return ret;
 }
@@ -741,9 +1003,15 @@ static int end(struct sr_input *in)
        int ret;
 
        if (in->sdi_ready)
-               ret = process_buffer(in);
+               ret = process_buffer(in, TRUE);
        else
                ret = SR_OK;
+       if (ret != SR_OK)
+               return ret;
+
+       ret = flush_logic_samples(in);
+       if (ret != SR_OK)
+               return ret;
 
        inc = in->priv;
        if (inc->started)
@@ -756,16 +1024,14 @@ static void cleanup(struct sr_input *in)
 {
        struct context *inc;
 
-       inc = in->priv;
-
-       if (inc->delimiter)
-               g_string_free(inc->delimiter, TRUE);
+       keep_header_for_reread(in);
 
-       if (inc->comment)
-               g_string_free(inc->comment, TRUE);
+       inc = in->priv;
 
        g_free(inc->termination);
-       g_free(inc->sample_buffer);
+       inc->termination = NULL;
+       g_free(inc->datafeed_buffer);
+       inc->datafeed_buffer = NULL;
 }
 
 static int reset(struct sr_input *in)
@@ -779,31 +1045,51 @@ static int reset(struct sr_input *in)
        return SR_OK;
 }
 
+enum option_index {
+       OPT_SINGLE_COL,
+       OPT_NUM_LOGIC,
+       OPT_DELIM,
+       OPT_FORMAT,
+       OPT_COMMENT,
+       OPT_RATE,
+       OPT_FIRST_COL,
+       OPT_HEADER,
+       OPT_START,
+       OPT_MAX,
+};
+
 static struct sr_option options[] = {
-       { "single-column", "Single column", "Enable/specify single column", NULL, NULL },
-       { "numchannels", "Max channels", "Number of channels", NULL, NULL },
-       { "delimiter", "Delimiter", "Column delimiter", NULL, NULL },
-       { "format", "Format", "Numeric format", NULL, NULL },
-       { "comment", "Comment", "Comment prefix character", NULL, NULL },
-       { "samplerate", "Samplerate", "Samplerate used during capture", NULL, NULL },
-       { "first-channel", "First channel", "Column number of first channel", NULL, NULL },
-       { "header", "Header", "Treat first line as header with channel names", NULL, NULL },
-       { "startline", "Start line", "Line number at which to start processing samples", NULL, NULL },
-       ALL_ZERO
+       [OPT_SINGLE_COL] = { "single-column", "Single column", "Enable single-column mode, using the specified column (>= 1); 0: multi-col. mode", NULL, NULL },
+       [OPT_NUM_LOGIC] = { "numchannels", "Number of logic channels", "The number of (logic) channels (single-col. mode: number of bits beginning at 'first channel', LSB-first)", NULL, NULL },
+       [OPT_DELIM] = { "delimiter", "Column delimiter", "The column delimiter (>= 1 characters)", NULL, NULL },
+       [OPT_FORMAT] = { "format", "Data format (single-col. mode)", "The numeric format of the data (single-col. mode): bin, hex, oct", NULL, NULL },
+       [OPT_COMMENT] = { "comment", "Comment character(s)", "The comment prefix character(s)", NULL, NULL },
+       [OPT_RATE] = { "samplerate", "Samplerate (Hz)", "The sample rate (used during capture) in Hz", NULL, NULL },
+       [OPT_FIRST_COL] = { "first-column", "First column", "The column number of the first channel (multi-col. mode)", NULL, NULL },
+       [OPT_HEADER] = { "header", "Interpret first line as header (multi-col. mode)", "Treat the first line as header with channel names (multi-col. mode)", NULL, NULL },
+       [OPT_START] = { "startline", "Start line", "The line number at which to start processing samples (>= 1)", NULL, NULL },
+       [OPT_MAX] = ALL_ZERO,
 };
 
 static const struct sr_option *get_options(void)
 {
+       GSList *l;
+
        if (!options[0].def) {
-               options[0].def = g_variant_ref_sink(g_variant_new_int32(0));
-               options[1].def = g_variant_ref_sink(g_variant_new_int32(0));
-               options[2].def = g_variant_ref_sink(g_variant_new_string(","));
-               options[3].def = g_variant_ref_sink(g_variant_new_string("bin"));
-               options[4].def = g_variant_ref_sink(g_variant_new_string(";"));
-               options[5].def = g_variant_ref_sink(g_variant_new_uint64(0));
-               options[6].def = g_variant_ref_sink(g_variant_new_int32(0));
-               options[7].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
-               options[8].def = g_variant_ref_sink(g_variant_new_int32(1));
+               options[OPT_SINGLE_COL].def = g_variant_ref_sink(g_variant_new_uint32(0));
+               options[OPT_NUM_LOGIC].def = g_variant_ref_sink(g_variant_new_uint32(0));
+               options[OPT_DELIM].def = g_variant_ref_sink(g_variant_new_string(","));
+               options[OPT_FORMAT].def = g_variant_ref_sink(g_variant_new_string("bin"));
+               l = NULL;
+               l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("bin")));
+               l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("hex")));
+               l = g_slist_append(l, g_variant_ref_sink(g_variant_new_string("oct")));
+               options[OPT_FORMAT].values = l;
+               options[OPT_COMMENT].def = g_variant_ref_sink(g_variant_new_string(";"));
+               options[OPT_RATE].def = g_variant_ref_sink(g_variant_new_uint64(0));
+               options[OPT_FIRST_COL].def = g_variant_ref_sink(g_variant_new_uint32(1));
+               options[OPT_HEADER].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
+               options[OPT_START].def = g_variant_ref_sink(g_variant_new_uint32(1));
        }
 
        return options;