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