]> sigrok.org Git - libsigrok.git/blame - input/vcd.c
Add downsample and skip parameters to input/vcd.
[libsigrok.git] / input / vcd.c
CommitLineData
99eaa206
PA
1/*
2 * This file is part of the sigrok project.
3 *
0157808d 4 * Copyright (C) 2012 Petteri Aimonen <jpa@sr.mail.kapsi.fi>
99eaa206
PA
5 *
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.
10 *
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.
15 *
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/>.
18 */
19
0157808d
PA
20/* The VCD input module has the following options:
21 *
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.
25 *
26 * skip: Allows skipping until given timestamp in the file.
27 * This can speed up analyzing of long captures.
28 *
29 * Value < 0: Skip until first timestamp listed in
30 * the file. (default)
31 *
32 * Value = 0: Do not skip, instead generate samples
33 * beginning from timestamp 0.
34 *
35 * Value > 0: Start at the given timestamp.
36 *
37 * downsample: Divide the samplerate by the given factor.
38 * This can speed up analyzing of long captures.
39 *
40 * Based on Verilog standard IEEE Std 1364-2001 Version C
41 *
42 * Supported features:
43 * - $var with 'wire' and 'reg' types of scalar variables
44 * - $timescale definition for samplerate
45 * - multiple character variable identifiers
46 *
47 * Most important unsupported features:
48 * - vector variables (bit vectors etc.)
49 * - analog, integer and real number variables
50 * - $dumpvars initial value declaration
51 */
52
53/* */
99eaa206
PA
54
55#include <stdlib.h>
56#include <glib.h>
57#include <stdio.h>
61a429c9 58#include <string.h>
99eaa206
PA
59#include "libsigrok.h"
60#include "libsigrok-internal.h"
61
62/* Message logging helpers with driver-specific prefix string. */
63#define DRIVER_LOG_DOMAIN "input/vcd: "
64#define sr_log(l, s, args...) sr_log(l, DRIVER_LOG_DOMAIN s, ## args)
65#define sr_spew(s, args...) sr_spew(DRIVER_LOG_DOMAIN s, ## args)
66#define sr_dbg(s, args...) sr_dbg(DRIVER_LOG_DOMAIN s, ## args)
67#define sr_info(s, args...) sr_info(DRIVER_LOG_DOMAIN s, ## args)
68#define sr_warn(s, args...) sr_warn(DRIVER_LOG_DOMAIN s, ## args)
69#define sr_err(s, args...) sr_err(DRIVER_LOG_DOMAIN s, ## args)
70
71#define DEFAULT_NUM_PROBES 8
72
73/* Read until specific type of character occurs in file.
74 * Skip input if dest is NULL.
75 * Modes:
76 * 'W' read until whitespace
77 * 'N' read until non-whitespace, and ungetc() the character
78 * '$' read until $end
79 */
80static gboolean read_until(FILE *file, GString *dest, char mode)
81{
82 char prev[4] = "";
83 for(;;)
84 {
85 int c = fgetc(file);
86
87 if (c == EOF)
88 {
61a429c9
PA
89 if (mode != 'N')
90 sr_err("Unexpected EOF.");
99eaa206
PA
91 return FALSE;
92 }
93
94 if (mode == 'W' && g_ascii_isspace(c))
95 return TRUE;
96
97 if (mode == 'N' && !g_ascii_isspace(c))
98 {
99 ungetc(c, file);
100 return TRUE;
101 }
102
103 if (mode == '$')
104 {
105 prev[0] = prev[1]; prev[1] = prev[2]; prev[2] = prev[3]; prev[3] = c;
106 if (prev[0] == '$' && prev[1] == 'e' && prev[2] == 'n' && prev[3] == 'd')
107 {
108 if (dest != NULL)
109 g_string_truncate(dest, dest->len - 3);
110
111 return TRUE;
112 }
113 }
114
115 if (dest != NULL)
116 g_string_append_c(dest, c);
117 }
118}
119
120/* Reads a single VCD section from input file and parses it to structure.
121 * e.g. $timescale 1ps $end => "timescale" "1ps"
122 */
123static gboolean parse_section(FILE *file, gchar **name, gchar **contents)
124{
125 gboolean status;
126 GString *sname, *scontents;
127
128 /* Skip any initial white-space */
129 if (!read_until(file, NULL, 'N')) return FALSE;
130
131 /* Section tag should start with $. */
132 if (fgetc(file) != '$')
133 {
134 sr_err("Expected $ at beginning of section.");
135 return FALSE;
136 }
137
138 /* Read the section tag */
139 sname = g_string_sized_new(32);
140 status = read_until(file, sname, 'W');
141
142 /* Skip whitespace before content */
143 status = status && read_until(file, NULL, 'N');
144
145 /* Read the content */
146 scontents = g_string_sized_new(128);
147 status = status && read_until(file, scontents, '$');
148 g_strchomp(scontents->str);
149
150 /* Release strings if status is FALSE, return them if status is TRUE */
151 *name = g_string_free(sname, !status);
152 *contents = g_string_free(scontents, !status);
153 return status;
154}
155
156struct probe
157{
158 gchar *name;
159 gchar *identifier;
160};
161
162struct context
163{
164 uint64_t samplerate;
165 int maxprobes;
166 int probecount;
0157808d
PA
167 int downsample;
168 int64_t skip;
99eaa206
PA
169 struct probe probes[SR_MAX_NUM_PROBES];
170};
171
61a429c9
PA
172static void release_context(struct context *ctx)
173{
174 int i;
175 for (i = 0; i < ctx->probecount; i++)
176 {
177 g_free(ctx->probes[i].name); ctx->probes[i].name = NULL;
178 g_free(ctx->probes[i].identifier); ctx->probes[i].identifier = NULL;
179 }
180
181 g_free(ctx);
182}
183
99eaa206
PA
184/* Remove empty parts from an array returned by g_strsplit. */
185static void remove_empty_parts(gchar **parts)
186{
187 gchar **src = parts;
188 gchar **dest = parts;
189 while (*src != NULL)
190 {
191 if (**src != '\0')
192 {
193 *dest++ = *src;
194 }
195
196 src++;
197 }
198
199 *dest = NULL;
200}
201
202/* Parse VCD header to get values for context structure.
203 * The context structure should be zeroed before calling this.
204 */
205static gboolean parse_header(FILE *file, struct context *ctx)
206{
207 gchar *name = NULL, *contents = NULL;
208 gboolean status = FALSE;
209
210 while (parse_section(file, &name, &contents))
211 {
212 sr_dbg("Section '%s', contents '%s'.", name, contents);
213
214 if (g_strcmp0(name, "enddefinitions") == 0)
215 {
216 status = TRUE;
217 break;
218 }
219 else if (g_strcmp0(name, "timescale") == 0)
220 {
221 /* The standard allows for values 1, 10 or 100
222 * and units s, ms, us, ns, ps and fs. */
223 struct sr_rational period;
224 if (sr_parse_period(contents, &period) == SR_OK)
225 {
226 ctx->samplerate = period.q / period.p;
227 if (period.q % period.p != 0)
228 {
229 /* Does not happen unless time value is non-standard */
0157808d 230 sr_warn("Inexact rounding of samplerate, %" PRIu64 " / %" PRIu64 " to %" PRIu64 " Hz.",
99eaa206
PA
231 period.q, period.p, ctx->samplerate);
232 }
233
234 sr_dbg("Samplerate: %" PRIu64, ctx->samplerate);
235 }
236 else
237 {
238 sr_err("Parsing timescale failed.");
239 }
240 }
241 else if (g_strcmp0(name, "var") == 0)
242 {
243 /* Format: $var type size identifier reference $end */
244 gchar **parts = g_strsplit_set(contents, " \r\n\t", 0);
245 remove_empty_parts(parts);
246
247 if (g_strv_length(parts) != 4)
248 {
249 sr_err("$var section should have 4 items");
250 }
251 else if (g_strcmp0(parts[0], "reg") != 0 && g_strcmp0(parts[0], "wire") != 0)
252 {
253 sr_warn("Unsupported signal type: '%s'", parts[0]);
254 }
255 else if (strtol(parts[1], NULL, 10) != 1)
256 {
257 sr_warn("Unsupported signal size: '%s'", parts[1]);
258 }
259 else if (ctx->probecount >= ctx->maxprobes)
260 {
261 sr_warn("Skipping '%s' because only %d probes requested.", parts[3], ctx->maxprobes);
262 }
263 else
264 {
265 sr_info("Probe %d is '%s' identified by '%s'.", ctx->probecount, parts[3], parts[2]);
266 ctx->probes[ctx->probecount].identifier = g_strdup(parts[2]);
267 ctx->probes[ctx->probecount].name = g_strdup(parts[3]);
268 ctx->probecount++;
269 }
270
271 g_strfreev(parts);
272 }
273
274 g_free(name); name = NULL;
275 g_free(contents); contents = NULL;
276 }
277
278 g_free(name);
279 g_free(contents);
280
281 return status;
282}
283
284static int format_match(const char *filename)
285{
286 FILE *file;
287 gchar *name = NULL, *contents = NULL;
288 gboolean status;
289
290 file = fopen(filename, "r");
291 if (file == NULL)
292 return FALSE;
293
294 /* If we can parse the first section correctly,
295 * then it is assumed to be a VCD file.
296 */
297 status = parse_section(file, &name, &contents);
298 status = status && (*name != '\0');
299
300 g_free(name);
301 g_free(contents);
302 fclose(file);
303
304 return status;
305}
306
307static int init(struct sr_input *in)
308{
309 struct sr_probe *probe;
310 int num_probes, i;
311 char name[SR_MAX_PROBENAME_LEN + 1];
312 char *param;
313 struct context *ctx;
314
315 if (!(ctx = g_try_malloc0(sizeof(*ctx)))) {
316 sr_err("Input format context malloc failed.");
317 return SR_ERR_MALLOC;
318 }
319
320 num_probes = DEFAULT_NUM_PROBES;
321 ctx->samplerate = 0;
0157808d
PA
322 ctx->downsample = 1;
323 ctx->skip = -1;
99eaa206
PA
324
325 if (in->param) {
326 param = g_hash_table_lookup(in->param, "numprobes");
327 if (param) {
328 num_probes = strtoul(param, NULL, 10);
329 if (num_probes < 1)
61a429c9
PA
330 {
331 release_context(ctx);
99eaa206 332 return SR_ERR;
61a429c9 333 }
99eaa206 334 }
0157808d
PA
335
336 param = g_hash_table_lookup(in->param, "downsample");
337 if (param) {
338 ctx->downsample = strtoul(param, NULL, 10);
339 if (ctx->downsample < 1)
340 {
341 ctx->downsample = 1;
342 }
343 }
344
345 param = g_hash_table_lookup(in->param, "skip");
346 if (param) {
347 ctx->skip = strtoul(param, NULL, 10) / ctx->downsample;
348 }
99eaa206
PA
349 }
350
351 /* Maximum number of probes to parse from the VCD */
352 ctx->maxprobes = num_probes;
353
354 /* Create a virtual device. */
355 in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
356 in->internal = ctx;
357
358 for (i = 0; i < num_probes; i++) {
359 snprintf(name, SR_MAX_PROBENAME_LEN, "%d", i);
360
361 if (!(probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, name)))
61a429c9
PA
362 {
363 release_context(ctx);
99eaa206 364 return SR_ERR;
61a429c9
PA
365 }
366
99eaa206
PA
367 in->sdi->probes = g_slist_append(in->sdi->probes, probe);
368 }
369
370 return SR_OK;
371}
372
61a429c9
PA
373#define CHUNKSIZE 1024
374
375/* Send N samples of the given value. */
376static void send_samples(const struct sr_dev_inst *sdi, uint64_t sample, uint64_t count)
377{
378 struct sr_datafeed_packet packet;
379 struct sr_datafeed_logic logic;
380 uint64_t buffer[CHUNKSIZE];
381 uint64_t i;
382 unsigned chunksize = CHUNKSIZE;
0157808d 383
61a429c9
PA
384 if (count < chunksize)
385 chunksize = count;
386
387 for (i = 0; i < chunksize; i++)
388 {
389 buffer[i] = sample;
390 }
391
392 packet.type = SR_DF_LOGIC;
393 packet.payload = &logic;
394 logic.unitsize = sizeof(uint64_t);
395 logic.data = buffer;
396
397 while (count)
398 {
399 if (count < chunksize)
400 chunksize = count;
401
402 logic.length = sizeof(uint64_t) * chunksize;
403
404 sr_session_send(sdi, &packet);
405 count -= chunksize;
406 }
407}
408
409/* Parse the data section of VCD */
410static void parse_contents(FILE *file, const struct sr_dev_inst *sdi, struct context *ctx)
411{
412 GString *token = g_string_sized_new(32);
413
61a429c9 414 uint64_t prev_timestamp = 0;
0157808d 415 uint64_t new_values = 0;
61a429c9
PA
416 uint64_t prev_values = 0;
417
418 /* Read one space-delimited token at a time. */
419 while (read_until(file, NULL, 'N') && read_until(file, token, 'W'))
420 {
421 if (token->str[0] == '#' && g_ascii_isdigit(token->str[1]))
422 {
423 /* Numeric value beginning with # is a new timestamp value */
424 uint64_t timestamp;
425 timestamp = strtoull(token->str + 1, NULL, 10);
426
0157808d
PA
427 if (ctx->downsample > 1)
428 timestamp /= ctx->downsample;
429
430 /* Skip < 0 => skip until first timestamp.
431 * Skip = 0 => don't skip
432 * Skip > 0 => skip until timestamp >= skip.
433 */
434 if (ctx->skip < 0)
435 {
436 ctx->skip = timestamp;
437 }
438 else if (ctx->skip > 0 && timestamp < (uint64_t)ctx->skip)
61a429c9 439 {
0157808d
PA
440 prev_timestamp = ctx->skip - 1;
441 }
442 else if (timestamp == prev_timestamp)
443 {
444 /* This only occurs when ctx->downsample > 1 */
445 if (prev_values != new_values)
446 {
447 sr_warn("VCD downsampling hides a glitch at %" PRIu64, timestamp);
448 prev_values = new_values;
449 }
61a429c9
PA
450 }
451 else
452 {
453 sr_dbg("New timestamp: %" PRIu64, timestamp);
454
455 /* Generate samples from prev_timestamp up to timestamp - 1. */
0157808d
PA
456 send_samples(sdi, new_values, timestamp - prev_timestamp);
457
458 prev_timestamp = timestamp;
459 prev_values = new_values;
61a429c9 460 }
61a429c9
PA
461 }
462 else if (token->str[0] == '$')
463 {
464 /* This is probably a $dumpvars, $comment or similar.
465 * For now, just skip it until $end. */
466 read_until(file, NULL, '$');
467 }
468 else if (strchr("01xXzZ", token->str[0]) != NULL)
469 {
470 /* A new 1-bit sample value */
471 int i, bit;
472 bit = (token->str[0] == '1');
473
474 g_string_erase(token, 0, 1);
475 if (token->len == 0)
476 {
477 /* There was a space between value and identifier.
478 * Read in the rest.
479 */
480 read_until(file, NULL, 'N');
481 read_until(file, token, 'W');
482 }
483
484 for (i = 0; i < ctx->probecount; i++)
485 {
486 if (g_strcmp0(token->str, ctx->probes[i].identifier) == 0)
487 {
488 sr_dbg("Probe %d new value %d.", i, bit);
489
490 /* Found our probe */
491 if (bit)
0157808d 492 new_values |= (1 << i);
61a429c9 493 else
0157808d 494 new_values &= ~(1 << i);
61a429c9
PA
495
496 break;
497 }
498 }
499
500 if (i == ctx->probecount)
501 {
502 sr_info("Did not find probe for identifier '%s'.", token->str);
503 }
504 }
505
506 g_string_truncate(token, 0);
507 }
508
509 g_string_free(token, TRUE);
510}
511
99eaa206
PA
512static int loadfile(struct sr_input *in, const char *filename)
513{
514 struct sr_datafeed_header header;
515 struct sr_datafeed_packet packet;
516 struct sr_datafeed_meta_logic meta;
99eaa206
PA
517 FILE *file;
518 struct context *ctx;
519
520 ctx = in->internal;
521
522 if ((file = fopen(filename, "r")) == NULL)
523 return SR_ERR;
524
525 if (!parse_header(file, ctx))
526 {
527 sr_err("VCD parsing failed");
528 fclose(file);
529 return SR_ERR;
530 }
531
532 /* Send header packet to the session bus. */
533 header.feed_version = 1;
534 gettimeofday(&header.starttime, NULL);
535 packet.type = SR_DF_HEADER;
536 packet.payload = &header;
537 sr_session_send(in->sdi, &packet);
538
539 /* Send metadata about the SR_DF_LOGIC packets to come. */
540 packet.type = SR_DF_META_LOGIC;
541 packet.payload = &meta;
0157808d 542 meta.samplerate = ctx->samplerate / ctx->downsample;
99eaa206
PA
543 meta.num_probes = ctx->probecount;
544 sr_session_send(in->sdi, &packet);
545
61a429c9
PA
546 /* Parse the contents of the VCD file */
547 parse_contents(file, in->sdi, ctx);
548
99eaa206
PA
549 /* Send end packet to the session bus. */
550 packet.type = SR_DF_END;
551 sr_session_send(in->sdi, &packet);
552
61a429c9
PA
553 fclose(file);
554 release_context(ctx);
99eaa206
PA
555 in->internal = NULL;
556
557 return SR_OK;
558}
559
560SR_PRIV struct sr_input_format input_vcd = {
561 .id = "vcd",
562 .description = "Value Change Dump",
563 .format_match = format_match,
564 .init = init,
565 .loadfile = loadfile,
566};