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