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