2 * This file is part of the sigrok project.
4 * Copyright (C) 2012 Petteri Aimonen <jpa@sr.mail.kapsi.fi>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 /* The VCD input module has the following options:
22 * numprobes: Maximum number of probes to use. The probes are
23 * detected in the same order as they are listed
24 * in the $var sections of the VCD file.
26 * skip: Allows skipping until given timestamp in the file.
27 * This can speed up analyzing of long captures.
29 * Value < 0: Skip until first timestamp listed in
32 * Value = 0: Do not skip, instead generate samples
33 * beginning from timestamp 0.
35 * Value > 0: Start at the given timestamp.
37 * downsample: Divide the samplerate by the given factor.
38 * This can speed up analyzing of long captures.
40 * Based on Verilog standard IEEE Std 1364-2001 Version C
43 * - $var with 'wire' and 'reg' types of scalar variables
44 * - $timescale definition for samplerate
45 * - multiple character variable identifiers
47 * Most important unsupported features:
48 * - vector variables (bit vectors etc.)
49 * - analog, integer and real number variables
50 * - $dumpvars initial value declaration
60 #include "libsigrok.h"
61 #include "libsigrok-internal.h"
63 /* Message logging helpers with driver-specific prefix string. */
64 #define DRIVER_LOG_DOMAIN "input/vcd: "
65 #define sr_log(l, s, args...) sr_log(l, DRIVER_LOG_DOMAIN s, ## args)
66 #define sr_spew(s, args...) sr_spew(DRIVER_LOG_DOMAIN s, ## args)
67 #define sr_dbg(s, args...) sr_dbg(DRIVER_LOG_DOMAIN s, ## args)
68 #define sr_info(s, args...) sr_info(DRIVER_LOG_DOMAIN s, ## args)
69 #define sr_warn(s, args...) sr_warn(DRIVER_LOG_DOMAIN s, ## args)
70 #define sr_err(s, args...) sr_err(DRIVER_LOG_DOMAIN s, ## args)
72 #define DEFAULT_NUM_PROBES 8
74 /* Read until specific type of character occurs in file.
75 * Skip input if dest is NULL.
77 * 'W' read until whitespace
78 * 'N' read until non-whitespace, and ungetc() the character
81 static gboolean read_until(FILE *file, GString *dest, char mode)
84 long startpos = ftell(file);
92 sr_err("Unexpected EOF, read started at %ld.", startpos);
96 if (mode == 'W' && g_ascii_isspace(c))
99 if (mode == 'N' && !g_ascii_isspace(c))
107 prev[0] = prev[1]; prev[1] = prev[2]; prev[2] = prev[3]; prev[3] = c;
108 if (prev[0] == '$' && prev[1] == 'e' && prev[2] == 'n' && prev[3] == 'd')
111 g_string_truncate(dest, dest->len - 3);
118 g_string_append_c(dest, c);
122 /* Reads a single VCD section from input file and parses it to structure.
123 * e.g. $timescale 1ps $end => "timescale" "1ps"
125 static gboolean parse_section(FILE *file, gchar **name, gchar **contents)
128 GString *sname, *scontents;
130 /* Skip any initial white-space */
131 if (!read_until(file, NULL, 'N')) return FALSE;
133 /* Section tag should start with $. */
134 if (fgetc(file) != '$')
136 sr_err("Expected $ at beginning of section.");
140 /* Read the section tag */
141 sname = g_string_sized_new(32);
142 status = read_until(file, sname, 'W');
144 /* Skip whitespace before content */
145 status = status && read_until(file, NULL, 'N');
147 /* Read the content */
148 scontents = g_string_sized_new(128);
149 status = status && read_until(file, scontents, '$');
150 g_strchomp(scontents->str);
152 /* Release strings if status is FALSE, return them if status is TRUE */
153 *name = g_string_free(sname, !status);
154 *contents = g_string_free(scontents, !status);
171 struct probe probes[SR_MAX_NUM_PROBES];
174 static void release_context(struct context *ctx)
177 for (i = 0; i < ctx->probecount; i++)
179 g_free(ctx->probes[i].name); ctx->probes[i].name = NULL;
180 g_free(ctx->probes[i].identifier); ctx->probes[i].identifier = NULL;
186 /* Remove empty parts from an array returned by g_strsplit. */
187 static void remove_empty_parts(gchar **parts)
190 gchar **dest = parts;
204 /* Parse VCD header to get values for context structure.
205 * The context structure should be zeroed before calling this.
207 static gboolean parse_header(FILE *file, struct context *ctx)
209 gchar *name = NULL, *contents = NULL;
210 gboolean status = FALSE;
212 while (parse_section(file, &name, &contents))
214 sr_dbg("Section '%s', contents '%s'.", name, contents);
216 if (g_strcmp0(name, "enddefinitions") == 0)
221 else if (g_strcmp0(name, "timescale") == 0)
223 /* The standard allows for values 1, 10 or 100
224 * and units s, ms, us, ns, ps and fs. */
225 struct sr_rational period;
226 if (sr_parse_period(contents, &period) == SR_OK)
228 ctx->samplerate = period.q / period.p;
229 if (period.q % period.p != 0)
231 /* Does not happen unless time value is non-standard */
232 sr_warn("Inexact rounding of samplerate, %" PRIu64 " / %" PRIu64 " to %" PRIu64 " Hz.",
233 period.q, period.p, ctx->samplerate);
236 sr_dbg("Samplerate: %" PRIu64, ctx->samplerate);
240 sr_err("Parsing timescale failed.");
243 else if (g_strcmp0(name, "var") == 0)
245 /* Format: $var type size identifier reference $end */
246 gchar **parts = g_strsplit_set(contents, " \r\n\t", 0);
247 remove_empty_parts(parts);
249 if (g_strv_length(parts) != 4)
251 sr_warn("$var section should have 4 items");
253 else if (g_strcmp0(parts[0], "reg") != 0 && g_strcmp0(parts[0], "wire") != 0)
255 sr_info("Unsupported signal type: '%s'", parts[0]);
257 else if (strtol(parts[1], NULL, 10) != 1)
259 sr_info("Unsupported signal size: '%s'", parts[1]);
261 else if (ctx->probecount >= ctx->maxprobes)
263 sr_warn("Skipping '%s' because only %d probes requested.", parts[3], ctx->maxprobes);
267 sr_info("Probe %d is '%s' identified by '%s'.", ctx->probecount, parts[3], parts[2]);
268 ctx->probes[ctx->probecount].identifier = g_strdup(parts[2]);
269 ctx->probes[ctx->probecount].name = g_strdup(parts[3]);
276 g_free(name); name = NULL;
277 g_free(contents); contents = NULL;
286 static int format_match(const char *filename)
289 gchar *name = NULL, *contents = NULL;
292 file = fopen(filename, "r");
296 /* If we can parse the first section correctly,
297 * then it is assumed to be a VCD file.
299 status = parse_section(file, &name, &contents);
300 status = status && (*name != '\0');
309 static int init(struct sr_input *in)
311 struct sr_probe *probe;
313 char name[SR_MAX_PROBENAME_LEN + 1];
317 if (!(ctx = g_try_malloc0(sizeof(*ctx)))) {
318 sr_err("Input format context malloc failed.");
319 return SR_ERR_MALLOC;
322 num_probes = DEFAULT_NUM_PROBES;
328 param = g_hash_table_lookup(in->param, "numprobes");
330 num_probes = strtoul(param, NULL, 10);
333 release_context(ctx);
338 param = g_hash_table_lookup(in->param, "downsample");
340 ctx->downsample = strtoul(param, NULL, 10);
341 if (ctx->downsample < 1)
347 param = g_hash_table_lookup(in->param, "skip");
349 ctx->skip = strtoul(param, NULL, 10) / ctx->downsample;
353 /* Maximum number of probes to parse from the VCD */
354 ctx->maxprobes = num_probes;
356 /* Create a virtual device. */
357 in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
360 for (i = 0; i < num_probes; i++) {
361 snprintf(name, SR_MAX_PROBENAME_LEN, "%d", i);
363 if (!(probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, name)))
365 release_context(ctx);
369 in->sdi->probes = g_slist_append(in->sdi->probes, probe);
375 #define CHUNKSIZE 1024
377 /* Send N samples of the given value. */
378 static void send_samples(const struct sr_dev_inst *sdi, uint64_t sample, uint64_t count)
380 struct sr_datafeed_packet packet;
381 struct sr_datafeed_logic logic;
382 uint64_t buffer[CHUNKSIZE];
384 unsigned chunksize = CHUNKSIZE;
386 if (count < chunksize)
389 for (i = 0; i < chunksize; i++)
394 packet.type = SR_DF_LOGIC;
395 packet.payload = &logic;
396 logic.unitsize = sizeof(uint64_t);
401 if (count < chunksize)
404 logic.length = sizeof(uint64_t) * chunksize;
406 sr_session_send(sdi, &packet);
411 /* Parse the data section of VCD */
412 static void parse_contents(FILE *file, const struct sr_dev_inst *sdi, struct context *ctx)
414 GString *token = g_string_sized_new(32);
416 uint64_t prev_timestamp = 0;
417 uint64_t prev_values = 0;
419 /* Read one space-delimited token at a time. */
420 while (read_until(file, NULL, 'N') && read_until(file, token, 'W'))
422 if (token->str[0] == '#' && g_ascii_isdigit(token->str[1]))
424 /* Numeric value beginning with # is a new timestamp value */
426 timestamp = strtoull(token->str + 1, NULL, 10);
428 if (ctx->downsample > 1)
429 timestamp /= ctx->downsample;
431 /* Skip < 0 => skip until first timestamp.
432 * Skip = 0 => don't skip
433 * Skip > 0 => skip until timestamp >= skip.
437 ctx->skip = timestamp;
438 prev_timestamp = timestamp;
440 else if (ctx->skip > 0 && timestamp < (uint64_t)ctx->skip)
442 prev_timestamp = ctx->skip;
444 else if (timestamp == prev_timestamp)
446 /* Ignore repeated timestamps (e.g. sigrok outputs these) */
450 sr_dbg("New timestamp: %" PRIu64, timestamp);
452 /* Generate samples from prev_timestamp up to timestamp - 1. */
453 send_samples(sdi, prev_values, timestamp - prev_timestamp);
454 prev_timestamp = timestamp;
457 else if (token->str[0] == '$' && token->len > 1)
459 /* This is probably a $dumpvars, $comment or similar.
460 * $dump* contain useful data, but other tags will be skipped until $end. */
461 if (g_strcmp0(token->str, "$dumpvars") == 0 ||
462 g_strcmp0(token->str, "$dumpon") == 0 ||
463 g_strcmp0(token->str, "$dumpoff") == 0 ||
464 g_strcmp0(token->str, "$end") == 0)
466 /* Ignore, parse contents as normally. */
470 /* Skip until $end */
471 read_until(file, NULL, '$');
474 else if (strchr("bBrR", token->str[0]) != NULL)
476 /* A vector value. Skip it and also the following identifier. */
477 read_until(file, NULL, 'N');
478 read_until(file, NULL, 'W');
480 else if (strchr("01xXzZ", token->str[0]) != NULL)
482 /* A new 1-bit sample value */
484 bit = (token->str[0] == '1');
486 g_string_erase(token, 0, 1);
489 /* There was a space between value and identifier.
492 read_until(file, NULL, 'N');
493 read_until(file, token, 'W');
496 for (i = 0; i < ctx->probecount; i++)
498 if (g_strcmp0(token->str, ctx->probes[i].identifier) == 0)
500 sr_dbg("Probe %d new value %d.", i, bit);
502 /* Found our probe */
504 prev_values |= (1 << i);
506 prev_values &= ~(1 << i);
512 if (i == ctx->probecount)
514 sr_dbg("Did not find probe for identifier '%s'.", token->str);
519 sr_warn("Skipping unknown token '%s'.", token->str);
522 g_string_truncate(token, 0);
525 g_string_free(token, TRUE);
528 static int loadfile(struct sr_input *in, const char *filename)
530 struct sr_datafeed_header header;
531 struct sr_datafeed_packet packet;
532 struct sr_datafeed_meta_logic meta;
538 if ((file = fopen(filename, "r")) == NULL)
541 if (!parse_header(file, ctx))
543 sr_err("VCD parsing failed");
548 /* Send header packet to the session bus. */
549 header.feed_version = 1;
550 gettimeofday(&header.starttime, NULL);
551 packet.type = SR_DF_HEADER;
552 packet.payload = &header;
553 sr_session_send(in->sdi, &packet);
555 /* Send metadata about the SR_DF_LOGIC packets to come. */
556 packet.type = SR_DF_META_LOGIC;
557 packet.payload = &meta;
558 meta.samplerate = ctx->samplerate / ctx->downsample;
559 meta.num_probes = ctx->probecount;
560 sr_session_send(in->sdi, &packet);
562 /* Parse the contents of the VCD file */
563 parse_contents(file, in->sdi, ctx);
565 /* Send end packet to the session bus. */
566 packet.type = SR_DF_END;
567 sr_session_send(in->sdi, &packet);
570 release_context(ctx);
576 SR_PRIV struct sr_input_format input_vcd = {
578 .description = "Value Change Dump",
579 .format_match = format_match,
581 .loadfile = loadfile,