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