Corrected a comment typo
[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 <libsigrok/libsigrok.h>
34 #include "sigrok-cli.h"
35 #include "config.h"
36
37 #define DEFAULT_OUTPUT_FORMAT "bits:width=64"
38
39 static struct sr_context *sr_ctx = NULL;
40
41 static uint64_t limit_samples = 0;
42 static uint64_t limit_frames = 0;
43 static struct sr_output_format *output_format = NULL;
44 static int default_output_format = FALSE;
45 static char *output_format_param = NULL;
46 static GHashTable *pd_ann_visible = NULL;
47 static struct sr_datastore *singleds = NULL;
48
49 static gboolean opt_version = FALSE;
50 static gint opt_loglevel = SR_LOG_WARN; /* Show errors+warnings per default. */
51 static gboolean opt_list_devs = FALSE;
52 static gboolean opt_wait_trigger = FALSE;
53 static gchar *opt_input_file = NULL;
54 static gchar *opt_output_file = NULL;
55 static gchar *opt_drv = NULL;
56 static gchar *opt_dev = NULL;
57 static gchar *opt_probes = NULL;
58 static gchar *opt_triggers = NULL;
59 static gchar *opt_pds = NULL;
60 static gchar *opt_pd_stack = NULL;
61 static gchar *opt_pd_annotations = NULL;
62 static gchar *opt_input_format = NULL;
63 static gchar *opt_output_format = NULL;
64 static gchar *opt_show = NULL;
65 static gchar *opt_time = NULL;
66 static gchar *opt_samples = NULL;
67 static gchar *opt_frames = NULL;
68 static gchar *opt_continuous = NULL;
69
70 static GOptionEntry optargs[] = {
71         {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
72                         "Show version and support list", NULL},
73         {"loglevel", 'l', 0, G_OPTION_ARG_INT, &opt_loglevel,
74                         "Set libsigrok/libsigrokdecode loglevel", NULL},
75         {"list-devices", 'D', 0, G_OPTION_ARG_NONE, &opt_list_devs,
76                         "Scan for devices", NULL},
77         {"driver", 0, 0, G_OPTION_ARG_STRING, &opt_drv,
78                         "Use only this driver", NULL},
79         {"device", 'd', 0, G_OPTION_ARG_STRING, &opt_dev,
80                         "Use specified device", NULL},
81         {"input-file", 'i', 0, G_OPTION_ARG_FILENAME, &opt_input_file,
82                         "Load input from file", NULL},
83         {"input-format", 'I', 0, G_OPTION_ARG_STRING, &opt_input_format,
84                         "Input format", NULL},
85         {"output-file", 'o', 0, G_OPTION_ARG_FILENAME, &opt_output_file,
86                         "Save output to file", NULL},
87         {"output-format", 'O', 0, G_OPTION_ARG_STRING, &opt_output_format,
88                         "Output format", NULL},
89         {"probes", 'p', 0, G_OPTION_ARG_STRING, &opt_probes,
90                         "Probes to use", NULL},
91         {"triggers", 't', 0, G_OPTION_ARG_STRING, &opt_triggers,
92                         "Trigger configuration", NULL},
93         {"wait-trigger", 'w', 0, G_OPTION_ARG_NONE, &opt_wait_trigger,
94                         "Wait for trigger", NULL},
95         {"protocol-decoders", 'a', 0, G_OPTION_ARG_STRING, &opt_pds,
96                         "Protocol decoders to run", NULL},
97         {"protocol-decoder-stack", 's', 0, G_OPTION_ARG_STRING, &opt_pd_stack,
98                         "Protocol decoder stack", NULL},
99         {"protocol-decoder-annotations", 'A', 0, G_OPTION_ARG_STRING, &opt_pd_annotations,
100                         "Protocol decoder annotation(s) to show", NULL},
101         {"show", 0, 0, G_OPTION_ARG_NONE, &opt_show,
102                         "Show device detail", NULL},
103         {"time", 0, 0, G_OPTION_ARG_STRING, &opt_time,
104                         "How long to sample (ms)", NULL},
105         {"samples", 0, 0, G_OPTION_ARG_STRING, &opt_samples,
106                         "Number of samples to acquire", NULL},
107         {"frames", 0, 0, G_OPTION_ARG_STRING, &opt_frames,
108                         "Number of frames to acquire", NULL},
109         {"continuous", 0, 0, G_OPTION_ARG_NONE, &opt_continuous,
110                         "Sample continuously", NULL},
111         {NULL, 0, 0, 0, NULL, NULL, NULL}
112 };
113
114
115 /* Convert driver options hash to GSList of struct sr_hwopt. */
116 static GSList *hash_to_hwopt(GHashTable *hash)
117 {
118         const struct sr_hwcap_option *hwo;
119         struct sr_hwopt *hwopt;
120         GList *gl, *keys;
121         GSList *opts;
122         char *key, *value;
123
124         keys = g_hash_table_get_keys(hash);
125         opts = NULL;
126         for (gl = keys; gl; gl = gl->next) {
127                 key = gl->data;
128                 if (!(hwo = sr_drvopt_name_get(key))) {
129                         g_critical("Unknown option %s", key);
130                         return NULL;
131                 }
132                 hwopt = g_try_malloc(sizeof(struct sr_hwopt));
133                 hwopt->hwopt = hwo->hwcap;
134                 value = g_hash_table_lookup(hash, key);
135                 hwopt->value = g_strdup(value);
136                 opts = g_slist_append(opts, hwopt);
137         }
138         g_list_free(keys);
139
140         return opts;
141 }
142
143 static GSList *device_scan(void)
144 {
145         struct sr_dev_driver **drivers, *driver;
146         GHashTable *drvargs;
147         GSList *drvopts, *devices, *tmpdevs, *l;
148         int i;
149         char *drvname;
150
151         if (opt_drv) {
152                 drvargs = parse_generic_arg(opt_drv, TRUE);
153                 drvname = g_strdup(g_hash_table_lookup(drvargs, "sigrok_key"));
154                 g_hash_table_remove(drvargs, "sigrok_key");
155                 driver = NULL;
156                 drivers = sr_driver_list();
157                 for (i = 0; drivers[i]; i++) {
158                         if (strcmp(drivers[i]->name, drvname))
159                                 continue;
160                         driver = drivers[i];
161                 }
162                 if (!driver) {
163                         g_critical("Driver %s not found.", drvname);
164                         return NULL;
165                 }
166                 g_free(drvname);
167                 if (sr_driver_init(sr_ctx, driver) != SR_OK) {
168                         g_critical("Failed to initialize driver.");
169                         return NULL;
170                 }
171                 drvopts = NULL;
172                 if (g_hash_table_size(drvargs) > 0)
173                         if (!(drvopts = hash_to_hwopt(drvargs)))
174                                 /* Unknown options, already logged. */
175                                 return NULL;
176                 devices = sr_driver_scan(driver, drvopts);
177         } else {
178                 /* No driver specified, let them all scan on their own. */
179                 devices = NULL;
180                 drivers = sr_driver_list();
181                 for (i = 0; drivers[i]; i++) {
182                         driver = drivers[i];
183                         if (sr_driver_init(sr_ctx, driver) != SR_OK) {
184                                 g_critical("Failed to initialize driver.");
185                                 return NULL;
186                         }
187                         tmpdevs = sr_driver_scan(driver, NULL);
188                         for (l = tmpdevs; l; l = l->next)
189                                 devices = g_slist_append(devices, l->data);
190                         g_slist_free(tmpdevs);
191                 }
192         }
193
194         return devices;
195 }
196
197 static void show_version(void)
198 {
199         const GSList *l;
200         struct sr_dev_driver **drivers;
201         struct sr_input_format **inputs;
202         struct sr_output_format **outputs;
203         struct srd_decoder *dec;
204         int i;
205
206         printf("sigrok-cli %s\n\n", VERSION);
207
208         printf("Using libsigrok %s (lib version %s).\n",
209                sr_package_version_string_get(), sr_lib_version_string_get());
210         printf("Using libsigrokdecode %s (lib version %s).\n\n",
211                srd_package_version_string_get(), srd_lib_version_string_get());
212
213         printf("Supported hardware drivers:\n");
214         drivers = sr_driver_list();
215         for (i = 0; drivers[i]; i++) {
216                 printf("  %-20s %s\n", drivers[i]->name, drivers[i]->longname);
217         }
218         printf("\n");
219
220         printf("Supported input formats:\n");
221         inputs = sr_input_list();
222         for (i = 0; inputs[i]; i++)
223                 printf("  %-20s %s\n", inputs[i]->id, inputs[i]->description);
224         printf("\n");
225
226         printf("Supported output formats:\n");
227         outputs = sr_output_list();
228         for (i = 0; outputs[i]; i++)
229                 printf("  %-20s %s\n", outputs[i]->id, outputs[i]->description);
230         printf("\n");
231
232         if (srd_init(NULL) == SRD_OK) {
233                 printf("Supported protocol decoders:\n");
234                 srd_decoder_load_all();
235                 for (l = srd_decoder_list(); l; l = l->next) {
236                         dec = l->data;
237                         printf("  %-20s %s\n", dec->id, dec->longname);
238                         /* Print protocol description upon "-l 3" or higher. */
239                         if (opt_loglevel >= SR_LOG_INFO)
240                                 printf("  %-20s %s\n", "", dec->desc);
241                 }
242                 srd_exit();
243         }
244         printf("\n");
245 }
246
247 static void print_dev_line(const struct sr_dev_inst *sdi)
248 {
249         struct sr_probe *probe;
250         GSList *l;
251
252         if (sdi->vendor && sdi->vendor[0])
253                 printf("%s ", sdi->vendor);
254         if (sdi->model && sdi->model[0])
255                 printf("%s ", sdi->model);
256         if (sdi->version && sdi->version[0])
257                 printf("%s ", sdi->version);
258         if (sdi->probes) {
259                 if (g_slist_length(sdi->probes) == 1) {
260                         probe = sdi->probes->data;
261                         printf("with 1 probe: %s", probe->name);
262                 } else {
263                         printf("with %d probes:", g_slist_length(sdi->probes));
264                         for (l = sdi->probes; l; l = l->next) {
265                                 probe = l->data;
266                                 printf(" %s", probe->name);
267                         }
268                 }
269         }
270         printf("\n");
271 }
272
273 static void show_dev_list(void)
274 {
275         struct sr_dev_inst *sdi;
276         GSList *devices, *l;
277
278         if (!(devices = device_scan()))
279                 return;
280
281         printf("The following devices were found:\n");
282         for (l = devices; l; l = l->next) {
283                 sdi = l->data;
284                 print_dev_line(sdi);
285         }
286         g_slist_free(devices);
287
288 }
289
290 static void show_dev_detail(void)
291 {
292         struct sr_dev_inst *sdi;
293         const struct sr_hwcap_option *hwo;
294         const struct sr_samplerates *samplerates;
295         struct sr_rational *rationals;
296         GSList *devices;
297         uint64_t *integers;
298         const int *hwopts, *hwcaps;
299         int cap, num_devices, n, i;
300         char *s, *title;
301         const char *charopts, **stropts;
302
303         if (!(devices = device_scan())) {
304                 g_critical("No devices found.");
305                 return;
306         }
307
308         num_devices = g_slist_length(devices);
309         if (num_devices > 1) {
310                 if (!opt_dev) {
311                         g_critical("%d devices found. Use --list-devices to show them, "
312                                         "and --device to select one.", num_devices);
313                         return;
314                 }
315                 /* opt_dev is NULL if not specified, which is fine. */
316                 n = strtol(opt_dev, NULL, 10);
317                 if (n >= num_devices) {
318                         g_critical("%d devices found, numbered starting from 0.",
319                                         num_devices);
320                         return;
321                 }
322                 sdi = g_slist_nth_data(devices, n);
323         } else
324                 sdi = g_slist_nth_data(devices, 0);
325
326         print_dev_line(sdi);
327
328         if (sr_info_get(sdi->driver, SR_DI_TRIGGER_TYPES, (const void **)&charopts,
329                         sdi) == SR_OK && charopts) {
330                 printf("Supported triggers: ");
331                 while (*charopts) {
332                         printf("%c ", *charopts);
333                         charopts++;
334                 }
335                 printf("\n");
336         }
337
338         if ((sr_info_get(sdi->driver, SR_DI_HWOPTS, (const void **)&hwopts,
339                         NULL) == SR_OK) && hwopts) {
340                 printf("Supported driver options:\n");
341                 for (i = 0; hwopts[i]; i++) {
342                         if (!(hwo = sr_drvopt_get(hwopts[i])))
343                                 continue;
344                         printf("    %s\n", hwo->shortname);
345                 }
346         }
347
348         title = "Supported device options:\n";
349         if ((sr_info_get(sdi->driver, SR_DI_HWCAPS, (const void **)&hwcaps,
350                         NULL) != SR_OK) || !hwcaps)
351                 /* Driver supports no device instance options. */
352                 return;
353
354         for (cap = 0; hwcaps[cap]; cap++) {
355                 if (!(hwo = sr_devopt_get(hwcaps[cap])))
356                         continue;
357
358                 if (title) {
359                         printf("%s", title);
360                         title = NULL;
361                 }
362
363                 if (hwo->hwcap == SR_HWCAP_PATTERN_MODE) {
364                         /* Pattern generator modes */
365                         printf("    %s", hwo->shortname);
366                         if (sr_info_get(sdi->driver, SR_DI_PATTERNS,
367                                         (const void **)&stropts, sdi) == SR_OK) {
368                                 printf(" - supported patterns:\n");
369                                 for (i = 0; stropts[i]; i++)
370                                         printf("      %s\n", stropts[i]);
371                         } else {
372                                 printf("\n");
373                         }
374
375                 } else if (hwo->hwcap == SR_HWCAP_SAMPLERATE) {
376                         /* Supported samplerates */
377                         printf("    %s", hwo->shortname);
378                         if (sr_info_get(sdi->driver, SR_DI_SAMPLERATES,
379                                         (const void **)&samplerates, sdi) != SR_OK) {
380                                 printf("\n");
381                                 continue;
382                         }
383                         if (samplerates->step) {
384                                 /* low */
385                                 if (!(s = sr_samplerate_string(samplerates->low)))
386                                         continue;
387                                 printf(" (%s", s);
388                                 g_free(s);
389                                 /* high */
390                                 if (!(s = sr_samplerate_string(samplerates->high)))
391                                         continue;
392                                 printf(" - %s", s);
393                                 g_free(s);
394                                 /* step */
395                                 if (!(s = sr_samplerate_string(samplerates->step)))
396                                         continue;
397                                 printf(" in steps of %s)\n", s);
398                                 g_free(s);
399                         } else {
400                                 printf(" - supported samplerates:\n");
401                                 for (i = 0; samplerates->list[i]; i++)
402                                         printf("      %s\n", sr_samplerate_string(samplerates->list[i]));
403                         }
404
405                 } else if (hwo->hwcap == SR_HWCAP_BUFFERSIZE) {
406                         /* Supported buffer sizes */
407                         printf("    %s", hwo->shortname);
408                         if (sr_info_get(sdi->driver, SR_DI_BUFFERSIZES,
409                                         (const void **)&integers, sdi) != SR_OK) {
410                                 printf("\n");
411                                 continue;
412                         }
413                         printf(" - supported buffer sizes:\n");
414                         for (i = 0; integers[i]; i++)
415                                 printf("      %"PRIu64"\n", integers[i]);
416
417                 } else if (hwo->hwcap == SR_HWCAP_TIMEBASE) {
418                         /* Supported time bases */
419                         printf("    %s", hwo->shortname);
420                         if (sr_info_get(sdi->driver, SR_DI_TIMEBASES,
421                                         (const void **)&rationals, sdi) != SR_OK) {
422                                 printf("\n");
423                                 continue;
424                         }
425                         printf(" - supported time bases:\n");
426                         for (i = 0; rationals[i].p && rationals[i].q; i++)
427                                 printf("      %s\n", sr_period_string(
428                                                 rationals[i].p * rationals[i].q));
429
430                 } else if (hwo->hwcap == SR_HWCAP_TRIGGER_SOURCE) {
431                         /* Supported trigger sources */
432                         printf("    %s", hwo->shortname);
433                         if (sr_info_get(sdi->driver, SR_DI_TRIGGER_SOURCES,
434                                         (const void **)&stropts, sdi) != SR_OK) {
435                                 printf("\n");
436                                 continue;
437                         }
438                         printf(" - supported trigger sources:\n");
439                         for (i = 0; stropts[i]; i++)
440                                 printf("      %s\n", stropts[i]);
441
442                 } else if (hwo->hwcap == SR_HWCAP_FILTER) {
443                         /* Supported filters */
444                         printf("    %s", hwo->shortname);
445                         if (sr_info_get(sdi->driver, SR_DI_FILTERS,
446                                         (const void **)&stropts, sdi) != SR_OK) {
447                                 printf("\n");
448                                 continue;
449                         }
450                         printf(" - supported filter targets:\n");
451                         for (i = 0; stropts[i]; i++)
452                                 printf("      %s\n", stropts[i]);
453
454                 } else if (hwo->hwcap == SR_HWCAP_VDIV) {
455                         /* Supported volts/div values */
456                         printf("    %s", hwo->shortname);
457                         if (sr_info_get(sdi->driver, SR_DI_VDIVS,
458                                         (const void **)&rationals, sdi) != SR_OK) {
459                                 printf("\n");
460                                 continue;
461                         }
462                         printf(" - supported volts/div:\n");
463                         for (i = 0; rationals[i].p && rationals[i].q; i++)
464                                 printf("      %s\n", sr_voltage_string( &rationals[i]));
465
466                 } else if (hwo->hwcap == SR_HWCAP_COUPLING) {
467                         /* Supported coupling settings */
468                         printf("    %s", hwo->shortname);
469                         if (sr_info_get(sdi->driver, SR_DI_COUPLING,
470                                         (const void **)&stropts, sdi) != SR_OK) {
471                                 printf("\n");
472                                 continue;
473                         }
474                         printf(" - supported coupling options:\n");
475                         for (i = 0; stropts[i]; i++)
476                                 printf("      %s\n", stropts[i]);
477
478                 } else {
479                         /* Everything else */
480                         printf("    %s\n", hwo->shortname);
481                 }
482         }
483
484 }
485
486 static void show_pd_detail(void)
487 {
488         GSList *l;
489         struct srd_decoder *dec;
490         char **pdtokens, **pdtok, **ann, *doc;
491         struct srd_probe *p;
492
493         pdtokens = g_strsplit(opt_pds, ",", -1);
494         for (pdtok = pdtokens; *pdtok; pdtok++) {
495                 if (!(dec = srd_decoder_get_by_id(*pdtok))) {
496                         g_critical("Protocol decoder %s not found.", *pdtok);
497                         return;
498                 }
499                 printf("ID: %s\nName: %s\nLong name: %s\nDescription: %s\n",
500                                 dec->id, dec->name, dec->longname, dec->desc);
501                 printf("License: %s\n", dec->license);
502                 printf("Annotations:\n");
503                 if (dec->annotations) {
504                         for (l = dec->annotations; l; l = l->next) {
505                                 ann = l->data;
506                                 printf("- %s\n  %s\n", ann[0], ann[1]);
507                         }
508                 } else {
509                         printf("None.\n");
510                 }
511                 /* TODO: Print supported decoder options. */
512                 printf("Required probes:\n");
513                 if (dec->probes) {
514                         for (l = dec->probes; l; l = l->next) {
515                                 p = l->data;
516                                 printf("- %s (%s): %s\n",
517                                        p->name, p->id, p->desc);
518                         }
519                 } else {
520                         printf("None.\n");
521                 }
522                 printf("Optional probes:\n");
523                 if (dec->opt_probes) {
524                         for (l = dec->opt_probes; l; l = l->next) {
525                                 p = l->data;
526                                 printf("- %s (%s): %s\n",
527                                        p->name, p->id, p->desc);
528                         }
529                 } else {
530                         printf("None.\n");
531                 }
532                 if ((doc = srd_decoder_doc_get(dec))) {
533                         printf("Documentation:\n%s\n",
534                                doc[0] == '\n' ? doc + 1 : doc);
535                         g_free(doc);
536                 }
537         }
538
539         g_strfreev(pdtokens);
540 }
541
542 static void datafeed_in(const struct sr_dev_inst *sdi,
543                 const struct sr_datafeed_packet *packet)
544 {
545         static struct sr_output *o = NULL;
546         static int logic_probelist[SR_MAX_NUM_PROBES] = { -1 };
547         static uint64_t received_samples = 0;
548         static int unitsize = 0;
549         static int triggered = 0;
550         static FILE *outfile = NULL;
551         struct sr_probe *probe;
552         const struct sr_datafeed_logic *logic;
553         const struct sr_datafeed_meta_logic *meta_logic;
554         const struct sr_datafeed_analog *analog;
555         int num_enabled_probes, sample_size, ret, i;
556         uint64_t output_len, filter_out_len;
557         uint8_t *output_buf, *filter_out;
558         GString *out;
559
560         /* If the first packet to come in isn't a header, don't even try. */
561         if (packet->type != SR_DF_HEADER && o == NULL)
562                 return;
563
564         sample_size = -1;
565         switch (packet->type) {
566         case SR_DF_HEADER:
567                 g_debug("cli: Received SR_DF_HEADER");
568                 /* Initialize the output module. */
569                 if (!(o = g_try_malloc(sizeof(struct sr_output)))) {
570                         g_critical("Output module malloc failed.");
571                         exit(1);
572                 }
573                 o->format = output_format;
574                 o->sdi = (struct sr_dev_inst *)sdi;
575                 o->param = output_format_param;
576                 if (o->format->init) {
577                         if (o->format->init(o) != SR_OK) {
578                                 g_critical("Output format initialization failed.");
579                                 exit(1);
580                         }
581                 }
582                 break;
583
584         case SR_DF_END:
585                 g_debug("cli: Received SR_DF_END");
586                 if (!o) {
587                         g_debug("cli: double end!");
588                         break;
589                 }
590                 if (o->format->event) {
591                         o->format->event(o, SR_DF_END, &output_buf, &output_len);
592                         if (output_buf) {
593                                 if (outfile)
594                                         fwrite(output_buf, 1, output_len, outfile);
595                                 g_free(output_buf);
596                                 output_len = 0;
597                         }
598                 }
599                 if (limit_samples && received_samples < limit_samples)
600                         g_warning("Device only sent %" PRIu64 " samples.",
601                                received_samples);
602                 if (opt_continuous)
603                         g_warning("Device stopped after %" PRIu64 " samples.",
604                                received_samples);
605                 if (outfile && outfile != stdout)
606                         fclose(outfile);
607
608                 if (o->format->cleanup)
609                         o->format->cleanup(o);
610                 g_free(o);
611                 o = NULL;
612                 break;
613
614         case SR_DF_TRIGGER:
615                 g_debug("cli: received SR_DF_TRIGGER");
616                 if (o->format->event)
617                         o->format->event(o, SR_DF_TRIGGER, &output_buf,
618                                          &output_len);
619                 triggered = 1;
620                 break;
621
622         case SR_DF_META_LOGIC:
623                 g_message("cli: Received SR_DF_META_LOGIC");
624                 meta_logic = packet->payload;
625                 num_enabled_probes = 0;
626                 for (i = 0; i < meta_logic->num_probes; i++) {
627                         probe = g_slist_nth_data(sdi->probes, i);
628                         if (probe->enabled)
629                                 logic_probelist[num_enabled_probes++] = probe->index;
630                 }
631                 logic_probelist[num_enabled_probes] = -1;
632                 /* How many bytes we need to store num_enabled_probes bits */
633                 unitsize = (num_enabled_probes + 7) / 8;
634
635                 outfile = stdout;
636                 if (opt_output_file) {
637                         if (default_output_format) {
638                                 /* output file is in session format, which means we'll
639                                  * dump everything in the datastore as it comes in,
640                                  * and save from there after the session. */
641                                 outfile = NULL;
642                                 ret = sr_datastore_new(unitsize, &singleds);
643                                 if (ret != SR_OK) {
644                                         g_critical("Failed to create datastore.");
645                                         exit(1);
646                                 }
647                         } else {
648                                 /* saving to a file in whatever format was set
649                                  * with --format, so all we need is a filehandle */
650                                 outfile = g_fopen(opt_output_file, "wb");
651                         }
652                 }
653                 if (opt_pds)
654                         srd_session_start(num_enabled_probes, unitsize,
655                                         meta_logic->samplerate);
656                 break;
657
658         case SR_DF_LOGIC:
659                 logic = packet->payload;
660                 g_message("cli: received SR_DF_LOGIC, %"PRIu64" bytes", logic->length);
661                 sample_size = logic->unitsize;
662                 if (logic->length == 0)
663                         break;
664
665                 /* Don't store any samples until triggered. */
666                 if (opt_wait_trigger && !triggered)
667                         break;
668
669                 if (limit_samples && received_samples >= limit_samples)
670                         break;
671
672                 ret = sr_filter_probes(sample_size, unitsize, logic_probelist,
673                                 logic->data, logic->length,
674                                 &filter_out, &filter_out_len);
675                 if (ret != SR_OK)
676                         break;
677
678                 /* what comes out of the filter is guaranteed to be packed into the
679                  * minimum size needed to support the number of samples at this sample
680                  * size. however, the driver may have submitted too much -- cut off
681                  * the buffer of the last packet according to the sample limit.
682                  */
683                 if (limit_samples && (received_samples + logic->length / sample_size >
684                                 limit_samples * sample_size))
685                         filter_out_len = limit_samples * sample_size - received_samples;
686
687                 if (singleds)
688                         sr_datastore_put(singleds, filter_out,
689                                         filter_out_len, sample_size, logic_probelist);
690
691                 if (opt_output_file && default_output_format)
692                         /* saving to a session file, don't need to do anything else
693                          * to this data for now. */
694                         goto cleanup;
695
696                 if (opt_pds) {
697                         if (srd_session_send(received_samples, (uint8_t*)filter_out,
698                                         filter_out_len) != SRD_OK)
699                                 sr_session_stop();
700                 } else {
701                         output_len = 0;
702                         if (o->format->data && packet->type == o->format->df_type)
703                                 o->format->data(o, filter_out, filter_out_len, &output_buf, &output_len);
704                         if (output_buf) {
705                                 fwrite(output_buf, 1, output_len, outfile);
706                                 fflush(outfile);
707                                 g_free(output_buf);
708                         }
709                 }
710
711                 cleanup:
712                 g_free(filter_out);
713                 received_samples += logic->length / sample_size;
714                 break;
715
716         case SR_DF_META_ANALOG:
717                 g_message("cli: Received SR_DF_META_ANALOG");
718
719                 outfile = stdout;
720                 if (opt_output_file) {
721                         if (default_output_format) {
722                                 /* output file is in session format, which means we'll
723                                  * dump everything in the datastore as it comes in,
724                                  * and save from there after the session. */
725                                 outfile = NULL;
726                                 ret = sr_datastore_new(unitsize, &singleds);
727                                 if (ret != SR_OK) {
728                                         g_critical("Failed to create datastore.");
729                                         exit(1);
730                                 }
731                         } else {
732                                 /* saving to a file in whatever format was set
733                                  * with --format, so all we need is a filehandle */
734                                 outfile = g_fopen(opt_output_file, "wb");
735                         }
736                 }
737                 break;
738
739         case SR_DF_ANALOG:
740                 analog = packet->payload;
741                 g_message("cli: received SR_DF_ANALOG, %d samples", analog->num_samples);
742                 if (analog->num_samples == 0)
743                         break;
744
745                 if (limit_samples && received_samples >= limit_samples)
746                         break;
747
748                 if (o->format->data && packet->type == o->format->df_type) {
749                         o->format->data(o, (const uint8_t *)analog->data,
750                                         analog->num_samples * sizeof(float),
751                                         &output_buf, &output_len);
752                         if (output_buf) {
753                                 fwrite(output_buf, 1, output_len, outfile);
754                                 fflush(outfile);
755                                 g_free(output_buf);
756                         }
757                 }
758
759                 received_samples += analog->num_samples;
760                 break;
761
762         case SR_DF_FRAME_BEGIN:
763                 g_debug("cli: received SR_DF_FRAME_BEGIN");
764                 if (o->format->event) {
765                         o->format->event(o, SR_DF_FRAME_BEGIN, &output_buf,
766                                          &output_len);
767                         if (output_buf) {
768                                 fwrite(output_buf, 1, output_len, outfile);
769                                 fflush(outfile);
770                                 g_free(output_buf);
771                         }
772                 }
773                 break;
774
775         case SR_DF_FRAME_END:
776                 g_debug("cli: received SR_DF_FRAME_END");
777                 if (o->format->event) {
778                         o->format->event(o, SR_DF_FRAME_END, &output_buf,
779                                          &output_len);
780                         if (output_buf) {
781                                 fwrite(output_buf, 1, output_len, outfile);
782                                 fflush(outfile);
783                                 g_free(output_buf);
784                         }
785                 }
786                 break;
787
788         default:
789                 g_message("received unknown packet type %d", packet->type);
790         }
791
792         if (o && o->format->recv) {
793                 out = o->format->recv(o, sdi, packet);
794                 if (out && out->len) {
795                         fwrite(out->str, 1, out->len, outfile);
796                         fflush(outfile);
797                 }
798         }
799
800 }
801
802 /* Register the given PDs for this session.
803  * Accepts a string of the form: "spi:sck=3:sdata=4,spi:sck=3:sdata=5"
804  * That will instantiate two SPI decoders on the clock but different data
805  * lines.
806  */
807 static int register_pds(struct sr_dev *dev, const char *pdstring)
808 {
809         GHashTable *pd_opthash;
810         struct srd_decoder_inst *di;
811         int ret;
812         char **pdtokens, **pdtok, *pd_name;
813
814         (void)dev;
815
816         ret = 0;
817         pd_ann_visible = g_hash_table_new_full(g_str_hash, g_int_equal,
818                         g_free, NULL);
819         pd_name = NULL;
820         pd_opthash = NULL;
821         pdtokens = g_strsplit(pdstring, ",", 0);
822         for (pdtok = pdtokens; *pdtok; pdtok++) {
823                 if (!(pd_opthash = parse_generic_arg(*pdtok, TRUE))) {
824                         g_critical("Invalid protocol decoder option '%s'.", *pdtok);
825                         goto err_out;
826                 }
827
828                 pd_name = g_strdup(g_hash_table_lookup(pd_opthash, "sigrok_key"));
829                 g_hash_table_remove(pd_opthash, "sigrok_key");
830                 if (srd_decoder_load(pd_name) != SRD_OK) {
831                         g_critical("Failed to load protocol decoder %s.", pd_name);
832                         ret = 1;
833                         goto err_out;
834                 }
835                 if (!(di = srd_inst_new(pd_name, pd_opthash))) {
836                         g_critical("Failed to instantiate protocol decoder %s.", pd_name);
837                         ret = 1;
838                         goto err_out;
839                 }
840
841                 /* If no annotation list was specified, add them all in now.
842                  * This will be pared down later to leave only the last PD
843                  * in the stack.
844                  */
845                 if (!opt_pd_annotations)
846                         g_hash_table_insert(pd_ann_visible,
847                                             g_strdup(di->inst_id), NULL);
848
849                 /* Any keys left in the options hash are probes, where the key
850                  * is the probe name as specified in the decoder class, and the
851                  * value is the probe number i.e. the order in which the PD's
852                  * incoming samples are arranged. */
853                 if (srd_inst_probe_set_all(di, pd_opthash) != SRD_OK) {
854                         ret = 1;
855                         goto err_out;
856                 }
857                 g_hash_table_destroy(pd_opthash);
858                 pd_opthash = NULL;
859         }
860
861 err_out:
862         g_strfreev(pdtokens);
863         if (pd_opthash)
864                 g_hash_table_destroy(pd_opthash);
865         if (pd_name)
866                 g_free(pd_name);
867
868         return ret;
869 }
870
871 int setup_pd_stack(void)
872 {
873         struct srd_decoder_inst *di_from, *di_to;
874         int ret, i;
875         char **pds, **ids;
876
877         /* Set up the protocol decoder stack. */
878         pds = g_strsplit(opt_pds, ",", 0);
879         if (g_strv_length(pds) > 1) {
880                 if (opt_pd_stack) {
881                         /* A stack setup was specified, use that. */
882                         g_strfreev(pds);
883                         pds = g_strsplit(opt_pd_stack, ",", 0);
884                         if (g_strv_length(pds) < 2) {
885                                 g_strfreev(pds);
886                                 g_critical("Specify at least two protocol decoders to stack.");
887                                 return 1;
888                         }
889                 }
890
891                 /* First PD goes at the bottom of the stack. */
892                 ids = g_strsplit(pds[0], ":", 0);
893                 if (!(di_from = srd_inst_find_by_id(ids[0]))) {
894                         g_strfreev(ids);
895                         g_critical("Cannot stack protocol decoder '%s': "
896                                         "instance not found.", pds[0]);
897                         return 1;
898                 }
899                 g_strfreev(ids);
900
901                 /* Every subsequent PD goes on top. */
902                 for (i = 1; pds[i]; i++) {
903                         ids = g_strsplit(pds[i], ":", 0);
904                         if (!(di_to = srd_inst_find_by_id(ids[0]))) {
905                                 g_strfreev(ids);
906                                 g_critical("Cannot stack protocol decoder '%s': "
907                                                 "instance not found.", pds[i]);
908                                 return 1;
909                         }
910                         g_strfreev(ids);
911                         if ((ret = srd_inst_stack(di_from, di_to)) != SRD_OK)
912                                 return 1;
913
914                         /* Don't show annotation from this PD. Only the last PD in
915                          * the stack will be left on the annotation list (unless
916                          * the annotation list was specifically provided).
917                          */
918                         if (!opt_pd_annotations)
919                                 g_hash_table_remove(pd_ann_visible,
920                                                     di_from->inst_id);
921
922                         di_from = di_to;
923                 }
924         }
925         g_strfreev(pds);
926
927         return 0;
928 }
929
930 int setup_pd_annotations(void)
931 {
932         GSList *l;
933         struct srd_decoder *dec;
934         int ann;
935         char **pds, **pdtok, **keyval, **ann_descr;
936
937         /* Set up custom list of PDs and annotations to show. */
938         if (opt_pd_annotations) {
939                 pds = g_strsplit(opt_pd_annotations, ",", 0);
940                 for (pdtok = pds; *pdtok && **pdtok; pdtok++) {
941                         ann = 0;
942                         keyval = g_strsplit(*pdtok, "=", 0);
943                         if (!(dec = srd_decoder_get_by_id(keyval[0]))) {
944                                 g_critical("Protocol decoder '%s' not found.", keyval[0]);
945                                 return 1;
946                         }
947                         if (!dec->annotations) {
948                                 g_critical("Protocol decoder '%s' has no annotations.", keyval[0]);
949                                 return 1;
950                         }
951                         if (g_strv_length(keyval) == 2) {
952                                 for (l = dec->annotations; l; l = l->next, ann++) {
953                                         ann_descr = l->data;
954                                         if (!canon_cmp(ann_descr[0], keyval[1]))
955                                                 /* Found it. */
956                                                 break;
957                                 }
958                                 if (!l) {
959                                         g_critical("Annotation '%s' not found "
960                                                         "for protocol decoder '%s'.", keyval[1], keyval[0]);
961                                         return 1;
962                                 }
963                         }
964                         g_debug("cli: showing protocol decoder annotation %d from '%s'", ann, keyval[0]);
965                         g_hash_table_insert(pd_ann_visible, g_strdup(keyval[0]), GINT_TO_POINTER(ann));
966                         g_strfreev(keyval);
967                 }
968                 g_strfreev(pds);
969         }
970
971         return 0;
972 }
973
974 int setup_output_format(void)
975 {
976         GHashTable *fmtargs;
977         GHashTableIter iter;
978         gpointer key, value;
979         struct sr_output_format **outputs;
980         int i;
981         char *fmtspec;
982
983         if (!opt_output_format) {
984                 opt_output_format = DEFAULT_OUTPUT_FORMAT;
985                 /* we'll need to remember this so when saving to a file
986                  * later, sigrok session format will be used.
987                  */
988                 default_output_format = TRUE;
989         }
990
991         fmtargs = parse_generic_arg(opt_output_format, TRUE);
992         fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
993         if (!fmtspec) {
994                 g_critical("Invalid output format.");
995                 return 1;
996         }
997         outputs = sr_output_list();
998         for (i = 0; outputs[i]; i++) {
999                 if (strcmp(outputs[i]->id, fmtspec))
1000                         continue;
1001                 g_hash_table_remove(fmtargs, "sigrok_key");
1002                 output_format = outputs[i];
1003                 g_hash_table_iter_init(&iter, fmtargs);
1004                 while (g_hash_table_iter_next(&iter, &key, &value)) {
1005                         /* only supporting one parameter per output module
1006                          * for now, and only its value */
1007                         output_format_param = g_strdup(value);
1008                         break;
1009                 }
1010                 break;
1011         }
1012         if (!output_format) {
1013                 g_critical("Invalid output format %s.", opt_output_format);
1014                 return 1;
1015         }
1016         g_hash_table_destroy(fmtargs);
1017
1018         return 0;
1019 }
1020
1021 void show_pd_annotations(struct srd_proto_data *pdata, void *cb_data)
1022 {
1023         int i;
1024         char **annotations;
1025         gpointer ann_format;
1026
1027         /* 'cb_data' is not used in this specific callback. */
1028         (void)cb_data;
1029
1030         if (!pd_ann_visible)
1031                 return;
1032
1033         if (!g_hash_table_lookup_extended(pd_ann_visible, pdata->pdo->di->inst_id,
1034                         NULL, &ann_format))
1035                 /* Not in the list of PDs whose annotations we're showing. */
1036                 return;
1037
1038         if (pdata->ann_format != GPOINTER_TO_INT(ann_format))
1039                 /* We don't want this particular format from the PD. */
1040                 return;
1041
1042         annotations = pdata->data;
1043         if (opt_loglevel > SR_LOG_WARN)
1044                 printf("%"PRIu64"-%"PRIu64" ", pdata->start_sample, pdata->end_sample);
1045         printf("%s: ", pdata->pdo->proto_id);
1046         for (i = 0; annotations[i]; i++)
1047                 printf("\"%s\" ", annotations[i]);
1048         printf("\n");
1049         fflush(stdout);
1050 }
1051
1052 static int select_probes(struct sr_dev_inst *sdi)
1053 {
1054         struct sr_probe *probe;
1055         GSList *selected_probes, *l;
1056
1057         if (!opt_probes)
1058                 return SR_OK;
1059
1060         if (!(selected_probes = parse_probestring(sdi, opt_probes)))
1061                 return SR_ERR;
1062
1063         for (l = sdi->probes; l; l = l->next) {
1064                 probe = l->data;
1065                 if (g_slist_find(selected_probes, probe))
1066                         probe->enabled = TRUE;
1067                 else
1068                         probe->enabled = FALSE;
1069         }
1070         g_slist_free(selected_probes);
1071
1072         return SR_OK;
1073 }
1074
1075 /**
1076  * Return the input file format which the CLI tool should use.
1077  *
1078  * If the user specified -I / --input-format, use that one. Otherwise, try to
1079  * autodetect the format as good as possible. Failing that, return NULL.
1080  *
1081  * @param filename The filename of the input file. Must not be NULL.
1082  * @param opt The -I / --input-file option the user specified (or NULL).
1083  *
1084  * @return A pointer to the 'struct sr_input_format' that should be used,
1085  *         or NULL if no input format was selected or auto-detected.
1086  */
1087 static struct sr_input_format *determine_input_file_format(
1088                         const char *filename, const char *opt)
1089 {
1090         int i;
1091         struct sr_input_format **inputs;
1092
1093         /* If there are no input formats, return NULL right away. */
1094         inputs = sr_input_list();
1095         if (!inputs) {
1096                 g_critical("No supported input formats available.");
1097                 return NULL;
1098         }
1099
1100         /* If the user specified -I / --input-format, use that one. */
1101         if (opt) {
1102                 for (i = 0; inputs[i]; i++) {
1103                         if (strcasecmp(inputs[i]->id, opt))
1104                                 continue;
1105                         g_debug("Using user-specified input file format '%s'.",
1106                                         inputs[i]->id);
1107                         return inputs[i];
1108                 }
1109
1110                 /* The user specified an unknown input format, return NULL. */
1111                 g_critical("Error: specified input file format '%s' is "
1112                         "unknown.", opt);
1113                 return NULL;
1114         }
1115
1116         /* Otherwise, try to find an input module that can handle this file. */
1117         for (i = 0; inputs[i]; i++) {
1118                 if (inputs[i]->format_match(filename))
1119                         break;
1120         }
1121
1122         /* Return NULL if no input module wanted to touch this. */
1123         if (!inputs[i]) {
1124                 g_critical("Error: no matching input module found.");
1125                 return NULL;
1126         }
1127
1128         g_debug("cli: Autodetected '%s' input format for file '%s'.",
1129                 inputs[i]->id, filename);
1130                 
1131         return inputs[i];
1132 }
1133
1134 static void load_input_file_format(void)
1135 {
1136         GHashTable *fmtargs = NULL;
1137         struct stat st;
1138         struct sr_input *in;
1139         struct sr_input_format *input_format;
1140         char *fmtspec = NULL;
1141
1142         if (opt_input_format) {
1143                 fmtargs = parse_generic_arg(opt_input_format, TRUE);
1144                 fmtspec = g_hash_table_lookup(fmtargs, "sigrok_key");
1145         }
1146
1147         if (!(input_format = determine_input_file_format(opt_input_file,
1148                                                    fmtspec))) {
1149                 /* The exact cause was already logged. */
1150                 return;
1151         }
1152
1153         if (fmtargs)
1154                 g_hash_table_remove(fmtargs, "sigrok_key");
1155
1156         if (stat(opt_input_file, &st) == -1) {
1157                 g_critical("Failed to load %s: %s", opt_input_file,
1158                         strerror(errno));
1159                 exit(1);
1160         }
1161
1162         /* Initialize the input module. */
1163         if (!(in = g_try_malloc(sizeof(struct sr_input)))) {
1164                 g_critical("Failed to allocate input module.");
1165                 exit(1);
1166         }
1167         in->format = input_format;
1168         in->param = fmtargs;
1169         if (in->format->init) {
1170                 if (in->format->init(in) != SR_OK) {
1171                         g_critical("Input format init failed.");
1172                         exit(1);
1173                 }
1174         }
1175
1176         if (select_probes(in->sdi) > 0)
1177             return;
1178
1179         sr_session_new();
1180         sr_session_datafeed_callback_add(datafeed_in);
1181         if (sr_session_dev_add(in->sdi) != SR_OK) {
1182                 g_critical("Failed to use device.");
1183                 sr_session_destroy();
1184                 return;
1185         }
1186
1187         input_format->loadfile(in, opt_input_file);
1188         if (opt_output_file && default_output_format) {
1189                 if (sr_session_save(opt_output_file, in->sdi, singleds) != SR_OK)
1190                         g_critical("Failed to save session.");
1191         }
1192         sr_session_destroy();
1193
1194         if (fmtargs)
1195                 g_hash_table_destroy(fmtargs);
1196 }
1197
1198 static void load_input_file(void)
1199 {
1200
1201         if (sr_session_load(opt_input_file) == SR_OK) {
1202                 /* sigrok session file */
1203                 sr_session_datafeed_callback_add(datafeed_in);
1204                 sr_session_start();
1205                 sr_session_run();
1206                 sr_session_stop();
1207         }
1208         else {
1209                 /* fall back on input modules */
1210                 load_input_file_format();
1211         }
1212 }
1213
1214 static int set_dev_options(struct sr_dev_inst *sdi, GHashTable *args)
1215 {
1216         const struct sr_hwcap_option *hwo;
1217         GHashTableIter iter;
1218         gpointer key, value;
1219         int ret;
1220         float tmp_float;
1221         uint64_t tmp_u64;
1222         struct sr_rational tmp_rat;
1223         gboolean tmp_bool;
1224         void *val;
1225
1226         g_hash_table_iter_init(&iter, args);
1227         while (g_hash_table_iter_next(&iter, &key, &value)) {
1228                 if (!(hwo = sr_devopt_name_get(key))) {
1229                         g_critical("Unknown device option '%s'.", (char *) key);
1230                         return SR_ERR;
1231                 }
1232
1233                 if ((value == NULL) &&
1234                         (hwo->type != SR_T_BOOL)) {
1235                         g_critical("Option '%s' needs a value.", (char *)key);
1236                         return SR_ERR;
1237                 }
1238                 val = NULL;
1239                 switch (hwo->type) {
1240                 case SR_T_UINT64:
1241                         ret = sr_parse_sizestring(value, &tmp_u64);
1242                         if (ret != SR_OK)
1243                                 break;
1244                         val = &tmp_u64;
1245                         break;
1246                 case SR_T_CHAR:
1247                         val = value;
1248                         break;
1249                 case SR_T_BOOL:
1250                         if (!value)
1251                                 tmp_bool = TRUE;
1252                         else
1253                                 tmp_bool = sr_parse_boolstring(value);
1254                         val = &tmp_bool;
1255                         break;
1256                 case SR_T_FLOAT:
1257                         tmp_float = strtof(value, NULL);
1258                         val = &tmp_float;
1259                         break;
1260                 case SR_T_RATIONAL_PERIOD:
1261                         if ((ret = sr_parse_period(value, &tmp_rat)) != SR_OK)
1262                                 break;
1263                         val = &tmp_rat;
1264                         break;
1265                 case SR_T_RATIONAL_VOLT:
1266                         if ((ret = sr_parse_voltage(value, &tmp_rat)) != SR_OK)
1267                                 break;
1268                         val = &tmp_rat;
1269                         break;
1270                 default:
1271                         ret = SR_ERR;
1272                 }
1273                 if (val)
1274                         ret = sr_dev_config_set(sdi, hwo->hwcap, val);
1275                 if (ret != SR_OK) {
1276                         g_critical("Failed to set device option '%s'.", (char *)key);
1277                         return ret;
1278                 }
1279         }
1280
1281         return SR_OK;
1282 }
1283
1284 static int set_limit_time(const struct sr_dev_inst *sdi)
1285 {
1286         uint64_t time_msec;
1287         uint64_t *samplerate;
1288
1289         time_msec = sr_parse_timestring(opt_time);
1290         if (time_msec == 0) {
1291                 g_critical("Invalid time '%s'", opt_time);
1292                 sr_session_destroy();
1293                 return SR_ERR;
1294         }
1295
1296         if (sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_LIMIT_MSEC)) {
1297                 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_MSEC, &time_msec) != SR_OK) {
1298                         g_critical("Failed to configure time limit.");
1299                         sr_session_destroy();
1300                         return SR_ERR;
1301                 }
1302         }
1303         else {
1304                 /* time limit set, but device doesn't support this...
1305                  * convert to samples based on the samplerate.
1306                  */
1307                 limit_samples = 0;
1308                 if (sr_dev_has_hwcap(sdi, SR_HWCAP_SAMPLERATE)) {
1309                         sr_info_get(sdi->driver, SR_DI_CUR_SAMPLERATE,
1310                                         (const void **)&samplerate, sdi);
1311                         limit_samples = (*samplerate) * time_msec / (uint64_t)1000;
1312                 }
1313                 if (limit_samples == 0) {
1314                         g_critical("Not enough time at this samplerate.");
1315                         sr_session_destroy();
1316                         return SR_ERR;
1317                 }
1318
1319                 if (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1320                                         &limit_samples) != SR_OK) {
1321                         g_critical("Failed to configure time-based sample limit.");
1322                         sr_session_destroy();
1323                         return SR_ERR;
1324                 }
1325         }
1326
1327         return SR_OK;
1328 }
1329
1330 static void run_session(void)
1331 {
1332         GSList *devices;
1333         GHashTable *devargs;
1334         struct sr_dev_inst *sdi;
1335         int max_probes, i;
1336         char **triggerlist;
1337
1338         devices = device_scan();
1339         if (!devices) {
1340                 g_critical("No devices found.");
1341                 return;
1342         }
1343         if (g_slist_length(devices) > 1) {
1344                 g_critical("sigrok-cli only supports one device for capturing.");
1345                 return;
1346         }
1347         sdi = devices->data;
1348
1349         sr_session_new();
1350         sr_session_datafeed_callback_add(datafeed_in);
1351
1352         if (sr_session_dev_add(sdi) != SR_OK) {
1353                 g_critical("Failed to use device.");
1354                 sr_session_destroy();
1355                 return;
1356         }
1357
1358         if (opt_dev) {
1359                 if ((devargs = parse_generic_arg(opt_dev, FALSE))) {
1360                         if (set_dev_options(sdi, devargs) != SR_OK)
1361                                 return;
1362                         g_hash_table_destroy(devargs);
1363                 }
1364         }
1365
1366         if (select_probes(sdi) != SR_OK) {
1367                 g_critical("Failed to set probes.");
1368                 sr_session_destroy();
1369                 return;
1370         }
1371
1372         if (opt_triggers) {
1373                 if (!(triggerlist = sr_parse_triggerstring(sdi, opt_triggers))) {
1374                         sr_session_destroy();
1375                         return;
1376                 }
1377                 max_probes = g_slist_length(sdi->probes);
1378                 for (i = 0; i < max_probes; i++) {
1379                         if (triggerlist[i]) {
1380                                 sr_dev_trigger_set(sdi, i, triggerlist[i]);
1381                                 g_free(triggerlist[i]);
1382                         }
1383                 }
1384                 g_free(triggerlist);
1385         }
1386
1387         if (opt_continuous) {
1388                 if (!sr_driver_hwcap_exists(sdi->driver, SR_HWCAP_CONTINUOUS)) {
1389                         g_critical("This device does not support continuous sampling.");
1390                         sr_session_destroy();
1391                         return;
1392                 }
1393         }
1394
1395         if (opt_time) {
1396                 if (set_limit_time(sdi) != SR_OK) {
1397                         sr_session_destroy();
1398                         return;
1399                 }
1400         }
1401
1402         if (opt_samples) {
1403                 if ((sr_parse_sizestring(opt_samples, &limit_samples) != SR_OK)
1404                                 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_SAMPLES,
1405                                                 &limit_samples) != SR_OK)) {
1406                         g_critical("Failed to configure sample limit.");
1407                         sr_session_destroy();
1408                         return;
1409                 }
1410         }
1411
1412         if (opt_frames) {
1413                 if ((sr_parse_sizestring(opt_frames, &limit_frames) != SR_OK)
1414                                 || (sr_dev_config_set(sdi, SR_HWCAP_LIMIT_FRAMES,
1415                                                 &limit_frames) != SR_OK)) {
1416                         g_critical("Failed to configure frame limit.");
1417                         sr_session_destroy();
1418                         return;
1419                 }
1420         }
1421
1422         if (sr_session_start() != SR_OK) {
1423                 g_critical("Failed to start session.");
1424                 sr_session_destroy();
1425                 return;
1426         }
1427
1428         if (opt_continuous)
1429                 add_anykey();
1430
1431         sr_session_run();
1432
1433         if (opt_continuous)
1434                 clear_anykey();
1435
1436         if (opt_output_file && default_output_format) {
1437                 if (sr_session_save(opt_output_file, sdi, singleds) != SR_OK)
1438                         g_critical("Failed to save session.");
1439         }
1440         sr_session_destroy();
1441         g_slist_free(devices);
1442
1443 }
1444
1445 static void logger(const gchar *log_domain, GLogLevelFlags log_level,
1446                    const gchar *message, gpointer cb_data)
1447 {
1448         (void)log_domain;
1449         (void)cb_data;
1450
1451         /*
1452          * All messages, warnings, errors etc. go to stderr (not stdout) in
1453          * order to not mess up the CLI tool data output, e.g. VCD output.
1454          */
1455         if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1456                         || opt_loglevel > SR_LOG_WARN) {
1457                 fprintf(stderr, "%s\n", message);
1458                 fflush(stderr);
1459         }
1460 }
1461
1462 int main(int argc, char **argv)
1463 {
1464         int ret = 1;
1465         GOptionContext *context;
1466         GError *error;
1467
1468         g_log_set_default_handler(logger, NULL);
1469
1470         error = NULL;
1471         context = g_option_context_new(NULL);
1472         g_option_context_add_main_entries(context, optargs, NULL);
1473
1474         if (!g_option_context_parse(context, &argc, &argv, &error)) {
1475                 g_critical("%s", error->message);
1476                 goto done;
1477         }
1478
1479         /* Set the loglevel (amount of messages to output) for libsigrok. */
1480         if (sr_log_loglevel_set(opt_loglevel) != SR_OK)
1481                 goto done;
1482
1483         /* Set the loglevel (amount of messages to output) for libsigrokdecode. */
1484         if (srd_log_loglevel_set(opt_loglevel) != SRD_OK)
1485                 goto done;
1486
1487         if (sr_init(&sr_ctx) != SR_OK)
1488                 goto done;
1489
1490         if (opt_pds) {
1491                 if (srd_init(NULL) != SRD_OK)
1492                         goto done;
1493                 if (register_pds(NULL, opt_pds) != 0)
1494                         goto done;
1495                 if (srd_pd_output_callback_add(SRD_OUTPUT_ANN,
1496                                 show_pd_annotations, NULL) != SRD_OK)
1497                         goto done;
1498                 if (setup_pd_stack() != 0)
1499                         goto done;
1500                 if (setup_pd_annotations() != 0)
1501                         goto done;
1502         }
1503
1504         if (setup_output_format() != 0)
1505                 goto done;
1506
1507         if (opt_version)
1508                 show_version();
1509         else if (opt_list_devs)
1510                 show_dev_list();
1511         else if (opt_pds && opt_show)
1512                 show_pd_detail();
1513         else if (opt_show)
1514                 show_dev_detail();
1515         else if (opt_input_file)
1516                 load_input_file();
1517         else if (opt_samples || opt_time || opt_frames || opt_continuous)
1518                 run_session();
1519         else
1520                 printf("%s", g_option_context_get_help(context, TRUE, NULL));
1521
1522         if (opt_pds)
1523                 srd_exit();
1524
1525         ret = 0;
1526
1527 done:
1528         if (sr_ctx)
1529                 sr_exit(sr_ctx);
1530
1531         g_option_context_free(context);
1532
1533         return ret;
1534 }