cli: factor out output format setup
[sigrok-cli.git] / sigrok-cli.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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 #include <sigrokdecode.h> /* First, so we avoid a _POSIX_C_SOURCE warning. */
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <time.h>
26 #include <sys/time.h>
27 #include <inttypes.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <errno.h>
31 #include <glib.h>
32 #include <glib/gstdio.h>
33 #include <sigrok.h>
34 #include "sigrok-cli.h"
35 #include "config.h"
36
37 #define DEFAULT_OUTPUT_FORMAT "bits:width=64"
38
39 extern struct sr_hwcap_option sr_hwcap_options[];
40
41 static uint64_t limit_samples = 0;
42 static struct sr_output_format *output_format = NULL;
43 static int default_output_format = FALSE;
44 static char *output_format_param = NULL;
45 static char *input_format_param = NULL;
46 static GHashTable *pd_ann_visible = NULL;
47
48 static gboolean opt_version = FALSE;
49 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
50 static gboolean opt_list_devs = FALSE;
51 static gboolean opt_wait_trigger = FALSE;
52 static gchar *opt_input_file = NULL;
53 static gchar *opt_output_file = NULL;
54 static gchar *opt_dev = NULL;
55 static gchar *opt_probes = NULL;
56 static gchar *opt_triggers = NULL;
57 static gchar *opt_pds = NULL;
58 static gchar *opt_pd_stack = NULL;
59 static gchar *opt_pd_annotation = NULL;
60 static gchar *opt_input_format = NULL;
61 static gchar *opt_output_format = NULL;
62 static gchar *opt_time = NULL;
63 static gchar *opt_samples = NULL;
64 static gchar *opt_continuous = NULL;
65
66 static GOptionEntry optargs[] = {
67         {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
68                         "Show version and support list", NULL},
69         {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
70                         "Select libsigrok/libsigrokdecode loglevel", NULL},
71         {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs,
72                         "Scan for devices", NULL},
73         {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
74                         "Use specified device", NULL},
75         {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
76                         "Load input from file", NULL},
77         {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
78                         "Input format", NULL},
79         {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
80                         "Save output to file", NULL},
81         {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
82                         "Output format", NULL},
83         {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
84                         "Probes to use", NULL},
85         {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
86                         "Trigger configuration", NULL},
87         {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
88                         "Wait for trigger", NULL},
89         {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
90                         "Protocol decoders to run", NULL},
91         {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
92                         "Protocol decoder stack", NULL},
93         {"protocol-decoder-annotation", 0, 0, G_OPTION_ARG_STRING, &opt_pd_annotation,
94                         "Protocol decoder annotation to show", NULL},
95         {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
96                         "How long to sample (ms)", NULL},
97         {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
98                         "Number of samples to acquire", NULL},
99         {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
100                         "Sample continuously", NULL},
101         {NULL, 0, 0, 0, NULL, NULL, NULL}
102 };
103
104 static void show_version(void)
105 {
106         GSList *l;
107         struct sr_dev_driver **drivers;
108         struct sr_input_format **inputs;
109         struct sr_output_format **outputs;
110         struct srd_decoder *dec;
111         int i;
112
113         printf("sigrok-cli %s\n\n", VERSION);
114
115         printf("Using libsigrok %s (lib version %s).\n",
116                sr_package_version_string_get(), sr_lib_version_string_get());
117         printf("Using libsigrokdecode %s (lib version %s).\n\n",
118                srd_package_version_string_get(), srd_lib_version_string_get());
119
120         printf("Supported hardware drivers:\n");
121         drivers = sr_driver_list();
122         for (i = 0; drivers[i]; i++) {
123                 printf("  %-20s %s\n", drivers[i]->name, drivers[i]->longname);
124         }
125         printf("\n");
126
127         printf("Supported input formats:\n");
128         inputs = sr_input_list();
129         for (i = 0; inputs[i]; i++)
130                 printf("  %-20s %s\n", inputs[i]->id, inputs[i]->description);
131         printf("\n");
132
133         printf("Supported output formats:\n");
134         outputs = sr_output_list();
135         for (i = 0; outputs[i]; i++)
136                 printf("  %-20s %s\n", outputs[i]->id, outputs[i]->description);
137         printf("\n");
138
139         if (srd_init(NULL) == SRD_OK) {
140                 printf("Supported protocol decoders:\n");
141                 srd_decoder_load_all();
142                 for (l = srd_decoder_list(); l; l = l->next) {
143                         dec = l->data;
144                         printf("  %-20s %s\n", dec->id, dec->longname);
145                         /* Print protocol description upon "-l 3" or higher. */
146                         if (opt_loglevel >= SR_LOG_INFO)
147                                 printf("  %-20s %s\n", "", dec->desc);
148                 }
149                 srd_exit();
150         }
151         printf("\n");
152 }
153
154 static void print_dev_line(const struct sr_dev *dev)
155 {
156         const struct sr_dev_inst *sdi;
157
158         sr_dev_info_get(dev, SR_DI_INST, (const void **)&sdi);
159
160         if (sdi->vendor && sdi->vendor[0])
161                 printf("%s ", sdi->vendor);
162         if (sdi->model && sdi->model[0])
163                 printf("%s ", sdi->model);
164         if (sdi->version && sdi->version[0])
165                 printf("%s ", sdi->version);
166         if (dev->probes)
167                 printf("with %d probes", g_slist_length(dev->probes));
168         printf("\n");
169 }
170
171 static void show_dev_list(void)
172 {
173         struct sr_dev *dev, *demo_dev;
174         GSList *devs, *l;
175         int devcnt;
176
177         devcnt = 0;
178         devs = sr_dev_list();
179
180         if (g_slist_length(devs) == 0)
181                 return;
182
183         printf("The following devices were found:\nID    Device\n");
184         demo_dev = NULL;
185         for (l = devs; l; l = l->next) {
186                 dev = l->data;
187                 if (sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV)) {
188                         demo_dev = dev;
189                         continue;
190                 }
191                 printf("%-3d   ", devcnt++);
192                 print_dev_line(dev);
193         }
194         if (demo_dev) {
195                 printf("demo  ");
196                 print_dev_line(demo_dev);
197         }
198 }
199
200 static void show_dev_detail(void)
201 {
202         struct sr_dev *dev;
203         struct sr_hwcap_option *hwo;
204         const struct sr_samplerates *samplerates;
205         int cap, *hwcaps, i;
206         char *s, *title;
207         const char *charopts, **stropts;
208
209         dev = parse_devstring(opt_dev);
210         if (!dev) {
211                 printf("No such device. Use -D to list all devices.\n");
212                 return;
213         }
214
215         print_dev_line(dev);
216
217         if (sr_dev_info_get(dev, SR_DI_TRIGGER_TYPES,
218                                         (const void **)&charopts) == SR_OK) {
219                 printf("Supported triggers: ");
220                 while (*charopts) {
221                         printf("%c ", *charopts);
222                         charopts++;
223                 }
224                 printf("\n");
225         }
226
227         title = "Supported options:\n";
228         hwcaps = dev->driver->hwcap_get_all();
229         for (cap = 0; hwcaps[cap]; cap++) {
230                 if (!(hwo = sr_hw_hwcap_get(hwcaps[cap])))
231                         continue;
232
233                 if (title) {
234                         printf("%s", title);
235                         title = NULL;
236                 }
237
238                 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
239                         printf("    %s", hwo->shortname);
240                         if (sr_dev_info_get(dev, SR_DI_PATTERNS,
241                                         (const void **)&stropts) == SR_OK) {
242                                 printf(" - supported patterns:\n");
243                                 for (i = 0; stropts[i]; i++)
244                                         printf("      %s\n", stropts[i]);
245                         } else {
246                                 printf("\n");
247                         }
248                 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
249                         printf("    %s", hwo->shortname);
250                         /* Supported samplerates */
251                         if (sr_dev_info_get(dev, SR_DI_SAMPLERATES,
252                                         (const void **)&samplerates) != SR_OK) {
253                                 printf("\n");
254                                 continue;
255                         }
256
257                         if (samplerates->step) {
258                                 /* low */
259                                 if (!(s = sr_samplerate_string(samplerates->low)))
260                                         continue;
261                                 printf(" (%s", s);
262                                 g_free(s);
263                                 /* high */
264                                 if (!(s = sr_samplerate_string(samplerates->high)))
265                                         continue;
266                                 printf(" - %s", s);
267                                 g_free(s);
268                                 /* step */
269                                 if (!(s = sr_samplerate_string(samplerates->step)))
270                                         continue;
271                                 printf(" in steps of %s)\n", s);
272                                 g_free(s);
273                         } else {
274                                 printf(" - supported samplerates:\n");
275                                 for (i = 0; samplerates->list[i]; i++) {
276                                         printf("      %s\n", sr_samplerate_string(samplerates->list[i]));
277                                 }
278                         }
279                 } else {
280                         printf("    %s\n", hwo->shortname);
281                 }
282         }
283 }
284
285 static void show_pd_detail(void)
286 {
287         GSList *l;
288         struct srd_decoder *dec;
289         char **pdtokens, **pdtok, **ann, *doc;
290         struct srd_probe *p;
291
292         pdtokens = g_strsplit(opt_pds, ",", -1);
293         for (pdtok = pdtokens; *pdtok; pdtok++) {
294                 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
295                         printf("Protocol decoder %s not found.\n", *pdtok);
296                         return;
297                 }
298                 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
299                                 dec->id, dec->name, dec->longname, dec->desc);
300                 printf("License: %s\n", dec->license);
301                 printf("Annotations:\n");
302                 if (dec->annotations) {
303                         for (l = dec->annotations; l; l = l->next) {
304                                 ann = l->data;
305                                 printf("- %s\n  %s\n", ann[0], ann[1]);
306                         }
307                 } else {
308                         printf("None.\n");
309                 }
310                 /* TODO: Print supported decoder options. */
311                 printf("Required probes:\n");
312                 if (dec->probes) {
313                         for (l = dec->probes; l; l = l->next) {
314                                 p = l->data;
315                                 printf("- %s (%s): %s\n",
316                                        p->name, p->id, p->desc);
317                         }
318                 } else {
319                         printf("None.\n");
320                 }
321                 printf("Optional probes:\n");
322                 if (dec->opt_probes) {
323                         for (l = dec->opt_probes; l; l = l->next) {
324                                 p = l->data;
325                                 printf("- %s (%s): %s\n",
326                                        p->name, p->id, p->desc);
327                         }
328                 } else {
329                         printf("None.\n");
330                 }
331                 if ((doc = srd_decoder_doc_get(dec))) {
332                         printf("Documentation:\n%s\n",
333                                doc[0] == '\n' ? doc + 1 : doc);
334                         g_free(doc);
335                 }
336         }
337
338         g_strfreev(pdtokens);
339 }
340
341 static void datafeed_in(struct sr_dev *dev, struct sr_datafeed_packet *packet)
342 {
343         static struct sr_output *o = NULL;
344         static int probelist[SR_MAX_NUM_PROBES + 1] = { 0 };
345         static uint64_t received_samples = 0;
346         static int unitsize = 0;
347         static int triggered = 0;
348         static FILE *outfile = NULL;
349         struct sr_probe *probe;
350         struct sr_datafeed_header *header;
351         struct sr_datafeed_logic *logic;
352         int num_enabled_probes, sample_size, ret, i;
353         uint64_t output_len, filter_out_len;
354         uint8_t *output_buf, *filter_out;
355
356         /* If the first packet to come in isn't a header, don't even try. */
357         if (packet->type != SR_DF_HEADER && o == NULL)
358                 return;
359
360         sample_size = -1;
361         switch (packet->type) {
362         case SR_DF_HEADER:
363                 g_debug("cli: Received SR_DF_HEADER");
364                 /* Initialize the output module. */
365                 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
366                         g_critical("Output module malloc failed.");
367                         exit(1);
368                 }
369                 o->format = output_format;
370                 o->dev = dev;
371                 o->param = output_format_param;
372                 if (o->format->init) {
373                         if (o->format->init(o) != SR_OK) {
374                                 g_critical("Output format initialization failed.");
375                                 exit(1);
376                         }
377                 }
378
379                 header = packet->payload;
380                 num_enabled_probes = 0;
381                 for (i = 0; i < header->num_logic_probes; i++) {
382                         probe = g_slist_nth_data(dev->probes, i);
383                         if (probe->enabled)
384                                 probelist[num_enabled_probes++] = probe->index;
385                 }
386                 /* How many bytes we need to store num_enabled_probes bits */
387                 unitsize = (num_enabled_probes + 7) / 8;
388
389                 outfile = stdout;
390                 if (opt_output_file) {
391                         if (default_output_format) {
392                                 /* output file is in session format, which means we'll
393                                  * dump everything in the datastore as it comes in,
394                                  * and save from there after the session. */
395                                 outfile = NULL;
396                                 ret = sr_datastore_new(unitsize, &(dev->datastore));
397                                 if (ret != SR_OK) {
398                                         g_critical("Failed to create datastore.");
399                                         exit(1);
400                                 }
401                         } else {
402                                 /* saving to a file in whatever format was set
403                                  * with -O, so all we need is a filehandle */
404                                 outfile = g_fopen(opt_output_file, "wb");
405                         }
406                 }
407                 if (opt_pds) {
408                         if (srd_session_start(num_enabled_probes, unitsize,
409                                         header->samplerate) != SRD_OK)
410                                 sr_session_halt();
411                 }
412                 break;
413         case SR_DF_END:
414                 g_debug("cli: Received SR_DF_END");
415                 if (!o) {
416                         g_debug("cli: double end!");
417                         break;
418                 }
419                 if (o->format->event) {
420                         o->format->event(o, SR_DF_END, &output_buf, &output_len);
421                         if (output_len) {
422                                 if (outfile)
423                                         fwrite(output_buf, 1, output_len, outfile);
424                                 g_free(output_buf);
425                                 output_len = 0;
426                         }
427                 }
428                 if (limit_samples && received_samples < limit_samples)
429                         g_warning("Device only sent %" PRIu64 " samples.",
430                                received_samples);
431                 if (opt_continuous)
432                         g_warning("Device stopped after %" PRIu64 " samples.",
433                                received_samples);
434                 sr_session_halt();
435                 if (outfile && outfile != stdout)
436                         fclose(outfile);
437                 g_free(o);
438                 o = NULL;
439                 break;
440         case SR_DF_TRIGGER:
441                 g_debug("cli: received SR_DF_TRIGGER");
442                 if (o->format->event)
443                         o->format->event(o, SR_DF_TRIGGER, &output_buf,
444                                          &output_len);
445                 triggered = 1;
446                 break;
447         case SR_DF_LOGIC:
448                 logic = packet->payload;
449                 sample_size = logic->unitsize;
450                 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
451                 break;
452         }
453
454         /* not supporting anything but SR_DF_LOGIC for now */
455
456         if (sample_size == -1 || logic->length == 0)
457                 return;
458
459         /* Don't store any samples until triggered. */
460         if (opt_wait_trigger && !triggered)
461                 return;
462
463         if (limit_samples && received_samples >= limit_samples)
464                 return;
465
466         /* TODO: filters only support SR_DF_LOGIC */
467         ret = sr_filter_probes(sample_size, unitsize, probelist,
468                                    logic->data, logic->length,
469                                    &filter_out, &filter_out_len);
470         if (ret != SR_OK)
471                 return;
472
473         /* what comes out of the filter is guaranteed to be packed into the
474          * minimum size needed to support the number of samples at this sample
475          * size. however, the driver may have submitted too much -- cut off
476          * the buffer of the last packet according to the sample limit.
477          */
478         if (limit_samples && (received_samples + logic->length / sample_size >
479                         limit_samples * sample_size))
480                 filter_out_len = limit_samples * sample_size - received_samples;
481
482         if (dev->datastore)
483                 sr_datastore_put(dev->datastore, filter_out,
484                                  filter_out_len, sample_size, probelist);
485
486         if (opt_output_file && default_output_format)
487                 /* saving to a session file, don't need to do anything else
488                  * to this data for now. */
489                 goto cleanup;
490
491         if (opt_pds) {
492                 if (srd_session_send(received_samples, (uint8_t*)filter_out,
493                                 filter_out_len) != SRD_OK)
494                         sr_session_halt();
495         } else {
496                 output_len = 0;
497                 if (o->format->data && packet->type == o->format->df_type)
498                         o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
499                 if (output_len) {
500                         fwrite(output_buf, 1, output_len, outfile);
501                         g_free(output_buf);
502                 }
503         }
504
505 cleanup:
506         g_free(filter_out);
507         received_samples += logic->length / sample_size;
508 }
509
510 /* Register the given PDs for this session.
511  * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
512  * That will instantiate two SPI decoders on the clock but different data
513  * lines.
514  */
515 static int register_pds(struct sr_dev *dev, const char *pdstring)
516 {
517         GHashTable *pd_opthash;
518         struct srd_decoder_inst *di;
519         int ret;
520         char **pdtokens, **pdtok, *pd_name;
521
522         /* Avoid compiler warnings. */
523         (void)dev;
524
525         ret = 0;
526         pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
527                         g_free, NULL);
528         pd_name = NULL;
529         pd_opthash = NULL;
530         pdtokens = g_strsplit(pdstring, ",", 0);
531         for (pdtok = pdtokens; *pdtok; pdtok++) {
532                 if (!(pd_opthash = parse_generic_arg(*pdtok))) {
533                         g_critical("Invalid protocol decoder option '%s'.", *pdtok);
534                         goto err_out;
535                 }
536
537                 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
538                 g_hash_table_remove(pd_opthash, "sigrok_key");
539                 if (srd_decoder_load(pd_name) != SRD_OK) {
540                         g_critical("Failed to load protocol decoder %s.", pd_name);
541                         ret = 1;
542                         goto err_out;
543                 }
544                 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
545                         g_critical("Failed to instantiate protocol decoder %s.", pd_name);
546                         ret = 1;
547                         goto err_out;
548                 }
549
550                 /* If no annotation list was specified, add them all in now.
551                  * This will be pared down later to leave only the last PD
552                  * in the stack.
553                  */
554                 if (!opt_pd_annotation)
555                         g_hash_table_insert(pd_ann_visible, g_strdup(di->inst_id), NULL);
556
557                 /* Any keys left in the options hash are probes, where the key
558                  * is the probe name as specified in the decoder class, and the
559                  * value is the probe number i.e. the order in which the PD's
560                  * incoming samples are arranged. */
561                 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
562                         ret = 1;
563                         goto err_out;
564                 }
565                 g_hash_table_destroy(pd_opthash);
566                 pd_opthash = NULL;
567         }
568
569 err_out:
570         g_strfreev(pdtokens);
571         if (pd_opthash)
572                 g_hash_table_destroy(pd_opthash);
573         if (pd_name)
574                 g_free(pd_name);
575
576         return ret;
577 }
578
579 int setup_pd_stack(void)
580 {
581         struct srd_decoder_inst *di_from, *di_to;
582         int ret, i;
583         char **pds;
584
585         /* Set up the protocol decoder stack. */
586         pds = g_strsplit(opt_pds, ",", 0);
587         if (g_strv_length(pds) > 1) {
588                 if (opt_pd_stack) {
589                         /* A stack setup was specified, use that. */
590                         g_strfreev(pds);
591                         pds = g_strsplit(opt_pd_stack, ",", 0);
592                         if (g_strv_length(pds) < 2) {
593                                 g_strfreev(pds);
594                                 g_critical("Specify at least two protocol decoders to stack.");
595                                 return 1;
596                         }
597                 }
598
599                 if (!(di_from = srd_inst_find_by_id(pds[0]))) {
600                         g_critical("Cannot stack protocol decoder '%s': "
601                                         "instance not found.", pds[0]);
602                         return 1;
603                 }
604                 for (i = 1; pds[i]; i++) {
605                         if (!(di_to = srd_inst_find_by_id(pds[i]))) {
606                                 g_critical("Cannot stack protocol decoder '%s': "
607                                                 "instance not found.", pds[i]);
608                                 return 1;
609                         }
610                         if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
611                                 return 1;
612
613                         /* Don't show annotation from this PD. Only the last PD in
614                          * the stack will be left on the annotation list (unless
615                          * the annotation list was specifically provided).
616                          */
617                         if (!opt_pd_annotation)
618                                 g_hash_table_remove(pd_ann_visible, di_from->inst_id);
619
620                         di_from = di_to;
621                 }
622         }
623         g_strfreev(pds);
624
625         return 0;
626 }
627
628 int setup_pd_annotations(void)
629 {
630         GSList *l;
631         struct srd_decoder *dec;
632         int ann;
633         char **pds, **pdtok, **keyval, **ann_descr;
634
635         /* Set up custom list of PDs and annotations to show. */
636         if (opt_pd_annotation) {
637                 pds = g_strsplit(opt_pd_annotation, ",", 0);
638                 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
639                         ann = 0;
640                         keyval = g_strsplit(*pdtok, "=", 0);
641                         if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
642                                 g_critical("Protocol decoder '%s' not found.", keyval[0]);
643                                 return 1;
644                         }
645                         if (!dec->annotations) {
646                                 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
647                                 return 1;
648                         }
649                         if (g_strv_length(keyval) == 2) {
650                                 for (l = dec->annotations; l; l = l->next, ann++) {
651                                         ann_descr = l->data;
652                                         if (!canon_cmp(ann_descr[0], keyval[1]))
653                                                 /* Found it. */
654                                                 break;
655                                 }
656                                 if (!l) {
657                                         g_critical("Annotation '%s' not found "
658                                                         "for protocol decoder '%s'.", keyval[1], keyval[0]);
659                                         return 1;
660                                 }
661                         }
662                         g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
663                         g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
664                         g_strfreev(keyval);
665                 }
666                 g_strfreev(pds);
667         }
668
669         return 0;
670 }
671
672 int setup_output_format(void)
673 {
674         GHashTable *fmtargs;
675         GHashTableIter iter;
676         gpointer key, value;
677         struct sr_output_format **outputs;
678         int i;
679         char *fmtspec;
680
681         if (!opt_output_format) {
682                 opt_output_format = DEFAULT_OUTPUT_FORMAT;
683                 /* we'll need to remember this so when saving to a file
684                  * later, sigrok session format will be used.
685                  */
686                 default_output_format = TRUE;
687         }
688         fmtargs = parse_generic_arg(opt_output_format);
689         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
690         if (!fmtspec) {
691                 g_critical("Invalid output format.");
692                 return 1;
693         }
694         outputs = sr_output_list();
695         for (i = 0; outputs[i]; i++) {
696                 if (strcmp(outputs[i]->id, fmtspec))
697                         continue;
698                 g_hash_table_remove(fmtargs, "sigrok_key");
699                 output_format = outputs[i];
700                 g_hash_table_iter_init(&iter, fmtargs);
701                 while (g_hash_table_iter_next(&iter, &key, &value)) {
702                         /* only supporting one parameter per output module
703                          * for now, and only its value */
704                         output_format_param = g_strdup(value);
705                         break;
706                 }
707                 break;
708         }
709         if (!output_format) {
710                 g_critical("Invalid output format %s.", opt_output_format);
711                 return 1;
712         }
713         g_hash_table_destroy(fmtargs);
714
715         return 0;
716 }
717
718 void show_pd_annotation(struct srd_proto_data *pdata, void *cb_data)
719 {
720         int i;
721         char **annotations;
722         gpointer ann_format;
723
724         /* 'cb_data' is not used in this specific callback. */
725         (void)cb_data;
726
727         if (!pd_ann_visible)
728                 return;
729
730         if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
731                         NULL, &ann_format))
732                 /* Not in the list of PDs whose annotations we're showing. */
733                 return;
734
735         if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
736                 /* We don't want this particular format from the PD. */
737                 return;
738
739         annotations = pdata->data;
740         if (opt_loglevel > SR_LOG_WARN)
741                 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
742         printf("%s: ", pdata->pdo->proto_id);
743         for (i = 0; annotations[i]; i++)
744                 printf("\"%s\" ", annotations[i]);
745         printf("\n");
746 }
747
748 static int select_probes(struct sr_dev *dev)
749 {
750         struct sr_probe *probe;
751         char **probelist;
752         int max_probes, i;
753
754         if (!opt_probes)
755                 return SR_OK;
756
757         /*
758          * This only works because a device by default initializes
759          * and enables all its probes.
760          */
761         max_probes = g_slist_length(dev->probes);
762         probelist = parse_probestring(max_probes, opt_probes);
763         if (!probelist) {
764                 return SR_ERR;
765         }
766
767         for (i = 0; i < max_probes; i++) {
768                 if (probelist[i]) {
769                         sr_dev_probe_name_set(dev, i + 1, probelist[i]);
770                         g_free(probelist[i]);
771                 } else {
772                         probe = sr_dev_probe_find(dev, i + 1);
773                         probe->enabled = FALSE;
774                 }
775         }
776         g_free(probelist);
777
778         return SR_OK;
779 }
780
781 /**
782  * Return the input file format which the CLI tool should use.
783  *
784  * If the user specified -I / --input-format, use that one. Otherwise, try to
785  * autodetect the format as good as possible. Failing that, return NULL.
786  *
787  * @param filename The filename of the input file. Must not be NULL.
788  * @param opt The -I / --input-file option the user specified (or NULL).
789  *
790  * @return A pointer to the 'struct sr_input_format' that should be used,
791  *         or NULL if no input format was selected or auto-detected.
792  */
793 static struct sr_input_format *determine_input_file_format(
794                         const char *filename, const char *opt)
795 {
796         int i;
797         struct sr_input_format **inputs;
798
799         /* If there are no input formats, return NULL right away. */
800         inputs = sr_input_list();
801         if (!inputs) {
802                 g_critical("No supported input formats available.");
803                 return NULL;
804         }
805
806         /* If the user specified -I / --input-format, use that one. */
807         if (opt) {
808                 for (i = 0; inputs[i]; i++) {
809                         if (strcasecmp(inputs[i]->id, opt_input_format))
810                                 continue;
811                         g_debug("Using user-specified input file format '%s'.",
812                                         inputs[i]->id);
813                         return inputs[i];
814                 }
815
816                 /* The user specified an unknown input format, return NULL. */
817                 g_critical("Error: specified input file format '%s' is "
818                         "unknown.", opt_input_format);
819                 return NULL;
820         }
821
822         /* Otherwise, try to find an input module that can handle this file. */
823         for (i = 0; inputs[i]; i++) {
824                 if (inputs[i]->format_match(filename))
825                         break;
826         }
827
828         /* Return NULL if no input module wanted to touch this. */
829         if (!inputs[i]) {
830                 g_critical("Error: no matching input module found.");
831                 return NULL;
832         }
833                 
834         return inputs[i];
835 }
836
837 static void load_input_file_format(void)
838 {
839         struct stat st;
840         struct sr_input *in;
841         struct sr_input_format *input_format;
842
843         if (!(input_format = determine_input_file_format(opt_input_file,
844                                                    opt_input_format)))
845                 /* The exact cause was already logged. */
846                 return;
847
848         if (stat(opt_input_file, &st) == -1) {
849                 g_critical("Failed to load %s: %s", opt_input_file,
850                         strerror(errno));
851                 exit(1);
852         }
853
854         /* Initialize the input module. */
855         if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
856                 g_critical("Failed to allocate input module.");
857                 exit(1);
858         }
859         in->format = input_format;
860         in->param = input_format_param;
861         if (in->format->init) {
862                 if (in->format->init(in) != SR_OK) {
863                         g_critical("Input format init failed.");
864                         exit(1);
865                 }
866         }
867
868         if (select_probes(in->vdev) > 0)
869             return;
870
871         sr_session_new();
872         sr_session_datafeed_callback_add(datafeed_in);
873         if (sr_session_dev_add(in->vdev) != SR_OK) {
874                 g_critical("Failed to use device.");
875                 sr_session_destroy();
876                 return;
877         }
878
879         input_format->loadfile(in, opt_input_file);
880         if (opt_output_file && default_output_format) {
881                 if (sr_session_save(opt_output_file) != SR_OK)
882                         g_critical("Failed to save session.");
883         }
884         sr_session_destroy();
885 }
886
887 static void load_input_file(void)
888 {
889
890         if (sr_session_load(opt_input_file) == SR_OK) {
891                 /* sigrok session file */
892                 sr_session_datafeed_callback_add(datafeed_in);
893                 sr_session_start();
894                 sr_session_run();
895                 sr_session_stop();
896         }
897         else {
898                 /* fall back on input modules */
899                 load_input_file_format();
900         }
901 }
902
903 int num_real_devs(void)
904 {
905         struct sr_dev *dev;
906         GSList *devs, *l;
907         int num_devs;
908
909         num_devs = 0;
910         devs = sr_dev_list();
911         for (l = devs; l; l = l->next) {
912                 dev = l->data;
913                 if (!sr_dev_has_hwcap(dev, SR_HWCAP_DEMO_DEV))
914                         num_devs++;
915         }
916
917         return num_devs;
918 }
919
920 static int set_dev_options(struct sr_dev *dev, GHashTable *args)
921 {
922         GHashTableIter iter;
923         gpointer key, value;
924         int ret, i;
925         uint64_t tmp_u64;
926         gboolean found;
927         gboolean tmp_bool;
928
929         g_hash_table_iter_init(&iter, args);
930         while (g_hash_table_iter_next(&iter, &key, &value)) {
931                 found = FALSE;
932                 for (i = 0; sr_hwcap_options[i].hwcap; i++) {
933                         if (strcmp(sr_hwcap_options[i].shortname, key))
934                                 continue;
935                         if ((value == NULL) && 
936                             (sr_hwcap_options[i].type != SR_T_BOOL)) {
937                                 g_critical("Option '%s' needs a value.", (char *)key);
938                                 return SR_ERR;
939                         }
940                         found = TRUE;
941                         switch (sr_hwcap_options[i].type) {
942                         case SR_T_UINT64:
943                                 ret = sr_parse_sizestring(value, &tmp_u64);
944                                 if (ret != SR_OK)
945                                         break;
946                                 ret = dev->driver->dev_config_set(dev->driver_index,
947                                         sr_hwcap_options[i].hwcap, &tmp_u64);
948                                 break;
949                         case SR_T_CHAR:
950                                 ret = dev->driver->dev_config_set(dev->driver_index,
951                                         sr_hwcap_options[i].hwcap, value);
952                                 break;
953                         case SR_T_BOOL:
954                                 if (!value)
955                                         tmp_bool = TRUE;
956                                 else 
957                                         tmp_bool = sr_parse_boolstring(value);
958                                 ret = dev->driver->dev_config_set(dev->driver_index,
959                                                 sr_hwcap_options[i].hwcap, 
960                                                 GINT_TO_POINTER(tmp_bool));
961                                 break;
962                         default:
963                                 ret = SR_ERR;
964                         }
965
966                         if (ret != SR_OK) {
967                                 g_critical("Failed to set device option '%s'.", (char *)key);
968                                 return ret;
969                         }
970                         else
971                                 break;
972                 }
973                 if (!found) {
974                         g_critical("Unknown device option '%s'.", (char *) key);
975                         return SR_ERR;
976                 }
977         }
978
979         return SR_OK;
980 }
981
982 static void run_session(void)
983 {
984         struct sr_dev *dev;
985         GHashTable *devargs;
986         int num_devs, max_probes, i;
987         uint64_t time_msec;
988         char **probelist, *devspec;
989
990         devargs = NULL;
991         if (opt_dev) {
992                 devargs = parse_generic_arg(opt_dev);
993                 devspec = g_hash_table_lookup(devargs, "sigrok_key");
994                 dev = parse_devstring(devspec);
995                 if (!dev) {
996                         g_critical("Device not found.");
997                         return;
998                 }
999                 g_hash_table_remove(devargs, "sigrok_key");
1000         } else {
1001                 num_devs = num_real_devs();
1002                 if (num_devs == 1) {
1003                         /* No device specified, but there is only one. */
1004                         devargs = NULL;
1005                         dev = parse_devstring("0");
1006                 } else if (num_devs == 0) {
1007                         g_critical("No devices found.");
1008                         return;
1009                 } else {
1010                         g_critical("%d devices found, please select one.", num_devs);
1011                         return;
1012                 }
1013         }
1014
1015         sr_session_new();
1016         sr_session_datafeed_callback_add(datafeed_in);
1017
1018         if (sr_session_dev_add(dev) != SR_OK) {
1019                 g_critical("Failed to use device.");
1020                 sr_session_destroy();
1021                 return;
1022         }
1023
1024         if (devargs) {
1025                 if (set_dev_options(dev, devargs) != SR_OK) {
1026                         sr_session_destroy();
1027                         return;
1028                 }
1029                 g_hash_table_destroy(devargs);
1030         }
1031
1032         if (select_probes(dev) != SR_OK)
1033             return;
1034
1035         if (opt_continuous) {
1036                 if (!sr_driver_hwcap_exists(dev->driver, SR_HWCAP_CONTINUOUS)) {
1037                         g_critical("This device does not support continuous sampling.");
1038                         sr_session_destroy();
1039                         return;
1040                 }
1041         }
1042
1043         if (opt_triggers) {
1044                 probelist = sr_parse_triggerstring(dev, opt_triggers);
1045                 if (!probelist) {
1046                         sr_session_destroy();
1047                         return;
1048                 }
1049
1050                 max_probes = g_slist_length(dev->probes);
1051                 for (i = 0; i < max_probes; i++) {
1052                         if (probelist[i]) {
1053                                 sr_dev_trigger_set(dev, i + 1, probelist[i]);
1054                                 g_free(probelist[i]);
1055                         }
1056                 }
1057                 g_free(probelist);
1058         }
1059
1060         if (opt_time) {
1061                 time_msec = sr_parse_timestring(opt_time);
1062                 if (time_msec == 0) {
1063                         g_critical("Invalid time '%s'", opt_time);
1064                         sr_session_destroy();
1065                         return;
1066                 }
1067
1068                 if (sr_driver_hwcap_exists(dev->driver, SR_HWCAP_LIMIT_MSEC)) {
1069                         if (dev->driver->dev_config_set(dev->driver_index,
1070                             SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1071                                 g_critical("Failed to configure time limit.");
1072                                 sr_session_destroy();
1073                                 return;
1074                         }
1075                 }
1076                 else {
1077                         /* time limit set, but device doesn't support this...
1078                          * convert to samples based on the samplerate.
1079                          */
1080                         limit_samples = 0;
1081                         if (sr_dev_has_hwcap(dev, SR_HWCAP_SAMPLERATE)) {
1082                                 const uint64_t *samplerate;
1083
1084                                 sr_dev_info_get(dev, SR_DI_CUR_SAMPLERATE,
1085                                                 (const void **)&samplerate);
1086                                 limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1087                         }
1088                         if (limit_samples == 0) {
1089                                 g_critical("Not enough time at this samplerate.");
1090                                 sr_session_destroy();
1091                                 return;
1092                         }
1093
1094                         if (dev->driver->dev_config_set(dev->driver_index,
1095                             SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK) {
1096                                 g_critical("Failed to configure time-based sample limit.");
1097                                 sr_session_destroy();
1098                                 return;
1099                         }
1100                 }
1101         }
1102
1103         if (opt_samples) {
1104                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1105                         || (dev->driver->dev_config_set(dev->driver_index,
1106                             SR_HWCAP_LIMIT_SAMPLES, &limit_samples) != SR_OK)) {
1107                         g_critical("Failed to configure sample limit.");
1108                         sr_session_destroy();
1109                         return;
1110                 }
1111         }
1112
1113         if (dev->driver->dev_config_set(dev->driver_index,
1114                   SR_HWCAP_PROBECONFIG, (char *)dev->probes) != SR_OK) {
1115                 g_critical("Failed to configure probes.");
1116                 sr_session_destroy();
1117                 return;
1118         }
1119
1120         if (sr_session_start() != SR_OK) {
1121                 g_critical("Failed to start session.");
1122                 sr_session_destroy();
1123                 return;
1124         }
1125
1126         if (opt_continuous)
1127                 add_anykey();
1128
1129         sr_session_run();
1130
1131         if (opt_continuous)
1132                 clear_anykey();
1133
1134         if (opt_output_file && default_output_format) {
1135                 if (sr_session_save(opt_output_file) != SR_OK)
1136                         g_critical("Failed to save session.");
1137         }
1138         sr_session_destroy();
1139 }
1140
1141 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1142                    const gchar *message, gpointer cb_data)
1143 {
1144         /* Avoid compiler warnings. */
1145         (void)log_domain;
1146         (void)cb_data;
1147
1148         /*
1149          * All messages, warnings, errors etc. go to stderr (not stdout) in
1150          * order to not mess up the CLI tool data output, e.g. VCD output.
1151          */
1152         if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1153                         || opt_loglevel > SR_LOG_WARN) {
1154                 fprintf(stderr, "%s\n", message);
1155                 fflush(stderr);
1156         }
1157 }
1158
1159 int main(int argc, char **argv)
1160 {
1161         GOptionContext *context;
1162         GError *error;
1163
1164         g_log_set_default_handler(logger, NULL);
1165
1166         error = NULL;
1167         context = g_option_context_new(NULL);
1168         g_option_context_add_main_entries(context, optargs, NULL);
1169
1170         if (!g_option_context_parse(context, &argc, &argv, &error)) {
1171                 g_critical("%s", error->message);
1172                 return 1;
1173         }
1174
1175         /* Set the loglevel (amount of messages to output) for libsigrok. */
1176         if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1177                 return 1;
1178
1179         /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1180         if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1181                 return 1;
1182
1183         if (sr_init() != SR_OK)
1184                 return 1;
1185
1186         if (opt_pds) {
1187                 if (srd_init(NULL) != SRD_OK)
1188                         return 1;
1189                 if (register_pds(NULL, opt_pds) != 0)
1190                         return 1;
1191                 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1192                                 show_pd_annotation, NULL) != SRD_OK)
1193                         return 1;
1194                 if (setup_pd_stack() != 0)
1195                         return 1;
1196                 if (setup_pd_annotations() != 0)
1197                         return 1;
1198         }
1199
1200         if (setup_output_format() != 0)
1201                 return 1;
1202
1203         if (opt_version)
1204                 show_version();
1205         else if (opt_list_devs)
1206                 show_dev_list();
1207         else if (opt_input_file)
1208                 load_input_file();
1209         else if (opt_samples || opt_time || opt_continuous)
1210                 run_session();
1211         else if (opt_dev)
1212                 show_dev_detail();
1213         else if (opt_pds)
1214                 show_pd_detail();
1215         else
1216                 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1217
1218         if (opt_pds)
1219                 srd_exit();
1220
1221         g_option_context_free(context);
1222         sr_exit();
1223
1224         return 0;
1225 }