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