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