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