2 * This file is part of the libsigrok project.
4 * Copyright (C) 2012 Petteri Aimonen <jpa@sr.mail.kapsi.fi>
5 * Copyright (C) 2014 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
21 /* The VCD input module has the following options:
23 * numchannels: Maximum number of channels to use. The channels are
24 * detected in the same order as they are listed
25 * in the $var sections of the VCD file.
27 * skip: Allows skipping until given timestamp in the file.
28 * This can speed up analyzing of long captures.
30 * Value < 0: Skip until first timestamp listed in
33 * Value = 0: Do not skip, instead generate samples
34 * beginning from timestamp 0.
36 * Value > 0: Start at the given timestamp.
38 * downsample: Divide the samplerate by the given factor.
39 * This can speed up analyzing of long captures.
41 * compress: Compress idle periods longer than this value.
42 * This can speed up analyzing of long captures.
43 * Default 0 = don't compress.
45 * Based on Verilog standard IEEE Std 1364-2001 Version C
48 * - $var with 'wire' and 'reg' types of scalar variables
49 * - $timescale definition for samplerate
50 * - multiple character variable identifiers
52 * Most important unsupported features:
53 * - vector variables (bit vectors etc.)
54 * - analog, integer and real number variables
55 * - $dumpvars initial value declaration
57 * - more than 64 channels
64 #include "libsigrok.h"
65 #include "libsigrok-internal.h"
67 #define LOG_PREFIX "input/vcd"
69 #define DEFAULT_NUM_CHANNELS 8
70 #define CHUNKSIZE 1024
76 unsigned int maxchannels;
77 unsigned int channelcount;
81 gboolean skip_until_end;
91 * Reads a single VCD section from input file and parses it to name/contents.
92 * e.g. $timescale 1ps $end => "timescale" "1ps"
94 static gboolean parse_section(GString *buf, gchar **name, gchar **contents)
96 GString *sname, *scontent;
100 *name = *contents = NULL;
104 /* Skip any initial white-space. */
105 while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
108 /* Section tag should start with $. */
109 if (buf->str[pos++] != '$')
112 sname = g_string_sized_new(32);
113 scontent = g_string_sized_new(128);
115 /* Read the section tag. */
116 while (pos < buf->len && !g_ascii_isspace(buf->str[pos]))
117 g_string_append_c(sname, buf->str[pos++]);
119 /* Skip whitespace before content. */
120 while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
123 /* Read the content. */
124 while (pos < buf->len - 4 && strncmp(buf->str + pos, "$end", 4))
125 g_string_append_c(scontent, buf->str[pos++]);
127 if (sname->len && pos < buf->len - 4 && !strncmp(buf->str + pos, "$end", 4)) {
130 while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
132 g_string_erase(buf, 0, pos);
135 *name = g_string_free(sname, !status);
136 *contents = g_string_free(scontent, !status);
138 g_strchomp(*contents);
143 static void free_channel(void *data)
145 struct vcd_channel *vcd_ch = data;
146 g_free(vcd_ch->name);
147 g_free(vcd_ch->identifier);
151 /* Remove empty parts from an array returned by g_strsplit. */
152 static void remove_empty_parts(gchar **parts)
155 gchar **dest = parts;
156 while (*src != NULL) {
166 * Parse VCD header to get values for context structure.
167 * The context structure should be zeroed before calling this.
169 static gboolean parse_header(const struct sr_input *in, GString *buf)
171 struct vcd_channel *vcd_ch;
175 gchar *name, *contents, **parts;
178 name = contents = NULL;
180 while (parse_section(buf, &name, &contents)) {
181 sr_dbg("Section '%s', contents '%s'.", name, contents);
183 if (g_strcmp0(name, "enddefinitions") == 0) {
186 } else if (g_strcmp0(name, "timescale") == 0) {
188 * The standard allows for values 1, 10 or 100
189 * and units s, ms, us, ns, ps and fs.
191 if (sr_parse_period(contents, &p, &q) == SR_OK) {
192 inc->samplerate = q / p;
194 /* Does not happen unless time value is non-standard */
195 sr_warn("Inexact rounding of samplerate, %" PRIu64 " / %" PRIu64 " to %" PRIu64 " Hz.",
196 q, p, inc->samplerate);
199 sr_dbg("Samplerate: %" PRIu64, inc->samplerate);
201 sr_err("Parsing timescale failed.");
203 } else if (g_strcmp0(name, "var") == 0) {
204 /* Format: $var type size identifier reference $end */
205 parts = g_strsplit_set(contents, " \r\n\t", 0);
206 remove_empty_parts(parts);
208 if (g_strv_length(parts) != 4)
209 sr_warn("$var section should have 4 items");
210 else if (g_strcmp0(parts[0], "reg") != 0 && g_strcmp0(parts[0], "wire") != 0)
211 sr_info("Unsupported signal type: '%s'", parts[0]);
212 else if (strtol(parts[1], NULL, 10) != 1)
213 sr_info("Unsupported signal size: '%s'", parts[1]);
214 else if (inc->channelcount >= inc->maxchannels)
215 sr_warn("Skipping '%s' because only %d channels requested.",
216 parts[3], inc->maxchannels);
218 sr_info("Channel %d is '%s' identified by '%s'.",
219 inc->channelcount, parts[3], parts[2]);
220 vcd_ch = g_malloc(sizeof(struct vcd_channel));
221 vcd_ch->identifier = g_strdup(parts[2]);
222 vcd_ch->name = g_strdup(parts[3]);
223 inc->channels = g_slist_append(inc->channels, vcd_ch);
230 g_free(name); name = NULL;
231 g_free(contents); contents = NULL;
236 inc->got_header = status;
241 static int format_match(GHashTable *metadata)
243 GString *buf, *tmpbuf;
245 gchar *name, *contents;
247 buf = g_hash_table_lookup(metadata, GINT_TO_POINTER(SR_INPUT_META_HEADER));
248 tmpbuf = g_string_new_len(buf->str, buf->len);
251 * If we can parse the first section correctly,
252 * then it is assumed to be a VCD file.
254 status = parse_section(tmpbuf, &name, &contents);
255 g_string_free(tmpbuf, TRUE);
259 return status ? SR_OK : SR_ERR;
262 /* Send N samples of the given value. */
263 static void send_samples(const struct sr_dev_inst *sdi, uint64_t sample, uint64_t count)
265 struct sr_datafeed_packet packet;
266 struct sr_datafeed_logic logic;
267 uint64_t buffer[CHUNKSIZE];
269 unsigned chunksize = CHUNKSIZE;
271 if (count < chunksize)
274 for (i = 0; i < chunksize; i++)
277 packet.type = SR_DF_LOGIC;
278 packet.payload = &logic;
279 logic.unitsize = sizeof(uint64_t);
283 if (count < chunksize)
286 logic.length = sizeof(uint64_t) * chunksize;
288 sr_session_send(sdi, &packet);
293 /* Parse a set of lines from the data section. */
294 static void parse_contents(const struct sr_input *in, char *data)
297 struct vcd_channel *vcd_ch;
299 uint64_t timestamp, prev_timestamp, prev_values;
300 unsigned int bit, i, j;
304 prev_timestamp = prev_values = 0;
306 /* Read one space-delimited token at a time. */
307 tokens = g_strsplit_set(data, " \t\r\n", 0);
308 remove_empty_parts(tokens);
309 for (i = 0; tokens[i]; i++) {
310 if (inc->skip_until_end) {
311 if (!strcmp(tokens[i], "$end")) {
312 /* Done with unhandled/unknown section. */
313 inc->skip_until_end = FALSE;
317 if (tokens[i][0] == '#' && g_ascii_isdigit(tokens[i][1])) {
318 /* Numeric value beginning with # is a new timestamp value */
319 timestamp = strtoull(tokens[i] + 1, NULL, 10);
321 if (inc->downsample > 1)
322 timestamp /= inc->downsample;
325 * Skip < 0 => skip until first timestamp.
326 * Skip = 0 => don't skip
327 * Skip > 0 => skip until timestamp >= skip.
330 inc->skip = timestamp;
331 prev_timestamp = timestamp;
332 } else if (inc->skip > 0 && timestamp < (uint64_t)inc->skip) {
333 prev_timestamp = inc->skip;
334 } else if (timestamp == prev_timestamp) {
335 /* Ignore repeated timestamps (e.g. sigrok outputs these) */
337 if (inc->compress != 0 && timestamp - prev_timestamp > inc->compress) {
338 /* Compress long idle periods */
339 prev_timestamp = timestamp - inc->compress;
342 sr_dbg("New timestamp: %" PRIu64, timestamp);
344 /* Generate samples from prev_timestamp up to timestamp - 1. */
345 send_samples(in->sdi, prev_values, timestamp - prev_timestamp);
346 prev_timestamp = timestamp;
348 } else if (tokens[i][0] == '$' && tokens[i][1] != '\0') {
350 * This is probably a $dumpvars, $comment or similar.
351 * $dump* contain useful data.
353 if (g_strcmp0(tokens[i], "$dumpvars") == 0
354 || g_strcmp0(tokens[i], "$dumpon") == 0
355 || g_strcmp0(tokens[i], "$dumpoff") == 0
356 || g_strcmp0(tokens[i], "$end") == 0) {
357 /* Ignore, parse contents as normally. */
359 /* Ignore this and future lines until $end. */
360 inc->skip_until_end = TRUE;
363 } else if (strchr("bBrR", tokens[i][0]) != NULL) {
364 /* A vector value, not supported yet. */
366 } else if (strchr("01xXzZ", tokens[i][0]) != NULL) {
367 /* A new 1-bit sample value */
368 bit = (tokens[i][0] == '1');
371 * The identifier is either the next character, or, if
372 * there was whitespace after the bit, the next token.
374 if (tokens[i][1] == '\0') {
376 /* Missing identifier */
379 for (j = 1; tokens[i][j]; j++)
380 tokens[i][j - 1] = tokens[i][j];
381 tokens[i][j - 1] = '\0';
384 for (j = 0, l = inc->channels; j < inc->channelcount && l; j++, l = l->next) {
386 if (g_strcmp0(tokens[i], vcd_ch->identifier) == 0) {
387 /* Found our channel */
389 prev_values |= (uint64_t)1 << j;
391 prev_values &= ~((uint64_t)1 << j);
395 if (j == inc->channelcount)
396 sr_dbg("Did not find channel for identifier '%s'.", tokens[i]);
398 sr_warn("Skipping unknown token '%s'.", tokens[i]);
404 static int init(struct sr_input *in, GHashTable *options)
410 num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
411 if (num_channels < 1) {
412 sr_err("Invalid value for numchannels: must be at least 1.");
415 if (num_channels > 64) {
416 sr_err("No more than 64 channels supported.");
419 inc = in->priv = g_malloc0(sizeof(struct context));
420 inc->maxchannels = num_channels;
422 inc->downsample = g_variant_get_int32(g_hash_table_lookup(options, "downsample"));
423 if (inc->downsample < 1)
426 inc->compress = g_variant_get_int32(g_hash_table_lookup(options, "compress"));
427 inc->skip = g_variant_get_int32(g_hash_table_lookup(options, "skip"));
428 inc->skip /= inc->downsample;
430 in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
433 for (i = 0; i < num_channels; i++) {
434 snprintf(name, 16, "%d", i);
435 sr_channel_new(in->sdi, i, SR_CHANNEL_LOGIC, TRUE, name);
441 static gboolean have_header(GString *buf)
446 if (!(p = g_strstr_len(buf->str, buf->len, "$enddefinitions")))
448 pos = p - buf->str + 15;
449 while (pos < buf->len - 4 && g_ascii_isspace(buf->str[pos]))
451 if (!strncmp(buf->str + pos, "$end", 4))
457 static int process_buffer(struct sr_input *in)
459 struct sr_datafeed_packet packet;
460 struct sr_datafeed_meta meta;
461 struct sr_config *src;
468 std_session_send_df_header(in->sdi, LOG_PREFIX);
470 packet.type = SR_DF_META;
471 packet.payload = &meta;
472 samplerate = inc->samplerate / inc->downsample;
473 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
474 meta.config = g_slist_append(NULL, src);
475 sr_session_send(in->sdi, &packet);
481 while ((p = g_strrstr_len(in->buf->str, in->buf->len, "\n"))) {
483 g_strstrip(in->buf->str);
484 if (in->buf->str[0] != '\0')
485 parse_contents(in, in->buf->str);
486 g_string_erase(in->buf, 0, p - in->buf->str + 1);
492 static int receive(struct sr_input *in, GString *buf)
497 g_string_append_len(in->buf, buf->str, buf->len);
500 if (!inc->got_header) {
501 if (!have_header(in->buf))
503 if (!parse_header(in, in->buf))
504 /* There was a header in there, but it was malformed. */
507 in->sdi_ready = TRUE;
508 /* sdi is ready, notify frontend. */
512 ret = process_buffer(in);
517 static int end(struct sr_input *in)
519 struct sr_datafeed_packet packet;
524 ret = process_buffer(in);
530 packet.type = SR_DF_END;
531 sr_session_send(in->sdi, &packet);
537 static void cleanup(struct sr_input *in)
542 g_slist_free_full(inc->channels, free_channel);
545 static struct sr_option options[] = {
546 { "numchannels", "Number of channels", "Number of channels", NULL, NULL },
547 { "skip", "Skip", "Skip until timestamp", NULL, NULL },
548 { "downsample", "Downsample", "Divide samplerate by factor", NULL, NULL },
549 { "compress", "Compress", "Compress idle periods longer than this value", NULL, NULL },
553 static struct sr_option *get_options(void)
555 if (!options[0].def) {
556 options[0].def = g_variant_ref_sink(g_variant_new_int32(DEFAULT_NUM_CHANNELS));
557 options[1].def = g_variant_ref_sink(g_variant_new_int32(-1));
558 options[2].def = g_variant_ref_sink(g_variant_new_int32(1));
559 options[3].def = g_variant_ref_sink(g_variant_new_int32(0));
565 SR_PRIV struct sr_input_module input_vcd = {
568 .desc = "Value Change Dump",
569 .exts = (const char*[]){"vcd", NULL},
570 .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
571 .options = get_options,
572 .format_match = format_match,