]> sigrok.org Git - libsigrok.git/blobdiff - src/input/chronovu_la8.c
device: introduce common helpers for channel group allocation
[libsigrok.git] / src / input / chronovu_la8.c
index 0ac5e54a8fd23910151b18296c04aa82eb8d7c7e..91d05b90427fc349eec28299f76ae901cee49f39 100644 (file)
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+ * along with this program; if not, see <http://www.gnu.org/licenses/>.
  */
 
+#include <config.h>
 #include <stdlib.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/stat.h>
-#include "libsigrok.h"
+#include <libsigrok/libsigrok.h>
 #include "libsigrok-internal.h"
 
 #define LOG_PREFIX "input/chronovu-la8"
 
-#define NUM_PACKETS            2048
-#define PACKET_SIZE            4096
-#define DEFAULT_NUM_CHANNELS   8
+#define DEFAULT_NUM_CHANNELS    8
+#define DEFAULT_SAMPLERATE      SR_MHZ(100)
+#define CHUNK_SIZE              (4 * 1024 * 1024)
 
-/**
- * Convert the LA8 'divcount' value to the respective samplerate (in Hz).
+/*
+ * File layout:
+ * - Fixed size 8MiB data part at offset 0.
+ *   - Either one byte per sample for LA8.
+ *   - Or two bytes per sample for LA16, in little endian format.
+ * - Five byte "header" at offset 8MiB.
+ *   - One "clock divider" byte. The byte value is the divider factor
+ *     minus 1. Value 0xff is invalid. Base clock is 100MHz for LA8, or
+ *     200MHz for LA16.
+ *   - Four bytes for the trigger position. This 32bit value is the
+ *     sample number in little endian format, or 0 when unused.
+ */
+#define CHRONOVU_LA8_DATASIZE   (8 * 1024 * 1024)
+#define CHRONOVU_LA8_HDRSIZE    (sizeof(uint8_t) + sizeof(uint32_t))
+#define CHRONOVU_LA8_FILESIZE   (CHRONOVU_LA8_DATASIZE + CHRONOVU_LA8_HDRSIZE)
+
+/*
+ * Implementation note:
  *
- * LA8 hardware: sample period = (divcount + 1) * 10ns.
- * Min. value for divcount: 0x00 (10ns sample period, 100MHz samplerate).
- * Max. value for divcount: 0xfe (2550ns sample period, 392.15kHz samplerate).
+ * The .format_match() routine only checks the file size, but none of
+ * the header fields. Only little would be gained (only clock divider
+ * 0xff could get tested), but complexity would increase dramatically.
+ * Also the .format_match() routine is unlikely to receive large enough
+ * a buffer to include the header. Neither is the filename available to
+ * the .format_match() routine.
  *
- * @param divcount The divcount value as needed by the hardware.
+ * There is no way to programmatically tell whether the file was created
+ * by LA8 or LA16 software, i.e. with 8 or 16 logic channels. If the
+ * filename was available, one might guess based on the file extension,
+ * but still would require user specs if neither of the known extensions
+ * were used or the input is fed from a pipe.
  *
- * @return The samplerate in Hz, or 0xffffffffffffffff upon errors.
+ * The current input module implementation assumes that users specify
+ * the (channel count and) sample rate. Input data gets processed and
+ * passed along to the session bus, before the file "header" is seen.
+ * A future implementation could move channel creation from init() to
+ * receive() or end() (actually: a common routine called from those two
+ * routines), and could defer sample processing and feeding the session
+ * until the header was seen, including deferred samplerate calculation
+ * after having seen the header. But again this improvement depends on
+ * the availability of either the filename or the device type. Also note
+ * that applications then had to keep sending data to the input module's
+ * receive() routine until sufficient amounts of input data were seen
+ * including the header (see bug #1017).
  */
-static uint64_t divcount_to_samplerate(uint8_t divcount)
+
+struct context {
+       gboolean started;
+       uint64_t samplerate;
+       uint64_t samples_remain;
+};
+
+static int format_match(GHashTable *metadata, unsigned int *confidence)
 {
-       if (divcount == 0xff)
-               return 0xffffffffffffffffULL;
+       uint64_t size;
+
+       /*
+        * In the absence of a reliable condition like magic strings,
+        * we can only guess based on the file size. Since this is
+        * rather weak a condition, signal "little confidence" and
+        * optionally give precedence to better matches.
+        */
+       size = GPOINTER_TO_SIZE(g_hash_table_lookup(metadata,
+                       GINT_TO_POINTER(SR_INPUT_META_FILESIZE)));
+       if (size != CHRONOVU_LA8_FILESIZE)
+               return SR_ERR;
+       *confidence = 100;
 
-       return SR_MHZ(100) / (divcount + 1);
+       return SR_OK;
 }
 
-static int format_match(const char *filename)
+static int init(struct sr_input *in, GHashTable *options)
 {
-       struct stat stat_buf;
-       int ret;
+       struct context *inc;
+       int num_channels, i;
+       char name[16];
 
-       if (!filename) {
-               sr_err("%s: filename was NULL", __func__);
-               // return SR_ERR; /* FIXME */
-               return FALSE;
+       num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
+       if (num_channels < 1) {
+               sr_err("Invalid value for numchannels: must be at least 1.");
+               return SR_ERR_ARG;
        }
 
-       if (!g_file_test(filename, G_FILE_TEST_EXISTS)) {
-               sr_err("%s: input file '%s' does not exist",
-                      __func__, filename);
-               // return SR_ERR; /* FIXME */
-               return FALSE;
-       }
+       in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
+       in->priv = inc = g_malloc0(sizeof(struct context));
 
-       if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR)) {
-               sr_err("%s: input file '%s' not a regular file",
-                      __func__, filename);
-               // return SR_ERR; /* FIXME */
-               return FALSE;
-       }
+       inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
 
-       /* Only accept files of length 8MB + 5 bytes. */
-       ret = stat(filename, &stat_buf);
-       if (ret != 0) {
-               sr_err("%s: Error getting file size of '%s'",
-                      __func__, filename);
-               return FALSE;
-       }
-       if (stat_buf.st_size != (8 * 1024 * 1024 + 5)) {
-               sr_dbg("%s: File size must be exactly 8388613 bytes ("
-                      "it actually is %d bytes in size), so this is not a "
-                      "ChronoVu LA8 file.", __func__, stat_buf.st_size);
-               return FALSE;
+       for (i = 0; i < num_channels; i++) {
+               snprintf(name, sizeof(name), "%d", i);
+               sr_channel_new(in->sdi, i, SR_CHANNEL_LOGIC, TRUE, name);
        }
 
-       /* TODO: Check for divcount != 0xff. */
-
-       return TRUE;
+       return SR_OK;
 }
 
-static int init(struct sr_input *in, const char *filename)
+static int process_buffer(struct sr_input *in)
 {
-       struct sr_channel *ch;
-       int num_channels, i;
-       char name[SR_MAX_CHANNELNAME_LEN + 1];
-       char *param;
+       struct sr_datafeed_packet packet;
+       struct sr_datafeed_logic logic;
+       struct context *inc;
+       gsize chunk_size, i;
+       gsize chunk;
+       uint16_t unitsize;
 
-       (void)filename;
+       inc = in->priv;
+       unitsize = (g_slist_length(in->sdi->channels) + 7) / 8;
 
-       num_channels = DEFAULT_NUM_CHANNELS;
+       if (!inc->started) {
+               std_session_send_df_header(in->sdi);
 
-       if (in->param) {
-               param = g_hash_table_lookup(in->param, "numchannels");
-               if (param) {
-                       num_channels = strtoul(param, NULL, 10);
-                       if (num_channels < 1) {
-                               sr_err("%s: strtoul failed", __func__);
-                               return SR_ERR;
-                       }
+               if (inc->samplerate) {
+                       (void)sr_session_send_meta(in->sdi, SR_CONF_SAMPLERATE,
+                               g_variant_new_uint64(inc->samplerate));
                }
-       }
 
-       /* Create a virtual device. */
-       in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
+               inc->samples_remain = CHRONOVU_LA8_DATASIZE;
+               inc->samples_remain /= unitsize;
 
-       for (i = 0; i < num_channels; i++) {
-               snprintf(name, SR_MAX_CHANNELNAME_LEN, "%d", i);
-               /* TODO: Check return value. */
-               if (!(ch = sr_channel_new(i, SR_CHANNEL_LOGIC, TRUE, name)))
-                       return SR_ERR;
-               in->sdi->channels = g_slist_append(in->sdi->channels, ch);
+               inc->started = TRUE;
        }
 
+       packet.type = SR_DF_LOGIC;
+       packet.payload = &logic;
+       logic.unitsize = unitsize;
+
+       /* Cut off at multiple of unitsize. Avoid sending the "header". */
+       chunk_size = in->buf->len / logic.unitsize * logic.unitsize;
+       chunk_size = MIN(chunk_size, inc->samples_remain * unitsize);
+
+       for (i = 0; i < chunk_size; i += chunk) {
+               logic.data = in->buf->str + i;
+               chunk = MIN(CHUNK_SIZE, chunk_size - i);
+               if (chunk) {
+                       logic.length = chunk;
+                       sr_session_send(in->sdi, &packet);
+                       inc->samples_remain -= chunk / unitsize;
+               }
+       }
+       g_string_erase(in->buf, 0, chunk_size);
+
        return SR_OK;
 }
 
-static int loadfile(struct sr_input *in, const char *filename)
+static int receive(struct sr_input *in, GString *buf)
 {
-       struct sr_datafeed_packet packet;
-       struct sr_datafeed_meta meta;
-       struct sr_datafeed_logic logic;
-       struct sr_config *src;
-       uint8_t buf[PACKET_SIZE], divcount;
-       int i, fd, size, num_channels;
-       uint64_t samplerate;
+       int ret;
 
-       /* TODO: Use glib functions! GIOChannel, g_fopen, etc. */
-       if ((fd = open(filename, O_RDONLY)) == -1) {
-               sr_err("%s: file open failed", __func__);
-               return SR_ERR;
+       g_string_append_len(in->buf, buf->str, buf->len);
+
+       if (!in->sdi_ready) {
+               /* sdi is ready, notify frontend. */
+               in->sdi_ready = TRUE;
+               return SR_OK;
        }
 
-       num_channels = g_slist_length(in->sdi->channels);
+       ret = process_buffer(in);
 
-       /* Seek to the end of the file, and read the divcount byte. */
-       divcount = 0x00; /* TODO: Don't hardcode! */
+       return ret;
+}
 
-       /* Convert the divcount value to a samplerate. */
-       samplerate = divcount_to_samplerate(divcount);
-       if (samplerate == 0xffffffffffffffffULL) {
-               close(fd); /* FIXME */
-               return SR_ERR;
-       }
-       sr_dbg("%s: samplerate is %" PRIu64, __func__, samplerate);
+static int end(struct sr_input *in)
+{
+       struct context *inc;
+       int ret;
 
-       /* Send header packet to the session bus. */
-       std_session_send_df_header(in->sdi, LOG_PREFIX);
+       if (in->sdi_ready)
+               ret = process_buffer(in);
+       else
+               ret = SR_OK;
 
-       /* Send metadata about the SR_DF_LOGIC packets to come. */
-       packet.type = SR_DF_META;
-       packet.payload = &meta;
-       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);
-       sr_config_free(src);
+       inc = in->priv;
+       if (inc->started)
+               std_session_send_df_end(in->sdi);
 
-       /* TODO: Handle trigger point. */
+       return ret;
+}
 
-       /* Send data packets to the session bus. */
-       sr_dbg("%s: sending SR_DF_LOGIC data packets", __func__);
-       packet.type = SR_DF_LOGIC;
-       packet.payload = &logic;
-       logic.unitsize = (num_channels + 7) / 8;
-       logic.data = buf;
-
-       /* Send 8MB of total data to the session bus in small chunks. */
-       for (i = 0; i < NUM_PACKETS; i++) {
-               /* TODO: Handle errors, handle incomplete reads. */
-               size = read(fd, buf, PACKET_SIZE);
-               logic.length = size;
-               sr_session_send(in->sdi, &packet);
-       }
-       close(fd); /* FIXME */
+static int reset(struct sr_input *in)
+{
+       struct context *inc = in->priv;
 
-       /* Send end packet to the session bus. */
-       sr_dbg("%s: sending SR_DF_END", __func__);
-       packet.type = SR_DF_END;
-       packet.payload = NULL;
-       sr_session_send(in->sdi, &packet);
+       inc->started = FALSE;
+       g_string_truncate(in->buf, 0);
 
        return SR_OK;
 }
 
+static struct sr_option options[] = {
+       { "numchannels", "Number of logic channels", "The number of (logic) channels in the data", NULL, NULL },
+       { "samplerate", "Sample rate (Hz)", "The sample rate of the (logic) data in Hz", NULL, NULL },
+       ALL_ZERO
+};
+
+static const struct sr_option *get_options(void)
+{
+       if (!options[0].def) {
+               options[0].def = g_variant_ref_sink(g_variant_new_int32(DEFAULT_NUM_CHANNELS));
+               options[1].def = g_variant_ref_sink(g_variant_new_uint64(DEFAULT_SAMPLERATE));
+       }
+
+       return options;
+}
+
 SR_PRIV struct sr_input_module input_chronovu_la8 = {
        .id = "chronovu-la8",
-       .desc = "ChronoVu LA8",
+       .name = "ChronoVu LA8/LA16",
+       .desc = "ChronoVu LA8/LA16 native file format data",
+       .exts = (const char*[]){"kdt", "kd1", NULL},
+       .metadata = { SR_INPUT_META_FILESIZE | SR_INPUT_META_REQUIRED },
+       .options = get_options,
        .format_match = format_match,
        .init = init,
-       .loadfile = loadfile,
+       .receive = receive,
+       .end = end,
+       .reset = reset,
 };