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