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