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