]> sigrok.org Git - libsigrok.git/blame - src/input/vcd.c
Change sr_dev_inst_new() to take no parameters.
[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>
7db06394 5 * Copyright (C) 2014 Bert Vermeulen <bert@biot.com>
99eaa206
PA
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
0157808d
PA
21/* The VCD input module has the following options:
22 *
ba7dd8bb 23 * numchannels: Maximum number of channels to use. The channels are
0157808d
PA
24 * detected in the same order as they are listed
25 * in the $var sections of the VCD file.
26 *
27 * skip: Allows skipping until given timestamp in the file.
28 * This can speed up analyzing of long captures.
29 *
30 * Value < 0: Skip until first timestamp listed in
31 * the file. (default)
32 *
33 * Value = 0: Do not skip, instead generate samples
34 * beginning from timestamp 0.
35 *
36 * Value > 0: Start at the given timestamp.
37 *
38 * downsample: Divide the samplerate by the given factor.
39 * This can speed up analyzing of long captures.
40 *
6b7ace48
PA
41 * compress: Compress idle periods longer than this value.
42 * This can speed up analyzing of long captures.
43 * Default 0 = don't compress.
44 *
0157808d
PA
45 * Based on Verilog standard IEEE Std 1364-2001 Version C
46 *
47 * Supported features:
48 * - $var with 'wire' and 'reg' types of scalar variables
49 * - $timescale definition for samplerate
50 * - multiple character variable identifiers
51 *
52 * Most important unsupported features:
53 * - vector variables (bit vectors etc.)
54 * - analog, integer and real number variables
55 * - $dumpvars initial value declaration
8be87469 56 * - $scope namespaces
ba7dd8bb 57 * - more than 64 channels
0157808d
PA
58 */
59
99eaa206
PA
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
3544f848 67#define LOG_PREFIX "input/vcd"
99eaa206 68
3f239f08 69#define DEFAULT_NUM_CHANNELS 8
e4c8a4d7
BV
70#define CHUNKSIZE 1024
71
72struct context {
c10ef17c 73 gboolean started;
7db06394 74 gboolean got_header;
e4c8a4d7 75 uint64_t samplerate;
7db06394
BV
76 unsigned int maxchannels;
77 unsigned int channelcount;
e4c8a4d7
BV
78 int downsample;
79 unsigned compress;
80 int64_t skip;
7db06394 81 gboolean skip_until_end;
ba7dd8bb 82 GSList *channels;
e4c8a4d7
BV
83};
84
ba7dd8bb 85struct vcd_channel {
e4c8a4d7
BV
86 gchar *name;
87 gchar *identifier;
88};
89
99eaa206 90
e4c8a4d7 91/*
7db06394 92 * Reads a single VCD section from input file and parses it to name/contents.
99eaa206
PA
93 * e.g. $timescale 1ps $end => "timescale" "1ps"
94 */
7db06394 95static gboolean parse_section(GString *buf, gchar **name, gchar **contents)
99eaa206 96{
7db06394 97 GString *sname, *scontent;
99eaa206 98 gboolean status;
7db06394
BV
99 unsigned int pos;
100
101 *name = *contents = NULL;
102 status = FALSE;
103 pos = 0;
cd1b0e8f 104
7db06394
BV
105 /* Skip any initial white-space. */
106 while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
107 pos++;
cd1b0e8f 108
99eaa206 109 /* Section tag should start with $. */
7db06394 110 if (buf->str[pos++] != '$')
99eaa206 111 return FALSE;
cd1b0e8f 112
99eaa206 113 sname = g_string_sized_new(32);
7db06394
BV
114 scontent = g_string_sized_new(128);
115
116 /* Read the section tag. */
117 while (pos < buf->len && !g_ascii_isspace(buf->str[pos]))
118 g_string_append_c(sname, buf->str[pos++]);
119
120 /* Skip whitespace before content. */
121 while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
122 pos++;
123
124 /* Read the content. */
125 while (pos < buf->len - 4 && strncmp(buf->str + pos, "$end", 4))
126 g_string_append_c(scontent, buf->str[pos++]);
127
128 if (sname->len && pos < buf->len - 4 && !strncmp(buf->str + pos, "$end", 4)) {
129 status = TRUE;
130 pos += 4;
131 while (pos < buf->len && g_ascii_isspace(buf->str[pos]))
132 pos++;
133 g_string_erase(buf, 0, pos);
134 }
99eaa206 135
99eaa206 136 *name = g_string_free(sname, !status);
7db06394
BV
137 *contents = g_string_free(scontent, !status);
138 if (*contents)
139 g_strchomp(*contents);
140
99eaa206
PA
141 return status;
142}
143
ba7dd8bb 144static void free_channel(void *data)
db9679af 145{
ba7dd8bb
UH
146 struct vcd_channel *vcd_ch = data;
147 g_free(vcd_ch->name);
148 g_free(vcd_ch->identifier);
149 g_free(vcd_ch);
db9679af
ML
150}
151
99eaa206
PA
152/* Remove empty parts from an array returned by g_strsplit. */
153static void remove_empty_parts(gchar **parts)
154{
155 gchar **src = parts;
156 gchar **dest = parts;
e4c8a4d7 157 while (*src != NULL) {
99eaa206 158 if (**src != '\0')
99eaa206 159 *dest++ = *src;
99eaa206
PA
160 src++;
161 }
cd1b0e8f 162
99eaa206
PA
163 *dest = NULL;
164}
165
e4c8a4d7
BV
166/*
167 * Parse VCD header to get values for context structure.
99eaa206
PA
168 * The context structure should be zeroed before calling this.
169 */
7db06394 170static gboolean parse_header(const struct sr_input *in, GString *buf)
99eaa206 171{
ba7dd8bb 172 struct vcd_channel *vcd_ch;
7db06394
BV
173 uint64_t p, q;
174 struct context *inc;
175 gboolean status;
176 gchar *name, *contents, **parts;
99eaa206 177
7db06394
BV
178 inc = in->priv;
179 name = contents = NULL;
180 status = FALSE;
181 while (parse_section(buf, &name, &contents)) {
99eaa206 182 sr_dbg("Section '%s', contents '%s'.", name, contents);
cd1b0e8f 183
e4c8a4d7 184 if (g_strcmp0(name, "enddefinitions") == 0) {
99eaa206
PA
185 status = TRUE;
186 break;
e4c8a4d7
BV
187 } else if (g_strcmp0(name, "timescale") == 0) {
188 /*
189 * The standard allows for values 1, 10 or 100
190 * and units s, ms, us, ns, ps and fs.
7db06394 191 */
e4c8a4d7 192 if (sr_parse_period(contents, &p, &q) == SR_OK) {
7db06394 193 inc->samplerate = q / p;
e4c8a4d7 194 if (q % p != 0) {
99eaa206 195 /* Does not happen unless time value is non-standard */
0157808d 196 sr_warn("Inexact rounding of samplerate, %" PRIu64 " / %" PRIu64 " to %" PRIu64 " Hz.",
7db06394 197 q, p, inc->samplerate);
99eaa206 198 }
cd1b0e8f 199
7db06394 200 sr_dbg("Samplerate: %" PRIu64, inc->samplerate);
e4c8a4d7 201 } else {
99eaa206
PA
202 sr_err("Parsing timescale failed.");
203 }
e4c8a4d7 204 } else if (g_strcmp0(name, "var") == 0) {
99eaa206 205 /* Format: $var type size identifier reference $end */
7db06394 206 parts = g_strsplit_set(contents, " \r\n\t", 0);
99eaa206 207 remove_empty_parts(parts);
cd1b0e8f 208
99eaa206 209 if (g_strv_length(parts) != 4)
8be87469 210 sr_warn("$var section should have 4 items");
99eaa206 211 else if (g_strcmp0(parts[0], "reg") != 0 && g_strcmp0(parts[0], "wire") != 0)
8be87469 212 sr_info("Unsupported signal type: '%s'", parts[0]);
99eaa206 213 else if (strtol(parts[1], NULL, 10) != 1)
8be87469 214 sr_info("Unsupported signal size: '%s'", parts[1]);
7db06394
BV
215 else if (inc->channelcount >= inc->maxchannels)
216 sr_warn("Skipping '%s' because only %d channels requested.",
217 parts[3], inc->maxchannels);
e4c8a4d7 218 else {
7db06394
BV
219 sr_info("Channel %d is '%s' identified by '%s'.",
220 inc->channelcount, parts[3], parts[2]);
ba7dd8bb
UH
221 vcd_ch = g_malloc(sizeof(struct vcd_channel));
222 vcd_ch->identifier = g_strdup(parts[2]);
223 vcd_ch->name = g_strdup(parts[3]);
7db06394
BV
224 inc->channels = g_slist_append(inc->channels, vcd_ch);
225 inc->channelcount++;
99eaa206 226 }
cd1b0e8f 227
99eaa206
PA
228 g_strfreev(parts);
229 }
cd1b0e8f 230
99eaa206
PA
231 g_free(name); name = NULL;
232 g_free(contents); contents = NULL;
233 }
99eaa206
PA
234 g_free(name);
235 g_free(contents);
cd1b0e8f 236
7db06394
BV
237 inc->got_header = status;
238
99eaa206
PA
239 return status;
240}
241
7db06394 242static int format_match(GHashTable *metadata)
99eaa206 243{
7db06394 244 GString *buf, *tmpbuf;
99eaa206 245 gboolean status;
7db06394 246 gchar *name, *contents;
cd1b0e8f 247
7db06394
BV
248 buf = g_hash_table_lookup(metadata, GINT_TO_POINTER(SR_INPUT_META_HEADER));
249 tmpbuf = g_string_new_len(buf->str, buf->len);
99eaa206 250
e4c8a4d7
BV
251 /*
252 * If we can parse the first section correctly,
99eaa206
PA
253 * then it is assumed to be a VCD file.
254 */
7db06394
BV
255 status = parse_section(tmpbuf, &name, &contents);
256 g_string_free(tmpbuf, TRUE);
99eaa206
PA
257 g_free(name);
258 g_free(contents);
cd1b0e8f 259
4f979115 260 return status ? SR_OK : SR_ERR;
99eaa206
PA
261}
262
61a429c9
PA
263/* Send N samples of the given value. */
264static void send_samples(const struct sr_dev_inst *sdi, uint64_t sample, uint64_t count)
265{
266 struct sr_datafeed_packet packet;
267 struct sr_datafeed_logic logic;
268 uint64_t buffer[CHUNKSIZE];
269 uint64_t i;
270 unsigned chunksize = CHUNKSIZE;
cd1b0e8f 271
61a429c9
PA
272 if (count < chunksize)
273 chunksize = count;
274
275 for (i = 0; i < chunksize; i++)
61a429c9 276 buffer[i] = sample;
cd1b0e8f 277
61a429c9 278 packet.type = SR_DF_LOGIC;
cd1b0e8f 279 packet.payload = &logic;
61a429c9
PA
280 logic.unitsize = sizeof(uint64_t);
281 logic.data = buffer;
cd1b0e8f 282
e4c8a4d7 283 while (count) {
61a429c9
PA
284 if (count < chunksize)
285 chunksize = count;
cd1b0e8f 286
61a429c9 287 logic.length = sizeof(uint64_t) * chunksize;
cd1b0e8f 288
61a429c9
PA
289 sr_session_send(sdi, &packet);
290 count -= chunksize;
291 }
292}
293
7db06394
BV
294/* Parse a set of lines from the data section. */
295static void parse_contents(const struct sr_input *in, char *data)
61a429c9 296{
7db06394
BV
297 struct context *inc;
298 struct vcd_channel *vcd_ch;
299 GSList *l;
300 uint64_t timestamp, prev_timestamp, prev_values;
301 unsigned int bit, i, j;
302 char **tokens;
cd1b0e8f 303
7db06394
BV
304 inc = in->priv;
305 prev_timestamp = prev_values = 0;
cd1b0e8f 306
61a429c9 307 /* Read one space-delimited token at a time. */
7db06394
BV
308 tokens = g_strsplit_set(data, " \t\r\n", 0);
309 remove_empty_parts(tokens);
310 for (i = 0; tokens[i]; i++) {
311 if (inc->skip_until_end) {
312 if (!strcmp(tokens[i], "$end")) {
313 /* Done with unhandled/unknown section. */
314 inc->skip_until_end = FALSE;
315 break;
316 }
317 }
318 if (tokens[i][0] == '#' && g_ascii_isdigit(tokens[i][1])) {
61a429c9 319 /* Numeric value beginning with # is a new timestamp value */
7db06394 320 timestamp = strtoull(tokens[i] + 1, NULL, 10);
cd1b0e8f 321
7db06394
BV
322 if (inc->downsample > 1)
323 timestamp /= inc->downsample;
cd1b0e8f 324
e4c8a4d7
BV
325 /*
326 * Skip < 0 => skip until first timestamp.
0157808d
PA
327 * Skip = 0 => don't skip
328 * Skip > 0 => skip until timestamp >= skip.
329 */
7db06394
BV
330 if (inc->skip < 0) {
331 inc->skip = timestamp;
8be87469 332 prev_timestamp = timestamp;
7db06394
BV
333 } else if (inc->skip > 0 && timestamp < (uint64_t)inc->skip) {
334 prev_timestamp = inc->skip;
335 } else if (timestamp == prev_timestamp) {
8be87469 336 /* Ignore repeated timestamps (e.g. sigrok outputs these) */
7db06394
BV
337 } else {
338 if (inc->compress != 0 && timestamp - prev_timestamp > inc->compress) {
6b7ace48 339 /* Compress long idle periods */
7db06394 340 prev_timestamp = timestamp - inc->compress;
6b7ace48 341 }
cd1b0e8f 342
61a429c9 343 sr_dbg("New timestamp: %" PRIu64, timestamp);
cd1b0e8f 344
61a429c9 345 /* Generate samples from prev_timestamp up to timestamp - 1. */
7db06394 346 send_samples(in->sdi, prev_values, timestamp - prev_timestamp);
0157808d 347 prev_timestamp = timestamp;
61a429c9 348 }
7db06394
BV
349 } else if (tokens[i][0] == '$' && tokens[i][1] != '\0') {
350 /*
351 * This is probably a $dumpvars, $comment or similar.
352 * $dump* contain useful data.
353 */
354 if (g_strcmp0(tokens[i], "$dumpvars") == 0
355 || g_strcmp0(tokens[i], "$dumpon") == 0
356 || g_strcmp0(tokens[i], "$dumpoff") == 0
357 || g_strcmp0(tokens[i], "$end") == 0) {
8be87469 358 /* Ignore, parse contents as normally. */
e4c8a4d7 359 } else {
7db06394
BV
360 /* Ignore this and future lines until $end. */
361 inc->skip_until_end = TRUE;
362 break;
8be87469 363 }
7db06394
BV
364 } else if (strchr("bBrR", tokens[i][0]) != NULL) {
365 /* A vector value, not supported yet. */
366 break;
367 } else if (strchr("01xXzZ", tokens[i][0]) != NULL) {
61a429c9 368 /* A new 1-bit sample value */
7db06394
BV
369 bit = (tokens[i][0] == '1');
370
371 /*
372 * The identifier is either the next character, or, if
373 * there was whitespace after the bit, the next token.
374 */
375 if (tokens[i][1] == '\0') {
376 if (!tokens[++i])
377 /* Missing identifier */
378 continue;
379 } else {
380 for (j = 1; tokens[i][j]; j++)
381 tokens[i][j - 1] = tokens[i][j];
382 tokens[i][j - 1] = '\0';
61a429c9 383 }
cd1b0e8f 384
7db06394 385 for (j = 0, l = inc->channels; j < inc->channelcount && l; j++, l = l->next) {
ba7dd8bb 386 vcd_ch = l->data;
7db06394 387 if (g_strcmp0(tokens[i], vcd_ch->identifier) == 0) {
ba7dd8bb 388 /* Found our channel */
61a429c9 389 if (bit)
7db06394 390 prev_values |= (uint64_t)1 << j;
61a429c9 391 else
7db06394 392 prev_values &= ~((uint64_t)1 << j);
61a429c9
PA
393 break;
394 }
395 }
7db06394
BV
396 if (j == inc->channelcount)
397 sr_dbg("Did not find channel for identifier '%s'.", tokens[i]);
e4c8a4d7 398 } else {
7db06394 399 sr_warn("Skipping unknown token '%s'.", tokens[i]);
8be87469 400 }
7db06394
BV
401 }
402 g_strfreev(tokens);
403}
404
405static int init(struct sr_input *in, GHashTable *options)
406{
407 struct sr_channel *ch;
408 int num_channels, i;
409 char name[16];
410 struct context *inc;
411
7db06394
BV
412 num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
413 if (num_channels < 1) {
414 sr_err("Invalid value for numchannels: must be at least 1.");
415 return SR_ERR_ARG;
416 }
417 if (num_channels > 64) {
418 sr_err("No more than 64 channels supported.");
419 return SR_ERR_ARG;
420 }
d0181813 421 inc = in->priv = g_malloc0(sizeof(struct context));
7db06394 422 inc->maxchannels = num_channels;
cd1b0e8f 423
7db06394
BV
424 inc->downsample = g_variant_get_int32(g_hash_table_lookup(options, "downsample"));
425 if (inc->downsample < 1)
426 inc->downsample = 1;
427
428 inc->compress = g_variant_get_int32(g_hash_table_lookup(options, "compress"));
429 inc->skip = g_variant_get_int32(g_hash_table_lookup(options, "skip"));
430 inc->skip /= inc->downsample;
431
0af636be 432 in->sdi = sr_dev_inst_new();
7db06394
BV
433 in->priv = inc;
434
435 for (i = 0; i < num_channels; i++) {
436 snprintf(name, 16, "%d", i);
437 ch = sr_channel_new(i, SR_CHANNEL_LOGIC, TRUE, name);
438 in->sdi->channels = g_slist_append(in->sdi->channels, ch);
61a429c9 439 }
cd1b0e8f 440
7db06394 441 return SR_OK;
61a429c9
PA
442}
443
7db06394
BV
444static gboolean have_header(GString *buf)
445{
446 unsigned int pos;
447 char *p;
448
449 if (!(p = g_strstr_len(buf->str, buf->len, "$enddefinitions")))
450 return FALSE;
451 pos = p - buf->str + 15;
452 while (pos < buf->len - 4 && g_ascii_isspace(buf->str[pos]))
453 pos++;
454 if (!strncmp(buf->str + pos, "$end", 4))
455 return TRUE;
456
457 return FALSE;
458}
459
7066fd46 460static int process_buffer(struct sr_input *in)
99eaa206 461{
99eaa206 462 struct sr_datafeed_packet packet;
2df1e819
BV
463 struct sr_datafeed_meta meta;
464 struct sr_config *src;
7db06394 465 struct context *inc;
2df1e819 466 uint64_t samplerate;
7db06394
BV
467 char *p;
468
7db06394 469 inc = in->priv;
d0181813 470 if (!inc->started) {
7db06394 471 std_session_send_df_header(in->sdi, LOG_PREFIX);
99eaa206 472
7db06394
BV
473 packet.type = SR_DF_META;
474 packet.payload = &meta;
475 samplerate = inc->samplerate / inc->downsample;
476 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
477 meta.config = g_slist_append(NULL, src);
478 sr_session_send(in->sdi, &packet);
479 sr_config_free(src);
d0181813
BV
480
481 inc->started = TRUE;
99eaa206
PA
482 }
483
7db06394
BV
484 while ((p = g_strrstr_len(in->buf->str, in->buf->len, "\n"))) {
485 *p = '\0';
486 g_strstrip(in->buf->str);
487 if (in->buf->str[0] != '\0')
488 parse_contents(in, in->buf->str);
489 g_string_erase(in->buf, 0, p - in->buf->str + 1);
490 }
99eaa206 491
7db06394
BV
492 return SR_OK;
493}
cd1b0e8f 494
7066fd46
BV
495static int receive(struct sr_input *in, GString *buf)
496{
497 struct context *inc;
498 int ret;
499
500 g_string_append_len(in->buf, buf->str, buf->len);
501
502 inc = in->priv;
503 if (!inc->got_header) {
504 if (!have_header(in->buf))
505 return SR_OK;
506 if (!parse_header(in, in->buf) != SR_OK)
507 /* There was a header in there, but it was malformed. */
508 return SR_ERR;
509
510 in->sdi_ready = TRUE;
511 /* sdi is ready, notify frontend. */
512 return SR_OK;
513 }
514
515 ret = process_buffer(in);
516
517 return ret;
518}
519
520static int end(struct sr_input *in)
7db06394 521{
c10ef17c 522 struct sr_datafeed_packet packet;
7db06394 523 struct context *inc;
7066fd46
BV
524 int ret;
525
526 if (in->sdi_ready)
527 ret = process_buffer(in);
528 else
529 ret = SR_OK;
99eaa206 530
7db06394 531 inc = in->priv;
c10ef17c 532 if (inc->started) {
c10ef17c
BV
533 packet.type = SR_DF_END;
534 sr_session_send(in->sdi, &packet);
535 }
536
7066fd46
BV
537 return ret;
538}
539
d5cc282f 540static void cleanup(struct sr_input *in)
7066fd46
BV
541{
542 struct context *inc;
543
544 inc = in->priv;
7db06394 545 g_slist_free_full(inc->channels, free_channel);
99eaa206
PA
546}
547
7db06394 548static struct sr_option options[] = {
5e83cd74 549 { "numchannels", "Number of channels", "Number of channels", NULL, NULL },
7db06394
BV
550 { "skip", "Skip", "Skip until timestamp", NULL, NULL },
551 { "downsample", "Downsample", "Divide samplerate by factor", NULL, NULL },
552 { "compress", "Compress", "Compress idle periods longer than this value", NULL, NULL },
06ad20be 553 ALL_ZERO
7db06394
BV
554};
555
556static struct sr_option *get_options(void)
557{
558 if (!options[0].def) {
559 options[0].def = g_variant_ref_sink(g_variant_new_int32(DEFAULT_NUM_CHANNELS));
560 options[1].def = g_variant_ref_sink(g_variant_new_int32(-1));
561 options[2].def = g_variant_ref_sink(g_variant_new_int32(1));
562 options[3].def = g_variant_ref_sink(g_variant_new_int32(0));
563 }
564
565 return options;
566}
567
d4c93774 568SR_PRIV struct sr_input_module input_vcd = {
99eaa206 569 .id = "vcd",
7db06394 570 .name = "VCD",
17bfaca6 571 .desc = "Value Change Dump",
7db06394
BV
572 .metadata = { SR_INPUT_META_HEADER | SR_INPUT_META_REQUIRED },
573 .options = get_options,
99eaa206
PA
574 .format_match = format_match,
575 .init = init,
7db06394 576 .receive = receive,
7066fd46 577 .end = end,
7db06394 578 .cleanup = cleanup,
99eaa206 579};