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